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

session-logic.test.ts

1,496 lines50.1 KB

1import {
2 MessageId,
3 NodeId,
4 PlanId,
5 ProviderInstanceId,
6 ProviderThreadId,
7 RunAttemptId,
8 RunId,
9 ScheduledTaskId,
10 ThreadId,
11 TurnItemId,
12 type OrchestrationV2ProjectedTurnItem,
13 type OrchestrationV2ExecutionNode,
14 type OrchestrationV2RunAttempt,
15 type OrchestrationV2TurnItem,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import { describe, expect, it } from "vite-plus/test";
19​
20import {
21 deriveActivePlanState,
22 deriveTimelineEntriesFromVisibleTurnItems,
23 deriveTimelineEntriesFromVisibleTurnItemsWithState,
24 deriveRevertTurnCountByUserMessageId,
25 findLatestProposedPlan,
26 isLatestRunSettled,
27 selectHandoffImageResources,
28 selectMessageImageResources,
29 createMessageAttachmentPreviewProjector,
30 providerErrorPresentation,
31 type TimelineEntry,
32 workEntryIndicatesToolFailure,
33 workEntryDisplayIndicatesToolFailure,
34 workEntryIndicatesToolSuccess,
35} from "./session-logic";
36import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "./test-fixtures";
37import type { ChatMessage } from "./types";
38​
39describe("V2 session presentation", () => {
40 it("uses run status as the settlement boundary", () => {
41 const runId = RunId.make("run-1");
42 expect(
43 isLatestRunSettled(
44 {
45 runId,
46 status: "completed",
47 startedAt: "2026-06-20T00:00:00.000Z",
48 completedAt: "2026-06-20T00:01:00.000Z",
49 },
50 null,
51 ),
52 ).toBe(true);
53 expect(
54 isLatestRunSettled(
55 { runId, status: "running", startedAt: null, completedAt: null },
56 { status: "running", activeRunId: runId },
57 ),
58 ).toBe(false);
59 expect(
60 isLatestRunSettled(
61 { runId, status: "queued", startedAt: null, completedAt: null },
62 { status: "running", activeRunId: RunId.make("run-active") },
63 ),
64 ).toBe(false);
65 });
66​
67 it("labels provider retry progress, delay, recovery, and exhaustion", () => {
68 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
69 const retryItem = {
70 id: TurnItemId.make("item-provider-retry"),
71 threadId: ThreadId.make("thread-provider-retry"),
72 runId: RunId.make("run-provider-retry"),
73 nodeId: null,
74 providerThreadId: null,
75 providerTurnId: null,
76 nativeItemRef: null,
77 parentItemId: null,
78 ordinal: 1,
79 status: "running" as const,
80 title: "Provider retry",
81 startedAt: now,
82 completedAt: null,
83 updatedAt: now,
84 type: "error" as const,
85 failure: {
86 class: "provider_error" as const,
87 message: "Claude API overloaded.",
88 code: "api_error_529",
89 retryable: true,
90 },
91 retry: {
92 attempt: 2,
93 maxAttempts: 10,
94 retryDelayMs: 1_500,
95 },
96 } satisfies Extract<OrchestrationV2TurnItem, { readonly type: "error" }>;
97​
98 expect(providerErrorPresentation(retryItem)).toEqual({
99 label: "Retrying provider (2/10)",
100 detail: "Claude API overloaded. Retrying in 1.5s.",
101 });
102 expect(
103 providerErrorPresentation({
104 ...retryItem,
105 status: "completed",
106 completedAt: now,
107 }),
108 ).toMatchObject({ label: "Provider recovered (2/10 retries)" });
109 expect(
110 providerErrorPresentation({
111 ...retryItem,
112 status: "failed",
113 retry: { ...retryItem.retry, attempt: 10 },
114 completedAt: now,
115 }),
116 ).toMatchObject({ label: "Provider error after 10/10 retries" });
117 });
118​
119 it("selects the latest proposed plan for a run", () => {
120 const runId = RunId.make("run-1");
121 const planId = PlanId.make("plan-1");
122 const nodeId = NodeId.make("node-plan");
123 const now = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");
124 const baseProjection = makeThreadProjectionFixture();
125 const plan = findLatestProposedPlan(
126 {
127 ...baseProjection,
128 plans: [
129 {
130 id: planId,
131 threadId: baseProjection.thread.id,
132 nodeId,
133 kind: "proposed_plan" as const,
134 markdown: "Plan",
135 status: "active" as const,
136 runId,
137 },
138 ],
139 turnItems: [
140 {
141 id: TurnItemId.make("item-plan"),
142 threadId: baseProjection.thread.id,
143 nodeId,
144 providerThreadId: null,
145 providerTurnId: null,
146 nativeItemRef: null,
147 parentItemId: null,
148 ordinal: 0,
149 status: "completed" as const,
150 title: null,
151 startedAt: now,
152 completedAt: now,
153 updatedAt: now,
154 type: "proposed_plan" as const,
155 planId,
156 markdown: "Plan",
157 streaming: false,
158 runId,
159 },
160 ],
161 updatedAt: now,
162 },
163 runId,
164 );
165 expect(plan?.planMarkdown).toBe("Plan");
166 });
167​
168 it("assigns run rollback to the turn-start message instead of a later steer", () => {
169 const runId = RunId.make("run-steered");
170 const turnStartMessageId = MessageId.make("message-turn-start");
171 const steerMessageId = MessageId.make("message-steer");
172 const assistantMessageId = MessageId.make("message-assistant");
173 const messages: ChatMessage[] = [
174 {
175 id: turnStartMessageId,
176 role: "user",
177 text: "Start",
178 runId,
179 inputIntent: "turn_start",
180 streaming: false,
181 createdAt: "2026-06-20T00:00:00.000Z",
182 updatedAt: "2026-06-20T00:00:00.000Z",
183 },
184 {
185 id: steerMessageId,
186 role: "user",
187 text: "Steer",
188 runId,
189 inputIntent: "steer",
190 streaming: false,
191 createdAt: "2026-06-20T00:00:01.000Z",
192 updatedAt: "2026-06-20T00:00:01.000Z",
193 },
194 {
195 id: assistantMessageId,
196 role: "assistant",
197 text: "Done",
198 runId,
199 streaming: false,
200 createdAt: "2026-06-20T00:00:02.000Z",
201 updatedAt: "2026-06-20T00:00:02.000Z",
202 },
203 ];
204 const timelineEntries: TimelineEntry[] = messages.map((message): TimelineEntry => ({
205 id: message.id,
206 kind: "message",
207 createdAt: message.createdAt,
208 message,
209 }));
210​
211 const targets = deriveRevertTurnCountByUserMessageId({
212 timelineEntries,
213 checkpoints: [
214 {
215 runId,
216 checkpointTurnCount: 1,
217 checkpointRef: "checkpoint-run-1" as never,
218 status: "ready",
219 files: [],
220 assistantMessageId,
221 completedAt: "2026-06-20T00:00:03.000Z",
222 },
223 ],
224 });
225​
226 expect([...targets]).toEqual([[turnStartMessageId, 0]]);
227 expect(targets.has(steerMessageId)).toBe(false);
228 });
229​
230 it("uses visible turn item order and keeps provider errors in the work log", () => {
231 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
232 const threadId = ThreadId.make("thread-visible");
233 const runId = RunId.make("run-visible");
234 const base = (id: string, ordinal: number) => ({
235 id: TurnItemId.make(id),
236 threadId,
237 runId,
238 nodeId: null,
239 providerThreadId: null,
240 providerTurnId: null,
241 nativeItemRef: null,
242 parentItemId: null,
243 ordinal,
244 status: "completed" as const,
245 title: null,
246 startedAt: now,
247 completedAt: now,
248 updatedAt: now,
249 });
250 const userItem = {
251 ...base("item-user", 0),
252 type: "user_message" as const,
253 messageId: MessageId.make("message-user"),
254 inputIntent: "turn_start" as const,
255 text: "Start",
256 attachments: [],
257 createdBy: "user" as const,
258 creationSource: "web" as const,
259 } satisfies OrchestrationV2TurnItem;
260 const requestItem = {
261 ...base("item-interrupt-request", 1),
262 type: "run_interrupt_request" as const,
263 message: "Stopping",
264 } satisfies OrchestrationV2TurnItem;
265 const commandItem = {
266 ...base("item-command", 2),
267 type: "command_execution" as const,
268 input: "sleep 1",
269 output: "done",
270 exitCode: 0,
271 } satisfies OrchestrationV2TurnItem;
272 const resultItem = {
273 ...base("item-interrupt-result", 3),
274 type: "run_interrupt_result" as const,
275 message: "Stopped",
276 } satisfies OrchestrationV2TurnItem;
277 const todoItem = {
278 ...base("item-todo", 4),
279 type: "todo_list" as const,
280 planId: PlanId.make("plan-visible"),
281 explanation: "Keep task detail in the Tasks panel",
282 steps: [
283 { id: "step-1", text: "First", status: "completed" as const },
284 { id: "step-2", text: "Second", status: "pending" as const },
285 ],
286 } satisfies OrchestrationV2TurnItem;
287 const errorItem = {
288 ...base("item-error", 5),
289 status: "failed" as const,
290 type: "error" as const,
291 failure: {
292 class: "validation_error" as const,
293 message: "Invalid reasoning effort.",
294 code: "invalid_request",
295 retryable: false,
296 },
297 } satisfies OrchestrationV2TurnItem;
298 const threadCreatedItem = {
299 ...base("item-thread-created", 6),
300 type: "thread_created" as const,
301 title: "Follow-up thread",
302 targetThreadId: ThreadId.make("thread-follow-up"),
303 targetRunId: RunId.make("run-follow-up"),
304 targetProviderInstanceId: ProviderInstanceId.make("claude-default"),
305 targetModel: "claude-sonnet-4-6",
306 } satisfies OrchestrationV2TurnItem;
307 const workspacePreparationItem = {
308 ...base("item-workspace-preparation", 7),
309 type: "command_execution" as const,
310 title: "Workspace ready",
311 input: "Preparing workspace",
312 output: "Workspace preparation completed.",
313 exitCode: 0,
314 } satisfies OrchestrationV2TurnItem;
315 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
316 userItem,
317 requestItem,
318 commandItem,
319 resultItem,
320 todoItem,
321 errorItem,
322 threadCreatedItem,
323 workspacePreparationItem,
324 ].map((item, position) => ({
325 position,
326 visibility: "local" as const,
327 sourceThreadId: threadId,
328 sourceItemId: item.id,
329 item,
330 }));
331​
332 const entries = deriveTimelineEntriesFromVisibleTurnItems({
333 visibleTurnItems,
334 optimisticMessages: [],
335 });
336​
337 expect(entries.map((entry) => [entry.kind, entry.id])).toEqual([
338 ["message", userItem.messageId],
339 ["event", requestItem.id],
340 ["work", commandItem.id],
341 ["event", resultItem.id],
342 ["work", errorItem.id],
343 ["work", threadCreatedItem.id],
344 ]);
345 const commandEntry = entries[2];
346 const userEntry = entries[0];
347 expect(userEntry?.kind).toBe("message");
348 if (userEntry?.kind === "message") {
349 expect(userEntry.projectedItem).toBe(visibleTurnItems[0]);
350 expect(userEntry.message.inputIntent).toBe("turn_start");
351 expect(userEntry.message.createdBy).toBe("user");
352 expect(userEntry.message.creationSource).toBe("web");
353 }
354 expect(commandEntry?.kind).toBe("work");
355 if (commandEntry?.kind === "work") {
356 expect(commandEntry.entry.projectedItem).toBe(visibleTurnItems[2]);
357 expect(commandEntry.entry.structuredPayload).toBe(commandItem);
358 expect(commandEntry.entry.command).toBe(commandItem.input);
359 expect(commandEntry.entry.detail).toBeUndefined();
360 }
361 const errorEntry = entries[4];
362 expect(errorEntry?.kind).toBe("work");
363 if (errorEntry?.kind === "work") {
364 expect(errorEntry.entry.projectedItem).toBe(visibleTurnItems[5]);
365 expect(errorEntry.entry.label).toBe("Provider error");
366 expect(errorEntry.entry.detail).toBe("Invalid reasoning effort.");
367 expect(errorEntry.entry.tone).toBe("info");
368 expect(errorEntry.entry.toolLifecycleStatus).toBe("failed");
369 }
370 const threadCreatedEntry = entries[5];
371 expect(threadCreatedEntry?.kind).toBe("work");
372 if (threadCreatedEntry?.kind === "work") {
373 expect(threadCreatedEntry.entry.projectedItem?.item.type).toBe("thread_created");
374 }
375 });
376​
377 it.each(["pending", "running", "completed"] as const)(
378 "keeps %s task progress available to the composer and out of the timeline",
379 (stepStatus) => {
380 const projection = makeThreadProjectionFixture();
381 const now = DateTime.makeUnsafe("2026-09-04T00:00:00.000Z");
382 const runId = RunId.make("run-tasks");
383 const nodeId = NodeId.make("node-tasks");
384 const planId = PlanId.make("plan-tasks");
385 const steps = [{ id: "step-1", text: "Verify the change", status: stepStatus }];
386 const item = {
387 id: TurnItemId.make("item-tasks"),
388 threadId: projection.thread.id,
389 runId,
390 nodeId,
391 providerThreadId: null,
392 providerTurnId: null,
393 nativeItemRef: null,
394 parentItemId: null,
395 ordinal: 0,
396 status: "completed" as const,
397 title: null,
398 startedAt: now,
399 completedAt: now,
400 updatedAt: now,
401 type: "todo_list" as const,
402 planId,
403 steps,
404 } satisfies OrchestrationV2TurnItem;
405 const plans = [
406 {
407 id: planId,
408 threadId: projection.thread.id,
409 runId,
410 nodeId,
411 kind: "todo_list" as const,
412 status: "active" as const,
413 steps,
414 },
415 ];
416​
417 expect(
418 deriveTimelineEntriesFromVisibleTurnItems({
419 visibleTurnItems: [
420 {
421 position: 0,
422 visibility: "local",
423 sourceThreadId: projection.thread.id,
424 sourceItemId: item.id,
425 item,
426 },
427 ],
428 optimisticMessages: [],
429 plans,
430 }),
431 ).toEqual([]);
432 expect(
433 deriveActivePlanState({ ...projection, plans, turnItems: [item] }, runId),
434 ).toMatchObject({
435 runId,
436 steps: [
437 {
438 step: "Verify the change",
439 status: stepStatus === "running" ? "inProgress" : stepStatus,
440 },
441 ],
442 });
443 },
444 );
445​
446 it("preserves independently derived durations for repeated plan-step labels", () => {
447 const projection = makeThreadProjectionFixture();
448 const runId = RunId.make("run-timed-tasks");
449 const planId = PlanId.make("plan-timed-tasks");
450 const plan = {
451 id: planId,
452 threadId: projection.thread.id,
453 runId,
454 nodeId: NodeId.make("node-timed-tasks"),
455 kind: "todo_list" as const,
456 status: "active" as const,
457 steps: [
458 { id: "verify-a", text: "Verify", status: "completed" as const, durationMs: 3_000 },
459 { id: "verify-b", text: "Verify", status: "completed" as const, durationMs: 4_000 },
460 { id: "report", text: "Report", status: "pending" as const },
461 ],
462 };
463​
464 expect(deriveActivePlanState({ ...projection, plans: [plan] }, runId)?.steps).toEqual([
465 { step: "Verify", status: "completed", durationMs: 3_000 },
466 { step: "Verify", status: "completed", durationMs: 4_000 },
467 { step: "Report", status: "pending" },
468 ]);
469 });
470​
471 it("keeps failed tool items tool-toned so groups still summarize", () => {
472 const failedCommand = {
473 id: TurnItemId.make("item-failed-command"),
474 threadId: ThreadId.make("thread-1"),
475 runId: RunId.make("run-1"),
476 nodeId: null,
477 providerThreadId: null,
478 providerTurnId: null,
479 nativeItemRef: null,
480 parentItemId: null,
481 ordinal: 0,
482 status: "failed" as const,
483 title: null,
484 startedAt: null,
485 completedAt: null,
486 updatedAt: DateTime.nowUnsafe(),
487 type: "command_execution" as const,
488 input: "ssh host true",
489 output: "connection refused",
490 exitCode: 255,
491 } satisfies OrchestrationV2TurnItem;
492 const entries = deriveTimelineEntriesFromVisibleTurnItems({
493 visibleTurnItems: [
494 {
495 position: 0,
496 visibility: "local" as const,
497 sourceThreadId: ThreadId.make("thread-1"),
498 sourceItemId: failedCommand.id,
499 item: failedCommand,
500 } as never,
501 ],
502 optimisticMessages: [],
503 });
504 const entry = entries[0];
505 expect(entry?.kind).toBe("work");
506 if (entry?.kind === "work") {
507 // An exit-code failure is still an ordinary tool row: the failed
508 // lifecycle status carries the marker, and an "error" tone here would
509 // knock the whole group out of the "Ran N commands" summary.
510 expect(entry.entry.tone).toBe("tool");
511 expect(entry.entry.toolLifecycleStatus).toBe("failed");
512 }
513 });
514​
515 it("waits for a dispatched turn item before adding queued input to the timeline", () => {
516 const projection = makeThreadProjectionFixture();
517 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
518 const runId = RunId.make("run-dispatched-queued");
519 const messageId = MessageId.make("message-dispatched-queued");
520 const optimisticMessage = {
521 id: messageId,
522 role: "user" as const,
523 text: "Queued input",
524 runId: null,
525 inputIntent: "queued_turn" as const,
526 streaming: false,
527 createdAt: DateTime.formatIso(now),
528 updatedAt: DateTime.formatIso(now),
529 };
530​
531 expect(
532 deriveTimelineEntriesFromVisibleTurnItems({
533 visibleTurnItems: [],
534 optimisticMessages: [optimisticMessage],
535 }),
536 ).toEqual([]);
537​
538 const dispatchedItem = {
539 id: TurnItemId.make("item-dispatched-queued"),
540 threadId: projection.thread.id,
541 runId,
542 nodeId: null,
543 providerThreadId: null,
544 providerTurnId: null,
545 nativeItemRef: null,
546 parentItemId: null,
547 ordinal: 200,
548 status: "completed" as const,
549 title: null,
550 startedAt: now,
551 completedAt: now,
552 updatedAt: now,
553 type: "user_message" as const,
554 messageId,
555 inputIntent: "turn_start" as const,
556 text: "Queued input",
557 attachments: [],
558 createdBy: "agent" as const,
559 creationSource: "mcp" as const,
560 scheduledTaskId: ScheduledTaskId.make("task-queued"),
561 } satisfies OrchestrationV2TurnItem;
562 const promotedEntries = deriveTimelineEntriesFromVisibleTurnItems({
563 visibleTurnItems: [
564 {
565 position: 0,
566 visibility: "local",
567 sourceThreadId: projection.thread.id,
568 sourceItemId: dispatchedItem.id,
569 item: dispatchedItem,
570 },
571 ],
572 optimisticMessages: [optimisticMessage],
573 });
574 expect(promotedEntries.map((entry) => entry.id)).toEqual([messageId]);
575 expect(promotedEntries[0]?.kind).toBe("message");
576 if (promotedEntries[0]?.kind === "message") {
577 expect(promotedEntries[0].message.inputIntent).toBe("turn_start");
578 expect(promotedEntries[0].message.scheduledTaskId).toBe("task-queued");
579 }
580 });
581​
582 it("anchors feedback before later committed turns without reordering canonical history", () => {
583 const threadId = ThreadId.make("thread-feedback-order");
584 const messageItem = (input: {
585 readonly id: string;
586 readonly role: "user" | "assistant";
587 readonly createdAt: string;
588 readonly ordinal: number;
589 }): OrchestrationV2TurnItem => {
590 const timestamp = DateTime.makeUnsafe(input.createdAt);
591 const common = {
592 id: TurnItemId.make(`item-${input.id}`),
593 threadId,
594 runId: RunId.make(`run-${input.ordinal}`),
595 nodeId: null,
596 providerThreadId: null,
597 providerTurnId: null,
598 nativeItemRef: null,
599 parentItemId: null,
600 ordinal: input.ordinal,
601 status: "completed" as const,
602 title: null,
603 startedAt: timestamp,
604 completedAt: timestamp,
605 updatedAt: timestamp,
606 messageId: MessageId.make(input.id),
607 text: input.id,
608 };
609 return input.role === "user"
610 ? {
611 ...common,
612 type: "user_message",
613 inputIntent: "turn_start",
614 attachments: [],
615 createdBy: "user",
616 creationSource: "web",
617 }
618 : { ...common, type: "assistant_message", streaming: false };
619 };
620 const canonicalItems = [
621 messageItem({ id: "old-user", role: "user", createdAt: "2026-08-29T00:00:01Z", ordinal: 1 }),
622 messageItem({
623 id: "old-assistant",
624 role: "assistant",
625 createdAt: "2026-08-29T00:00:02Z",
626 ordinal: 2,
627 }),
628 messageItem({
629 id: "later-user",
630 role: "user",
631 createdAt: "2026-08-29T00:00:05Z",
632 ordinal: 3,
633 }),
634 messageItem({
635 id: "later-assistant",
636 role: "assistant",
637 createdAt: "2026-08-29T00:00:04Z",
638 ordinal: 4,
639 }),
640 ];
641 const visibleTurnItems = canonicalItems.map((item, position) => ({
642 position,
643 visibility: "local" as const,
644 sourceThreadId: threadId,
645 sourceItemId: item.id,
646 item,
647 }));
648 const feedback = (id: string, role: "user" | "assistant"): ChatMessage => ({
649 id: MessageId.make(id),
650 role,
651 text: id,
652 runId: null,
653 streaming: false,
654 createdAt: "2026-08-29T00:00:03Z",
655 updatedAt: "2026-08-29T00:00:03Z",
656 });
657 const entries = deriveTimelineEntriesFromVisibleTurnItems({
658 visibleTurnItems,
659 anchoredMessages: [
660 feedback("feedback-user", "user"),
661 feedback("feedback-assistant", "assistant"),
662 feedback("later-user", "user"),
663 ],
664 optimisticMessages: [
665 { ...feedback("optimistic-user", "user"), createdAt: "2026-08-29T00:00:00Z" },
666 ],
667 });
668​
669 expect(entries.map((entry) => entry.id)).toEqual([
670 "old-user",
671 "old-assistant",
672 "feedback-user",
673 "feedback-assistant",
674 "later-user",
675 "later-assistant",
676 "optimistic-user",
677 ]);
678 expect(
679 entries
680 .filter((entry) => entry.id.startsWith("feedback-"))
681 .every((entry) => entry.kind === "message" && entry.projectedItem === undefined),
682 ).toBe(true);
683 });
684​
685 it("uses projected plan status and file contents in timeline entries", () => {
686 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
687 const threadId = ThreadId.make("thread-timeline-artifacts");
688 const runId = RunId.make("run-timeline-artifacts");
689 const nodeId = NodeId.make("node-timeline-artifacts");
690 const planId = PlanId.make("plan-timeline-artifacts");
691 const base = {
692 threadId,
693 runId,
694 nodeId,
695 providerThreadId: null,
696 providerTurnId: null,
697 nativeItemRef: null,
698 parentItemId: null,
699 status: "completed" as const,
700 title: null,
701 startedAt: now,
702 completedAt: now,
703 updatedAt: now,
704 };
705 const planItem = {
706 ...base,
707 id: TurnItemId.make("item-proposed-plan"),
708 ordinal: 0,
709 type: "proposed_plan" as const,
710 planId,
711 markdown: "Finished plan",
712 streaming: false,
713 } satisfies OrchestrationV2TurnItem;
714 const fileItem = {
715 ...base,
716 id: TurnItemId.make("item-file-change"),
717 ordinal: 1,
718 type: "file_change" as const,
719 fileName: "src/example.ts",
720 newStr: "export const answer = 42;\n",
721 } satisfies OrchestrationV2TurnItem;
722 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
723 planItem,
724 fileItem,
725 ].map((item, position) => ({
726 position,
727 visibility: "local",
728 sourceThreadId: threadId,
729 sourceItemId: item.id,
730 item,
731 }));
732​
733 const entries = deriveTimelineEntriesFromVisibleTurnItems({
734 visibleTurnItems,
735 optimisticMessages: [],
736 plans: [
737 {
738 id: planId,
739 threadId,
740 runId,
741 nodeId,
742 kind: "proposed_plan",
743 markdown: "",
744 status: "completed",
745 detailInTurnItem: true,
746 },
747 ],
748 });
749​
750 expect(entries[0]?.kind).toBe("proposed-plan");
751 if (entries[0]?.kind === "proposed-plan") {
752 expect(entries[0].proposedPlan.status).toBe("completed");
753 expect(entries[0].proposedPlan.planMarkdown).toBe("Finished plan");
754 }
755 expect(entries[1]?.kind).toBe("work");
756 if (entries[1]?.kind === "work") {
757 expect(entries[1].entry.detail).toBeUndefined();
758 expect(entries[1].entry.changedFiles).toEqual([fileItem.fileName]);
759 }
760 });
761​
762 it("resolves attempt identity through V2 execution nodes", () => {
763 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
764 const threadId = ThreadId.make("thread-attempts");
765 const runId = RunId.make("run-steered");
766 const supersededRootNodeId = NodeId.make("node-attempt-1-root");
767 const supersededChildNodeId = NodeId.make("node-attempt-1-child");
768 const activeRootNodeId = NodeId.make("node-attempt-2-root");
769 const supersededAttemptId = RunAttemptId.make("attempt-1");
770 const activeAttemptId = RunAttemptId.make("attempt-2");
771 const providerInstanceId = ProviderInstanceId.make("codex-default");
772 const providerThreadId = ProviderThreadId.make("provider-thread-attempts");
773 const attempts: ReadonlyArray<OrchestrationV2RunAttempt> = [
774 {
775 id: supersededAttemptId,
776 runId,
777 attemptOrdinal: 1,
778 rootNodeId: supersededRootNodeId,
779 providerInstanceId,
780 providerThreadId,
781 providerTurnId: null,
782 reason: "initial",
783 status: "superseded",
784 startedAt: now,
785 completedAt: now,
786 },
787 {
788 id: activeAttemptId,
789 runId,
790 attemptOrdinal: 2,
791 rootNodeId: activeRootNodeId,
792 providerInstanceId,
793 providerThreadId,
794 providerTurnId: null,
795 reason: "steering_restart",
796 status: "running",
797 startedAt: now,
798 completedAt: null,
799 },
800 ];
801 const node = (
802 id: OrchestrationV2ExecutionNode["id"],
803 rootNodeId: OrchestrationV2ExecutionNode["rootNodeId"],
804 parentNodeId: OrchestrationV2ExecutionNode["parentNodeId"],
805 ): OrchestrationV2ExecutionNode => ({
806 id,
807 threadId,
808 runId,
809 parentNodeId,
810 rootNodeId,
811 kind: id === rootNodeId ? "root_turn" : "assistant_message",
812 status: "running",
813 countsForRun: true,
814 providerThreadId,
815 providerTurnId: null,
816 nativeItemRef: null,
817 runtimeRequestId: null,
818 checkpointScopeId: null,
819 startedAt: now,
820 completedAt: null,
821 });
822 const nodes = [
823 node(supersededRootNodeId, supersededRootNodeId, null),
824 node(supersededChildNodeId, supersededRootNodeId, supersededRootNodeId),
825 node(activeRootNodeId, activeRootNodeId, null),
826 ];
827 const assistantItem = (
828 id: string,
829 messageId: string,
830 nodeId: NodeId,
831 text: string,
832 ordinal: number,
833 ): OrchestrationV2TurnItem => ({
834 id: TurnItemId.make(id),
835 threadId,
836 runId,
837 nodeId,
838 providerThreadId,
839 providerTurnId: null,
840 nativeItemRef: null,
841 parentItemId: null,
842 ordinal,
843 status: "running",
844 title: null,
845 startedAt: now,
846 completedAt: null,
847 updatedAt: now,
848 type: "assistant_message",
849 messageId: MessageId.make(messageId),
850 text,
851 streaming: true,
852 });
853 const items = [
854 assistantItem(
855 "item-superseded",
856 "message-superseded",
857 supersededChildNodeId,
858 "Partial old response",
859 0,
860 ),
861 assistantItem("item-active", "message-active", activeRootNodeId, "Current response", 1),
862 ];
863 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = items.map(
864 (item, position) => ({
865 position,
866 visibility: "local",
867 sourceThreadId: threadId,
868 sourceItemId: item.id,
869 item,
870 }),
871 );
872​
873 const entries = deriveTimelineEntriesFromVisibleTurnItems({
874 visibleTurnItems,
875 optimisticMessages: [],
876 attempts,
877 nodes,
878 });
879​
880 expect(entries.map((entry) => [entry.attempt?.id, entry.attempt?.status])).toEqual([
881 [supersededAttemptId, "superseded"],
882 [activeAttemptId, "running"],
883 ]);
884 const input = { visibleTurnItems, optimisticMessages: [], attempts, nodes };
885 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
886 const nextInput = {
887 ...input,
888 attempts: attempts.map((attempt) =>
889 attempt.id === activeAttemptId ? { ...attempt, status: "superseded" as const } : attempt,
890 ),
891 };
892 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
893 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
894 expect(next.entries.at(-1)?.attempt?.status).toBe("superseded");
895 expect(previous.entries.at(-1)?.attempt?.status).toBe("running");
896 });
897});
898​
899describe("native provider presentation in the v2 timeline", () => {
900 const timestamp = DateTime.makeUnsafe("2026-09-04T12:00:00.000Z");
901 const base = {
902 id: TurnItemId.make("native-item"),
903 threadId: ThreadId.make("native-thread"),
904 runId: RunId.make("native-run"),
905 nodeId: null,
906 providerThreadId: null,
907 providerTurnId: null,
908 nativeItemRef: null,
909 parentItemId: null,
910 ordinal: 0,
911 status: "completed" as const,
912 title: null,
913 startedAt: timestamp,
914 completedAt: timestamp,
915 updatedAt: timestamp,
916 };
917 const visible = (item: OrchestrationV2TurnItem): OrchestrationV2ProjectedTurnItem => ({
918 position: 0,
919 visibility: "local",
920 sourceThreadId: item.threadId,
921 sourceItemId: item.id,
922 item,
923 });
924​
925 it.each([
926 { outputIndicatesFailure: true },
927 { exitCode: 2 },
928 { output: "bash: foo: command not found" },
929 ])("keeps completed command failures visible without exposing output: %j", (result) => {
930 const item = {
931 ...base,
932 type: "command_execution" as const,
933 input: "foo",
934 ...result,
935 } satisfies OrchestrationV2TurnItem;
936 const [entry] = deriveTimelineEntriesFromVisibleTurnItems({
937 visibleTurnItems: [visible(item)],
938 optimisticMessages: [],
939 });
940 if (entry?.kind !== "work") throw new Error("Expected a command work entry");
941​
942 expect(entry.entry.detail).toBeUndefined();
943 expect(entry.entry.command).toBe("foo");
944 expect(entry.entry.toolLifecycleStatus).toBe("completed");
945 expect(workEntryDisplayIndicatesToolFailure(entry.entry)).toBe(true);
946 expect(workEntryIndicatesToolSuccess(entry.entry)).toBe(false);
947 });
948​
949 it("retains Claude Read image previews without tool output", () => {
950 const item = {
951 ...base,
952 type: "dynamic_tool" as const,
953 toolName: "Read",
954 input: { file_path: "/workspace/reference.png" },
955 viewedImagePath: "/workspace/reference.png",
956 } satisfies OrchestrationV2TurnItem;
957 const [entry] = deriveTimelineEntriesFromVisibleTurnItems({
958 visibleTurnItems: [visible(item)],
959 optimisticMessages: [],
960 });
961 expect(entry).toMatchObject({
962 kind: "work",
963 entry: { viewedImagePath: "/workspace/reference.png" },
964 });
965 });
966​
967 it("keeps browser identity and its source on a completed tool row", () => {
968 const item = {
969 ...base,
970 type: "dynamic_tool" as const,
971 toolName: "browser_snapshot",
972 input: {},
973 output: {},
974 toolSurface: "browser" as const,
975 toolIcon: { _tag: "website" as const, pageUrl: "https://example.com/checkout" },
976 toolSource: { key: "browser-use:browser", name: "Chrome", kind: "browser" as const },
977 } satisfies OrchestrationV2TurnItem;
978 const [entry] = deriveTimelineEntriesFromVisibleTurnItems({
979 visibleTurnItems: [visible(item)],
980 optimisticMessages: [],
981 });
982 expect(entry).toMatchObject({
983 kind: "work",
984 entry: {
985 toolSurface: "browser",
986 toolIcon: item.toolIcon,
987 toolSource: item.toolSource,
988 toolLifecycleStatus: "completed",
989 },
990 });
991 });
992​
993 it("shows provider-returned images on an assistant message using the environment asset URL", () => {
994 const attachment = {
995 type: "image" as const,
996 id: "assistant-image",
997 name: "screenshot.png",
998 mimeType: "image/png",
999 sizeBytes: 512,
1000 };
1001 const item = {
1002 ...base,
1003 type: "assistant_message" as const,
1004 messageId: MessageId.make("assistant-native-image"),
1005 text: "Here is the screenshot.",
1006 streaming: false,
1007 attachments: [attachment],
1008 } satisfies OrchestrationV2TurnItem;
1009 const [entry] = deriveTimelineEntriesFromVisibleTurnItems({
1010 visibleTurnItems: [visible(item)],
1011 optimisticMessages: [],
1012 attachmentUrlById: new Map([[attachment.id, "https://remote.example/api/assets/screenshot"]]),
1013 });
1014 expect(entry).toMatchObject({
1015 kind: "message",
1016 message: {
1017 role: "assistant",
1018 attachments: [
1019 { ...attachment, previewUrl: "https://remote.example/api/assets/screenshot" },
1020 ],
1021 },
1022 });
1023 });
1024​
1025 it("keeps an idle provider task neutral without a completion mark", () => {
1026 const entry = {
1027 id: "idle-tool",
1028 createdAt: DateTime.formatIso(timestamp),
1029 label: "Waiting for the next task",
1030 tone: "tool" as const,
1031 toolLifecycleStatus: "idle" as const,
1032 };
1033 expect(workEntryIndicatesToolSuccess(entry)).toBe(false);
1034 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);
1035 });
1036});
1037​
1038describe("work-log failure policy (#7999/#7893)", () => {
1039 const toolEntry = (overrides: Record<string, unknown>) =>
1040 ({
1041 id: "entry-1",
1042 createdAt: "2026-08-27T00:00:00.000Z",
1043 label: "Ran command",
1044 tone: "tool",
1045 ...overrides,
1046 }) as never;
1047​
1048 it("flags success-status rows whose output text reports a failure", () => {
1049 expect(
1050 workEntryIndicatesToolFailure(
1051 toolEntry({ toolLifecycleStatus: "completed", detail: "bash: foo: command not found" }),
1052 ),
1053 ).toBe(true);
1054 expect(
1055 workEntryIndicatesToolFailure(
1056 toolEntry({ toolLifecycleStatus: "completed", detail: "<exited with exit code 2>" }),
1057 ),
1058 ).toBe(true);
1059 });
1060​
1061 it("keeps the rendered row calm when only the command mentions failure text", () => {
1062 const entry = toolEntry({
1063 toolLifecycleStatus: "completed",
1064 command: "rg 'command not found' src/",
1065 });
1066 expect(workEntryIndicatesToolFailure(entry)).toBe(true);
1067 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);
1068 });
1069​
1070 it("does not call a clean completed row failed", () => {
1071 const entry = toolEntry({ toolLifecycleStatus: "completed", detail: "3 files changed" });
1072 expect(workEntryIndicatesToolFailure(entry)).toBe(false);
1073 expect(workEntryIndicatesToolSuccess(entry)).toBe(true);
1074 });
1075​
1076 it("recovered failure text no longer counts as success", () => {
1077 const entry = toolEntry({ toolLifecycleStatus: "completed", detail: "ENOENT: no such file" });
1078 expect(workEntryIndicatesToolSuccess(entry)).toBe(false);
1079 });
1080});
1081​
1082describe("incremental v2 timeline entries", () => {
1083 it("retains history and attachment previews through decoded streaming updates", () => {
1084 const fixture = makeStreamingTimelineFixture("Partial");
1085 const attachment = {
1086 type: "image" as const,
1087 id: "stream-image",
1088 name: "image.png",
1089 mimeType: "image/png",
1090 sizeBytes: 42,
1091 };
1092 const visibleTurnItems = fixture.visibleTurnItems.map((row) =>
1093 row.item.type === "assistant_message"
1094 ? { ...row, item: { ...row.item, attachments: [attachment] } }
1095 : row,
1096 );
1097 const input = {
1098 visibleTurnItems,
1099 optimisticMessages: [],
1100 attachmentUrlById: new Map([[attachment.id, "https://server.test/image"]]),
1101 };
1102 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1103 Object.freeze(previous.entries);
1104 for (const entry of previous.entries) Object.freeze(entry);
1105 const last = visibleTurnItems.at(-1)!;
1106 if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
1107 const nextItem = {
1108 ...last,
1109 item: {
1110 ...last.item,
1111 text: "Next token",
1112 attachments: [{ ...attachment }],
1113 startedAt: DateTime.makeUnsafe(fixture.time(7)),
1114 updatedAt: DateTime.makeUnsafe(fixture.time(8)),
1115 },
1116 };
1117 const nextInput = {
1118 ...input,
1119 visibleTurnItems: [...visibleTurnItems.slice(0, -1), nextItem],
1120 attachmentUrlById: new Map(input.attachmentUrlById),
1121 };
1122 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1123 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1124 for (const [index, entry] of previous.entries.slice(0, -1).entries()) {
1125 expect(next.entries[index]).toBe(entry);
1127 const beforeMessage = previous.entries.at(-1)!;
1128 const nextMessage = next.entries.at(-1)!;
1129 if (beforeMessage.kind !== "message" || nextMessage.kind !== "message") {
1130 throw new Error("Expected assistant entries");
1132 expect(nextMessage.message.attachments).toBe(beforeMessage.message.attachments);
1133 expect(nextMessage.projectedItem).toBe(nextItem);
1134 expect(nextMessage.message.text).toBe("Next token");
1135 expect(beforeMessage.message.text).toBe("Partial");
1136​
1137 const renewedInput = {
1138 ...nextInput,
1139 attachmentUrlById: new Map([[attachment.id, "https://renewed.test/image"]]),
1140 };
1141 const renewed = deriveTimelineEntriesFromVisibleTurnItemsWithState(renewedInput, next);
1142 expect(renewed.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(renewedInput));
1143 expect(renewed.entries.at(-1)).toMatchObject({
1144 message: { attachments: [{ previewUrl: "https://renewed.test/image" }] },
1145 });
1146 expect(nextMessage.message.attachments?.[0]).toMatchObject({
1147 previewUrl: "https://server.test/image",
1148 });
1149 const restoredInput = { ...renewedInput, attachmentUrlById: new Map<string, string>() };
1150 const restored = deriveTimelineEntriesFromVisibleTurnItemsWithState(restoredInput, renewed);
1151 expect(restored.entries.at(-1)).toMatchObject({ message: { attachments: [attachment] } });
1152 const restoredMessage = restored.entries.at(-1)!;
1153 if (restoredMessage.kind !== "message") throw new Error("Expected assistant entry");
1154 expect(restoredMessage.message.attachments?.[0]).not.toHaveProperty("previewUrl");
1155 });
1156​
1157 it("appends committed items in canonical order even when their timestamps go backwards", () => {
1158 const fixture = makeStreamingTimelineFixture("Partial");
1159 const input = { visibleTurnItems: fixture.visibleTurnItems, optimisticMessages: [] };
1160 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1161 const last = fixture.visibleTurnItems.at(-1)!;
1162 const appended = {
1163 ...last,
1164 position: last.position + 1,
1165 sourceItemId: TurnItemId.make("late-item"),
1166 item: {
1167 ...last.item,
1168 id: TurnItemId.make("late-item"),
1169 messageId: MessageId.make("late-message"),
1170 startedAt: DateTime.makeUnsafe(fixture.time(0)),
1171 },
1172 };
1173 const nextInput = { ...input, visibleTurnItems: [...input.visibleTurnItems, appended] };
1174 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1175 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1176 expect(next.entries.at(-1)).toMatchObject({ id: "late-message" });
1177 for (const [index, entry] of previous.entries.entries())
1178 expect(next.entries[index]).toBe(entry);
1179 });
1180​
1181 it.each(["completion", "provenance", "ordering", "attachment", "run"] as const)(
1182 "rebuilds entries for a %s change instead of retaining stale v2 metadata",
1183 (change) => {
1184 const fixture = makeStreamingTimelineFixture("Partial");
1185 const input = { visibleTurnItems: fixture.visibleTurnItems, optimisticMessages: [] };
1186 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1187 const last = fixture.visibleTurnItems.at(-1)!;
1188 if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
1189 const changed =
1190 change === "provenance"
1191 ? { ...last, sourceThreadId: ThreadId.make("inherited-thread") }
1192 : {
1193 ...last,
1194 item:
1195 change === "completion"
1196 ? { ...last.item, streaming: false, status: "completed" as const }
1197 : change === "ordering"
1198 ? { ...last.item, startedAt: DateTime.makeUnsafe(fixture.time(0)) }
1199 : change === "run"
1200 ? { ...last.item, runId: fixture.historyRunId }
1201 : {
1202 ...last.item,
1203 attachments: [
1205 type: "image",
1206 id: "new-image",
1207 name: "new.png",
1208 mimeType: "image/png",
1209 sizeBytes: 42,
1210 },
1211 ],
1212 },
1213 };
1214 const nextInput = {
1215 ...input,
1216 visibleTurnItems: [...input.visibleTurnItems.slice(0, -1), changed],
1217 };
1218 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1219 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1220 expect(next.entries.at(-1)).not.toBe(previous.entries.at(-1));
1221 },
1222 );
1223​
1224 it("updates fallback timestamps when the provider has not supplied a message start time", () => {
1225 const fixture = makeStreamingTimelineFixture("Partial");
1226 const visibleTurnItems = fixture.visibleTurnItems.map((row) =>
1227 row.item.type === "assistant_message" && row.item.streaming
1228 ? { ...row, item: { ...row.item, startedAt: null } }
1229 : row,
1230 );
1231 const input = { visibleTurnItems, optimisticMessages: [] };
1232 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1233 const nextInput = {
1234 ...input,
1235 visibleTurnItems: visibleTurnItems.map((row) =>
1236 row.item.type === "assistant_message" && row.item.streaming
1237 ? {
1238 ...row,
1239 item: {
1240 ...row.item,
1241 text: "Next token",
1242 updatedAt: DateTime.makeUnsafe(fixture.time(8)),
1243 },
1245 : row,
1246 ),
1247 };
1248 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1249 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1250 expect(next.entries.at(-1)?.createdAt).toBe(fixture.time(8));
1251 });
1252​
1253 it("keeps unchanged message previews while tool output rebuilds the work log", () => {
1254 const fixture = makeStreamingTimelineFixture("Partial");
1255 const input = { visibleTurnItems: fixture.visibleTurnItems, optimisticMessages: [] };
1256 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1257 const nextInput = {
1258 ...input,
1259 visibleTurnItems: input.visibleTurnItems.map((row) =>
1260 row.item.type === "command_execution"
1261 ? { ...row, item: { ...row.item, output: "Additional output" } }
1262 : row,
1263 ),
1264 };
1265 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1266 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1267 for (const [index, entry] of previous.entries.entries()) {
1268 if (entry.kind === "message") expect(next.entries[index]).toBe(entry);
1270 });
1271​
1272 it("deduplicates optimistic sends when committed items arrive and retains anchored ordering", () => {
1273 const fixture = makeStreamingTimelineFixture();
1274 const input = {
1275 visibleTurnItems: fixture.visibleTurnItems.slice(0, 3),
1276 optimisticMessages: [
1278 id: MessageId.make("live-user"),
1279 runId: null,
1280 role: "user" as const,
1281 text: "Continue",
1282 streaming: false,
1283 createdAt: fixture.time(5),
1284 updatedAt: fixture.time(5),
1285 },
1286 ],
1287 anchoredMessages: [
1289 id: MessageId.make("feedback"),
1290 runId: null,
1291 role: "assistant" as const,
1292 text: "Feedback received",
1293 streaming: false,
1294 createdAt: fixture.time(4),
1295 updatedAt: fixture.time(4),
1296 },
1297 ],
1298 };
1299 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1300 const nextInput = { ...input, visibleTurnItems: fixture.visibleTurnItems };
1301 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1302 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1303 expect(next.entries.filter((entry) => entry.id === "live-user")).toHaveLength(1);
1304 expect(next.entries.map((entry) => entry.id)).toEqual([
1305 "history-user",
1306 "history-work",
1307 "history-assistant",
1308 "feedback",
1309 "live-user",
1310 "live-work",
1311 "live-assistant",
1312 ]);
1313 });
1314});
1315​
1316describe("image asset requests", () => {
1317 const image = {
1318 type: "image" as const,
1319 id: "image",
1320 name: "image.png",
1321 mimeType: "image/png",
1322 sizeBytes: 42,
1323 };
1324 const message = {
1325 id: MessageId.make("image-message"),
1326 role: "user" as const,
1327 text: "Inspect these images",
1328 runId: null,
1329 createdAt: "2026-09-04T00:00:00.000Z",
1330 updatedAt: "2026-09-04T00:00:00.000Z",
1331 streaming: false,
1332 attachments: [image],
1333 };
1334​
1335 it("requests the whole row's gallery and crops without signing local preview IDs", () => {
1336 const attachments = Object.freeze([
1337 image,
1338 { ...image, id: "second" },
1339 { ...image, id: "crop", name: "preview-annotation-1.png" },
1340 { ...image, id: "local", previewUrl: "blob:local" },
1341 { ...image, id: "inline", previewUrl: "data:image/png;base64,AA==" },
1342 { ...image, id: "provided", previewUrl: "https://preview.test/image" },
1343 { ...image, type: "file" as const, id: "file", mimeType: "application/pdf" },
1344 { ...image, type: "future", id: "unknown" },
1345 image,
1346 ]);
1347​
1348 expect(selectMessageImageResources(attachments)).toEqual([
1349 { _tag: "attachment", attachmentId: "image" },
1350 { _tag: "attachment", attachmentId: "second" },
1351 { _tag: "attachment", attachmentId: "crop" },
1352 { _tag: "attachment", attachmentId: "provided" },
1353 ]);
1354 });
1355​
1356 it("requests offscreen handoffs without signing the rest of the loaded history", () => {
1357 const history = {
1358 ...message,
1359 id: MessageId.make("history"),
1360 attachments: [{ ...image, id: "history-image" }],
1361 };
1362 const offscreen = {
1363 ...message,
1364 id: MessageId.make("offscreen"),
1365 attachments: [image, { ...image, id: "crop", name: "preview-annotation-1.png" }],
1366 };
1367 const empty = {
1368 ...message,
1369 id: MessageId.make("empty"),
1370 attachments: [{ ...image, id: "empty" }],
1371 };
1372 const assistant = {
1373 ...message,
1374 id: MessageId.make("assistant"),
1375 role: "assistant" as const,
1376 attachments: [{ ...image, id: "assistant-image" }],
1377 };
1378 expect(
1379 selectHandoffImageResources([history, message, offscreen, empty, assistant], {
1380 [message.id]: ["blob:message"],
1381 [offscreen.id]: ["blob:offscreen", "blob:crop"],
1382 [empty.id]: [],
1383 [assistant.id]: ["blob:unused"],
1384 }),
1385 ).toEqual([
1386 { _tag: "attachment", attachmentId: "image" },
1387 { _tag: "attachment", attachmentId: "crop" },
1388 ]);
1389 });
1390​
1391 it("does not scan history when no handoff is pending", () => {
1392 let reads = 0;
1393 const messages = new Proxy([message], {
1394 get(target, property, receiver) {
1395 if (property === "0") reads += 1;
1396 return Reflect.get(target, property, receiver);
1397 },
1398 });
1399 const empty = selectHandoffImageResources(messages, {});
1400 expect(reads).toBe(0);
1401 expect(empty).toHaveLength(0);
1402 expect(selectHandoffImageResources(undefined, { missing: ["blob:missing"] })).toBe(empty);
1403 expect(selectMessageImageResources(undefined)).toBe(empty);
1404 });
1405​
1406 it("hands signed URLs to a mounted row only after the local preview is released", () => {
1407 const server = createMessageAttachmentPreviewProjector();
1408 const handoff = createMessageAttachmentPreviewProjector();
1409 const row = createMessageAttachmentPreviewProjector();
1410 const pending = handoff(
1411 server(message, () => undefined),
1412 () => "blob:pending",
1413 );
1414 expect(selectMessageImageResources(pending.attachments)).toEqual([]);
1415 expect(selectHandoffImageResources([message], { [message.id]: ["blob:pending"] })).toEqual([
1416 { _tag: "attachment", attachmentId: image.id },
1417 ]);
1418​
1419 const ready = server(message, () => "https://server.test/image");
1420 expect(selectMessageImageResources(handoff(ready, () => "blob:pending").attachments)).toEqual(
1421 [],
1422 );
1423 const released = server(message, () => undefined);
1424 expect(selectMessageImageResources(released.attachments)).toEqual([
1425 { _tag: "attachment", attachmentId: image.id },
1426 ]);
1427 const displayed = row(released, () => "https://server.test/image");
1428 expect(displayed).toEqual(ready);
1429 expect(pending.attachments?.[0]).toMatchObject({ previewUrl: "blob:pending" });
1430 expect(row(released, () => "https://server.test/renewed").attachments?.[0]).toMatchObject({
1431 previewUrl: "https://server.test/renewed",
1432 });
1433 expect(displayed.attachments?.[0]).toMatchObject({ previewUrl: "https://server.test/image" });
1434 expect(row(released, () => undefined)).toBe(message);
1435 });
1436});
1437​
1438it("renders automatic completion as a work entry instead of a user bubble", () => {
1439 const now = DateTime.makeUnsafe("2026-09-09T00:00:00Z");
1440 const item = {
1441 id: TurnItemId.make("wake-item"),
1442 threadId: ThreadId.make("parent"),
1443 runId: RunId.make("wake-run"),
1444 nodeId: null,
1445 providerThreadId: null,
1446 providerTurnId: null,
1447 nativeItemRef: null,
1448 parentItemId: null,
1449 ordinal: 0,
1450 status: "completed" as const,
1451 title: null,
1452 startedAt: now,
1453 completedAt: now,
1454 updatedAt: now,
1455 type: "notification" as const,
1456 source: { kind: "delegated_task" as const, taskIds: [NodeId.make("task-1")] },
1457 outcome: "unknown" as const,
1458 summary: "Delegated task finished",
1459 };
1460 const row = {
1461 item,
1462 position: 0,
1463 visibility: "local" as const,
1464 sourceThreadId: item.threadId,
1465 sourceItemId: item.id,
1466 };
1467 const entries = deriveTimelineEntriesFromVisibleTurnItems({
1468 optimisticMessages: [],
1469 visibleTurnItems: [row],
1470 });
1471 expect(entries).toHaveLength(1);
1472 expect(entries[0]).toMatchObject({
1473 kind: "work",
1474 entry: { label: "Delegated task finished", tone: "info", projectedItem: row },
1475 });
1476 expect(
1477 deriveTimelineEntriesFromVisibleTurnItems({
1478 optimisticMessages: [],
1479 visibleTurnItems: [
1481 ...row,
1482 item: {
1483 ...item,
1484 type: "user_message",
1485 messageId: MessageId.make("wake-message"),
1486 createdBy: "agent" as const,
1487 creationSource: "server" as const,
1488 inputIntent: "turn_start" as const,
1489 attachments: [],
1490 text: "Delegated task node:task-1 reached a terminal state. Use task_status with taskId node:task-1 to read the result.",
1491 },
1492 },
1493 ],
1494 })[0]?.kind,
1495 ).toBe("message");
1496});