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

main
ts 2,020 lines 69.4 KB
Raw
1 import {
2 MessageId,
3 RuntimeRequestId,
4 CheckpointId,
5 CheckpointScopeId,
6 NodeId,
7 PlanId,
8 ProviderInstanceId,
9 ProviderThreadId,
10 RunAttemptId,
11 RunId,
12 ScheduledTaskId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2PlanArtifact,
16 type OrchestrationV2ProjectedTurnItem,
17 type OrchestrationV2ExecutionNode,
18 type OrchestrationV2RunAttempt,
19 type OrchestrationV2TurnItem,
20 } from "@t3tools/contracts";
21 import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";
22 import { deriveMessagesTimelineRows } from "./components/chat/MessagesTimeline.logic";
23 import * as DateTime from "effect/DateTime";
24 import { describe, expect, it } from "vite-plus/test";
25
26 import {
27 deriveCanInterruptRunningThread,
28 deriveTimelineEntriesFromVisibleTurnItems,
29 deriveTimelineEntriesFromVisibleTurnItemsWithState,
30 deriveRevertTurnCountByUserMessageId,
31 derivePhase,
32 isLatestRunSettled,
33 selectHandoffImageResources,
34 selectMessageImageResources,
35 createMessageAttachmentPreviewProjector,
36 providerErrorPresentation,
37 type TimelineEntry,
38 workEntryIndicatesToolFailure,
39 workEntryDisplayIndicatesToolFailure,
40 workEntryIndicatesToolSuccess,
41 } from "./session-logic";
42 import {
43 makeStreamingTimelineFixture,
44 makeStreamingWorkTimelineFixture,
45 makeThreadProjectionFixture,
46 withStreamedText,
47 } from "./test-fixtures";
48 import type { ChatMessage } from "./types";
49
50 function streamingPlanArtifact(
51 fixture: ReturnType<typeof makeStreamingWorkTimelineFixture>,
52 markdown: string,
53 status: "active" | "superseded",
54 ): OrchestrationV2PlanArtifact {
55 return {
56 id: PlanId.make("live-plan"),
57 threadId: fixture.threadId,
58 runId: fixture.runId,
59 nodeId: NodeId.make("live-node"),
60 kind: "proposed_plan",
61 markdown,
62 status,
63 };
64 }
65
66 describe("V2 session presentation", () => {
67 it("uses run status as the settlement boundary", () => {
68 const runId = RunId.make("run-1");
69 expect(
70 isLatestRunSettled(
71 {
72 runId,
73 status: "completed",
74 startedAt: "2026-06-20T00:00:00.000Z",
75 completedAt: "2026-06-20T00:01:00.000Z",
76 },
77 null,
78 ),
79 ).toBe(true);
80 expect(
81 isLatestRunSettled(
82 { runId, status: "running", startedAt: null, completedAt: null },
83 { status: "running", activeRunId: runId },
84 ),
85 ).toBe(false);
86 expect(
87 isLatestRunSettled(
88 { runId, status: "queued", startedAt: null, completedAt: null },
89 { status: "running", activeRunId: RunId.make("run-active") },
90 ),
91 ).toBe(false);
92 });
93
94 it("offers Stop while a run is preparing/starting, not just once it's running (#13392)", () => {
95 const runtimeWithStatus = (
96 status: ThreadRuntimeSummary["status"],
97 activeRunId: RunId | null = null,
98 ): ThreadRuntimeSummary => ({
99 status,
100 activeRunId,
101 providerInstanceId: ProviderInstanceId.make("claude-default"),
102 providerName: null,
103 lastError: null,
104 updatedAt: "2026-09-29T00:00:00.000Z",
105 });
106 const runId = RunId.make("run-stop-while-starting");
107
108 for (const status of ["preparing", "starting", "running"] as const) {
109 const runtime = runtimeWithStatus(status, runId);
110 expect(deriveCanInterruptRunningThread(true, runtime)).toBe(true);
111 }
112
113 expect(deriveCanInterruptRunningThread(false, runtimeWithStatus("running", runId))).toBe(false);
114
115 expect(derivePhase(runtimeWithStatus("queued"))).toBe("connecting");
116 expect(deriveCanInterruptRunningThread(true, runtimeWithStatus("queued"))).toBe(false);
117 expect(deriveCanInterruptRunningThread(true, runtimeWithStatus("queued", runId))).toBe(true);
118
119 expect(derivePhase(runtimeWithStatus("waiting"))).toBe("running");
120 expect(deriveCanInterruptRunningThread(true, runtimeWithStatus("waiting"))).toBe(true);
121
122 expect(deriveCanInterruptRunningThread(true, null)).toBe(false);
123 });
124
125 it("labels provider retry progress, delay, recovery, and exhaustion", () => {
126 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
127 const retryItem = {
128 id: TurnItemId.make("item-provider-retry"),
129 threadId: ThreadId.make("thread-provider-retry"),
130 runId: RunId.make("run-provider-retry"),
131 nodeId: null,
132 providerThreadId: null,
133 providerTurnId: null,
134 nativeItemRef: null,
135 parentItemId: null,
136 ordinal: 1,
137 status: "running" as const,
138 title: "Provider retry",
139 startedAt: now,
140 completedAt: null,
141 updatedAt: now,
142 type: "error" as const,
143 failure: {
144 class: "provider_error" as const,
145 message: "Claude API overloaded.",
146 code: "api_error_529",
147 retryable: true,
148 },
149 retry: {
150 attempt: 2,
151 maxAttempts: 10,
152 retryDelayMs: 1_500,
153 },
154 } satisfies Extract<OrchestrationV2TurnItem, { readonly type: "error" }>;
155
156 expect(
157 providerErrorPresentation({
158 ...retryItem,
159 status: "failed",
160 failure: { ...retryItem.failure, class: "usage_limit" },
161 }),
162 ).toMatchObject({ label: "Usage limit reached after 2/10 retries" });
163 const recoveredLimit = {
164 ...retryItem,
165 status: "completed" as const,
166 completedAt: now,
167 failure: { ...retryItem.failure, class: "usage_limit" as const },
168 };
169 const [recoveredEntry] = deriveTimelineEntriesFromVisibleTurnItems({
170 visibleTurnItems: [
171 {
172 item: recoveredLimit,
173 position: 0,
174 visibility: "local",
175 sourceThreadId: recoveredLimit.threadId,
176 sourceItemId: recoveredLimit.id,
177 },
178 ],
179 optimisticMessages: [],
180 });
181 if (recoveredEntry?.kind !== "work") throw new Error("Expected recovered provider work");
182 expect(recoveredEntry.entry.label).toBe("Provider recovered (2/10 retries)");
183 expect(recoveredEntry.entry.sourceActivityKind).not.toBe("runtime.warning");
184 expect(workEntryDisplayIndicatesToolFailure(recoveredEntry.entry)).toBe(false);
185 expect(providerErrorPresentation(retryItem)).toEqual({
186 label: "Retrying provider (2/10)",
187 detail: "Claude API overloaded. Retrying in 1.5s.",
188 });
189 expect(
190 providerErrorPresentation({
191 ...retryItem,
192 status: "completed",
193 completedAt: now,
194 }),
195 ).toMatchObject({ label: "Provider recovered (2/10 retries)" });
196 expect(
197 providerErrorPresentation({
198 ...retryItem,
199 status: "failed",
200 retry: { ...retryItem.retry, attempt: 10 },
201 completedAt: now,
202 }),
203 ).toMatchObject({ label: "Provider error after 10/10 retries" });
204 });
205
206 it("assigns run rollback to the turn-start message instead of a later steer", () => {
207 const runId = RunId.make("run-steered");
208 const turnStartMessageId = MessageId.make("message-turn-start");
209 const steerMessageId = MessageId.make("message-steer");
210 const assistantMessageId = MessageId.make("message-assistant");
211 const messages: ChatMessage[] = [
212 {
213 id: turnStartMessageId,
214 role: "user",
215 text: "Start",
216 runId,
217 inputIntent: "turn_start",
218 streaming: false,
219 createdAt: "2026-06-20T00:00:00.000Z",
220 updatedAt: "2026-06-20T00:00:00.000Z",
221 },
222 {
223 id: steerMessageId,
224 role: "user",
225 text: "Steer",
226 runId,
227 inputIntent: "steer",
228 streaming: false,
229 createdAt: "2026-06-20T00:00:01.000Z",
230 updatedAt: "2026-06-20T00:00:01.000Z",
231 },
232 {
233 id: assistantMessageId,
234 role: "assistant",
235 text: "Done",
236 runId,
237 streaming: false,
238 createdAt: "2026-06-20T00:00:02.000Z",
239 updatedAt: "2026-06-20T00:00:02.000Z",
240 },
241 ];
242 const timelineEntries: TimelineEntry[] = messages.map((message): TimelineEntry => ({
243 id: message.id,
244 kind: "message",
245 createdAt: message.createdAt,
246 message,
247 }));
248
249 const targets = deriveRevertTurnCountByUserMessageId({
250 timelineEntries,
251 threadStartCheckpointAvailable: true,
252 checkpoints: [
253 {
254 runId,
255 checkpointTurnCount: 1,
256 checkpointRef: "checkpoint-run-1" as never,
257 status: "ready",
258 files: [],
259 assistantMessageId,
260 completedAt: "2026-06-20T00:00:03.000Z",
261 },
262 ],
263 });
264
265 expect([...targets]).toEqual([[turnStartMessageId, 0]]);
266 expect(targets.has(steerMessageId)).toBe(false);
267 });
268
269 describe("revert targets after a rewind", () => {
270 const runId = (ordinal: number) => RunId.make(`run-${ordinal}`);
271 const turn = (ordinal: number): TimelineEntry[] =>
272 (["user", "assistant"] as const).map((role) => {
273 const id = MessageId.make(`${role}-${ordinal}`);
274 const createdAt = `2026-06-20T00:00:0${ordinal}.000Z`;
275 return {
276 id,
277 kind: "message",
278 createdAt,
279 message: {
280 id,
281 role,
282 text: role,
283 runId: runId(ordinal),
284 ...(role === "user" ? { inputIntent: "turn_start" as const } : {}),
285 streaming: false,
286 createdAt,
287 updatedAt: createdAt,
288 },
289 };
290 });
291 const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({
292 runId: runId(ordinal),
293 checkpointTurnCount: ordinal,
294 checkpointRef: `checkpoint-${ordinal}` as never,
295 status,
296 files: [],
297 assistantMessageId: MessageId.make(`assistant-${ordinal}`),
298 completedAt: "2026-06-20T00:00:09.000Z",
299 });
300 const targets = (
301 ordinals: ReadonlyArray<number>,
302 checkpoints: ReadonlyArray<ReturnType<typeof checkpoint>>,
303 options: { threadStartCheckpointAvailable?: boolean; unsettledRunId?: RunId } = {},
304 ) =>
305 Object.fromEntries(
306 deriveRevertTurnCountByUserMessageId({
307 timelineEntries: ordinals.flatMap(turn),
308 checkpoints,
309 threadStartCheckpointAvailable: options.threadStartCheckpointAvailable ?? true,
310 unsettledRunId: options.unsettledRunId ?? null,
311 }),
312 );
313
314 it("keeps rewound and stopped runs editable at the previous visible checkpoint", () => {
315 // Runs 1 and 3 were rewound; run 5 stopped without capturing a checkpoint.
316 expect(targets([2, 4, 5], [checkpoint(2), checkpoint(3, "stale"), checkpoint(4)])).toEqual({
317 "user-2": 0,
318 "user-4": 2,
319 "user-5": 4,
320 });
321 expect(targets([2], [checkpoint(1, "stale")])).toEqual({ "user-2": 0 });
322 // Without file snapshots, missing checkpoints still pin the conversation.
323 expect(targets([1, 2], [checkpoint(1, "missing"), checkpoint(2, "missing")])).toEqual({
324 "user-1": 0,
325 "user-2": 1,
326 });
327 });
328
329 it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => {
330 const fixture = makeStreamingTimelineFixture();
331 const first = fixture.visibleTurnItems[0]!;
332 if (first.item.type !== "user_message") throw new Error("Expected a user message fixture.");
333 const notification = {
334 ...first,
335 item: {
336 ...first.item,
337 id: TurnItemId.make("wake-item"),
338 runId: runId(2),
339 type: "notification" as const,
340 source: { kind: "delegated_task" as const, taskIds: [NodeId.make("task-1")] },
341 outcome: "unknown" as const,
342 summary: "Delegated task finished",
343 },
344 };
345 const inherited = {
346 ...notification,
347 visibility: "inherited" as const,
348 sourceThreadId: ThreadId.make("parent-thread"),
349 sourceItemId: TurnItemId.make("inherited-wake"),
350 item: {
351 ...notification.item,
352 id: TurnItemId.make("inherited-wake"),
353 threadId: ThreadId.make("parent-thread"),
354 runId: runId(7),
355 },
356 };
357 const work: TimelineEntry = {
358 id: "background-work",
359 kind: "work",
360 createdAt: "2026-06-20T00:00:02.000Z",
361 entry: {
362 id: "background-work",
363 createdAt: "2026-06-20T00:00:02.000Z",
364 runId: runId(8),
365 itemType: "command_execution",
366 label: "Background work",
367 tone: "tool",
368 },
369 };
370
371 expect(
372 Object.fromEntries(
373 deriveRevertTurnCountByUserMessageId({
374 timelineEntries: [
375 ...turn(1),
376 ...deriveTimelineEntriesFromVisibleTurnItems({
377 visibleTurnItems: [notification, inherited],
378 optimisticMessages: [],
379 }),
380 work,
381 ...turn(3),
382 ],
383 checkpoints: [
384 checkpoint(1),
385 checkpoint(2),
386 checkpoint(3),
387 checkpoint(7),
388 checkpoint(8),
389 ],
390 threadStartCheckpointAvailable: true,
391 }),
392 ),
393 ).toEqual({ "user-1": 0, "user-3": 2 });
394 });
395
396 it("hides edit when the predecessor is unavailable or the run is unsettled", () => {
397 expect(targets([1, 2], [checkpoint(2)])).toEqual({ "user-1": 0 });
398 expect(targets([1, 2], [checkpoint(1, "stale"), checkpoint(2)])).toEqual({ "user-1": 0 });
399 // Earlier history is paged out, so the first loaded run's predecessor is unknown.
400 expect(
401 targets([4, 5], [checkpoint(4), checkpoint(5)], { threadStartCheckpointAvailable: false }),
402 ).toEqual({ "user-5": 4 });
403 expect(targets([1, 2], [checkpoint(1), checkpoint(2)], { unsettledRunId: runId(2) })).toEqual(
404 { "user-1": 0 },
405 );
406 });
407
408 it("can edit a cancelled run but cannot target its checkpoint without a provider turn", () => {
409 expect(
410 Object.fromEntries(
411 deriveRevertTurnCountByUserMessageId({
412 timelineEntries: [1, 2, 3].flatMap(turn),
413 checkpoints: [checkpoint(1), checkpoint(2), checkpoint(3)],
414 threadStartCheckpointAvailable: true,
415 availableRevertTurnCounts: new Set([0, 1]),
416 }),
417 ),
418 ).toEqual({ "user-1": 0, "user-2": 1 });
419 });
420
421 it("leaves inherited history uneditable and restores the first local run to thread start", () => {
422 const fixture = makeStreamingTimelineFixture();
423 const inheritedEntries = deriveTimelineEntriesFromVisibleTurnItems({
424 visibleTurnItems: fixture.visibleTurnItems
425 .filter(({ item }) => item.runId === fixture.historyRunId)
426 .map((item) => ({ ...item, visibility: "inherited" as const })),
427 optimisticMessages: [],
428 });
429 expect(
430 Object.fromEntries(
431 deriveRevertTurnCountByUserMessageId({
432 timelineEntries: [...inheritedEntries, ...turn(2)],
433 checkpoints: [{ ...checkpoint(7), runId: fixture.historyRunId }, checkpoint(2)],
434 threadStartCheckpointAvailable: true,
435 }),
436 ),
437 ).toEqual({ "user-2": 0 });
438 });
439 });
440
441 it("uses visible turn item order and keeps provider errors in the work log", () => {
442 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
443 const threadId = ThreadId.make("thread-visible");
444 const runId = RunId.make("run-visible");
445 const base = (id: string, ordinal: number) => ({
446 id: TurnItemId.make(id),
447 threadId,
448 runId,
449 nodeId: null,
450 providerThreadId: null,
451 providerTurnId: null,
452 nativeItemRef: null,
453 parentItemId: null,
454 ordinal,
455 status: "completed" as const,
456 title: null,
457 startedAt: now,
458 completedAt: now,
459 updatedAt: now,
460 });
461 const userItem = {
462 ...base("item-user", 0),
463 type: "user_message" as const,
464 messageId: MessageId.make("message-user"),
465 inputIntent: "turn_start" as const,
466 text: "Start",
467 attachments: [],
468 createdBy: "user" as const,
469 creationSource: "web" as const,
470 } satisfies OrchestrationV2TurnItem;
471 const requestItem = {
472 ...base("item-interrupt-request", 1),
473 type: "run_interrupt_request" as const,
474 message: "Stopping",
475 } satisfies OrchestrationV2TurnItem;
476 const commandItem = {
477 ...base("item-command", 2),
478 type: "command_execution" as const,
479 input: "sleep 1",
480 output: "done",
481 exitCode: 0,
482 } satisfies OrchestrationV2TurnItem;
483 const resultItem = {
484 ...base("item-interrupt-result", 3),
485 type: "run_interrupt_result" as const,
486 message: "Stopped",
487 } satisfies OrchestrationV2TurnItem;
488 const todoItem = {
489 ...base("item-todo", 4),
490 type: "todo_list" as const,
491 planId: PlanId.make("plan-visible"),
492 explanation: "Show task updates where the agent wrote them",
493 steps: [
494 { id: "step-1", text: "First", status: "completed" as const },
495 { id: "step-2", text: "Second", status: "pending" as const },
496 ],
497 } satisfies OrchestrationV2TurnItem;
498 const errorItem = {
499 ...base("item-error", 5),
500 status: "failed" as const,
501 type: "error" as const,
502 failure: {
503 class: "validation_error" as const,
504 message: "Invalid reasoning effort.",
505 code: "invalid_request",
506 retryable: false,
507 },
508 } satisfies OrchestrationV2TurnItem;
509 const threadCreatedItem = {
510 ...base("item-thread-created", 6),
511 type: "thread_created" as const,
512 title: "Follow-up thread",
513 targetThreadId: ThreadId.make("thread-follow-up"),
514 targetRunId: RunId.make("run-follow-up"),
515 targetProviderInstanceId: ProviderInstanceId.make("claude-default"),
516 targetModel: "claude-sonnet-4-6",
517 } satisfies OrchestrationV2TurnItem;
518 const workspacePreparationItem = {
519 ...base("item-workspace-preparation", 7),
520 type: "command_execution" as const,
521 title: "Workspace ready",
522 input: "Preparing workspace",
523 output: "Workspace preparation completed.",
524 exitCode: 0,
525 } satisfies OrchestrationV2TurnItem;
526 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
527 userItem,
528 requestItem,
529 commandItem,
530 resultItem,
531 todoItem,
532 errorItem,
533 threadCreatedItem,
534 workspacePreparationItem,
535 ].map((item, position) => ({
536 position,
537 visibility: "local" as const,
538 sourceThreadId: threadId,
539 sourceItemId: item.id,
540 item,
541 }));
542
543 const entries = deriveTimelineEntriesFromVisibleTurnItems({
544 visibleTurnItems,
545 optimisticMessages: [],
546 });
547
548 expect(entries.map((entry) => [entry.kind, entry.id])).toEqual([
549 ["message", userItem.messageId],
550 ["event", requestItem.id],
551 ["work", commandItem.id],
552 ["event", resultItem.id],
553 ["work", todoItem.id],
554 ["work", errorItem.id],
555 ["work", threadCreatedItem.id],
556 ]);
557 const commandEntry = entries[2];
558 const userEntry = entries[0];
559 expect(userEntry?.kind).toBe("message");
560 if (userEntry?.kind === "message") {
561 expect(userEntry.projectedItem).toBe(visibleTurnItems[0]);
562 expect(userEntry.message.inputIntent).toBe("turn_start");
563 expect(userEntry.message.createdBy).toBe("user");
564 expect(userEntry.message.creationSource).toBe("web");
565 }
566 expect(commandEntry?.kind).toBe("work");
567 if (commandEntry?.kind === "work") {
568 expect(commandEntry.entry.projectedItem).toBe(visibleTurnItems[2]);
569 expect(commandEntry.entry.structuredPayload).toBe(commandItem);
570 expect(commandEntry.entry.command).toBe(commandItem.input);
571 expect(commandEntry.entry.detail).toBeUndefined();
572 }
573 const errorEntry = entries[5];
574 expect(errorEntry?.kind).toBe("work");
575 if (errorEntry?.kind === "work") {
576 expect(errorEntry.entry.projectedItem).toBe(visibleTurnItems[5]);
577 expect(errorEntry.entry.label).toBe("Provider error");
578 expect(errorEntry.entry.detail).toBe("Invalid reasoning effort.");
579 expect(errorEntry.entry.tone).toBe("info");
580 expect(errorEntry.entry.toolLifecycleStatus).toBe("failed");
581 }
582 const threadCreatedEntry = entries[6];
583 expect(threadCreatedEntry?.kind).toBe("work");
584 if (threadCreatedEntry?.kind === "work") {
585 expect(threadCreatedEntry.entry.projectedItem?.item.type).toBe("thread_created");
586 }
587 expect(
588 deriveTimelineEntriesFromVisibleTurnItems({
589 visibleTurnItems: [
590 {
591 ...visibleTurnItems.at(-1)!,
592 item: {
593 ...workspacePreparationItem,
594 deferredWork: { cursor: "work-page", itemCount: 100, lastOrdinal: 107 },
595 },
596 },
597 ],
598 optimisticMessages: [],
599 }).map((entry) => entry.id),
600 ).toEqual([workspacePreparationItem.id]);
601 });
602
603 it.each(["pending", "running", "completed"] as const)(
604 "shows a %s todo update in the timeline where the agent wrote it",
605 (stepStatus) => {
606 const projection = makeThreadProjectionFixture();
607 const now = DateTime.makeUnsafe("2026-09-04T00:00:00.000Z");
608 const runId = RunId.make("run-tasks");
609 const nodeId = NodeId.make("node-tasks");
610 const planId = PlanId.make("plan-tasks");
611 const steps = [{ id: "step-1", text: "Verify the change", status: stepStatus }];
612 const item = {
613 id: TurnItemId.make("item-tasks"),
614 threadId: projection.thread.id,
615 runId,
616 nodeId,
617 providerThreadId: null,
618 providerTurnId: null,
619 nativeItemRef: null,
620 parentItemId: null,
621 ordinal: 0,
622 status: "completed" as const,
623 title: null,
624 startedAt: now,
625 completedAt: now,
626 updatedAt: now,
627 type: "todo_list" as const,
628 planId,
629 steps,
630 } satisfies OrchestrationV2TurnItem;
631 const plans = [
632 {
633 id: planId,
634 threadId: projection.thread.id,
635 runId,
636 nodeId,
637 kind: "todo_list" as const,
638 status: "active" as const,
639 steps,
640 },
641 ];
642
643 expect(
644 deriveTimelineEntriesFromVisibleTurnItems({
645 visibleTurnItems: [
646 {
647 position: 0,
648 visibility: "local",
649 sourceThreadId: projection.thread.id,
650 sourceItemId: item.id,
651 item,
652 },
653 ],
654 optimisticMessages: [],
655 plans,
656 }),
657 ).toMatchObject([
658 {
659 kind: "work",
660 entry: {
661 label: stepStatus === "completed" ? "Tasks 1/1" : "Tasks 0/1 · Verify the change",
662 },
663 },
664 ]);
665 },
666 );
667
668 it("waits for a dispatched turn item before adding queued input to the timeline", () => {
669 const projection = makeThreadProjectionFixture();
670 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
671 const runId = RunId.make("run-dispatched-queued");
672 const messageId = MessageId.make("message-dispatched-queued");
673 const optimisticMessage = {
674 id: messageId,
675 role: "user" as const,
676 text: "Queued input",
677 runId: null,
678 inputIntent: "queued_turn" as const,
679 streaming: false,
680 createdAt: DateTime.formatIso(now),
681 updatedAt: DateTime.formatIso(now),
682 };
683
684 expect(
685 deriveTimelineEntriesFromVisibleTurnItems({
686 visibleTurnItems: [],
687 optimisticMessages: [optimisticMessage],
688 }),
689 ).toEqual([]);
690
691 const dispatchedItem = {
692 id: TurnItemId.make("item-dispatched-queued"),
693 threadId: projection.thread.id,
694 runId,
695 nodeId: null,
696 providerThreadId: null,
697 providerTurnId: null,
698 nativeItemRef: null,
699 parentItemId: null,
700 ordinal: 200,
701 status: "completed" as const,
702 title: null,
703 startedAt: now,
704 completedAt: now,
705 updatedAt: now,
706 type: "user_message" as const,
707 messageId,
708 inputIntent: "turn_start" as const,
709 text: "Queued input",
710 attachments: [],
711 createdBy: "agent" as const,
712 creationSource: "mcp" as const,
713 scheduledTaskId: ScheduledTaskId.make("task-queued"),
714 senderThreadId: ThreadId.make("thread-agent-sender"),
715 } satisfies OrchestrationV2TurnItem;
716 for (const inputIntent of [
717 "queued_turn",
718 "turn_start",
719 "steer",
720 "promoted_queued_to_steer",
721 ] as const) {
722 expect(
723 deriveTimelineEntriesFromVisibleTurnItems({
724 visibleTurnItems: [
725 {
726 position: 0,
727 visibility: "local",
728 sourceThreadId: projection.thread.id,
729 sourceItemId: dispatchedItem.id,
730 item: { ...dispatchedItem, inputIntent, status: "pending" },
731 },
732 ],
733 optimisticMessages: [],
734 }),
735 ).toHaveLength(inputIntent === "queued_turn" ? 0 : 1);
736 }
737 const promotedEntries = deriveTimelineEntriesFromVisibleTurnItems({
738 visibleTurnItems: [
739 {
740 position: 0,
741 visibility: "local",
742 sourceThreadId: projection.thread.id,
743 sourceItemId: dispatchedItem.id,
744 item: dispatchedItem,
745 },
746 ],
747 optimisticMessages: [optimisticMessage],
748 });
749 expect(promotedEntries.map((entry) => entry.id)).toEqual([messageId]);
750 expect(promotedEntries[0]?.kind).toBe("message");
751 if (promotedEntries[0]?.kind === "message") {
752 expect(promotedEntries[0].message.inputIntent).toBe("turn_start");
753 expect(promotedEntries[0].message.scheduledTaskId).toBe("task-queued");
754 expect(promotedEntries[0].message.senderThreadId).toBe("thread-agent-sender");
755 }
756 });
757
758 it("anchors feedback before later committed turns without reordering canonical history", () => {
759 const threadId = ThreadId.make("thread-feedback-order");
760 const messageItem = (input: {
761 readonly id: string;
762 readonly role: "user" | "assistant";
763 readonly createdAt: string;
764 readonly ordinal: number;
765 }): OrchestrationV2TurnItem => {
766 const timestamp = DateTime.makeUnsafe(input.createdAt);
767 const common = {
768 id: TurnItemId.make(`item-${input.id}`),
769 threadId,
770 runId: RunId.make(`run-${input.ordinal}`),
771 nodeId: null,
772 providerThreadId: null,
773 providerTurnId: null,
774 nativeItemRef: null,
775 parentItemId: null,
776 ordinal: input.ordinal,
777 status: "completed" as const,
778 title: null,
779 startedAt: timestamp,
780 completedAt: timestamp,
781 updatedAt: timestamp,
782 messageId: MessageId.make(input.id),
783 text: input.id,
784 };
785 return input.role === "user"
786 ? {
787 ...common,
788 type: "user_message",
789 inputIntent: "turn_start",
790 attachments: [],
791 createdBy: "user",
792 creationSource: "web",
793 }
794 : { ...common, type: "assistant_message", streaming: false };
795 };
796 const canonicalItems = [
797 messageItem({ id: "old-user", role: "user", createdAt: "2026-08-29T00:00:01Z", ordinal: 1 }),
798 messageItem({
799 id: "old-assistant",
800 role: "assistant",
801 createdAt: "2026-08-29T00:00:02Z",
802 ordinal: 2,
803 }),
804 messageItem({
805 id: "later-user",
806 role: "user",
807 createdAt: "2026-08-29T00:00:05Z",
808 ordinal: 3,
809 }),
810 messageItem({
811 id: "later-assistant",
812 role: "assistant",
813 createdAt: "2026-08-29T00:00:04Z",
814 ordinal: 4,
815 }),
816 ];
817 const visibleTurnItems = canonicalItems.map((item, position) => ({
818 position,
819 visibility: "local" as const,
820 sourceThreadId: threadId,
821 sourceItemId: item.id,
822 item,
823 }));
824 const feedback = (id: string, role: "user" | "assistant"): ChatMessage => ({
825 id: MessageId.make(id),
826 role,
827 text: id,
828 runId: null,
829 streaming: false,
830 createdAt: "2026-08-29T00:00:03Z",
831 updatedAt: "2026-08-29T00:00:03Z",
832 });
833 const entries = deriveTimelineEntriesFromVisibleTurnItems({
834 visibleTurnItems,
835 anchoredMessages: [
836 feedback("feedback-user", "user"),
837 feedback("feedback-assistant", "assistant"),
838 feedback("later-user", "user"),
839 ],
840 optimisticMessages: [
841 { ...feedback("optimistic-user", "user"), createdAt: "2026-08-29T00:00:00Z" },
842 ],
843 });
844
845 expect(entries.map((entry) => entry.id)).toEqual([
846 "old-user",
847 "old-assistant",
848 "feedback-user",
849 "feedback-assistant",
850 "later-user",
851 "later-assistant",
852 "optimistic-user",
853 ]);
854 expect(
855 entries
856 .filter((entry) => entry.id.startsWith("feedback-"))
857 .every((entry) => entry.kind === "message" && entry.projectedItem === undefined),
858 ).toBe(true);
859 });
860
861 it("uses projected plan status and file contents in timeline entries", () => {
862 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
863 const threadId = ThreadId.make("thread-timeline-artifacts");
864 const runId = RunId.make("run-timeline-artifacts");
865 const nodeId = NodeId.make("node-timeline-artifacts");
866 const planId = PlanId.make("plan-timeline-artifacts");
867 const base = {
868 threadId,
869 runId,
870 nodeId,
871 providerThreadId: null,
872 providerTurnId: null,
873 nativeItemRef: null,
874 parentItemId: null,
875 status: "completed" as const,
876 title: null,
877 startedAt: now,
878 completedAt: now,
879 updatedAt: now,
880 };
881 const planItem = {
882 ...base,
883 id: TurnItemId.make("item-proposed-plan"),
884 ordinal: 0,
885 type: "proposed_plan" as const,
886 planId,
887 markdown: "Finished plan",
888 streaming: false,
889 } satisfies OrchestrationV2TurnItem;
890 const fileItem = {
891 ...base,
892 id: TurnItemId.make("item-file-change"),
893 ordinal: 1,
894 type: "file_change" as const,
895 fileName: "src/example.ts",
896 newStr: "export const answer = 42;\n",
897 } satisfies OrchestrationV2TurnItem;
898 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
899 planItem,
900 fileItem,
901 ].map((item, position) => ({
902 position,
903 visibility: "local",
904 sourceThreadId: threadId,
905 sourceItemId: item.id,
906 item,
907 }));
908
909 const entries = deriveTimelineEntriesFromVisibleTurnItems({
910 visibleTurnItems,
911 optimisticMessages: [],
912 plans: [
913 {
914 id: planId,
915 threadId,
916 runId,
917 nodeId,
918 kind: "proposed_plan",
919 markdown: "",
920 status: "completed",
921 detailInTurnItem: true,
922 },
923 ],
924 });
925
926 expect(entries[0]?.kind).toBe("proposed-plan");
927 if (entries[0]?.kind === "proposed-plan") {
928 expect(entries[0].proposedPlan.status).toBe("completed");
929 expect(entries[0].proposedPlan.planMarkdown).toBe("Finished plan");
930 }
931 expect(entries[1]?.kind).toBe("work");
932 if (entries[1]?.kind === "work") {
933 expect(entries[1].entry.detail).toBeUndefined();
934 expect(entries[1].entry.changedFiles).toEqual([fileItem.fileName]);
935 }
936 });
937
938 it("resolves attempt identity through V2 execution nodes", () => {
939 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
940 const threadId = ThreadId.make("thread-attempts");
941 const runId = RunId.make("run-steered");
942 const supersededRootNodeId = NodeId.make("node-attempt-1-root");
943 const supersededChildNodeId = NodeId.make("node-attempt-1-child");
944 const activeRootNodeId = NodeId.make("node-attempt-2-root");
945 const supersededAttemptId = RunAttemptId.make("attempt-1");
946 const activeAttemptId = RunAttemptId.make("attempt-2");
947 const providerInstanceId = ProviderInstanceId.make("codex-default");
948 const providerThreadId = ProviderThreadId.make("provider-thread-attempts");
949 const attempts: ReadonlyArray<OrchestrationV2RunAttempt> = [
950 {
951 id: supersededAttemptId,
952 runId,
953 attemptOrdinal: 1,
954 rootNodeId: supersededRootNodeId,
955 providerInstanceId,
956 providerThreadId,
957 providerTurnId: null,
958 reason: "initial",
959 status: "superseded",
960 startedAt: now,
961 completedAt: now,
962 },
963 {
964 id: activeAttemptId,
965 runId,
966 attemptOrdinal: 2,
967 rootNodeId: activeRootNodeId,
968 providerInstanceId,
969 providerThreadId,
970 providerTurnId: null,
971 reason: "steering_restart",
972 status: "running",
973 startedAt: now,
974 completedAt: null,
975 },
976 ];
977 const node = (
978 id: OrchestrationV2ExecutionNode["id"],
979 rootNodeId: OrchestrationV2ExecutionNode["rootNodeId"],
980 parentNodeId: OrchestrationV2ExecutionNode["parentNodeId"],
981 ): OrchestrationV2ExecutionNode => ({
982 id,
983 threadId,
984 runId,
985 parentNodeId,
986 rootNodeId,
987 kind: id === rootNodeId ? "root_turn" : "assistant_message",
988 status: "running",
989 countsForRun: true,
990 providerThreadId,
991 providerTurnId: null,
992 nativeItemRef: null,
993 runtimeRequestId: null,
994 checkpointScopeId: null,
995 startedAt: now,
996 completedAt: null,
997 });
998 const nodes = [
999 node(supersededRootNodeId, supersededRootNodeId, null),
1000 node(supersededChildNodeId, supersededRootNodeId, supersededRootNodeId),
1001 node(activeRootNodeId, activeRootNodeId, null),
1002 ];
1003 const assistantItem = (
1004 id: string,
1005 messageId: string,
1006 nodeId: NodeId,
1007 text: string,
1008 ordinal: number,
1009 ): OrchestrationV2TurnItem => ({
1010 id: TurnItemId.make(id),
1011 threadId,
1012 runId,
1013 nodeId,
1014 providerThreadId,
1015 providerTurnId: null,
1016 nativeItemRef: null,
1017 parentItemId: null,
1018 ordinal,
1019 status: "running",
1020 title: null,
1021 startedAt: now,
1022 completedAt: null,
1023 updatedAt: now,
1024 type: "assistant_message",
1025 messageId: MessageId.make(messageId),
1026 text,
1027 streaming: true,
1028 });
1029 const items = [
1030 assistantItem(
1031 "item-superseded",
1032 "message-superseded",
1033 supersededChildNodeId,
1034 "Partial old response",
1035 0,
1036 ),
1037 assistantItem("item-active", "message-active", activeRootNodeId, "Current response", 1),
1038 ];
1039 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = items.map(
1040 (item, position) => ({
1041 position,
1042 visibility: "local",
1043 sourceThreadId: threadId,
1044 sourceItemId: item.id,
1045 item,
1046 }),
1047 );
1048
1049 const entries = deriveTimelineEntriesFromVisibleTurnItems({
1050 visibleTurnItems,
1051 optimisticMessages: [],
1052 attempts,
1053 nodes,
1054 });
1055
1056 expect(entries.map((entry) => [entry.attempt?.id, entry.attempt?.status])).toEqual([
1057 [supersededAttemptId, "superseded"],
1058 [activeAttemptId, "running"],
1059 ]);
1060 const input = { visibleTurnItems, optimisticMessages: [], attempts, nodes };
1061 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1062 const nextInput = {
1063 ...input,
1064 attempts: attempts.map((attempt) =>
1065 attempt.id === activeAttemptId ? { ...attempt, status: "superseded" as const } : attempt,
1066 ),
1067 };
1068 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1069 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1070 expect(next.entries.at(-1)?.attempt?.status).toBe("superseded");
1071 expect(previous.entries.at(-1)?.attempt?.status).toBe("running");
1072 });
1073 });
1074
1075 describe("native provider presentation in the v2 timeline", () => {
1076 const timestamp = DateTime.makeUnsafe("2026-09-04T12:00:00.000Z");
1077 const base = {
1078 id: TurnItemId.make("native-item"),
1079 threadId: ThreadId.make("native-thread"),
1080 runId: RunId.make("native-run"),
1081 nodeId: null,
1082 providerThreadId: null,
1083 providerTurnId: null,
1084 nativeItemRef: null,
1085 parentItemId: null,
1086 ordinal: 0,
1087 status: "completed" as const,
1088 title: null,
1089 startedAt: timestamp,
1090 completedAt: timestamp,
1091 updatedAt: timestamp,
1092 };
1093 const visible = (item: OrchestrationV2TurnItem): OrchestrationV2ProjectedTurnItem => ({
1094 position: 0,
1095 visibility: "local",
1096 sourceThreadId: item.threadId,
1097 sourceItemId: item.id,
1098 item,
1099 });
1100
1101 it("keeps async answers in the question row, including incrementally appended replies", () => {
1102 const requestId = RuntimeRequestId.make("question");
1103 const question: OrchestrationV2TurnItem = {
1104 ...base,
1105 type: "user_input_request",
1106 requestId,
1107 questions: [],
1108 questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} },
1109 };
1110 const reply: OrchestrationV2TurnItem = {
1111 ...base,
1112 id: TurnItemId.make("answer"),
1113 type: "user_message",
1114 messageId: MessageId.make(`async-answer:${requestId}`),
1115 inputIntent: "steer",
1116 text: "Which color?\nBlue",
1117 createdBy: "user",
1118 creationSource: "server",
1119 attachments: [],
1120 };
1121 const input = { visibleTurnItems: [visible(question)], optimisticMessages: [] };
1122 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1123 const nextInput = { ...input, visibleTurnItems: [...input.visibleTurnItems, visible(reply)] };
1124 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1125 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1126 expect(next.entries).toHaveLength(1);
1127 const replyFirst = { ...input, visibleTurnItems: [visible(reply)] };
1128 const replyProjection = deriveTimelineEntriesFromVisibleTurnItemsWithState(replyFirst);
1129 const questionAfterReply = {
1130 ...input,
1131 visibleTurnItems: [...replyFirst.visibleTurnItems, visible(question)],
1132 };
1133 expect(
1134 deriveTimelineEntriesFromVisibleTurnItemsWithState(questionAfterReply, replyProjection)
1135 .entries,
1136 ).toEqual(deriveTimelineEntriesFromVisibleTurnItems(questionAfterReply));
1137
1138 expect(next.entries[0]).toMatchObject({
1139 kind: "work",
1140 entry: { questionAnswer: question.questionAnswer },
1141 });
1142 expect(
1143 deriveTimelineEntriesFromVisibleTurnItems({ ...input, visibleTurnItems: [visible(reply)] })[0]
1144 ?.kind,
1145 ).toBe("message");
1146 });
1147
1148 it("shows a late async answer that started a later run where that run begins", () => {
1149 const requestId = RuntimeRequestId.make("late-question");
1150 const inRun = (item: OrchestrationV2TurnItem, runId: string, ordinal: number) =>
1151 visible({ ...item, runId: RunId.make(runId), ordinal });
1152 const userMessage = (
1153 id: string,
1154 text: string,
1155 ): Extract<OrchestrationV2TurnItem, { type: "user_message" }> => ({
1156 ...base,
1157 id: TurnItemId.make(id),
1158 type: "user_message",
1159 messageId: MessageId.make(id),
1160 inputIntent: "queued_turn",
1161 text,
1162 createdBy: "user",
1163 creationSource: "web",
1164 attachments: [],
1165 });
1166 const assistantMessage = (id: string, text: string): OrchestrationV2TurnItem => ({
1167 ...base,
1168 id: TurnItemId.make(id),
1169 type: "assistant_message",
1170 messageId: MessageId.make(id),
1171 text,
1172 streaming: false,
1173 });
1174 const question = inRun(
1175 {
1176 ...base,
1177 id: TurnItemId.make("late-question"),
1178 type: "user_input_request",
1179 requestId,
1180 questions: [],
1181 questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} },
1182 },
1183 "run-8",
1184 8_000_070,
1185 );
1186 const answerMessageId = MessageId.make(`async-answer:${requestId}`);
1187 const settledPrefix = [
1188 question,
1189 inRun(userMessage("queued", "Queued follow-up"), "run-9", 9_000_001),
1190 inRun(assistantMessage("reply-9", "RUN 9 REPLY"), "run-9", 9_000_002),
1191 ];
1192 const lateRun = [
1193 inRun(
1194 {
1195 ...userMessage(answerMessageId, "Which color?\nBlue"),
1196 inputIntent: "steer",
1197 creationSource: "server",
1198 },
1199 "run-10",
1200 10_000_001,
1201 ),
1202 inRun(assistantMessage("reply-10", "RUN 10 ACKNOWLEDGED BLUE"), "run-10", 10_000_002),
1203 ];
1204 const input = { visibleTurnItems: [...settledPrefix, ...lateRun], optimisticMessages: [] };
1205 const messageIds = (entries: ReadonlyArray<TimelineEntry>) =>
1206 entries.flatMap((entry) => (entry.kind === "message" ? [entry.message.id] : []));
1207 const expectedMessageIds = ["queued", "reply-9", answerMessageId, "reply-10"];
1208
1209 expect
1210 .soft(messageIds(deriveTimelineEntriesFromVisibleTurnItems(input)), "full projection")
1211 .toEqual(expectedMessageIds);
1212 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState({
1213 ...input,
1214 visibleTurnItems: settledPrefix,
1215 });
1216 expect
1217 .soft(
1218 messageIds(deriveTimelineEntriesFromVisibleTurnItemsWithState(input, previous).entries),
1219 "incremental projection",
1220 )
1221 .toEqual(expectedMessageIds);
1222 });
1223
1224 it("excludes checkpoint-only work from the timeline", () => {
1225 const message: OrchestrationV2TurnItem = {
1226 ...base,
1227 type: "assistant_message",
1228 messageId: MessageId.make("done"),
1229 text: "Done",
1230 streaming: false,
1231 };
1232 const checkpoint: OrchestrationV2TurnItem = {
1233 ...base,
1234 id: TurnItemId.make("checkpoint"),
1235 type: "checkpoint",
1236 checkpointId: CheckpointId.make("checkpoint"),
1237 scopeId: CheckpointScopeId.make("scope"),
1238 files: [],
1239 };
1240 const entries = deriveTimelineEntriesFromVisibleTurnItems({
1241 visibleTurnItems: [visible(message), visible(checkpoint)],
1242 optimisticMessages: [],
1243 });
1244 expect(entries.map((entry) => entry.kind)).toEqual(["message"]);
1245 const rows = deriveMessagesTimelineRows({
1246 timelineEntries: entries,
1247 latestRun: {
1248 runId: base.runId,
1249 status: "completed",
1250 startedAt: DateTime.formatIso(timestamp),
1251 completedAt: DateTime.formatIso(timestamp),
1252 },
1253 isWorking: false,
1254 activeTurnStartedAt: null,
1255 turnDiffSummaries: [],
1256 supportsConversationRollback: false,
1257 });
1258 expect(rows.map((row) => row.kind)).toEqual(["message"]);
1259 });
1260
1261 it.each([
1262 { outputIndicatesFailure: true },
1263 { exitCode: 2 },
1264 { output: "bash: foo: command not found" },
1265 ])("keeps completed command failures visible without exposing output: %j", (result) => {
1266 const item = {
1267 ...base,
1268 type: "command_execution" as const,
1269 input: "foo",
1270 ...result,
1271 } satisfies OrchestrationV2TurnItem;
1272 const [entry] = deriveTimelineEntriesFromVisibleTurnItems({
1273 visibleTurnItems: [visible(item)],
1274 optimisticMessages: [],
1275 });
1276 if (entry?.kind !== "work") throw new Error("Expected a command work entry");
1277
1278 expect(entry.entry.detail).toBeUndefined();
1279 expect(entry.entry.command).toBe("foo");
1280 expect(entry.entry.toolLifecycleStatus).toBe("completed");
1281 expect(workEntryDisplayIndicatesToolFailure(entry.entry)).toBe(true);
1282 expect(workEntryIndicatesToolSuccess(entry.entry)).toBe(false);
1283 });
1284 });
1285
1286 describe("HTML renders in the timeline", () => {
1287 const runId = RunId.make("render-run");
1288 const at = (second: number) =>
1289 DateTime.makeUnsafe(`2026-09-04T12:00:${String(second).padStart(2, "0")}.000Z`);
1290 const base = (id: string, second: number) => ({
1291 id: TurnItemId.make(id),
1292 threadId: ThreadId.make("render-thread"),
1293 runId,
1294 nodeId: null,
1295 providerThreadId: null,
1296 providerTurnId: null,
1297 nativeItemRef: null,
1298 parentItemId: null,
1299 ordinal: second,
1300 status: "completed" as const,
1301 title: null,
1302 startedAt: at(second),
1303 completedAt: at(second),
1304 updatedAt: at(second),
1305 });
1306 const visible = (item: OrchestrationV2TurnItem): OrchestrationV2ProjectedTurnItem => ({
1307 position: item.ordinal,
1308 visibility: "local",
1309 sourceThreadId: item.threadId,
1310 sourceItemId: item.id,
1311 item,
1312 });
1313 const htmlRender = { attachmentId: "render-thread-chart.html", title: "Chart", height: 420 };
1314 const renderCall = (
1315 status: OrchestrationV2TurnItem["status"],
1316 output?: unknown,
1317 ): OrchestrationV2TurnItem => ({
1318 ...base("render", 2),
1319 status,
1320 type: "dynamic_tool",
1321 toolName: "mcp__t3-code__html_render",
1322 input: { title: "Chart", height: 420 },
1323 ...(output === undefined ? {} : { output }),
1324 });
1325 const command = (id: string, second: number): OrchestrationV2TurnItem => ({
1326 ...base(id, second),
1327 type: "command_execution",
1328 input: "vp test run",
1329 });
1330 const turn = (render: OrchestrationV2TurnItem) => {
1331 const items: OrchestrationV2TurnItem[] = [
1332 {
1333 ...base("prompt", 0),
1334 type: "user_message",
1335 messageId: MessageId.make("prompt"),
1336 inputIntent: "turn_start",
1337 text: "Chart it",
1338 createdBy: "user",
1339 creationSource: "server",
1340 attachments: [],
1341 },
1342 command("before", 1),
1343 render,
1344 command("after", 3),
1345 {
1346 ...base("reply", 4),
1347 type: "assistant_message",
1348 messageId: MessageId.make("reply"),
1349 text: "Here it is.",
1350 streaming: false,
1351 },
1352 ];
1353 return deriveTimelineEntriesFromVisibleTurnItems({
1354 visibleTurnItems: items.map(visible),
1355 optimisticMessages: [],
1356 });
1357 };
1358 const rowsFor = (entries: TimelineEntry[], expanded: boolean) =>
1359 deriveMessagesTimelineRows({
1360 timelineEntries: entries,
1361 latestRun: {
1362 runId,
1363 status: "completed",
1364 startedAt: DateTime.formatIso(at(0)),
1365 completedAt: DateTime.formatIso(at(5)),
1366 },
1367 ...(expanded ? { expandedRunIds: new Set([runId]) } : {}),
1368 isWorking: false,
1369 activeTurnStartedAt: null,
1370 turnDiffSummaries: [],
1371 supportsConversationRollback: false,
1372 }).map((row) => row.kind);
1373
1374 it("shows a completed render in place, above the reply, through the turn fold", () => {
1375 const entries = turn(
1376 renderCall("completed", { structuredContent: { htmlRender }, content: [] }),
1377 );
1378 expect(entries.find((entry) => entry.kind === "html-render")).toMatchObject({
1379 id: "render",
1380 runId,
1381 htmlRender,
1382 });
1383 expect(rowsFor(entries, false)).toEqual(["message", "turn-fold", "html-render", "message"]);
1384 expect(rowsFor(entries, true)).toEqual([
1385 "message",
1386 "turn-fold",
1387 "work",
1388 "html-render",
1389 "work",
1390 "message",
1391 ]);
1392 });
1393
1394 it("shows a sent message in place through the turn fold, and only once sent", () => {
1395 const sentMessage = "Draft reply:\n\n> Thanks, Thursday works.";
1396 const send = (
1397 status: OrchestrationV2TurnItem["status"],
1398 output?: unknown,
1399 ): OrchestrationV2TurnItem => ({
1400 ...base("render", 2),
1401 status,
1402 type: "dynamic_tool",
1403 toolName: "mcp__t3-code__send_to_user",
1404 input: { message: sentMessage },
1405 ...(output === undefined ? {} : { output }),
1406 });
1407 const entries = turn(send("completed", { structuredContent: { sentMessage }, content: [] }));
1408 expect(entries.find((entry) => entry.kind === "sent-message")).toMatchObject({
1409 id: "render",
1410 runId,
1411 text: sentMessage,
1412 });
1413 expect(rowsFor(entries, false)).toEqual(["message", "turn-fold", "sent-message", "message"]);
1414 expect(turn(send("running")).some((entry) => entry.kind === "sent-message")).toBe(false);
1415 });
1416
1417 it("hosts a captured MCP app after its tool row, from any provider's tool", () => {
1418 const mcpApp = {
1419 attachmentId: "render-thread-app-html",
1420 server: "weather",
1421 tool: "get_weather",
1422 resourceUri: "ui://weather/dashboard",
1423 };
1424 const call = renderCall("completed", { t3McpApp: mcpApp, result: { content: [] } });
1425 const entries = turn(
1426 call.type === "dynamic_tool" ? { ...call, toolName: "weather.get_weather" } : call,
1427 );
1428 expect(entries.find((entry) => entry.kind === "mcp-app")).toMatchObject({
1429 id: "mcp-app:render",
1430 itemId: "render",
1431 mcpApp,
1432 });
1433 expect(rowsFor(entries, false)).toEqual(["message", "turn-fold", "mcp-app", "message"]);
1434 });
1435
1436 it("keeps an MCP app call's tool row and output beside its app card", () => {
1437 const mcpApp = {
1438 attachmentId: "render-thread-app-html",
1439 server: "repro",
1440 tool: "aggregate_rum_events",
1441 resourceUri: "ui://repro/dataviz",
1442 };
1443 const result = { content: [{ type: "text", text: "Notice\nview\tcount\n/home\t42" }] };
1444 const call = renderCall("completed", { t3McpApp: mcpApp, result });
1445 const entries = turn(
1446 call.type === "dynamic_tool" ? { ...call, toolName: "repro.aggregate_rum_events" } : call,
1447 );
1448 expect(entries.find((entry) => entry.kind === "mcp-app")).toMatchObject({ mcpApp });
1449 const toolRows = entries.flatMap((entry) =>
1450 entry.kind === "work" && entry.entry.toolTitle === "repro.aggregate_rum_events"
1451 ? [entry.entry]
1452 : [],
1453 );
1454 expect(toolRows).toMatchObject([{ toolData: { output: { result } } }]);
1455 });
1456
1457 it("drops an MCP app card when an update removes the call's app", () => {
1458 const mcpApp = {
1459 attachmentId: "render-thread-app-html",
1460 server: "repro",
1461 tool: "aggregate_rum_events",
1462 resourceUri: "ui://repro/dataviz",
1463 };
1464 const call = (output: unknown) => ({
1465 ...renderCall("completed", output),
1466 toolName: "repro.aggregate_rum_events",
1467 });
1468 const result = { content: [{ type: "text", text: "rows" }] };
1469 const input = (output: unknown) => ({
1470 visibleTurnItems: [visible(command("before", 1)), visible(call(output))],
1471 optimisticMessages: [],
1472 });
1473 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(
1474 input({ t3McpApp: mcpApp, result }),
1475 );
1476 const nextInput = input({ result });
1477 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1478 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1479 });
1480
1481 it("hosts an MCP app whose call failed, as a form-deferring write does", () => {
1482 const mcpApp = {
1483 attachmentId: "render-thread-app-html",
1484 server: "github",
1485 tool: "create_pull_request",
1486 resourceUri: "ui://github-mcp-server/pr-create",
1487 };
1488 const call = renderCall("failed", {
1489 t3McpApp: mcpApp,
1490 result: { content: [], isError: true },
1491 });
1492 const entries = turn(
1493 call.type === "dynamic_tool" ? { ...call, toolName: "github.create_pull_request" } : call,
1494 );
1495 expect(entries.find((entry) => entry.kind === "mcp-app")).toMatchObject({ mcpApp });
1496 });
1497
1498 it("keeps a render visible when its superseded attempt folds", () => {
1499 const attempt: OrchestrationV2RunAttempt = {
1500 id: RunAttemptId.make("attempt-superseded"),
1501 runId,
1502 attemptOrdinal: 1,
1503 rootNodeId: NodeId.make("node-superseded"),
1504 providerInstanceId: ProviderInstanceId.make("codex-default"),
1505 providerThreadId: ProviderThreadId.make("provider-thread"),
1506 providerTurnId: null,
1507 reason: "initial",
1508 status: "superseded",
1509 startedAt: at(0),
1510 completedAt: at(4),
1511 };
1512 const entries = turn(
1513 renderCall("completed", { structuredContent: { htmlRender }, content: [] }),
1514 ).map((entry) =>
1515 entry.kind === "message" && entry.message.role === "user" ? entry : { ...entry, attempt },
1516 );
1517 expect(rowsFor(entries, true)).toEqual(["message", "turn-fold", "attempt-fold", "html-render"]);
1518 });
1519
1520 it.each([
1521 ["running", "running", undefined],
1522 ["failed", "failed", { content: [{ type: "text", text: "Invalid HTML" }], isError: true }],
1523 ["errored", "completed", { structuredContent: { htmlRender }, isError: true }],
1524 ] as const)("keeps a %s call in the work log", (_label, status, output) => {
1525 const entries = turn(renderCall(status, output));
1526 expect(entries.some((entry) => entry.kind === "html-render")).toBe(false);
1527 expect(entries.find((entry) => entry.id === "render")?.kind).toBe("work");
1528 });
1529 });
1530
1531 describe("work-log failure policy (#7999/#7893)", () => {
1532 const toolEntry = (overrides: Record<string, unknown>) =>
1533 ({
1534 id: "entry-1",
1535 createdAt: "2026-08-27T00:00:00.000Z",
1536 label: "Ran command",
1537 tone: "tool",
1538 ...overrides,
1539 }) as never;
1540
1541 it("flags success-status rows whose output text reports a failure", () => {
1542 expect(
1543 workEntryIndicatesToolFailure(
1544 toolEntry({ toolLifecycleStatus: "completed", detail: "bash: foo: command not found" }),
1545 ),
1546 ).toBe(true);
1547 expect(
1548 workEntryIndicatesToolFailure(
1549 toolEntry({ toolLifecycleStatus: "completed", detail: "<exited with exit code 2>" }),
1550 ),
1551 ).toBe(true);
1552 });
1553
1554 it("keeps the rendered row calm when only the command mentions failure text", () => {
1555 const entry = toolEntry({
1556 toolLifecycleStatus: "completed",
1557 command: "rg 'command not found' src/",
1558 });
1559 expect(workEntryIndicatesToolFailure(entry)).toBe(true);
1560 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);
1561 });
1562 });
1563
1564 describe("incremental v2 timeline entries", () => {
1565 it("retains history and attachment previews through decoded streaming updates", () => {
1566 const fixture = makeStreamingTimelineFixture("Partial");
1567 const attachment = {
1568 type: "image" as const,
1569 id: "stream-image",
1570 name: "image.png",
1571 mimeType: "image/png",
1572 sizeBytes: 42,
1573 };
1574 const visibleTurnItems = fixture.visibleTurnItems.map((row) =>
1575 row.item.type === "assistant_message"
1576 ? { ...row, item: { ...row.item, attachments: [attachment] } }
1577 : row,
1578 );
1579 const input = {
1580 visibleTurnItems,
1581 optimisticMessages: [],
1582 attachmentUrlById: new Map([[attachment.id, "https://server.test/image"]]),
1583 };
1584 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1585 Object.freeze(previous.entries);
1586 for (const entry of previous.entries) Object.freeze(entry);
1587 const last = visibleTurnItems.at(-1)!;
1588 if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
1589 const nextItem = {
1590 ...last,
1591 item: {
1592 ...last.item,
1593 text: "Next token",
1594 attachments: [{ ...attachment }],
1595 startedAt: DateTime.makeUnsafe(fixture.time(7)),
1596 updatedAt: DateTime.makeUnsafe(fixture.time(8)),
1597 },
1598 };
1599 const nextInput = {
1600 ...input,
1601 visibleTurnItems: [...visibleTurnItems.slice(0, -1), nextItem],
1602 attachmentUrlById: new Map(input.attachmentUrlById),
1603 };
1604 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1605 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1606 for (const [index, entry] of previous.entries.slice(0, -1).entries()) {
1607 expect(next.entries[index]).toBe(entry);
1608 }
1609 const beforeMessage = previous.entries.at(-1)!;
1610 const nextMessage = next.entries.at(-1)!;
1611 if (beforeMessage.kind !== "message" || nextMessage.kind !== "message") {
1612 throw new Error("Expected assistant entries");
1613 }
1614 expect(nextMessage.message.attachments).toBe(beforeMessage.message.attachments);
1615 expect(nextMessage.projectedItem).toBe(nextItem);
1616 expect(nextMessage.message.text).toBe("Next token");
1617 expect(beforeMessage.message.text).toBe("Partial");
1618
1619 const renewedInput = {
1620 ...nextInput,
1621 attachmentUrlById: new Map([[attachment.id, "https://renewed.test/image"]]),
1622 };
1623 const renewed = deriveTimelineEntriesFromVisibleTurnItemsWithState(renewedInput, next);
1624 expect(renewed.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(renewedInput));
1625 expect(renewed.entries.at(-1)).toMatchObject({
1626 message: { attachments: [{ previewUrl: "https://renewed.test/image" }] },
1627 });
1628 expect(nextMessage.message.attachments?.[0]).toMatchObject({
1629 previewUrl: "https://server.test/image",
1630 });
1631 const restoredInput = { ...renewedInput, attachmentUrlById: new Map<string, string>() };
1632 const restored = deriveTimelineEntriesFromVisibleTurnItemsWithState(restoredInput, renewed);
1633 expect(restored.entries.at(-1)).toMatchObject({ message: { attachments: [attachment] } });
1634 const restoredMessage = restored.entries.at(-1)!;
1635 if (restoredMessage.kind !== "message") throw new Error("Expected assistant entry");
1636 expect(restoredMessage.message.attachments?.[0]).not.toHaveProperty("previewUrl");
1637 });
1638
1639 it("appends committed items in canonical order even when their timestamps go backwards", () => {
1640 const fixture = makeStreamingTimelineFixture("Partial");
1641 const input = { visibleTurnItems: fixture.visibleTurnItems, optimisticMessages: [] };
1642 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1643 const last = fixture.visibleTurnItems.at(-1)!;
1644 const appended = {
1645 ...last,
1646 position: last.position + 1,
1647 sourceItemId: TurnItemId.make("late-item"),
1648 item: {
1649 ...last.item,
1650 id: TurnItemId.make("late-item"),
1651 messageId: MessageId.make("late-message"),
1652 startedAt: DateTime.makeUnsafe(fixture.time(0)),
1653 },
1654 };
1655 const nextInput = { ...input, visibleTurnItems: [...input.visibleTurnItems, appended] };
1656 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1657 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1658 expect(next.entries.at(-1)).toMatchObject({ id: "late-message" });
1659 for (const [index, entry] of previous.entries.entries())
1660 expect(next.entries[index]).toBe(entry);
1661 });
1662
1663 it("re-derives only the work entry whose tool item changed", () => {
1664 const fixture = makeStreamingTimelineFixture("Partial");
1665 const visibleTurnItems = fixture.visibleTurnItems.map((row) =>
1666 row.item.id === "live-work"
1667 ? { ...row, item: { ...row.item, status: "running" as const, completedAt: null } }
1668 : row,
1669 );
1670 const input = { visibleTurnItems, optimisticMessages: [] };
1671 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1672 const nextInput = { ...input, visibleTurnItems: fixture.visibleTurnItems };
1673 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1674 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1675 for (const [index, entry] of previous.entries.entries()) {
1676 if (entry.id === "live-work") expect(next.entries[index]).not.toBe(entry);
1677 else expect(next.entries[index]).toBe(entry);
1678 }
1679
1680 const anchoredInput = {
1681 ...nextInput,
1682 anchoredMessages: [
1683 {
1684 id: MessageId.make("feedback"),
1685 runId: null,
1686 role: "assistant" as const,
1687 text: "Feedback received",
1688 streaming: false,
1689 createdAt: fixture.time(6),
1690 updatedAt: fixture.time(6),
1691 },
1692 ],
1693 };
1694 const anchored = deriveTimelineEntriesFromVisibleTurnItemsWithState(anchoredInput);
1695 const movedInput = {
1696 ...anchoredInput,
1697 visibleTurnItems: anchoredInput.visibleTurnItems.map((row) =>
1698 row.item.id === "live-work"
1699 ? { ...row, item: { ...row.item, startedAt: DateTime.makeUnsafe(fixture.time(8)) } }
1700 : row,
1701 ),
1702 };
1703 expect(
1704 deriveTimelineEntriesFromVisibleTurnItemsWithState(movedInput, anchored).entries,
1705 ).toEqual(deriveTimelineEntriesFromVisibleTurnItems(movedInput));
1706 });
1707
1708 it.each(["completion", "provenance", "ordering", "attachment", "run"] as const)(
1709 "rebuilds entries for a %s change instead of retaining stale v2 metadata",
1710 (change) => {
1711 const fixture = makeStreamingTimelineFixture("Partial");
1712 const input = { visibleTurnItems: fixture.visibleTurnItems, optimisticMessages: [] };
1713 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1714 const last = fixture.visibleTurnItems.at(-1)!;
1715 if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
1716 const changed =
1717 change === "provenance"
1718 ? { ...last, sourceThreadId: ThreadId.make("inherited-thread") }
1719 : {
1720 ...last,
1721 item:
1722 change === "completion"
1723 ? { ...last.item, streaming: false, status: "completed" as const }
1724 : change === "ordering"
1725 ? { ...last.item, startedAt: DateTime.makeUnsafe(fixture.time(0)) }
1726 : change === "run"
1727 ? { ...last.item, runId: fixture.historyRunId }
1728 : {
1729 ...last.item,
1730 attachments: [
1731 {
1732 type: "image",
1733 id: "new-image",
1734 name: "new.png",
1735 mimeType: "image/png",
1736 sizeBytes: 42,
1737 },
1738 ],
1739 },
1740 };
1741 const nextInput = {
1742 ...input,
1743 visibleTurnItems: [...input.visibleTurnItems.slice(0, -1), changed],
1744 };
1745 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1746 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1747 expect(next.entries.at(-1)).not.toBe(previous.entries.at(-1));
1748 },
1749 );
1750
1751 it("deduplicates optimistic sends when committed items arrive and retains anchored ordering", () => {
1752 const fixture = makeStreamingTimelineFixture();
1753 const input = {
1754 visibleTurnItems: fixture.visibleTurnItems.slice(0, 3),
1755 optimisticMessages: [
1756 {
1757 id: MessageId.make("live-user"),
1758 runId: null,
1759 role: "user" as const,
1760 text: "Continue",
1761 streaming: false,
1762 createdAt: fixture.time(5),
1763 updatedAt: fixture.time(5),
1764 },
1765 ],
1766 anchoredMessages: [
1767 {
1768 id: MessageId.make("feedback"),
1769 runId: null,
1770 role: "assistant" as const,
1771 text: "Feedback received",
1772 streaming: false,
1773 createdAt: fixture.time(4),
1774 updatedAt: fixture.time(4),
1775 },
1776 ],
1777 };
1778 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1779 const nextInput = { ...input, visibleTurnItems: fixture.visibleTurnItems };
1780 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1781 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1782 expect(next.entries.filter((entry) => entry.id === "live-user")).toHaveLength(1);
1783 expect(next.entries.map((entry) => entry.id)).toEqual([
1784 "history-user",
1785 "history-work",
1786 "history-assistant",
1787 "feedback",
1788 "live-user",
1789 "live-work",
1790 "live-assistant",
1791 ]);
1792 });
1793
1794 it("keeps every other entry when streaming plan text changes", () => {
1795 const fixture = makeStreamingWorkTimelineFixture("proposed_plan");
1796 // Codex emits `plan.updated` with each delta, so the artifact array is rebuilt too.
1797 const plans = (markdown: string) => [streamingPlanArtifact(fixture, markdown, "active")];
1798 let input = {
1799 visibleTurnItems: withStreamedText(
1800 fixture.visibleTurnItems,
1801 fixture.streamingItemId,
1802 "Let",
1803 fixture.time(20),
1804 ),
1805 optimisticMessages: [],
1806 plans: plans("Let"),
1807 };
1808 let projection = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1809 for (const [step, text] of ["Let me", "Let me check the tests"].entries()) {
1810 input = {
1811 visibleTurnItems: withStreamedText(
1812 input.visibleTurnItems,
1813 fixture.streamingItemId,
1814 text,
1815 fixture.time(21 + step),
1816 ),
1817 optimisticMessages: [],
1818 plans: plans(text),
1819 };
1820 const previous = projection;
1821 projection = deriveTimelineEntriesFromVisibleTurnItemsWithState(input, previous);
1822 expect(projection.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(input));
1823 for (const [index, entry] of previous.entries.entries()) {
1824 if (entry.id !== fixture.streamingItemId) expect(projection.entries[index]).toBe(entry);
1825 }
1826 }
1827 });
1828
1829 it("rebuilds the plan entry when only its artifact status changes", () => {
1830 const fixture = makeStreamingWorkTimelineFixture("proposed_plan");
1831 const visibleTurnItems = withStreamedText(
1832 fixture.visibleTurnItems,
1833 fixture.streamingItemId,
1834 "Plan",
1835 fixture.time(20),
1836 );
1837 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState({
1838 visibleTurnItems,
1839 optimisticMessages: [],
1840 plans: [streamingPlanArtifact(fixture, "Plan", "active")],
1841 });
1842 const input = {
1843 visibleTurnItems,
1844 optimisticMessages: [],
1845 plans: [streamingPlanArtifact(fixture, "Plan", "superseded")],
1846 };
1847 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(input, previous);
1848 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(input));
1849 expect(next.entries.find((entry) => entry.kind === "proposed-plan")).toMatchObject({
1850 proposedPlan: { status: "superseded" },
1851 });
1852 });
1853 });
1854
1855 describe("image asset requests", () => {
1856 const image = {
1857 type: "image" as const,
1858 id: "image",
1859 name: "image.png",
1860 mimeType: "image/png",
1861 sizeBytes: 42,
1862 };
1863 const message = {
1864 id: MessageId.make("image-message"),
1865 role: "user" as const,
1866 text: "Inspect these images",
1867 runId: null,
1868 createdAt: "2026-09-04T00:00:00.000Z",
1869 updatedAt: "2026-09-04T00:00:00.000Z",
1870 streaming: false,
1871 attachments: [image],
1872 };
1873
1874 it("requests the whole row's gallery and crops without signing local preview IDs", () => {
1875 const attachments = Object.freeze([
1876 image,
1877 { ...image, id: "second" },
1878 { ...image, id: "crop", name: "preview-annotation-1.png" },
1879 { ...image, id: "local", previewUrl: "blob:local" },
1880 { ...image, id: "inline", previewUrl: "data:image/png;base64,AA==" },
1881 { ...image, id: "provided", previewUrl: "https://preview.test/image" },
1882 { ...image, type: "file" as const, id: "file", mimeType: "application/pdf" },
1883 { ...image, type: "future", id: "unknown" },
1884 image,
1885 ]);
1886
1887 expect(selectMessageImageResources(attachments)).toEqual([
1888 { _tag: "attachment", attachmentId: "image" },
1889 { _tag: "attachment", attachmentId: "second" },
1890 { _tag: "attachment", attachmentId: "crop" },
1891 { _tag: "attachment", attachmentId: "provided" },
1892 ]);
1893 });
1894
1895 it("requests offscreen handoffs without signing the rest of the loaded history", () => {
1896 const history = {
1897 ...message,
1898 id: MessageId.make("history"),
1899 attachments: [{ ...image, id: "history-image" }],
1900 };
1901 const offscreen = {
1902 ...message,
1903 id: MessageId.make("offscreen"),
1904 attachments: [image, { ...image, id: "crop", name: "preview-annotation-1.png" }],
1905 };
1906 const empty = {
1907 ...message,
1908 id: MessageId.make("empty"),
1909 attachments: [{ ...image, id: "empty" }],
1910 };
1911 const assistant = {
1912 ...message,
1913 id: MessageId.make("assistant"),
1914 role: "assistant" as const,
1915 attachments: [{ ...image, id: "assistant-image" }],
1916 };
1917 expect(
1918 selectHandoffImageResources([history, message, offscreen, empty, assistant], {
1919 [message.id]: ["blob:message"],
1920 [offscreen.id]: ["blob:offscreen", "blob:crop"],
1921 [empty.id]: [],
1922 [assistant.id]: ["blob:unused"],
1923 }),
1924 ).toEqual([
1925 { _tag: "attachment", attachmentId: "image" },
1926 { _tag: "attachment", attachmentId: "crop" },
1927 ]);
1928 });
1929
1930 it("hands signed URLs to a mounted row only after the local preview is released", () => {
1931 const server = createMessageAttachmentPreviewProjector();
1932 const handoff = createMessageAttachmentPreviewProjector();
1933 const row = createMessageAttachmentPreviewProjector();
1934 const pending = handoff(
1935 server(message, () => undefined),
1936 () => "blob:pending",
1937 );
1938 expect(selectMessageImageResources(pending.attachments)).toEqual([]);
1939 expect(selectHandoffImageResources([message], { [message.id]: ["blob:pending"] })).toEqual([
1940 { _tag: "attachment", attachmentId: image.id },
1941 ]);
1942
1943 const ready = server(message, () => "https://server.test/image");
1944 expect(selectMessageImageResources(handoff(ready, () => "blob:pending").attachments)).toEqual(
1945 [],
1946 );
1947 const released = server(message, () => undefined);
1948 expect(selectMessageImageResources(released.attachments)).toEqual([
1949 { _tag: "attachment", attachmentId: image.id },
1950 ]);
1951 const displayed = row(released, () => "https://server.test/image");
1952 expect(displayed).toEqual(ready);
1953 expect(pending.attachments?.[0]).toMatchObject({ previewUrl: "blob:pending" });
1954 expect(row(released, () => "https://server.test/renewed").attachments?.[0]).toMatchObject({
1955 previewUrl: "https://server.test/renewed",
1956 });
1957 expect(displayed.attachments?.[0]).toMatchObject({ previewUrl: "https://server.test/image" });
1958 expect(row(released, () => undefined)).toBe(message);
1959 });
1960 });
1961
1962 it("renders automatic completion as a work entry instead of a user bubble", () => {
1963 const now = DateTime.makeUnsafe("2026-09-09T00:00:00Z");
1964 const item = {
1965 id: TurnItemId.make("wake-item"),
1966 threadId: ThreadId.make("parent"),
1967 runId: RunId.make("wake-run"),
1968 nodeId: null,
1969 providerThreadId: null,
1970 providerTurnId: null,
1971 nativeItemRef: null,
1972 parentItemId: null,
1973 ordinal: 0,
1974 status: "completed" as const,
1975 title: null,
1976 startedAt: now,
1977 completedAt: now,
1978 updatedAt: now,
1979 type: "notification" as const,
1980 source: { kind: "delegated_task" as const, taskIds: [NodeId.make("task-1")] },
1981 outcome: "unknown" as const,
1982 summary: "Delegated task finished",
1983 };
1984 const row = {
1985 item,
1986 position: 0,
1987 visibility: "local" as const,
1988 sourceThreadId: item.threadId,
1989 sourceItemId: item.id,
1990 };
1991 const entries = deriveTimelineEntriesFromVisibleTurnItems({
1992 optimisticMessages: [],
1993 visibleTurnItems: [row],
1994 });
1995 expect(entries).toHaveLength(1);
1996 expect(entries[0]).toMatchObject({
1997 kind: "work",
1998 entry: { label: "Delegated task finished", tone: "info", projectedItem: row },
1999 });
2000 expect(
2001 deriveTimelineEntriesFromVisibleTurnItems({
2002 optimisticMessages: [],
2003 visibleTurnItems: [
2004 {
2005 ...row,
2006 item: {
2007 ...item,
2008 type: "user_message",
2009 messageId: MessageId.make("wake-message"),
2010 createdBy: "agent" as const,
2011 creationSource: "server" as const,
2012 inputIntent: "turn_start" as const,
2013 attachments: [],
2014 text: "Delegated task node:task-1 reached a terminal state. Use task_status with taskId node:task-1 to read the result.",
2015 },
2016 },
2017 ],
2018 })[0]?.kind,
2019 ).toBe("message");
2020 });