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

session-logic.test.ts

1,411 lines47.3 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("keeps failed tool items tool-toned so groups still summarize", () => {
447 const failedCommand = {
448 id: TurnItemId.make("item-failed-command"),
449 threadId: ThreadId.make("thread-1"),
450 runId: RunId.make("run-1"),
451 nodeId: null,
452 providerThreadId: null,
453 providerTurnId: null,
454 nativeItemRef: null,
455 parentItemId: null,
456 ordinal: 0,
457 status: "failed" as const,
458 title: null,
459 startedAt: null,
460 completedAt: null,
461 updatedAt: DateTime.nowUnsafe(),
462 type: "command_execution" as const,
463 input: "ssh host true",
464 output: "connection refused",
465 exitCode: 255,
466 } satisfies OrchestrationV2TurnItem;
467 const entries = deriveTimelineEntriesFromVisibleTurnItems({
468 visibleTurnItems: [
469 {
470 position: 0,
471 visibility: "local" as const,
472 sourceThreadId: ThreadId.make("thread-1"),
473 sourceItemId: failedCommand.id,
474 item: failedCommand,
475 } as never,
476 ],
477 optimisticMessages: [],
478 });
479 const entry = entries[0];
480 expect(entry?.kind).toBe("work");
481 if (entry?.kind === "work") {
482 // An exit-code failure is still an ordinary tool row: the failed
483 // lifecycle status carries the marker, and an "error" tone here would
484 // knock the whole group out of the "Ran N commands" summary.
485 expect(entry.entry.tone).toBe("tool");
486 expect(entry.entry.toolLifecycleStatus).toBe("failed");
487 }
488 });
489​
490 it("waits for a dispatched turn item before adding queued input to the timeline", () => {
491 const projection = makeThreadProjectionFixture();
492 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
493 const runId = RunId.make("run-dispatched-queued");
494 const messageId = MessageId.make("message-dispatched-queued");
495 const optimisticMessage = {
496 id: messageId,
497 role: "user" as const,
498 text: "Queued input",
499 runId: null,
500 inputIntent: "queued_turn" as const,
501 streaming: false,
502 createdAt: DateTime.formatIso(now),
503 updatedAt: DateTime.formatIso(now),
504 };
505​
506 expect(
507 deriveTimelineEntriesFromVisibleTurnItems({
508 visibleTurnItems: [],
509 optimisticMessages: [optimisticMessage],
510 }),
511 ).toEqual([]);
512​
513 const dispatchedItem = {
514 id: TurnItemId.make("item-dispatched-queued"),
515 threadId: projection.thread.id,
516 runId,
517 nodeId: null,
518 providerThreadId: null,
519 providerTurnId: null,
520 nativeItemRef: null,
521 parentItemId: null,
522 ordinal: 200,
523 status: "completed" as const,
524 title: null,
525 startedAt: now,
526 completedAt: now,
527 updatedAt: now,
528 type: "user_message" as const,
529 messageId,
530 inputIntent: "turn_start" as const,
531 text: "Queued input",
532 attachments: [],
533 createdBy: "agent" as const,
534 creationSource: "mcp" as const,
535 scheduledTaskId: ScheduledTaskId.make("task-queued"),
536 } satisfies OrchestrationV2TurnItem;
537 const promotedEntries = deriveTimelineEntriesFromVisibleTurnItems({
538 visibleTurnItems: [
539 {
540 position: 0,
541 visibility: "local",
542 sourceThreadId: projection.thread.id,
543 sourceItemId: dispatchedItem.id,
544 item: dispatchedItem,
545 },
546 ],
547 optimisticMessages: [optimisticMessage],
548 });
549 expect(promotedEntries.map((entry) => entry.id)).toEqual([messageId]);
550 expect(promotedEntries[0]?.kind).toBe("message");
551 if (promotedEntries[0]?.kind === "message") {
552 expect(promotedEntries[0].message.inputIntent).toBe("turn_start");
553 expect(promotedEntries[0].message.scheduledTaskId).toBe("task-queued");
554 }
555 });
556​
557 it("anchors feedback before later committed turns without reordering canonical history", () => {
558 const threadId = ThreadId.make("thread-feedback-order");
559 const messageItem = (input: {
560 readonly id: string;
561 readonly role: "user" | "assistant";
562 readonly createdAt: string;
563 readonly ordinal: number;
564 }): OrchestrationV2TurnItem => {
565 const timestamp = DateTime.makeUnsafe(input.createdAt);
566 const common = {
567 id: TurnItemId.make(`item-${input.id}`),
568 threadId,
569 runId: RunId.make(`run-${input.ordinal}`),
570 nodeId: null,
571 providerThreadId: null,
572 providerTurnId: null,
573 nativeItemRef: null,
574 parentItemId: null,
575 ordinal: input.ordinal,
576 status: "completed" as const,
577 title: null,
578 startedAt: timestamp,
579 completedAt: timestamp,
580 updatedAt: timestamp,
581 messageId: MessageId.make(input.id),
582 text: input.id,
583 };
584 return input.role === "user"
585 ? {
586 ...common,
587 type: "user_message",
588 inputIntent: "turn_start",
589 attachments: [],
590 createdBy: "user",
591 creationSource: "web",
592 }
593 : { ...common, type: "assistant_message", streaming: false };
594 };
595 const canonicalItems = [
596 messageItem({ id: "old-user", role: "user", createdAt: "2026-08-29T00:00:01Z", ordinal: 1 }),
597 messageItem({
598 id: "old-assistant",
599 role: "assistant",
600 createdAt: "2026-08-29T00:00:02Z",
601 ordinal: 2,
602 }),
603 messageItem({
604 id: "later-user",
605 role: "user",
606 createdAt: "2026-08-29T00:00:05Z",
607 ordinal: 3,
608 }),
609 messageItem({
610 id: "later-assistant",
611 role: "assistant",
612 createdAt: "2026-08-29T00:00:04Z",
613 ordinal: 4,
614 }),
615 ];
616 const visibleTurnItems = canonicalItems.map((item, position) => ({
617 position,
618 visibility: "local" as const,
619 sourceThreadId: threadId,
620 sourceItemId: item.id,
621 item,
622 }));
623 const feedback = (id: string, role: "user" | "assistant"): ChatMessage => ({
624 id: MessageId.make(id),
625 role,
626 text: id,
627 runId: null,
628 streaming: false,
629 createdAt: "2026-08-29T00:00:03Z",
630 updatedAt: "2026-08-29T00:00:03Z",
631 });
632 const entries = deriveTimelineEntriesFromVisibleTurnItems({
633 visibleTurnItems,
634 anchoredMessages: [
635 feedback("feedback-user", "user"),
636 feedback("feedback-assistant", "assistant"),
637 feedback("later-user", "user"),
638 ],
639 optimisticMessages: [
640 { ...feedback("optimistic-user", "user"), createdAt: "2026-08-29T00:00:00Z" },
641 ],
642 });
643​
644 expect(entries.map((entry) => entry.id)).toEqual([
645 "old-user",
646 "old-assistant",
647 "feedback-user",
648 "feedback-assistant",
649 "later-user",
650 "later-assistant",
651 "optimistic-user",
652 ]);
653 expect(
654 entries
655 .filter((entry) => entry.id.startsWith("feedback-"))
656 .every((entry) => entry.kind === "message" && entry.projectedItem === undefined),
657 ).toBe(true);
658 });
659​
660 it("uses projected plan status and file contents in timeline entries", () => {
661 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
662 const threadId = ThreadId.make("thread-timeline-artifacts");
663 const runId = RunId.make("run-timeline-artifacts");
664 const nodeId = NodeId.make("node-timeline-artifacts");
665 const planId = PlanId.make("plan-timeline-artifacts");
666 const base = {
667 threadId,
668 runId,
669 nodeId,
670 providerThreadId: null,
671 providerTurnId: null,
672 nativeItemRef: null,
673 parentItemId: null,
674 status: "completed" as const,
675 title: null,
676 startedAt: now,
677 completedAt: now,
678 updatedAt: now,
679 };
680 const planItem = {
681 ...base,
682 id: TurnItemId.make("item-proposed-plan"),
683 ordinal: 0,
684 type: "proposed_plan" as const,
685 planId,
686 markdown: "Finished plan",
687 streaming: false,
688 } satisfies OrchestrationV2TurnItem;
689 const fileItem = {
690 ...base,
691 id: TurnItemId.make("item-file-change"),
692 ordinal: 1,
693 type: "file_change" as const,
694 fileName: "src/example.ts",
695 newStr: "export const answer = 42;\n",
696 } satisfies OrchestrationV2TurnItem;
697 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
698 planItem,
699 fileItem,
700 ].map((item, position) => ({
701 position,
702 visibility: "local",
703 sourceThreadId: threadId,
704 sourceItemId: item.id,
705 item,
706 }));
707​
708 const entries = deriveTimelineEntriesFromVisibleTurnItems({
709 visibleTurnItems,
710 optimisticMessages: [],
711 plans: [
712 {
713 id: planId,
714 threadId,
715 runId,
716 nodeId,
717 kind: "proposed_plan",
718 markdown: "",
719 status: "completed",
720 detailInTurnItem: true,
721 },
722 ],
723 });
724​
725 expect(entries[0]?.kind).toBe("proposed-plan");
726 if (entries[0]?.kind === "proposed-plan") {
727 expect(entries[0].proposedPlan.status).toBe("completed");
728 expect(entries[0].proposedPlan.planMarkdown).toBe("Finished plan");
729 }
730 expect(entries[1]?.kind).toBe("work");
731 if (entries[1]?.kind === "work") {
732 expect(entries[1].entry.detail).toBeUndefined();
733 expect(entries[1].entry.changedFiles).toEqual([fileItem.fileName]);
734 }
735 });
736​
737 it("resolves attempt identity through V2 execution nodes", () => {
738 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
739 const threadId = ThreadId.make("thread-attempts");
740 const runId = RunId.make("run-steered");
741 const supersededRootNodeId = NodeId.make("node-attempt-1-root");
742 const supersededChildNodeId = NodeId.make("node-attempt-1-child");
743 const activeRootNodeId = NodeId.make("node-attempt-2-root");
744 const supersededAttemptId = RunAttemptId.make("attempt-1");
745 const activeAttemptId = RunAttemptId.make("attempt-2");
746 const providerInstanceId = ProviderInstanceId.make("codex-default");
747 const providerThreadId = ProviderThreadId.make("provider-thread-attempts");
748 const attempts: ReadonlyArray<OrchestrationV2RunAttempt> = [
749 {
750 id: supersededAttemptId,
751 runId,
752 attemptOrdinal: 1,
753 rootNodeId: supersededRootNodeId,
754 providerInstanceId,
755 providerThreadId,
756 providerTurnId: null,
757 reason: "initial",
758 status: "superseded",
759 startedAt: now,
760 completedAt: now,
761 },
762 {
763 id: activeAttemptId,
764 runId,
765 attemptOrdinal: 2,
766 rootNodeId: activeRootNodeId,
767 providerInstanceId,
768 providerThreadId,
769 providerTurnId: null,
770 reason: "steering_restart",
771 status: "running",
772 startedAt: now,
773 completedAt: null,
774 },
775 ];
776 const node = (
777 id: OrchestrationV2ExecutionNode["id"],
778 rootNodeId: OrchestrationV2ExecutionNode["rootNodeId"],
779 parentNodeId: OrchestrationV2ExecutionNode["parentNodeId"],
780 ): OrchestrationV2ExecutionNode => ({
781 id,
782 threadId,
783 runId,
784 parentNodeId,
785 rootNodeId,
786 kind: id === rootNodeId ? "root_turn" : "assistant_message",
787 status: "running",
788 countsForRun: true,
789 providerThreadId,
790 providerTurnId: null,
791 nativeItemRef: null,
792 runtimeRequestId: null,
793 checkpointScopeId: null,
794 startedAt: now,
795 completedAt: null,
796 });
797 const nodes = [
798 node(supersededRootNodeId, supersededRootNodeId, null),
799 node(supersededChildNodeId, supersededRootNodeId, supersededRootNodeId),
800 node(activeRootNodeId, activeRootNodeId, null),
801 ];
802 const assistantItem = (
803 id: string,
804 messageId: string,
805 nodeId: NodeId,
806 text: string,
807 ordinal: number,
808 ): OrchestrationV2TurnItem => ({
809 id: TurnItemId.make(id),
810 threadId,
811 runId,
812 nodeId,
813 providerThreadId,
814 providerTurnId: null,
815 nativeItemRef: null,
816 parentItemId: null,
817 ordinal,
818 status: "running",
819 title: null,
820 startedAt: now,
821 completedAt: null,
822 updatedAt: now,
823 type: "assistant_message",
824 messageId: MessageId.make(messageId),
825 text,
826 streaming: true,
827 });
828 const items = [
829 assistantItem(
830 "item-superseded",
831 "message-superseded",
832 supersededChildNodeId,
833 "Partial old response",
834 0,
835 ),
836 assistantItem("item-active", "message-active", activeRootNodeId, "Current response", 1),
837 ];
838 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = items.map(
839 (item, position) => ({
840 position,
841 visibility: "local",
842 sourceThreadId: threadId,
843 sourceItemId: item.id,
844 item,
845 }),
846 );
847​
848 const entries = deriveTimelineEntriesFromVisibleTurnItems({
849 visibleTurnItems,
850 optimisticMessages: [],
851 attempts,
852 nodes,
853 });
854​
855 expect(entries.map((entry) => [entry.attempt?.id, entry.attempt?.status])).toEqual([
856 [supersededAttemptId, "superseded"],
857 [activeAttemptId, "running"],
858 ]);
859 const input = { visibleTurnItems, optimisticMessages: [], attempts, nodes };
860 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
861 const nextInput = {
862 ...input,
863 attempts: attempts.map((attempt) =>
864 attempt.id === activeAttemptId ? { ...attempt, status: "superseded" as const } : attempt,
865 ),
866 };
867 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
868 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
869 expect(next.entries.at(-1)?.attempt?.status).toBe("superseded");
870 expect(previous.entries.at(-1)?.attempt?.status).toBe("running");
871 });
872});
873​
874describe("native provider presentation in the v2 timeline", () => {
875 const timestamp = DateTime.makeUnsafe("2026-09-04T12:00:00.000Z");
876 const base = {
877 id: TurnItemId.make("native-item"),
878 threadId: ThreadId.make("native-thread"),
879 runId: RunId.make("native-run"),
880 nodeId: null,
881 providerThreadId: null,
882 providerTurnId: null,
883 nativeItemRef: null,
884 parentItemId: null,
885 ordinal: 0,
886 status: "completed" as const,
887 title: null,
888 startedAt: timestamp,
889 completedAt: timestamp,
890 updatedAt: timestamp,
891 };
892 const visible = (item: OrchestrationV2TurnItem): OrchestrationV2ProjectedTurnItem => ({
893 position: 0,
894 visibility: "local",
895 sourceThreadId: item.threadId,
896 sourceItemId: item.id,
897 item,
898 });
899​
900 it.each([
901 { outputIndicatesFailure: true },
902 { exitCode: 2 },
903 { output: "bash: foo: command not found" },
904 ])("keeps completed command failures visible without exposing output: %j", (result) => {
905 const item = {
906 ...base,
907 type: "command_execution" as const,
908 input: "foo",
909 ...result,
910 } satisfies OrchestrationV2TurnItem;
911 const [entry] = deriveTimelineEntriesFromVisibleTurnItems({
912 visibleTurnItems: [visible(item)],
913 optimisticMessages: [],
914 });
915 if (entry?.kind !== "work") throw new Error("Expected a command work entry");
916​
917 expect(entry.entry.detail).toBeUndefined();
918 expect(entry.entry.command).toBe("foo");
919 expect(entry.entry.toolLifecycleStatus).toBe("completed");
920 expect(workEntryDisplayIndicatesToolFailure(entry.entry)).toBe(true);
921 expect(workEntryIndicatesToolSuccess(entry.entry)).toBe(false);
922 });
923​
924 it("retains Claude Read image previews without tool output", () => {
925 const item = {
926 ...base,
927 type: "dynamic_tool" as const,
928 toolName: "Read",
929 input: { file_path: "/workspace/reference.png" },
930 viewedImagePath: "/workspace/reference.png",
931 } satisfies OrchestrationV2TurnItem;
932 const [entry] = deriveTimelineEntriesFromVisibleTurnItems({
933 visibleTurnItems: [visible(item)],
934 optimisticMessages: [],
935 });
936 expect(entry).toMatchObject({
937 kind: "work",
938 entry: { viewedImagePath: "/workspace/reference.png" },
939 });
940 });
941​
942 it("keeps browser identity and its source on a completed tool row", () => {
943 const item = {
944 ...base,
945 type: "dynamic_tool" as const,
946 toolName: "browser_snapshot",
947 input: {},
948 output: {},
949 toolSurface: "browser" as const,
950 toolIcon: { _tag: "website" as const, pageUrl: "https://example.com/checkout" },
951 toolSource: { key: "browser-use:browser", name: "Chrome", kind: "browser" as const },
952 } satisfies OrchestrationV2TurnItem;
953 const [entry] = deriveTimelineEntriesFromVisibleTurnItems({
954 visibleTurnItems: [visible(item)],
955 optimisticMessages: [],
956 });
957 expect(entry).toMatchObject({
958 kind: "work",
959 entry: {
960 toolSurface: "browser",
961 toolIcon: item.toolIcon,
962 toolSource: item.toolSource,
963 toolLifecycleStatus: "completed",
964 },
965 });
966 });
967​
968 it("shows provider-returned images on an assistant message using the environment asset URL", () => {
969 const attachment = {
970 type: "image" as const,
971 id: "assistant-image",
972 name: "screenshot.png",
973 mimeType: "image/png",
974 sizeBytes: 512,
975 };
976 const item = {
977 ...base,
978 type: "assistant_message" as const,
979 messageId: MessageId.make("assistant-native-image"),
980 text: "Here is the screenshot.",
981 streaming: false,
982 attachments: [attachment],
983 } satisfies OrchestrationV2TurnItem;
984 const [entry] = deriveTimelineEntriesFromVisibleTurnItems({
985 visibleTurnItems: [visible(item)],
986 optimisticMessages: [],
987 attachmentUrlById: new Map([[attachment.id, "https://remote.example/api/assets/screenshot"]]),
988 });
989 expect(entry).toMatchObject({
990 kind: "message",
991 message: {
992 role: "assistant",
993 attachments: [
994 { ...attachment, previewUrl: "https://remote.example/api/assets/screenshot" },
995 ],
996 },
997 });
998 });
999​
1000 it("keeps an idle provider task neutral without a completion mark", () => {
1001 const entry = {
1002 id: "idle-tool",
1003 createdAt: DateTime.formatIso(timestamp),
1004 label: "Waiting for the next task",
1005 tone: "tool" as const,
1006 toolLifecycleStatus: "idle" as const,
1007 };
1008 expect(workEntryIndicatesToolSuccess(entry)).toBe(false);
1009 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);
1010 });
1011});
1012​
1013describe("work-log failure policy (#7999/#7893)", () => {
1014 const toolEntry = (overrides: Record<string, unknown>) =>
1015 ({
1016 id: "entry-1",
1017 createdAt: "2026-08-27T00:00:00.000Z",
1018 label: "Ran command",
1019 tone: "tool",
1020 ...overrides,
1021 }) as never;
1022​
1023 it("flags success-status rows whose output text reports a failure", () => {
1024 expect(
1025 workEntryIndicatesToolFailure(
1026 toolEntry({ toolLifecycleStatus: "completed", detail: "bash: foo: command not found" }),
1027 ),
1028 ).toBe(true);
1029 expect(
1030 workEntryIndicatesToolFailure(
1031 toolEntry({ toolLifecycleStatus: "completed", detail: "<exited with exit code 2>" }),
1032 ),
1033 ).toBe(true);
1034 });
1035​
1036 it("keeps the rendered row calm when only the command mentions failure text", () => {
1037 const entry = toolEntry({
1038 toolLifecycleStatus: "completed",
1039 command: "rg 'command not found' src/",
1040 });
1041 expect(workEntryIndicatesToolFailure(entry)).toBe(true);
1042 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);
1043 });
1044​
1045 it("does not call a clean completed row failed", () => {
1046 const entry = toolEntry({ toolLifecycleStatus: "completed", detail: "3 files changed" });
1047 expect(workEntryIndicatesToolFailure(entry)).toBe(false);
1048 expect(workEntryIndicatesToolSuccess(entry)).toBe(true);
1049 });
1050​
1051 it("recovered failure text no longer counts as success", () => {
1052 const entry = toolEntry({ toolLifecycleStatus: "completed", detail: "ENOENT: no such file" });
1053 expect(workEntryIndicatesToolSuccess(entry)).toBe(false);
1054 });
1055});
1056​
1057describe("incremental v2 timeline entries", () => {
1058 it("retains history and attachment previews through decoded streaming updates", () => {
1059 const fixture = makeStreamingTimelineFixture("Partial");
1060 const attachment = {
1061 type: "image" as const,
1062 id: "stream-image",
1063 name: "image.png",
1064 mimeType: "image/png",
1065 sizeBytes: 42,
1066 };
1067 const visibleTurnItems = fixture.visibleTurnItems.map((row) =>
1068 row.item.type === "assistant_message"
1069 ? { ...row, item: { ...row.item, attachments: [attachment] } }
1070 : row,
1071 );
1072 const input = {
1073 visibleTurnItems,
1074 optimisticMessages: [],
1075 attachmentUrlById: new Map([[attachment.id, "https://server.test/image"]]),
1076 };
1077 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1078 Object.freeze(previous.entries);
1079 for (const entry of previous.entries) Object.freeze(entry);
1080 const last = visibleTurnItems.at(-1)!;
1081 if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
1082 const nextItem = {
1083 ...last,
1084 item: {
1085 ...last.item,
1086 text: "Next token",
1087 attachments: [{ ...attachment }],
1088 startedAt: DateTime.makeUnsafe(fixture.time(7)),
1089 updatedAt: DateTime.makeUnsafe(fixture.time(8)),
1090 },
1091 };
1092 const nextInput = {
1093 ...input,
1094 visibleTurnItems: [...visibleTurnItems.slice(0, -1), nextItem],
1095 attachmentUrlById: new Map(input.attachmentUrlById),
1096 };
1097 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1098 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1099 for (const [index, entry] of previous.entries.slice(0, -1).entries()) {
1100 expect(next.entries[index]).toBe(entry);
1102 const beforeMessage = previous.entries.at(-1)!;
1103 const nextMessage = next.entries.at(-1)!;
1104 if (beforeMessage.kind !== "message" || nextMessage.kind !== "message") {
1105 throw new Error("Expected assistant entries");
1107 expect(nextMessage.message.attachments).toBe(beforeMessage.message.attachments);
1108 expect(nextMessage.projectedItem).toBe(nextItem);
1109 expect(nextMessage.message.text).toBe("Next token");
1110 expect(beforeMessage.message.text).toBe("Partial");
1111​
1112 const renewedInput = {
1113 ...nextInput,
1114 attachmentUrlById: new Map([[attachment.id, "https://renewed.test/image"]]),
1115 };
1116 const renewed = deriveTimelineEntriesFromVisibleTurnItemsWithState(renewedInput, next);
1117 expect(renewed.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(renewedInput));
1118 expect(renewed.entries.at(-1)).toMatchObject({
1119 message: { attachments: [{ previewUrl: "https://renewed.test/image" }] },
1120 });
1121 expect(nextMessage.message.attachments?.[0]).toMatchObject({
1122 previewUrl: "https://server.test/image",
1123 });
1124 const restoredInput = { ...renewedInput, attachmentUrlById: new Map<string, string>() };
1125 const restored = deriveTimelineEntriesFromVisibleTurnItemsWithState(restoredInput, renewed);
1126 expect(restored.entries.at(-1)).toMatchObject({ message: { attachments: [attachment] } });
1127 const restoredMessage = restored.entries.at(-1)!;
1128 if (restoredMessage.kind !== "message") throw new Error("Expected assistant entry");
1129 expect(restoredMessage.message.attachments?.[0]).not.toHaveProperty("previewUrl");
1130 });
1131​
1132 it("appends committed items in canonical order even when their timestamps go backwards", () => {
1133 const fixture = makeStreamingTimelineFixture("Partial");
1134 const input = { visibleTurnItems: fixture.visibleTurnItems, optimisticMessages: [] };
1135 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1136 const last = fixture.visibleTurnItems.at(-1)!;
1137 const appended = {
1138 ...last,
1139 position: last.position + 1,
1140 sourceItemId: TurnItemId.make("late-item"),
1141 item: {
1142 ...last.item,
1143 id: TurnItemId.make("late-item"),
1144 messageId: MessageId.make("late-message"),
1145 startedAt: DateTime.makeUnsafe(fixture.time(0)),
1146 },
1147 };
1148 const nextInput = { ...input, visibleTurnItems: [...input.visibleTurnItems, appended] };
1149 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1150 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1151 expect(next.entries.at(-1)).toMatchObject({ id: "late-message" });
1152 for (const [index, entry] of previous.entries.entries())
1153 expect(next.entries[index]).toBe(entry);
1154 });
1155​
1156 it.each(["completion", "provenance", "ordering", "attachment", "run"] as const)(
1157 "rebuilds entries for a %s change instead of retaining stale v2 metadata",
1158 (change) => {
1159 const fixture = makeStreamingTimelineFixture("Partial");
1160 const input = { visibleTurnItems: fixture.visibleTurnItems, optimisticMessages: [] };
1161 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1162 const last = fixture.visibleTurnItems.at(-1)!;
1163 if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
1164 const changed =
1165 change === "provenance"
1166 ? { ...last, sourceThreadId: ThreadId.make("inherited-thread") }
1167 : {
1168 ...last,
1169 item:
1170 change === "completion"
1171 ? { ...last.item, streaming: false, status: "completed" as const }
1172 : change === "ordering"
1173 ? { ...last.item, startedAt: DateTime.makeUnsafe(fixture.time(0)) }
1174 : change === "run"
1175 ? { ...last.item, runId: fixture.historyRunId }
1176 : {
1177 ...last.item,
1178 attachments: [
1180 type: "image",
1181 id: "new-image",
1182 name: "new.png",
1183 mimeType: "image/png",
1184 sizeBytes: 42,
1185 },
1186 ],
1187 },
1188 };
1189 const nextInput = {
1190 ...input,
1191 visibleTurnItems: [...input.visibleTurnItems.slice(0, -1), changed],
1192 };
1193 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1194 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1195 expect(next.entries.at(-1)).not.toBe(previous.entries.at(-1));
1196 },
1197 );
1198​
1199 it("updates fallback timestamps when the provider has not supplied a message start time", () => {
1200 const fixture = makeStreamingTimelineFixture("Partial");
1201 const visibleTurnItems = fixture.visibleTurnItems.map((row) =>
1202 row.item.type === "assistant_message" && row.item.streaming
1203 ? { ...row, item: { ...row.item, startedAt: null } }
1204 : row,
1205 );
1206 const input = { visibleTurnItems, optimisticMessages: [] };
1207 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1208 const nextInput = {
1209 ...input,
1210 visibleTurnItems: visibleTurnItems.map((row) =>
1211 row.item.type === "assistant_message" && row.item.streaming
1212 ? {
1213 ...row,
1214 item: {
1215 ...row.item,
1216 text: "Next token",
1217 updatedAt: DateTime.makeUnsafe(fixture.time(8)),
1218 },
1220 : row,
1221 ),
1222 };
1223 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1224 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1225 expect(next.entries.at(-1)?.createdAt).toBe(fixture.time(8));
1226 });
1227​
1228 it("keeps unchanged message previews while tool output rebuilds the work log", () => {
1229 const fixture = makeStreamingTimelineFixture("Partial");
1230 const input = { visibleTurnItems: fixture.visibleTurnItems, optimisticMessages: [] };
1231 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1232 const nextInput = {
1233 ...input,
1234 visibleTurnItems: input.visibleTurnItems.map((row) =>
1235 row.item.type === "command_execution"
1236 ? { ...row, item: { ...row.item, output: "Additional output" } }
1237 : row,
1238 ),
1239 };
1240 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1241 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1242 for (const [index, entry] of previous.entries.entries()) {
1243 if (entry.kind === "message") expect(next.entries[index]).toBe(entry);
1245 });
1246​
1247 it("deduplicates optimistic sends when committed items arrive and retains anchored ordering", () => {
1248 const fixture = makeStreamingTimelineFixture();
1249 const input = {
1250 visibleTurnItems: fixture.visibleTurnItems.slice(0, 3),
1251 optimisticMessages: [
1253 id: MessageId.make("live-user"),
1254 runId: null,
1255 role: "user" as const,
1256 text: "Continue",
1257 streaming: false,
1258 createdAt: fixture.time(5),
1259 updatedAt: fixture.time(5),
1260 },
1261 ],
1262 anchoredMessages: [
1264 id: MessageId.make("feedback"),
1265 runId: null,
1266 role: "assistant" as const,
1267 text: "Feedback received",
1268 streaming: false,
1269 createdAt: fixture.time(4),
1270 updatedAt: fixture.time(4),
1271 },
1272 ],
1273 };
1274 const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState(input);
1275 const nextInput = { ...input, visibleTurnItems: fixture.visibleTurnItems };
1276 const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous);
1277 expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput));
1278 expect(next.entries.filter((entry) => entry.id === "live-user")).toHaveLength(1);
1279 expect(next.entries.map((entry) => entry.id)).toEqual([
1280 "history-user",
1281 "history-work",
1282 "history-assistant",
1283 "feedback",
1284 "live-user",
1285 "live-work",
1286 "live-assistant",
1287 ]);
1288 });
1289});
1290​
1291describe("image asset requests", () => {
1292 const image = {
1293 type: "image" as const,
1294 id: "image",
1295 name: "image.png",
1296 mimeType: "image/png",
1297 sizeBytes: 42,
1298 };
1299 const message = {
1300 id: MessageId.make("image-message"),
1301 role: "user" as const,
1302 text: "Inspect these images",
1303 runId: null,
1304 createdAt: "2026-09-04T00:00:00.000Z",
1305 updatedAt: "2026-09-04T00:00:00.000Z",
1306 streaming: false,
1307 attachments: [image],
1308 };
1309​
1310 it("requests the whole row's gallery and crops without signing local preview IDs", () => {
1311 const attachments = Object.freeze([
1312 image,
1313 { ...image, id: "second" },
1314 { ...image, id: "crop", name: "preview-annotation-1.png" },
1315 { ...image, id: "local", previewUrl: "blob:local" },
1316 { ...image, id: "inline", previewUrl: "data:image/png;base64,AA==" },
1317 { ...image, id: "provided", previewUrl: "https://preview.test/image" },
1318 { ...image, type: "file" as const, id: "file", mimeType: "application/pdf" },
1319 { ...image, type: "future", id: "unknown" },
1320 image,
1321 ]);
1322​
1323 expect(selectMessageImageResources(attachments)).toEqual([
1324 { _tag: "attachment", attachmentId: "image" },
1325 { _tag: "attachment", attachmentId: "second" },
1326 { _tag: "attachment", attachmentId: "crop" },
1327 { _tag: "attachment", attachmentId: "provided" },
1328 ]);
1329 });
1330​
1331 it("requests offscreen handoffs without signing the rest of the loaded history", () => {
1332 const history = {
1333 ...message,
1334 id: MessageId.make("history"),
1335 attachments: [{ ...image, id: "history-image" }],
1336 };
1337 const offscreen = {
1338 ...message,
1339 id: MessageId.make("offscreen"),
1340 attachments: [image, { ...image, id: "crop", name: "preview-annotation-1.png" }],
1341 };
1342 const empty = {
1343 ...message,
1344 id: MessageId.make("empty"),
1345 attachments: [{ ...image, id: "empty" }],
1346 };
1347 const assistant = {
1348 ...message,
1349 id: MessageId.make("assistant"),
1350 role: "assistant" as const,
1351 attachments: [{ ...image, id: "assistant-image" }],
1352 };
1353 expect(
1354 selectHandoffImageResources([history, message, offscreen, empty, assistant], {
1355 [message.id]: ["blob:message"],
1356 [offscreen.id]: ["blob:offscreen", "blob:crop"],
1357 [empty.id]: [],
1358 [assistant.id]: ["blob:unused"],
1359 }),
1360 ).toEqual([
1361 { _tag: "attachment", attachmentId: "image" },
1362 { _tag: "attachment", attachmentId: "crop" },
1363 ]);
1364 });
1365​
1366 it("does not scan history when no handoff is pending", () => {
1367 let reads = 0;
1368 const messages = new Proxy([message], {
1369 get(target, property, receiver) {
1370 if (property === "0") reads += 1;
1371 return Reflect.get(target, property, receiver);
1372 },
1373 });
1374 const empty = selectHandoffImageResources(messages, {});
1375 expect(reads).toBe(0);
1376 expect(empty).toHaveLength(0);
1377 expect(selectHandoffImageResources(undefined, { missing: ["blob:missing"] })).toBe(empty);
1378 expect(selectMessageImageResources(undefined)).toBe(empty);
1379 });
1380​
1381 it("hands signed URLs to a mounted row only after the local preview is released", () => {
1382 const server = createMessageAttachmentPreviewProjector();
1383 const handoff = createMessageAttachmentPreviewProjector();
1384 const row = createMessageAttachmentPreviewProjector();
1385 const pending = handoff(
1386 server(message, () => undefined),
1387 () => "blob:pending",
1388 );
1389 expect(selectMessageImageResources(pending.attachments)).toEqual([]);
1390 expect(selectHandoffImageResources([message], { [message.id]: ["blob:pending"] })).toEqual([
1391 { _tag: "attachment", attachmentId: image.id },
1392 ]);
1393​
1394 const ready = server(message, () => "https://server.test/image");
1395 expect(selectMessageImageResources(handoff(ready, () => "blob:pending").attachments)).toEqual(
1396 [],
1397 );
1398 const released = server(message, () => undefined);
1399 expect(selectMessageImageResources(released.attachments)).toEqual([
1400 { _tag: "attachment", attachmentId: image.id },
1401 ]);
1402 const displayed = row(released, () => "https://server.test/image");
1403 expect(displayed).toEqual(ready);
1404 expect(pending.attachments?.[0]).toMatchObject({ previewUrl: "blob:pending" });
1405 expect(row(released, () => "https://server.test/renewed").attachments?.[0]).toMatchObject({
1406 previewUrl: "https://server.test/renewed",
1407 });
1408 expect(displayed.attachments?.[0]).toMatchObject({ previewUrl: "https://server.test/image" });
1409 expect(row(released, () => undefined)).toBe(message);
1410 });
1411});