@steerable/agent-shell-web 0.12.5 → 0.12.7

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
+ }