@steerable/agent-shell-web 0.12.4 → 0.12.6

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.
@@ -0,0 +1,374 @@
1
+ import { Fragment, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
2
+ import { LuChevronDown, LuChevronRight } from 'react-icons/lu';
3
+ import {
4
+ useThinkingDisplay,
5
+ type ThinkingDisplayMode,
6
+ } from '@/lib/show-thinking-content';
7
+ import {
8
+ estimateReasoningDurationMs,
9
+ processStatusLabel,
10
+ thinkingFoldLabel,
11
+ } from './process-status';
12
+ import {
13
+ compactProcessBlocks,
14
+ splitTurnProcess,
15
+ type ProcessTimelineBlock,
16
+ } from './turn-timeline';
17
+
18
+ /**
19
+ * Shared Codex / DeepSeek-style turn process disclosure.
20
+ *
21
+ * Separates intermediate process steps (`reasoning`, `tools`, pre-tool `text`)
22
+ * from the trailing final answer, tracks per-round thinking durations while
23
+ * streaming, and collapses finished work behind one summary line. When
24
+ * `thinkingDisplay === 'hidden'`, reasoning blocks are filtered out and
25
+ * adjacent tool groups merge into a single block.
26
+ */
27
+
28
+ export const THINKING_PEEK_LINES = 5;
29
+ /** 思考正文行高(`leading-snug`)。 */
30
+ const THINKING_LINE_HEIGHT = 1.375;
31
+ /**
32
+ * 最多 5 行:用 max-height,短思考按内容收,不撑空。
33
+ * 不用 CSS `lh`:Windows Electron 在中文字体尚未就绪时 `lh` 会算成 0,
34
+ * 思考 peek 整块消失,字体加载后又把主列表高度撑跳。
35
+ */
36
+ export const THINKING_PEEK_HEIGHT = `${THINKING_PEEK_LINES * THINKING_LINE_HEIGHT}em`;
37
+
38
+ const THINKING_TEXT =
39
+ 'border-l border-agent-border/70 pl-2 text-xs leading-snug text-agent-muted-foreground';
40
+
41
+ function splitThinkingParagraphs(content: string): string[] {
42
+ return content.split(/\n{2,}/).filter((part) => part.length > 0);
43
+ }
44
+
45
+ function ReasoningBody({
46
+ content,
47
+ showCursor,
48
+ }: {
49
+ content: string;
50
+ showCursor?: boolean;
51
+ }) {
52
+ const parts = splitThinkingParagraphs(content);
53
+ return (
54
+ <>
55
+ <div className="space-y-1">
56
+ {parts.map((part, index) => (
57
+ <div key={index} className="whitespace-pre-wrap break-words">
58
+ {part}
59
+ </div>
60
+ ))}
61
+ </div>
62
+ {showCursor ? (
63
+ <span className="ml-0.5 inline-block h-3 w-[2px] animate-agent-cursor-blink bg-agent-muted-foreground/60 align-text-bottom" />
64
+ ) : null}
65
+ </>
66
+ );
67
+ }
68
+
69
+ export function resolveThinkingDisplay(
70
+ preference: ThinkingDisplayMode,
71
+ thinkingDisplay?: ThinkingDisplayMode,
72
+ showThinkingContent?: boolean,
73
+ ): ThinkingDisplayMode {
74
+ if (thinkingDisplay) return thinkingDisplay;
75
+ if (showThinkingContent === true) return 'full';
76
+ if (showThinkingContent === false) return 'peek';
77
+ return preference;
78
+ }
79
+
80
+ function useLiveNow(enabled: boolean): number {
81
+ const [now, setNow] = useState(() => Date.now());
82
+ useEffect(() => {
83
+ if (!enabled) return;
84
+ setNow(Date.now());
85
+ const id = window.setInterval(() => setNow(Date.now()), 1000);
86
+ return () => window.clearInterval(id);
87
+ }, [enabled]);
88
+ return now;
89
+ }
90
+
91
+ function ReasoningPane({
92
+ content,
93
+ showCursor,
94
+ clipped,
95
+ }: {
96
+ content: string;
97
+ showCursor?: boolean;
98
+ clipped?: boolean;
99
+ }) {
100
+ const scrollerRef = useRef<HTMLDivElement>(null);
101
+ useLayoutEffect(() => {
102
+ if (!clipped) return;
103
+ const el = scrollerRef.current;
104
+ if (!el) return;
105
+ el.scrollTop = el.scrollHeight;
106
+ }, [clipped, content]);
107
+ const body = (
108
+ <div className={THINKING_TEXT}>
109
+ <ReasoningBody content={content} showCursor={showCursor} />
110
+ </div>
111
+ );
112
+ if (!clipped) return body;
113
+ return (
114
+ <div
115
+ ref={scrollerRef}
116
+ className="overflow-y-auto overflow-anchor-none [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden"
117
+ style={{ maxHeight: THINKING_PEEK_HEIGHT }}
118
+ data-thinking-peek=""
119
+ data-testid="thinking-peek"
120
+ data-peek-lines={THINKING_PEEK_LINES}
121
+ >
122
+ {body}
123
+ </div>
124
+ );
125
+ }
126
+
127
+ function ThinkingFold({
128
+ content,
129
+ label,
130
+ showCursor,
131
+ mode,
132
+ defaultOpen,
133
+ }: {
134
+ content: string;
135
+ label: string;
136
+ showCursor?: boolean;
137
+ mode: ThinkingDisplayMode;
138
+ defaultOpen: boolean;
139
+ }) {
140
+ const [open, setOpen] = useState(defaultOpen);
141
+ useEffect(() => {
142
+ setOpen(defaultOpen);
143
+ }, [defaultOpen]);
144
+
145
+ if (mode === 'hidden') return null;
146
+
147
+ return (
148
+ <div className="space-y-1" data-testid="turn-thinking">
149
+ <button
150
+ type="button"
151
+ 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"
153
+ aria-expanded={open}
154
+ data-thinking-fold=""
155
+ >
156
+ <span className="truncate">{label}</span>
157
+ {open ? (
158
+ <LuChevronDown className="h-3 w-3 shrink-0" />
159
+ ) : (
160
+ <LuChevronRight className="h-3 w-3 shrink-0" />
161
+ )}
162
+ </button>
163
+ {open ? (
164
+ <ReasoningPane
165
+ content={content}
166
+ showCursor={showCursor}
167
+ clipped={mode === 'peek'}
168
+ />
169
+ ) : null}
170
+ </div>
171
+ );
172
+ }
173
+
174
+ export interface TurnProcessTimelineProps<TTool = unknown> {
175
+ blocks: ReadonlyArray<ProcessTimelineBlock<TTool>>;
176
+ isStreaming: boolean;
177
+ startedAtMs?: number;
178
+ durationMs?: number;
179
+ thinkingDisplay?: ThinkingDisplayMode;
180
+ showThinkingContent?: boolean;
181
+ collapseWhenFinished?: boolean;
182
+ /** When thinkingDisplay === 'hidden', omit reasoning and merge adjacent tool groups. Default true. */
183
+ compactHiddenProcess?: boolean;
184
+ emptyFallback?: ReactNode;
185
+ streamingHint?: ReactNode;
186
+ processFooter?: ReactNode;
187
+ renderTools: (actions: TTool[], index: number) => ReactNode;
188
+ renderIntermediateText: (
189
+ block: Extract<ProcessTimelineBlock<TTool>, { type: 'text' }>,
190
+ isLiveLast: boolean,
191
+ index: number,
192
+ ) => ReactNode;
193
+ renderAnswer: (
194
+ block: Extract<ProcessTimelineBlock<TTool>, { type: 'text' }>,
195
+ isLast: boolean,
196
+ index: number,
197
+ ) => ReactNode;
198
+ }
199
+
200
+ export function TurnProcessTimeline<TTool = unknown>({
201
+ blocks,
202
+ isStreaming,
203
+ startedAtMs,
204
+ durationMs,
205
+ thinkingDisplay: thinkingDisplayProp,
206
+ showThinkingContent: showThinkingContentProp,
207
+ collapseWhenFinished = true,
208
+ compactHiddenProcess = true,
209
+ emptyFallback,
210
+ streamingHint,
211
+ processFooter,
212
+ renderTools,
213
+ renderIntermediateText,
214
+ renderAnswer,
215
+ }: TurnProcessTimelineProps<TTool>) {
216
+ const preference = useThinkingDisplay();
217
+ const thinkingDisplay = resolveThinkingDisplay(
218
+ preference,
219
+ thinkingDisplayProp,
220
+ showThinkingContentProp,
221
+ );
222
+ const showFullThinking = thinkingDisplay === 'full';
223
+ const hideThinking = thinkingDisplay === 'hidden';
224
+ const { process, answer } = splitTurnProcess(blocks, { finalize: !isStreaming });
225
+ const visibleProcess = compactProcessBlocks(process, {
226
+ hideThinking: hideThinking && compactHiddenProcess,
227
+ });
228
+
229
+ const defaultOpen = isStreaming
230
+ ? thinkingDisplay !== 'hidden'
231
+ : showFullThinking && !collapseWhenFinished;
232
+ const [userOpen, setUserOpen] = useState<boolean | null>(null);
233
+ const open = userOpen ?? defaultOpen;
234
+ useEffect(() => {
235
+ setUserOpen(null);
236
+ }, [isStreaming]);
237
+
238
+ const now = useLiveNow(isStreaming);
239
+ const streamClockRef = useRef<number | undefined>(undefined);
240
+ if (isStreaming) {
241
+ streamClockRef.current ??= startedAtMs ?? now;
242
+ } else {
243
+ streamClockRef.current = undefined;
244
+ }
245
+ const liveElapsedMs = isStreaming
246
+ ? Math.max(0, now - (startedAtMs ?? streamClockRef.current ?? now))
247
+ : undefined;
248
+ const lastLiveElapsedRef = useRef<number | undefined>(undefined);
249
+ if (isStreaming && liveElapsedMs != null) {
250
+ lastLiveElapsedRef.current = liveElapsedMs;
251
+ }
252
+ const elapsedMs = isStreaming
253
+ ? liveElapsedMs
254
+ : durationMs ?? lastLiveElapsedRef.current;
255
+
256
+ const lastProcess = visibleProcess[visibleProcess.length - 1];
257
+ const lastIsReasoning = lastProcess?.type === 'reasoning';
258
+ const reasoningDurationsRef = useRef<number[]>([]);
259
+ const reasoningClockRef = useRef<{ index: number; startedAt: number } | null>(null);
260
+ if (isStreaming && lastIsReasoning) {
261
+ const index = visibleProcess.length - 1;
262
+ if (reasoningClockRef.current?.index !== index) {
263
+ const prev = reasoningClockRef.current;
264
+ if (prev) {
265
+ reasoningDurationsRef.current[prev.index] = Math.max(0, now - prev.startedAt);
266
+ }
267
+ reasoningClockRef.current = { index, startedAt: now };
268
+ }
269
+ } else if (reasoningClockRef.current) {
270
+ const prev = reasoningClockRef.current;
271
+ reasoningDurationsRef.current[prev.index] = Math.max(0, now - prev.startedAt);
272
+ reasoningClockRef.current = null;
273
+ }
274
+ const thinkingElapsedByIndex = visibleProcess.map((block, index) => {
275
+ if (block.type !== 'reasoning') return undefined;
276
+ if (
277
+ isStreaming &&
278
+ lastIsReasoning &&
279
+ index === visibleProcess.length - 1 &&
280
+ reasoningClockRef.current
281
+ ) {
282
+ return Math.max(0, now - reasoningClockRef.current.startedAt);
283
+ }
284
+ return reasoningDurationsRef.current[index];
285
+ });
286
+
287
+ if (blocks.length === 0) return <>{emptyFallback}</>;
288
+
289
+ const showToggle =
290
+ process.length > 0 &&
291
+ (isStreaming || visibleProcess.length > 0 || !hideThinking || Boolean(processFooter));
292
+ const showProcess = !showToggle || open;
293
+ const showStreamingHint =
294
+ Boolean(streamingHint) && isStreaming && answer.length === 0 && !showToggle;
295
+ const processIsLive = isStreaming && answer.length === 0;
296
+ const lastVisibleIndex = visibleProcess.length - 1;
297
+
298
+ return (
299
+ <div className="space-y-1" data-turn-timeline>
300
+ {showToggle && (
301
+ <button
302
+ 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"
305
+ aria-expanded={open}
306
+ data-turn-process=""
307
+ data-testid="turn-process-toggle"
308
+ data-open={open || undefined}
309
+ >
310
+ <span className="min-w-0 truncate">
311
+ {processStatusLabel({
312
+ process: visibleProcess,
313
+ isStreaming,
314
+ elapsedMs,
315
+ hideThinking,
316
+ })}
317
+ </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
+ </button>
324
+ )}
325
+ {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
+ })}
363
+ {processFooter}
364
+ </div>
365
+ )}
366
+ {showStreamingHint ? streamingHint : null}
367
+ {answer.map((block, index) => (
368
+ <Fragment key={`answer-${index}`}>
369
+ {renderAnswer(block, index === answer.length - 1, index)}
370
+ </Fragment>
371
+ ))}
372
+ </div>
373
+ );
374
+ }
@@ -9,6 +9,7 @@ import { formatElapsedCompact } from './elapsed';
9
9
  import {
10
10
  countProcessReasoning,
11
11
  countProcessTools,
12
+ type ProcessTimelineBlock,
12
13
  type TurnBlock,
13
14
  } from './turn-timeline';
14
15
 
@@ -71,15 +72,16 @@ function formatElapsedPart(
71
72
 
72
73
  /** Work disclosure: live is only 「工作中」; finished is a counts + duration summary. */
73
74
  export function processStatusLabel(input: {
74
- process: TurnBlock[];
75
+ process: ReadonlyArray<ProcessTimelineBlock<unknown>>;
75
76
  isStreaming: boolean;
76
77
  elapsedMs?: number;
78
+ hideThinking?: boolean;
77
79
  }): string {
78
- const { process, isStreaming, elapsedMs } = input;
80
+ const { process, isStreaming, elapsedMs, hideThinking } = input;
79
81
  if (isStreaming) return t('Working');
80
82
 
81
83
  const parts: string[] = [];
82
- const thinks = countProcessReasoning(process);
84
+ const thinks = hideThinking ? 0 : countProcessReasoning(process);
83
85
  const tools = countProcessTools(process);
84
86
  const elapsed = formatElapsedPart(false, elapsedMs);
85
87
  if (elapsed) parts.push(t('Worked {elapsed}', { elapsed }));
@@ -10,7 +10,7 @@
10
10
 
11
11
  import type { ExecutedAction } from './ExecutedActionsCard';
12
12
 
13
- export type TurnBlock =
13
+ export type ProcessTimelineBlock<TTool = unknown> =
14
14
  | {
15
15
  type: 'reasoning';
16
16
  content: string;
@@ -19,7 +19,9 @@ export type TurnBlock =
19
19
  durationMs?: number;
20
20
  }
21
21
  | { type: 'text'; content: string; sealed?: boolean }
22
- | { type: 'tools'; actions: ExecutedAction[] };
22
+ | { type: 'tools'; actions: TTool[] };
23
+
24
+ export type TurnBlock = ProcessTimelineBlock<ExecutedAction>;
23
25
 
24
26
  /**
25
27
  * 内容指纹:只要屏上会多出/变化一行,它就变。过程面板用它决定「要不要把
@@ -204,26 +206,56 @@ export function parseTurnBlocks(raw: unknown): TurnBlock[] | null {
204
206
  * While streaming, every text block stays in the process as a post-think
205
207
  * response so the next reasoning burst cannot restyle it as thinking.
206
208
  */
207
- export function splitTurnProcess(
208
- blocks: TurnBlock[],
209
+ export function splitTurnProcess<TTool = ExecutedAction>(
210
+ blocks: ReadonlyArray<ProcessTimelineBlock<TTool>>,
209
211
  options?: { finalize?: boolean },
210
212
  ): {
211
- process: TurnBlock[];
212
- answer: Extract<TurnBlock, { type: 'text' }>[];
213
+ process: ProcessTimelineBlock<TTool>[];
214
+ answer: Extract<ProcessTimelineBlock<TTool>, { type: 'text' }>[];
213
215
  } {
214
216
  const finalize = options?.finalize ?? true;
215
217
  if (!finalize) {
216
- return { process: blocks, answer: [] };
218
+ return { process: [...blocks], answer: [] };
217
219
  }
218
220
  let split = blocks.length;
219
221
  while (split > 0 && blocks[split - 1].type === 'text') split -= 1;
220
222
  return {
221
223
  process: blocks.slice(0, split),
222
- answer: blocks.slice(split) as Extract<TurnBlock, { type: 'text' }>[],
224
+ answer: blocks.slice(split) as Extract<ProcessTimelineBlock<TTool>, { type: 'text' }>[],
223
225
  };
224
226
  }
225
227
 
226
- export function countProcessTools(process: TurnBlock[]): number {
228
+ /**
229
+ * Filter thinking blocks and merge consecutive tool groups that become adjacent
230
+ * once reasoning is hidden (Codex-style compact process presentation).
231
+ */
232
+ export function compactProcessBlocks<TTool>(
233
+ process: ReadonlyArray<ProcessTimelineBlock<TTool>>,
234
+ options: { hideThinking: boolean; mergeAdjacentTools?: boolean },
235
+ ): ProcessTimelineBlock<TTool>[] {
236
+ if (!options.hideThinking) return [...process];
237
+ const mergeAdjacentTools = options.mergeAdjacentTools ?? true;
238
+ const out: ProcessTimelineBlock<TTool>[] = [];
239
+ for (const block of process) {
240
+ if (block.type === 'reasoning') continue;
241
+ if (block.type === 'tools' && mergeAdjacentTools) {
242
+ const prev = out[out.length - 1];
243
+ if (prev && prev.type === 'tools') {
244
+ out[out.length - 1] = {
245
+ type: 'tools',
246
+ actions: [...prev.actions, ...block.actions],
247
+ };
248
+ continue;
249
+ }
250
+ }
251
+ out.push(block);
252
+ }
253
+ return out;
254
+ }
255
+
256
+ export function countProcessTools(
257
+ process: ReadonlyArray<ProcessTimelineBlock<unknown>>,
258
+ ): number {
227
259
  let n = 0;
228
260
  for (const block of process) {
229
261
  if (block.type === 'tools') n += block.actions.length;
@@ -231,7 +263,9 @@ export function countProcessTools(process: TurnBlock[]): number {
231
263
  return n;
232
264
  }
233
265
 
234
- export function countProcessReasoning(process: TurnBlock[]): number {
266
+ export function countProcessReasoning(
267
+ process: ReadonlyArray<ProcessTimelineBlock<unknown>>,
268
+ ): number {
235
269
  let n = 0;
236
270
  for (const block of process) {
237
271
  if (block.type === 'reasoning' && block.content.trim().length > 0) n += 1;
@@ -239,6 +273,8 @@ export function countProcessReasoning(process: TurnBlock[]): number {
239
273
  return n;
240
274
  }
241
275
 
242
- export function processHasReasoning(process: TurnBlock[]): boolean {
276
+ export function processHasReasoning(
277
+ process: ReadonlyArray<ProcessTimelineBlock<unknown>>,
278
+ ): boolean {
243
279
  return process.some((block) => block.type === 'reasoning' && block.content.trim().length > 0);
244
280
  }