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

MessagesTimeline.logic.ts

1,317 lines44.6 KB

1import * as Equal from "effect/Equal";
2import { shallow } from "zustand/vanilla/shallow";
3import { renderCodexDirectivesForCopy } from "@t3tools/client-runtime/codex-markdown-directives";
4import { commandProgramName } from "@t3tools/client-runtime/work-log/command-label";
5import {
6 liveActivityToolStatus,
7 normalizeCompactToolLabel,
8 omitSupersededLifecycleMarkers,
9 resolveWorkEntryToolPresentation,
10 summarizeToolGroup,
11 toolGroupAction,
12 toolGroupSummaryKind,
13 type ToolGroupSummaryKind,
14} from "@t3tools/client-runtime/work-log/presentation";
15export {
16 normalizeCompactToolLabel,
17 summarizeToolGroup,
18 toolGroupAction,
19 workLogEntryIsLocalCodeSearch,
20} from "@t3tools/client-runtime/work-log/presentation";
21import {
22 formatDuration,
23 isStreamingMessageTextUpdate,
24 workEntryDisplayIndicatesToolFailure,
25 workEntryIndicatesToolSuccess,
26 workEntryIndicatesToolNeutralStatus,
27 workLogEntryIsToolLike,
28 type TimelineEntry,
29 type WorkLogEntry,
30} from "../../session-logic";
31import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
32import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
33import { formatWorkspaceRelativePath } from "../../filePathDisplay";
34​
35export const TIMELINE_MINIMAP_ITEM_SPACING = 8;
36export const TIMELINE_MINIMAP_MIN_ITEMS = 2;
37export const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "calc(100vh - 18rem)";
38export const TIMELINE_CONTENT_MAX_WIDTH = 768;
39export const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48;
40​
41function singleToolCallLabel(entry: WorkLogEntry): string {
42 const toolPresentation = resolveWorkEntryToolPresentation(entry, "completed");
43 if (toolPresentation) return toolPresentation.displayName;
44 const command = entry.command?.trim();
45 if (command) return command;
46 const heading = normalizeCompactToolLabel(entry.toolTitle || entry.label);
47 return `${heading.charAt(0).toUpperCase()}${heading.slice(1)}`;
49​
50export function workEntryDisplayLabel(entry: WorkLogEntry, workspaceRoot: string | undefined) {
51 const toolPresentation = resolveWorkEntryToolPresentation(entry);
52 if (toolPresentation) return toolPresentation.displayName;
53 if (entry.command) return entry.command;
54 if (entry.detail) return entry.detail;
55 const [firstPath] = entry.changedFiles ?? [];
56 if (firstPath) {
57 const path = formatWorkspaceRelativePath(firstPath, workspaceRoot);
58 return entry.changedFiles!.length === 1
59 ? path
60 : `${path} +${entry.changedFiles!.length - 1} more`;
61 }
62 const heading = normalizeCompactToolLabel(entry.toolTitle || entry.label);
63 return `${heading.charAt(0).toUpperCase()}${heading.slice(1)}`;
65​
66export function liveWorkEntryLabel(
67 entry: WorkLogEntry,
68 workspaceRoot: string | undefined,
69 active: boolean,
70) {
71 const status = liveActivityToolStatus(entry.toolLifecycleStatus, active);
72 const toolPresentation = resolveWorkEntryToolPresentation({
73 ...entry,
74 toolLifecycleStatus: status,
75 });
76 if (toolPresentation) return toolPresentation.displayName;
77 const command = entry.command?.trim();
78 if (command) {
79 const verb =
80 status === "inProgress"
81 ? "Running"
82 : status === "failed"
83 ? "Failed"
84 : status === "declined"
85 ? "Declined"
86 : status === "stopped"
87 ? "Stopped"
88 : "Ran";
89 return `${verb} ${commandProgramName(command) ?? "command"}`;
90 }
91 return workEntryDisplayLabel(entry, workspaceRoot);
93​
94export function workEntryIsVisibleInGroup(
95 entry: WorkLogEntry,
96 expandedToolGroupEntry = false,
97): boolean {
98 return (
99 (expandedToolGroupEntry &&
100 (entry.toolLifecycleStatus === "inProgress" ||
101 entry.sourceActivityKind === "task.progress")) ||
102 !workEntryIndicatesToolNeutralStatus(entry)
103 );
105​
106export interface WorkGroupScrollAnchor {
107 readonly entryId: string;
108 readonly offset: number;
110​
111/** Restore a visible tool, including a position partway through its expanded output. */
112export function resolveWorkGroupScrollIndex(
113 entries: ReadonlyArray<{ readonly id: string }>,
114 anchor: WorkGroupScrollAnchor | undefined,
115): { index: number; viewOffset: number } | undefined {
116 if (!anchor) return undefined;
117 const index = entries.findIndex((entry) => entry.id === anchor.entryId);
118 return index < 0 ? undefined : { index, viewOffset: -anchor.offset };
120​
121/** Only newly appended calls may follow the end, never status or output updates. */
122export function shouldFollowWorkGroupAppend(
123 previous: ReadonlyArray<{ readonly id: string }>,
124 entries: ReadonlyArray<{ readonly id: string }>,
125 distanceFromEnd: number,
126): boolean {
127 return (
128 previous.length > 0 &&
129 entries.length > previous.length &&
130 distanceFromEnd <= 1 &&
131 previous.every((entry, index) => entry.id === entries[index]?.id)
132 );
134​
135export interface TimelineEndState {
136 readonly isAtEnd?: boolean;
137 readonly contentLength?: number;
138 readonly scroll?: number;
139 readonly scrollLength?: number;
141​
142/**
143 * Follow re-arm band above the hard bottom. Strict on purpose: LegendList's
144 * isNearEnd fires within half a viewport, which re-armed live-follow while the
145 * user was reading history and yanked them back down on the next stream chunk.
146 * A small pixel band (instead of the 1px isAtEnd epsilon alone) keeps re-arming
147 * reliable while streaming content is still growing under the viewport.
148 */
149export const TIMELINE_FOLLOW_REARM_THRESHOLD_PX = 40;
150​
151export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined {
152 if (!state) {
153 return undefined;
154 }
155 const { contentLength, scroll, scrollLength } = state;
156 if (contentLength === undefined || scroll === undefined || scrollLength === undefined) {
157 return state.isAtEnd;
158 }
159 // contentLength includes the composer inset spacer, but the composer hides
160 // the same amount of viewport, so the inset cancels: plain
161 // contentLength - scroll - scrollLength is the gap between the last real row
162 // and the visible edge above the composer. LegendList's own isAtEnd subtracts
163 // the inset and is true anywhere in the bottom composer-height band, so it is
164 // only a fallback here, never a short-circuit.
165 return contentLength - scroll - scrollLength <= TIMELINE_FOLLOW_REARM_THRESHOLD_PX;
167​
168export function shouldPreserveAssistantLineBreaks(text: string): boolean {
169 return /^★ Insight(?:\s|─)/mu.test(text);
171​
172export function resolveTimelineMinimapHeightStyle(itemCount: number): string {
173 const naturalHeight = Math.max(1, (itemCount - 1) * TIMELINE_MINIMAP_ITEM_SPACING);
174 return `min(${naturalHeight}px, ${TIMELINE_MINIMAP_MAX_HEIGHT_CSS})`;
176​
177export function resolveTimelineMinimapTopPercent(index: number, itemCount: number): number {
178 if (itemCount <= 1) {
179 return 0;
180 }
181 return (Math.max(0, Math.min(index, itemCount - 1)) / (itemCount - 1)) * 100;
183​
184export function resolveTimelineMinimapIndexFromPointer(input: {
185 readonly itemCount: number;
186 readonly railTop: number;
187 readonly railHeight: number;
188 readonly pointerY: number;
189}): number | null {
190 if (input.itemCount <= 0 || input.railHeight <= 0) {
191 return null;
192 }
193 if (input.itemCount === 1) {
194 return 0;
195 }
196​
197 const progress = Math.max(0, Math.min(1, (input.pointerY - input.railTop) / input.railHeight));
198 return Math.max(0, Math.min(input.itemCount - 1, Math.round(progress * (input.itemCount - 1))));
200​
201export function resolveTimelineMinimapHasPersistentGutter(viewportWidth: number): boolean {
202 if (!Number.isFinite(viewportWidth) || viewportWidth <= 0) {
203 return false;
204 }
205​
206 const contentWidth = Math.min(viewportWidth, TIMELINE_CONTENT_MAX_WIDTH);
207 const sideGutter = Math.max(0, (viewportWidth - contentWidth) / 2);
208 return sideGutter >= TIMELINE_MINIMAP_PERSISTENT_GUTTER;
210​
211export const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 12;
212export const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40;
213export const TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH = "22rem";
214​
215/**
216 * The minimap overlays the viewport's left edge while the content column is
217 * centered, so the side gutter between them shrinks under browser zoom or a
218 * narrow pane. A fixed-width hover strip would then sit on top of the message
219 * text and swallow its pointer events. Cap the strip's width so it never
220 * extends past the gutter into the content column; 0 disables the strip.
221 */
222export function resolveTimelineMinimapHitStripWidth(viewportWidth: number): number {
223 if (!Number.isFinite(viewportWidth) || viewportWidth <= 0) {
224 return 0;
225 }
226​
227 const contentWidth = Math.min(viewportWidth, TIMELINE_CONTENT_MAX_WIDTH);
228 const sideGutter = Math.max(0, (viewportWidth - contentWidth) / 2);
229 return Math.max(
230 0,
231 Math.min(
232 TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH,
233 Math.floor(sideGutter) - TIMELINE_MINIMAP_HIT_STRIP_LEFT,
234 ),
235 );
237​
238/**
239 * Once the preview is open, keep the full preview and the space leading to it
240 * interactive. The collapsed strip remains gutter-capped so it cannot block
241 * selecting message text.
242 */
243export function resolveTimelineMinimapInteractiveWidth(
244 collapsedWidth: number,
245 expanded: boolean,
246): number | string {
247 return expanded ? TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH : collapsedWidth;
249​
250function computeElapsedMs(startIso: string, endIso: string): number | null {
251 const start = Date.parse(startIso);
252 const end = Date.parse(endIso);
253 if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
254 return Math.max(0, end - start);
256​
257function maxIsoTimestamp(a: string | null, b: string | null): string | null {
258 if (a === null) return b;
259 if (b === null) return a;
260 const aMs = Date.parse(a);
261 const bMs = Date.parse(b);
262 if (!Number.isFinite(aMs)) return b;
263 if (!Number.isFinite(bMs)) return a;
264 return bMs > aMs ? b : a;
266​
267export interface TimelineDurationMessage {
268 id: string;
269 role: "user" | "assistant" | "system";
270 createdAt: string;
271 updatedAt: string;
272 streaming: boolean;
274​
275export type TimelineLatestTurn = Pick<
276 OrchestrationLatestTurn,
277 "turnId" | "state" | "startedAt" | "completedAt"
278>;
279​
280const LIVE_ACTIVITY_ROW_ID = "live-activity-row";
281​
282export type MessagesTimelineRow =
283 | {
284 kind: "work";
285 id: string;
286 createdAt: string;
287 groupedEntries: WorkLogEntry[];
288 isExpandedToolGroup: boolean;
289 displayLabel?: string;
290 }
291 | {
292 kind: "work-live";
293 id: string;
294 createdAt: string;
295 entry: WorkLogEntry;
296 groupedEntries: WorkLogEntry[];
297 groupId: string;
298 expanded: boolean;
299 active: boolean;
300 }
301 | {
302 kind: "work-toggle";
303 id: string;
304 createdAt: string;
305 turnId?: TurnId | null;
306 groupId: string;
307 hiddenCount: number;
308 expanded: boolean;
309 summary: string;
310 summaryKind: ToolGroupSummaryKind;
311 toolSurface?: WorkLogEntry["toolSurface"];
312 toolIcon?: WorkLogEntry["toolIcon"];
313 summaryToolIcon?: "browser" | "t3-code";
314 hasFailure: boolean;
315 }
316 | {
317 kind: "turn-fold";
318 id: string;
319 createdAt: string;
320 turnId: TurnId;
321 label: string;
322 expanded: boolean;
323 }
324 | {
325 kind: "context-compaction";
326 id: string;
327 createdAt: string;
328 label: string;
329 }
330 | {
331 kind: "message";
332 id: string;
333 createdAt: string;
334 message: ChatMessage;
335 durationStart: string;
336 showAssistantMeta: boolean;
337 showAssistantCopyButton: boolean;
338 assistantCopyStreaming: boolean;
339 assistantTurnDiffSummary?: TurnDiffSummary | undefined;
340 revertTurnCount?: number | undefined;
341 }
342 | {
343 kind: "assistant-meta";
344 id: string;
345 createdAt: string;
346 message: ChatMessage;
347 showAssistantCopyButton: boolean;
348 assistantCopyStreaming: boolean;
349 }
350 | {
351 kind: "proposed-plan";
352 id: string;
353 createdAt: string;
354 proposedPlan: ProposedPlan;
355 }
356 | {
357 kind: "working";
358 id: string;
359 createdAt: string | null;
360 }
361 | {
362 kind: "thinking";
363 id: string;
364 createdAt: string | null;
365 };
366​
367export interface StableMessagesTimelineRowsState {
368 byId: Map<string, MessagesTimelineRow>;
369 result: MessagesTimelineRow[];
371​
372export function computeMessageDurationStart(
373 messages: ReadonlyArray<TimelineDurationMessage>,
374): Map<string, string> {
375 const result = new Map<string, string>();
376 let lastBoundary: string | null = null;
377​
378 for (const message of messages) {
379 if (message.role === "user") {
380 lastBoundary = message.createdAt;
381 }
382 result.set(message.id, lastBoundary ?? message.createdAt);
383 if (message.role === "assistant" && !message.streaming) {
384 lastBoundary = message.updatedAt;
385 }
386 }
387​
388 return result;
390​
391function workGroupIdentity(timelineEntryId: string, entry: WorkLogEntry): string {
392 return entry.toolCallId
393 ? `tool:${entry.turnId ?? "no-turn"}:${entry.toolCallId}`
394 : timelineEntryId;
396​
397function workGroupId(timelineEntryId: string, entry: WorkLogEntry): string {
398 return `work-group:${workGroupIdentity(timelineEntryId, entry)}`;
400​
401function expandedWorkGroupRow(
402 groupId: string,
403 createdAt: string,
404 groupedEntries: WorkLogEntry[],
405): Extract<MessagesTimelineRow, { kind: "work" }> {
406 return {
407 kind: "work",
408 id: `${groupId}:details`,
409 createdAt,
410 groupedEntries,
411 isExpandedToolGroup: true,
412 };
414​
415export function resolveAssistantMessageCopyState({
416 text,
417 showCopyButton,
418 streaming,
419}: {
420 text: string | null;
421 showCopyButton: boolean;
422 streaming: boolean;
423}) {
424 const hasText = text !== null && text.trim().length > 0;
425 const visible = showCopyButton && hasText && !streaming;
426 return {
427 text: hasText ? (visible ? renderCodexDirectivesForCopy(text) : text) : null,
428 visible,
429 };
431​
432function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
433 const lastAssistantMessageIdByResponseKey = new Map<string, string>();
434 let nullTurnResponseIndex = 0;
435​
436 for (const timelineEntry of timelineEntries) {
437 if (timelineEntry.kind !== "message") {
438 continue;
439 }
440 const { message } = timelineEntry;
441 if (message.role === "user") {
442 nullTurnResponseIndex += 1;
443 continue;
444 }
445 if (message.role !== "assistant") {
446 continue;
447 }
448​
449 const responseKey = message.turnId
450 ? `turn:${message.turnId}`
451 : `unkeyed:${nullTurnResponseIndex}`;
452 lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
453 }
454​
455 return new Set(lastAssistantMessageIdByResponseKey.values());
457​
458interface TurnFold {
459 turnId: TurnId;
460 anchorEntryId: string;
461 createdAt: string;
462 hiddenEntryIds: ReadonlySet<string>;
463 label: string;
465​
466/**
467 * The session's running turn is authoritative when latestTurn briefly lags or
468 * regresses behind it. Otherwise, the latest turn counts as unsettled while it
469 * is still running (or has not recorded a completion). This is deliberately
470 * keyed on turn lifecycle rather than transient working state: right after the
471 * user sends a message, the previous turn is still the "active" one until the
472 * server creates the new turn, and folding must not flicker through that window.
473 */
474function deriveUnsettledTurnId(
475 latestTurn: TimelineLatestTurn | null,
476 runningTurnId: TurnId | null,
477): TurnId | null {
478 if (runningTurnId !== null) {
479 return runningTurnId;
480 }
481 if (!latestTurn) {
482 return null;
483 }
484 const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
485 return isSettled ? null : latestTurn.turnId;
487​
488function lastUserMessageIndex(timelineEntries: ReadonlyArray<TimelineEntry>): number {
489 return timelineEntries.findLastIndex(
490 (entry) => entry.kind === "message" && entry.message.role === "user",
491 );
493​
494function timelineEntryTurnId(entry: TimelineEntry): TurnId | null {
495 if (entry.kind === "message") {
496 return entry.message.role === "assistant" ? (entry.message.turnId ?? null) : null;
497 }
498 if (entry.kind === "proposed-plan") {
499 return entry.proposedPlan.turnId;
500 }
501 return entry.kind === "work" ? (entry.entry.turnId ?? null) : null;
503​
504/**
505 * A promptless provider restart replaces the native turn without adding a
506 * user message. Keep every provider turn since the latest user message in one
507 * visual response until the replacement turn settles. A steer has its own
508 * user message, so it naturally starts a new visual response.
509 */
510function deriveActiveVisualResponseTurnIds(input: {
511 timelineEntries: ReadonlyArray<TimelineEntry>;
512 unsettledTurnId: TurnId | null;
513 isWorking: boolean;
514}): ReadonlySet<TurnId> {
515 const turnIds = new Set<TurnId>();
516 if (input.unsettledTurnId === null) {
517 return turnIds;
518 }
519​
520 turnIds.add(input.unsettledTurnId);
521 if (!input.isWorking) {
522 return turnIds;
523 }
524​
525 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
526 for (let index = latestUserMessageIndex + 1; index < input.timelineEntries.length; index += 1) {
527 const turnId = timelineEntryTurnId(input.timelineEntries[index]!);
528 if (turnId !== null) {
529 turnIds.add(turnId);
530 }
531 }
532 return turnIds;
534​
535function workEntryIsActiveTurnActivity(entry: WorkLogEntry): boolean {
536 return (
537 entry.toolLifecycleStatus === "inProgress" ||
538 (entry.toolLifecycleStatus === undefined &&
539 (entry.sourceActivityKind === "task.progress" || workLogEntryIsToolLike(entry)))
540 );
542​
543/**
544 * Settled turns fold activity before their terminal assistant message behind
545 * a "Worked for ..." row. A single ordinary activity after that message joins
546 * the fold, while larger groups and failures stay visible as a trailing summary.
547 */
548function deriveTurnFolds(input: {
549 timelineEntries: ReadonlyArray<TimelineEntry>;
550 terminalAssistantMessageIds: ReadonlySet<string>;
551 latestTurn: TimelineLatestTurn | null;
552 unfoldedTurnIds: ReadonlySet<TurnId>;
553}): ReadonlyMap<string, TurnFold> {
554 interface TurnGroup {
555 entries: Array<TimelineEntry>;
556 terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
557 hasStreamingMessage: boolean;
558 /**
559 * The user message that kicked the turn off. Entry timestamps alone
560 * undercount the duration (the first entry appears only once the
561 * provider starts producing output), and a turn cut short by a steer may
562 * hold a single instantaneous commentary message.
563 */
564 startBoundary: string | null;
565 }
566 const groupsByTurnId = new Map<TurnId, TurnGroup>();
567​
568 let pendingUserBoundary: string | null = null;
569 for (const entry of input.timelineEntries) {
570 if (entry.kind === "message" && entry.message.role === "user") {
571 pendingUserBoundary = entry.message.createdAt;
572 continue;
573 }
574 const turnId =
575 entry.kind === "message" && entry.message.role === "assistant"
576 ? (entry.message.turnId ?? null)
577 : entry.kind === "work"
578 ? (entry.entry.turnId ?? null)
579 : null;
580 if (!turnId) {
581 continue;
582 }
583 let group = groupsByTurnId.get(turnId);
584 if (!group) {
585 group = {
586 entries: [],
587 terminalEntry: null,
588 hasStreamingMessage: false,
589 // Each user boundary starts at most one turn; a second turn after the
590 // same user message (e.g. a steer-superseded continuation) falls back
591 // to its own first entry.
592 startBoundary: pendingUserBoundary,
593 };
594 pendingUserBoundary = null;
595 groupsByTurnId.set(turnId, group);
596 }
597 group.entries.push(entry);
598 if (entry.kind === "message") {
599 if (input.terminalAssistantMessageIds.has(entry.message.id)) {
600 group.terminalEntry = entry;
601 }
602 if (entry.message.streaming) {
603 group.hasStreamingMessage = true;
604 }
605 }
606 }
607​
608 const foldsByAnchorEntryId = new Map<string, TurnFold>();
609 for (const [turnId, group] of groupsByTurnId) {
610 if (input.unfoldedTurnIds.has(turnId)) {
611 continue;
612 }
613 if (group.hasStreamingMessage) {
614 continue;
615 }
616 const hiddenEntryIds = new Set<string>();
617 const terminalEntryIndex = group.terminalEntry
618 ? group.entries.findIndex((entry) => entry.id === group.terminalEntry?.id)
619 : group.entries.length;
620 for (const [index, entry] of group.entries.entries()) {
621 if (entry.id === group.terminalEntry?.id) {
622 continue;
623 }
624 const isCompaction =
625 entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction";
626 const isSingleTrailingActivity =
627 group.entries.length === terminalEntryIndex + 2 &&
628 entry.kind === "work" &&
629 !workEntryDisplayIndicatesToolFailure(entry.entry);
630 if (!isCompaction && index > terminalEntryIndex && !isSingleTrailingActivity) {
631 continue;
632 }
633 // Agent-spawn CTA rows never fold: workflows outlive their launching
634 // turn (dynamic spawns, background execution), and folding the CTA
635 // when the turn settles makes a still-running fleet invisible.
636 if (entry.kind === "work" && entry.entry.agentSpawn !== undefined) {
637 continue;
638 }
639 hiddenEntryIds.add(entry.id);
640 }
641 if (hiddenEntryIds.size === 0) {
642 continue;
643 }
644 // A lone compaction row stays visible on its own; it only folds away as
645 // part of a turn that already folds other work.
646 const hidesNonCompactionWork = group.entries.some(
647 (entry) =>
648 hiddenEntryIds.has(entry.id) &&
649 !(entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction"),
650 );
651 if (!hidesNonCompactionWork) {
652 continue;
653 }
654​
655 const firstEntry = group.entries[0];
656 const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
657 const lastEntry = group.entries.at(-1);
658 if (!firstEntry || !firstHiddenEntry || !lastEntry) {
659 continue;
660 }
661​
662 const isLatestInterruptedTurn =
663 input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
664 // A turn cut short by a steer leaves trailing work entries behind its
665 // terminal message — take whichever ended last.
666 const lastEntryEnd =
667 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
668 const elapsedMs =
669 input.latestTurn?.turnId === turnId &&
670 input.latestTurn.startedAt &&
671 input.latestTurn.completedAt
672 ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
673 : computeElapsedMs(
674 group.startBoundary ?? firstEntry.createdAt,
675 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
676 lastEntryEnd,
677 );
678 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
679 const label = isLatestInterruptedTurn
680 ? duration
681 ? `You stopped after ${duration}`
682 : "You stopped this response"
683 : duration
684 ? `Worked for ${duration}`
685 : "Worked";
686​
687 foldsByAnchorEntryId.set(firstHiddenEntry.id, {
688 turnId,
689 anchorEntryId: firstHiddenEntry.id,
690 createdAt: firstHiddenEntry.createdAt,
691 hiddenEntryIds,
692 label,
693 });
694 }
695 return foldsByAnchorEntryId;
697​
698/**
699 * When a settled turn ends with tool calls after its terminal text, treat the
700 * text and tools as one visual response. The message metadata becomes the
701 * footer for the whole block instead of separating the prose from the tools.
702 */
703function attachTrailingToolGroupsToAssistant(
704 rows: ReadonlyArray<MessagesTimelineRow>,
705): MessagesTimelineRow[] {
706 const messageRowsWithoutMeta = new Set<string>();
707 const metaRowsAfterIndex = new Map<
708 number,
709 Extract<MessagesTimelineRow, { kind: "assistant-meta" }>
710 >();
711​
712 for (const [messageIndex, row] of rows.entries()) {
713 const turnId = row.kind === "message" ? (row.message.turnId ?? null) : null;
714 if (
715 row.kind !== "message" ||
716 row.message.role !== "assistant" ||
717 !row.showAssistantMeta ||
718 turnId === null
719 ) {
720 continue;
721 }
722​
723 let lastTrailingWorkIndex = -1;
724 let hasTrailingToolGroup = false;
725 for (let index = messageIndex + 1; index < rows.length; index += 1) {
726 const candidate = rows[index];
727 if (!candidate || candidate.kind === "message") {
728 break;
729 }
730 if (candidate.kind === "work-toggle" && candidate.turnId === turnId) {
731 hasTrailingToolGroup = true;
732 lastTrailingWorkIndex = index;
733 continue;
734 }
735 if (
736 candidate.kind === "work" &&
737 candidate.groupedEntries.some((entry) => entry.turnId === turnId)
738 ) {
739 if (
740 !candidate.isExpandedToolGroup &&
741 candidate.groupedEntries.some(workLogEntryIsToolLike)
742 ) {
743 hasTrailingToolGroup = true;
744 }
745 if (hasTrailingToolGroup) {
746 lastTrailingWorkIndex = index;
747 }
748 }
749 }
750​
751 if (lastTrailingWorkIndex < 0) {
752 continue;
753 }
754​
755 messageRowsWithoutMeta.add(row.id);
756 metaRowsAfterIndex.set(lastTrailingWorkIndex, {
757 kind: "assistant-meta",
758 id: `assistant-meta:${row.message.id}`,
759 createdAt: rows[lastTrailingWorkIndex]?.createdAt ?? row.message.updatedAt,
760 message: row.message,
761 showAssistantCopyButton: row.showAssistantCopyButton,
762 assistantCopyStreaming: row.assistantCopyStreaming,
763 });
764 }
765​
766 const result: MessagesTimelineRow[] = [];
767 for (const [index, row] of rows.entries()) {
768 if (row.kind === "message" && messageRowsWithoutMeta.has(row.id)) {
769 result.push({ ...row, showAssistantMeta: false, showAssistantCopyButton: false });
770 } else {
771 result.push(row);
772 }
773 const metaRow = metaRowsAfterIndex.get(index);
774 if (metaRow) {
775 result.push(metaRow);
776 }
777 }
778 return result;
780​
781export function deriveMessagesTimelineRows(input: {
782 timelineEntries: ReadonlyArray<TimelineEntry>;
783 latestTurn?: TimelineLatestTurn | null;
784 runningTurnId?: TurnId | null;
785 expandedTurnIds?: ReadonlySet<TurnId>;
786 expandedWorkGroupIds?: ReadonlySet<string>;
787 isWorking: boolean;
788 activeTurnStartedAt: string | null;
789 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
790 revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
791}): MessagesTimelineRow[] {
792 const nextRows: MessagesTimelineRow[] = [];
793 const durationStartByMessageId = computeMessageDurationStart(
794 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
795 );
796 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
797 const unsettledTurnId = deriveUnsettledTurnId(
798 input.latestTurn ?? null,
799 input.runningTurnId ?? null,
800 );
801 const activeVisualResponseTurnIds = deriveActiveVisualResponseTurnIds({
802 timelineEntries: input.timelineEntries,
803 unsettledTurnId,
804 isWorking: input.isWorking,
805 });
806 const foldsByAnchorEntryId = deriveTurnFolds({
807 timelineEntries: input.timelineEntries,
808 terminalAssistantMessageIds,
809 latestTurn: input.latestTurn ?? null,
810 unfoldedTurnIds: activeVisualResponseTurnIds,
811 });
812 const collapsedEntryIds = new Set<string>();
813 for (const fold of foldsByAnchorEntryId.values()) {
814 if (!input.expandedTurnIds?.has(fold.turnId)) {
815 for (const entryId of fold.hiddenEntryIds) {
816 collapsedEntryIds.add(entryId);
817 }
818 }
819 }
820​
821 let activeTurnHeaderIndex = input.timelineEntries.length;
822 if (input.isWorking) {
823 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
824 activeTurnHeaderIndex = latestUserMessageIndex + 1;
825 }
826 const entryBelongsToActiveTurn = (entry: TimelineEntry, index: number) =>
827 input.isWorking &&
828 index >= activeTurnHeaderIndex &&
829 (unsettledTurnId === null || timelineEntryTurnId(entry) === unsettledTurnId);
830 const workEntryIsInActiveRun = (entry: WorkLogEntry) =>
831 input.isWorking &&
832 unsettledTurnId !== null &&
833 entry.toolLifecycleStatus === "inProgress" &&
834 entry.turnId === unsettledTurnId;
835 const activeToolEntries: Array<Extract<TimelineEntry, { kind: "work" }>> = [];
836 for (let index = input.timelineEntries.length - 1; index >= activeTurnHeaderIndex; index -= 1) {
837 const entry = input.timelineEntries[index]!;
838 if (
839 !entryBelongsToActiveTurn(entry, index) ||
840 entry.kind !== "work" ||
841 entry.entry.agentSpawn !== undefined ||
842 entry.entry.sourceActivityKind === "context-compaction" ||
843 entry.entry.tone === "error"
844 ) {
845 break;
846 }
847 activeToolEntries.unshift(entry);
848 }
849 const visibleActiveToolEntries = omitSupersededLifecycleMarkers(
850 activeToolEntries.filter((entry) => workEntryIsVisibleInGroup(entry.entry, true)),
851 (entry) => entry.entry,
852 );
853 const activeWorkAnchor = activeToolEntries[0];
854 const latestVisibleToolEntry = visibleActiveToolEntries.at(-1);
855 const latestRunningToolEntry = visibleActiveToolEntries.findLast((entry) =>
856 workEntryIsActiveTurnActivity(entry.entry),
857 );
858 const latestToolFailed =
859 latestRunningToolEntry === undefined &&
860 latestVisibleToolEntry !== undefined &&
861 latestVisibleToolEntry.entry.toolLifecycleStatus !== "declined" &&
862 workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry);
863 const latestToolKeepsActivityLive =
864 latestRunningToolEntry !== undefined ||
865 (latestVisibleToolEntry !== undefined &&
866 workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry));
867 const activeWorkPlacementEntryId = latestVisibleToolEntry?.id;
868 const activeWorkRow =
869 activeWorkAnchor && latestVisibleToolEntry && !latestToolFailed
870 ? (() => {
871 const groupId = workGroupId(activeWorkAnchor.id, activeWorkAnchor.entry);
872 return {
873 kind: "work-live" as const,
874 id: latestToolKeepsActivityLive
875 ? LIVE_ACTIVITY_ROW_ID
876 : `work-live:${workGroupIdentity(activeWorkAnchor.id, activeWorkAnchor.entry)}`,
877 createdAt: activeWorkAnchor.createdAt,
878 entry: (latestRunningToolEntry ?? latestVisibleToolEntry).entry,
879 groupedEntries: visibleActiveToolEntries.map((entry) => entry.entry),
880 groupId,
881 expanded: input.expandedWorkGroupIds?.has(groupId) ?? false,
882 active: latestToolKeepsActivityLive,
883 };
884 })()
885 : null;
886 const activeWorkEntryIds = new Set(
887 activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [],
888 );
889 const appendWorkingRow = () => {
890 const latestUserMessage = input.timelineEntries[lastUserMessageIndex(input.timelineEntries)];
891 const visualResponseStartedAt =
892 activeVisualResponseTurnIds.size > 1 &&
893 latestUserMessage?.kind === "message" &&
894 latestUserMessage.message.role === "user"
895 ? latestUserMessage.message.createdAt
896 : input.activeTurnStartedAt;
897 nextRows.push({
898 kind: "working",
899 id: "working-indicator-row",
900 createdAt: visualResponseStartedAt,
901 });
902 };
903 let hasActivityRow = false;
904 const appendActiveWorkRows = () => {
905 if (activeWorkRow === null) return;
906 nextRows.push(activeWorkRow);
907 hasActivityRow ||= activeWorkRow.active;
908 if (!activeWorkRow.expanded) return;
909 nextRows.push(
910 expandedWorkGroupRow(
911 activeWorkRow.groupId,
912 activeWorkRow.createdAt,
913 activeWorkRow.groupedEntries,
914 ),
915 );
916 };
917​
918 for (let index = 0; index < input.timelineEntries.length; index += 1) {
919 const timelineEntry = input.timelineEntries[index];
920 if (!timelineEntry) {
921 continue;
922 }
923​
924 if (input.isWorking && index === activeTurnHeaderIndex) {
925 appendWorkingRow();
926 }
927​
928 if (timelineEntry.id === activeWorkPlacementEntryId) {
929 appendActiveWorkRows();
930 }
931​
932 const anchoredTurnFold = foldsByAnchorEntryId.get(timelineEntry.id);
933 if (anchoredTurnFold) {
934 nextRows.push({
935 kind: "turn-fold",
936 id: `turn-fold:${anchoredTurnFold.turnId}`,
937 createdAt: anchoredTurnFold.createdAt,
938 turnId: anchoredTurnFold.turnId,
939 label: anchoredTurnFold.label,
940 expanded: input.expandedTurnIds?.has(anchoredTurnFold.turnId) ?? false,
941 });
942 }
943​
944 if (collapsedEntryIds.has(timelineEntry.id)) {
945 continue;
946 }
947​
948 if (activeWorkEntryIds.has(timelineEntry.id)) {
949 continue;
950 }
951​
952 if (
953 timelineEntry.kind === "work" &&
954 timelineEntry.entry.sourceActivityKind === "context-compaction"
955 ) {
956 nextRows.push({
957 kind: "context-compaction",
958 id: timelineEntry.id,
959 createdAt: timelineEntry.createdAt,
960 label: timelineEntry.entry.label,
961 });
962 continue;
963 }
964​
965 if (timelineEntry.kind === "work") {
966 if (timelineEntry.entry.agentSpawn !== undefined || timelineEntry.entry.tone === "error") {
967 nextRows.push({
968 kind: "work",
969 id: timelineEntry.id,
970 createdAt: timelineEntry.createdAt,
971 groupedEntries: [timelineEntry.entry],
972 isExpandedToolGroup: false,
973 });
974 continue;
975 }
976 const groupedEntries = [timelineEntry.entry];
977 let cursor = index + 1;
978 while (cursor < input.timelineEntries.length) {
979 const nextEntry = input.timelineEntries[cursor];
980 if (
981 !nextEntry ||
982 nextEntry.kind !== "work" ||
983 nextEntry.entry.agentSpawn !== undefined ||
984 nextEntry.entry.sourceActivityKind === "context-compaction" ||
985 nextEntry.entry.tone === "error" ||
986 activeWorkEntryIds.has(nextEntry.id) ||
987 collapsedEntryIds.has(nextEntry.id) ||
988 foldsByAnchorEntryId.has(nextEntry.id)
989 ) {
990 break;
991 }
992 groupedEntries.push(nextEntry.entry);
993 cursor += 1;
994 }
995 const visibleGroupedEntries = omitSupersededLifecycleMarkers(
996 groupedEntries.filter((entry) =>
997 workEntryIsVisibleInGroup(entry, workEntryIsInActiveRun(entry)),
998 ),
999 (entry) => entry,
1000 );
1001 if (visibleGroupedEntries.length > 0) {
1002 const activeInProgressToolEntries = visibleGroupedEntries.filter(workEntryIsInActiveRun);
1003 if (activeInProgressToolEntries.length > 0) {
1004 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
1005 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
1006 const latestActiveToolEntry = activeInProgressToolEntries.at(-1)!;
1007 nextRows.push({
1008 kind: "work-live",
1009 id: `work-live:${workGroupIdentity(timelineEntry.id, timelineEntry.entry)}`,
1010 createdAt: timelineEntry.createdAt,
1011 entry: latestActiveToolEntry,
1012 groupedEntries: visibleGroupedEntries,
1013 groupId,
1014 expanded,
1015 active: true,
1016 });
1017 hasActivityRow = true;
1018 if (expanded) {
1019 nextRows.push(
1020 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1021 );
1023 } else if (
1024 visibleGroupedEntries.length === 1 &&
1025 workLogEntryIsToolLike(visibleGroupedEntries[0]!)
1026 ) {
1027 const singleEntry = visibleGroupedEntries[0]!;
1028 nextRows.push({
1029 kind: "work",
1030 id: timelineEntry.id,
1031 createdAt: timelineEntry.createdAt,
1032 groupedEntries: visibleGroupedEntries,
1033 isExpandedToolGroup: false,
1034 displayLabel:
1035 toolGroupAction(singleEntry) === "edit"
1036 ? summarizeToolGroup(visibleGroupedEntries)
1037 : singleToolCallLabel(singleEntry),
1038 });
1039 } else {
1040 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
1041 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
1042 const summaryKind = toolGroupSummaryKind(visibleGroupedEntries);
1043 const primarySourceEntry = visibleGroupedEntries.find(
1044 (entry) => entry.toolSource !== undefined,
1045 );
1046 const primarySourceKey = primarySourceEntry?.toolSource?.key;
1047 const primarySourceIcon = primarySourceKey
1048 ? (visibleGroupedEntries.find(
1049 (entry) =>
1050 entry.toolSource?.key === primarySourceKey && entry.toolIcon !== undefined,
1051 )?.toolIcon ?? primarySourceEntry?.toolSource?.icon)
1052 : undefined;
1053 const groupToolSurface =
1054 primarySourceEntry?.toolSurface ??
1055 visibleGroupedEntries.findLast((entry) => entry.toolSurface !== undefined)?.toolSurface;
1056 const groupToolIcon =
1057 primarySourceIcon ??
1058 visibleGroupedEntries.findLast((entry) => entry.toolIcon !== undefined)?.toolIcon;
1059 const latestToolEntry = visibleGroupedEntries.findLast(workLogEntryIsToolLike);
1060 const singleEntry =
1061 visibleGroupedEntries.length === 1 ? (visibleGroupedEntries[0] ?? null) : null;
1062 const usesSingleToolCallLabel =
1063 singleEntry !== null &&
1064 workLogEntryIsToolLike(singleEntry) &&
1065 toolGroupAction(singleEntry) !== "edit";
1066 const summaryToolIcon = usesSingleToolCallLabel
1067 ? resolveWorkEntryToolPresentation(singleEntry, "completed")?.icon
1068 : undefined;
1069 nextRows.push({
1070 kind: "work-toggle",
1071 id: `work-toggle:${timelineEntry.id}`,
1072 createdAt: timelineEntry.createdAt,
1073 turnId: timelineEntry.entry.turnId ?? null,
1074 groupId,
1075 hiddenCount: visibleGroupedEntries.length,
1076 expanded,
1077 summary: usesSingleToolCallLabel
1078 ? singleToolCallLabel(singleEntry)
1079 : singleEntry !== null && !workLogEntryIsToolLike(singleEntry)
1080 ? singleEntry.label
1081 : summarizeToolGroup(visibleGroupedEntries),
1082 summaryKind,
1083 ...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
1084 ...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
1085 ...(summaryToolIcon ? { summaryToolIcon } : {}),
1086 hasFailure:
1087 latestToolEntry !== undefined &&
1088 workEntryDisplayIndicatesToolFailure(latestToolEntry),
1089 });
1090 if (expanded) {
1091 nextRows.push(
1092 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1093 );
1097 index = cursor - 1;
1098 continue;
1100​
1101 if (timelineEntry.kind === "proposed-plan") {
1102 nextRows.push({
1103 kind: "proposed-plan",
1104 id: timelineEntry.id,
1105 createdAt: timelineEntry.createdAt,
1106 proposedPlan: timelineEntry.proposedPlan,
1107 });
1108 continue;
1110​
1111 const assistantResponseStillInProgress =
1112 timelineEntry.message.role === "assistant" &&
1113 timelineEntry.message.turnId !== null &&
1114 timelineEntry.message.turnId !== undefined &&
1115 activeVisualResponseTurnIds.has(timelineEntry.message.turnId);
1116​
1117 const durationStart =
1118 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
1119​
1120 // While the turn is still running, the latest assistant message is only
1121 // provisionally terminal — withhold the metadata row until the turn
1122 // settles so commentary doesn't flash timestamps mid-work.
1123 const showAssistantMeta =
1124 timelineEntry.message.role === "assistant" &&
1125 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
1126 !assistantResponseStillInProgress;
1127​
1128 nextRows.push({
1129 kind: "message",
1130 id: timelineEntry.id,
1131 createdAt: timelineEntry.createdAt,
1132 message: timelineEntry.message,
1133 durationStart,
1134 showAssistantMeta,
1135 showAssistantCopyButton: showAssistantMeta,
1136 assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress,
1137 assistantTurnDiffSummary:
1138 timelineEntry.message.role === "assistant"
1139 ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
1140 : undefined,
1141 revertTurnCount:
1142 timelineEntry.message.role === "user"
1143 ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
1144 : undefined,
1145 });
1147​
1148 if (input.isWorking && activeTurnHeaderIndex === input.timelineEntries.length) {
1149 appendWorkingRow();
1151 if (input.isWorking && (!hasActivityRow || latestToolFailed)) {
1152 nextRows.push({
1153 kind: "thinking",
1154 id: LIVE_ACTIVITY_ROW_ID,
1155 createdAt: input.activeTurnStartedAt,
1156 });
1158​
1159 return attachTrailingToolGroupsToAssistant(nextRows);
1161​
1162type MessagesTimelineRowsInput = Parameters<typeof deriveMessagesTimelineRows>[0];
1163​
1164export interface MessagesTimelineRowsProjection {
1165 readonly input: MessagesTimelineRowsInput;
1166 readonly rows: MessagesTimelineRow[];
1168​
1169function replaceStreamingMessageRows(
1170 input: MessagesTimelineRowsInput,
1171 previous: MessagesTimelineRowsProjection,
1172): MessagesTimelineRow[] | null {
1173 const { timelineEntries: previousEntries, ...previousContext } = previous.input;
1174 const { timelineEntries, ...context } = input;
1175 if (timelineEntries.length !== previousEntries.length || !shallow(previousContext, context)) {
1176 return null;
1178 const replacements = new Map<ChatMessage, ChatMessage>();
1179 for (const [index, entry] of timelineEntries.entries()) {
1180 const previousEntry = previousEntries[index]!;
1181 if (entry === previousEntry) continue;
1182 if (
1183 entry.kind !== "message" ||
1184 previousEntry.kind !== "message" ||
1185 entry.id !== previousEntry.id ||
1186 entry.createdAt !== previousEntry.createdAt
1187 ) {
1188 return null;
1190 if (entry.message === previousEntry.message) continue;
1191 if (!isStreamingMessageTextUpdate(previousEntry.message, entry.message)) return null;
1192 replacements.set(previousEntry.message, entry.message);
1194 if (replacements.size === 0) return previous.rows;
1195 return previous.rows.map((row) => {
1196 if (row.kind !== "message" && row.kind !== "assistant-meta") return row;
1197 const message = replacements.get(row.message);
1198 return message ? { ...row, message } : row;
1199 });
1201​
1202/** Keep one projection per timeline. Reuse rows only when streaming content changes. */
1203export function deriveMessagesTimelineRowsWithState(
1204 input: MessagesTimelineRowsInput,
1205 previous: MessagesTimelineRowsProjection | null = null,
1206): MessagesTimelineRowsProjection {
1207 return {
1208 input,
1209 rows:
1210 (previous === null ? null : replaceStreamingMessageRows(input, previous)) ??
1211 deriveMessagesTimelineRows(input),
1212 };
1214​
1215export function computeStableMessagesTimelineRows(
1216 rows: MessagesTimelineRow[],
1217 previous: StableMessagesTimelineRowsState,
1218): StableMessagesTimelineRowsState {
1219 const next = new Map<string, MessagesTimelineRow>();
1220 let anyChanged = rows.length !== previous.byId.size;
1221​
1222 const result = rows.map((row, index) => {
1223 const prevRow = previous.byId.get(row.id);
1224 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
1225 next.set(row.id, nextRow);
1226 if (!anyChanged && previous.result[index] !== nextRow) {
1227 anyChanged = true;
1229 return nextRow;
1230 });
1231​
1232 return anyChanged ? { byId: next, result } : previous;
1234​
1235/** Shallow field comparison per row variant — avoids deep equality cost. */
1236function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
1237 if (a.kind !== b.kind || a.id !== b.id) return false;
1238​
1239 switch (a.kind) {
1240 case "working":
1241 case "thinking":
1242 return a.createdAt === (b as typeof a).createdAt;
1243​
1244 case "assistant-meta": {
1245 const bm = b as typeof a;
1246 return (
1247 a.createdAt === bm.createdAt &&
1248 a.message === bm.message &&
1249 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1250 a.assistantCopyStreaming === bm.assistantCopyStreaming
1251 );
1253​
1254 case "turn-fold": {
1255 const bf = b as typeof a;
1256 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
1258​
1259 case "context-compaction": {
1260 const bc = b as typeof a;
1261 return a.createdAt === bc.createdAt && a.label === bc.label;
1263​
1264 case "proposed-plan":
1265 return a.proposedPlan === (b as typeof a).proposedPlan;
1266​
1267 case "work": {
1268 const bw = b as typeof a;
1269 return (
1270 a.isExpandedToolGroup === bw.isExpandedToolGroup &&
1271 a.displayLabel === bw.displayLabel &&
1272 Equal.equals(a.groupedEntries, bw.groupedEntries)
1273 );
1275​
1276 case "work-live": {
1277 const bw = b as typeof a;
1278 return (
1279 a.createdAt === bw.createdAt &&
1280 a.groupId === bw.groupId &&
1281 a.expanded === bw.expanded &&
1282 a.active === bw.active &&
1283 Equal.equals(a.entry, bw.entry) &&
1284 Equal.equals(a.groupedEntries, bw.groupedEntries)
1285 );
1287​
1288 case "work-toggle": {
1289 const bw = b as typeof a;
1290 return (
1291 a.createdAt === bw.createdAt &&
1292 a.turnId === bw.turnId &&
1293 a.groupId === bw.groupId &&
1294 a.hiddenCount === bw.hiddenCount &&
1295 a.expanded === bw.expanded &&
1296 a.summary === bw.summary &&
1297 a.summaryKind === bw.summaryKind &&
1298 a.toolSurface === bw.toolSurface &&
1299 Equal.equals(a.toolIcon, bw.toolIcon) &&
1300 a.hasFailure === bw.hasFailure
1301 );
1303​
1304 case "message": {
1305 const bm = b as typeof a;
1306 return (
1307 a.message === bm.message &&
1308 a.durationStart === bm.durationStart &&
1309 a.showAssistantMeta === bm.showAssistantMeta &&
1310 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1311 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
1312 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
1313 a.revertTurnCount === bm.revertTurnCount
1314 );