diff --git a/docs/UI.md b/docs/UI.md index 15bdd95..bb22c30 100644 --- a/docs/UI.md +++ b/docs/UI.md @@ -17,8 +17,8 @@ The topbar switches between two persisted modes: | Mode | Header | Trajectory filters | Statistics | |---|---|---|---| -| **Basic** | Turns, input tokens, cost, errors | Search, kind and the error/tool/compaction/retry/subagent/context chips | Turns with trigger, duration, in/out tokens, cost, status; expandable steps | -| **Advanced** | All eight tiles | Every filter and range control | Full 19-column turn/step table | +| **Basic** | Turns, input tokens, cost, errors | Search, kind, the error/tool/compaction/retry/subagent/context chips and Clear, plus the **Advanced filters** dialog | Turns with trigger, duration, in/out tokens, cost, status; expandable steps | +| **Advanced** | All eight tiles | The same bar and dialog (filters are not mode-gated) | Full 19-column turn/step table | The mode is stored per browser and can also be changed from Settings. @@ -56,6 +56,8 @@ Rows are chronological by recorded session sequence. Turn headers and step heade Filters are applied on the server, so search spans the whole session, not only the loaded page. Changing a filter resets to the newest matching page. +The essential controls (Search, Kind, the six chips and Clear) always sit in the filter bar. Agent, Model, Provider, Tool, Status, From/To and the prompt-token range live in the **Advanced filters** dialog opened from its button; the badge on that button counts the advanced controls currently set. The dialog is not gated by the view mode — its values always apply — and it closes on Esc, an outside click or any change, returning focus to the button. + ### Recovery map A **Recovery map** strip sits between the filter bar/legend and the ledger. It reads `analysis.diagnostics.incidents` from the deterministic engine verbatim; the UI never computes an incident. With no incidents it shows “No diagnostic incidents recorded in this session.” @@ -218,6 +220,8 @@ The native TUI panels re-fetch their existing `analysis` RPC on the same 5 secon Advisory budget warnings sit directly below the live-warning rows and above the active pane, in **both** view modes: they are deliberately not an Advanced-only section. Every analysis load appends the browser's six `gr.*` budgets to the request, so the server evaluates them against the same analysis (contract in [HEALTH.md](HEALTH.md#guardrails)). +The block is a native disclosure (`
`): the summary always carries the `Guardrails` heading and the `N advisory` count, while the rows are collapsed by default. Opening it is ordinary keyboard/pointer disclosure, and the open state persists per browser (`guardrailsExpanded` / `guardrailsCollapsed` in localStorage). + - **Rows** — each crossed budget keeps the health-rule rhythm: the budget label, the `derived` basis, an `advisory` chip, the deterministic observation with the budget it crossed, and capped evidence buttons carrying `data-event-id` that jump to the event in Trajectory. Every budget shows evidence: the event-backed ones (`retries`, `tool-failures`, `elapsed-minutes`) render `Event N` buttons for their capped event ids, and the event-only ones (`tokens-total`, `cost-total`, `context-run`) render `Turn N` buttons whose anchor is the turn's trigger event (falling back to its first recorded event). A turn whose anchor cannot be resolved renders no button rather than an id that cannot be opened. The threshold keeps up to two decimals, so a `$12.75` cost budget is never displayed as `13`. The section header carries the count (`N advisory`) and the standing line `advisory — never blocks anything`; there is no score, no ranking and no ordering control. A budget that could not be evaluated appears as a `Not evaluated — …` line instead of a guess. - **Settings** — the settings panel has a Guardrails group with one numeric input per budget (total tokens, total cost, context growth run, retries, tool failures, elapsed minutes), each validated inline against its documented bounds, plus **Reset guardrail defaults**. A rejected value shows its message and is never stored or sent. Budgets persist in this browser's localStorage; the server keeps no configuration. Changing one re-requests the current session's analysis, which is where the budgets are evaluated. - **TUI** — the native statistics banner adds `Guardrails (defaults): N advisory`. Browser thresholds never cross the RPC, so the panel names the defaults it evaluates. diff --git a/src/ui/app.js b/src/ui/app.js index 927c4f1..222710c 100644 --- a/src/ui/app.js +++ b/src/ui/app.js @@ -116,6 +116,14 @@ class ApiError extends Error { } } +/** + * The guardrail disclosure is a native `
`: the persisted preference is + * a pair of mirrored keys, and either one saying "expanded" wins so a stale + * single-key write can never hide warnings the user asked to see. + */ +const guardrailsExpandedInitial = + get("guardrailsExpanded") === true || get("guardrailsCollapsed") === false; + const state = { token: null, sessions: [], @@ -126,6 +134,11 @@ const state = { // Route-level guardrail sibling of the analysis response (never an Analysis // rider). Advisory only; recomputed by the server from the browser's budgets. guardrails: null, + // Guardrail disclosure state. The two names are aliases kept in sync so the + // persisted keys and the renderer never disagree; `expanded` is the source of + // truth and `collapsed` its inverse. + guardrailsExpanded: guardrailsExpandedInitial, + guardrailsCollapsed: !guardrailsExpandedInitial, facets: null, view: "trajectory", filters: defaultFilters(), @@ -134,6 +147,13 @@ const state = { reveal: false, revealAllowed: false, viewMode: getViewMode(), + // Advanced Trajectory filters live in a dialog opened from the filter bar. + // The three names are aliases kept in sync; the trigger is remembered so + // focus returns to it when the dialog closes. + advancedFiltersOpen: false, + advancedFiltersModalOpen: false, + filterAdvancedOpen: false, + advancedFiltersTrigger: null, contextBasis: get("contextBasis") === "cumulative" ? "cumulative" : "latest", showEventRows: get("showEventRows") === true, expandedTurns: new Set(), @@ -220,17 +240,28 @@ function filtersActive() { return activeFilterCount() > 0; } -function activeFilterCount() { +/** + * The advanced-controls count behind the "Advanced filters" badge. These + * controls always live in the dialog but their values still narrow the query, + * so the badge must report them even while the dialog is closed. + */ +function advancedFilterCount() { const f = state.filters; - const advanced = state.viewMode === "advanced"; let count = 0; - if (f.q.trim()) count++; - const listKeys = advanced - ? ["kinds", "agents", "models", "providers", "tools", "statuses"] - : ["kinds"]; - for (const key of listKeys) { + for (const key of ["agents", "models", "providers", "tools", "statuses"]) { if (f[key].length > 0) count++; } + for (const key of ["from", "to", "minPromptTokens", "maxPromptTokens"]) { + if (f[key]) count++; + } + return count; +} + +function activeFilterCount() { + const f = state.filters; + let count = 0; + if (f.q.trim()) count++; + if (f.kinds.length > 0) count++; for (const key of [ "errorsOnly", "retriesOnly", @@ -240,11 +271,9 @@ function activeFilterCount() { ]) { if (f[key]) count++; } - if (advanced && f.from) count++; - if (advanced && f.to) count++; - if (advanced && f.minPromptTokens) count++; - if (advanced && f.maxPromptTokens) count++; - return count; + // Advanced values are never discarded: the server applies them in every + // mode, so the Clear badge counts them too. + return count + advancedFilterCount(); } async function api(path, params = {}, options = {}) { @@ -349,25 +378,20 @@ function toast(message) { function filterParams() { const f = state.filters; - const advanced = state.viewMode === "advanced"; - const from = advanced && f.from ? Date.parse(f.from) : undefined; - const to = advanced && f.to ? Date.parse(f.to) : undefined; + const from = f.from ? Date.parse(f.from) : undefined; + const to = f.to ? Date.parse(f.to) : undefined; return { q: f.q.trim() || undefined, kind: f.kinds, - ...(advanced - ? { - agent: f.agents, - model: f.models, - provider: f.providers, - tool: f.tools, - status: f.statuses, - from: Number.isFinite(from) ? from : undefined, - to: Number.isFinite(to) ? to : undefined, - minPromptTokens: f.minPromptTokens || undefined, - maxPromptTokens: f.maxPromptTokens || undefined, - } - : {}), + agent: f.agents, + model: f.models, + provider: f.providers, + tool: f.tools, + status: f.statuses, + from: Number.isFinite(from) ? from : undefined, + to: Number.isFinite(to) ? to : undefined, + minPromptTokens: f.minPromptTokens || undefined, + maxPromptTokens: f.maxPromptTokens || undefined, errors: f.errorsOnly || undefined, retries: f.retriesOnly || undefined, compactions: f.compactionsOnly || undefined, @@ -680,7 +704,7 @@ function filterBarHtml() { statuses: [], }; const toolsActive = f.kinds.length === 1 && f.kinds[0] === "tool"; - const advanced = state.viewMode === "advanced" ? "" : " advanced-only"; + const advancedCount = advancedFilterCount(); const chip = (kind, label, active) => ` + + `; } +/** + * The advanced-filter dialog. It is re-created with the Trajectory view, so the + * helpers look it up by id instead of caching a node that a re-render replaces. + * The three state names are aliases; every write goes through one setter. + */ +function advancedFiltersModal() { + return document.getElementById("advanced-filters"); +} + +function setAdvancedFiltersOpen(open) { + state.advancedFiltersOpen = open; + state.advancedFiltersModalOpen = open; + state.filterAdvancedOpen = open; + // Single owner: every alias write also re-syncs the trigger's aria state. + syncAdvancedFiltersTrigger(); +} + +function syncAdvancedFiltersTrigger() { + const trigger = $("#advanced-filters-btn"); + if (trigger) { + trigger.setAttribute("aria-expanded", String(state.advancedFiltersOpen)); + } +} + +function openAdvancedFilters(trigger = null) { + const modal = advancedFiltersModal(); + if (!modal) return; + state.advancedFiltersTrigger = + trigger instanceof HTMLElement + ? trigger + : document.activeElement instanceof HTMLElement + ? document.activeElement + : null; + setAdvancedFiltersOpen(true); + modal.hidden = false; + modal.querySelector(".modal-close")?.focus(); +} + +function closeAdvancedFilters(options = {}) { + const modal = advancedFiltersModal(); + const wasOpen = state.advancedFiltersOpen || (modal ? !modal.hidden : false); + if (modal) modal.hidden = true; + setAdvancedFiltersOpen(false); + const trigger = state.advancedFiltersTrigger; + state.advancedFiltersTrigger = null; + if (!wasOpen || options.restoreFocus === false) return; + if (trigger?.isConnected) trigger.focus(); + else $("#advanced-filters-btn")?.focus(); +} + function bindFilters() { const search = $("#event-search"); if (search) { @@ -795,6 +886,15 @@ function bindFilters() { } else { state.filters[key] = element.value; } + if (element.closest("#advanced-filters")) { + // A change applies immediately and closes the dialog; the trigger is + // rebuilt by the reload, so focus is restored by id afterwards. + closeAdvancedFilters({ restoreFocus: false }); + void loadEvents({ reset: true }).then(() => { + $("#advanced-filters-btn")?.focus(); + }); + return; + } void loadEvents({ reset: true }); }); } @@ -812,10 +912,26 @@ function bindFilters() { void loadEvents({ reset: true }); }); } + const advancedTrigger = $("#advanced-filters-btn"); + if (advancedTrigger) { + advancedTrigger.addEventListener("click", () => openAdvancedFilters(advancedTrigger)); + } + const advancedModal = advancedFiltersModal(); + if (advancedModal) { + advancedModal.addEventListener("click", (event) => { + if ( + event.target === advancedModal || + event.target.closest("[data-close-advanced-filters]") + ) { + closeAdvancedFilters(); + } + }); + } const clear = $("#clear-filters"); if (clear) { clear.addEventListener("click", () => { state.filters = defaultFilters(); + closeAdvancedFilters({ restoreFocus: false }); void loadEvents({ reset: true }); }); } @@ -1204,14 +1320,47 @@ function renderLive() { */ let guardrailsMarkup = null; +/** + * Set on a summary click (capture) and cleared by the next + * `applyGuardrailsState()` pass. While pending, that pass must not write + * `details.open` back to the stored value and undo the user's toggle before the + * queued `toggle` event has synced state. + */ +let guardrailsTogglePending = false; + +/** + * Applies the persisted disclosure state to the freshly written markup. The + * block is re-created whenever the advisory rows change, so both the write path + * and the cached early-return path converge here; `open` and the summary's + * `aria-expanded` therefore never drift from `state`. + */ +function applyGuardrailsState() { + const block = dom.guardrails?.querySelector("details.guardrails-block"); + if (!block) return; + const expanded = + state.guardrailsExpanded === true || state.guardrailsCollapsed === false; + if (!guardrailsTogglePending) block.open = expanded; + const open = block.open; + state.guardrailsExpanded = open; + state.guardrailsCollapsed = !open; + guardrailsTogglePending = false; + block + .querySelector("summary") + ?.setAttribute("aria-expanded", open ? "true" : "false"); +} + function renderGuardrails() { if (!dom.guardrails) return; const turns = state.analysis?.turns ?? []; const markup = guardrailsHtml(state.guardrails, turns); - if (markup === guardrailsMarkup) return; + if (markup === guardrailsMarkup) { + applyGuardrailsState(); + return; + } guardrailsMarkup = markup; dom.guardrails.innerHTML = markup; dom.guardrails.hidden = markup.length === 0; + applyGuardrailsState(); } function tile(label, value, sub = "") { @@ -1585,6 +1734,10 @@ function renderTrajectory(options = {}) { dom.view.className = "view view-trajectory"; const total = state.page?.totalMatched ?? state.events.length; const all = state.page?.totalInSession ?? total; + // The dialog lives inside this subtree: remember whether it was open before + // the rewrite so an unrelated re-render (live refresh, tab return) does not + // silently close it. `filterBarHtml()` still renders the markup hidden. + const wasAdvancedFiltersOpen = state.advancedFiltersOpen; dom.view.innerHTML = `${filterBarHtml()}
${formatNumber(state.events.length)} loaded · ${formatNumber( @@ -1615,6 +1768,12 @@ function renderTrajectory(options = {}) {
`; bindFilters(); + if (wasAdvancedFiltersOpen) { + const advancedModal = advancedFiltersModal(); + if (advancedModal) advancedModal.hidden = false; + // The setter also re-syncs the rebuilt trigger's aria-expanded. + setAdvancedFiltersOpen(true); + } bindRecoveryMap(); const scroller = $("#ledger-scroll"); const rows = buildLedgerRows(); @@ -3023,8 +3182,8 @@ function setMode(mode) { renderViewModeState(); renderHeader(); if (state.sessionID) { - // Advanced filters may be hidden but still present in state; reloading - // applies only the filters the new mode actually shows. + // Filters are no longer gated by the mode, but the result set is unchanged + // by the switch, so the ledger is reloaded only to keep the counters fresh. void loadEvents({ reset: true }); } else { renderView(); @@ -3234,6 +3393,9 @@ function bindSettingsForm() { state.showEventRows = false; state.groupByProject = true; state.sessionTree = true; + state.guardrailsExpanded = false; + state.guardrailsCollapsed = true; + applyGuardrailsState(); state.expandedProjects.clear(); state.expandedParents.clear(); renderViewModeState(); @@ -4178,6 +4340,36 @@ function bindStaticEvents() { const eventID = button.dataset.eventId; if (eventID) void jumpToEvent(eventID); }); + // Mark the user's disclosure click before any re-render can run, so a state + // pass queued in the same task never snaps `open` back to the stored value. + dom.guardrails?.addEventListener( + "click", + (event) => { + if (event.target.closest(".guardrails-summary")) { + guardrailsTogglePending = true; + } + }, + true, + ); + // The `toggle` event does not bubble, so it is observed in the capture phase + // on the stable container. Both persisted keys are written together. + dom.guardrails?.addEventListener( + "toggle", + (event) => { + const block = event.target; + if (!(block instanceof HTMLElement) || block.tagName !== "DETAILS") return; + if (!block.classList.contains("guardrails-block")) return; + const expanded = block.open; + state.guardrailsExpanded = expanded; + state.guardrailsCollapsed = !expanded; + setSetting("guardrailsExpanded", expanded); + setSetting("guardrailsCollapsed", !expanded); + block + .querySelector("summary") + ?.setAttribute("aria-expanded", expanded ? "true" : "false"); + }, + true, + ); dom.revealToggle?.addEventListener("click", () => void toggleReveal()); $("#settings-btn")?.addEventListener("click", openSettings); for (const button of document.querySelectorAll("[data-view-mode-option]")) { @@ -4317,6 +4509,16 @@ function onKeyDown(event) { } return; } + const advancedModal = advancedFiltersModal(); + if (advancedModal && !advancedModal.hidden) { + if (event.key === "Escape") { + event.preventDefault(); + closeAdvancedFilters(); + } else if (event.key === "Tab") { + trapFocus(event, advancedModal); + } + return; + } if (!dom.drawer?.hidden) { if (event.key === "Escape") { event.preventDefault(); diff --git a/src/ui/guardrails.js b/src/ui/guardrails.js index 42c3881..bd82ff0 100644 --- a/src/ui/guardrails.js +++ b/src/ui/guardrails.js @@ -169,18 +169,26 @@ export function guardrailsHtml(guardrails, turns = []) { rows.length > 0 ? `` : ""; + // The block is a native disclosure: the summary carries the header and the + // standing count, so the frame stays visible while the rows are collapsed by + // default. The body id is fixed because only one guardrail block ever renders; + // `aria-controls`/`aria-expanded` are re-applied by the app after every write. return `
-
-

Guardrails

- ${escapeHtml( - `${formatNumber(count)} advisory`, - )} - basis derived -
-

${escapeHtml( - GUARDRAIL_ADVISORY_COPY, - )}

- ${listHtml} - ${skippedHtml} +
+ +
+

${escapeHtml( + GUARDRAIL_ADVISORY_COPY, + )}

+ ${listHtml} + ${skippedHtml} +
+
`; } diff --git a/src/ui/settings.js b/src/ui/settings.js index 01cc464..900f992 100644 --- a/src/ui/settings.js +++ b/src/ui/settings.js @@ -128,6 +128,8 @@ const DEFAULTS = { expandedProjects: [], expandedParents: [], guardrails: null, + guardrailsExpanded: false, + guardrailsCollapsed: true, }; const KEY_PREFIX = "observability-"; diff --git a/src/ui/styles.css b/src/ui/styles.css index c662fae..ba1d0cd 100644 --- a/src/ui/styles.css +++ b/src/ui/styles.css @@ -275,6 +275,14 @@ code, pre, .mono { font-family: var(--mono); } .field input[type="datetime-local"] { width: 180px; } .filter-bar .grow { flex: 1; min-width: 200px; } .filter-actions { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.filter-advanced-count { margin-left: 4px; } +.advanced-filters-card { width: min(520px, 96vw); } +.advanced-filters-grid { + display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); + gap: 10px 12px; margin: 12px 0 16px; +} +.advanced-filters-grid .field input, +.advanced-filters-grid .field select { max-width: none; width: 100%; } .chip { display: inline-flex; align-items: center; gap: 5px; border: 1px solid var(--border-strong); background: var(--surface); border-radius: 999px; padding: 4px 10px; font-size: 12px; color: var(--text-2); @@ -653,6 +661,18 @@ code, pre, .mono { font-family: var(--mono); } the active pane, in both view modes. Rows keep the health-rule rhythm; the warning tint is a border only and every row keeps its text label. */ .guardrails { margin: 0; } +.guardrails-block { margin: 0; } +.guardrails-summary { + display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px; + cursor: pointer; list-style: none; +} +.guardrails-summary::-webkit-details-marker { display: none; } +.guardrails-summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.guardrails-summary::after { + content: "▸"; color: var(--muted); font-size: 11px; margin-left: auto; +} +.guardrails-block[open] > .guardrails-summary::after { content: "▾"; } +.guardrails-body { padding-top: 8px; } .guardrails-section { border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); padding: 10px 12px; margin-bottom: 10px;