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

main
ts 2,319 lines 78.9 KB
Raw
1 import {
2 MessageId,
3 CheckpointId,
4 CheckpointRef,
5 CheckpointScopeId,
6 RuntimeRequestId,
7 NodeId,
8 ProviderInstanceId,
9 ProviderDriverKind,
10 ProviderThreadId,
11 ProviderTurnId,
12 RunId,
13 RunAttemptId,
14 ThreadId,
15 TurnItemId,
16 type OrchestrationV2RunAttempt,
17 type OrchestrationV2ProjectedTurnItem,
18 type OrchestrationV2TurnItem,
19 } from "@t3tools/contracts";
20 import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints";
21 import { summarizeToolGroup } from "@t3tools/client-runtime/work-log/presentation";
22 import { getReviewSectionIdForCheckpoint } from "../features/review/reviewModel";
23 import * as DateTime from "effect/DateTime";
24 import { describe, expect, it } from "vite-plus/test";
25
26 import {
27 buildThreadFeed,
28 workEntryRowLabel,
29 threadFeedCompactionLabels,
30 createThreadFeedCache,
31 deriveThreadFeedPresentation,
32 messageFoldRunId,
33 type ThreadFeedCache,
34 type ThreadFeedEntry,
35 type ThreadFeedLatestRun,
36 } from "./threadActivity";
37
38 const threadId = ThreadId.make("thread-1");
39 const sourceThreadId = ThreadId.make("thread-source");
40 const runId = RunId.make("run-1");
41
42 it.each(["info", "warning", "error", undefined] as const)(
43 "renders %s system notice severity",
44 (level) => {
45 const item = {
46 ...base("notice", "2026-08-29T00:00:00.000Z", 1),
47 type: "system_notice" as const,
48 message: "Extension notice",
49 ...(level === undefined ? {} : { level }),
50 };
51 const activity = buildThreadFeed([projected(item, 0)]).flatMap((entry) =>
52 entry.type === "activity-group" ? entry.activities : [],
53 )[0];
54 expect(activity?.icon).toBe(level === "info" ? "zap" : "warning");
55 expect(activity?.summary).toBe(item.message);
56 },
57 );
58
59 it("shows a captured MCP app for a failed deferred write", () => {
60 const mcpApp = {
61 attachmentId: "deferred-app-html",
62 server: "github",
63 tool: "create_pull_request",
64 resourceUri: "ui://github-mcp-server/pr-create",
65 };
66 const item: OrchestrationV2TurnItem = {
67 ...base("deferred-app", "2026-08-29T00:00:00.000Z", 1),
68 type: "dynamic_tool",
69 toolName: "github.create_pull_request",
70 status: "failed",
71 input: {},
72 output: { t3McpApp: mcpApp, result: { content: [], isError: true } },
73 };
74 expect(buildThreadFeed([projected(item, 0)])).toMatchObject([
75 { type: "activity-group" },
76 { type: "mcp-app", app: mcpApp },
77 ]);
78 });
79
80 it("keeps an MCP app call's tool activity beside its app card", () => {
81 const mcpApp = {
82 attachmentId: "repro-app-html",
83 server: "repro",
84 tool: "aggregate_rum_events",
85 resourceUri: "ui://repro/dataviz",
86 };
87 const item: OrchestrationV2TurnItem = {
88 ...base("repro-app", "2026-08-29T00:00:00.000Z", 1),
89 type: "dynamic_tool",
90 toolName: "repro.aggregate_rum_events",
91 input: { query: "@type:view" },
92 output: {
93 t3McpApp: mcpApp,
94 result: { content: [{ type: "text", text: "Notice\nview\tcount\n/home\t42" }] },
95 },
96 };
97 const feed = buildThreadFeed([projected(item, 0)]);
98 expect(feed).toContainEqual(expect.objectContaining({ type: "mcp-app", app: mcpApp }));
99 const activities = feed.flatMap((entry) =>
100 entry.type === "activity-group" ? entry.activities : [],
101 );
102 expect(activities).toHaveLength(1);
103 expect(activities[0]?.getFullDetail()).toContain("@type:view");
104 });
105
106 it("keeps historical plan detail accessible from its paged turn item", () => {
107 const item = {
108 ...base("historical-plan", "2026-08-29T00:00:00.000Z", 1),
109 type: "proposed_plan",
110 planId: "plan-historical",
111 markdown: "Full historical plan text",
112 streaming: false,
113 } as OrchestrationV2TurnItem;
114
115 const entries = buildThreadFeed([projected(item, 0)]);
116 const activity = entries.flatMap((entry) =>
117 entry.type === "activity-group" ? entry.activities : [],
118 )[0];
119 expect(activity?.detail).toBe("Full historical plan text");
120 expect(activity?.getFullDetail()).toBe("Full historical plan text");
121 expect(activity?.getCopyText()).toBe("Full historical plan text\n");
122 expect(activity?.prominent).toBe(true);
123 const presented = deriveThreadFeedPresentation(
124 buildThreadFeed([
125 projected(userMessage(), 0),
126 projected(command(), 1),
127 projected(item, 2),
128 projected(assistantMessage(), 3),
129 ]),
130 null,
131 new Set(),
132 );
133 expect(presented.map((entry) => entry.type)).toEqual([
134 "message",
135 "run-fold",
136 "activity-group",
137 "message",
138 ]);
139 expect(presented[2]).toMatchObject({ activities: [{ projectedItem: { item } }] });
140 });
141
142 it("shows a compact command as one mobile divider before, during, and after compaction", () => {
143 const startedAt = "2026-06-20T00:00:01.000Z";
144 const prompt = projected({ ...userMessage(), text: "/compact", idleCompaction: "onReturn" }, 0);
145 const latestRun = { runId, status: "running" as const, startedAt, completedAt: null };
146 const present = (items: OrchestrationV2ProjectedTurnItem[]) =>
147 deriveThreadFeedPresentation(
148 buildThreadFeed(items),
149 latestRun,
150 new Set(),
151 new Set(),
152 startedAt,
153 );
154
155 const waiting = present([prompt]);
156 expect(waiting.map((entry) => entry.type)).toEqual(["message"]);
157 expect(waiting[0]?.type === "message" ? waiting[0].message.idleCompaction : null).toBe(
158 "onReturn",
159 );
160 for (const status of ["running", "completed", "failed"] as const) {
161 const compaction = projected(
162 {
163 ...base("compaction", "2026-06-20T00:00:02.000Z", 1),
164 type: "compaction",
165 driver: ProviderDriverKind.make("claude"),
166 status,
167 beforeTokenCount: 100_000,
168 ...(status === "completed" ? { afterTokenCount: 20_000 } : {}),
169 ...(status === "failed" ? { summary: "Not enough messages to compact." } : {}),
170 },
171 1,
172 );
173 const rows = present([prompt, compaction]);
174 expect(rows.map((entry) => entry.type)).toEqual(["activity-group"]);
175 expect(
176 rows[0]?.type === "activity-group" ? rows[0].activities[0]?.projectedItem.item : null,
177 ).toMatchObject({ type: "compaction", status });
178 }
179 });
180
181 it("shows a skipped compaction as one stopped row, without a separate interrupted row", () => {
182 const prompt = projected({ ...userMessage(), text: "/compact", idleCompaction: "onReturn" }, 0);
183 const compaction = projected(
184 {
185 ...base("compaction", "2026-06-20T00:00:02.000Z", 1),
186 type: "compaction",
187 driver: ProviderDriverKind.make("claude"),
188 status: "interrupted",
189 },
190 1,
191 );
192 const interrupted = projected(
193 {
194 ...base("interrupt-result", "2026-06-20T00:00:03.000Z", 2),
195 type: "run_interrupt_result",
196 status: "interrupted",
197 message: "Skipped compaction to send a queued message",
198 },
199 2,
200 );
201 const rows = deriveThreadFeedPresentation(
202 buildThreadFeed([prompt, compaction, interrupted]),
203 {
204 runId,
205 status: "interrupted",
206 startedAt: "2026-06-20T00:00:01.000Z",
207 completedAt: "2026-06-20T00:00:03.000Z",
208 },
209 new Set(),
210 );
211
212 expect(rows.map((entry) => entry.type)).toEqual(["activity-group"]);
213 expect(
214 rows[0]?.type === "activity-group"
215 ? rows[0].activities.map((a) => a.projectedItem.item.type)
216 : null,
217 ).toEqual(["compaction"]);
218 });
219
220 it("keeps the interrupted row for a compaction stopped before its provider started", () => {
221 const rows = deriveThreadFeedPresentation(
222 buildThreadFeed([
223 projected({ ...userMessage(), text: "/compact" }, 0),
224 projected(
225 {
226 ...base("interrupt-result", "2026-06-20T00:00:03.000Z", 1),
227 type: "run_interrupt_result",
228 status: "interrupted",
229 message: "Run interrupted before provider start",
230 },
231 1,
232 ),
233 ]),
234 {
235 runId,
236 status: "interrupted",
237 startedAt: "2026-06-20T00:00:01.000Z",
238 completedAt: "2026-06-20T00:00:03.000Z",
239 },
240 new Set(),
241 );
242
243 expect(
244 rows.flatMap((entry) =>
245 entry.type === "activity-group"
246 ? entry.activities.map((activity) => activity.projectedItem.item.type)
247 : [],
248 ),
249 ).toContain("run_interrupt_result");
250 });
251
252 it.each(["/compact", "Continue"])(
253 "keeps a completed compaction divider visible while other settled work folds for %s",
254 (promptText) => {
255 const rows = deriveThreadFeedPresentation(
256 buildThreadFeed([
257 projected({ ...userMessage(), text: promptText }, 0),
258 projected(command(), 1),
259 projected(
260 {
261 ...base("compaction", "2026-06-20T00:00:03.000Z", 2),
262 type: "compaction",
263 driver: ProviderDriverKind.make("claude"),
264 status: "completed",
265 beforeTokenCount: 100_000,
266 afterTokenCount: 20_000,
267 },
268 2,
269 ),
270 ]),
271 {
272 runId,
273 status: "completed",
274 startedAt: "2026-06-20T00:00:01.000Z",
275 completedAt: "2026-06-20T00:00:03.000Z",
276 },
277 new Set(),
278 );
279 expect(rows.filter((entry) => entry.type === "run-fold")).toHaveLength(1);
280 const activities = rows.flatMap((entry) =>
281 entry.type === "activity-group" ? entry.activities : [],
282 );
283 expect(activities.map((activity) => activity.projectedItem.item)).toMatchObject([
284 {
285 type: "compaction",
286 status: "completed",
287 beforeTokenCount: 100_000,
288 afterTokenCount: 20_000,
289 },
290 ]);
291 if (promptText === "/compact") {
292 expect(rows.some((entry) => entry.type === "message")).toBe(false);
293 }
294 },
295 );
296
297 it("keeps only the latest compaction divider visible when a turn that compacted twice folds", () => {
298 const compaction = (id: string, ordinal: number, beforeTokenCount: number) => ({
299 ...base(id, "2026-06-20T00:00:03.000Z", ordinal),
300 type: "compaction" as const,
301 driver: ProviderDriverKind.make("claude"),
302 status: "completed" as const,
303 beforeTokenCount,
304 afterTokenCount: 20_000,
305 });
306 const feed = buildThreadFeed([
307 projected(userMessage(), 0),
308 projected(compaction("first-compaction", 1, 100_000), 1),
309 projected(command(), 2),
310 projected(compaction("second-compaction", 3, 90_000), 3),
311 ]);
312 const latestRun = {
313 runId,
314 status: "completed" as const,
315 startedAt: "2026-06-20T00:00:01.000Z",
316 completedAt: "2026-06-20T00:00:03.000Z",
317 };
318 const compactionsIn = (rows: ReadonlyArray<ThreadFeedEntry>) =>
319 rows.flatMap((entry) =>
320 entry.type === "activity-group"
321 ? entry.activities.flatMap(({ projectedItem: { item } }) =>
322 item.type === "compaction" ? [item.beforeTokenCount] : [],
323 )
324 : [],
325 );
326 const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
327 expect(collapsed.filter((entry) => entry.type === "run-fold")).toHaveLength(1);
328 expect(compactionsIn(collapsed)).toEqual([90_000]);
329 expect(compactionsIn(deriveThreadFeedPresentation(feed, latestRun, new Set([runId])))).toEqual([
330 100_000, 90_000,
331 ]);
332 });
333
334 it("binds a persisted resume answer only to the next compaction in its run", () => {
335 const requestId = RuntimeRequestId.make("resume-compaction");
336 const question = projected(
337 {
338 ...base("resume-question", "2026-06-20T00:00:02.000Z", 1),
339 type: "user_input_request",
340 requestId,
341 questions: [],
342 questionAnswer: {
343 requestId,
344 questionTextById: {
345 resume:
346 "This session is 2h 10m old and uses 200,000 tokens. Compact it before continuing?",
347 },
348 answers: { resume: "Compact and continue" },
349 attachmentsByQuestionId: {},
350 },
351 },
352 1,
353 );
354 const compaction = (id: string, position: number, status: "running" | "completed") =>
355 projected(
356 {
357 ...base(id, `2026-06-20T00:00:0${position + 1}.000Z`, position),
358 type: "compaction",
359 driver: ProviderDriverKind.make("claude"),
360 status,
361 beforeTokenCount: 200_000,
362 },
363 position,
364 );
365 for (const status of ["running", "completed"] as const) {
366 // Rebuild from persisted items, without a live question or prior feed cache.
367 const feed = buildThreadFeed([
368 projected(userMessage(), 0),
369 question,
370 compaction("resume-compact", 2, "completed"),
371 compaction("auto-compact", 3, status),
372 ]);
373 const labels = threadFeedCompactionLabels(feed);
374 const compactRows = feed.filter(
375 (entry) =>
376 entry.type === "activity-group" &&
377 entry.activities[0]?.projectedItem.item.type === "compaction",
378 );
379 expect(compactRows).toHaveLength(2);
380 expect(labels.get(compactRows[0]!.id)).toEqual({
381 title: "Context compacted after 2h 10m idle",
382 compacting: "Compacting…",
383 });
384 expect(labels.get(compactRows[1]!.id)).toBeUndefined();
385 }
386 });
387
388 function base(id: string, updatedAt: string, ordinal: number) {
389 const timestamp = DateTime.makeUnsafe(updatedAt);
390 return {
391 id: TurnItemId.make(id),
392 threadId,
393 runId,
394 nodeId: null,
395 providerThreadId: null,
396 providerTurnId: null,
397 nativeItemRef: null,
398 parentItemId: null,
399 ordinal,
400 status: "completed" as const,
401 title: null,
402 startedAt: timestamp,
403 completedAt: timestamp,
404 updatedAt: timestamp,
405 };
406 }
407
408 function projected(
409 item: OrchestrationV2TurnItem,
410 position: number,
411 visibility: OrchestrationV2ProjectedTurnItem["visibility"] = "local",
412 ): OrchestrationV2ProjectedTurnItem {
413 return {
414 position,
415 visibility,
416 sourceThreadId: visibility === "local" ? threadId : sourceThreadId,
417 sourceItemId: item.id,
418 item,
419 };
420 }
421
422 function userMessage(updatedAt = "2026-06-20T00:00:01.000Z") {
423 return {
424 ...base("item-user", updatedAt, 0),
425 type: "user_message" as const,
426 messageId: MessageId.make("message-user"),
427 createdBy: "user" as const,
428 creationSource: "mobile" as const,
429 inputIntent: "turn_start" as const,
430 text: "Run checks",
431 attachments: [],
432 };
433 }
434
435 function command(updatedAt = "2026-06-20T00:00:02.000Z") {
436 return {
437 ...base("item-command", updatedAt, 1),
438 type: "command_execution" as const,
439 input: "vp check",
440 output: "ok",
441 exitCode: 0,
442 };
443 }
444
445 function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") {
446 return {
447 ...base("item-assistant", updatedAt, 2),
448 type: "assistant_message" as const,
449 messageId: MessageId.make("message-assistant"),
450 text: "Done",
451 streaming: false,
452 };
453 }
454
455 describe("buildThreadFeed", () => {
456 it("keeps async answers in question history instead of user bubbles", () => {
457 const requestId = RuntimeRequestId.make("question");
458 const question: OrchestrationV2TurnItem = {
459 ...base("question", "2026-06-20T00:00:01.000Z", 0),
460 type: "user_input_request",
461 requestId,
462 questions: [],
463 questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} },
464 };
465 const reply: OrchestrationV2TurnItem = {
466 ...userMessage(),
467 id: TurnItemId.make("answer"),
468 messageId: MessageId.make(`async-answer:${requestId}`),
469 };
470 const feed = buildThreadFeed([projected(question, 0), projected(reply, 1)]);
471 expect(feed).toHaveLength(1);
472 expect(feed[0]).toMatchObject({
473 type: "activity-group",
474 activities: [{ workEntry: { questionAnswer: question.questionAnswer } }],
475 });
476 expect(buildThreadFeed([projected(reply, 0)])[0]?.type).toBe("message");
477 });
478
479 it.each([false, true])(
480 "shows an async answer that started a later run where that run begins (cache: %s)",
481 (cached) => {
482 const requestId = RuntimeRequestId.make("late-question");
483 const inRun = (item: OrchestrationV2TurnItem, run: string, position: number) =>
484 projected({ ...item, runId: RunId.make(run) }, position);
485 const message = (id: string, role: "user" | "assistant"): OrchestrationV2TurnItem => ({
486 ...(role === "user" ? userMessage() : assistantMessage()),
487 id: TurnItemId.make(id),
488 messageId: MessageId.make(id),
489 });
490 const answerMessageId = `async-answer:${requestId}`;
491 const settledPrefix = [
492 inRun(
493 {
494 ...base("late-question", "2026-06-20T00:00:01.000Z", 0),
495 type: "user_input_request",
496 requestId,
497 questions: [],
498 questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} },
499 },
500 "run-8",
501 0,
502 ),
503 inRun(message("queued", "user"), "run-9", 1),
504 inRun(message("reply-9", "assistant"), "run-9", 2),
505 ];
506 const rows = [
507 ...settledPrefix,
508 inRun(message(answerMessageId, "user"), "run-10", 3),
509 inRun(message("reply-10", "assistant"), "run-10", 4),
510 ];
511 const cache = cached ? createThreadFeedCache() : undefined;
512 if (cache) buildThreadFeed(settledPrefix, { cache });
513 expect(
514 buildThreadFeed(rows, { cache }).flatMap((entry) =>
515 entry.type === "message" ? [entry.id] : [],
516 ),
517 ).toEqual(["queued", "reply-9", answerMessageId, "reply-10"]);
518 },
519 );
520
521 it.each([false, true])(
522 "keeps answered questions outside settled work (attachments only: %s)",
523 (attachmentsOnly) => {
524 const requestId = RuntimeRequestId.make("answered-question");
525 const question: OrchestrationV2TurnItem = {
526 ...base("answered-question", "2026-06-20T00:00:02.500Z", 2),
527 type: "user_input_request",
528 requestId,
529 questions: [],
530 questionAnswer: {
531 requestId,
532 questionTextById: { color: "Which color?" },
533 answers: { color: attachmentsOnly ? "" : "Blue" },
534 attachmentsByQuestionId: attachmentsOnly
535 ? {
536 color: [
537 {
538 type: "file",
539 id: "color-file",
540 name: "color.txt",
541 mimeType: "text/plain",
542 sizeBytes: 4,
543 },
544 ],
545 }
546 : {},
547 },
548 };
549 const feed = buildThreadFeed([
550 projected(userMessage(), 0),
551 projected(command(), 1),
552 projected(question, 2),
553 projected(assistantMessage(), 3),
554 ]);
555 const presented = deriveThreadFeedPresentation(feed, null, new Set());
556 expect(presented.map((entry) => entry.type)).toEqual([
557 "message",
558 "run-fold",
559 "activity-group",
560 "message",
561 ]);
562 expect(presented[2]).toMatchObject({
563 activities: [{ workEntry: { questionAnswer: question.questionAnswer } }],
564 });
565 expect(
566 deriveThreadFeedPresentation(feed, null, new Set([runId])).map((entry) => entry.type),
567 ).toEqual(["message", "run-fold", "activity-group", "activity-group", "message"]);
568 },
569 );
570
571 it.each([false, true])(
572 "carries a late checkpoint to only the final answer without changing cached messages (cache: %s)",
573 (cached) => {
574 const cache = cached ? createThreadFeedCache() : undefined;
575 const earlier = {
576 ...assistantMessage(),
577 id: TurnItemId.make("earlier-item"),
578 messageId: MessageId.make("earlier-message"),
579 text: "Working on the files",
580 };
581 const final = assistantMessage("2026-06-20T00:00:04.000Z");
582 const rows = [projected(earlier, 0), projected(final, 1)];
583 const before = buildThreadFeed(rows, { cache });
584 const [summary] = deriveThreadCheckpointSummaries({
585 messages: [earlier, final].map((message) => ({
586 ...message,
587 id: message.messageId,
588 role: "assistant",
589 createdBy: "agent",
590 creationSource: "provider",
591 attachments: [],
592 createdAt: message.startedAt,
593 })),
594 checkpoints: [
595 {
596 id: CheckpointId.make("checkpoint-final"),
597 threadId,
598 scopeId: CheckpointScopeId.make("scope"),
599 runId,
600 nodeId: NodeId.make("node"),
601 parentCheckpointId: null,
602 ordinalWithinScope: 1,
603 appRunOrdinal: 2,
604 ref: CheckpointRef.make("checkpoint-ref"),
605 status: "ready",
606 capturedAt: final.updatedAt,
607 files: [
608 { path: "src/one.ts", kind: "modified", additions: 10, deletions: 2 },
609 { path: "src/two.ts", kind: "added", additions: 5, deletions: 0 },
610 ],
611 },
612 ],
613 });
614 expect(summary).toBeDefined();
615 if (!summary) return;
616 const after = buildThreadFeed(rows, { checkpointSummaries: [summary], cache });
617 expect(after[0]).toBe(before[0]);
618 expect(after[1]).toMatchObject({
619 type: "message",
620 message: { id: final.messageId, checkpointSummary: summary },
621 });
622 expect(before[1]).not.toHaveProperty("message.checkpointSummary");
623 expect(getReviewSectionIdForCheckpoint(summary)).toBe("turn:2");
624 const fallback = deriveThreadFeedPresentation(
625 [after.at(-1)!],
626 null,
627 new Set(),
628 new Set(),
629 null,
630 false,
631 cache,
632 );
633 expect(fallback.at(-1)).toMatchObject({ message: { checkpointSummary: summary } });
634 const workRows = [
635 projected(userMessage(), 0),
636 projected(command(), 1),
637 projected({ ...command(), id: TurnItemId.make("second-command") }, 2),
638 projected(final, 3),
639 ];
640 const workBefore = buildThreadFeed(workRows, { cache });
641 deriveThreadFeedPresentation(workBefore, null, new Set(), new Set(), null, false, cache);
642 const workAfter = buildThreadFeed(workRows, { checkpointSummaries: [summary], cache });
643 for (const expanded of [new Set<RunId>(), new Set([runId])]) {
644 const presented = deriveThreadFeedPresentation(
645 workAfter,
646 null,
647 expanded,
648 new Set(),
649 null,
650 false,
651 cache,
652 );
653 expect(presented.find((entry) => entry.type === "run-fold")).toMatchObject({
654 checkpointSummary: summary,
655 });
656 expect(presented.at(-1)).not.toHaveProperty("message.checkpointSummary");
657 }
658 const active = deriveThreadFeedPresentation(
659 workAfter,
660 {
661 runId,
662 status: "running",
663 startedAt: "2026-06-20T00:00:00.000Z",
664 completedAt: null,
665 },
666 new Set(),
667 new Set(),
668 null,
669 false,
670 cache,
671 );
672 expect(active.find((entry) => entry.type === "work-toggle")).toMatchObject({
673 checkpointSummary: summary,
674 });
675 expect(active.at(-1)).not.toHaveProperty("message.checkpointSummary");
676 expect(workBefore.at(-1)).not.toHaveProperty("message.checkpointSummary");
677
678 for (const checkpoint of [
679 { ...summary, files: [] },
680 ...(["missing", "error", "stale"] as const).map((status) => ({ ...summary, status })),
681 { ...summary, runId: RunId.make("another-run") },
682 { ...summary, assistantMessageId: MessageId.make("unloaded-message") },
683 ]) {
684 expect(buildThreadFeed(rows, { checkpointSummaries: [checkpoint], cache })).toEqual(before);
685 }
686 expect(buildThreadFeed(rows, { cache })).toEqual(before);
687 },
688 );
689
690 it("omits cached tool output and patch bodies from expanded and copied activity", () => {
691 const rawOutput = "RAW_TOOL_OUTPUT";
692 const items: OrchestrationV2TurnItem[] = [
693 { ...command(), output: rawOutput },
694 {
695 ...base("dynamic-output", "2026-06-20T00:00:03.000Z", 2),
696 type: "dynamic_tool",
697 toolName: "example",
698 input: { query: "keep input" },
699 output: { text: rawOutput },
700 },
701 {
702 ...base("file-output", "2026-06-20T00:00:04.000Z", 3),
703 type: "file_change",
704 fileName: "src/example.ts",
705 diffStr: rawOutput,
706 oldStr: rawOutput,
707 newStr: rawOutput,
708 },
709 ];
710 const activities = buildThreadFeed(items.map((item, index) => projected(item, index))).flatMap(
711 (entry) => (entry.type === "activity-group" ? entry.activities : []),
712 );
713 expect(activities).toHaveLength(3);
714 for (const activity of activities) {
715 expect(activity.workEntry.detail).toBeUndefined();
716 expect(activity.getFullDetail()).not.toContain(rawOutput);
717 expect(activity.getCopyText()).not.toContain(rawOutput);
718 }
719 expect(activities[0]?.detail).toBe("vp check");
720 expect(activities[1]?.getFullDetail()).toContain("keep input");
721 expect(activities[2]?.detail).toBe("src/example.ts");
722 expect(items[0]).toMatchObject({ output: rawOutput });
723 });
724
725 it("counts every file of a multi-file patch", () => {
726 const item: OrchestrationV2TurnItem = {
727 ...base("multi-file-change", "2026-06-20T00:00:04.000Z", 3),
728 type: "file_change",
729 fileName: "src/a.ts",
730 changes: [
731 { operation: "update", path: "src/a.ts" },
732 { operation: "add", path: "src/b.ts" },
733 { operation: "update", path: "src/renamed.ts", oldPath: "src/original.ts" },
734 ],
735 };
736 const activity = buildThreadFeed([projected(item, 0)]).flatMap((entry) =>
737 entry.type === "activity-group" ? entry.activities : [],
738 )[0]!;
739 expect(workEntryRowLabel(activity.workEntry)).toBe("src/a.ts +2 more");
740 expect(summarizeToolGroup([activity.workEntry]).summary).toBe("Changed 3 files");
741 });
742
743 it("labels a running command without command text by its status", () => {
744 const item: OrchestrationV2TurnItem = {
745 ...base("commandless", "2026-06-20T00:00:02.000Z", 1),
746 type: "command_execution",
747 title: "Ran command",
748 status: "running",
749 completedAt: null,
750 runId: null,
751 input: "",
752 };
753 const feed = buildThreadFeed([
754 projected({ ...userMessage(), runId: null }, 0),
755 projected(item, 1),
756 ]);
757 const activity = feed.flatMap((entry) =>
758 entry.type === "activity-group" ? entry.activities : [],
759 )[0]!;
760 expect(workEntryRowLabel(activity.workEntry)).toBe("Running command");
761 const presented = deriveThreadFeedPresentation(
762 feed,
763 null,
764 new Set(),
765 new Set(),
766 "2026-06-20T00:00:01.000Z",
767 true,
768 );
769 expect(presented.find((entry) => entry.type === "activity-group")).toMatchObject({
770 activities: [{ live: true, groupStandIn: { label: "Running command" } }],
771 });
772 });
773
774 it("anchors feedback before later committed turns", () => {
775 const laterUser = {
776 ...userMessage("2026-08-29T00:00:05.000Z"),
777 id: TurnItemId.make("item-later-user"),
778 messageId: MessageId.make("message-later-user"),
779 ordinal: 2,
780 text: "Later user turn",
781 };
782 const laterAssistant = {
783 ...assistantMessage("2026-08-29T00:00:04.000Z"),
784 id: TurnItemId.make("item-later-assistant"),
785 messageId: MessageId.make("message-later-assistant"),
786 ordinal: 3,
787 text: "Later assistant turn",
788 };
789 const localMessage = (id: string, role: "user" | "assistant") => ({
790 id: MessageId.make(id),
791 role,
792 text: id,
793 turnId: null,
794 streaming: false,
795 createdAt: "2026-08-29T00:00:03.000Z",
796 updatedAt: "2026-08-29T00:00:03.000Z",
797 });
798 const feed = buildThreadFeed(
799 [
800 projected(userMessage("2026-08-29T00:00:01.000Z"), 0),
801 projected(laterUser, 1),
802 projected(laterAssistant, 2),
803 ],
804 {
805 anchoredMessages: [
806 localMessage("feedback-user", "user"),
807 localMessage("feedback-assistant", "assistant"),
808 localMessage("message-later-user", "user"),
809 ],
810 },
811 );
812 const messages = feed.filter((entry) => entry.type === "message");
813
814 expect(messages.map((entry) => entry.id)).toEqual([
815 "message-user",
816 "feedback-user",
817 "feedback-assistant",
818 "message-later-user",
819 "message-later-assistant",
820 ]);
821 expect(
822 messages
823 .filter((entry) => entry.id.startsWith("feedback-"))
824 .every((entry) => entry.message.projectedItem === undefined),
825 ).toBe(true);
826 });
827
828 it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
829 const rows = [
830 projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
831 projected(command("2026-06-20T00:00:01.000Z"), 1),
832 projected(assistantMessage("2026-06-20T00:00:02.000Z"), 2),
833 ];
834
835 const feed = buildThreadFeed(rows);
836 expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
837 expect(feed.map((entry) => entry.id)).toEqual([
838 "message-user",
839 "local:thread-1:item-command",
840 "message-assistant",
841 ]);
842 const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
843 expect(activity?.projectedItem).toBe(rows[1]);
844 expect(activity?.getFullDetail()).toContain('"input": "vp check"');
845 });
846
847 it("keeps adjacent work from different V2 attempts in separate groups", () => {
848 const firstRootNodeId = NodeId.make("node-attempt-1");
849 const secondRootNodeId = NodeId.make("node-attempt-2");
850 const firstCommand = { ...command(), nodeId: firstRootNodeId };
851 const secondCommand = {
852 ...command("2026-06-20T00:00:03.000Z"),
853 id: TurnItemId.make("item-command-retry"),
854 ordinal: 2,
855 nodeId: secondRootNodeId,
856 };
857 const attempts = [
858 {
859 id: RunAttemptId.make("attempt-1"),
860 runId,
861 attemptOrdinal: 1,
862 rootNodeId: firstRootNodeId,
863 providerInstanceId: ProviderInstanceId.make("provider-instance-1"),
864 providerThreadId: ProviderThreadId.make("provider-thread-1"),
865 providerTurnId: null,
866 reason: "initial",
867 status: "completed",
868 startedAt: DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"),
869 completedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
870 },
871 {
872 id: RunAttemptId.make("attempt-2"),
873 runId,
874 attemptOrdinal: 2,
875 rootNodeId: secondRootNodeId,
876 providerInstanceId: ProviderInstanceId.make("provider-instance-1"),
877 providerThreadId: ProviderThreadId.make("provider-thread-1"),
878 providerTurnId: null,
879 reason: "retry",
880 status: "completed",
881 startedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
882 completedAt: DateTime.makeUnsafe("2026-06-20T00:00:03.000Z"),
883 },
884 ] satisfies ReadonlyArray<OrchestrationV2RunAttempt>;
885
886 const feed = buildThreadFeed([projected(firstCommand, 0), projected(secondCommand, 1)], {
887 attempts,
888 });
889
890 expect(feed).toHaveLength(2);
891 expect(
892 feed.map((entry) =>
893 entry.type === "activity-group" ? entry.activities[0]?.attemptId : null,
894 ),
895 ).toEqual(["attempt-1", "attempt-2"]);
896 });
897
898 it("retains inherited and synthetic rows with their original projected identity", () => {
899 const inherited = projected(command(), 0, "inherited");
900 const { providerThreadId: _providerThreadId, ...forkBase } = base(
901 "item-fork",
902 "2026-06-20T00:00:03.000Z",
903 2,
904 );
905 const synthetic = projected(
906 {
907 ...forkBase,
908 type: "fork",
909 source: { type: "run", threadId: sourceThreadId, runId },
910 targetThreadId: threadId,
911 },
912 1,
913 "synthetic",
914 );
915
916 const feed = buildThreadFeed([inherited, synthetic]);
917 const activities = feed.flatMap((entry) =>
918 entry.type === "activity-group" ? entry.activities : [],
919 );
920 expect(activities.map((activity) => activity.projectedItem)).toEqual([inherited, synthetic]);
921 expect(activities.map((activity) => activity.projectedItem.visibility)).toEqual([
922 "inherited",
923 "synthetic",
924 ]);
925 expect(activities.at(-1)?.prominent).toBe(true);
926 });
927
928 it.each([
929 ["local", undefined],
930 ["inherited", undefined],
931 ["synthetic", undefined],
932 ["synthetic", "Forked from conversation"],
933 ] as const)(
934 "labels a %s fork row with title %s without exposing its target ID",
935 (visibility, title) => {
936 const { providerThreadId: _providerThreadId, ...forkBase } = base(
937 "item-fork",
938 "2026-06-20T00:00:03.000Z",
939 2,
940 );
941 const activity = buildThreadFeed([
942 projected(
943 {
944 ...forkBase,
945 type: "fork",
946 title: title ?? null,
947 source: { type: "run", threadId: sourceThreadId, runId },
948 targetThreadId: threadId,
949 },
950 0,
951 visibility,
952 ),
953 ]).flatMap((entry) => (entry.type === "activity-group" ? entry.activities : []))[0]!;
954
955 expect(workEntryRowLabel(activity.workEntry)).toBe(title ?? "Thread forked");
956 expect(workEntryRowLabel(activity.workEntry, true)).toBe(title ?? "Thread forked");
957 expect(activity.canExpand).toBe(true);
958 expect(activity.getFullDetail()).toContain(threadId);
959 },
960 );
961
962 it("names the fold that hides a progress message, with or without a run", () => {
963 const middle = {
964 ...assistantMessage("2026-06-20T00:00:02.500Z"),
965 id: TurnItemId.make("item-middle"),
966 messageId: MessageId.make("message-middle"),
967 text: "Needle found in the build config.",
968 };
969 const items = [userMessage(), command(), middle, assistantMessage()];
970 for (const runless of [false, true]) {
971 const feed = buildThreadFeed(
972 items.map((item, position) =>
973 projected(runless ? { ...item, runId: null } : item, position),
974 ),
975 );
976 const ids = (expanded: ReadonlySet<RunId>) =>
977 deriveThreadFeedPresentation(feed, null, expanded).map((entry) => entry.id);
978 const foldRunId = messageFoldRunId(
979 feed,
980 "message-middle",
981 deriveThreadFeedPresentation(feed, null, new Set()),
982 );
983 expect(foldRunId, String(runless)).toBe(runless ? "runless:message-user" : runId);
984 expect(ids(new Set())).not.toContain("message-middle");
985 expect(ids(new Set([foldRunId!]))).toContain("message-middle");
986 }
987 expect(
988 messageFoldRunId(buildThreadFeed([projected(userMessage(), 0)]), "message-user", []),
989 ).toBe(null);
990 });
991
992 it("folds progress messages while keeping the final assistant answer visible", () => {
993 const opening = {
994 ...assistantMessage("2026-06-20T00:00:01.500Z"),
995 id: TurnItemId.make("item-opening"),
996 messageId: MessageId.make("message-opening"),
997 text: "I will check the deployment configuration.",
998 };
999 const middle = {
1000 ...assistantMessage("2026-06-20T00:00:02.500Z"),
1001 id: TurnItemId.make("item-middle"),
1002 messageId: MessageId.make("message-middle"),
1003 text: "The configuration is valid; checking the build next.",
1004 };
1005 const feed = buildThreadFeed([
1006 projected(userMessage(), 0),
1007 projected(opening, 1),
1008 projected(command(), 2),
1009 projected(middle, 3),
1010 projected(assistantMessage(), 4),
1011 ]);
1012 const latestRun = {
1013 runId,
1014 status: "completed" as const,
1015 startedAt: "2026-06-20T00:00:01.000Z",
1016 completedAt: "2026-06-20T00:00:03.000Z",
1017 };
1018
1019 const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
1020 expect(collapsed.map((entry) => entry.id)).toEqual([
1021 "message-user",
1022 "run-fold:run-1",
1023 "message-assistant",
1024 ]);
1025 expect(collapsed[1]).toMatchObject({
1026 type: "run-fold",
1027 createdAt: "2026-06-20T00:00:01.500Z",
1028 label: "Worked for 2s",
1029 });
1030
1031 const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
1032 expect(expanded.map((entry) => entry.type)).toEqual([
1033 "message",
1034 "run-fold",
1035 "message",
1036 "activity-group",
1037 "message",
1038 "message",
1039 ]);
1040 const anchor = {
1041 ...command(),
1042 deferredWork: { cursor: "old-work", itemCount: 100, lastOrdinal: 100 },
1043 };
1044 const deferredFeed = buildThreadFeed([projected(userMessage(), 0), projected(anchor, 1)]);
1045 const running = { ...latestRun, status: "running" as const, completedAt: null };
1046 const deferredRows = deriveThreadFeedPresentation(deferredFeed, running, new Set());
1047 const disclosure = deferredRows.find((entry) => entry.type === "run-fold");
1048 expect(disclosure).toMatchObject({ deferredWorkItemIds: [anchor.id], expanded: false });
1049 if (disclosure?.type !== "run-fold") throw new Error("Expected deferred work disclosure");
1050 expect(
1051 deriveThreadFeedPresentation(deferredFeed, running, new Set([disclosure.runId])).some(
1052 (entry) => entry.type === "activity-group",
1053 ),
1054 ).toBe(true);
1055 expect(expanded[4]).toMatchObject({ message: { id: middle.messageId, text: middle.text } });
1056
1057 const active = deriveThreadFeedPresentation(
1058 feed,
1059 { ...latestRun, status: "running", completedAt: null },
1060 new Set(),
1061 );
1062 expect(active.filter((entry) => entry.type === "message").map((entry) => entry.id)).toEqual([
1063 "message-user",
1064 "message-opening",
1065 "message-middle",
1066 "message-assistant",
1067 ]);
1068 });
1069
1070 // regression: #21393 show plans and fold settled progress notes
1071 it("folds progress even when a response has no tool calls", () => {
1072 const feed = buildThreadFeed([
1073 projected(userMessage(), 0),
1074 projected(
1075 {
1076 ...assistantMessage("2026-06-20T00:00:02.000Z"),
1077 id: TurnItemId.make("item-opening"),
1078 messageId: MessageId.make("message-opening"),
1079 text: "The result is ready.",
1080 },
1081 1,
1082 ),
1083 projected(assistantMessage(), 2),
1084 ]);
1085
1086 const presented = deriveThreadFeedPresentation(feed, null, new Set());
1087 expect(presented.map((entry) => entry.id)).toEqual([
1088 "message-user",
1089 "run-fold:run-1",
1090 "message-assistant",
1091 ]);
1092 });
1093
1094 it("splits a settled turn's work fold at a steer", () => {
1095 const steer = {
1096 ...userMessage("2026-06-20T00:00:04.000Z"),
1097 id: TurnItemId.make("item-steer"),
1098 messageId: MessageId.make("message-steer"),
1099 inputIntent: "steer" as const,
1100 };
1101 const after = { ...command("2026-06-20T00:00:06.000Z"), id: TurnItemId.make("item-after") };
1102 const progress = {
1103 ...assistantMessage("2026-06-20T00:00:07.000Z"),
1104 id: TurnItemId.make("item-progress"),
1105 messageId: MessageId.make("message-progress"),
1106 };
1107 const feed = buildThreadFeed(
1108 [
1109 userMessage(),
1110 command(),
1111 steer,
1112 after,
1113 progress,
1114 assistantMessage("2026-06-20T00:00:09.000Z"),
1115 ].map((item, position) => projected(item, position)),
1116 );
1117
1118 expect(
1119 deriveThreadFeedPresentation(feed, null, new Set()).map((entry) =>
1120 entry.type === "message" ? entry.id : entry.type,
1121 ),
1122 ).toEqual(["message-user", "run-fold", "message-steer", "run-fold", "message-assistant"]);
1123 const foldRunId = messageFoldRunId(
1124 feed,
1125 "message-progress",
1126 deriveThreadFeedPresentation(feed, null, new Set()),
1127 );
1128 expect(
1129 deriveThreadFeedPresentation(feed, null, new Set([foldRunId!])).map((entry) =>
1130 entry.type === "message" ? entry.id : entry.type,
1131 ),
1132 ).toEqual([
1133 "message-user",
1134 "run-fold",
1135 "message-steer",
1136 "run-fold",
1137 "activity-group",
1138 "message-progress",
1139 "message-assistant",
1140 ]);
1141
1142 // Hiding tools leaves no output before the steer, so nothing splits there.
1143 const hideAll = (expanded: ReadonlySet<RunId>) =>
1144 deriveThreadFeedPresentation(feed, null, expanded, new Set(), null, false, undefined, {
1145 toolCallVisibility: "hideAll",
1146 revealedMessageId: null,
1147 });
1148 const hiddenToolsFoldRunId = messageFoldRunId(feed, "message-progress", hideAll(new Set()));
1149 expect(hideAll(new Set([hiddenToolsFoldRunId!])).map((entry) => entry.id)).toContain(
1150 "message-progress",
1151 );
1152 });
1153
1154 it("folds subagents while keeping created-thread and fork cards visible", () => {
1155 const { providerThreadId: _providerThreadId, ...forkBase } = base(
1156 "item-fork",
1157 "2026-06-20T00:00:02.000Z",
1158 2,
1159 );
1160 const resourceItems = [
1161 {
1162 ...base("item-subagent", "2026-06-20T00:00:01.500Z", 1),
1163 type: "subagent",
1164 subagentId: NodeId.make("child-agent"),
1165 origin: "app_owned",
1166 driver: ProviderDriverKind.make("codex"),
1167 providerInstanceId: ProviderInstanceId.make("codex"),
1168 childThreadId: sourceThreadId,
1169 prompt: "Inspect the deployment configuration",
1170 result: "Configuration is valid",
1171 },
1172 {
1173 ...forkBase,
1174 type: "fork",
1175 source: { type: "run", threadId, runId },
1176 targetThreadId: sourceThreadId,
1177 },
1178 {
1179 ...base("item-created-thread", "2026-06-20T00:00:04.000Z", 4),
1180 type: "thread_created",
1181 targetThreadId: sourceThreadId,
1182 targetRunId: null,
1183 targetProviderInstanceId: ProviderInstanceId.make("codex"),
1184 targetModel: "gpt-5.4",
1185 },
1186 ] satisfies ReadonlyArray<OrchestrationV2TurnItem>;
1187 const projectedResources = [
1188 projected(resourceItems[0]!, 1),
1189 projected(resourceItems[1]!, 2),
1190 projected(resourceItems[2]!, 4),
1191 ];
1192 const feed = buildThreadFeed([
1193 projected(userMessage(), 0),
1194 projectedResources[0]!,
1195 projectedResources[1]!,
1196 projected(command("2026-06-20T00:00:03.000Z"), 3),
1197 projectedResources[2]!,
1198 projected(assistantMessage("2026-06-20T00:00:05.000Z"), 5),
1199 ]);
1200
1201 const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
1202 expect(collapsed.map((entry) => entry.type)).toEqual([
1203 "message",
1204 "run-fold",
1205 "activity-group",
1206 "activity-group",
1207 "message",
1208 ]);
1209 expect(collapsed[1]).toMatchObject({
1210 type: "run-fold",
1211 createdAt: "2026-06-20T00:00:01.500Z",
1212 });
1213 expect(
1214 collapsed.flatMap((entry) =>
1215 entry.type === "activity-group"
1216 ? entry.activities.map((activity) => activity.projectedItem)
1217 : [],
1218 ),
1219 ).toEqual(projectedResources.slice(1));
1220 const expanded = deriveThreadFeedPresentation(feed, null, new Set([runId]));
1221 expect(
1222 expanded.some(
1223 (entry) =>
1224 entry.type === "activity-group" &&
1225 entry.activities.some((activity) => activity.projectedItem.item.type === "subagent"),
1226 ),
1227 ).toBe(true);
1228 });
1229
1230 it("keeps a settled run's still-running subagents visible while its other work folds", () => {
1231 const subagent = (
1232 id: string,
1233 updatedAt: string,
1234 ordinal: number,
1235 status: OrchestrationV2TurnItem["status"],
1236 ): OrchestrationV2TurnItem => ({
1237 ...base(id, updatedAt, ordinal),
1238 providerTurnId: ProviderTurnId.make("provider-turn-1"),
1239 status,
1240 completedAt: status === "running" ? null : DateTime.makeUnsafe(updatedAt),
1241 type: "subagent",
1242 subagentId: NodeId.make(id),
1243 origin: "app_owned",
1244 driver: ProviderDriverKind.make("codex"),
1245 providerInstanceId: ProviderInstanceId.make("codex"),
1246 childThreadId: sourceThreadId,
1247 prompt: `Inspect ${id}`,
1248 result: null,
1249 });
1250 const latestRun = {
1251 runId,
1252 status: "completed" as const,
1253 startedAt: "2026-06-20T00:00:01.000Z",
1254 completedAt: "2026-06-20T00:00:05.000Z",
1255 };
1256 const present = (children: ReadonlyArray<OrchestrationV2TurnItem>) =>
1257 deriveThreadFeedPresentation(
1258 buildThreadFeed([
1259 projected(userMessage(), 0),
1260 projected(command("2026-06-20T00:00:02.000Z"), 1),
1261 ...children.map((child, index) => projected(child, index + 2)),
1262 projected(assistantMessage("2026-06-20T00:00:05.000Z"), 5),
1263 ]),
1264 latestRun,
1265 new Set(),
1266 );
1267 const visibleSubagentIds = (presented: ReadonlyArray<ThreadFeedEntry>) =>
1268 presented.flatMap((entry) =>
1269 entry.type === "activity-group"
1270 ? entry.activities.flatMap((activity) =>
1271 activity.projectedItem.item.type === "subagent"
1272 ? [activity.projectedItem.item.id]
1273 : [],
1274 )
1275 : [],
1276 );
1277
1278 const live = present([subagent("item-live", "2026-06-20T00:00:03.000Z", 2, "running")]);
1279 expect(live.map((entry) => entry.type)).toEqual([
1280 "message",
1281 "run-fold",
1282 "activity-group",
1283 "message",
1284 ]);
1285 expect(visibleSubagentIds(live)).toEqual(["item-live"]);
1286
1287 const mixed = present([
1288 subagent("item-done", "2026-06-20T00:00:03.000Z", 2, "completed"),
1289 subagent("item-live", "2026-06-20T00:00:04.000Z", 3, "running"),
1290 ]);
1291 expect(visibleSubagentIds(mixed)).toEqual(["item-done", "item-live"]);
1292
1293 const finished = present([subagent("item-done", "2026-06-20T00:00:03.000Z", 2, "completed")]);
1294 expect(finished.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
1295 });
1296
1297 it("folds each run of a provider-native subagent thread like a normal turn", () => {
1298 const runless = <T extends OrchestrationV2TurnItem>(item: T, id: string, ordinal: number) => ({
1299 ...item,
1300 id: TurnItemId.make(id),
1301 runId: null,
1302 ordinal,
1303 });
1304 const prompt = (id: string, ordinal: number, at: string) =>
1305 runless(
1306 { ...userMessage(at), messageId: MessageId.make(id), creationSource: "provider" as const },
1307 id,
1308 ordinal,
1309 );
1310 const answer = (id: string, ordinal: number, at: string) =>
1311 runless({ ...assistantMessage(at), messageId: MessageId.make(id) }, id, ordinal);
1312 const { exitCode: _exitCode, ...completedCommand } = command("2026-06-20T00:01:17.000Z");
1313 const feed = (resumeRunning: boolean) =>
1314 buildThreadFeed(
1315 [
1316 prompt("launch", 1, "2026-06-20T00:00:00.000Z"),
1317 runless(command("2026-06-20T00:00:04.000Z"), "launch-ls", 2),
1318 answer("launch-answer", 3, "2026-06-20T00:00:08.000Z"),
1319 prompt("resume", 4, "2026-06-20T00:01:12.000Z"),
1320 resumeRunning
1321 ? runless(
1322 { ...completedCommand, status: "running", completedAt: null, output: "" },
1323 "resume-ls",
1324 5,
1325 )
1326 : runless(command("2026-06-20T00:01:17.000Z"), "resume-ls", 5),
1327 ...(resumeRunning ? [] : [answer("resume-answer", 6, "2026-06-20T00:01:20.000Z")]),
1328 ].map((item, position) => projected(item, position)),
1329 );
1330 const shape = (entries: ReadonlyArray<ThreadFeedEntry>) =>
1331 entries.map((entry) =>
1332 entry.type === "run-fold"
1333 ? `fold:${entry.label}`
1334 : entry.type === "message"
1335 ? `${entry.message.role}:${entry.message.id}`
1336 : entry.type,
1337 );
1338
1339 const settled = deriveThreadFeedPresentation(feed(false), null, new Set());
1340 expect(shape(settled)).toEqual([
1341 "user:launch",
1342 "fold:Worked for 8s",
1343 "assistant:launch-answer",
1344 "user:resume",
1345 "fold:Worked for 8s",
1346 "assistant:resume-answer",
1347 ]);
1348 const launchFold = settled.find((entry) => entry.type === "run-fold");
1349 if (launchFold?.type !== "run-fold") throw new Error("Expected the launch fold");
1350 expect(
1351 shape(deriveThreadFeedPresentation(feed(false), null, new Set([launchFold.runId]))),
1352 ).toEqual([
1353 "user:launch",
1354 "fold:Worked for 8s",
1355 "activity-group",
1356 "assistant:launch-answer",
1357 "user:resume",
1358 "fold:Worked for 8s",
1359 "assistant:resume-answer",
1360 ]);
1361
1362 const working = deriveThreadFeedPresentation(
1363 feed(true),
1364 null,
1365 new Set(),
1366 new Set(),
1367 "2026-06-20T00:01:12.000Z",
1368 true,
1369 );
1370 expect(shape(working)).toEqual([
1371 "user:launch",
1372 "fold:Worked for 8s",
1373 "assistant:launch-answer",
1374 "user:resume",
1375 "fold:Working",
1376 "activity-group",
1377 ]);
1378 // The live timer row becomes the settled fold in place.
1379 expect(working[4]?.id).toBe(settled[4]?.id);
1380 });
1381
1382 it("keeps imported V1 turns folded once the thread's first V2 run starts", () => {
1383 const imported = <T extends OrchestrationV2TurnItem>(item: T, id: string) => ({
1384 ...item,
1385 id: TurnItemId.make(id),
1386 runId: null,
1387 });
1388 const presented = (start: OrchestrationV2TurnItem) =>
1389 deriveThreadFeedPresentation(
1390 buildThreadFeed(
1391 [
1392 imported(userMessage("2026-06-20T00:00:00.000Z"), "imported-prompt"),
1393 imported(
1394 {
1395 ...assistantMessage("2026-06-20T00:00:02.000Z"),
1396 messageId: MessageId.make("update"),
1397 },
1398 "imported-update",
1399 ),
1400 imported(command("2026-06-20T00:00:04.000Z"), "imported-ls"),
1401 imported(
1402 {
1403 ...assistantMessage("2026-06-20T00:00:08.000Z"),
1404 messageId: MessageId.make("answer"),
1405 },
1406 "imported-answer",
1407 ),
1408 start,
1409 ].map((item, position) => projected(item, position)),
1410 ),
1411 { runId, status: "running", startedAt: "2026-06-20T00:01:00.000Z", completedAt: null },
1412 new Set(),
1413 new Set(),
1414 "2026-06-20T00:01:00.000Z",
1415 )
1416 .slice(0, 3)
1417 .map((entry) => (entry.type === "message" ? entry.message.role : entry.type));
1418
1419 expect(
1420 presented({
1421 ...userMessage("2026-06-20T00:01:00.000Z"),
1422 id: TurnItemId.make("new-prompt"),
1423 messageId: MessageId.make("new-prompt"),
1424 }),
1425 ).toEqual(["user", "run-fold", "assistant"]);
1426 expect(
1427 presented({
1428 ...base("wake", "2026-06-20T00:01:00.000Z", 4),
1429 type: "notification",
1430 source: { kind: "background_task" },
1431 outcome: "completed",
1432 summary: "Background task finished",
1433 }),
1434 ).toEqual(["user", "run-fold", "assistant"]);
1435 });
1436
1437 it("keeps a provider-native subagent's runless tool call live while it works", () => {
1438 const startedAt = "2026-06-20T00:00:01.000Z";
1439 const { exitCode: _exitCode, ...completedCommand } = command();
1440 const runningCommand: OrchestrationV2TurnItem = {
1441 ...completedCommand,
1442 runId: null,
1443 status: "running",
1444 completedAt: null,
1445 output: "",
1446 };
1447 const feed = buildThreadFeed([
1448 projected({ ...userMessage(), runId: null }, 0),
1449 projected(runningCommand, 1),
1450 ]);
1451
1452 const presented = deriveThreadFeedPresentation(
1453 feed,
1454 null,
1455 new Set(),
1456 new Set(),
1457 startedAt,
1458 true,
1459 );
1460 expect(presented.find((entry) => entry.type === "activity-group")).toMatchObject({
1461 id: "live-activity-row",
1462 activities: [{ live: true, groupStandIn: { label: "Running vp" } }],
1463 });
1464 expect(presented.some((entry) => entry.type === "thinking")).toBe(false);
1465 });
1466
1467 it("does not show Thinking once the open run's provider turn has ended", () => {
1468 const startedAt = "2026-04-01T00:00:01.000Z";
1469 const run = { runId, status: "running" as const, startedAt, completedAt: null };
1470 expect(
1471 deriveThreadFeedPresentation(
1472 [],
1473 { ...run, turnEnded: true },
1474 new Set(),
1475 new Set(),
1476 startedAt,
1477 ).map((row) => row.type),
1478 ).toEqual(["run-fold"]);
1479 });
1480 it("hides tool calls or everything but the final answer", () => {
1481 const at = (second: number) => `2026-06-20T00:00:${String(second).padStart(2, "0")}.000Z`;
1482 const say = (name: string, second: number, user = false, steer = false) => ({
1483 ...(user ? userMessage(at(second)) : assistantMessage(at(second))),
1484 id: TurnItemId.make(name),
1485 messageId: MessageId.make(name),
1486 text: name,
1487 ...(steer ? { inputIntent: "steer" as const } : {}),
1488 });
1489 const ran = (name: string, second: number, status: "completed" | "failed") => ({
1490 ...command(at(second)),
1491 id: TurnItemId.make(name),
1492 status,
1493 });
1494 const [user, step, passed, failed, final] = [
1495 say("user", 1, true),
1496 say("step", 2),
1497 ran("passed", 3, "completed"),
1498 ran("failed", 4, "failed"),
1499 say("final", 5),
1500 ];
1501 const running = { runId, status: "running" as const, startedAt: at(1), completedAt: null };
1502 const rows = (
1503 items: ReadonlyArray<OrchestrationV2TurnItem>,
1504 toolCallVisibility: "hideSuccessful" | "hideAll" | "zen",
1505 latestRun: ThreadFeedLatestRun | null = null,
1506 ) =>
1507 deriveThreadFeedPresentation(
1508 buildThreadFeed(items.map((item, index) => projected(item, index))),
1509 latestRun,
1510 new Set([runId]),
1511 new Set(),
1512 latestRun ? at(1) : null,
1513 false,
1514 undefined,
1515 { toolCallVisibility, revealedMessageId: null },
1516 ).map((row) =>
1517 row.type === "activity-group"
1518 ? row.activities.map((activity) => activity.projectedItem.item.id).join("+")
1519 : row.type === "thinking"
1520 ? `thinking:${row.label ?? ""}`
1521 : row.type === "run-fold"
1522 ? "fold"
1523 : row.id,
1524 );
1525
1526 const turn = [user, step, passed, failed, final];
1527 expect(rows(turn, "hideSuccessful")).toEqual(["user", "fold", "step", "failed", "final"]);
1528 expect(rows(turn, "hideAll")).toEqual(["user", "fold", "step", "final"]);
1529 expect(rows(turn, "zen")).toEqual(["user", "final"]);
1530 const [steer, answer] = [say("steer", 2, true, true), say("answer", 3)];
1531 expect(rows([user, steer, answer, final], "zen")).toEqual(["user", "steer", "answer", "final"]);
1532 const commentary = { ...step, phase: "commentary" as const };
1533 expect(rows([user, commentary, steer, final], "zen")).toEqual(["user", "steer", "final"]);
1534 for (const phase of ["commentary", "partial_answer", "final_answer", undefined] as const) {
1535 const partial = { ...answer, ...(phase === undefined ? {} : { phase }) };
1536 const interrupted = buildThreadFeed(
1537 [user, passed, partial, steer, final].map((item, index) => projected(item, index)),
1538 );
1539 expect(
1540 deriveThreadFeedPresentation(interrupted, null, new Set()).some(
1541 (row) => row.type === "message" && row.message.id === answer.messageId,
1542 ),
1543 ).toBe(phase === "final_answer");
1544 expect(rows([user, partial, steer, final], "zen").includes("answer")).toBe(
1545 phase === "final_answer",
1546 );
1547 }
1548 const confirmed = { ...answer, phase: "final_answer" as const };
1549 const continued = buildThreadFeed(
1550 [user, confirmed, passed, final].map((item, index) => projected(item, index)),
1551 );
1552 expect(
1553 deriveThreadFeedPresentation(continued, null, new Set()).some(
1554 (row) => row.type === "message" && row.message.id === answer.messageId,
1555 ),
1556 ).toBe(true);
1557 expect(rows([user, confirmed, passed, final], "zen")).toEqual(["user", "answer", "final"]);
1558 expect(rows([user, steer, step, passed, final], "zen")).toEqual(["user", "steer", "final"]);
1559 expect(rows([user, steer, answer, step], "zen", running)).toEqual([
1560 "user",
1561 "steer",
1562 "answer",
1563 "thinking:step",
1564 ]);
1565 expect(rows([user, step, passed], "zen", running)).toEqual(["user", "thinking:step"]);
1566 expect(rows(turn, "zen", { ...running, turnEnded: true })).toEqual(["user", "final"]);
1567 const nextRun = { ...running, runId: RunId.make("run-2") };
1568 const followUp = { ...say("follow-up", 6, true), runId: nextRun.runId };
1569 expect(rows([...turn, followUp], "zen", nextRun)).toEqual([
1570 "user",
1571 "final",
1572 "follow-up",
1573 "thinking:",
1574 ]);
1575 const wake: OrchestrationV2TurnItem = {
1576 ...base("wake", at(6), 5),
1577 runId: nextRun.runId,
1578 type: "notification",
1579 source: { kind: "background_task" },
1580 outcome: "completed",
1581 summary: "Task finished",
1582 };
1583 expect(rows([user, final, wake], "zen", nextRun)).toEqual([
1584 "user",
1585 "final",
1586 "wake",
1587 "thinking:",
1588 ]);
1589 });
1590 });
1591
1592 describe("retained v2 feed presentation", () => {
1593 it("retains unchanged rows while the assistant streams", () => {
1594 const rows = [
1595 projected(userMessage(), 0),
1596 projected(command(), 1),
1597 projected({ ...assistantMessage(), streaming: true }, 2),
1598 ];
1599 const latestRun = {
1600 runId,
1601 status: "running" as const,
1602 startedAt: "2026-06-20T00:00:01.000Z",
1603 completedAt: null,
1604 };
1605 const before = buildThreadFeed(rows);
1606 const beforePresentation = deriveThreadFeedPresentation(
1607 before,
1608 latestRun,
1609 new Set(),
1610 new Set(),
1611 latestRun.startedAt,
1612 );
1613 const after = buildThreadFeed([
1614 rows[0]!,
1615 rows[1]!,
1616 projected(
1617 { ...assistantMessage("2026-06-20T00:00:04.000Z"), text: "Still working", streaming: true },
1618 2,
1619 ),
1620 ]);
1621 const afterPresentation = deriveThreadFeedPresentation(
1622 after,
1623 latestRun,
1624 new Set(),
1625 new Set(),
1626 latestRun.startedAt,
1627 );
1628 expect(after[0]).toBe(before[0]);
1629 expect(after[1]).toBe(before[1]);
1630 expect(after[2]).not.toBe(before[2]);
1631 expect(afterPresentation[0]).toBe(beforePresentation[0]);
1632 expect(afterPresentation[1]).toBe(beforePresentation[1]);
1633 });
1634
1635 it.each([
1636 { envelope: "direct", output: { taskId: "a" } },
1637 { envelope: "structured", output: { structuredContent: { taskId: "a" } } },
1638 { envelope: "text", output: { content: [{ type: "text", text: '{"taskId":"a"}' }] } },
1639 ])(
1640 "folds matched $envelope delegations without hiding pending, failed or unmatched calls",
1641 ({ output }) => {
1642 const agent = (
1643 id: string,
1644 index: number,
1645 origin = "app_owned" as "app_owned" | "provider_native",
1646 ) =>
1647 projected(
1648 {
1649 ...base(id, "2026-06-20T00:00:01.000Z", index),
1650 type: "subagent",
1651 subagentId: NodeId.make(id),
1652 origin,
1653 driver: ProviderDriverKind.make("codex"),
1654 providerInstanceId: ProviderInstanceId.make("codex"),
1655 childThreadId: ThreadId.make(`child-${id}`),
1656 prompt: "Identical task",
1657 result: "Done",
1658 },
1659 index,
1660 );
1661 const delegation = (
1662 id: string,
1663 index: number,
1664 overrides: Partial<Extract<OrchestrationV2TurnItem, { type: "dynamic_tool" }>> = {},
1665 ) =>
1666 projected(
1667 {
1668 ...base(id, "2026-06-20T00:00:02.000Z", index),
1669 type: "dynamic_tool",
1670 toolName: "t3-code.delegate_task",
1671 input: { task: "Identical task" },
1672 output,
1673 ...overrides,
1674 },
1675 index,
1676 );
1677 const feed = buildThreadFeed([
1678 agent("a", 1),
1679 delegation("matched", 2),
1680 agent("b", 3),
1681 delegation("pending", 4, { status: "running", output: null }),
1682 delegation("unmatched", 5, { output: { taskId: "missing" } }),
1683 delegation("failed", 6, { status: "failed" }),
1684 delegation("error-output", 7, { output: { taskId: "a", isError: true } }),
1685 delegation("other-run", 8, { runId: RunId.make("other-run") }),
1686 agent("native", 9, "provider_native"),
1687 delegation("native-delegation", 10, { output: { taskId: "native" } }),
1688 ]);
1689 const groups = feed.flatMap((entry) =>
1690 entry.type === "activity-group"
1691 ? [entry.activities.map((activity) => activity.projectedItem.item.id)]
1692 : [],
1693 );
1694 expect(groups[0]).toEqual(["a", "b"]);
1695 expect(groups.flat()).toEqual([
1696 "a",
1697 "b",
1698 "pending",
1699 "unmatched",
1700 "failed",
1701 "error-output",
1702 "other-run",
1703 "native",
1704 "native-delegation",
1705 ]);
1706 const presented = deriveThreadFeedPresentation(
1707 feed,
1708 null,
1709 new Set([runId, RunId.make("other-run")]),
1710 );
1711 expect(
1712 presented.find(
1713 (entry) =>
1714 entry.type === "activity-group" && entry.activities[0]?.projectedItem.item.id === "a",
1715 )?.continuesWorkLog,
1716 ).toBeUndefined();
1717 },
1718 );
1719
1720 it("groups only adjacent subagents in the same run, keeping their child links", () => {
1721 const agent = (id: string, index: number, agentRunId = runId) =>
1722 projected(
1723 {
1724 ...base(id, `2026-06-20T00:00:0${index}.000Z`, index),
1725 type: "subagent",
1726 runId: agentRunId,
1727 subagentId: NodeId.make(id),
1728 origin: "app_owned",
1729 driver: ProviderDriverKind.make("codex"),
1730 providerInstanceId: ProviderInstanceId.make("codex"),
1731 childThreadId: ThreadId.make(`child-${id}`),
1732 prompt: "Solve the puzzle",
1733 result: "Done",
1734 },
1735 index,
1736 );
1737 const feed = buildThreadFeed([
1738 agent("a", 1),
1739 agent("b", 2),
1740 projected(command("2026-06-20T00:00:03.000Z"), 3),
1741 agent("c", 4),
1742 agent("d", 5, RunId.make("other-run")),
1743 ]);
1744 expect(
1745 feed.flatMap((entry) =>
1746 entry.type === "activity-group"
1747 ? [entry.activities.map((activity) => activity.projectedItem.item.id)]
1748 : [],
1749 ),
1750 ).toEqual([["a", "b"], ["item-command"], ["c"], ["d"]]);
1751 const presented = deriveThreadFeedPresentation(
1752 feed,
1753 null,
1754 new Set([runId, RunId.make("other-run")]),
1755 );
1756 const groups = presented.flatMap((entry) =>
1757 entry.type === "activity-group" && entry.activities[0]?.projectedItem.item.type === "subagent"
1758 ? [entry]
1759 : [],
1760 );
1761 expect(groups.map((entry) => entry.activities.length)).toEqual([2, 1, 1]);
1762 expect(groups[0]?.activities.map((activity) => activity.projectedItem.item)).toMatchObject([
1763 { childThreadId: "child-a" },
1764 { childThreadId: "child-b" },
1765 ]);
1766 });
1767 });
1768
1769 describe("subagent continued by a later turn", () => {
1770 const run2 = RunId.make("run-2");
1771 const at = (second: number) => `2026-10-09T10:00:${String(second).padStart(2, "0")}.000Z`;
1772 const item = (id: string, itemRunId: RunId, ordinal: number, second: number) => ({
1773 ...base(id, at(second), ordinal),
1774 runId: itemRunId,
1775 });
1776 const user = (id: string, itemRunId: RunId, ordinal: number, second: number) => ({
1777 ...item(id, itemRunId, ordinal, second),
1778 type: "user_message" as const,
1779 messageId: MessageId.make(id),
1780 createdBy: "user" as const,
1781 creationSource: "mobile" as const,
1782 inputIntent: "turn_start" as const,
1783 text: `Prompt ${id}`,
1784 attachments: [],
1785 });
1786 const assistant = (id: string, itemRunId: RunId, ordinal: number, second: number) => ({
1787 ...item(id, itemRunId, ordinal, second),
1788 type: "assistant_message" as const,
1789 messageId: MessageId.make(id),
1790 text: `Answer ${id}`,
1791 streaming: false,
1792 });
1793 const reasoning = (id: string, itemRunId: RunId, ordinal: number, second: number) => ({
1794 ...item(id, itemRunId, ordinal, second),
1795 type: "reasoning" as const,
1796 text: "Thinking",
1797 streaming: false,
1798 });
1799 const items: OrchestrationV2TurnItem[] = [
1800 user("prompt-1", runId, 1_000_001, 0),
1801 reasoning("reasoning-1", runId, 1_000_002, 1),
1802 {
1803 ...item("subagent", run2, 1_000_003, 2),
1804 type: "subagent",
1805 subagentId: NodeId.make("subagent"),
1806 origin: "provider_native",
1807 driver: ProviderDriverKind.make("claudeAgent"),
1808 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
1809 childThreadId: null,
1810 prompt: "Research the bug",
1811 result: "Found it",
1812 },
1813 assistant("answer-1", runId, 1_000_004, 3),
1814 user("prompt-2", run2, 2_000_001, 30),
1815 reasoning("reasoning-2", run2, 2_000_002, 31),
1816 assistant("answer-2", run2, 2_000_003, 32),
1817 {
1818 ...item("send-message", run2, 2_000_004, 33),
1819 type: "dynamic_tool",
1820 toolName: "SendMessage",
1821 input: { to: "subagent" },
1822 output: "Sent",
1823 },
1824 assistant("closing-2", run2, 2_000_005, 41),
1825 ];
1826
1827 it("keeps each turn's fold between its own prompt and answer", () => {
1828 const feed = buildThreadFeed(items.map((entry, index) => projected(entry, index)));
1829 const presented = deriveThreadFeedPresentation(
1830 feed,
1831 { runId: run2, status: "completed", startedAt: at(30), completedAt: at(41) },
1832 new Set(),
1833 );
1834 expect(presented.map((entry) => entry.id)).toEqual([
1835 "prompt-1",
1836 `run-fold:${runId}`,
1837 "answer-1",
1838 "prompt-2",
1839 `run-fold:${run2}`,
1840 "closing-2",
1841 ]);
1842
1843 // While the run works, its fold row already holds that slot with a live timer.
1844 const live = deriveThreadFeedPresentation(
1845 feed,
1846 { runId: run2, status: "running", startedAt: at(30), completedAt: null },
1847 new Set(),
1848 new Set(),
1849 at(30),
1850 );
1851 expect(live.slice(3, 6).map((entry) => entry.id)).toEqual([
1852 "prompt-2",
1853 `run-fold:${run2}`,
1854 expect.not.stringMatching(/^run-fold:/),
1855 ]);
1856 expect(live[4]).toMatchObject({ workingSince: at(30) });
1857 expect(live.filter((entry) => entry.type === "run-fold")).toHaveLength(2);
1858 });
1859
1860 it("puts the live fold after a plan the settled fold leaves in view", () => {
1861 const planned = buildThreadFeed(
1862 [
1863 user("prompt", run2, 1, 0),
1864 {
1865 ...item("plan", run2, 2, 1),
1866 type: "proposed_plan",
1867 planId: "plan",
1868 markdown: "The plan",
1869 streaming: false,
1870 } as OrchestrationV2TurnItem,
1871 reasoning("reasoning", run2, 3, 2),
1872 assistant("closing", run2, 4, 9),
1873 ].map((entry, index) => projected(entry, index)),
1874 );
1875 const ids = (running: boolean) =>
1876 deriveThreadFeedPresentation(
1877 planned,
1878 running
1879 ? { runId: run2, status: "running", startedAt: at(0), completedAt: null }
1880 : { runId: run2, status: "completed", startedAt: at(0), completedAt: at(9) },
1881 new Set(),
1882 new Set(),
1883 running ? at(0) : null,
1884 ).map((entry) => entry.id);
1885 const settledIds = ids(false);
1886 const foldIndex = settledIds.indexOf(`run-fold:${run2}`);
1887 expect(foldIndex).toBeGreaterThan(1);
1888 expect(ids(true).indexOf(`run-fold:${run2}`)).toBe(foldIndex);
1889 });
1890 });
1891
1892 it("stops stranded thinking after a steer and follows the next thought or tool", () => {
1893 const at = "2026-06-20T00:00:02.000Z";
1894 const thought = (id: string): OrchestrationV2TurnItem => ({
1895 ...base(id, at, 1),
1896 type: "reasoning",
1897 status: "running",
1898 completedAt: null,
1899 streaming: true,
1900 text: id,
1901 });
1902 const first = thought("first-thought");
1903 const next = thought("next-thought");
1904 const steer = { ...userMessage(at), inputIntent: "steer" as const };
1905 const tool = { ...command(at), status: "running" as const, completedAt: null };
1906 const rows = (items: ReadonlyArray<OrchestrationV2TurnItem>, expanded = new Set<string>()) =>
1907 deriveThreadFeedPresentation(
1908 buildThreadFeed(items.map((item, position) => projected(item, position))),
1909 { runId, status: "running", startedAt: at, completedAt: null },
1910 new Set(),
1911 expanded,
1912 at,
1913 );
1914 expect(rows([first]).find((row) => row.type === "work-toggle")).toMatchObject({
1915 summary: "Thinking",
1916 thought: "first-thought",
1917 live: true,
1918 shimmer: true,
1919 });
1920 const afterSteer = rows([first, steer]);
1921 expect(afterSteer.find((row) => row.type === "work-toggle")).toMatchObject({
1922 live: false,
1923 shimmer: false,
1924 });
1925 expect(afterSteer.at(-1)?.type).toBe("thinking");
1926 const header = afterSteer.find((row) => row.type === "work-toggle");
1927 if (header?.type !== "work-toggle") throw new Error("Expected thought toggle");
1928 const expanded = rows([first, steer], new Set([header.groupId]));
1929 expect(expanded.find((row) => row.type === "work-toggle")).toMatchObject({ summary: "Thought" });
1930 expect(expanded.find((row) => row.type === "activity-group")).toMatchObject({
1931 activities: [{ lifecycleStatus: "completed", workEntry: { toolLifecycleStatus: "completed" } }],
1932 });
1933 for (const items of [
1934 [first, steer, next],
1935 [first, next],
1936 [first, steer, next, tool],
1937 ]) {
1938 const live = rows(items).filter((row) => row.type === "work-toggle" && row.shimmer);
1939 expect(live).toHaveLength(1);
1940 expect(live[0]).toMatchObject(
1941 items.at(-1)!.type === "reasoning"
1942 ? { summary: "Thinking", thought: "next-thought" }
1943 : { summary: "Running vp" },
1944 );
1945 }
1946 expect(first.status).toBe("running");
1947 });
1948
1949 it.each(["provider_error", "usage_limit"] as const)(
1950 "keeps a historical %s failure and preceding work visible without disclosures",
1951 (failureClass) => {
1952 const at = "2026-06-20T00:00:03.000Z";
1953 const error: OrchestrationV2TurnItem = {
1954 ...base("failure", at, 2),
1955 type: "error",
1956 status: "failed",
1957 failure: {
1958 class: failureClass,
1959 message: "The provider stopped this turn.\nRetry later.",
1960 code: null,
1961 retryable: true,
1962 },
1963 };
1964 const command: OrchestrationV2TurnItem = {
1965 ...base("command", "2026-06-20T00:00:02.000Z", 1),
1966 type: "command_execution",
1967 input: "pwd",
1968 output: "",
1969 exitCode: 0,
1970 };
1971 const sourceFeed = buildThreadFeed([
1972 projected(userMessage(), 0),
1973 projected(command, 1),
1974 projected(error, 2),
1975 ]);
1976 const feed = deriveThreadFeedPresentation(
1977 sourceFeed,
1978 { runId: RunId.make("newer-run"), status: "completed", startedAt: at, completedAt: at },
1979 new Set(),
1980 );
1981 const whileWorking = deriveThreadFeedPresentation(
1982 sourceFeed,
1983 { runId: RunId.make("newer-run"), status: "running", startedAt: at, completedAt: null },
1984 new Set(),
1985 );
1986 for (const entry of feed) {
1987 expect(whileWorking.find((row) => row.id === entry.id)).toBe(entry);
1988 }
1989 expect(feed.some((entry) => entry.type === "run-fold" || entry.type === "work-toggle")).toBe(
1990 false,
1991 );
1992 const activities = feed.flatMap((entry) =>
1993 entry.type === "activity-group" ? entry.activities : [],
1994 );
1995 expect(activities.map((activity) => activity.projectedItem.item.id)).toEqual([
1996 "command",
1997 "failure",
1998 ]);
1999 expect(activities.at(-1)).toMatchObject({
2000 detail: error.failure.message,
2001 createdAt: at,
2002 canExpand: false,
2003 prominent: true,
2004 });
2005 },
2006 );
2007
2008 describe("streamed feed updates", () => {
2009 const runs = [RunId.make("run-1"), RunId.make("run-2"), RunId.make("run-3")] as const;
2010 const at = (second: number) => `2026-06-20T00:00:${String(second).padStart(2, "0")}.000Z`;
2011 const item = (id: string, second: number, run: RunId) => ({
2012 ...base(id, at(second), second),
2013 runId: run,
2014 });
2015 const user = (
2016 id: string,
2017 second: number,
2018 run: RunId,
2019 ): Extract<OrchestrationV2TurnItem, { type: "user_message" }> => ({
2020 ...item(id, second, run),
2021 type: "user_message",
2022 messageId: MessageId.make(`message-${id}`),
2023 createdBy: "user",
2024 creationSource: "mobile",
2025 inputIntent: "turn_start",
2026 text: `Prompt ${id}`,
2027 attachments: [],
2028 });
2029 const reply = (id: string, second: number, run: RunId, text = "Done", streaming = false) =>
2030 ({
2031 ...item(id, second, run),
2032 ...(streaming ? { status: "running" as const, completedAt: null } : {}),
2033 type: "assistant_message",
2034 messageId: MessageId.make(`message-${id}`),
2035 text,
2036 streaming,
2037 }) satisfies OrchestrationV2TurnItem;
2038 const shell = (id: string, second: number, run: RunId): OrchestrationV2TurnItem => ({
2039 ...item(id, second, run),
2040 type: "command_execution",
2041 input: `echo ${id}`,
2042 output: id,
2043 exitCode: 0,
2044 });
2045 const requestId = RuntimeRequestId.make("request-color");
2046 const question = (answered: boolean): OrchestrationV2TurnItem => ({
2047 ...item("question", 12, runs[1]),
2048 type: "user_input_request",
2049 requestId,
2050 questions: [],
2051 ...(answered
2052 ? { questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} } }
2053 : {}),
2054 });
2055 const answer: OrchestrationV2TurnItem = {
2056 ...user("answer", 40, runs[1]),
2057 messageId: MessageId.make(`async-answer:${requestId}`),
2058 };
2059 const delegation: OrchestrationV2TurnItem = {
2060 ...item("delegation", 3, runs[0]),
2061 type: "dynamic_tool",
2062 toolName: "t3-code.delegate_task",
2063 input: { task: "Check" },
2064 output: { taskId: "child" },
2065 };
2066 const lateChild: OrchestrationV2TurnItem = {
2067 ...item("late-child", 30, runs[0]),
2068 type: "subagent",
2069 subagentId: NodeId.make("child"),
2070 origin: "app_owned",
2071 driver: ProviderDriverKind.make("codex"),
2072 providerInstanceId: ProviderInstanceId.make("codex"),
2073 childThreadId: sourceThreadId,
2074 prompt: "Check",
2075 result: "Fine",
2076 };
2077 const resumed: OrchestrationV2TurnItem = {
2078 ...lateChild,
2079 ...item("resumed", 3, runs[2]),
2080 subagentId: NodeId.make("resumed"),
2081 origin: "provider_native",
2082 childThreadId: null,
2083 };
2084 const history: OrchestrationV2TurnItem[] = [
2085 user("u1", 1, runs[0]),
2086 shell("s1", 2, runs[0]),
2087 delegation,
2088 reply("a1", 4, runs[0]),
2089 user("u2", 10, runs[1]),
2090 shell("s2", 11, runs[1]),
2091 question(false),
2092 reply("a2", 13, runs[1]),
2093 user("u3", 20, runs[2]),
2094 shell("s3", 21, runs[2]),
2095 ];
2096 const running = {
2097 runId: runs[2],
2098 status: "running" as const,
2099 startedAt: at(20),
2100 completedAt: null,
2101 };
2102 const settled = { ...running, status: "completed" as const, completedAt: at(50) };
2103 // Each step is what one streamed event leaves behind, including the edits
2104 // that reach back into earlier runs.
2105 const steps: ReadonlyArray<{
2106 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
2107 readonly latestRun: ThreadFeedLatestRun;
2108 }> = [
2109 { items: [...history, reply("a3", 22, runs[2], "W", true)], latestRun: running },
2110 { items: [...history, reply("a3", 22, runs[2], "Wor", true)], latestRun: running },
2111 {
2112 items: [...history, reply("a3", 22, runs[2], "Working", true), shell("s4", 23, runs[2])],
2113 latestRun: running,
2114 },
2115 {
2116 items: [
2117 ...history,
2118 reply("a3", 22, runs[2], "Working", true),
2119 shell("s4", 23, runs[2]),
2120 lateChild,
2121 ],
2122 latestRun: running,
2123 },
2124 {
2125 items: [
2126 ...history.map((entry) => (entry.id === "question" ? question(true) : entry)),
2127 reply("a3", 22, runs[2], "Working", true),
2128 shell("s4", 23, runs[2]),
2129 lateChild,
2130 answer,
2131 ],
2132 latestRun: running,
2133 },
2134 {
2135 items: [
2136 ...history.slice(0, 9),
2137 shell("inserted", 20, runs[2]),
2138 ...history.slice(9),
2139 reply("a3", 22, runs[2], "Working", true),
2140 shell("s4", 23, runs[2]),
2141 ],
2142 latestRun: running,
2143 },
2144 {
2145 items: [...history, reply("a3", 22, runs[2], "Working on it"), shell("s4", 23, runs[2])],
2146 latestRun: running,
2147 },
2148 {
2149 items: [...history, reply("a3", 22, runs[2], "Working on it"), shell("s4", 23, runs[2])],
2150 latestRun: settled,
2151 },
2152 {
2153 items: [
2154 ...history,
2155 reply("a3", 22, runs[2], "Working on it"),
2156 shell("s4", 23, runs[2]),
2157 shell("late-s1", 45, runs[0]),
2158 ],
2159 latestRun: settled,
2160 },
2161 // The first run's fold above was timed to the late item; dropping it must reach back too.
2162 {
2163 items: [...history, reply("a3", 22, runs[2], "Working on it"), shell("s4", 23, runs[2])],
2164 latestRun: settled,
2165 },
2166 // The latest run resumes a subagent from the first run: the item moves to
2167 // the latest run but keeps its place, so it folds with the first run.
2168 {
2169 items: [
2170 ...history.slice(0, 3),
2171 resumed,
2172 ...history.slice(3),
2173 reply("a3", 22, runs[2], "Working on it"),
2174 shell("s4", 23, runs[2]),
2175 ],
2176 latestRun: running,
2177 },
2178 {
2179 items: [
2180 ...history.slice(0, 3),
2181 resumed,
2182 ...history.slice(3),
2183 reply("a3", 22, runs[2], "Working on it"),
2184 shell("s4", 23, runs[2]),
2185 reply("a4", 24, runs[2], "Still", true),
2186 ],
2187 latestRun: running,
2188 },
2189 ];
2190 // Like the projection reducer, an unchanged item at an unchanged position keeps its row.
2191 const rowsByItem = new Map<
2192 OrchestrationV2TurnItem,
2193 Map<number, OrchestrationV2ProjectedTurnItem>
2194 >();
2195 const row = (entry: OrchestrationV2TurnItem, position: number) => {
2196 const byPosition = rowsByItem.get(entry) ?? new Map<number, OrchestrationV2ProjectedTurnItem>();
2197 rowsByItem.set(entry, byPosition);
2198 const cached = byPosition.get(position) ?? projected(entry, position);
2199 byPosition.set(position, cached);
2200 return cached;
2201 };
2202 const present = (
2203 step: (typeof steps)[number],
2204 expandedRunIds: ReadonlySet<RunId>,
2205 cache?: ThreadFeedCache,
2206 ) =>
2207 deriveThreadFeedPresentation(
2208 buildThreadFeed(step.items.map(row), { cache }),
2209 step.latestRun,
2210 expandedRunIds,
2211 new Set(),
2212 step.latestRun.status === "running" ? at(20) : null,
2213 false,
2214 cache,
2215 );
2216
2217 it.each([
2218 { folds: "collapsed", expandedRunIds: new Set<RunId>() },
2219 { folds: "expanded", expandedRunIds: new Set<RunId>(runs) },
2220 ])("matches a fresh build after every update with $folds runs", ({ expandedRunIds }) => {
2221 const cache = createThreadFeedCache();
2222 const streamed = steps.map((step) => present(step, expandedRunIds, cache));
2223 const fresh = steps.map((step) => present(step, expandedRunIds));
2224 // Closures on activities are not part of what a row shows.
2225 const values = (rows: ReadonlyArray<ThreadFeedEntry>) => JSON.parse(JSON.stringify(rows));
2226 for (const [index, rows] of streamed.entries()) {
2227 expect(values(rows), `step ${index}`).toEqual(values(fresh[index]!));
2228 }
2229 });
2230
2231 it("hides a delegation once its child reaches back into the earlier run", () => {
2232 const showsDelegation = (step: (typeof steps)[number]) =>
2233 buildThreadFeed(step.items.map(row)).some(
2234 (entry) =>
2235 entry.type === "activity-group" &&
2236 entry.activities.some((activity) => activity.projectedItem.item.id === "delegation"),
2237 );
2238 expect(showsDelegation(steps[2]!)).toBe(true);
2239 expect(showsDelegation(steps[3]!)).toBe(false);
2240 });
2241 });
2242
2243 it.each([false, true])(
2244 "caps live approval headers while preserving the prompt (grouped: %s)",
2245 (grouped) => {
2246 const at = "2026-06-20T00:00:02.000Z";
2247 const prompt = `python3 - <<'PY'\n${"print('approval')\n".repeat(400)}PY`;
2248 const approval: OrchestrationV2TurnItem = {
2249 ...base("long-approval", at, 2),
2250 type: "approval_request",
2251 status: "waiting",
2252 completedAt: null,
2253 requestId: RuntimeRequestId.make("long-approval"),
2254 requestKind: "command",
2255 prompt,
2256 };
2257 const presented = deriveThreadFeedPresentation(
2258 buildThreadFeed([
2259 projected(userMessage(), 0),
2260 ...(grouped ? [projected(command(), 1)] : []),
2261 projected(approval, 2),
2262 ]),
2263 { runId, status: "running", startedAt: at, completedAt: null },
2264 new Set(),
2265 new Set(),
2266 at,
2267 );
2268 const header = presented.find((row) =>
2269 grouped ? row.type === "work-toggle" : row.type === "activity-group",
2270 );
2271 const label =
2272 header?.type === "work-toggle"
2273 ? header.summary
2274 : header?.type === "activity-group"
2275 ? header.activities[0]?.groupStandIn?.label
2276 : undefined;
2277 expect(label).toBeDefined();
2278 expect(label!.length).toBeLessThanOrEqual(203);
2279 expect(label).toMatch(/^python3 - <<'PY' print/);
2280 expect(label).not.toContain("\n");
2281 const feed = buildThreadFeed([projected(approval, 0)]);
2282 const activity = feed.flatMap((row) =>
2283 row.type === "activity-group" ? row.activities : [],
2284 )[0]!;
2285 expect(activity.detail).toBe(prompt);
2286 expect(JSON.parse(activity.getFullDetail()!).item).toMatchObject({ prompt });
2287 expect(activity.getCopyText()).toContain(prompt);
2288 },
2289 );
2290
2291 it("caps live thought previews while preserving reasoning detail", () => {
2292 const at = "2026-06-20T00:00:02.000Z";
2293 const text = "Considering the pending approval\n".repeat(100);
2294 const thought: OrchestrationV2TurnItem = {
2295 ...base("long-thought", at, 1),
2296 type: "reasoning",
2297 status: "running",
2298 completedAt: null,
2299 text,
2300 streaming: true,
2301 };
2302 const feed = buildThreadFeed([projected(userMessage(), 0), projected(thought, 1)]);
2303 const rows = deriveThreadFeedPresentation(
2304 feed,
2305 { runId, status: "running", startedAt: at, completedAt: null },
2306 new Set(),
2307 new Set(),
2308 at,
2309 );
2310 const header = rows.find((row) => row.type === "work-toggle");
2311 expect(header).toMatchObject({ summary: "Thinking", live: true });
2312 expect(header?.thought).toMatch(/^Considering the pending approval/);
2313 expect(header?.thought).not.toContain("\n");
2314 expect(header!.thought!.length).toBeLessThanOrEqual(203);
2315 const activity = feed.flatMap((row) => (row.type === "activity-group" ? row.activities : []))[0]!;
2316 expect(activity.detail).toBe(text);
2317 expect(JSON.parse(activity.getFullDetail()!).item).toMatchObject({ text });
2318 expect(activity.getCopyText()).toContain(text);
2319 });