@optilogic/chat 1.0.0-beta.9 → 1.1.0

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.
Files changed (31) hide show
  1. package/README.md +43 -0
  2. package/dist/index.cjs +709 -79
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +283 -4
  5. package/dist/index.d.ts +283 -4
  6. package/dist/index.js +674 -53
  7. package/dist/index.js.map +1 -1
  8. package/package.json +3 -3
  9. package/src/components/agent-response/AgentResponse.tsx +59 -13
  10. package/src/components/agent-response/components/MetadataRow.tsx +15 -4
  11. package/src/components/agent-response/components/TruncatedMessage.tsx +52 -0
  12. package/src/components/agent-response/components/index.ts +3 -0
  13. package/src/components/agent-response/hooks/useAgentResponseAccumulator.ts +65 -8
  14. package/src/components/agent-response/index.ts +19 -0
  15. package/src/components/agent-response/types.ts +61 -1
  16. package/src/components/agent-timeline/AgentTimeline.tsx +256 -0
  17. package/src/components/agent-timeline/TimelineAgentBlock.tsx +84 -0
  18. package/src/components/agent-timeline/TimelineItem.tsx +97 -0
  19. package/src/components/agent-timeline/index.ts +14 -0
  20. package/src/components/agent-timeline/types.ts +49 -0
  21. package/src/components/agent-timeline/utils.ts +189 -0
  22. package/src/components/hitl-interactions/HITLQuestionPanel.tsx +35 -21
  23. package/src/components/hitl-interactions/index.ts +1 -1
  24. package/src/components/inline-actions/ActionMarkdownRenderer.tsx +60 -0
  25. package/src/components/inline-actions/index.ts +18 -0
  26. package/src/components/inline-actions/parseResponseSegments.ts +66 -0
  27. package/src/components/inline-actions/prompts.ts +41 -0
  28. package/src/components/inline-actions/types.ts +57 -0
  29. package/src/components/user-prompt-input/UserPromptInput.tsx +13 -8
  30. package/src/components/user-prompt-input/types.ts +4 -0
  31. package/src/index.ts +29 -0
@@ -0,0 +1,256 @@
1
+ import { useMemo, useRef, useState, useCallback, type ReactNode } from "react";
2
+ import {
3
+ Brain,
4
+ Wrench,
5
+ BookOpen,
6
+ HardDrive,
7
+ Activity,
8
+ MessageSquare,
9
+ AlertCircle,
10
+ ChevronsDownUp,
11
+ ChevronsUpDown,
12
+ } from "lucide-react";
13
+ import type { TimelineEntry, TimelineEntryType } from "./types";
14
+ import { groupIntoAgentRuns } from "./utils";
15
+ import { TimelineAgentBlock } from "./TimelineAgentBlock";
16
+
17
+ /** Externalized UI state that survives component remounts */
18
+ export interface TimelineUIState {
19
+ expandedItems: Set<string>;
20
+ collapsedRuns: Set<string>;
21
+ activeFilters: Set<TimelineEntryType>;
22
+ }
23
+
24
+ export function createTimelineUIState(): TimelineUIState {
25
+ return {
26
+ expandedItems: new Set(),
27
+ collapsedRuns: new Set(),
28
+ activeFilters: new Set(),
29
+ };
30
+ }
31
+
32
+ /** Icon + label config for each entry type */
33
+ const TYPE_CONFIG: {
34
+ type: TimelineEntryType;
35
+ icon: typeof Brain;
36
+ label: string;
37
+ }[] = [
38
+ { type: "status_update", icon: Activity, label: "Status" },
39
+ { type: "thinking", icon: Brain, label: "Thinking" },
40
+ { type: "tool_call", icon: Wrench, label: "Tools" },
41
+ { type: "knowledge", icon: BookOpen, label: "Knowledge" },
42
+ { type: "memory", icon: HardDrive, label: "Memory" },
43
+ { type: "ai_response", icon: MessageSquare, label: "AI" },
44
+ { type: "error", icon: AlertCircle, label: "Errors" },
45
+ ];
46
+
47
+ interface AgentTimelineProps {
48
+ entries: TimelineEntry[];
49
+ renderMarkdown?: (content: string) => ReactNode;
50
+ /**
51
+ * External UI state store. When provided, expand/collapse/filter state
52
+ * is read from and written to this object (which should be ref-backed
53
+ * in the parent) so it survives component remounts during streaming.
54
+ */
55
+ uiState?: TimelineUIState;
56
+ /**
57
+ * Maximum height of the scrollable timeline container.
58
+ * Defaults to "300px". Set to "none" to disable.
59
+ */
60
+ maxHeight?: string;
61
+ }
62
+
63
+ export function AgentTimeline({ entries, renderMarkdown, uiState, maxHeight = "300px" }: AgentTimelineProps) {
64
+ const containerRef = useRef<HTMLDivElement>(null);
65
+
66
+ // Render tick: forces re-renders AND invalidates useMemo deps when we mutate Sets in-place
67
+ const [renderTick, setRenderTick] = useState(0);
68
+ const forceRender = useCallback(() => setRenderTick((t) => t + 1), []);
69
+
70
+ // Resolve state: prefer external uiState (ref-backed, survives remounts)
71
+ // Fall back to internal state if no external store provided
72
+ const [internalExpandedItems] = useState<Set<string>>(() => new Set());
73
+ const [internalCollapsedRuns] = useState<Set<string>>(() => new Set());
74
+ const [internalActiveFilters] = useState<Set<TimelineEntryType>>(() => new Set());
75
+
76
+ const expandedItems = uiState?.expandedItems ?? internalExpandedItems;
77
+ const collapsedRuns = uiState?.collapsedRuns ?? internalCollapsedRuns;
78
+ const activeFilters = uiState?.activeFilters ?? internalActiveFilters;
79
+
80
+ // Compute which types actually exist in the entries
81
+ const availableTypes = useMemo(() => {
82
+ const types = new Set<TimelineEntryType>();
83
+ for (const entry of entries) {
84
+ types.add(entry.type);
85
+ }
86
+ return types;
87
+ }, [entries]);
88
+
89
+ // Filter entries, then group into runs
90
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- renderTick invalidates when mutated Sets change
91
+ const filteredEntries = useMemo(
92
+ () =>
93
+ activeFilters.size === 0
94
+ ? entries
95
+ : entries.filter((e) => activeFilters.has(e.type)),
96
+ [entries, activeFilters, renderTick],
97
+ );
98
+
99
+ // eslint-disable-next-line react-hooks/exhaustive-deps
100
+ const agentRuns = useMemo(() => groupIntoAgentRuns(filteredEntries), [filteredEntries, renderTick]);
101
+
102
+ // --- Mutators (mutate the set in-place + trigger re-render) ---
103
+
104
+ const toggleFilter = useCallback((type: TimelineEntryType) => {
105
+ if (activeFilters.has(type)) {
106
+ activeFilters.delete(type);
107
+ } else {
108
+ activeFilters.add(type);
109
+ }
110
+ forceRender();
111
+ }, [activeFilters, forceRender]);
112
+
113
+ const clearFilters = useCallback(() => {
114
+ activeFilters.clear();
115
+ forceRender();
116
+ }, [activeFilters, forceRender]);
117
+
118
+ const toggleItemExpanded = useCallback((entryId: string) => {
119
+ if (expandedItems.has(entryId)) {
120
+ expandedItems.delete(entryId);
121
+ } else {
122
+ expandedItems.add(entryId);
123
+ }
124
+ forceRender();
125
+ }, [expandedItems, forceRender]);
126
+
127
+ const collapseAll = useCallback(() => {
128
+ collapsedRuns.clear();
129
+ agentRuns.forEach((run, i) => {
130
+ collapsedRuns.add(`${run.agentName}-${i}`);
131
+ });
132
+ expandedItems.clear();
133
+ forceRender();
134
+ }, [agentRuns, collapsedRuns, expandedItems, forceRender]);
135
+
136
+ const expandAll = useCallback(() => {
137
+ collapsedRuns.clear();
138
+ agentRuns.forEach((run, i) => {
139
+ collapsedRuns.add(`${run.agentName}-${i}:expanded`);
140
+ });
141
+ forceRender();
142
+ }, [agentRuns, collapsedRuns, forceRender]);
143
+
144
+ if (entries.length === 0) return null;
145
+
146
+ const isSingle = agentRuns.length === 1;
147
+ const hasActiveFilter = activeFilters.size > 0;
148
+
149
+ const scrollStyle = maxHeight !== "none" ? { maxHeight } : undefined;
150
+
151
+ return (
152
+ <div
153
+ ref={containerRef}
154
+ className={maxHeight !== "none" ? "overflow-y-auto" : ""}
155
+ style={scrollStyle}
156
+ >
157
+ {/* Filter + controls bar (sticky within scroll container) */}
158
+ <div className="sticky top-0 z-10 bg-background flex items-center gap-1 py-1.5 mb-1 border-b border-border/50 flex-wrap pl-2">
159
+ {/* Type filter chips */}
160
+ {TYPE_CONFIG.filter((tc) => availableTypes.has(tc.type)).map((tc) => {
161
+ const isActive = activeFilters.has(tc.type);
162
+ const count = entries.filter((e) => e.type === tc.type).length;
163
+ return (
164
+ <button
165
+ key={tc.type}
166
+ onClick={() => toggleFilter(tc.type)}
167
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] transition-colors ${
168
+ isActive
169
+ ? "bg-accent text-accent-foreground ring-1 ring-accent-foreground/20"
170
+ : "text-muted-foreground/60 hover:text-muted-foreground hover:bg-muted/50"
171
+ }`}
172
+ title={`${isActive ? "Hide" : "Show only"} ${tc.label}`}
173
+ >
174
+ <tc.icon className="w-3 h-3" />
175
+ <span>{count}</span>
176
+ </button>
177
+ );
178
+ })}
179
+
180
+ {/* Clear filter button */}
181
+ {hasActiveFilter && (
182
+ <button
183
+ onClick={clearFilters}
184
+ className="text-[10px] text-muted-foreground/60 hover:text-muted-foreground px-1"
185
+ >
186
+ Clear
187
+ </button>
188
+ )}
189
+
190
+ {/* Spacer */}
191
+ <div className="flex-1" />
192
+
193
+ {/* Collapse/expand all */}
194
+ {!isSingle && (
195
+ <>
196
+ <button
197
+ onClick={collapseAll}
198
+ className="inline-flex items-center gap-0.5 text-[10px] text-muted-foreground/60 hover:text-muted-foreground px-1 py-0.5 rounded hover:bg-muted/50 transition-colors"
199
+ title="Collapse all"
200
+ >
201
+ <ChevronsDownUp className="w-3 h-3" />
202
+ </button>
203
+ <button
204
+ onClick={expandAll}
205
+ className="inline-flex items-center gap-0.5 text-[10px] text-muted-foreground/60 hover:text-muted-foreground px-1 py-0.5 rounded hover:bg-muted/50 transition-colors"
206
+ title="Expand all"
207
+ >
208
+ <ChevronsUpDown className="w-3 h-3" />
209
+ </button>
210
+ </>
211
+ )}
212
+ </div>
213
+
214
+ {/* Timeline content */}
215
+ {filteredEntries.length === 0 ? (
216
+ <div className="text-[10px] text-muted-foreground/50 py-2 text-center">
217
+ No entries match the selected filters
218
+ </div>
219
+ ) : (
220
+ <div className="space-y-0.5">
221
+ {agentRuns.map((run, i) => {
222
+ const runKey = `${run.agentName}-${i}`;
223
+ const defaultCollapsed = run.depth > 0;
224
+ const isCollapsed = collapsedRuns.has(runKey)
225
+ ? true
226
+ : collapsedRuns.has(`${runKey}:expanded`)
227
+ ? false
228
+ : defaultCollapsed;
229
+
230
+ return (
231
+ <TimelineAgentBlock
232
+ key={runKey}
233
+ block={run}
234
+ renderMarkdown={renderMarkdown}
235
+ isSingleAgent={isSingle}
236
+ isCollapsed={isCollapsed}
237
+ onToggleCollapsed={() => {
238
+ if (isCollapsed) {
239
+ collapsedRuns.delete(runKey);
240
+ collapsedRuns.add(`${runKey}:expanded`);
241
+ } else {
242
+ collapsedRuns.delete(`${runKey}:expanded`);
243
+ collapsedRuns.add(runKey);
244
+ }
245
+ forceRender();
246
+ }}
247
+ expandedItems={expandedItems}
248
+ onToggleItemExpanded={toggleItemExpanded}
249
+ />
250
+ );
251
+ })}
252
+ </div>
253
+ )}
254
+ </div>
255
+ );
256
+ }
@@ -0,0 +1,84 @@
1
+ import type { ReactNode } from "react";
2
+ import { ChevronDown, ChevronRight } from "lucide-react";
3
+ import type { AgentRun } from "./types";
4
+ import { TimelineItem } from "./TimelineItem";
5
+
6
+ interface TimelineAgentBlockProps {
7
+ block: AgentRun;
8
+ renderMarkdown?: (content: string) => ReactNode;
9
+ /** If true, skip the collapsible header and render entries directly */
10
+ isSingleAgent: boolean;
11
+ /** Controlled collapsed state (lifted to AgentTimeline) */
12
+ isCollapsed: boolean;
13
+ onToggleCollapsed: () => void;
14
+ /** Set of entry IDs whose content is expanded (lifted to AgentTimeline) */
15
+ expandedItems: Set<string>;
16
+ onToggleItemExpanded: (entryId: string) => void;
17
+ }
18
+
19
+ export function TimelineAgentBlock({
20
+ block,
21
+ renderMarkdown,
22
+ isSingleAgent,
23
+ isCollapsed,
24
+ onToggleCollapsed,
25
+ expandedItems,
26
+ onToggleItemExpanded,
27
+ }: TimelineAgentBlockProps) {
28
+ const indentPx = block.depth * 16;
29
+
30
+ // Skip header only for a single root-level agent (depth 0).
31
+ // If filtering leaves only a sub-agent, still show the header for context.
32
+ if (isSingleAgent && block.depth === 0) {
33
+ return (
34
+ <div style={{ paddingLeft: `${indentPx}px` }}>
35
+ {block.entries.map((displayEntry, i) => (
36
+ <TimelineItem
37
+ key={displayEntry.entry.id + "-" + i}
38
+ displayEntry={displayEntry}
39
+ renderMarkdown={renderMarkdown}
40
+ isExpanded={expandedItems.has(displayEntry.entry.id)}
41
+ onToggleExpanded={() => onToggleItemExpanded(displayEntry.entry.id)}
42
+ />
43
+ ))}
44
+ </div>
45
+ );
46
+ }
47
+
48
+ return (
49
+ <div style={{ paddingLeft: `${indentPx}px` }}>
50
+ {/* Agent header */}
51
+ <button
52
+ onClick={onToggleCollapsed}
53
+ className="w-full flex items-center gap-1.5 py-1 hover:bg-muted/50 -ml-1 pl-1 pr-2 rounded transition-colors text-left"
54
+ >
55
+ {isCollapsed ? (
56
+ <ChevronRight className="w-3 h-3 text-muted-foreground flex-shrink-0" />
57
+ ) : (
58
+ <ChevronDown className="w-3 h-3 text-muted-foreground flex-shrink-0" />
59
+ )}
60
+ <span className="text-xs font-medium text-foreground/80">
61
+ {block.agentName}
62
+ </span>
63
+ <span className="text-[10px] text-muted-foreground/60">
64
+ ({block.entries.reduce((sum, e) => sum + e.count, 0)})
65
+ </span>
66
+ </button>
67
+
68
+ {/* Entries */}
69
+ {!isCollapsed && (
70
+ <div className="ml-4">
71
+ {block.entries.map((displayEntry, i) => (
72
+ <TimelineItem
73
+ key={displayEntry.entry.id + "-" + i}
74
+ displayEntry={displayEntry}
75
+ renderMarkdown={renderMarkdown}
76
+ isExpanded={expandedItems.has(displayEntry.entry.id)}
77
+ onToggleExpanded={() => onToggleItemExpanded(displayEntry.entry.id)}
78
+ />
79
+ ))}
80
+ </div>
81
+ )}
82
+ </div>
83
+ );
84
+ }
@@ -0,0 +1,97 @@
1
+ import type { ReactNode } from "react";
2
+ import {
3
+ Brain,
4
+ Wrench,
5
+ BookOpen,
6
+ HardDrive,
7
+ Activity,
8
+ MessageSquare,
9
+ AlertCircle,
10
+ } from "lucide-react";
11
+ import type { DisplayEntry, TimelineEntryType } from "./types";
12
+
13
+ const ICON_MAP: Record<TimelineEntryType, typeof Brain> = {
14
+ thinking: Brain,
15
+ tool_call: Wrench,
16
+ knowledge: BookOpen,
17
+ memory: HardDrive,
18
+ status_update: Activity,
19
+ ai_response: MessageSquare,
20
+ error: AlertCircle,
21
+ };
22
+
23
+ interface TimelineItemProps {
24
+ displayEntry: DisplayEntry;
25
+ renderMarkdown?: (content: string) => ReactNode;
26
+ /** Controlled expanded state (lifted to AgentTimeline) */
27
+ isExpanded: boolean;
28
+ onToggleExpanded: () => void;
29
+ }
30
+
31
+ export function TimelineItem({
32
+ displayEntry,
33
+ renderMarkdown,
34
+ isExpanded,
35
+ onToggleExpanded,
36
+ }: TimelineItemProps) {
37
+ const { entry, count } = displayEntry;
38
+
39
+ const Icon = ICON_MAP[entry.type] ?? Activity;
40
+
41
+ // Determine if content is long enough to warrant truncation
42
+ const isLong = entry.content.length > 200 || entry.content.split("\n").length > 3;
43
+ const canExpand = isLong || entry.type === "ai_response";
44
+
45
+ return (
46
+ <div className="py-1 flex items-start gap-2 group">
47
+ {/* Type icon */}
48
+ <Icon className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0 mt-0.5" />
49
+
50
+ {/* Content */}
51
+ <div className="min-w-0 flex-1">
52
+ {isExpanded && entry.type === "ai_response" && renderMarkdown ? (
53
+ // Expanded AI response: rendered markdown
54
+ <div>
55
+ {renderMarkdown(entry.content)}
56
+ <button
57
+ onClick={onToggleExpanded}
58
+ className="text-[10px] text-muted-foreground/70 hover:text-muted-foreground mt-1"
59
+ >
60
+ Show less
61
+ </button>
62
+ </div>
63
+ ) : isExpanded ? (
64
+ // Expanded non-AI: plain text
65
+ <div>
66
+ <pre className="text-xs text-muted-foreground whitespace-pre-wrap font-mono">
67
+ {entry.content}
68
+ </pre>
69
+ <button
70
+ onClick={onToggleExpanded}
71
+ className="text-[10px] text-muted-foreground/70 hover:text-muted-foreground mt-1"
72
+ >
73
+ Show less
74
+ </button>
75
+ </div>
76
+ ) : (
77
+ // Collapsed: truncated with optional expand
78
+ <div className="flex items-baseline gap-1.5 min-w-0">
79
+ <div
80
+ className={`text-xs text-muted-foreground min-w-0 ${canExpand ? "line-clamp-2 cursor-pointer hover:text-foreground/80" : ""}`}
81
+ onClick={canExpand ? onToggleExpanded : undefined}
82
+ >
83
+ {entry.content}
84
+ </div>
85
+
86
+ {/* Dedup count badge */}
87
+ {count > 1 && (
88
+ <span className="text-[10px] text-muted-foreground/60 whitespace-nowrap flex-shrink-0">
89
+ (x{count})
90
+ </span>
91
+ )}
92
+ </div>
93
+ )}
94
+ </div>
95
+ </div>
96
+ );
97
+ }
@@ -0,0 +1,14 @@
1
+ // Components
2
+ export { AgentTimeline, createTimelineUIState } from "./AgentTimeline";
3
+ export type { TimelineUIState } from "./AgentTimeline";
4
+
5
+ // Utilities
6
+ export { buildTimelineEntries, groupIntoAgentRuns, deduplicateEntries } from "./utils";
7
+
8
+ // Types
9
+ export type {
10
+ TimelineEntry,
11
+ TimelineEntryType,
12
+ AgentRun,
13
+ DisplayEntry,
14
+ } from "./types";
@@ -0,0 +1,49 @@
1
+ /** All possible timeline entry types */
2
+ export type TimelineEntryType =
3
+ | "thinking"
4
+ | "tool_call"
5
+ | "knowledge"
6
+ | "memory"
7
+ | "status_update"
8
+ | "ai_response"
9
+ | "error";
10
+
11
+ /** A single event in the agent execution timeline */
12
+ export interface TimelineEntry {
13
+ /** Unique ID for React keys */
14
+ id: string;
15
+ /** Discriminated type for icon and rendering */
16
+ type: TimelineEntryType;
17
+ /** The agent that produced this entry */
18
+ agentName: string | null;
19
+ /** The parent agent (null for root agent) */
20
+ parentAgent: string | null;
21
+ /** Nesting depth (0 = root) */
22
+ depth: number;
23
+ /** Display content (may be long) */
24
+ content: string;
25
+ /** Original title from the WebSocket message */
26
+ title: string | null;
27
+ /** Millisecond timestamp for ordering */
28
+ timestamp: number;
29
+ }
30
+
31
+ /** A consecutive run of messages from the same agent */
32
+ export interface AgentRun {
33
+ /** Agent name (display label) */
34
+ agentName: string;
35
+ /** Parent agent name (null for root) */
36
+ parentAgent: string | null;
37
+ /** Depth in agent hierarchy */
38
+ depth: number;
39
+ /** The entries belonging to this run, in order, after dedup */
40
+ entries: DisplayEntry[];
41
+ }
42
+
43
+ /** After dedup — count > 1 means consecutive identical messages collapsed */
44
+ export interface DisplayEntry {
45
+ /** The underlying timeline entry (first of the group if deduped) */
46
+ entry: TimelineEntry;
47
+ /** How many consecutive identical messages were collapsed into this one */
48
+ count: number;
49
+ }
@@ -0,0 +1,189 @@
1
+ import type { TimelineEntry, AgentRun, DisplayEntry } from "./types";
2
+ import type { AgentResponseState } from "../agent-response/types";
3
+
4
+ /**
5
+ * Build a flat, chronologically sorted array of TimelineEntry from the
6
+ * accumulator state. Maps each typed array (toolCalls, knowledge, etc.)
7
+ * to unified TimelineEntry objects with per-source stable IDs.
8
+ */
9
+ export function buildTimelineEntries(state: AgentResponseState): TimelineEntry[] {
10
+ const entries: TimelineEntry[] = [];
11
+
12
+ // Thinking steps (structured)
13
+ if (state.thinkingSteps) {
14
+ let idx = 0;
15
+ for (const step of state.thinkingSteps) {
16
+ entries.push({
17
+ id: `tl-think-${idx++}`,
18
+ type: "thinking",
19
+ agentName: step.agentName ?? null,
20
+ parentAgent: step.parentAgent ?? null,
21
+ depth: step.depth ?? 0,
22
+ content: step.content,
23
+ title: step.label,
24
+ timestamp: step.timestamp ?? 0,
25
+ });
26
+ }
27
+ } else if (state.thinking) {
28
+ // Plain text thinking (legacy) — single entry
29
+ entries.push({
30
+ id: "tl-think-0",
31
+ type: "thinking",
32
+ agentName: null,
33
+ parentAgent: null,
34
+ depth: 0,
35
+ content: state.thinking,
36
+ title: null,
37
+ timestamp: state.thinkingStartTime ?? 0,
38
+ });
39
+ }
40
+
41
+ // Tool calls
42
+ let toolIdx = 0;
43
+ for (const tool of state.toolCalls) {
44
+ entries.push({
45
+ id: `tl-tool-${toolIdx++}`,
46
+ type: "tool_call",
47
+ agentName: tool.agentName ?? null,
48
+ parentAgent: tool.parentAgent ?? null,
49
+ depth: tool.depth ?? 0,
50
+ content: tool.name,
51
+ title: null,
52
+ timestamp: tool.timestamp,
53
+ });
54
+ }
55
+
56
+ // Knowledge items
57
+ let knowIdx = 0;
58
+ for (const item of state.knowledge) {
59
+ entries.push({
60
+ id: `tl-know-${knowIdx++}`,
61
+ type: "knowledge",
62
+ agentName: item.agentName ?? null,
63
+ parentAgent: item.parentAgent ?? null,
64
+ depth: item.depth ?? 0,
65
+ content: item.content,
66
+ title: item.source,
67
+ timestamp: item.timestamp,
68
+ });
69
+ }
70
+
71
+ // Memory items
72
+ let memIdx = 0;
73
+ for (const item of state.memory) {
74
+ entries.push({
75
+ id: `tl-mem-${memIdx++}`,
76
+ type: "memory",
77
+ agentName: item.agentName ?? null,
78
+ parentAgent: item.parentAgent ?? null,
79
+ depth: item.depth ?? 0,
80
+ content: item.content,
81
+ title: item.type,
82
+ timestamp: item.timestamp,
83
+ });
84
+ }
85
+
86
+ // Status updates
87
+ let statIdx = 0;
88
+ for (const item of state.statusUpdates) {
89
+ entries.push({
90
+ id: `tl-stat-${statIdx++}`,
91
+ type: "status_update",
92
+ agentName: item.agentName ?? item.agent ?? null,
93
+ parentAgent: item.parentAgent ?? null,
94
+ depth: item.depth ?? 0,
95
+ content: item.message,
96
+ title: null,
97
+ timestamp: item.timestamp,
98
+ });
99
+ }
100
+
101
+ // Potential responses → ai_response timeline entries
102
+ if (state.potentialResponses) {
103
+ let respIdx = 0;
104
+ for (const resp of state.potentialResponses) {
105
+ entries.push({
106
+ id: `tl-resp-${respIdx++}`,
107
+ type: "ai_response",
108
+ agentName: resp.agentName ?? null,
109
+ parentAgent: resp.parentAgent ?? null,
110
+ depth: resp.depth ?? 0,
111
+ content: resp.content,
112
+ title: null,
113
+ timestamp: resp.timestamp,
114
+ });
115
+ }
116
+ }
117
+
118
+ // Merge any custom timeline entries (consumer-provided)
119
+ if (state.customTimelineEntries) {
120
+ entries.push(...state.customTimelineEntries);
121
+ }
122
+
123
+ // Sort chronologically
124
+ entries.sort((a, b) => a.timestamp - b.timestamp);
125
+
126
+ return entries;
127
+ }
128
+
129
+ /**
130
+ * Group a sorted array of timeline entries into consecutive "agent runs".
131
+ * A new run starts whenever the agentName changes.
132
+ * Each run's entries are deduplicated.
133
+ */
134
+ export function groupIntoAgentRuns(entries: TimelineEntry[]): AgentRun[] {
135
+ const runs: AgentRun[] = [];
136
+ let currentRun: AgentRun | null = null;
137
+
138
+ for (const entry of entries) {
139
+ const name = entry.agentName || "Agent";
140
+
141
+ if (!currentRun || currentRun.agentName !== name) {
142
+ // Start a new run
143
+ currentRun = {
144
+ agentName: name,
145
+ parentAgent: entry.parentAgent,
146
+ depth: entry.depth,
147
+ entries: [],
148
+ };
149
+ runs.push(currentRun);
150
+ }
151
+
152
+ currentRun.entries.push({ entry, count: 1 });
153
+ }
154
+
155
+ // Deduplicate within each run
156
+ for (const run of runs) {
157
+ run.entries = deduplicateEntries(run.entries);
158
+ }
159
+
160
+ return runs;
161
+ }
162
+
163
+ /**
164
+ * Collapse consecutive entries with identical type AND content into
165
+ * a single DisplayEntry with count > 1.
166
+ * Handles patterns like "Loading documents" appearing 8 times.
167
+ */
168
+ export function deduplicateEntries(entries: DisplayEntry[]): DisplayEntry[] {
169
+ if (entries.length === 0) return [];
170
+
171
+ const result: DisplayEntry[] = [entries[0]];
172
+
173
+ for (let i = 1; i < entries.length; i++) {
174
+ const prev = result[result.length - 1];
175
+ const curr = entries[i];
176
+
177
+ if (
178
+ prev.entry.type === curr.entry.type &&
179
+ prev.entry.content === curr.entry.content
180
+ ) {
181
+ // Merge into previous
182
+ prev.count += curr.count;
183
+ } else {
184
+ result.push({ ...curr });
185
+ }
186
+ }
187
+
188
+ return result;
189
+ }