@steerable/agent-shell-web 0.14.1 → 0.14.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,15 @@
1
1
  import { Fragment, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
2
- import { LuChevronDown, LuChevronRight } from 'react-icons/lu';
2
+ import { LuChevronDown, LuChevronRight, LuSearch } from 'react-icons/lu';
3
3
  import {
4
4
  useThinkingDisplay,
5
5
  type ThinkingDisplayMode,
6
6
  } from '@/lib/show-thinking-content';
7
7
  import {
8
+ summarizeFoldedRoundKinds,
9
+ type FoldableRoundActionKind,
10
+ } from './executed-actions-model';
11
+ import {
12
+ completedHistoryLabel,
8
13
  estimateReasoningDurationMs,
9
14
  processStatusLabel,
10
15
  thinkingFoldLabel,
@@ -35,8 +40,11 @@ const THINKING_LINE_HEIGHT = 1.375;
35
40
  */
36
41
  export const THINKING_PEEK_HEIGHT = `${THINKING_PEEK_LINES * THINKING_LINE_HEIGHT}em`;
37
42
 
43
+ const TIMELINE_FOLD_BUTTON =
44
+ 'inline-flex max-w-full cursor-pointer items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left text-xs text-agent-muted-foreground transition-colors hover:bg-agent-muted/55 hover:text-agent-foreground';
45
+
38
46
  const THINKING_TEXT =
39
- 'border-l border-agent-border/70 pl-2 text-xs leading-snug text-agent-muted-foreground';
47
+ 'ml-3 border-l border-agent-border/70 pl-[11px] text-xs leading-snug text-agent-muted-foreground';
40
48
 
41
49
  function splitThinkingParagraphs(content: string): string[] {
42
50
  return content.split(/\n{2,}/).filter((part) => part.length > 0);
@@ -149,16 +157,16 @@ function ThinkingFold({
149
157
  <button
150
158
  type="button"
151
159
  onClick={() => setOpen((value) => !value)}
152
- className="flex min-w-0 items-center gap-1 py-0.5 text-left text-[11px] text-agent-muted-foreground/80 transition-colors hover:text-agent-foreground"
160
+ className={TIMELINE_FOLD_BUTTON}
153
161
  aria-expanded={open}
154
162
  data-thinking-fold=""
155
163
  >
156
- <span className="truncate">{label}</span>
157
164
  {open ? (
158
165
  <LuChevronDown className="h-3 w-3 shrink-0" />
159
166
  ) : (
160
167
  <LuChevronRight className="h-3 w-3 shrink-0" />
161
168
  )}
169
+ <span className="truncate">{label}</span>
162
170
  </button>
163
171
  {open ? (
164
172
  <ReasoningPane
@@ -171,14 +179,392 @@ function ThinkingFold({
171
179
  );
172
180
  }
173
181
 
182
+ function StreamingHistoryFold({
183
+ label,
184
+ open,
185
+ onToggle,
186
+ children,
187
+ }: {
188
+ label: string;
189
+ open: boolean;
190
+ onToggle: () => void;
191
+ children: ReactNode;
192
+ }) {
193
+ return (
194
+ <div className="space-y-1" data-testid="turn-history-section">
195
+ <button
196
+ type="button"
197
+ onClick={onToggle}
198
+ aria-expanded={open}
199
+ data-testid="turn-history-fold"
200
+ className={TIMELINE_FOLD_BUTTON}
201
+ >
202
+ {open ? (
203
+ <LuChevronDown className="h-3 w-3 shrink-0" />
204
+ ) : (
205
+ <LuChevronRight className="h-3 w-3 shrink-0" />
206
+ )}
207
+ <span className="truncate">{label}</span>
208
+ </button>
209
+ {open ? (
210
+ <div className="ml-3 space-y-1 border-l border-agent-border/50 pl-2">
211
+ {children}
212
+ </div>
213
+ ) : null}
214
+ </div>
215
+ );
216
+ }
217
+
218
+ function ProcessRoundsFold({
219
+ summary,
220
+ isSearchOnly,
221
+ collapsedPreview,
222
+ children,
223
+ }: {
224
+ summary: string;
225
+ isSearchOnly: boolean;
226
+ collapsedPreview?: (controls: { expand: () => void }) => ReactNode;
227
+ children: ReactNode;
228
+ }) {
229
+ const [open, setOpen] = useState(false);
230
+ return (
231
+ <div className="space-y-0.5" data-testid="turn-rounds-section">
232
+ <button
233
+ type="button"
234
+ onClick={() => setOpen((value) => !value)}
235
+ aria-expanded={open}
236
+ data-testid="turn-rounds-fold"
237
+ className={TIMELINE_FOLD_BUTTON}
238
+ >
239
+ {open ? (
240
+ <LuChevronDown className="h-3 w-3 shrink-0" />
241
+ ) : isSearchOnly ? (
242
+ <LuSearch className="h-3 w-3 shrink-0" />
243
+ ) : (
244
+ <LuChevronRight className="h-3 w-3 shrink-0" />
245
+ )}
246
+ <span className="truncate">{summary}</span>
247
+ </button>
248
+ {!open && collapsedPreview
249
+ ? collapsedPreview({ expand: () => setOpen(true) })
250
+ : null}
251
+ {open ? (
252
+ <div className="ml-3 space-y-1 border-l border-agent-border/50 pl-2">
253
+ {children}
254
+ </div>
255
+ ) : null}
256
+ </div>
257
+ );
258
+ }
259
+
260
+ export interface IndexedProcessBlock<TTool = unknown> {
261
+ block: ProcessTimelineBlock<TTool>;
262
+ index: number;
263
+ }
264
+
265
+ export type ProcessDisplaySegment<TTool = unknown> =
266
+ | { kind: 'entry'; entry: IndexedProcessBlock<TTool> }
267
+ | {
268
+ kind: 'round-fold';
269
+ firstIndex: number;
270
+ summary: string;
271
+ isSearchOnly: boolean;
272
+ entries: IndexedProcessBlock<TTool>[];
273
+ };
274
+
275
+ type RoundFoldFlavor = 'routine' | 'image';
276
+
277
+ function classifyToolsBlockForRoundFold<TTool>(
278
+ actions: readonly TTool[],
279
+ classifyAction: (action: TTool) => FoldableRoundActionKind | null,
280
+ ): { flavor: RoundFoldFlavor; kinds: FoldableRoundActionKind[] } | null {
281
+ if (actions.length === 0) return null;
282
+ const kinds: FoldableRoundActionKind[] = [];
283
+ for (const action of actions) {
284
+ const kind = classifyAction(action);
285
+ if (kind === null) return null;
286
+ kinds.push(kind);
287
+ }
288
+ const allImage = kinds.every((kind) => kind === 'image');
289
+ if (allImage) return { flavor: 'image', kinds };
290
+ const anyImage = kinds.some((kind) => kind === 'image');
291
+ if (anyImage) return null;
292
+ return { flavor: 'routine', kinds };
293
+ }
294
+
295
+ /**
296
+ * Fold ≥ 2 consecutive settled routine rounds (`[reasoning?] + tools`) or
297
+ * consecutive `view_image` rounds into a single expandable summary row so
298
+ * expanded multi-round timelines surface failures and milestones instead of
299
+ * walls of single-tool rounds.
300
+ */
301
+ export function groupProcessEntries<TTool>(
302
+ entries: ReadonlyArray<IndexedProcessBlock<TTool>>,
303
+ options: {
304
+ classifyAction?: (action: TTool) => FoldableRoundActionKind | null;
305
+ liveReasoningIndex?: number;
306
+ },
307
+ ): ProcessDisplaySegment<TTool>[] {
308
+ const { classifyAction, liveReasoningIndex } = options;
309
+ if (!classifyAction || entries.length === 0) {
310
+ return entries.map((entry) => ({ kind: 'entry', entry }));
311
+ }
312
+
313
+ const segments: ProcessDisplaySegment<TTool>[] = [];
314
+ let bufferFlavor: RoundFoldFlavor | null = null;
315
+ let bufferUnits: Array<{
316
+ entries: IndexedProcessBlock<TTool>[];
317
+ kinds: FoldableRoundActionKind[];
318
+ }> = [];
319
+
320
+ const flushBuffer = () => {
321
+ if (bufferUnits.length === 0) return;
322
+ if (bufferUnits.length >= 2) {
323
+ const flatEntries = bufferUnits.flatMap((unit) => unit.entries);
324
+ const flatKinds = bufferUnits.flatMap((unit) => unit.kinds);
325
+ const { summary, isSearchOnly } = summarizeFoldedRoundKinds(flatKinds);
326
+ segments.push({
327
+ kind: 'round-fold',
328
+ firstIndex: flatEntries[0]!.index,
329
+ summary,
330
+ isSearchOnly,
331
+ entries: flatEntries,
332
+ });
333
+ } else {
334
+ for (const entry of bufferUnits[0]!.entries) {
335
+ segments.push({ kind: 'entry', entry });
336
+ }
337
+ }
338
+ bufferFlavor = null;
339
+ bufferUnits = [];
340
+ };
341
+
342
+ let cursor = 0;
343
+ while (cursor < entries.length) {
344
+ const current = entries[cursor]!;
345
+ if (
346
+ current.block.type === 'reasoning' &&
347
+ current.index !== liveReasoningIndex &&
348
+ cursor + 1 < entries.length &&
349
+ entries[cursor + 1]!.block.type === 'tools'
350
+ ) {
351
+ const next = entries[cursor + 1]!;
352
+ const nextTools = next.block as Extract<ProcessTimelineBlock<TTool>, { type: 'tools' }>;
353
+ const classified = classifyToolsBlockForRoundFold(nextTools.actions, classifyAction);
354
+ if (classified) {
355
+ if (bufferFlavor !== null && bufferFlavor !== classified.flavor) {
356
+ flushBuffer();
357
+ }
358
+ bufferFlavor = classified.flavor;
359
+ bufferUnits.push({ entries: [current, next], kinds: classified.kinds });
360
+ cursor += 2;
361
+ continue;
362
+ }
363
+ // Keep a round's reasoning paired right above its high-value tools block.
364
+ flushBuffer();
365
+ segments.push({ kind: 'entry', entry: current });
366
+ segments.push({ kind: 'entry', entry: next });
367
+ cursor += 2;
368
+ continue;
369
+ }
370
+
371
+ if (current.block.type === 'tools') {
372
+ const classified = classifyToolsBlockForRoundFold(current.block.actions, classifyAction);
373
+ if (classified) {
374
+ if (bufferFlavor !== null && bufferFlavor !== classified.flavor) {
375
+ flushBuffer();
376
+ }
377
+ bufferFlavor = classified.flavor;
378
+ bufferUnits.push({ entries: [current], kinds: classified.kinds });
379
+ cursor += 1;
380
+ continue;
381
+ }
382
+ }
383
+
384
+ flushBuffer();
385
+ segments.push({ kind: 'entry', entry: current });
386
+ cursor += 1;
387
+ }
388
+
389
+ flushBuffer();
390
+ return segments;
391
+ }
392
+
393
+ function blockPhase<TTool>(block: ProcessTimelineBlock<TTool>): number {
394
+ if (block.type === 'reasoning') return 0;
395
+ if (block.type === 'text') return 1;
396
+ return 2;
397
+ }
398
+
399
+ function selectFeaturedToolIndex<TTool>(
400
+ actions: readonly TTool[],
401
+ isToolRunning?: (action: TTool) => boolean,
402
+ isInteractiveRunningTool?: (action: TTool) => boolean,
403
+ ): number {
404
+ if (isInteractiveRunningTool) {
405
+ for (let i = actions.length - 1; i >= 0; i -= 1) {
406
+ if (isInteractiveRunningTool(actions[i]!)) return i;
407
+ }
408
+ }
409
+ if (isToolRunning) {
410
+ for (let i = actions.length - 1; i >= 0; i -= 1) {
411
+ if (isToolRunning(actions[i]!)) return i;
412
+ }
413
+ }
414
+ return actions.length - 1;
415
+ }
416
+
417
+ export type ProcessStageSegment<TTool = unknown> =
418
+ | {
419
+ kind: 'history-fold';
420
+ key: string;
421
+ entries: IndexedProcessBlock<TTool>[];
422
+ }
423
+ | {
424
+ kind: 'entry';
425
+ entry: IndexedProcessBlock<TTool>;
426
+ };
427
+
428
+ function partitionNonTextTail<TTool>(
429
+ tail: ReadonlyArray<IndexedProcessBlock<TTool>>,
430
+ options?: {
431
+ isToolRunning?: (action: TTool) => boolean;
432
+ isInteractiveRunningTool?: (action: TTool) => boolean;
433
+ },
434
+ ): ProcessStageSegment<TTool>[] {
435
+ if (tail.length === 0) return [];
436
+ const lastPos = tail.length - 1;
437
+ let stagePos = lastPos;
438
+ let earliestPhase = blockPhase(tail[lastPos]!.block);
439
+ while (stagePos > 0) {
440
+ const prevPhase = blockPhase(tail[stagePos - 1]!.block);
441
+ if (prevPhase < earliestPhase) {
442
+ stagePos -= 1;
443
+ earliestPhase = prevPhase;
444
+ } else {
445
+ break;
446
+ }
447
+ }
448
+
449
+ const priorEntries = tail.slice(0, stagePos);
450
+ const lastEntry = tail[lastPos]!;
451
+ let historyEntries: IndexedProcessBlock<TTool>[];
452
+ let stageEntries: IndexedProcessBlock<TTool>[];
453
+
454
+ if (lastEntry.block.type === 'tools' && lastEntry.block.actions.length > 0) {
455
+ const featuredIdx = selectFeaturedToolIndex(
456
+ lastEntry.block.actions,
457
+ options?.isToolRunning,
458
+ options?.isInteractiveRunningTool,
459
+ );
460
+ const featured = lastEntry.block.actions[featuredIdx]!;
461
+ const otherActions = lastEntry.block.actions.filter((_, idx) => idx !== featuredIdx);
462
+ historyEntries =
463
+ otherActions.length > 0
464
+ ? [
465
+ ...priorEntries,
466
+ { block: { type: 'tools', actions: otherActions }, index: lastEntry.index },
467
+ ]
468
+ : [...priorEntries];
469
+ stageEntries = [
470
+ ...tail.slice(stagePos, lastPos),
471
+ { block: { type: 'tools', actions: [featured] }, index: lastEntry.index },
472
+ ];
473
+ } else {
474
+ historyEntries = [...priorEntries];
475
+ stageEntries = tail.slice(stagePos);
476
+ }
477
+
478
+ const out: ProcessStageSegment<TTool>[] = [];
479
+ if (historyEntries.length > 0) {
480
+ out.push({
481
+ kind: 'history-fold',
482
+ key: `tail-${historyEntries[0]!.index}`,
483
+ entries: historyEntries,
484
+ });
485
+ }
486
+ for (const entry of stageEntries) {
487
+ out.push({ kind: 'entry', entry });
488
+ }
489
+ return out;
490
+ }
491
+
492
+ /**
493
+ * Partition `visibleProcess` in Codex commentary style:
494
+ * - Intermediate `text` blocks (non-thinking, non-tool progress narration) stay
495
+ * directly visible in chronological order whenever the process section is open
496
+ * (during streaming and when `Worked for Xs` is expanded).
497
+ * - Only `reasoning` and `tools` steps fold into `StreamingHistoryFold`s, keeping
498
+ * the latest single stage visible at the tail.
499
+ */
500
+ export function partitionProcessSegments<TTool>(
501
+ visibleProcess: ReadonlyArray<ProcessTimelineBlock<TTool>>,
502
+ options?: {
503
+ isToolRunning?: (action: TTool) => boolean;
504
+ isInteractiveRunningTool?: (action: TTool) => boolean;
505
+ },
506
+ ): ProcessStageSegment<TTool>[] {
507
+ if (visibleProcess.length === 0) return [];
508
+ const lastIndex = visibleProcess.length - 1;
509
+ const segments: ProcessStageSegment<TTool>[] = [];
510
+ let buffer: IndexedProcessBlock<TTool>[] = [];
511
+
512
+ const flushPreTextBuffer = () => {
513
+ if (buffer.length === 0) return;
514
+ if (buffer.length === 1 && buffer[0]!.block.type === 'reasoning') {
515
+ segments.push({ kind: 'entry', entry: buffer[0]! });
516
+ } else {
517
+ segments.push({
518
+ kind: 'history-fold',
519
+ key: `pre-${buffer[0]!.index}`,
520
+ entries: buffer,
521
+ });
522
+ }
523
+ buffer = [];
524
+ };
525
+
526
+ for (let index = 0; index < visibleProcess.length; index += 1) {
527
+ const block = visibleProcess[index]!;
528
+ if (block.type === 'text') {
529
+ if (block.content.trim().length === 0 && index < lastIndex) {
530
+ continue;
531
+ }
532
+ flushPreTextBuffer();
533
+ segments.push({ kind: 'entry', entry: { block, index } });
534
+ } else {
535
+ buffer.push({ block, index });
536
+ }
537
+ }
538
+
539
+ segments.push(...partitionNonTextTail(buffer, options));
540
+ return segments;
541
+ }
542
+
174
543
  export interface TurnProcessTimelineProps<TTool = unknown> {
175
544
  blocks: ReadonlyArray<ProcessTimelineBlock<TTool>>;
176
545
  isStreaming: boolean;
546
+ /** True only when the turn terminated in failure; hides self-healed tool error counts on succeeded turns. */
547
+ turnFailed?: boolean;
177
548
  startedAtMs?: number;
178
549
  durationMs?: number;
179
550
  thinkingDisplay?: ThinkingDisplayMode;
180
551
  showThinkingContent?: boolean;
181
552
  collapseWhenFinished?: boolean;
553
+ /** Fold prior stages behind a single summary line, showing only the latest stage. Defaults to `collapseWhenFinished`. */
554
+ collapsePriorStages?: boolean;
555
+ /** Predicate identifying in-flight tool items so active tasks win over settled ones in the latest stage. */
556
+ isToolRunning?: (action: TTool) => boolean;
557
+ /** Predicate identifying interactive tools waiting on user input (`ask_user`), kept visible over sibling tools. */
558
+ isInteractiveRunningTool?: (action: TTool) => boolean;
559
+ /** Predicate identifying terminal housekeeping tools (`todo_write` all done, `present_files`) after final text. */
560
+ isTrailingHousekeepingTool?: (action: TTool) => boolean;
561
+ /** Classifier folding consecutive settled routine or `view_image` rounds into a single expandable row. */
562
+ classifyFoldableRoundAction?: (action: TTool) => FoldableRoundActionKind | null;
563
+ /** Optional inline preview rendered underneath a collapsed `round-fold` summary (e.g. viewed image strip). */
564
+ renderRoundFoldPreview?: (
565
+ actions: TTool[],
566
+ controls: { expand: () => void },
567
+ ) => ReactNode;
182
568
  /** When thinkingDisplay === 'hidden', omit reasoning and merge adjacent tool groups. Default true. */
183
569
  compactHiddenProcess?: boolean;
184
570
  emptyFallback?: ReactNode;
@@ -200,11 +586,18 @@ export interface TurnProcessTimelineProps<TTool = unknown> {
200
586
  export function TurnProcessTimeline<TTool = unknown>({
201
587
  blocks,
202
588
  isStreaming,
589
+ turnFailed = false,
203
590
  startedAtMs,
204
591
  durationMs,
205
592
  thinkingDisplay: thinkingDisplayProp,
206
593
  showThinkingContent: showThinkingContentProp,
207
594
  collapseWhenFinished = true,
595
+ collapsePriorStages = collapseWhenFinished,
596
+ isToolRunning,
597
+ isInteractiveRunningTool,
598
+ isTrailingHousekeepingTool,
599
+ classifyFoldableRoundAction,
600
+ renderRoundFoldPreview,
208
601
  compactHiddenProcess = true,
209
602
  emptyFallback,
210
603
  streamingHint,
@@ -221,7 +614,10 @@ export function TurnProcessTimeline<TTool = unknown>({
221
614
  );
222
615
  const showFullThinking = thinkingDisplay === 'full';
223
616
  const hideThinking = thinkingDisplay === 'hidden';
224
- const { process, answer } = splitTurnProcess(blocks, { finalize: !isStreaming });
617
+ const { process, answer } = splitTurnProcess(blocks, {
618
+ finalize: !isStreaming,
619
+ isTrailingHousekeepingTool,
620
+ });
225
621
  const visibleProcess = compactProcessBlocks(process, {
226
622
  hideThinking: hideThinking && compactHiddenProcess,
227
623
  });
@@ -230,9 +626,11 @@ export function TurnProcessTimeline<TTool = unknown>({
230
626
  ? thinkingDisplay !== 'hidden'
231
627
  : showFullThinking && !collapseWhenFinished;
232
628
  const [userOpen, setUserOpen] = useState<boolean | null>(null);
629
+ const [historyOpenByKey, setHistoryOpenByKey] = useState<Record<string, boolean>>({});
233
630
  const open = userOpen ?? defaultOpen;
234
631
  useEffect(() => {
235
632
  setUserOpen(null);
633
+ setHistoryOpenByKey({});
236
634
  }, [isStreaming]);
237
635
 
238
636
  const now = useLiveNow(isStreaming);
@@ -254,7 +652,7 @@ export function TurnProcessTimeline<TTool = unknown>({
254
652
  : durationMs ?? lastLiveElapsedRef.current;
255
653
 
256
654
  const lastProcess = visibleProcess[visibleProcess.length - 1];
257
- const lastIsReasoning = lastProcess?.type === 'reasoning';
655
+ const lastIsReasoning = lastProcess?.type === 'reasoning' && !lastProcess.sealed;
258
656
  const reasoningDurationsRef = useRef<number[]>([]);
259
657
  const reasoningClockRef = useRef<{ index: number; startedAt: number } | null>(null);
260
658
  if (isStreaming && lastIsReasoning) {
@@ -295,71 +693,156 @@ export function TurnProcessTimeline<TTool = unknown>({
295
693
  const processIsLive = isStreaming && answer.length === 0;
296
694
  const lastVisibleIndex = visibleProcess.length - 1;
297
695
 
696
+ const stageSegments = collapsePriorStages
697
+ ? partitionProcessSegments(visibleProcess, {
698
+ isToolRunning,
699
+ isInteractiveRunningTool,
700
+ })
701
+ : null;
702
+
703
+ const renderProcessEntry = (entry: IndexedProcessBlock<TTool>, keyPrefix = ''): ReactNode => {
704
+ const { block, index } = entry;
705
+ const isLast = index === lastVisibleIndex;
706
+ if (block.type === 'reasoning') {
707
+ const isLive = processIsLive && isLast && !block.sealed;
708
+ const elapsed =
709
+ thinkingElapsedByIndex[index] ??
710
+ block.durationMs ??
711
+ (isLive ? undefined : estimateReasoningDurationMs(block.content));
712
+ return (
713
+ <ThinkingFold
714
+ key={`${keyPrefix}reasoning-${index}`}
715
+ content={block.content}
716
+ label={thinkingFoldLabel({
717
+ content: block.content,
718
+ isLive,
719
+ elapsedMs: elapsed,
720
+ })}
721
+ showCursor={isLive}
722
+ mode={thinkingDisplay}
723
+ defaultOpen={isLive || !collapseWhenFinished}
724
+ />
725
+ );
726
+ }
727
+ if (block.type === 'tools') {
728
+ return (
729
+ <div key={`${keyPrefix}tools-${index}`} data-testid="turn-tools">
730
+ {renderTools(block.actions, index)}
731
+ </div>
732
+ );
733
+ }
734
+ return (
735
+ <div key={`${keyPrefix}text-${index}`} data-testid="turn-response">
736
+ {renderIntermediateText(block, processIsLive && isLast && !block.sealed, index)}
737
+ </div>
738
+ );
739
+ };
740
+
741
+ const liveReasoningIndex = processIsLive && lastIsReasoning ? lastVisibleIndex : undefined;
742
+ const renderProcessEntries = (
743
+ entries: ReadonlyArray<IndexedProcessBlock<TTool>>,
744
+ keyPrefix = '',
745
+ ): ReactNode => {
746
+ const segments = groupProcessEntries(entries, {
747
+ classifyAction: collapseWhenFinished ? classifyFoldableRoundAction : undefined,
748
+ liveReasoningIndex,
749
+ });
750
+ return segments.map((segment) => {
751
+ if (segment.kind === 'round-fold') {
752
+ const foldedActions = renderRoundFoldPreview
753
+ ? segment.entries.flatMap((entry) =>
754
+ entry.block.type === 'tools' ? entry.block.actions : [],
755
+ )
756
+ : [];
757
+ return (
758
+ <ProcessRoundsFold
759
+ key={`${keyPrefix}round-fold-${segment.firstIndex}`}
760
+ summary={segment.summary}
761
+ isSearchOnly={segment.isSearchOnly}
762
+ collapsedPreview={
763
+ renderRoundFoldPreview && foldedActions.length > 0
764
+ ? (controls) => renderRoundFoldPreview(foldedActions, controls)
765
+ : undefined
766
+ }
767
+ >
768
+ {segment.entries.map((entry) =>
769
+ renderProcessEntry(entry, `${keyPrefix}round-${segment.firstIndex}-`),
770
+ )}
771
+ </ProcessRoundsFold>
772
+ );
773
+ }
774
+ return renderProcessEntry(segment.entry, keyPrefix);
775
+ });
776
+ };
777
+
298
778
  return (
299
779
  <div className="space-y-1" data-turn-timeline>
300
780
  {showToggle && (
301
781
  <button
302
782
  type="button"
303
- onClick={() => setUserOpen(!open)}
304
- className="flex w-full items-center gap-1 py-0.5 text-left text-xs text-agent-muted-foreground transition-colors hover:text-agent-foreground"
783
+ onClick={() => {
784
+ const nextOpen = !open;
785
+ setUserOpen(nextOpen);
786
+ if (!nextOpen) setHistoryOpenByKey({});
787
+ }}
788
+ className="inline-flex max-w-full cursor-pointer items-center gap-1 py-0.5 text-left text-xs text-agent-muted-foreground transition-colors hover:text-agent-foreground"
305
789
  aria-expanded={open}
306
790
  data-turn-process=""
307
791
  data-testid="turn-process-toggle"
308
792
  data-open={open || undefined}
309
793
  >
794
+ {open ? (
795
+ <LuChevronDown className="h-3.5 w-3.5 shrink-0" />
796
+ ) : (
797
+ <LuChevronRight className="h-3.5 w-3.5 shrink-0" />
798
+ )}
310
799
  <span className="min-w-0 truncate">
311
800
  {processStatusLabel({
312
801
  process: visibleProcess,
313
802
  isStreaming,
314
803
  elapsedMs,
315
804
  hideThinking,
805
+ turnFailed,
316
806
  })}
317
807
  </span>
318
- {open ? (
319
- <LuChevronDown className="h-3.5 w-3.5 shrink-0" />
320
- ) : (
321
- <LuChevronRight className="h-3.5 w-3.5 shrink-0" />
322
- )}
323
808
  </button>
324
809
  )}
325
810
  {showProcess && (visibleProcess.length > 0 || Boolean(processFooter)) && (
326
- <div className="space-y-1.5">
327
- {visibleProcess.map((block, index) => {
328
- const isLast = index === lastVisibleIndex;
329
- if (block.type === 'reasoning') {
330
- const isLive = processIsLive && isLast;
331
- const elapsed =
332
- thinkingElapsedByIndex[index] ??
333
- block.durationMs ??
334
- (isLive ? undefined : estimateReasoningDurationMs(block.content));
335
- return (
336
- <ThinkingFold
337
- key={`reasoning-${index}`}
338
- content={block.content}
339
- label={thinkingFoldLabel({
340
- content: block.content,
341
- isLive,
342
- elapsedMs: elapsed,
343
- })}
344
- showCursor={isLive}
345
- mode={thinkingDisplay}
346
- defaultOpen={isLive || !collapseWhenFinished}
347
- />
348
- );
349
- }
350
- if (block.type === 'tools') {
351
- return (
352
- <div key={`tools-${index}`} data-testid="turn-tools">
353
- {renderTools(block.actions, index)}
354
- </div>
355
- );
356
- }
357
- return (
358
- <div key={`text-${index}`} data-testid="turn-response">
359
- {renderIntermediateText(block, processIsLive && isLast, index)}
360
- </div>
361
- );
362
- })}
811
+ <div
812
+ className={
813
+ showToggle
814
+ ? 'ml-1.5 space-y-1 border-l border-agent-border/60 pl-3'
815
+ : 'space-y-1.5'
816
+ }
817
+ >
818
+ {stageSegments
819
+ ? stageSegments.map((segment) => {
820
+ if (segment.kind === 'history-fold') {
821
+ const isFoldOpen = Boolean(historyOpenByKey[segment.key]);
822
+ return (
823
+ <StreamingHistoryFold
824
+ key={`history-fold-${segment.key}`}
825
+ label={completedHistoryLabel(
826
+ segment.entries.map((entry) => entry.block),
827
+ { showFailedCount: turnFailed },
828
+ )}
829
+ open={isFoldOpen}
830
+ onToggle={() =>
831
+ setHistoryOpenByKey((prev) => ({
832
+ ...prev,
833
+ [segment.key]: !prev[segment.key],
834
+ }))
835
+ }
836
+ >
837
+ {renderProcessEntries(segment.entries, `history-${segment.key}-`)}
838
+ </StreamingHistoryFold>
839
+ );
840
+ }
841
+ return renderProcessEntry(segment.entry, 'stage-');
842
+ })
843
+ : renderProcessEntries(
844
+ visibleProcess.map((block, index) => ({ block, index })),
845
+ )}
363
846
  {processFooter}
364
847
  </div>
365
848
  )}