1. Current Architecture
Data flow
src/tabs/chatbot/chatApp.ts:372-468 — ChatApp.handleSubmit():
- Adds
[You] line.
- Starts metrics.
- Creates
[AI] ⠋ thinking... placeholder at chatApp.ts:410-411.
- Calls
streamQuery() and switches on events at chatApp.ts:431-455.
src/tabs/chatbot/agent/streaming.ts:39-141 — streamQuery():
- Calls LangGraph
graph.streamEvents(..., { version: 'v2' }) at streaming.ts:52-60.
- Converts LangGraph events into app-level
StreamEvent.
src/tabs/chatbot/agent/graph.ts:160-304 — graph nodes:
classify_intent → inject_schema → llm → tools → sql_critic → llm → validate_answer.
- Tool execution is via
ToolNode([...nbaTools]) at graph.ts:244.
src/tabs/chatbot/agent/model.ts:24-37 — OpenRouter via ChatOpenAI, with parallel_tool_calls: true.
Current stream event definitions
src/tabs/chatbot/agent/streaming.ts:20-28:
token
tool_start { name, input, runId }
tool_end { name, output, runId }
tool_error { name, error }
chain_stage { stage }
usage { usage }
done { messages }
error { message }
Current UI handling
- Tokens:
chatApp.ts:286-299
- Appends streamed text into
fullResponse.
- Replaces the current
[AI] line.
- Tool start:
chatApp.ts:301-322
- Shows SQL text for
query_nba_db.
- Shows spinner/status for schema lookup or generic tools.
- Tool end:
chatApp.ts:324-326
- Only records metrics. It does not render a completion line or result summary.
- Tool error:
chatApp.ts:328-333
- Renders visible error via
formatToolErrorLine().
- Chain stage:
chatApp.ts:444-447
- Metrics/debug only. No visible status block.
- Usage:
chatApp.ts:451-454
- Done:
streamQuery() emits done at streaming.ts:133.
ChatApp currently has no explicit done case.
Tool args/results availability
Verified available:
- Tool args are emitted on start from
event.data?.input at streaming.ts:84-92.
- Tool output is emitted on end from
event.data?.output at streaming.ts:95-102.
- Current UI only displays SQL args on start, not output summaries.
2. Gaps
- No pretty status blocks for graph stages, despite
chain_stage events already existing.
- “Thinking” is a spinner placeholder only; it is not updated with safe stage progress.
- Tool completion is invisible to the user because
handleToolEndEvent() only records metrics.
- Tool output exists in
tool_end.output, but no formatter/truncator is used before display.
tool_error lacks runId, making it harder to reconcile visible active tool state with metrics/UI.
activeToolCount increments on start, but only resets on token or decrements on error; successful tool end does not decrement.
- Provider reasoning/thinking content is not currently parsed; token extraction only uses chunk
content text at streaming.ts:69-81. Do not expose hidden chain-of-thought.
3. Minimal Implementation Plan
A. Keep architecture; add formatting helpers
Add a small helper module:
src/tabs/chatbot/utils/streamFormatting.ts
Suggested exports:
formatChainStageStatus(stage: ChainStageName): string
- Maps internal stages to safe summaries:
classify_intent → Classifying question...
inject_schema → Loading relevant schema...
llm → Composing answer...
tools → Preparing tool calls...
sql_critic → Checking SQL result...
validate_answer → Validating answer...
formatToolStartBlock(name, input): string[]
formatToolEndBlock(name, output): string[]
formatToolErrorBlock(name, error): string
summarizeToolInput(input): string
summarizeToolOutput(output): string
truncateMiddle(text, maxChars): string
Formatting/truncation should happen here, not in streaming.ts, so stream events remain raw and testable.
B. Slight event shape improvement
In src/tabs/chatbot/agent/streaming.ts:
- Change active tool map from
Map<string, string> to something like:
Map<string, { name: string; input: Record<string, unknown>; startedAt: number }>
| { type: 'tool_end'; name: string; input?: Record<string, unknown>; output: string; runId: string; durationMs?: number }
| { type: 'tool_error'; name: string; error: string; runId?: string }
This preserves current behavior while making tool end/error rendering more useful.
C. Render safe “thinking/status” blocks
In src/tabs/chatbot/chatApp.ts:
- Import stream formatting helpers.
- Add
handleChainStageEvent().
- On
chain_stage, append or update a dim status line, e.g.:
[Status] Loading relevant schema...
[Status] Running database query...
[Status] Validating answer...
Use statusText()/dim styling. Do not display hidden reasoning or raw provider reasoning fields.
D. Render tool info
Update:
handleToolStartEvent():
- Use
formatToolStartBlock().
- For SQL, display a compact SQL block, truncated.
- For schema/list/check tools, show tool name and args.
handleToolEndEvent():
- Call
recordToolEnd(event.runId).
- Decrement
activeToolCount.
- Append a compact result summary:
✓ query_nba_db completed in 243ms
Result: 20 rows shown / output preview...
- Do not dump full query result unless very short.
handleToolErrorEvent():
- Include
runId if available.
- Decrement active count.
E. Handle done
Add explicit case in chatApp.ts switch:
case 'done':
break;
Optional: record final status, but avoid rewriting the final answer from messages unless needed.
4. Tests
Add/update scoped tests.
src/tabs/chatbot/__tests__/streaming.test.ts
Add cases for:
tool_end includes original input and durationMs when start was seen.
tool_error includes runId and resolves name from active tool map if possible.
- Non-string tool output is JSON-stringified as today.
New src/tabs/chatbot/__tests__/streamFormatting.test.ts
Cover:
- Stage names map to safe user-facing status text.
- SQL input is truncated.
- Tool output preview is truncated.
- Long result payloads do not exceed max display length.
- No raw ANSI requirement if helpers return plain/ANSI consistently.
src/tabs/chatbot/__tests__/accessibility.test.ts
Extend existing helper tests:
- Tool status/result lines contain visible labels.
- Tool error remains visible and understandable.
- Status summaries do not include “chain of thought” wording.
Existing ANSI/markdown tests
Likely no change unless new colors are added. If adding new ANSI colors, update:
src/tabs/chatbot/__tests__/ansi.test.ts
5. Risks / Tradeoffs
- Privacy: Do not surface hidden chain-of-thought. Use graph-stage status summaries only.
- Noisy UI: Tool output can be huge. Always truncate and summarize.
- Payload size: Keep raw stream events internal; truncate only for display.
- Snapshot stability: Prefer deterministic wording and fixed truncation limits.
- Parallel tools:
parallel_tool_calls: true means multiple tool starts/ends can interleave. Track by runId.
- Markdown/ANSI boundary: Continue converting through
ansiToStyledText() only at render boundaries.
6. Verification
Recommended scoped commands:
bun test src/tabs/chatbot/__tests__/streaming.test.ts --concurrency=1
bun test src/tabs/chatbot/__tests__/accessibility.test.ts --concurrency=1
bun test src/tabs/chatbot/__tests__/ansi.test.ts --concurrency=1
bun test src/tabs/chatbot/__tests__/markdown.test.ts --concurrency=1
bunx tsc --noEmit src/tabs/chatbot/agent/streaming.ts
bunx tsc --noEmit src/tabs/chatbot/chatApp.ts
bunx biome check src/tabs/chatbot
Minimal path: update streaming.ts, add utils/streamFormatting.ts, update chatApp.ts, and add focused tests.