Open History to see the last commit
1import {
2 MessageId,
3 NodeId,
4 PlanId,
5 ProviderInstanceId,
6 ProviderDriverKind,
7 ProviderThreadId,
8 RunId,
9 RunAttemptId,
10 ThreadId,
11 TurnItemId,
12 type OrchestrationV2RunAttempt,
13 type OrchestrationV2ProjectedTurnItem,
14 type OrchestrationV2TurnItem,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import { describe, expect, it } from "vite-plus/test";
18
19import {
20 buildThreadFeed,
21 deriveThreadFeedPresentation,
22 threadFeedActivityIsVisible,
23 threadFeedRunIsUnsettled,
24 type ThreadFeedActivity,
25 type ThreadFeedEntry,
26 togglePendingUserInputOptionSelection,
27 setPendingUserInputCustomAnswer,
28 isPendingUserInputOptionSelected,
29 buildPendingUserInputAnswers,
30} from "./threadActivity";
31
32const threadId = ThreadId.make("thread-1");
33const sourceThreadId = ThreadId.make("thread-source");
34const runId = RunId.make("run-1");
35
36it("keeps historical plan detail accessible from its paged turn item", () => {
37 const item = {
38 ...base("historical-plan", "2026-08-29T00:00:00.000Z", 1),
39 type: "proposed_plan",
40 planId: "plan-historical",
41 markdown: "Full historical plan text",
42 streaming: false,
43 } as OrchestrationV2TurnItem;
44
45 const entries = buildThreadFeed([projected(item, 0)]);
46 const activity = entries.flatMap((entry) =>
47 entry.type === "activity-group" ? entry.activities : [],
48 )[0];
49 expect(activity?.detail).toBe("Full historical plan text");
50 expect(activity?.getFullDetail()).toContain("Full historical plan text");
51});
52
53function base(id: string, updatedAt: string, ordinal: number) {
54 const timestamp = DateTime.makeUnsafe(updatedAt);
55 return {
56 id: TurnItemId.make(id),
57 threadId,
58 runId,
59 nodeId: null,
60 providerThreadId: null,
61 providerTurnId: null,
62 nativeItemRef: null,
63 parentItemId: null,
64 ordinal,
65 status: "completed" as const,
66 title: null,
67 startedAt: timestamp,
68 completedAt: timestamp,
69 updatedAt: timestamp,
70 };
71}
72
73function projected(
74 item: OrchestrationV2TurnItem,
75 position: number,
76 visibility: OrchestrationV2ProjectedTurnItem["visibility"] = "local",
77): OrchestrationV2ProjectedTurnItem {
78 return {
79 position,
80 visibility,
81 sourceThreadId: visibility === "local" ? threadId : sourceThreadId,
82 sourceItemId: item.id,
83 item,
84 };
85}
86
87function userMessage(updatedAt = "2026-06-20T00:00:01.000Z") {
88 return {
89 ...base("item-user", updatedAt, 0),
90 type: "user_message" as const,
91 messageId: MessageId.make("message-user"),
92 createdBy: "user" as const,
93 creationSource: "mobile" as const,
94 inputIntent: "turn_start" as const,
95 text: "Run checks",
96 attachments: [],
97 };
98}
99
100function command(updatedAt = "2026-06-20T00:00:02.000Z") {
101 return {
102 ...base("item-command", updatedAt, 1),
103 type: "command_execution" as const,
104 input: "vp check",
105 output: "ok",
106 exitCode: 0,
107 };
108}
109
110function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") {
111 return {
112 ...base("item-assistant", updatedAt, 2),
113 type: "assistant_message" as const,
114 messageId: MessageId.make("message-assistant"),
115 text: "Done",
116 streaming: false,
117 };
118}
119
120describe("buildThreadFeed", () => {
121 it("adds local feedback messages to an otherwise server-authored feed", () => {
122 const feed = buildThreadFeed([], {
123 localMessages: [
124 {
125 id: MessageId.make("feedback-local"),
126 role: "assistant",
127 text: "Feedback sent to OpenAI.\n\nThread ID: `codex-thread-1`",
128 turnId: null,
129 streaming: false,
130 createdAt: "2026-08-29T00:00:00.000Z",
131 updatedAt: "2026-08-29T00:00:00.000Z",
132 },
133 ],
134 });
135
136 expect(feed).toHaveLength(1);
137 expect(feed[0]).toMatchObject({
138 type: "message",
139 message: {
140 id: "feedback-local",
141 role: "assistant",
142 text: expect.stringContaining("codex-thread-1"),
143 },
144 });
145 });
146
147 it("anchors feedback before later committed turns and appends true optimistic messages", () => {
148 const laterUser = {
149 ...userMessage("2026-08-29T00:00:05.000Z"),
150 id: TurnItemId.make("item-later-user"),
151 messageId: MessageId.make("message-later-user"),
152 ordinal: 2,
153 text: "Later user turn",
154 };
155 const laterAssistant = {
156 ...assistantMessage("2026-08-29T00:00:04.000Z"),
157 id: TurnItemId.make("item-later-assistant"),
158 messageId: MessageId.make("message-later-assistant"),
159 ordinal: 3,
160 text: "Later assistant turn",
161 };
162 const localMessage = (id: string, role: "user" | "assistant") => ({
163 id: MessageId.make(id),
164 role,
165 text: id,
166 turnId: null,
167 streaming: false,
168 createdAt: "2026-08-29T00:00:03.000Z",
169 updatedAt: "2026-08-29T00:00:03.000Z",
170 });
171 const feed = buildThreadFeed(
172 [
173 projected(userMessage("2026-08-29T00:00:01.000Z"), 0),
174 projected(laterUser, 1),
175 projected(laterAssistant, 2),
176 ],
177 {
178 anchoredMessages: [
179 localMessage("feedback-user", "user"),
180 localMessage("feedback-assistant", "assistant"),
181 localMessage("message-later-user", "user"),
182 ],
183 localMessages: [
184 {
185 ...localMessage("optimistic-user", "user"),
186 createdAt: "2026-08-29T00:00:00.000Z",
187 },
188 ],
189 },
190 );
191 const messages = feed.filter((entry) => entry.type === "message");
192
193 expect(messages.map((entry) => entry.id)).toEqual([
194 "message-user",
195 "feedback-user",
196 "feedback-assistant",
197 "message-later-user",
198 "message-later-assistant",
199 "optimistic-user",
200 ]);
201 expect(
202 messages
203 .filter((entry) => entry.id.startsWith("feedback-"))
204 .every((entry) => entry.message.projectedItem === undefined),
205 ).toBe(true);
206 });
207
208 it("keeps prominent activity visible while it is running", () => {
209 expect(
210 threadFeedActivityIsVisible({ prominent: true, status: "neutral", toolLike: true }),
211 ).toBe(true);
212 expect(
213 threadFeedActivityIsVisible({ prominent: false, status: "neutral", toolLike: true }),
214 ).toBe(false);
215 });
216
217 it("keeps provider notices visible outside completed work folds without failure styling", () => {
218 const message = "Safeguards flagged this message. Switched to Opus 4.8.";
219 const item = {
220 ...base("item-system-notice", "2026-06-20T00:00:02.000Z", 1),
221 type: "system_notice" as const,
222 message,
223 };
224 const feed = buildThreadFeed([projected(item, 0)]);
225 const presented = deriveThreadFeedPresentation(feed, null, new Set());
226 const activities = presented.flatMap((entry) =>
227 entry.type === "activity-group" ? entry.activities : [],
228 );
229 expect(activities).toHaveLength(1);
230 expect(activities[0]).toMatchObject({
231 summary: message,
232 detail: message,
233 prominent: true,
234 toolLike: false,
235 status: null,
236 icon: "warning",
237 workEntry: { tone: "info", itemType: "system_notice" },
238 });
239 expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
240 });
241
242 it("presents provider retries as visible work-log activity", () => {
243 const retryBase = {
244 ...base("item-provider-retry", "2026-06-20T00:00:02.000Z", 1),
245 type: "error" as const,
246 failure: {
247 class: "transport_error" as const,
248 message: "The response stream disconnected.",
249 code: "responseStreamDisconnected",
250 retryable: true,
251 },
252 retry: {
253 attempt: 2,
254 maxAttempts: 5,
255 retryDelayMs: null,
256 },
257 };
258 const runningFeed = buildThreadFeed([
259 projected(
260 {
261 ...retryBase,
262 status: "running",
263 title: "Provider retry",
264 completedAt: null,
265 },
266 0,
267 ),
268 ]);
269 const recoveredFeed = buildThreadFeed([
270 projected(
271 {
272 ...retryBase,
273 status: "completed",
274 title: "Provider recovered",
275 },
276 0,
277 ),
278 ]);
279 const failedFeed = buildThreadFeed([
280 projected(
281 {
282 ...retryBase,
283 status: "failed",
284 title: "Provider retry failed",
285 },
286 0,
287 ),
288 projected(command("2026-06-20T00:00:03.000Z"), 1),
289 ]);
290 const runningActivity = runningFeed.find((entry) => entry.type === "activity-group")
291 ?.activities[0];
292 const recoveredActivity = recoveredFeed.find((entry) => entry.type === "activity-group")
293 ?.activities[0];
294 if (runningActivity === undefined || recoveredActivity === undefined) {
295 throw new Error("Expected provider retry work-log activities.");
296 }
297
298 expect(runningActivity).toMatchObject({
299 summary: "Provider retry",
300 status: "neutral",
301 toolLike: false,
302 });
303 expect(threadFeedActivityIsVisible(runningActivity)).toBe(true);
304 expect(recoveredActivity).toMatchObject({
305 summary: "Provider recovered",
306 status: "success",
307 toolLike: false,
308 });
309 const failedPresentation = deriveThreadFeedPresentation(
310 failedFeed,
311 { runId, status: "running", startedAt: null, completedAt: null },
312 new Set(),
313 );
314 expect(failedPresentation.map((entry) => entry.type)).toEqual([
315 "activity-group",
316 "work-toggle",
317 ]);
318 expect(
319 failedPresentation[0]?.type === "activity-group"
320 ? failedPresentation[0].activities[0]?.summary
321 : null,
322 ).toBe("Provider retry failed");
323 });
324
325 it.each(["pending", "running", "completed"] as const)(
326 "omits %s task progress without hiding adjacent conversation items",
327 (stepStatus) => {
328 const todoItem = {
329 ...base("item-tasks", "2026-06-20T00:00:02.500Z", 2),
330 type: "todo_list" as const,
331 planId: PlanId.make("plan-tasks"),
332 steps: [{ id: "step-1", text: "Verify the change", status: stepStatus }],
333 } satisfies OrchestrationV2TurnItem;
334 const user = projected(userMessage(), 0);
335 const tool = projected(command(), 1);
336 const assistant = projected(assistantMessage(), 3);
337
338 expect(buildThreadFeed([user, tool, projected(todoItem, 2), assistant])).toEqual(
339 buildThreadFeed([user, tool, assistant]),
340 );
341 },
342 );
343
344 it("hides synthetic workspace preparation activity", () => {
345 const workspacePreparation = projected(
346 {
347 ...command(),
348 title: "Workspace ready",
349 input: "Preparing workspace",
350 output: "Workspace preparation completed.",
351 },
352 0,
353 );
354
355 expect(buildThreadFeed([workspacePreparation])).toEqual([]);
356 });
357
358 it("does not treat a queued-only run as live feed activity", () => {
359 expect(
360 threadFeedRunIsUnsettled({
361 runId,
362 status: "queued",
363 startedAt: null,
364 completedAt: null,
365 }),
366 ).toBe(false);
367 expect(
368 threadFeedRunIsUnsettled({
369 runId,
370 status: "running",
371 startedAt: "2026-06-20T00:00:01.000Z",
372 completedAt: null,
373 }),
374 ).toBe(true);
375 expect(
376 threadFeedRunIsUnsettled({
377 runId,
378 status: "completed",
379 startedAt: "2026-06-20T00:00:01.000Z",
380 completedAt: null,
381 }),
382 ).toBe(true);
383 expect(
384 threadFeedRunIsUnsettled({
385 runId,
386 status: "waiting",
387 startedAt: "2026-06-20T00:00:01.000Z",
388 completedAt: null,
389 }),
390 ).toBe(true);
391 });
392
393 it("adds queued input only after dispatch creates its turn item", () => {
394 const dispatchedRunId = RunId.make("run-dispatched-queued");
395 const dispatchedMessageId = MessageId.make("message-dispatched-queued");
396 expect(buildThreadFeed([])).toEqual([]);
397
398 const promotedEntries = buildThreadFeed([
399 projected(
400 {
401 ...userMessage(),
402 id: TurnItemId.make("item-dispatched-queued"),
403 runId: dispatchedRunId,
404 messageId: dispatchedMessageId,
405 inputIntent: "turn_start",
406 },
407 0,
408 ),
409 ]);
410 expect(promotedEntries.map((entry) => entry.id)).toEqual([dispatchedMessageId]);
411 expect(
412 promotedEntries[0]?.type === "message" ? promotedEntries[0].message.inputIntent : undefined,
413 ).toBe("turn_start");
414 });
415
416 it("hides the interruption request and keeps the terminal result", () => {
417 const request = projected(
418 {
419 ...base("item-interrupt-request", "2026-06-20T00:00:02.000Z", 1),
420 type: "run_interrupt_request",
421 message: "Interrupt requested",
422 },
423 0,
424 );
425 const result = projected(
426 {
427 ...base("item-interrupt-result", "2026-06-20T00:00:03.000Z", 2),
428 type: "run_interrupt_result",
429 message: "Run interrupted before provider start",
430 },
431 1,
432 );
433
434 const activities = buildThreadFeed([request, result]).flatMap((entry) =>
435 entry.type === "activity-group" ? entry.activities : [],
436 );
437
438 expect(activities).toHaveLength(1);
439 expect(activities[0]?.summary).toBe("Run interrupted");
440 expect(activities[0]?.detail).toBe("Run interrupted before provider start");
441 expect(
442 deriveThreadFeedPresentation(
443 buildThreadFeed([request, result]),
444 {
445 runId,
446 status: "interrupted",
447 startedAt: "2026-06-20T00:00:01.000Z",
448 completedAt: "2026-06-20T00:00:03.000Z",
449 },
450 new Set(),
451 ).some((entry) => entry.type === "run-fold"),
452 ).toBe(false);
453 });
454
455 it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
456 const rows = [
457 projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
458 projected(command("2026-06-20T00:00:01.000Z"), 1),
459 projected(assistantMessage("2026-06-20T00:00:02.000Z"), 2),
460 ];
461
462 const feed = buildThreadFeed(rows);
463 expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
464 expect(feed.map((entry) => entry.id)).toEqual([
465 "message-user",
466 "local:thread-1:item-command",
467 "message-assistant",
468 ]);
469 const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
470 expect(activity?.projectedItem).toBe(rows[1]);
471 expect(activity?.getFullDetail()).toContain('"input": "vp check"');
472 });
473
474 it("keeps adjacent work from different V2 attempts in separate groups", () => {
475 const firstRootNodeId = NodeId.make("node-attempt-1");
476 const secondRootNodeId = NodeId.make("node-attempt-2");
477 const firstCommand = { ...command(), nodeId: firstRootNodeId };
478 const secondCommand = {
479 ...command("2026-06-20T00:00:03.000Z"),
480 id: TurnItemId.make("item-command-retry"),
481 ordinal: 2,
482 nodeId: secondRootNodeId,
483 };
484 const attempts = [
485 {
486 id: RunAttemptId.make("attempt-1"),
487 runId,
488 attemptOrdinal: 1,
489 rootNodeId: firstRootNodeId,
490 providerInstanceId: ProviderInstanceId.make("provider-instance-1"),
491 providerThreadId: ProviderThreadId.make("provider-thread-1"),
492 providerTurnId: null,
493 reason: "initial",
494 status: "completed",
495 startedAt: DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"),
496 completedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
497 },
498 {
499 id: RunAttemptId.make("attempt-2"),
500 runId,
501 attemptOrdinal: 2,
502 rootNodeId: secondRootNodeId,
503 providerInstanceId: ProviderInstanceId.make("provider-instance-1"),
504 providerThreadId: ProviderThreadId.make("provider-thread-1"),
505 providerTurnId: null,
506 reason: "retry",
507 status: "completed",
508 startedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
509 completedAt: DateTime.makeUnsafe("2026-06-20T00:00:03.000Z"),
510 },
511 ] satisfies ReadonlyArray<OrchestrationV2RunAttempt>;
512
513 const feed = buildThreadFeed([projected(firstCommand, 0), projected(secondCommand, 1)], {
514 attempts,
515 });
516
517 expect(feed).toHaveLength(2);
518 expect(
519 feed.map((entry) =>
520 entry.type === "activity-group" ? entry.activities[0]?.attemptId : null,
521 ),
522 ).toEqual(["attempt-1", "attempt-2"]);
523 });
524
525 it("retains inherited and synthetic rows with their original projected identity", () => {
526 const inherited = projected(command(), 0, "inherited");
527 const { providerThreadId: _providerThreadId, ...forkBase } = base(
528 "item-fork",
529 "2026-06-20T00:00:03.000Z",
530 2,
531 );
532 const synthetic = projected(
533 {
534 ...forkBase,
535 type: "fork",
536 source: { type: "run", threadId: sourceThreadId, runId },
537 targetThreadId: threadId,
538 },
539 1,
540 "synthetic",
541 );
542
543 const feed = buildThreadFeed([inherited, synthetic]);
544 const activities = feed.flatMap((entry) =>
545 entry.type === "activity-group" ? entry.activities : [],
546 );
547 expect(activities.map((activity) => activity.projectedItem)).toEqual([inherited, synthetic]);
548 expect(activities.map((activity) => activity.projectedItem.visibility)).toEqual([
549 "inherited",
550 "synthetic",
551 ]);
552 expect(activities.at(-1)?.prominent).toBe(true);
553 });
554
555 it("keeps orchestration relationship cards visible when a completed run is folded", () => {
556 const { providerThreadId: _providerThreadId, ...forkBase } = base(
557 "item-fork",
558 "2026-06-20T00:00:02.500Z",
559 2,
560 );
561 const feed = buildThreadFeed([
562 projected(userMessage(), 0),
563 projected(command(), 1),
564 projected(
565 {
566 ...forkBase,
567 type: "fork",
568 source: { type: "run", threadId, runId },
569 targetThreadId: sourceThreadId,
570 },
571 2,
572 ),
573 projected(assistantMessage(), 3),
574 ]);
575
576 const collapsed = deriveThreadFeedPresentation(
577 feed,
578 {
579 runId,
580 status: "completed",
581 startedAt: "2026-06-20T00:00:01.000Z",
582 completedAt: "2026-06-20T00:00:03.000Z",
583 },
584 new Set(),
585 );
586
587 expect(
588 collapsed.some(
589 (entry) =>
590 entry.type === "activity-group" &&
591 entry.activities.some((activity) => activity.projectedItem.item.type === "fork"),
592 ),
593 ).toBe(true);
594 expect(
595 collapsed.some(
596 (entry) =>
597 entry.type === "activity-group" &&
598 entry.activities.some(
599 (activity) => activity.projectedItem.item.type === "command_execution",
600 ),
601 ),
602 ).toBe(false);
603 });
604
605 it("keeps opening and final assistant messages around the first hidden work", () => {
606 const opening = {
607 ...assistantMessage("2026-06-20T00:00:01.500Z"),
608 id: TurnItemId.make("item-opening"),
609 messageId: MessageId.make("message-opening"),
610 text: "I will check the deployment configuration.",
611 };
612 const middle = {
613 ...assistantMessage("2026-06-20T00:00:02.500Z"),
614 id: TurnItemId.make("item-middle"),
615 messageId: MessageId.make("message-middle"),
616 text: "The configuration is valid; checking the build next.",
617 };
618 const feed = buildThreadFeed([
619 projected(userMessage(), 0),
620 projected(opening, 1),
621 projected(command(), 2),
622 projected(middle, 3),
623 projected(assistantMessage(), 4),
624 ]);
625 const latestRun = {
626 runId,
627 status: "completed" as const,
628 startedAt: "2026-06-20T00:00:01.000Z",
629 completedAt: "2026-06-20T00:00:03.000Z",
630 };
631
632 const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
633 expect(collapsed.map((entry) => entry.id)).toEqual([
634 "message-user",
635 "message-opening",
636 "run-fold:run-1",
637 "message-assistant",
638 ]);
639 expect(collapsed[1]).toMatchObject({ message: { text: opening.text } });
640 expect(collapsed[2]).toMatchObject({
641 type: "run-fold",
642 createdAt: "2026-06-20T00:00:02.000Z",
643 label: "Worked for 2.0s",
644 });
645
646 const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
647 expect(expanded.map((entry) => entry.type)).toEqual([
648 "message",
649 "message",
650 "run-fold",
651 "work-toggle",
652 "message",
653 "message",
654 ]);
655 expect(expanded[4]).toMatchObject({ message: { id: middle.messageId, text: middle.text } });
656 });
657
658 it("does not fold a response that only has opening and final messages", () => {
659 const feed = buildThreadFeed([
660 projected(userMessage(), 0),
661 projected(
662 {
663 ...assistantMessage("2026-06-20T00:00:02.000Z"),
664 id: TurnItemId.make("item-opening"),
665 messageId: MessageId.make("message-opening"),
666 text: "The result is ready.",
667 },
668 1,
669 ),
670 projected(assistantMessage(), 2),
671 ]);
672
673 const presented = deriveThreadFeedPresentation(feed, null, new Set());
674 expect(presented.map((entry) => entry.id)).toEqual([
675 "message-user",
676 "message-opening",
677 "message-assistant",
678 ]);
679 });
680
681 it("places the fold after leading resource cards and keeps later cards visible", () => {
682 const { providerThreadId: _providerThreadId, ...forkBase } = base(
683 "item-fork",
684 "2026-06-20T00:00:02.000Z",
685 2,
686 );
687 const resourceItems = [
688 {
689 ...base("item-subagent", "2026-06-20T00:00:01.500Z", 1),
690 type: "subagent",
691 subagentId: NodeId.make("child-agent"),
692 origin: "app_owned",
693 driver: ProviderDriverKind.make("codex"),
694 providerInstanceId: ProviderInstanceId.make("codex"),
695 childThreadId: sourceThreadId,
696 prompt: "Inspect the deployment configuration",
697 result: "Configuration is valid",
698 },
699 {
700 ...forkBase,
701 type: "fork",
702 source: { type: "run", threadId, runId },
703 targetThreadId: sourceThreadId,
704 },
705 {
706 ...base("item-created-thread", "2026-06-20T00:00:04.000Z", 4),
707 type: "thread_created",
708 targetThreadId: sourceThreadId,
709 targetRunId: null,
710 targetProviderInstanceId: ProviderInstanceId.make("codex"),
711 targetModel: "gpt-5.4",
712 },
713 ] satisfies ReadonlyArray<OrchestrationV2TurnItem>;
714 const projectedResources = [
715 projected(resourceItems[0]!, 1),
716 projected(resourceItems[1]!, 2),
717 projected(resourceItems[2]!, 4),
718 ];
719 const feed = buildThreadFeed([
720 projected(userMessage(), 0),
721 projectedResources[0]!,
722 projectedResources[1]!,
723 projected(command("2026-06-20T00:00:03.000Z"), 3),
724 projectedResources[2]!,
725 projected(assistantMessage("2026-06-20T00:00:05.000Z"), 5),
726 ]);
727
728 const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
729 expect(collapsed.map((entry) => entry.type)).toEqual([
730 "message",
731 "activity-group",
732 "activity-group",
733 "run-fold",
734 "activity-group",
735 "message",
736 ]);
737 expect(collapsed[3]).toMatchObject({
738 type: "run-fold",
739 createdAt: "2026-06-20T00:00:03.000Z",
740 });
741 expect(
742 collapsed.flatMap((entry) =>
743 entry.type === "activity-group"
744 ? entry.activities.map((activity) => activity.projectedItem)
745 : [],
746 ),
747 ).toEqual(projectedResources);
748 });
749
750 it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
751 const feed = buildThreadFeed([
752 projected(userMessage(), 0),
753 projected(command(), 1),
754 projected(assistantMessage(), 2),
755 ]);
756 const latestRun = {
757 runId,
758 status: "completed" as const,
759 startedAt: "2026-06-20T00:00:01.000Z",
760 completedAt: "2026-06-20T00:00:03.000Z",
761 };
762
763 const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
764 expect(collapsed.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
765
766 const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
767 expect(expanded.map((entry) => entry.type)).toEqual([
768 "message",
769 "run-fold",
770 "work-toggle",
771 "message",
772 ]);
773 });
774
775 it("keeps an active run expanded and detects failures from completed command output", () => {
776 const failedCommand: OrchestrationV2TurnItem = {
777 ...command(),
778 output: "sh: missing-command: command not found",
779 };
780 const feed = buildThreadFeed([projected(userMessage(), 0), projected(failedCommand, 1)]);
781 const presented = deriveThreadFeedPresentation(
782 feed,
783 {
784 runId,
785 status: "running",
786 startedAt: "2026-06-20T00:00:01.000Z",
787 completedAt: null,
788 },
789 new Set(),
790 );
791
792 expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
793 expect(presented.find((entry) => entry.type === "work-toggle")).toMatchObject({
794 summary: "vp check",
795 hiddenCount: 1,
796 hasFailure: true,
797 live: false,
798 });
799 });
800
801 it("does not append synthetic timeline work without a projected item", () => {
802 const startedAt = "2026-04-01T00:00:01.000Z";
803 const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
804
805 expect(presented).toEqual([]);
806 });
807
808 it("keeps expanded work in one group with stable row identities", () => {
809 const activity = (
810 id: string,
811 createdAt: string,
812 status: ThreadFeedActivity["status"] = "success",
813 ): ThreadFeedActivity => ({
814 id,
815 createdAt,
816 runId: null,
817 attemptId: null,
818 summary: `Tool ${id}`,
819 detail: null,
820 canExpand: false,
821 getFullDetail: () => null,
822 getCopyText: () => id,
823 icon: "command",
824 logo: null,
825 toolLike: true,
826 prominent: false,
827 status,
828 lifecycleStatus: status === "neutral" ? "inProgress" : "completed",
829 workEntry: {
830 id,
831 createdAt,
832 label: `Tool ${id}`,
833 tone: "tool",
834 command: "vp check",
835 itemType: "command_execution",
836 toolLifecycleStatus: status === "neutral" ? "inProgress" : "completed",
837 },
838 projectedItem: projected(command(createdAt), 0),
839 });
840 const feed: ThreadFeedEntry[] = [
841 {
842 type: "activity-group",
843 id: "work-group-1",
844 createdAt: "2026-04-01T00:00:01.000Z",
845 runId: null,
846 activities: [
847 activity("activity-neutral", "2026-04-01T00:00:01.000Z", "neutral"),
848 activity("activity-1", "2026-04-01T00:00:02.000Z"),
849 activity("activity-2", "2026-04-01T00:00:03.000Z"),
850 activity("activity-3", "2026-04-01T00:00:04.000Z"),
851 ],
852 },
853 ];
854
855 const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
856 expect(collapsed.map((entry) => entry.id)).toEqual(["work-toggle:work-group:activity-neutral"]);
857 expect(collapsed[0]).toMatchObject({
858 type: "work-toggle",
859 groupId: "work-group:activity-neutral",
860 hiddenCount: 3,
861 expanded: false,
862 summary: "Ran 3 commands",
863 });
864
865 const expanded = deriveThreadFeedPresentation(
866 feed,
867 null,
868 new Set(),
869 new Set(["work-group:activity-neutral"]),
870 );
871 expect(expanded.map((entry) => entry.id)).toEqual([
872 "work-toggle:work-group:activity-neutral",
873 "work-details:work-group:activity-neutral",
874 ]);
875 expect(expanded[0]).toMatchObject({
876 type: "work-toggle",
877 expanded: true,
878 });
879 expect(expanded[1]).toMatchObject({
880 type: "activity-group",
881 activities: [
882 { id: "activity-1", groupedToolDetail: true, live: false },
883 { id: "activity-2", groupedToolDetail: true, live: false },
884 { id: "activity-3", groupedToolDetail: true, live: false },
885 ],
886 });
887 });
888
889 it("pretty prints T3 MCP dynamic tool activities and attaches the product logo", () => {
890 const toolItem: OrchestrationV2TurnItem = {
891 ...base("item-t3-tool", "2026-06-20T00:00:04.000Z", 3),
892 type: "dynamic_tool",
893 toolName: "mcp__t3-code__t3_thread_read",
894 input: { threadId: "thread-child" },
895 output: { messages: [] },
896 };
897
898 const feed = buildThreadFeed([projected(toolItem, 0)]);
899 const activity = feed[0]?.type === "activity-group" ? feed[0].activities[0] : null;
900
901 expect(activity?.summary).toBe("Read a T3 thread");
902 expect(activity?.logo).toBe("t3-code");
903 expect(activity?.getCopyText().split("\n")[0]).toBe("Read a T3 thread");
904 });
905
906 it("uses canonical T3 orchestration summaries in compact work groups", () => {
907 const rows = [
908 projected(command("2026-06-20T00:00:01.000Z"), 0),
909 ...["mcp__t3-code__t3_thread_send", "t3_code.t3_thread_send", "t3_thread_send"].map(
910 (toolName, index) =>
911 projected(
912 {
913 ...base(`item-send-${index}`, `2026-06-20T00:00:0${index + 2}.000Z`, index + 2),
914 type: "dynamic_tool" as const,
915 toolName,
916 input: { threadId: `thread-${index}`, message: "Continue" },
917 output: { threadId: `thread-${index}`, messageId: `message-${index}` },
918 },
919 index + 1,
920 ),
921 ),
922 projected(
923 {
924 ...command("2026-06-20T00:00:06.000Z"),
925 id: TurnItemId.make("item-command-2"),
926 ordinal: 6,
927 },
928 4,
929 ),
930 ];
931
932 const presented = deriveThreadFeedPresentation(
933 buildThreadFeed(rows),
934 { runId, status: "running", startedAt: null, completedAt: null },
935 new Set(),
936 );
937
938 expect(presented).toMatchObject([
939 {
940 type: "work-toggle",
941 summary: "Ran 2 commands and sent messages to 3 threads",
942 hiddenCount: 5,
943 hasFailure: false,
944 },
945 ]);
946 });
947});
948
949describe("retained v2 feed presentation", () => {
950 it("retains unchanged rows while the assistant streams", () => {
951 const rows = [
952 projected(userMessage(), 0),
953 projected(command(), 1),
954 projected({ ...assistantMessage(), streaming: true }, 2),
955 ];
956 const latestRun = {
957 runId,
958 status: "running" as const,
959 startedAt: "2026-06-20T00:00:01.000Z",
960 completedAt: null,
961 };
962 const before = buildThreadFeed(rows);
963 const beforePresentation = deriveThreadFeedPresentation(
964 before,
965 latestRun,
966 new Set(),
967 new Set(),
968 latestRun.startedAt,
969 );
970 const after = buildThreadFeed([
971 rows[0]!,
972 rows[1]!,
973 projected(
974 { ...assistantMessage("2026-06-20T00:00:04.000Z"), text: "Still working", streaming: true },
975 2,
976 ),
977 ]);
978 const afterPresentation = deriveThreadFeedPresentation(
979 after,
980 latestRun,
981 new Set(),
982 new Set(),
983 latestRun.startedAt,
984 );
985 expect(after[0]).toBe(before[0]);
986 expect(after[1]).toBe(before[1]);
987 expect(after[2]).not.toBe(before[2]);
988 expect(afterPresentation[0]).toBe(beforePresentation[0]);
989 expect(afterPresentation[1]).toBe(beforePresentation[1]);
990 });
991
992 it("keeps a standalone compaction visible and folds it with other completed work", () => {
993 const compact = projected(
994 {
995 ...base("compacted", "2026-06-20T00:00:02.000Z", 1),
996 type: "compaction",
997 driver: null,
998 summary: "Shorter context",
999 },
1000 1,
1001 );
1002 const latestRun = {
1003 runId,
1004 status: "completed" as const,
1005 startedAt: "2026-06-20T00:00:01.000Z",
1006 completedAt: "2026-06-20T00:00:04.000Z",
1007 };
1008 const onlyCompaction = deriveThreadFeedPresentation(
1009 buildThreadFeed([projected(userMessage(), 0), compact]),
1010 latestRun,
1011 new Set(),
1012 );
1013 expect(onlyCompaction.map((entry) => entry.type)).toEqual(["message", "activity-group"]);
1014 const feed = buildThreadFeed([
1015 projected(userMessage(), 0),
1016 compact,
1017 projected(command("2026-06-20T00:00:03.000Z"), 2),
1018 projected(assistantMessage("2026-06-20T00:00:04.000Z"), 3),
1019 ]);
1020 expect(
1021 deriveThreadFeedPresentation(feed, latestRun, new Set()).map((entry) => entry.type),
1022 ).toEqual(["message", "run-fold", "message"]);
1023 const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
1024 expect(
1025 expanded.find(
1026 (entry) =>
1027 entry.type === "activity-group" &&
1028 entry.activities[0]?.projectedItem.item.type === "compaction",
1029 ),
1030 ).toMatchObject({ activities: [{ summary: "Context compacted" }] });
1031 });
1032
1033 it("retains assistant image attachments from the wire", () => {
1034 const image = {
1035 type: "image" as const,
1036 id: "assistant-image",
1037 name: "result.png",
1038 mimeType: "image/png",
1039 sizeBytes: 100,
1040 };
1041 const feed = buildThreadFeed([
1042 projected({ ...assistantMessage(), text: "", attachments: [image] }, 0),
1043 ]);
1044 expect(feed).toMatchObject([
1045 { type: "message", message: { role: "assistant", attachments: [image] } },
1046 ]);
1047 });
1048
1049 it("keeps native application icons and source identity in collapsed and expanded work", () => {
1050 const icon = {
1051 _tag: "native-app" as const,
1052 app: { _tag: "app-id" as const, appId: "com.example.Editor" },
1053 };
1054 const source = {
1055 key: "native-app:com.example.editor",
1056 name: "Editor",
1057 kind: "computer" as const,
1058 icon,
1059 };
1060 const rows = [0, 1].map((index) =>
1061 projected(
1062 {
1063 ...base(`native-${index}`, `2026-06-20T00:00:0${index + 2}.000Z`, index + 1),
1064 type: "dynamic_tool" as const,
1065 toolName: "computer.click",
1066 input: { x: index, y: 1 },
1067 output: null,
1068 toolSurface: "computer" as const,
1069 toolIcon: icon,
1070 toolSource: source,
1071 },
1072 index,
1073 ),
1074 );
1075 const feed = buildThreadFeed(rows);
1076 const latestRun = { runId, status: "running" as const, startedAt: null, completedAt: null };
1077 const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
1078 const toggle = collapsed[0];
1079 if (toggle?.type !== "work-toggle") throw new Error("Expected a collapsed work group");
1080 const presented = deriveThreadFeedPresentation(
1081 feed,
1082 latestRun,
1083 new Set(),
1084 new Set([toggle.groupId]),
1085 );
1086 expect(presented[0]).toMatchObject({
1087 type: "work-toggle",
1088 summary: "Used Editor",
1089 toolSurface: "computer",
1090 toolIcon: icon,
1091 });
1092 expect(presented[1]).toMatchObject({
1093 type: "activity-group",
1094 activities: [
1095 { icon: "computer", workEntry: { toolSource: source, toolIcon: icon } },
1096 { icon: "computer", workEntry: { toolSource: source, toolIcon: icon } },
1097 ],
1098 });
1099 });
1100
1101 it.each([
1102 ["failed", "Failed to click in the preview browser", true],
1103 ["cancelled", "Stopped clicking in the preview browser", false],
1104 ] as const)(
1105 "keeps %s calls terminal while the parent run remains live",
1106 (status, summary, hasFailure) => {
1107 const feed = buildThreadFeed([
1108 projected(
1109 {
1110 ...base("preview-click", "2026-06-20T00:00:02.000Z", 1),
1111 type: "dynamic_tool",
1112 status,
1113 toolName: "mcp__t3-code__preview_click",
1114 input: { element: "button" },
1115 output: null,
1116 },
1117 0,
1118 ),
1119 ]);
1120 const rows = deriveThreadFeedPresentation(
1121 feed,
1122 { runId, status: "running", startedAt: "2026-06-20T00:00:01.000Z", completedAt: null },
1123 new Set(),
1124 new Set(),
1125 "2026-06-20T00:00:01.000Z",
1126 );
1127 expect(rows[0]).toMatchObject({ type: "work-toggle", summary, hasFailure, shimmer: false });
1128 },
1129 );
1130
1131 it("shows an idle native subagent without claiming completion", () => {
1132 const rows = buildThreadFeed([
1133 projected(
1134 {
1135 ...base("native-agent", "2026-06-20T00:00:02.000Z", 1),
1136 type: "subagent",
1137 status: "idle",
1138 subagentId: NodeId.make("native-agent"),
1139 origin: "provider_native",
1140 driver: ProviderDriverKind.make("antigravity"),
1141 providerInstanceId: ProviderInstanceId.make("antigravity"),
1142 childThreadId: null,
1143 title: "Search",
1144 prompt: "Find relevant files",
1145 result: null,
1146 },
1147 0,
1148 ),
1149 ]);
1150 expect(rows[0]).toMatchObject({
1151 type: "activity-group",
1152 activities: [{ status: "neutral", lifecycleStatus: "idle", prominent: true }],
1153 });
1154 expect(deriveThreadFeedPresentation(rows, null, new Set())).toMatchObject([
1155 { type: "activity-group", activities: [{ lifecycleStatus: "idle" }] },
1156 ]);
1157 });
1158});
1159
1160const singleSelectQuestion = {
1161 id: "runtime",
1162 header: "Runtime",
1163 question: "Which runtime should be used?",
1164 options: [
1165 { label: "Go", description: "One binary" },
1166 { label: "Node.js", description: "Reuse TypeScript" },
1167 ],
1168 multiSelect: false,
1169} as const;
1170
1171const multiSelectQuestion = {
1172 id: "scope",
1173 header: "Scope",
1174 question: "Which data should be collected?",
1175 options: [
1176 { label: "Orders", description: "Receipts" },
1177 { label: "Listings", description: "Inventory" },
1178 ],
1179 multiSelect: true,
1180} as const;
1181
1182describe("pending user input answers", () => {
1183 it("replaces single-select options and toggles multi-select options", () => {
1184 expect(
1185 togglePendingUserInputOptionSelection(
1186 singleSelectQuestion,
1187 { selectedOptionValues: ["Go"] },
1188 "Node.js",
1189 ),
1190 ).toEqual({ customAnswer: "", selectedOptionValues: ["Node.js"] });
1191
1192 const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");
1193 const ordersAndListings = togglePendingUserInputOptionSelection(
1194 multiSelectQuestion,
1195 orders,
1196 "Listings",
1197 );
1198 expect(ordersAndListings).toEqual({
1199 customAnswer: "",
1200 selectedOptionValues: ["Orders", "Listings"],
1201 });
1202 expect(
1203 togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),
1204 ).toEqual({ customAnswer: "", selectedOptionValues: ["Listings"] });
1205
1206 const paddedOrders = togglePendingUserInputOptionSelection(
1207 multiSelectQuestion,
1208 undefined,
1209 " Orders ",
1210 );
1211 expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionValues: ["Orders"] });
1212 expect(
1213 togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "),
1214 ).toEqual({ customAnswer: "" });
1215 });
1216
1217 it("builds array answers for multi-select questions", () => {
1218 expect(
1219 buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {
1220 runtime: { selectedOptionValues: ["Go"] },
1221 scope: { selectedOptionValues: ["Orders", "Listings"] },
1222 }),
1223 ).toEqual({
1224 runtime: "Go",
1225 scope: ["Orders", "Listings"],
1226 });
1227 });
1228
1229 it("clears selected options while a custom answer is active", () => {
1230 expect(
1231 setPendingUserInputCustomAnswer(
1232 multiSelectQuestion,
1233 { selectedOptionValues: ["Orders", "Listings"] },
1234 "Orders first",
1235 ),
1236 ).toEqual({ customAnswer: "Orders first" });
1237 });
1238
1239 it("matches selected chips against normalized option labels", () => {
1240 expect(
1241 isPendingUserInputOptionSelected(
1242 multiSelectQuestion,
1243 { selectedOptionValues: ["Orders"] },
1244 " Orders ",
1245 ),
1246 ).toBe(true);
1247 expect(
1248 isPendingUserInputOptionSelected(
1249 multiSelectQuestion,
1250 { selectedOptionValues: ["Orders"], customAnswer: "Orders first" },
1251 " Orders ",
1252 ),
1253 ).toBe(false);
1254 });
1255});
1256
1257describe("provider question values", () => {
1258 const question = {
1259 ...singleSelectQuestion,
1260 allowCustomAnswer: false,
1261 options: [
1262 { label: "Same label", value: " exact first ", description: "First" },
1263 { label: "Same label", value: "second", description: "Second" },
1264 ],
1265 } as const;
1266
1267 it("submits raw option values and distinguishes duplicate labels", () => {
1268 const first = togglePendingUserInputOptionSelection(question, undefined, " exact first ");
1269 expect(isPendingUserInputOptionSelected(question, first, " exact first ")).toBe(true);
1270 expect(isPendingUserInputOptionSelected(question, first, "second")).toBe(false);
1271 expect(buildPendingUserInputAnswers([question], { runtime: first })).toEqual({
1272 runtime: " exact first ",
1273 });
1274 expect(togglePendingUserInputOptionSelection(question, first, "Same label")).toBe(first);
1275 });
1276
1277 it("rejects arbitrary text when the provider only accepts offered options", () => {
1278 expect(setPendingUserInputCustomAnswer(question, undefined, "Other")).toEqual({});
1279 expect(
1280 buildPendingUserInputAnswers([question], { runtime: { customAnswer: "Other" } }),
1281 ).toBeNull();
1282 expect(
1283 buildPendingUserInputAnswers([question], { runtime: { selectedOptionValues: ["unknown"] } }),
1284 ).toBeNull();
1285 expect(
1286 buildPendingUserInputAnswers([question], {
1287 runtime: { selectedOptionValues: ["second"], customAnswer: "stale draft" },
1288 }),
1289 ).toEqual({ runtime: "second" });
1290 });
1291});