Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

IterationTimeline.tsx

568 lines18.6 KB

1import { For, Index, Show, createMemo, createSignal } from 'solid-js'
2import { JsonTree } from '@tanstack/devtools-ui'
3import { useStyles } from '../../styles/use-styles'
4import {
5 createHoverTarget,
6 getHoverDataAttributes,
7 isMessageHighlighted,
8} from '../hooks/preview-model'
9import { formatDuration } from '../utils'
10import { buildSubagentSteps, groupTimeline } from '../../store/subagent-steps'
11import { IterationCard } from './IterationCard'
12import type { HoverTarget } from '../hooks/preview-model'
13import type { Iteration, Message } from '../../store/ai-store'
14import type {
15 AgentStepGroup,
16 SubagentInfo,
17 TimelineGroup,
18} from '../../store/subagent-steps'
19import type { Component } from 'solid-js'
20​
21/** A group of iterations triggered by a single user message */
22type UserMessageGroup = TimelineGroup
23​
24interface IterationTimelineProps {
25 iterations: Array<Iteration>
26 messages: Array<Message>
27 /** Child agents from the hook snapshot. Their steps get their own cards. */
28 subagents?: Array<SubagentInfo>
29 /** The chat's user messages, from the snapshot. They mark the turns. */
30 turns?: Array<Message>
31 hoverTarget?: HoverTarget | null
32 onHoverTarget?: (target: HoverTarget | null) => void
34​
35export const IterationTimeline: Component<IterationTimelineProps> = (props) => {
36 const styles = useStyles()
37 const s = () => styles().iterationTimeline
38​
39 /**
40 * Group iterations by user messages.
41 * Memoized to avoid recomputing on unrelated store changes.
42 */
43 const groups = createMemo(
44 (): Array<UserMessageGroup> =>
45 groupTimeline(
46 props.iterations,
47 props.messages,
48 props.subagents ?? [],
49 props.turns ?? [],
50 ),
51 )
52​
53 return (
54 <div class={s().container}>
55 <Show
56 when={props.iterations.length > 0}
57 fallback={<div class={s().noIterations}>No iterations recorded</div>}
58 >
59 <div class={s().pipeline}>
60 <Index each={groups()}>
61 {(group) => (
62 <UserMessageGroupCard
63 group={group()}
64 allMessages={props.messages}
65 hoverTarget={props.hoverTarget ?? null}
66 onHoverTarget={props.onHoverTarget}
67 />
68 )}
69 </Index>
70 </div>
71 </Show>
72 </div>
73 )
75​
76/** Collapsible system prompt with preview */
77export const SystemPromptItem: Component<{ prompt: string; index: number }> = (
78 props,
79) => {
80 const styles = useStyles()
81 const s = () => styles().iterationTimeline
82 const [expanded, setExpanded] = createSignal(false)
83​
84 const isLong = () => props.prompt.length > 120
85 const preview = () =>
86 isLong() ? props.prompt.slice(0, 120) + '...' : props.prompt
87​
88 return (
89 <div class={s().systemPromptCard}>
90 <div
91 class={s().systemPromptHeader}
92 onClick={() => isLong() && setExpanded(!expanded())}
93 >
94 <span class={s().systemPromptIndex}>#{props.index + 1}</span>
95 <span class={s().systemPromptPreview}>
96 {expanded() ? '' : preview()}
97 </span>
98 <Show when={isLong()}>
99 <span class={s().stepExpandToggle}>
100 {expanded() ? 'collapse' : 'expand'}
101 </span>
102 </Show>
103 </div>
104 <Show when={expanded()}>
105 <pre class={s().systemPromptFull}>{props.prompt}</pre>
106 </Show>
107 </div>
108 )
110​
111/** Card wrapping a user message and its child iterations */
112const UserMessageGroupCard: Component<{
113 group: UserMessageGroup
114 allMessages: Array<Message>
115 hoverTarget: HoverTarget | null
116 onHoverTarget?: (target: HoverTarget | null) => void
117}> = (props) => {
118 const styles = useStyles()
119 const s = () => styles().iterationTimeline
120 const [isOpen, setIsOpen] = createSignal(true)
121 const [configExpanded, setConfigExpanded] = createSignal(false)
122​
123 const group = () => props.group
124 const userMsg = () => group().userMessage
125 const userMessageId = () => userMsg()?.id
126 const iters = () => group().iterations
127​
128 const totalDuration = createMemo(() => {
129 let sum = 0
130 for (const it of iters()) {
131 if (it.completedAt) {
132 sum += it.completedAt - it.startedAt
133 }
134 }
135 return sum > 0 ? sum : undefined
136 })
137​
138 /** Count actual tool invocations across all messages in this group */
139 const toolInvocationCounts = createMemo(() => {
140 const counts = new Map<string, number>()
141 const allMsgIds = new Set<string>()
142 for (const it of iters()) {
143 for (const id of it.messageIds) allMsgIds.add(id)
144 }
145 for (const msg of props.allMessages) {
146 if (allMsgIds.has(msg.id) && msg.toolCalls) {
147 for (const tc of msg.toolCalls) {
148 counts.set(tc.name, (counts.get(tc.name) || 0) + 1)
149 }
150 }
151 }
152 return counts
153 })
154​
155 const totalToolCalls = createMemo(() => {
156 let count = 0
157 for (const v of toolInvocationCounts().values()) count += v
158 return count
159 })
160​
161 // Iterations store CUMULATIVE usage per request, so keep the MAX totalTokens
162 // reading per requestId. Comparing on totalTokens directly (not prompt +
163 // completion) is necessary because some providers — Anthropic, OpenAI o-series
164 // — bundle reasoning tokens into totalTokens that are not summed into
165 // prompt + completion, and a later reading with fewer reasoning tokens would
166 // otherwise overwrite a larger earlier one.
167 const totalUsage = createMemo(() => {
168 const maxByRequest = new Map<
169 string,
170 { prompt: number; completion: number; total: number }
171 >()
172 for (const it of iters()) {
173 if (!it.usage) continue
174 const key = it.requestId || '__default__'
175 const existing = maxByRequest.get(key)
176 if (!existing || it.usage.totalTokens > existing.total) {
177 maxByRequest.set(key, {
178 prompt: it.usage.promptTokens,
179 completion: it.usage.completionTokens,
180 total: it.usage.totalTokens,
181 })
182 }
183 }
184 let prompt = 0
185 let completion = 0
186 let total = 0
187 for (const v of maxByRequest.values()) {
188 prompt += v.prompt
189 completion += v.completion
190 total += v.total
191 }
192 if (total === 0) return undefined
193 return {
194 promptTokens: prompt,
195 completionTokens: completion,
196 totalTokens: total,
197 }
198 })
199​
200 const isActive = () => iters().some((it) => !it.completedAt)
201 const hasError = () => iters().some((it) => it.finishReason === 'error')
202 const allCompleted = () =>
203 iters().every((it) => !!it.completedAt) && !hasError()
204​
205 const groupAccentClass = () => {
206 if (isActive()) return s().cardActive
207 if (hasError()) return s().cardError
208 if (allCompleted()) return s().cardCompleted
209 return ''
210 }
211​
212 const userContent = () => {
213 const msg = userMsg()
214 if (!msg) return '(no user message)'
215 const text = msg.content || ''
216 return text.length > 120 ? text.slice(0, 120) + '...' : text
217 }
218​
219 const handleUserMouseEnter = () => {
220 const messageId = userMessageId()
221 if (messageId) {
222 props.onHoverTarget?.(
223 createHoverTarget({
224 messageIds: [messageId],
225 origin: 'timeline',
226 }),
227 )
228 }
229 }
230​
231 const handleUserMouseLeave = () => {
232 props.onHoverTarget?.(null)
233 }
234​
235 const isUserMessageHighlighted = () => {
236 const messageId = userMessageId()
237 return messageId
238 ? isMessageHighlighted(messageId, props.hoverTarget)
239 : false
240 }
241​
242 // Config from the first iteration of this group
243 const firstIter = createMemo(() => iters()[0])
244​
245 const configSubtitle = () => {
246 const first = firstIter()
247 if (!first) return null
248 const parts: Array<string> = []
249 if (first.model) parts.push(first.model)
250 if (first.provider) parts.push(first.provider)
251 return parts.length > 0 ? parts.join(' \u00B7 ') : null
252 }
253​
254 const toolNames = () => firstIter()?.toolNames || []
255 const systemPrompts = () => firstIter()?.systemPrompts || []
256 const modelOptions = () => firstIter()?.modelOptions
257 const hasModelOptions = () => {
258 const opts = modelOptions()
259 return opts && Object.keys(opts).length > 0
260 }
261​
262 const middlewareTransformCount = createMemo(() => {
263 let count = 0
264 for (const it of iters()) {
265 for (const ev of it.middlewareEvents) {
266 if (ev.hasTransform) count++
267 }
268 }
269 return count
270 })
271​
272 const hasExpandableConfig = () =>
273 toolNames().length > 0 || systemPrompts().length > 0 || hasModelOptions()
274​
275 return (
276 <div
277 {...getHoverDataAttributes({
278 messageIds: userMessageId() ? [userMessageId() ?? ''] : [],
279 })}
280 class={`${s().card} ${groupAccentClass()} ${
281 isUserMessageHighlighted() ? s().cardHighlighted : ''
282 }`}
283 >
284 {/* User message header */}
285 <div
286 class={s().cardHeader}
287 onClick={() => setIsOpen(!isOpen())}
288 onMouseEnter={handleUserMouseEnter}
289 onMouseLeave={handleUserMouseLeave}
290 >
291 <div class={s().userBubble}>U</div>
292 <div class={s().cardHeaderContent}>
293 <span class={s().cardHeaderLabel}>{userContent()}</span>
294 {/* Config subtitle — always visible under user message */}
295 <div class={s().cardSubtitle}>
296 <Show when={configSubtitle()}>
297 <span class={s().subtitleText}>{configSubtitle()}</span>
298 </Show>
299 <Show when={toolNames().length > 0}>
300 <span class={s().subtitleBadge}>
301 {toolNames().length} tool{toolNames().length === 1 ? '' : 's'}
302 </span>
303 </Show>
304 <Show when={systemPrompts().length > 0}>
305 <span class={s().subtitleBadge}>
306 {systemPrompts().length} system prompt
307 {systemPrompts().length === 1 ? '' : 's'}
308 </span>
309 </Show>
310 <Show when={hasModelOptions()}>
311 <span class={s().subtitleBadge}>options</span>
312 </Show>
313 <Show when={middlewareTransformCount() > 0}>
314 <span class={s().subtitleBadgeWarn}>
315 {middlewareTransformCount()} middleware transform
316 {middlewareTransformCount() === 1 ? '' : 's'}
317 </span>
318 </Show>
319 <Show when={hasExpandableConfig()}>
320 <span
321 class={s().subtitleExpandToggle}
322 onClick={(e) => {
323 e.stopPropagation()
324 setConfigExpanded(!configExpanded())
325 }}
326 >
327 {configExpanded() ? 'hide config' : 'show config'}
328 </span>
329 </Show>
330 </div>
331 </div>
332 <div class={s().cardHeaderBadges}>
333 <Show when={iters().length > 0}>
334 <span
335 class={`${s().badge} ${s().badgeDuration}`}
336 title={`${iters().length} ${iters().length === 1 ? 'iteration' : 'iterations'}`}
337 >
338 🔄 {iters().length}
339 </span>
340 </Show>
341 <Show when={totalToolCalls() > 0}>
342 <span
343 class={`${s().badge} ${s().badgeFinishReasonToolCalls}`}
344 title={`${totalToolCalls()} tool ${totalToolCalls() === 1 ? 'call' : 'calls'}`}
345 >
346 🔧 {totalToolCalls()}
347 </span>
348 </Show>
349 <Show when={totalDuration()}>
350 <span
351 class={`${s().badge} ${s().badgeDuration}`}
352 title={formatDuration(totalDuration())}
353 >
354 ⏱️ {formatDuration(totalDuration())}
355 </span>
356 </Show>
357 <Show when={totalUsage()}>
358 {(usage) => (
359 <span
360 class={`${s().badge} ${s().badgeUsage}`}
361 title={`Prompt: ${usage().promptTokens.toLocaleString()} | Completion: ${usage().completionTokens.toLocaleString()}`}
362 >
363 🎯 {usage().totalTokens.toLocaleString()}
364 </span>
365 )}
366 </Show>
367 <Show when={isActive()}>
368 <span class={`${s().badge} ${s().badgeDuration}`}>⟳ streaming</span>
369 </Show>
370 </div>
371 <span class={`${s().chevron} ${isOpen() ? s().chevronOpen : ''}`}>
372 {'\u25B6'}
373 </span>
374 </div>
375​
376 {/* Expandable config details — sits between header and iterations */}
377 <div
378 class={`${s().configPanelWrapper} ${configExpanded() ? s().configPanelWrapperOpen : ''}`}
379 >
380 <div class={s().configPanel}>
381 <div>
382 <Show when={toolNames().length > 0}>
383 <div class={s().configPanelSection}>
384 <span class={s().configPanelLabel}>Tools</span>
385 <div class={s().configToolsList}>
386 <For each={toolNames()}>
387 {(name) => (
388 <span class={s().configToolChip}>
389 {name}
390 <span class={s().configToolChipCount}>
391 {toolInvocationCounts().get(name) || 0}
392 </span>
393 </span>
394 )}
395 </For>
396 </div>
397 </div>
398 </Show>
399 <Show when={systemPrompts().length > 0}>
400 <div class={s().configPanelSection}>
401 <span class={s().configPanelLabel}>
402 System Prompts ({systemPrompts().length})
403 </span>
404 <For each={systemPrompts()}>
405 {(prompt, i) => (
406 <SystemPromptItem prompt={prompt} index={i()} />
407 )}
408 </For>
409 </div>
410 </Show>
411 <Show when={hasModelOptions()}>
412 <div class={s().configPanelSection}>
413 <span class={s().configPanelLabel}>Model Options</span>
414 <div class={s().configJsonTreeContainer}>
415 <JsonTree
416 value={modelOptions()}
417 defaultExpansionDepth={2}
418 copyable
419 />
420 </div>
421 </div>
422 </Show>
423 </div>
424 </div>
425 </div>
426​
427 {/* Iterations list — full width */}
428 <div class={`${s().cardBody} ${isOpen() ? s().cardBodyOpen : ''}`}>
429 <div class={s().cardBodyInner}>
430 <div class={s().iterList}>
431 <For each={iters()}>
432 {(iteration, index) => (
433 <IterationCard
434 iteration={iteration}
435 previousIteration={
436 index() > 0 ? iters()[index() - 1] : undefined
437 }
438 messages={props.allMessages}
439 index={index()}
440 isLast={index() === iters().length - 1}
441 hoverTarget={props.hoverTarget}
442 onHoverTarget={props.onHoverTarget}
443 />
444 )}
445 </For>
446 <For each={group().agents}>
447 {(agentGroup) => (
448 <SubagentStepsCard
449 group={agentGroup}
450 hoverTarget={props.hoverTarget}
451 onHoverTarget={props.onHoverTarget}
452 />
453 )}
454 </For>
455 </div>
456 </div>
457 </div>
458 </div>
459 )
461​
462/** The steps of one child agent, drawn with the same cards as the root. */
463export const SubagentStepsCard: Component<{
464 group?: AgentStepGroup
465 /** Build the steps from the snapshot when no group is given. */
466 agent?: SubagentInfo
467 hoverTarget: HoverTarget | null
468 onHoverTarget?: (target: HoverTarget | null) => void
469}> = (props) => {
470 const styles = useStyles()
471 const s = () => styles().iterationTimeline
472 const [isOpen, setIsOpen] = createSignal(true)
473​
474 const group = createMemo((): AgentStepGroup | undefined => {
475 if (props.group) return props.group
476 if (!props.agent) return undefined
477 return {
478 agent: props.agent,
479 ...buildSubagentSteps(props.agent),
480 source: 'snapshot',
481 }
482 })
483 const agent = () => group()?.agent
484 const iterations = () => group()?.iterations ?? []
485​
486 const accentClass = () => {
487 const status = agent()?.status
488 if (status === 'running') return s().cardActive
489 if (status === 'error') return s().cardError
490 if (status === 'finished') return s().cardCompleted
491 return ''
492 }
493​
494 return (
495 <Show when={agent()}>
496 {(current) => (
497 <div
498 class={`${s().card} ${accentClass()}`}
499 style={{ 'margin-top': '8px' }}
500 data-testid="ai-devtools-subagent-steps"
501 data-agent={current().path}
502 data-source={group()?.source}
503 >
504 <div
505 class={s().cardHeader}
506 role="button"
507 tabIndex={0}
508 aria-expanded={isOpen()}
509 onClick={() => setIsOpen(!isOpen())}
510 onKeyDown={(event) => {
511 if (event.key !== 'Enter' && event.key !== ' ') return
512 event.preventDefault()
513 setIsOpen(!isOpen())
514 }}
515 >
516 <div class={s().userBubble}>
517 {current().name.charAt(0).toUpperCase()}
518 </div>
519 <div class={s().cardHeaderContent}>
520 <span class={s().cardHeaderLabel}>{current().path}</span>
521 <div class={s().cardSubtitle}>
522 <span class={s().subtitleText}>subagent</span>
523 <Show when={current().status}>
524 <span class={s().subtitleBadge}>{current().status}</span>
525 </Show>
526 <Show when={current().error}>
527 <span class={s().subtitleBadgeWarn}>{current().error}</span>
528 </Show>
529 </div>
530 </div>
531 <div class={s().cardHeaderBadges}>
532 <span
533 class={`${s().badge} ${s().badgeDuration}`}
534 title={`${iterations().length} ${iterations().length === 1 ? 'iteration' : 'iterations'}`}
535 >
536 🔄 {iterations().length}
537 </span>
538 </div>
539 <span class={`${s().chevron} ${isOpen() ? s().chevronOpen : ''}`}>
540 {'▶'}
541 </span>
542 </div>
543 <div class={`${s().cardBody} ${isOpen() ? s().cardBodyOpen : ''}`}>
544 <div class={s().cardBodyInner}>
545 <div class={s().iterList}>
546 <For each={iterations()}>
547 {(iteration, index) => (
548 <IterationCard
549 iteration={iteration}
550 previousIteration={
551 index() > 0 ? iterations()[index() - 1] : undefined
552 }
553 messages={group()?.messages ?? []}
554 index={index()}
555 isLast={index() === iterations().length - 1}
556 hoverTarget={props.hoverTarget}
557 onHoverTarget={props.onHoverTarget}
558 />
559 )}
560 </For>
561 </div>
562 </div>
563 </div>
564 </div>
565 )}
566 </Show>
567 )