hermes-trace/docs/frontend.md
XLion 09f6817706
refactor(frontend): extract CSS, fix bugs, improve a11y, and show all session turns
- Extract inline CSS from layout.html into static/hermes-trace.css
  (-42%, dead selectors from legacy side-panel/three-pane/waterfall removed)
- Fix fragile query-string building in openTurn (URLSearchParams)
- Fix payload race: beforeSwap guard drops stale JSON payloads when
  switching turns mid-flight
- Show Loading placeholder and surface HTMX failures instead of
  failing silently
- Extract inline x-data into Alpine.data("turnDetail") component
- a11y: keyboard-operable rows (tabindex + Enter/Space), Esc closes
  overlay, aria-label on close button, focusable token tooltip,
  higher-contrast latency-medium
- Table consistency: LLM latency renders with 's' unit, truncated
  cells get title attributes
- Show all turns in session view (drop default limit of 100) and
  remove now-dead _order offset logic
- Add X-Content-Type-Options: nosniff header and data: favicon
- Sync docs (frontend.md, database.md, AGENTS.md) with the above
2026-07-19 01:53:31 +08:00

7.1 KiB

hermes-trace Frontend

Stack

  • HTMX 2.0.10 — server round-trips for turn detail loading, lazy JSON loading
  • Alpine.js 3.15.12 — client-side state management (overlay panel, JSON toggles, tooltips)
  • Jinja2 — server-side HTML rendering
  • CSS — all styles in static/hermes-trace.css (linked from layout.html; no inline <style> block)
  • JS — shared listeners/components in static/hermes-trace.js (Alpine component registration, HTMX event guards, copy/resize handlers)

Session View (/session/{id})

The session view uses a flat table + right-side overlay panel pattern (not a CSS grid).

Component Role
Table Turn timeline: LLM calls + nested tool calls in a unified table
Overlay panel Right-side fixed panel for turn detail, opened by clicking a row

Table Structure

Columns:

Col Content
Start Timestamp (UTC+8) of LLM call
Call Badge: LLM #N (numbered by t._order; newest turn = largest N, e.g. 3 turns → newest is #3)
Input Truncated request preview (first 80 chars)
Response Truncated response preview (first 80 chars)
Latency Duration in seconds (LLM) or ms (tool), colour-coded
Model Model name badge

Two row types:

  • tr-llmcall — LLM API call row. Clicking it loads turn detail into the overlay via HTMX: htmx.ajax('GET', '/turn/{id}?order=N', {target:'#detail-body'}).
  • tr-toolcall — Tool call row, indented under its parent LLM call with a ↳ arrow. Clicking a tool call loads turn detail with ?focus_tc=N to auto-scroll to that tool call in the detail panel.

Both row types are keyboard-accessible: tabindex="0" + Enter/Space handlers (query string built with URLSearchParams), with :focus-visible outlines.

Detail Overlay Panel

.detail-overlay {
    position: fixed;
    top: 0;
    right: 0;
    width: 50%;
    height: 100vh;
    background: var(--bg-card);
    transform: translateX(100%);
    transition: transform 0.25s ease;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    box-shadow: -4px 0 16px rgba(0,0,0,0.35);
}
  • Opens via Alpine showDetail state when a table row is clicked; Esc closes it (@keydown.escape.window)
  • Has a resizable handle on the left edge (drag to resize, min 350px, max 92% width)
  • Contains a header (title + close button) and the scrollable #detail-body
  • Turn detail content is loaded into #detail-body via HTMX

Loading & Error States

  • openTurn() sets #detail-body to a .detail-loading "Loading…" placeholder before firing htmx.ajax.
  • HTMX failures are caught by an htmx:responseError listener (static/hermes-trace.js) that renders an error fragment into #detail-body / #json-request / #json-response.

Navigation Between Sessions

  • Back button at top: &larr; Back to sessions links back to /
  • Summary line: total turns, total tool calls, avg latency, tokens/sec

Turn Detail (GET /turn/{id})

An HTMX fragment rendered inside the overlay panel. Two tabs:

Preview Tab (default)

Section Content
Metadata chips Latency, token usage (with hover breakdown tooltip), finish reason, turn type
User Input <pre> block with copy button
Response <pre> block with copy button
Reasoning (if present) <pre> block with token count badge
Tool calls Each tool: Arguments + Result, each with JSON pretty/raw toggle and copy button

JSON Tab

Lazy-loaded via HTMX when tab is clicked:

  • Full Request — <textarea readonly> for crash-safe rendering of one server-formatted, valid JSON representation
  • Full Response — same pattern
  • Both sections loaded via htmx.ajax('GET', '/turn/{id}/payload?type=request|response', ...)

JSON Display

Large JSON Safety

  • Full Request/Response: Use <textarea readonly> not <pre>
  • Browser virtualizes textarea rendering — only visible lines are laid out
  • Formatted view: white-space: pre; overflow: auto (horizontal scroll)

Full Payload JSON

For large payloads (Full Request/Response), the server formats the JSON once without expanding escaped \\n sequences. The response contains one copy only:

<div class="td-payload">
    <textarea readonly class="td-textarea"
              style="white-space:pre;overflow:auto;">{{ formatted_json }}</textarea>
</div>

Small tool-call JSON (Arguments/Result) retains its client-side pretty/raw toggle because those payloads are typically only a few KB.

Lazy Loading

Full Request/Response are lazy-loaded only when the JSON tab is first activated:

  1. Clicking the JSON tab calls the Alpine loadJson() method on the turnDetail component — it runs once per fragment, guarded by a jsonLoaded flag.
  2. loadJson() fires two htmx.ajax GETs to /turn/{id}/payload?type=request|response, swapped into #json-request / #json-response (which show a .json-empty "Loading..." placeholder until then).
  3. An htmx:beforeSwap race guard (static/hermes-trace.js) discards a payload response whose turn id (parsed from /turn/{id}/payload in requestConfig.path) doesn't match the current fragment's data-turn-id — prevents stale JSON when the user switches turns mid-flight.
  4. Network failures surface via the htmx:responseError handler, which renders an error div into the target.

Token Usage Tooltip

Langfuse-inspired breakdown on hover or keyboard focus (the chip has tabindex="0" with @focus/@blur handlers):

Pill: 1,618 prompt → 31 completion (the Σ total is a separate chip)

Hover tooltip:

Usage breakdown
━━━━━━━━━━━━━━━━━━━━━━━
Input usage              193,362
  cache_read_input_tokens 191,744
  input                     1,618

Output usage                  31
  output                      31

Total usage              193,393

Metadata Pills

Detail pane top bar uses pill-shaped badges:

[Latency 5.4s] [Tokens 1,618 prompt → 31 completion] [Σ 193,393] [Finish tool_calls] [Type main]
  • Latency: Duration in seconds or milliseconds
  • Tokens: prompt → completion counts; hover or focus for breakdown
  • Σ: Total tokens (separate chip, shown when present)
  • Finish: stop / tool_calls / length / error (color-coded)
  • Type: main / background_review / subagent

Alpine Patterns

Pattern Usage
x-data Inline component state (showDetail, selectedTurn, raw, showTokens)
Alpine.data("turnDetail") Turn detail fragment state (tab, jsonLoaded, focusTc) — registered in static/hermes-trace.js via alpine:init; root div carries data-turn-id
x-show Conditional visibility (toggle sections, overlay)
$nextTick Wait for DOM before dispatching HTMX requests
x-cloak Prevent flash of unstyled content
@click Event handlers for row selection, tab switching
@keydown Keyboard support: Enter/Space on rows opens a turn, Esc closes the overlay
@focus / @blur Token tooltip for keyboard users (chip has tabindex="0")
:class Dynamic CSS classes for selected/highlight states