Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import { codexFeedbackMessage } from "@t3tools/client-runtime/state/threads";
3
4import {
5 EventId,
6 MessageId,
7 ProjectId,
8 ProviderInstanceId,
9 ThreadId,
10 TurnId,
11 type OrchestrationThread,
12 type OrchestrationThreadActivity,
13} from "@t3tools/contracts";
14
15import {
16 buildPendingUserInputAnswers,
17 buildThreadFeed,
18 derivePendingApprovals,
19 deriveThreadFeedPresentation,
20 isPendingUserInputOptionSelected,
21 setPendingUserInputCustomAnswer,
22 togglePendingUserInputOptionSelection,
23 type ThreadFeedActivity,
24 type ThreadFeedEntry,
25} from "./threadActivity";
26
27describe("Codex feedback pseudo-messages", () => {
28 it("keeps pending and completed feedback messages in the mobile thread body", () => {
29 const pending = {
30 id: MessageId.make("feedback-command"),
31 command: "/feedback The agent stopped early.",
32 createdAt: "2026-08-23T00:00:00.000Z",
33 status: "uploading" as const,
34 };
35 const entries = [codexFeedbackMessage(pending), codexFeedbackMessage(pending, "assistant")].map(
36 (message) => ({
37 type: "message" as const,
38 id: message.id,
39 createdAt: message.createdAt,
40 message,
41 }),
42 );
43
44 expect(deriveThreadFeedPresentation(entries, null, new Set())).toEqual(entries);
45 expect(entries[1]?.message.text).toBe("Sending feedback to OpenAI...");
46
47 const completed = codexFeedbackMessage(
48 { ...pending, status: "sent", feedbackId: "codex-thread-1" },
49 "assistant",
50 );
51 expect(completed.text).toContain("codex-thread-1");
52 });
53});
54
55const singleSelectQuestion = {
56 id: "runtime",
57 header: "Runtime",
58 question: "Which runtime should be used?",
59 options: [
60 { label: "Go", description: "One binary" },
61 { label: "Node.js", description: "Reuse TypeScript" },
62 ],
63 multiSelect: false,
64} as const;
65
66const multiSelectQuestion = {
67 id: "scope",
68 header: "Scope",
69 question: "Which data should be collected?",
70 options: [
71 { label: "Orders", description: "Receipts" },
72 { label: "Listings", description: "Inventory" },
73 ],
74 multiSelect: true,
75} as const;
76
77describe("pending user input answers", () => {
78 it("replaces single-select options and toggles multi-select options", () => {
79 expect(
80 togglePendingUserInputOptionSelection(
81 singleSelectQuestion,
82 { selectedOptionLabels: ["Go"] },
83 "Node.js",
84 ),
85 ).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] });
86
87 const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");
88 const ordersAndListings = togglePendingUserInputOptionSelection(
89 multiSelectQuestion,
90 orders,
91 "Listings",
92 );
93 expect(ordersAndListings).toEqual({
94 customAnswer: "",
95 selectedOptionLabels: ["Orders", "Listings"],
96 });
97 expect(
98 togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),
99 ).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] });
100
101 const paddedOrders = togglePendingUserInputOptionSelection(
102 multiSelectQuestion,
103 undefined,
104 " Orders ",
105 );
106 expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] });
107 expect(
108 togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "),
109 ).toEqual({ customAnswer: "" });
110 });
111
112 it("builds array answers for multi-select questions", () => {
113 expect(
114 buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {
115 runtime: { selectedOptionLabels: ["Go"] },
116 scope: { selectedOptionLabels: ["Orders", "Listings"] },
117 }),
118 ).toEqual({
119 runtime: "Go",
120 scope: ["Orders", "Listings"],
121 });
122 });
123
124 it("clears selected options while a custom answer is active", () => {
125 expect(
126 setPendingUserInputCustomAnswer(
127 { selectedOptionLabels: ["Orders", "Listings"] },
128 "Orders first",
129 ),
130 ).toEqual({ customAnswer: "Orders first" });
131 });
132
133 it("matches selected chips against normalized option labels", () => {
134 expect(
135 isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "),
136 ).toBe(true);
137 expect(
138 isPendingUserInputOptionSelected(
139 { selectedOptionLabels: ["Orders"], customAnswer: "Orders first" },
140 " Orders ",
141 ),
142 ).toBe(false);
143 });
144});
145
146describe("pending approvals", () => {
147 it("keeps app access approvals and persistence choices from remote environments", () => {
148 const options = [
149 { decision: "decline", label: "Decline" },
150 { decision: "acceptAlways", label: "Always allow Safari" },
151 { decision: "accept", label: "Approve" },
152 ];
153 const activity = makeActivity({
154 id: EventId.make("approval-safari"),
155 kind: "approval.requested",
156 summary: "App access approval requested",
157 createdAt: "2026-08-24T00:00:00.000Z",
158 payload: {
159 requestId: "req-safari",
160 requestType: "mcp_elicitation_approval",
161 detail: "Allow ChatGPT to use Safari?",
162 appName: "Safari",
163 options,
164 },
165 });
166
167 expect(derivePendingApprovals([activity])).toEqual([
168 {
169 requestId: "req-safari",
170 requestKind: "mcp-elicitation",
171 createdAt: "2026-08-24T00:00:00.000Z",
172 detail: "Allow ChatGPT to use Safari?",
173 appName: "Safari",
174 options,
175 },
176 ]);
177 });
178
179 it("removes an app access approval after a remote client rejects it", () => {
180 const requested = makeActivity({
181 id: EventId.make("approval-safari-open"),
182 kind: "approval.requested",
183 summary: "App access approval requested",
184 createdAt: "2026-08-24T00:00:00.000Z",
185 payload: { requestId: "req-safari", requestKind: "mcp-elicitation" },
186 });
187 const resolved = makeActivity({
188 id: EventId.make("approval-safari-resolved"),
189 kind: "approval.resolved",
190 summary: "Approval resolved",
191 createdAt: "2026-08-24T00:00:01.000Z",
192 payload: { requestId: "req-safari", decision: "decline" },
193 });
194
195 expect(derivePendingApprovals([requested, resolved])).toEqual([]);
196 });
197});
198
199function makeActivity(
200 input: Partial<OrchestrationThreadActivity> &
201 Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
202): OrchestrationThreadActivity {
203 return {
204 tone: "info",
205 payload: {},
206 turnId: null,
207 ...input,
208 };
209}
210
211function makeThread(
212 input: Partial<OrchestrationThread> & Pick<OrchestrationThread, "id" | "projectId" | "title">,
213): OrchestrationThread {
214 return {
215 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
216 runtimeMode: "full-access",
217 interactionMode: "default",
218 branch: null,
219 worktreePath: null,
220 latestTurn: null,
221 createdAt: "2026-04-01T00:00:00.000Z",
222 updatedAt: "2026-04-01T00:00:00.000Z",
223 archivedAt: null,
224 deletedAt: null,
225 messages: [],
226 proposedPlans: [],
227 activities: [],
228 checkpoints: [],
229 session: null,
230 ...input,
231 settledOverride: input.settledOverride ?? null,
232 settledAt: input.settledAt ?? null,
233 };
234}
235
236describe("buildThreadFeed", () => {
237 it("keeps setup failures visible without routine setup notices before or after a turn", () => {
238 const thread = makeThread({
239 id: ThreadId.make("thread-worktree-setup"),
240 projectId: ProjectId.make("project-1"),
241 title: "Worktree setup",
242 activities: [
243 makeActivity({
244 id: EventId.make("setup-requested"),
245 kind: "setup-script.requested",
246 summary: "Starting setup script",
247 createdAt: "2026-08-30T00:00:00.000Z",
248 }),
249 makeActivity({
250 id: EventId.make("setup-started"),
251 kind: "setup-script.started",
252 summary: "Setup script started",
253 createdAt: "2026-08-30T00:00:01.000Z",
254 }),
255 makeActivity({
256 id: EventId.make("setup-failed"),
257 kind: "setup-script.failed",
258 summary: "Setup script failed to start",
259 createdAt: "2026-08-30T00:00:02.000Z",
260 tone: "error",
261 payload: { detail: "Setup command was not found" },
262 }),
263 ],
264 });
265 const latestTurn = {
266 turnId: TurnId.make("turn-after-setup"),
267 state: "running" as const,
268 requestedAt: "2026-08-30T00:00:03.000Z",
269 startedAt: "2026-08-30T00:00:04.000Z",
270 completedAt: null,
271 assistantMessageId: null,
272 };
273
274 for (const currentTurn of [null, latestTurn]) {
275 const feed = buildThreadFeed({ ...thread, latestTurn: currentTurn });
276 expect(feed).toMatchObject([
277 {
278 type: "activity-group",
279 activities: [{ id: "setup-failed", status: "failure" }],
280 },
281 ]);
282 const group = feed[0];
283 if (group?.type !== "activity-group") throw new Error("Expected the setup failure group");
284 expect(group.activities[0]?.getCopyText()).toContain("Setup command was not found");
285 }
286 });
287
288 it.each(["setup-script.requested", "setup-script.started"])(
289 "keeps error-toned %s notices visible",
290 (kind) => {
291 const feed = buildThreadFeed(
292 makeThread({
293 id: ThreadId.make("thread-setup-error"),
294 projectId: ProjectId.make("project-1"),
295 title: "Setup error",
296 activities: [
297 makeActivity({
298 id: EventId.make("setup-error"),
299 kind,
300 summary: "Setup failed",
301 createdAt: "2026-08-30T00:00:00.000Z",
302 tone: "error",
303 }),
304 ],
305 }),
306 );
307
308 expect(feed).toMatchObject([
309 { type: "activity-group", activities: [{ id: "setup-error", status: "failure" }] },
310 ]);
311 },
312 );
313
314 it("keeps older local feedback before newer messages returned by the server", () => {
315 const submission = {
316 id: MessageId.make("feedback-command-ordering"),
317 command: "/feedback The agent stopped early.",
318 createdAt: "2026-08-23T00:00:01.000Z",
319 status: "sent" as const,
320 feedbackId: "codex-thread-1",
321 };
322 const laterMessage = {
323 id: MessageId.make("later-server-message"),
324 role: "assistant" as const,
325 text: "Newer server response",
326 turnId: null,
327 createdAt: "2026-08-23T00:00:02.000Z",
328 updatedAt: "2026-08-23T00:00:02.000Z",
329 streaming: false,
330 };
331 const thread = makeThread({
332 id: ThreadId.make("thread-feedback-ordering"),
333 projectId: ProjectId.make("project-1"),
334 title: "Feedback ordering",
335 messages: [laterMessage],
336 });
337
338 const feed = buildThreadFeed(thread, {
339 localMessages: [
340 codexFeedbackMessage(submission),
341 codexFeedbackMessage(submission, "assistant"),
342 ],
343 });
344
345 expect(feed.map((entry) => entry.id)).toEqual([
346 "feedback-command-ordering",
347 "feedback-command-ordering:feedback",
348 "later-server-message",
349 ]);
350 });
351
352 it("keeps historic work entries attributed to their turns", () => {
353 const thread = makeThread({
354 id: ThreadId.make("thread-1"),
355 projectId: ProjectId.make("project-1"),
356 title: "Runtime warning thread",
357 latestTurn: {
358 turnId: TurnId.make("turn-latest"),
359 state: "running",
360 requestedAt: "2026-04-01T00:00:00.000Z",
361 startedAt: "2026-04-01T00:00:01.000Z",
362 completedAt: null,
363 assistantMessageId: null,
364 },
365 activities: [
366 makeActivity({
367 id: EventId.make("activity-old"),
368 kind: "runtime.warning",
369 summary: "Runtime warning",
370 createdAt: "2026-04-01T00:00:02.000Z",
371 turnId: TurnId.make("turn-old"),
372 payload: {
373 message: "Old warning",
374 },
375 }),
376 makeActivity({
377 id: EventId.make("activity-latest"),
378 kind: "runtime.warning",
379 summary: "Runtime warning",
380 createdAt: "2026-04-01T00:00:03.000Z",
381 turnId: TurnId.make("turn-latest"),
382 payload: {
383 message: "Latest warning",
384 },
385 }),
386 ],
387 });
388
389 const feed = buildThreadFeed(thread);
390 expect(feed).toMatchObject([
391 {
392 type: "activity-group",
393 turnId: "turn-old",
394 activities: [{ id: "activity-old", turnId: "turn-old" }],
395 },
396 {
397 type: "activity-group",
398 turnId: "turn-latest",
399 activities: [{ id: "activity-latest", turnId: "turn-latest" }],
400 },
401 ]);
402 });
403
404 it("drops runtime warnings with no displayable content", () => {
405 const thread = makeThread({
406 id: ThreadId.make("thread-noise"),
407 projectId: ProjectId.make("project-1"),
408 title: "Warning noise thread",
409 activities: [
410 makeActivity({
411 id: EventId.make("activity-noise"),
412 kind: "runtime.warning",
413 summary: "Claude system message 'background_tasks_changed' (no displayable text content)",
414 createdAt: "2026-04-01T00:00:02.000Z",
415 turnId: TurnId.make("turn-1"),
416 }),
417 makeActivity({
418 id: EventId.make("activity-signal"),
419 kind: "runtime.warning",
420 summary: "Reconnecting... 2/5",
421 createdAt: "2026-04-01T00:00:03.000Z",
422 turnId: TurnId.make("turn-1"),
423 }),
424 ],
425 });
426
427 const feed = buildThreadFeed(thread);
428 expect(feed).toMatchObject([
429 {
430 type: "activity-group",
431 activities: [{ id: "activity-signal" }],
432 },
433 ]);
434 });
435
436 it("collapses matching tool lifecycle rows like desktop", () => {
437 const thread = makeThread({
438 id: ThreadId.make("thread-2"),
439 projectId: ProjectId.make("project-1"),
440 title: "Collapsed tools",
441 latestTurn: {
442 turnId: TurnId.make("turn-1"),
443 state: "completed",
444 requestedAt: "2026-04-01T00:00:00.000Z",
445 startedAt: "2026-04-01T00:00:01.000Z",
446 completedAt: "2026-04-01T00:00:03.000Z",
447 assistantMessageId: null,
448 },
449 activities: [
450 makeActivity({
451 id: EventId.make("tool-updated"),
452 kind: "tool.updated",
453 tone: "tool",
454 summary: "Run tests",
455 createdAt: "2026-04-01T00:00:01.000Z",
456 turnId: TurnId.make("turn-1"),
457 payload: {
458 title: "Run tests",
459 itemType: "command_execution",
460 detail: "/bin/zsh -lc 'bun run test'",
461 },
462 }),
463 makeActivity({
464 id: EventId.make("tool-completed"),
465 kind: "tool.completed",
466 tone: "tool",
467 summary: "Run tests completed",
468 createdAt: "2026-04-01T00:00:02.000Z",
469 turnId: TurnId.make("turn-1"),
470 payload: {
471 title: "Run tests",
472 itemType: "command_execution",
473 detail: "/bin/zsh -lc 'bun run test'",
474 },
475 }),
476 ],
477 });
478
479 const feed = buildThreadFeed(thread);
480 const group = feed[0];
481
482 expect(group).toMatchObject({
483 type: "activity-group",
484 });
485 if (!group || group.type !== "activity-group") {
486 return;
487 }
488
489 expect(group.activities).toHaveLength(1);
490 expect(group.activities[0]).toMatchObject({
491 id: "tool-updated",
492 createdAt: "2026-04-01T00:00:01.000Z",
493 turnId: "turn-1",
494 summary: "Run tests",
495 detail: "bun run test",
496 canExpand: true,
497 icon: "command",
498 toolLike: true,
499 status: "success",
500 });
501 expect(group.activities[0]?.getFullDetail()).toBe("/bin/zsh -lc 'bun run test'");
502 expect(group.activities[0]?.getCopyText()).toBe(
503 "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
504 );
505 });
506
507 it("keeps MCP inputs available to expanded mobile work rows", () => {
508 const turnId = TurnId.make("turn-mcp");
509 const thread = makeThread({
510 id: ThreadId.make("thread-mcp"),
511 projectId: ProjectId.make("project-1"),
512 title: "Expandable MCP call",
513 latestTurn: {
514 turnId,
515 state: "completed",
516 requestedAt: "2026-04-01T00:00:00.000Z",
517 startedAt: "2026-04-01T00:00:01.000Z",
518 completedAt: "2026-04-01T00:00:03.000Z",
519 assistantMessageId: null,
520 },
521 activities: [
522 makeActivity({
523 id: EventId.make("mcp-completed"),
524 kind: "tool.completed",
525 tone: "tool",
526 summary: "Call repository tool",
527 createdAt: "2026-04-01T00:00:02.000Z",
528 turnId,
529 payload: {
530 title: "Call repository tool",
531 itemType: "mcp_tool_call",
532 detail: "repository.search",
533 status: "completed",
534 data: {
535 item: {
536 server: "repository",
537 tool: "search",
538 arguments: { query: "work log" },
539 },
540 },
541 },
542 }),
543 ],
544 });
545
546 const group = buildThreadFeed(thread)[0];
547 expect(group).toMatchObject({ type: "activity-group" });
548 if (!group || group.type !== "activity-group") {
549 return;
550 }
551
552 expect(group.activities[0]?.icon).toBe("wrench");
553 expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"');
554 expect(group.activities[0]?.getFullDetail()).toContain("repository.search");
555 });
556
557 it("defers large tool output expansion until a work row is opened or copied", () => {
558 let serializedToolOutputs = 0;
559 const activities = Array.from({ length: 5_000 }, (_, index) =>
560 makeActivity({
561 id: EventId.make(`large-tool-${index}`),
562 kind: "tool.completed",
563 tone: "tool",
564 summary: `Tool ${index}`,
565 createdAt: new Date(Date.UTC(2026, 3, 1, 0, 0, index)).toISOString(),
566 payload: {
567 title: `Tool ${index}`,
568 itemType: "mcp_tool_call",
569 status: "completed",
570 data: {
571 item: {
572 toJSON: () => {
573 serializedToolOutputs += 1;
574 return { output: "x".repeat(32_768) };
575 },
576 },
577 },
578 },
579 }),
580 );
581 const thread = makeThread({
582 id: ThreadId.make("thread-large-tools"),
583 projectId: ProjectId.make("project-1"),
584 title: "Large tools",
585 activities,
586 });
587
588 const feed = buildThreadFeed(thread);
589 expect(serializedToolOutputs).toBe(0);
590
591 const group = feed[0];
592 expect(group).toMatchObject({ type: "activity-group" });
593 if (!group || group.type !== "activity-group") {
594 return;
595 }
596
597 expect(group.activities).toHaveLength(5_000);
598 expect(group.activities[0]?.getFullDetail()).toContain('"output"');
599 expect(serializedToolOutputs).toBe(1);
600 expect(group.activities[0]?.getCopyText()).toContain('"output"');
601 expect(serializedToolOutputs).toBe(1);
602 });
603
604 it("keeps the first and terminal assistant messages visible around settled work", () => {
605 const turnId = TurnId.make("turn-1");
606 const thread = makeThread({
607 id: ThreadId.make("thread-3"),
608 projectId: ProjectId.make("project-1"),
609 title: "Folded work",
610 latestTurn: {
611 turnId,
612 state: "completed",
613 requestedAt: "2026-04-01T00:00:00.000Z",
614 startedAt: "2026-04-01T00:00:01.000Z",
615 completedAt: "2026-04-01T00:00:18.000Z",
616 assistantMessageId: MessageId.make("assistant-final"),
617 },
618 messages: [
619 {
620 id: MessageId.make("assistant-first"),
621 role: "assistant",
622 text: "Synthetic deployment checklist\n1. Confirm the deployment is ready.",
623 turnId,
624 streaming: false,
625 createdAt: "2026-04-01T00:00:02.000Z",
626 updatedAt: "2026-04-01T00:00:03.000Z",
627 },
628 {
629 id: MessageId.make("assistant-final"),
630 role: "assistant",
631 text: "Done.",
632 turnId,
633 streaming: false,
634 createdAt: "2026-04-01T00:00:17.000Z",
635 updatedAt: "2026-04-01T00:00:18.000Z",
636 },
637 ],
638 activities: [
639 makeActivity({
640 id: EventId.make("tool-completed"),
641 kind: "tool.completed",
642 tone: "tool",
643 summary: "Read files",
644 createdAt: "2026-04-01T00:00:05.000Z",
645 turnId,
646 payload: {
647 title: "Read files",
648 itemType: "file_read",
649 status: "completed",
650 },
651 }),
652 ],
653 });
654
655 const feed = buildThreadFeed(thread);
656 const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
657 expect(collapsed.map((entry) => entry.id)).toEqual([
658 "assistant-first",
659 "turn-fold:turn-1",
660 "assistant-final",
661 ]);
662 expect(collapsed[1]).toMatchObject({
663 type: "turn-fold",
664 label: "Worked for 17s",
665 expanded: false,
666 });
667
668 const expanded = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set([turnId]));
669 expect(expanded.map((entry) => entry.id)).toEqual([
670 "assistant-first",
671 "turn-fold:turn-1",
672 "work-toggle:work-group:tool-completed",
673 "assistant-final",
674 ]);
675 });
676
677 it("folds assistant messages between the first and terminal messages", () => {
678 const turnId = TurnId.make("turn-1");
679 const thread = makeThread({
680 id: ThreadId.make("thread-middle-message"),
681 projectId: ProjectId.make("project-1"),
682 title: "Bounded narration",
683 latestTurn: {
684 turnId,
685 state: "completed",
686 requestedAt: "2026-04-01T00:00:00.000Z",
687 startedAt: "2026-04-01T00:00:01.000Z",
688 completedAt: "2026-04-01T00:00:06.000Z",
689 assistantMessageId: MessageId.make("assistant-final"),
690 },
691 messages: [
692 {
693 id: MessageId.make("assistant-first"),
694 role: "assistant",
695 text: "The main result is ready.",
696 turnId,
697 streaming: false,
698 createdAt: "2026-04-01T00:00:01.000Z",
699 updatedAt: "2026-04-01T00:00:02.000Z",
700 },
701 {
702 id: MessageId.make("assistant-middle"),
703 role: "assistant",
704 text: "I am checking one more detail.",
705 turnId,
706 streaming: false,
707 createdAt: "2026-04-01T00:00:03.000Z",
708 updatedAt: "2026-04-01T00:00:04.000Z",
709 },
710 {
711 id: MessageId.make("assistant-final"),
712 role: "assistant",
713 text: "Verification finished.",
714 turnId,
715 streaming: false,
716 createdAt: "2026-04-01T00:00:05.000Z",
717 updatedAt: "2026-04-01T00:00:06.000Z",
718 },
719 ],
720 });
721
722 const feed = buildThreadFeed(thread);
723 const rows = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
724
725 expect(rows.map((entry) => entry.id)).toEqual([
726 "assistant-first",
727 "turn-fold:turn-1",
728 "assistant-final",
729 ]);
730 });
731
732 it("measures a steer-superseded turn from its user boundary through trailing work", () => {
733 const firstTurnId = TurnId.make("turn-1");
734 const secondTurnId = TurnId.make("turn-2");
735 const thread = makeThread({
736 id: ThreadId.make("thread-steered"),
737 projectId: ProjectId.make("project-1"),
738 title: "Steered work",
739 latestTurn: {
740 turnId: secondTurnId,
741 state: "running",
742 requestedAt: "2026-04-01T00:00:14.000Z",
743 startedAt: "2026-04-01T00:00:14.000Z",
744 completedAt: null,
745 assistantMessageId: MessageId.make("assistant-next"),
746 },
747 messages: [
748 {
749 id: MessageId.make("user-1"),
750 role: "user",
751 text: "Do it once more.",
752 turnId: null,
753 streaming: false,
754 createdAt: "2026-04-01T00:00:00.000Z",
755 updatedAt: "2026-04-01T00:00:00.000Z",
756 },
757 {
758 id: MessageId.make("assistant-commentary"),
759 role: "assistant",
760 text: "Kicking off call 1.",
761 turnId: firstTurnId,
762 streaming: false,
763 createdAt: "2026-04-01T00:00:09.000Z",
764 updatedAt: "2026-04-01T00:00:09.000Z",
765 },
766 {
767 id: MessageId.make("user-2"),
768 role: "user",
769 text: "Actually do 15.",
770 turnId: null,
771 streaming: false,
772 createdAt: "2026-04-01T00:00:14.000Z",
773 updatedAt: "2026-04-01T00:00:14.000Z",
774 },
775 {
776 id: MessageId.make("assistant-next"),
777 role: "assistant",
778 text: "One down - adjusting.",
779 turnId: secondTurnId,
780 streaming: true,
781 createdAt: "2026-04-01T00:00:17.000Z",
782 updatedAt: "2026-04-01T00:00:17.000Z",
783 },
784 ],
785 activities: [
786 makeActivity({
787 id: EventId.make("work-1"),
788 kind: "tool.completed",
789 tone: "tool",
790 summary: "Ran command",
791 createdAt: "2026-04-01T00:00:12.000Z",
792 turnId: firstTurnId,
793 payload: {
794 title: "Ran command",
795 itemType: "command_execution",
796 status: "completed",
797 },
798 }),
799 ],
800 });
801
802 const feed = buildThreadFeed(thread);
803 const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
804 expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
805 turnId: firstTurnId,
806 label: "Worked for 12s",
807 });
808 });
809
810 it("keeps an active turn expanded and classifies error-shaped tool output", () => {
811 const turnId = TurnId.make("turn-running");
812 const thread = makeThread({
813 id: ThreadId.make("thread-4"),
814 projectId: ProjectId.make("project-1"),
815 title: "Running work",
816 latestTurn: {
817 turnId,
818 state: "running",
819 requestedAt: "2026-04-01T00:00:00.000Z",
820 startedAt: "2026-04-01T00:00:01.000Z",
821 completedAt: null,
822 assistantMessageId: null,
823 },
824 activities: [
825 makeActivity({
826 id: EventId.make("tool-succeeded"),
827 kind: "tool.completed",
828 tone: "tool",
829 summary: "Run command",
830 createdAt: "2026-04-01T00:00:04.000Z",
831 turnId,
832 payload: {
833 title: "Run command",
834 itemType: "command_execution",
835 detail: "done",
836 status: "completed",
837 },
838 }),
839 makeActivity({
840 id: EventId.make("tool-failed"),
841 kind: "tool.completed",
842 tone: "tool",
843 summary: "Run command",
844 createdAt: "2026-04-01T00:00:05.000Z",
845 turnId,
846 payload: {
847 title: "Run command",
848 itemType: "command_execution",
849 detail: "zsh: command not found: nope",
850 status: "completed",
851 },
852 }),
853 ],
854 });
855
856 const feed = buildThreadFeed(thread);
857 expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toMatchObject([
858 {
859 type: "work-toggle",
860 summary: "Ran 2 commands",
861 hiddenCount: 2,
862 hasFailure: true,
863 },
864 ]);
865 expect(feed[0]).toMatchObject({
866 type: "activity-group",
867 activities: [{ status: "success" }, { status: "failure" }],
868 });
869 expect(
870 deriveThreadFeedPresentation(
871 feed,
872 thread.latestTurn,
873 new Set(),
874 new Set(["work-group:tool-succeeded"]),
875 ).map((entry) => entry.id),
876 ).toEqual(["work-toggle:work-group:tool-succeeded", "tool-succeeded", "tool-failed"]);
877 });
878
879 it("models work-log overflow as list rows", () => {
880 const activity = (
881 id: string,
882 createdAt: string,
883 status: ThreadFeedActivity["status"] = "success",
884 ): ThreadFeedActivity => ({
885 id,
886 createdAt,
887 turnId: null,
888 summary: `Tool ${id}`,
889 detail: null,
890 canExpand: false,
891 getFullDetail: () => null,
892 getCopyText: () => id,
893 icon: "command",
894 toolLike: true,
895 status,
896 workEntry: {
897 id,
898 createdAt,
899 turnId: null,
900 label: `Tool ${id}`,
901 command: `command ${id}`,
902 tone: "tool",
903 },
904 });
905 const feed: ThreadFeedEntry[] = [
906 {
907 type: "activity-group",
908 id: "work-group-1",
909 createdAt: "2026-04-01T00:00:01.000Z",
910 turnId: null,
911 activities: [
912 activity("activity-1", "2026-04-01T00:00:01.000Z"),
913 activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
914 activity("activity-2", "2026-04-01T00:00:03.000Z"),
915 activity("activity-3", "2026-04-01T00:00:04.000Z"),
916 ],
917 },
918 ];
919
920 const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
921 expect(collapsed.map((entry) => entry.id)).toEqual(["work-toggle:work-group:activity-1"]);
922 expect(collapsed[0]).toMatchObject({
923 type: "work-toggle",
924 groupId: "work-group:activity-1",
925 hiddenCount: 3,
926 expanded: false,
927 summary: "Ran 3 commands",
928 });
929
930 const expanded = deriveThreadFeedPresentation(
931 feed,
932 null,
933 new Set(),
934 new Set(["work-group:activity-1"]),
935 );
936 expect(expanded.map((entry) => entry.id)).toEqual([
937 "work-toggle:work-group:activity-1",
938 "activity-1",
939 "activity-2",
940 "activity-3",
941 ]);
942 expect(expanded[0]).toMatchObject({
943 type: "work-toggle",
944 expanded: true,
945 });
946 });
947
948 it("keeps live state on the active uninterrupted tool run", () => {
949 const turnId = TurnId.make("turn-live-tools");
950 const activity = (
951 id: string,
952 status: ThreadFeedActivity["status"],
953 lifecycleStatus: ThreadFeedActivity["lifecycleStatus"],
954 tone: "tool" | "error" = "tool",
955 command?: string,
956 ): ThreadFeedActivity => ({
957 id,
958 createdAt: `2026-04-01T00:00:0${id.at(-1)}.000Z`,
959 turnId,
960 summary: `Tool ${id}`,
961 detail: null,
962 canExpand: false,
963 getFullDetail: () => null,
964 getCopyText: () => id,
965 icon: "command",
966 toolLike: true,
967 status,
968 lifecycleStatus,
969 workEntry: {
970 id,
971 createdAt: `2026-04-01T00:00:0${id.at(-1)}.000Z`,
972 turnId,
973 label: `Tool ${id}`,
974 tone,
975 toolLifecycleStatus: lifecycleStatus,
976 ...(command ? { command, itemType: "command_execution" as const } : {}),
977 },
978 });
979 const feed: ThreadFeedEntry[] = [
980 {
981 type: "activity-group",
982 id: "activity-1",
983 createdAt: "2026-04-01T00:00:01.000Z",
984 turnId,
985 activities: [
986 activity("activity-1", "success", "completed"),
987 activity("activity-2", "failure", "failed", "error"),
988 activity("activity-3", "success", "completed", "tool", "sudo -u root pnpm test"),
989 ],
990 },
991 ];
992 const latestTurn = {
993 turnId,
994 state: "running" as const,
995 requestedAt: "2026-04-01T00:00:00.000Z",
996 startedAt: "2026-04-01T00:00:00.000Z",
997 completedAt: null,
998 assistantMessageId: null,
999 };
1000
1001 const rows = deriveThreadFeedPresentation(
1002 feed,
1003 latestTurn,
1004 new Set(),
1005 new Set(),
1006 latestTurn.startedAt,
1007 );
1008 expect(rows.slice(0, 3).map((entry) => [entry.id, entry.type])).toEqual([
1009 ["work-toggle:work-group:activity-1", "work-toggle"],
1010 ["activity-2", "activity-group"],
1011 ["work-live:work-group:activity-3", "work-toggle"],
1012 ]);
1013 expect(rows.slice(0, 3).map((entry) => entry.type === "work-toggle" && entry.live)).toEqual([
1014 false,
1015 false,
1016 true,
1017 ]);
1018 expect(rows[2]).toMatchObject({
1019 summary: "Running pnpm",
1020 summaryKind: "command",
1021 live: true,
1022 shimmer: true,
1023 });
1024 expect(rows[0]).toMatchObject({ live: false, shimmer: false });
1025
1026 const stoppedRows = deriveThreadFeedPresentation(feed, latestTurn, new Set());
1027 expect(stoppedRows.filter((entry) => entry.type === "work-toggle")).toMatchObject([
1028 { live: false, shimmer: false },
1029 { live: false, shimmer: false },
1030 ]);
1031
1032 const completedRows = deriveThreadFeedPresentation(
1033 feed,
1034 { ...latestTurn, state: "completed", completedAt: "2026-04-01T00:00:04.000Z" },
1035 new Set([turnId]),
1036 new Set(),
1037 latestTurn.startedAt,
1038 );
1039 expect(completedRows.filter((entry) => entry.type === "work-toggle")).toMatchObject([
1040 { live: false, shimmer: false },
1041 { live: false, shimmer: false },
1042 ]);
1043 });
1044
1045 it("does not revive cached in-progress tools after work stops", () => {
1046 const turnId = TurnId.make("turn-stale-tool");
1047 const feed: ThreadFeedEntry[] = [
1048 {
1049 type: "activity-group",
1050 id: "stale-tool",
1051 createdAt: "2026-04-01T00:00:01.000Z",
1052 turnId,
1053 activities: [
1054 {
1055 id: "stale-tool",
1056 createdAt: "2026-04-01T00:00:01.000Z",
1057 turnId,
1058 summary: "Running tests",
1059 detail: null,
1060 canExpand: false,
1061 getFullDetail: () => null,
1062 getCopyText: () => "",
1063 icon: "command",
1064 toolLike: true,
1065 status: "neutral",
1066 lifecycleStatus: "inProgress",
1067 workEntry: {
1068 id: "stale-tool",
1069 createdAt: "2026-04-01T00:00:01.000Z",
1070 turnId,
1071 label: "Running tests",
1072 tone: "tool",
1073 toolLifecycleStatus: "inProgress",
1074 },
1075 },
1076 ],
1077 },
1078 ];
1079 const latestTurn = {
1080 turnId,
1081 state: "running" as const,
1082 requestedAt: "2026-04-01T00:00:00.000Z",
1083 startedAt: "2026-04-01T00:00:00.000Z",
1084 completedAt: null,
1085 assistantMessageId: null,
1086 };
1087
1088 expect(deriveThreadFeedPresentation(feed, latestTurn, new Set())).toEqual([]);
1089 expect(
1090 deriveThreadFeedPresentation(feed, latestTurn, new Set(), new Set(), latestTurn.startedAt),
1091 ).toMatchObject([{ type: "work-toggle", live: true, shimmer: true }]);
1092 });
1093
1094 it("collapses interleaved tool lifecycles by call identity", () => {
1095 const turnId = TurnId.make("turn-parallel-tools");
1096 const toolActivity = (
1097 id: string,
1098 toolCallId: string,
1099 kind: "tool.updated" | "tool.completed",
1100 status: "inProgress" | "completed",
1101 detail: string,
1102 nestedId = false,
1103 ) =>
1104 makeActivity({
1105 id: EventId.make(id),
1106 kind,
1107 tone: "tool",
1108 summary: `Run ${toolCallId} command`,
1109 createdAt: `2026-04-01T00:00:0${id.at(-1)}.000Z`,
1110 turnId,
1111 payload: {
1112 ...(nestedId ? { data: { toolCallId } } : { toolCallId }),
1113 itemType: "command_execution",
1114 status,
1115 detail,
1116 },
1117 });
1118 const thread = makeThread({
1119 id: ThreadId.make("thread-parallel-tools"),
1120 projectId: ProjectId.make("project-1"),
1121 title: "Parallel tools",
1122 activities: [
1123 toolActivity("call-a-1", "call-a", "tool.updated", "inProgress", "starting"),
1124 toolActivity("call-b-2", "call-b", "tool.updated", "inProgress", "starting", true),
1125 toolActivity("call-a-3", "call-a", "tool.completed", "completed", "first output"),
1126 toolActivity("call-b-4", "call-b", "tool.completed", "completed", "second output", true),
1127 ],
1128 });
1129
1130 const feed = buildThreadFeed(thread);
1131 const activityGroup = feed.find((entry) => entry.type === "activity-group");
1132 expect(activityGroup).toMatchObject({
1133 type: "activity-group",
1134 activities: [
1135 { id: "call-a-1", lifecycleStatus: "completed", detail: "first output" },
1136 { id: "call-b-2", lifecycleStatus: "completed", detail: "second output" },
1137 ],
1138 });
1139 expect(
1140 deriveThreadFeedPresentation(feed, null, new Set([turnId])).find(
1141 (entry) => entry.type === "work-toggle",
1142 ),
1143 ).toMatchObject({
1144 type: "work-toggle",
1145 hiddenCount: 2,
1146 summary: "Ran 2 commands",
1147 live: false,
1148 });
1149 });
1150});
1151
1152describe("quiet timeline: nested agents", () => {
1153 it("keeps a nested agent's terminal row but hides its background work", () => {
1154 const thread = makeThread({
1155 id: ThreadId.make("thread-nested"),
1156 projectId: ProjectId.make("project-1"),
1157 title: "Nested agents",
1158 activities: [
1159 // A subagent's own shell: internal, covered by the owner's liveness.
1160 makeActivity({
1161 id: EventId.make("shell-done"),
1162 kind: "task.completed",
1163 summary: "Task completed",
1164 createdAt: "2026-04-01T00:00:02.000Z",
1165 payload: { taskId: "sh-1", agentId: "owner", agentKind: "background" },
1166 }),
1167 // A nested AGENT's completion: mobile has no Agents sheet, so this
1168 // terminal row is the only signal it ever finished.
1169 makeActivity({
1170 id: EventId.make("nested-done"),
1171 kind: "task.completed",
1172 summary: "Task completed",
1173 createdAt: "2026-04-01T00:00:03.000Z",
1174 payload: { taskId: "n-1", agentId: "owner", agentKind: "agent" },
1175 }),
1176 ],
1177 });
1178
1179 const feed = buildThreadFeed(thread);
1180 const ids = feed.flatMap((entry) =>
1181 entry.type === "activity-group" ? entry.activities.map((row) => row.id) : [],
1182 );
1183 expect(ids).toContain("nested-done");
1184 expect(ids).not.toContain("shell-done");
1185 expect(deriveThreadFeedPresentation(feed, null, new Set())).toMatchObject([
1186 { type: "activity-group", id: "nested-done" },
1187 ]);
1188 });
1189});