AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
feat(console): Kibana-quality dashboards — durable CRUD, panel builder, free-form grid, chrome fix
xerj-orgb26c41a264f4
diff --git a/xerj-ux/assets/base.css b/xerj-ux/assets/base.cssindex ffcb74958..20891de2d 100644--- a/xerj-ux/assets/base.css+++ b/xerj-ux/assets/base.css@@ -1126,24 +1126,25 @@ button {z-index: 50;}-/* Top strip — EDIT MODE label + drag/resize/remove tips. Lives in the- page's top padding, never overlaps content. */+/* Top strip — EDIT MODE label + tips. Now a NORMAL-FLOW, sticky element+ rendered below the sub-nav (Issue 3 fix): it can never overlap the+ dashboard sub-nav row because it comes after it in the document, and+ it sticks just under the viewport top while scrolling. */.edit-strip-top {- position: fixed;- /* Sit just inside the top edge of the .edit-frame (top: 150px). */- top: 158px;- left: 28px;- right: 28px;+ position: sticky;+ top: 8px;display: flex;gap: var(--sp-3);align-items: baseline;+ margin: 0 0 var(--sp-3);font-family: var(--font-data);font-size: var(--fs-11);letter-spacing: var(--track-ui);text-transform: uppercase;- pointer-events: none;- z-index: 51;- padding: 0 8px;+ z-index: 40;+ padding: 6px 8px;+ border-top: 1px solid var(--z-faint);+ border-bottom: 1px solid var(--z-faint);background: var(--z-paper);}.edit-strip-top .marker {@@ -1198,13 +1199,53 @@ button {outline-offset: 10px;position: relative;z-index: 1;+ /* Reserve a 24px chrome strip so the drag grip (top-left) and the edit+ toolbar (top-right) never sit on top of the panel title/eyebrow —+ the Issue-3 overlap fix. */+ padding-top: 24px;transition: outline-color 120ms;}.panel.edit:hover { outline-color: var(--z-ink); }.panel.edit.dragging { opacity: 0.35; }+.panel.edit.dragging-geom { opacity: 0.9; outline-color: var(--z-accent); z-index: 6; }.panel.edit.drop-before { outline-color: var(--z-accent); }.panel.edit.drop-after { outline-color: var(--z-accent); }+/* Top-left drag GRIP — the move affordance. Lives in its own 20px strip+ so the whole panel body stays interactive. */+.panel-grip {+ position: absolute;+ top: 2px;+ left: 0;+ width: 20px; height: 20px; line-height: 20px;+ text-align: center;+ color: var(--z-mute);+ font-size: var(--fs-13);+ cursor: grab;+ user-select: none;+ z-index: 5;+}+.panel-grip:hover { color: var(--z-ink); }+.panel-grip:active { cursor: grabbing; color: var(--z-accent); }++/* SE-corner + right-edge + bottom-edge resize handles (declarative panels).+ Positioned just INSIDE the panel edges — the declarative canvas sets+ `overflow: hidden` on panels, which would clip anything placed outside+ (negative offsets), making the handles unhittable. */+.panel-resize { position: absolute; z-index: 5; }+.panel-resize.e { top: 24px; bottom: 14px; right: 0; width: 12px; cursor: ew-resize; }+.panel-resize.s { left: 24px; right: 14px; bottom: 0; height: 12px; cursor: ns-resize; }+.panel-resize.se { right: 0; bottom: 0; width: 16px; height: 16px; cursor: nwse-resize; }+.panel-resize.se::after {+ content: '';+ position: absolute; right: 3px; bottom: 3px;+ width: 9px; height: 9px;+ border-right: 1px solid var(--z-mute);+ border-bottom: 1px solid var(--z-mute);+}+.panel.user-panel.edit:hover .panel-resize.se::after,+.panel-resize.se:hover::after { border-color: var(--z-accent); }+/* (legacy inline grid header removed; now lives in .edit-strip-bottom) *//* Full-canvas 12-column overlay inside the grid */@@ -1226,20 +1267,27 @@ button {.panel-edit {position: absolute;- top: -30px;- left: 0;+ top: 0;right: 0;- display: flex;- gap: var(--sp-3);+ left: auto;+ display: inline-flex;+ gap: 6px;align-items: baseline;+ max-width: 100%;+ flex-wrap: nowrap;+ white-space: nowrap;+ justify-content: flex-end;font-family: var(--font-data);font-size: var(--fs-11);letter-spacing: var(--track-ui);text-transform: uppercase;- z-index: 3;+ z-index: 4;+ padding: 2px 2px 2px 10px;+ background: var(--z-paper);pointer-events: none;}.panel-edit > * { pointer-events: auto; }+.panel-edit button { background: none; border: 0; font: inherit; cursor: pointer; }.panel-edit .colsLabel {color: var(--z-accent);font-weight: 700;@@ -1259,12 +1307,17 @@ button {.panel-edit .sizes button:hover { color: var(--z-ink); }.panel-edit .sizes button.active { color: var(--z-accent); font-weight: 700; }.panel-edit .remove {- margin-left: auto;+ margin-left: 6px;color: var(--z-mute);font-family: var(--font-data);font-size: var(--fs-13);}.panel-edit .remove:hover { color: var(--z-accent); }+/* Declarative user-panel toolbar bits: the w×h readout + QUERY button. */+.panel-edit .wh { color: var(--z-accent); font-weight: 700; letter-spacing: 0.1em; }+.panel-edit .wh .x { color: var(--z-mute); margin: 0 1px; font-weight: 400; }+.panel-edit .cfg { color: var(--z-mute); font-weight: 700; letter-spacing: 0.12em; }+.panel-edit .cfg:hover { color: var(--z-accent); }/* The +ADD picker at the bottom of the canvas */.add-picker {@@ -1288,6 +1341,105 @@ button {}.add-picker .types button:hover { color: var(--z-accent); }+/* + ADD PANEL launcher for declarative dashboards. */+.add-panel-btn {+ background: none;+ border: 1px solid var(--z-accent);+ color: var(--z-accent);+ font: inherit;+ font-family: var(--font-data);+ text-transform: uppercase;+ letter-spacing: 0.14em;+ font-size: var(--fs-11);+ padding: 6px 14px;+ cursor: pointer;+ margin-right: var(--sp-3);+}+.add-panel-btn:hover { background: var(--z-accent); color: var(--z-paper); }+.empty-dash { padding: var(--sp-8) 0; font-size: var(--fs-13); text-align: center; letter-spacing: 0.06em; }++/* ============================================================+ Free-form declarative canvas + panel builder (net-new dashboards)+ ============================================================ */++/* Explicit-placement grid: panels carry grid-column/grid-row inline+ (x/y/w/h). A fixed row track maps `h` to pixels; denser gaps than the+ editorial 12-col reading canvas so panels tile like a real dashboard. */+.canvas.declarative {+ align-items: stretch;+ grid-auto-rows: 132px;+ column-gap: var(--sp-2);+ row-gap: var(--sp-2);+}+.canvas.declarative .panel { overflow: hidden; min-width: 0; }+.canvas.declarative .panel.user-panel { display: flex; flex-direction: column; }++/* The inline panel configurator (viz + index/query + live preview). */+.builder {+ margin-top: var(--sp-6);+ padding-top: var(--sp-3);+ border-top: 1px dashed var(--z-faint);+ font-family: var(--font-data);+}+.builder-head { display: flex; align-items: baseline; justify-content: space-between; margin-bottom: var(--sp-3); }+.builder-head .key { color: var(--z-accent); font-size: var(--fs-13); }+.builder-x { background: none; border: 0; color: var(--z-mute); cursor: pointer; font: inherit; }+.builder-x:hover { color: var(--z-accent); }+.builder-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: var(--sp-6); }+.builder-form { display: flex; flex-direction: column; gap: var(--sp-3); }+.builder-field { display: flex; flex-direction: column; gap: 6px; }+.builder-field > .key { color: var(--z-mute); }+.viz-tiles { display: flex; flex-wrap: wrap; gap: 4px 12px; }+.viz-tiles button,+.btn-row button {+ background: none; border: 0; font: inherit; cursor: pointer;+ color: var(--z-mute);+ text-transform: uppercase; letter-spacing: 0.08em;+ font-size: var(--fs-11); padding: 2px 0;+}+.viz-tiles button:hover, .btn-row button:hover { color: var(--z-ink); }+.viz-tiles button.active, .btn-row button.active { color: var(--z-accent); font-weight: 700; }+.btn-row { display: inline-flex; flex-wrap: wrap; gap: 6px; align-items: baseline; }+.btn-row .sep { color: var(--z-faint); }+.builder-select,+.builder-input {+ background: transparent;+ color: var(--z-ink);+ border: 0;+ border-bottom: 1px solid var(--z-faint);+ font: inherit;+ font-family: var(--font-data);+ padding: 4px 2px;+}+.builder-select:focus, .builder-input:focus { outline: none; border-bottom-color: var(--z-accent); }+.builder-input.short { max-width: 10ch; }+.builder-actions { display: flex; align-items: baseline; gap: var(--sp-3); margin-top: var(--sp-2); }+.builder-save {+ background: none;+ border: 1px solid var(--z-accent);+ color: var(--z-accent);+ font: inherit; font-family: var(--font-data);+ text-transform: uppercase; letter-spacing: 0.12em;+ padding: 6px 16px; cursor: pointer;+}+.builder-save:hover { background: var(--z-accent); color: var(--z-paper); }+.builder-cancel {+ background: none; border: 0; color: var(--z-mute);+ font: inherit; font-family: var(--font-data);+ text-transform: uppercase; letter-spacing: 0.12em; cursor: pointer;+}+.builder-cancel:hover { color: var(--z-ink); }+.builder-preview .key { color: var(--z-mute); }+.builder-preview-box {+ margin-top: var(--sp-2);+ padding: var(--sp-3);+ border: 1px dashed var(--z-faint);+ min-height: 168px;+}+@media (max-width: 900px) {+ .builder-grid { grid-template-columns: 1fr; gap: var(--sp-4); }+}+/* ============================================================Mobile / tablet responsive rulesDesktop-first product: the dashboards were designed for wide@@ -1342,6 +1494,11 @@ button {}.canvas > * { grid-column: 1 / -1 !important; }.canvas.edit { grid-auto-rows: auto; }+ /* Declarative geometry degrades gracefully: ignore x/y, stack panels by+ (y,x) document order at full width. */+ .canvas.declarative { grid-auto-rows: auto; }+ .canvas.declarative > * { grid-row: auto !important; }+ .builder-grid { grid-template-columns: 1fr; }.panel { min-width: 0; max-width: 100%; }diff --git a/xerj-ux/index.html b/xerj-ux/index.htmlindex 04e547ab2..96f1bc44f 100644--- a/xerj-ux/index.html+++ b/xerj-ux/index.html@@ -70,6 +70,17 @@} catch (e) {console.warn('[xerj-console sync]', e);}++ // Pull the durable dashboard set (GET /dashboards) BEFORE app.js's+ // first paint so the nav + declarative panels render from the+ // backend, not just the localStorage cache. Best-effort: on failure+ // the store keeps its LS cache (offline/dev still works).+ try {+ const ds = await import('./src/data/dashboard-store.js');+ await ds.hydrate();+ } catch (e) {+ console.warn('[xerj-console dashboards]', e);+ }} catch (e) {// Engine unreachable (offline dev, hot-reload mid-flight) —// load the SPA anyway so the user sees an error state insteaddiff --git a/xerj-ux/src/app.js b/xerj-ux/src/app.jsindex 73c533064..819a3de2d 100644--- a/xerj-ux/src/app.js+++ b/xerj-ux/src/app.js@@ -15,7 +15,10 @@ import { hitsToCsv, downloadText, svgToPng } from './data/export.js';import {mergedDashboards, renameDashboard, reorderDashboards, setHidden,createUserDashboard, deleteUserDashboard, isUserDash, resetAll as resetDashboards,+ getDoc, patchPanels, setOnChange,} from './data/dashboard-store.js';+import { renderDeclarativePanel } from './ux/panel-render.js';+import { panelResult, fetchPanel, onPanelData } from './data/panel-query.js';import {listClusters, listIndices, listFields, listClustersSync,defaultClusterId, setDefaultCluster,@@ -467,10 +470,17 @@ async function buildSectionData(sectionId) {}function loadAllLayouts() {+ // Iterate ALL `xerj.layout.*` keys — not just registry ids — so+ // layouts synced down from /prefs.layouts (which may include ids this+ // build doesn't ship, or default-dashboard overrides hydrated on+ // another machine) are picked up instead of silently dropped.const out = {};- for (const id of Object.keys(registry)) {+ const prefix = 'xerj.layout.';+ for (const k of Object.keys(localStorage)) {+ if (!k.startsWith(prefix)) continue;+ const id = k.slice(prefix.length);try {- const raw = localStorage.getItem(LS.layout(id));+ const raw = localStorage.getItem(k);if (raw) out[id] = JSON.parse(raw);} catch { /* ignore corrupt */ }}@@ -553,29 +563,134 @@ function mutate(dashId, defaultPanels, fn) {}// ---------- render -----------------------------------------const SIZES = [2, 3, 4, 6, 8, 12];+// Quick-size presets kept as a panel-toolbar convenience (the 6 discrete+// spans are no longer the ONLY resize path — declarative user panels get+// free w×h drag-resize; see the pointer handlers below).+const SIZES = [3, 4, 6, 8, 12];+const GRID_COLS = 12;+const ROW_H = 132; // px per grid row-unit in declarative canvases+const DEFAULT_GEOM = { x: 0, y: 0, w: 6, h: 2 };++// ---- declarative geometry helpers ------------------------+function clampInt(v, lo, hi) { v = Math.round(Number(v) || 0); return Math.max(lo, Math.min(hi, v)); }+function panelGeom(p) {+ const g = p.geometry || {};+ const w = clampInt(g.w ?? DEFAULT_GEOM.w, 1, GRID_COLS);+ return {+ x: clampInt(g.x ?? DEFAULT_GEOM.x, 0, GRID_COLS - w),+ y: Math.max(0, Math.round(Number(g.y) || 0)),+ w,+ h: Math.max(1, Math.round(Number(g.h) || DEFAULT_GEOM.h)),+ };+}+/** Next free row below everything, full-width-ish default slot. */+function nextGeometry(panels) {+ let maxBottom = 0;+ for (const p of panels || []) {+ const g = panelGeom(p);+ maxBottom = Math.max(maxBottom, g.y + g.h);+ }+ return { x: 0, y: maxBottom, w: 6, h: 2 };+}+/** Kibana-style vertical compaction: push overlapping panels down so no+ * two panels occupy the same cell. Stable by (y, x). */+function compact(panels) {+ const sorted = panels+ .map((p, i) => ({ p, g: panelGeom(p), i }))+ .sort((a, b) => (a.g.y - b.g.y) || (a.g.x - b.g.x) || (a.i - b.i));+ const placed = [];+ const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;+ for (const item of sorted) {+ const g = { ...item.g };+ let moved = true;+ while (moved) {+ moved = false;+ for (const q of placed) {+ if (overlaps(g, q.g)) { g.y = q.g.y + q.g.h; moved = true; }+ }+ }+ placed.push({ p: item.p, g });+ }+ return placed.map(({ p, g }) => ({ ...p, geometry: g }));+}++// ---- builder (per-panel configurator) state --------------+const builder = {+ open: false,+ editingId: null, // panel id when editing an existing panel, else null+ viz: 'topn',+ index: '',+ kind: 'terms',+ field: 'level',+ metric: 'count',+ size: 8,+ interval: '1h',+ q: '',+ title: '',+ time: false,+ preview: null, // { status, html } cache of the live preview+ previewKey: '',+};+let BUILDER_INDICES = []; // cached index list for the picker+let BUILDER_FIELDS = []; // cached field list for the current indexfunction renderEditChrome(p) {const sizes = SIZES.map((s) =>`<button type="button" data-panel="${esc(p.id)}" data-size="${s}" class="${p.cols === s ? 'active' : ''}" aria-pressed="${p.cols === s}">${s}</button>`- ).join('<span class="sep">·</span>');- const frac = Math.max(0, Math.min(12, p.cols)) / 12;- const meterFill = (frac * 96).toFixed(1);- const meter = `- <svg class="meter" viewBox="0 0 96 6" preserveAspectRatio="none" aria-hidden="true">- <line x1="0" y1="5" x2="96" y2="5" stroke="currentColor" stroke-width="1" stroke-opacity="0.25"/>- <line x1="0" y1="5" x2="${meterFill}" y2="5" stroke="var(--z-accent)" stroke-width="1"/>- </svg>`;+ ).join('');+ // Compact single-line toolbar so it fits the reserved 24px strip even on+ // dense 2-col tiles (Issue 3): a small n/12 readout + size presets + ✕.return `+ <span class="panel-grip" aria-hidden="true">⠿</span><div class="panel-edit" aria-label="Edit panel">- <span class="colsLabel"><span class="max">COL</span> ${p.cols}<span class="slash">/</span><span class="max">12</span></span>- ${meter}+ <span class="wh mono">${p.cols}<span class="x">/</span>12</span><span class="sizes">${sizes}</span><button type="button" class="remove" data-panel="${esc(p.id)}" data-remove aria-label="Remove">✕</button></div>`;}-function renderPanel(p, data, editMode) {+// Declarative user-panel chrome: a top-left drag GRIP + a top-right+// toolbar (never in title flow) + SE/E/S resize handles.+function renderUserPanelChrome(p) {+ const g = panelGeom(p);+ const presets = SIZES.map((s) =>+ `<button type="button" data-user-size="${s}" data-panel="${esc(p.id)}" class="${g.w === s ? 'active' : ''}">${s}</button>`+ ).join('<span class="sep">·</span>');+ return `+ <span class="panel-grip" data-grip="${esc(p.id)}" title="Drag to move" aria-label="Move panel">⠿</span>+ <div class="panel-edit user" aria-label="Edit panel">+ <span class="wh mono">${g.w}<span class="x">×</span>${g.h}</span>+ <span class="sizes">${presets}</span>+ <button type="button" class="cfg" data-user-config="${esc(p.id)}" title="Edit query / viz">QUERY</button>+ <button type="button" class="remove" data-user-remove="${esc(p.id)}" aria-label="Remove">✕</button>+ </div>+ <span class="panel-resize e" data-resize="e" data-panel="${esc(p.id)}" aria-hidden="true"></span>+ <span class="panel-resize s" data-resize="s" data-panel="${esc(p.id)}" aria-hidden="true"></span>+ <span class="panel-resize se" data-resize="se" data-panel="${esc(p.id)}" aria-hidden="true"></span>`;+}++function renderPanel(p, data, editMode, ctx) {+ // Declarative user panels: explicit x/y/w/h placement + per-panel live+ // query (data/panel-query.js) rendered through the shared chart+ // catalog (ux/panel-render.js). Chrome is out of title flow.+ if (p.source === 'user') {+ const g = panelGeom(p);+ let inner;+ try {+ inner = renderDeclarativePanel(p, panelResult(p, ctx || {}));+ } catch (err) {+ inner = `<div class="panel-empty mono faint">PANEL ERROR · ${esc((err.message || err) + '').slice(0, 80)}</div>`;+ }+ const style = `grid-column:${g.x + 1}/span ${g.w}; grid-row:${g.y + 1}/span ${g.h};`;+ const chrome = editMode ? renderUserPanelChrome(p) : '';+ return `+ <section class="panel user-panel${editMode ? ' edit' : ''}" data-panel="${esc(p.id)}" data-user-panel="1" style="${style}">+ ${chrome}+ ${p.title ? `<div class="key">${esc(p.title)}</div>` : ''}+ ${inner}+ </section>`;+ }+let inner = '';try {if (p.source === 'added') {@@ -611,7 +726,18 @@ function renderPanel(p, data, editMode) {</section>`;}-function renderAddPicker() {+function renderAddPicker(dash) {+ // Declarative user dashboards get the real builder: + ADD PANEL opens+ // an inline configurator (viz type → index/query → live preview).+ if (dash && dash.declarative) {+ if (builder.open) return renderBuilder();+ return `+ <div class="add-picker">+ <button type="button" class="add-panel-btn" data-builder-open>+ ADD PANEL</button>+ <span class="mono faint">BUILD A PANEL FROM ANY INDEX · PICK A VISUALIZATION + QUERY</span>+ </div>`;+ }+ // Default (code) dashboards keep the quick chart-type add picker.const items = chartTypeList.map((t) =>`<button type="button" data-add="${esc(t.id)}" title="${esc(t.describe || '')}">${esc(t.name)}</button>`).join('<span class="sep">·</span>');@@ -622,6 +748,115 @@ function renderAddPicker() {</div>`;}+// Build a declarative panel object from the current builder state.+function builderPanelDraft() {+ const autoTitle = (builder.field+ ? `${builder.field} · ${chartTypes[builder.viz]?.name || builder.viz}`+ : (chartTypes[builder.viz]?.name || builder.viz)).toUpperCase();+ return {+ id: builder.editingId || ('p-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5)),+ title: (builder.title || autoTitle),+ viz: { type: builder.viz, options: {} },+ query: {+ index: builder.index,+ kind: builder.kind,+ q: builder.q || '',+ field: builder.field || '',+ metric: builder.metric || 'count',+ size: Number(builder.size) || 8,+ interval: builder.interval || '1h',+ time: !!builder.time,+ },+ geometry: builder._geometry || null,+ };+}++const VIZ_LIST = ['metric', 'spark', 'gauge', 'line', 'bar', 'histogram', 'dist', 'topn', 'treemap', 'table', 'events'];+const KINDS = ['count', 'metric', 'timeseries', 'terms', 'search'];+const METRICS = ['count', 'sum', 'avg', 'max', 'min'];++// The inline configurator rendered in place of the ADD picker.+function renderBuilder() {+ const b = builder;+ const vizTiles = VIZ_LIST.map((id) =>+ `<button type="button" data-builder-viz="${id}" class="${b.viz === id ? 'active' : ''}" title="${esc(chartTypes[id]?.describe || '')}">${esc(chartTypes[id]?.name || id)}</button>`+ ).join('');+ const idxDatalist = BUILDER_INDICES.map((i) => `<option value="${esc(i.name)}"></option>`).join('');+ const kindBtns = KINDS.map((k) =>+ `<button type="button" data-builder-kind="${k}" class="${b.kind === k ? 'active' : ''}">${k.toUpperCase()}</button>`).join('<span class="sep">·</span>');+ const metricBtns = METRICS.map((m) =>+ `<button type="button" data-builder-metric="${m}" class="${b.metric === m ? 'active' : ''}">${m.toUpperCase()}</button>`).join('<span class="sep">·</span>');+ const fieldList = BUILDER_FIELDS.map((f) => `<option value="${esc(f.name)}"></option>`).join('');+ const needsField = b.kind === 'terms' || b.kind === 'metric' || (b.kind === 'timeseries' && b.metric !== 'count');+ const needsSize = b.kind === 'terms';+ const needsInterval = b.kind === 'timeseries';+ const preview = b.preview && b.preview.html+ ? b.preview.html+ : `<div class="panel-empty mono faint">${b.preview && b.preview.status === 'loading' ? 'RUNNING PREVIEW…' : 'PREVIEW APPEARS HERE'}</div>`;++ return `+ <div class="builder" role="dialog" aria-label="Configure panel">+ <div class="builder-head">+ <span class="key" style="color:var(--z-accent);">${b.editingId ? 'EDIT PANEL' : '+ NEW PANEL'}</span>+ <button type="button" class="builder-x" data-builder-cancel aria-label="Close">✕</button>+ </div>+ <div class="builder-grid">+ <div class="builder-col builder-form">+ <label class="builder-field">+ <span class="key">1 · VISUALIZATION</span>+ <span class="viz-tiles">${vizTiles}</span>+ </label>+ <label class="builder-field">+ <span class="key">2 · INDEX</span>+ <input type="text" data-builder-index list="builder-indices" value="${esc(b.index)}" placeholder="e.g. logs-prod" class="builder-input" />+ <datalist id="builder-indices">${idxDatalist}</datalist>+ </label>+ <label class="builder-field">+ <span class="key">3 · QUERY KIND</span>+ <span class="btn-row">${kindBtns}</span>+ </label>+ ${needsField ? `+ <label class="builder-field">+ <span class="key">FIELD</span>+ <input type="text" data-builder-field list="builder-fields" value="${esc(b.field)}" placeholder="e.g. level" class="builder-input" />+ <datalist id="builder-fields">${fieldList}</datalist>+ </label>` : ''}+ ${(b.kind === 'metric' || b.kind === 'timeseries' || b.kind === 'terms') ? `+ <label class="builder-field">+ <span class="key">METRIC</span>+ <span class="btn-row">${metricBtns}</span>+ </label>` : ''}+ ${needsSize ? `+ <label class="builder-field">+ <span class="key">TOP N</span>+ <input type="number" min="1" max="50" data-builder-size value="${esc(b.size)}" class="builder-input short" />+ </label>` : ''}+ ${needsInterval ? `+ <label class="builder-field">+ <span class="key">INTERVAL</span>+ <input type="text" data-builder-interval value="${esc(b.interval)}" placeholder="1h" class="builder-input short" />+ </label>` : ''}+ <label class="builder-field">+ <span class="key">FILTER (KQL)</span>+ <input type="text" data-builder-q value="${esc(b.q)}" placeholder="optional · e.g. level:error" class="builder-input" />+ </label>+ <label class="builder-field">+ <span class="key">TITLE</span>+ <input type="text" data-builder-title value="${esc(b.title)}" placeholder="auto" class="builder-input" />+ </label>+ <div class="builder-actions">+ <button type="button" class="builder-save" data-builder-save>${b.editingId ? 'SAVE CHANGES' : 'ADD PANEL'}</button>+ <button type="button" class="builder-cancel" data-builder-cancel>CANCEL</button>+ </div>+ </div>+ <div class="builder-col builder-preview">+ <span class="key">LIVE PREVIEW</span>+ <div class="builder-preview-box">${preview}</div>+ </div>+ </div>+ </div>`;+}+async function render() {const app = document.getElementById('app');// Resolve the active dashboard from either the default registry or@@ -640,11 +875,24 @@ async function render() {}const activeFilters = currentFilters();+ // A declarative (net-new) user dashboard runs a live query PER PANEL+ // (data/panel-query.js) rather than a single whole-dashboard fetch.+ const isDeclarative = !!(dash.isUser && dash.declarative);+ const panelCtx = {+ range: state.time,+ customRange: state.time === 'CUSTOM' ? state.timeCustom : null,+ cluster: state.cluster,+ };let data;let fetchErr = null;// Section-level views (data/settings/users/alerts) get their own// context builder. Everything else goes through the regular query.- if (state.section === 'data' || state.section === 'settings') {+ if (isDeclarative) {+ data = {};+ state.fetchErr = null;+ // NOTE: index priming happens in openBuilder(), NOT here — calling it+ // per-render would re-enter render() and loop.+ } else if (state.section === 'data' || state.section === 'settings') {try {data = await buildSectionData(state.section);} catch (err) {@@ -691,27 +939,44 @@ async function render() {view.title = (dash.name || view.title || '').toUpperCase();}} catch {}- const merged = mergeLayout(view.panels, state.layouts[dash.id]);- const panelsHtml = merged.length- ? merged.map((p) => renderPanel(p, data, state.edit)).join('')- : `<div class="mono faint" style="grid-column: span 12; padding:var(--sp-6) 0;">All panels hidden. Click RESET to restore defaults.</div>`;-- // Police-strip frame: a fixed-position overlay that lives in the page's- // existing margins, so entering edit mode never shifts content. The frame- // itself is a 1px dashed border around the viewport; the top strip carries- // the EDIT MODE label and tips; the bottom strip carries the column index.- const editFrame = state.edit ? `- <div class="edit-frame" aria-hidden="true"></div>++ let panelsHtml;+ let panelCount;+ if (isDeclarative) {+ // Geometry lives IN the panels (x/y/w/h) — no separate layout+ // override. Compact so a stale overlap never hides a panel.+ const panels = compact(view.panels || []);+ panelCount = panels.length;+ panelsHtml = panels.length+ ? panels.map((p) => renderPanel(p, data, state.edit, panelCtx)).join('')+ : `<div class="empty-dash mono faint" style="grid-column:1/span 12;">${+ state.edit+ ? 'EMPTY DASHBOARD · CLICK <span class="accent">+ ADD PANEL</span> BELOW TO BUILD YOUR FIRST PANEL'+ : 'EMPTY DASHBOARD · TOGGLE <span class="accent">EDIT</span> TO ADD PANELS'+ }</div>`;+ } else {+ const merged = mergeLayout(view.panels, state.layouts[dash.id]);+ panelCount = merged.length;+ panelsHtml = merged.length+ ? merged.map((p) => renderPanel(p, data, state.edit, panelCtx)).join('')+ : `<div class="mono faint" style="grid-column: span 12; padding:var(--sp-6) 0;">All panels hidden. Click RESET to restore defaults.</div>`;+ }++ // Edit chrome. The EDIT-MODE top strip now lives in NORMAL FLOW+ // (sticky) right below the sub-nav so it never overlaps the dashboard+ // sub-nav row (Issue 3). The dashed frame + numbered bottom strip stay+ // as fixed, non-interactive overlays behind the panels.+ const editTips = isDeclarative+ ? 'DRAG THE <span class="key-bind">⠿</span> GRIP TO MOVE · DRAG AN EDGE / CORNER TO RESIZE · <span class="key-bind">QUERY</span> TO RECONFIGURE'+ : 'DRAG PANEL TO REORDER · CLICK A <span class="key-bind">NUMBER</span> TO RESIZE · <span class="key-bind">✕</span> TO REMOVE';+ const editStripFlow = state.edit ? `<div class="edit-strip-top" role="status"><span class="marker">EDIT MODE</span>- <span class="tips">- DRAG PANEL TO REORDER ·- CLICK A <span class="key-bind">NUMBER</span> TO RESIZE ·- <span class="key-bind">✕</span> TO REMOVE ·- SCROLL FOR <span class="key-bind">+ ADD</span>- </span>- <span class="meta">${esc(dash.name.toUpperCase())} · ${merged.length} PANELS</span>- </div>+ <span class="tips">${editTips}</span>+ <span class="meta">${esc(dash.name.toUpperCase())} · ${panelCount} PANELS</span>+ </div>` : '';+ const editFrame = state.edit ? `+ <div class="edit-frame" aria-hidden="true"></div><div class="edit-strip-bottom" aria-hidden="true">${Array.from({ length: 12 }, (_, i) => `<span>${String(i + 1).padStart(2, '0')}</span>`).join('')}</div>@@ -719,12 +984,14 @@ async function render() {const gridOverlay = state.edit? `<div class="edit-grid" aria-hidden="true">${'<span></span>'.repeat(12)}</div>`: '';- const addHtml = state.edit ? renderAddPicker() : '';+ const addHtml = state.edit ? renderAddPicker(dash) : '';// Section-level views (alerts, data, users, settings) don't show the// inline time control — the time range is a dashboards-section concept.const hideTimeCtrl = state.section !== 'dashboards' && state.section !== 'discover';- const showFilterBar = state.section === 'dashboards';+ // Declarative user dashboards query per-panel; the dashboard-level KQL+ // bar / saved views don't apply, so hide them (time range still does).+ const showFilterBar = state.section === 'dashboards' && !isDeclarative;const filterBarHtml = showFilterBar? FilterBar({ filters: activeFilters, kql: serializeKql(activeFilters) }): '';@@ -759,7 +1026,8 @@ async function render() {${hideTimeCtrl ? '' : `<div class="dash-ctrls">${TimeCtrl({ active: state.time, custom: state.timeCustom })}${refreshHtml}${clusterHtml}</div>`}${filterBarHtml}${savedViewsHtml}- <main class="canvas${state.edit ? ' edit' : ''}" aria-label="${esc(dash.name)}">${gridOverlay}${panelsHtml}</main>+ ${editStripFlow}+ <main class="canvas${state.edit ? ' edit' : ''}${isDeclarative ? ' declarative' : ''}" aria-label="${esc(dash.name)}">${gridOverlay}${panelsHtml}</main>${addHtml}${state.mobile ? '</div><div class="iphone-home-bar"></div></div>' : ''}${Footer()}@@ -781,10 +1049,299 @@ async function render() {}}+// ==========================================================+// Declarative (net-new) user-dashboard subsystem+// • panel builder (viz + index/query + live preview)+// • per-panel mutation → PATCH panels[]+// • free-form pointer drag-move + edge/corner resize+// ==========================================================++/** The active dashboard IF it's a declarative user dashboard, else null. */+function activeUserDash() {+ const all = mergedDashboards(defaults, { includeHidden: true });+ const d = all.find((x) => x.id === state.route);+ return d && d.isUser && d.declarative ? d : null;+}++/** Clone the doc's panels[], apply fn, compact, persist (optimistic) + render. */+function userPanelsMutate(id, fn) {+ const doc = getDoc(id);+ if (!doc) return;+ const panels = (Array.isArray(doc.panels) ? doc.panels : []).map((p) => ({ ...p }));+ const next = fn(panels) || panels;+ patchPanels(id, compact(next));+ render();+}++// ---- panel builder ---------------------------------------+let BUILDER_INDICES_LOADED = false;+async function ensureBuilderIndices(force) {+ if (BUILDER_INDICES_LOADED && !force) return;+ // Mark loaded BEFORE the await so a concurrent/re-entrant render can't+ // spawn a second fetch → render → fetch loop.+ BUILDER_INDICES_LOADED = true;+ try {+ const list = await listIndices(defaultClusterId());+ BUILDER_INDICES = (list || []).filter((i) => i && i.name);+ if (!builder.index && BUILDER_INDICES.length) builder.index = BUILDER_INDICES[0].name;+ if (builder.open) render();+ } catch {+ BUILDER_INDICES_LOADED = false; // allow a later retry+ }+}+async function ensureBuilderFields(index) {+ if (!index) { BUILDER_FIELDS = []; return; }+ try {+ // Populate the field datalist silently — do NOT render() here, or a+ // render mid-keystroke in the index input would steal focus. The new+ // suggestions surface on the next natural render (viz/kind click, etc).+ BUILDER_FIELDS = (await listFields(index)) || [];+ } catch { BUILDER_FIELDS = []; }+}++function openBuilder(editingId) {+ const dash = activeUserDash();+ if (!dash) return;+ builder.open = true;+ builder.editingId = editingId || null;+ builder.preview = null;+ builder._geometry = null;+ if (editingId) {+ const p = (getDoc(dash.id)?.panels || []).find((x) => x.id === editingId);+ if (p) {+ builder.viz = p.viz?.type || 'topn';+ builder.index = p.query?.index || builder.index;+ builder.kind = p.query?.kind || 'terms';+ builder.field = p.query?.field || '';+ builder.metric = p.query?.metric || 'count';+ builder.size = p.query?.size || 8;+ builder.interval = p.query?.interval || '1h';+ builder.q = p.query?.q || '';+ builder.title = p.title || '';+ builder.time = !!p.query?.time;+ builder._geometry = p.geometry || null;+ }+ } else {+ builder.viz = builder.viz || 'topn';+ builder.kind = builder.kind || 'terms';+ builder.field = builder.field || 'level';+ builder.metric = builder.metric || 'count';+ builder.q = '';+ builder.title = '';+ }+ ensureBuilderIndices();+ ensureBuilderFields(builder.index);+ render();+ previewNow();+}++function closeBuilder() {+ builder.open = false;+ builder.editingId = null;+ builder.preview = null;+ render();+}++let previewSeq = 0;+let previewTimer = null;+function previewSoon() { clearTimeout(previewTimer); previewTimer = setTimeout(previewNow, 250); }+function paintPreview() {+ const box = document.querySelector('.builder-preview-box');+ if (!box) return;+ if (builder.preview && builder.preview.html) box.innerHTML = builder.preview.html;+ else if (builder.preview && builder.preview.status === 'loading') box.innerHTML = '<div class="panel-empty mono faint">RUNNING PREVIEW…</div>';+}+async function previewNow() {+ clearTimeout(previewTimer);+ const draft = builderPanelDraft();+ if (!draft.query.index || !draft.query.kind) { builder.preview = null; paintPreview(); return; }+ ensureBuilderFields(draft.query.index); // refresh field suggestions (debounced via previewNow)+ const my = ++previewSeq;+ builder.preview = { status: 'loading', html: '' };+ paintPreview();+ try {+ const res = await fetchPanel(draft, { range: state.time });+ if (my !== previewSeq) return;+ builder.preview = { status: 'ready', html: renderDeclarativePanel(draft, { status: 'ready', data: res }) };+ } catch (e) {+ if (my !== previewSeq) return;+ builder.preview = { status: 'error', html: `<div class="panel-empty mono faint">PREVIEW ERROR · ${esc(String(e.message || e)).slice(0, 80)}</div>` };+ }+ paintPreview();+}++function commitBuilder() {+ const dash = activeUserDash();+ if (!dash) return;+ const draft = builderPanelDraft();+ if (!draft.query.index) return;+ builder.open = false;+ builder.editingId = null;+ builder.preview = null;+ userPanelsMutate(dash.id, (panels) => {+ const idx = panels.findIndex((p) => p.id === draft.id);+ if (idx >= 0) {+ draft.geometry = draft.geometry || panels[idx].geometry || nextGeometry(panels);+ panels[idx] = draft;+ } else {+ draft.geometry = draft.geometry || nextGeometry(panels);+ panels.push(draft);+ }+ return panels;+ });+ requestAnimationFrame(() => {+ try {+ const el = document.querySelector(`.panel[data-panel="${CSS.escape(draft.id)}"]`);+ if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });+ } catch { /* ignore */ }+ });+}++// Click handling for builder + user-panel chrome. Returns true if handled.+function handleDeclClick(e) {+ if (e.target.closest('[data-builder-open]')) { openBuilder(); return true; }+ if (e.target.closest('[data-builder-cancel]')) { closeBuilder(); return true; }+ const viz = e.target.closest('[data-builder-viz]');+ if (viz) { builder.viz = viz.getAttribute('data-builder-viz'); render(); previewNow(); return true; }+ const kind = e.target.closest('[data-builder-kind]');+ if (kind) { builder.kind = kind.getAttribute('data-builder-kind'); render(); previewNow(); return true; }+ const metric = e.target.closest('[data-builder-metric]');+ if (metric) { builder.metric = metric.getAttribute('data-builder-metric'); render(); previewNow(); return true; }+ if (e.target.closest('[data-builder-save]')) { commitBuilder(); return true; }+ const cfg = e.target.closest('[data-user-config]');+ if (cfg) { openBuilder(cfg.getAttribute('data-user-config')); return true; }+ const rm = e.target.closest('[data-user-remove]');+ if (rm) {+ const id = rm.getAttribute('data-user-remove');+ const dash = activeUserDash();+ if (dash) userPanelsMutate(dash.id, (panels) => panels.filter((p) => p.id !== id));+ return true;+ }+ const usz = e.target.closest('[data-user-size]');+ if (usz) {+ const pid = usz.getAttribute('data-panel');+ const w = clampInt(usz.getAttribute('data-user-size'), 1, GRID_COLS);+ const dash = activeUserDash();+ if (dash) userPanelsMutate(dash.id, (panels) => {+ const idx = panels.findIndex((p) => p.id === pid);+ if (idx >= 0) {+ const g = panelGeom(panels[idx]);+ panels[idx] = { ...panels[idx], geometry: { ...g, w, x: Math.min(g.x, GRID_COLS - w) } };+ }+ return panels;+ });+ return true;+ }+ return false;+}++// Text-input handling for the builder (no full re-render → focus preserved).+function handleDeclInput(e) {+ const t = e.target;+ if (!t || !t.matches) return false;+ if (t.matches('[data-builder-index]')) { builder.index = t.value.trim(); previewSoon(); return true; }+ if (t.matches('[data-builder-field]')) { builder.field = t.value; previewSoon(); return true; }+ if (t.matches('[data-builder-size]')) { builder.size = t.value; previewSoon(); return true; }+ if (t.matches('[data-builder-interval]')) { builder.interval = t.value; previewSoon(); return true; }+ if (t.matches('[data-builder-q]')) { builder.q = t.value; previewSoon(); return true; }+ if (t.matches('[data-builder-title]')) { builder.title = t.value; return true; }+ return false;+}++// ---- free-form pointer drag-move + resize ----------------+let geomDrag = null;++function cellMetrics(canvasEl) {+ const rect = canvasEl.getBoundingClientRect();+ const cs = getComputedStyle(canvasEl);+ const colGap = parseFloat(cs.columnGap) || 16;+ const rowGap = parseFloat(cs.rowGap) || 16;+ const colW = (rect.width - colGap * (GRID_COLS - 1)) / GRID_COLS;+ return { pitchX: colW + colGap, pitchY: ROW_H + rowGap };+}++function startGeomDrag(e, mode, panelId) {+ if (!state.edit) return;+ // `panelId` identifies the panel; the doc is the ACTIVE DASHBOARD's doc+ // (getDoc/userPanelsMutate are keyed by dashboard id, not panel id).+ const dash = activeUserDash();+ if (!dash) return;+ const doc = getDoc(dash.id);+ const panelEl = e.target.closest('.panel');+ const canvasEl = panelEl && panelEl.closest('.canvas');+ if (!panelEl || !canvasEl || !doc) return;+ const p = (doc.panels || []).find((x) => x.id === panelId);+ if (!p) return;+ e.preventDefault();+ const m = cellMetrics(canvasEl);+ geomDrag = {+ dashId: dash.id, panelId, mode, panelEl,+ startX: e.clientX, startY: e.clientY,+ startGeom: panelGeom(p),+ pitchX: m.pitchX, pitchY: m.pitchY,+ cur: panelGeom(p),+ };+ panelEl.classList.add('dragging-geom');+ try { e.target.setPointerCapture(e.pointerId); } catch { /* ignore */ }+}++function moveGeomDrag(e) {+ if (!geomDrag) return;+ const d = geomDrag;+ const dCol = Math.round((e.clientX - d.startX) / d.pitchX);+ const dRow = Math.round((e.clientY - d.startY) / d.pitchY);+ const g = { ...d.startGeom };+ if (d.mode === 'move') {+ g.x = clampInt(d.startGeom.x + dCol, 0, GRID_COLS - d.startGeom.w);+ g.y = Math.max(0, d.startGeom.y + dRow);+ } else {+ if (d.mode === 'e' || d.mode === 'se') g.w = clampInt(d.startGeom.w + dCol, 1, GRID_COLS - d.startGeom.x);+ if (d.mode === 's' || d.mode === 'se') g.h = Math.max(1, d.startGeom.h + dRow);+ }+ d.cur = g;+ d.panelEl.style.gridColumn = `${g.x + 1}/span ${g.w}`;+ d.panelEl.style.gridRow = `${g.y + 1}/span ${g.h}`;+ const wh = d.panelEl.querySelector('.panel-edit .wh');+ if (wh) wh.innerHTML = `${g.w}<span class="x">×</span>${g.h}`;+}++function endGeomDrag() {+ if (!geomDrag) return;+ const d = geomDrag;+ geomDrag = null;+ d.panelEl.classList.remove('dragging-geom');+ const g = d.cur;+ const s = d.startGeom;+ if (g.x !== s.x || g.y !== s.y || g.w !== s.w || g.h !== s.h) {+ userPanelsMutate(d.dashId, (panels) => {+ const idx = panels.findIndex((p) => p.id === d.panelId);+ if (idx >= 0) panels[idx] = { ...panels[idx], geometry: g };+ return panels;+ });+ }+}++document.addEventListener('pointerdown', (e) => {+ const grip = e.target.closest('[data-grip]');+ if (grip) { startGeomDrag(e, 'move', grip.getAttribute('data-grip')); return; }+ const rz = e.target.closest('[data-resize]');+ if (rz) { startGeomDrag(e, rz.getAttribute('data-resize'), rz.getAttribute('data-panel')); }+});+document.addEventListener('pointermove', moveGeomDrag);+document.addEventListener('pointerup', endGeomDrag);+document.addEventListener('pointercancel', endGeomDrag);++// Builder text inputs (input event — no re-render, keeps focus).+document.addEventListener('input', (e) => { handleDeclInput(e); });+// ---------- event delegation ------------------------------let dragSrcId = null;document.addEventListener('click', (e) => {+ // Declarative user-dashboard chrome (builder + user-panel toolbar).+ // Handled first so its specific data-* attrs never fall through to the+ // default-dashboard handlers below.+ if (handleDeclClick(e)) { e.preventDefault(); return; }// Primary nav: top-level product sectionconst secA = e.target.closest('[data-section]');if (secA) {@@ -1118,11 +1675,13 @@ document.addEventListener('click', (e) => {if (mgClone) {const id = mgClone.getAttribute('data-mg-clone');const current = mergedDashboards(defaults, { includeHidden: true }).find((d) => d.id === id);- const name = prompt('Clone "' + (current?.name || id) + '" as:', (current?.name || 'Untitled') + ' (copy)');- if (name) {- const newId = createUserDashboard({ name, fromId: id });+ // POST a real durable doc, then route to it in edit mode. Rename is+ // inline (contenteditable scene title) — no window.prompt.+ (async () => {+ const newId = await createUserDashboard({ name: (current?.name || 'Untitled') + ' (copy)', fromId: id });+ state.edit = true; localStorage.setItem(LS.edit, '1');location.hash = '#/dashboards/' + newId;- }+ })();return;}const mgDelete = e.target.closest('[data-mg-delete]');@@ -1140,12 +1699,16 @@ document.addEventListener('click', (e) => {}const mgNew = e.target.closest('[data-mg-new]');if (mgNew) {- const fromId = mgNew.getAttribute('data-mg-new');- const name = prompt(fromId ? 'New dashboard from "' + fromId + '" · Name:' : 'New blank dashboard · Name:', 'Untitled');- if (name) {- const newId = createUserDashboard({ name, fromId: fromId || null });+ const fromId = mgNew.getAttribute('data-mg-new') || null;+ // Net-new = declarative shell (empty panels[]) → POST a real doc,+ // route to it in edit mode, and auto-open the panel builder. Naming+ // is inline via the contenteditable scene title (no window.prompt).+ (async () => {+ const newId = await createUserDashboard({ name: fromId ? 'Copy of ' + fromId : 'Untitled dashboard', fromId });+ state.edit = true; localStorage.setItem(LS.edit, '1');location.hash = '#/dashboards/' + newId;- }+ if (!fromId) setTimeout(() => { if (activeUserDash()) openBuilder(); }, 80);+ })();return;}const mgCluster = e.target.closest('[data-mg-cluster]');@@ -1360,4 +1923,18 @@ if (state.refresh > 0) setRefreshInterval(state.refresh);// Restore mobile preview class if it was active.if (state.mobile) document.documentElement.classList.add('mobile-preview');+// Re-render when the dashboard store reconciles (e.g. a 409 re-GET, or a+// late hydrate refresh) so the nav / panels reflect the durable set.+setOnChange(() => { if (!geomDrag) render(); });++// Re-render when a per-panel query settles — but never while the user is+// mid drag/resize or typing in the builder (that would nuke the gesture+// or steal input focus).+onPanelData(() => {+ if (geomDrag) return;+ const ae = document.activeElement;+ if (ae && (ae.tagName === 'INPUT' || ae.tagName === 'SELECT' || ae.isContentEditable)) return;+ render();+});+render();diff --git a/xerj-ux/src/data/dashboard-api.js b/xerj-ux/src/data/dashboard-api.jsnew file mode 100644index 000000000..ea20541ec--- /dev/null+++ b/xerj-ux/src/data/dashboard-api.js@@ -0,0 +1,63 @@+// ============================================================+// XERJ.ai — Dashboards CRUD client+//+// Thin async wrapper over the durable `/_xerj-console/api/v1/dashboards`+// surface (implemented in engine/crates/xerj-console-api/src/dashboards.rs).+// This is the ONLY thing that turns a user-created dashboard into+// backend-durable state — before this module existed the SPA wrote+// only to localStorage and the CRUD backend had no caller.+//+// Every method returns the parsed Dashboard doc (or the list envelope).+// Optimistic concurrency: PUT/PATCH send `If-Match: W/"<version>"` built+// from the doc's own `version` field (the primary concurrency source);+// the ETag response header is captured too as a convenience.+//+// Errors bubble up as Error objects carrying `.status` (409/403/404/…)+// so the store can branch on a stale-etag 409 and re-GET.+// ============================================================++import { apiRaw } from '../xerj-console-auth.js';++const BASE = '/dashboards';+const enc = encodeURIComponent;++/** Build the weak-etag If-Match header from a version number. */+function ifMatch(version) {+ if (version == null) return undefined;+ return { 'if-match': `W/"${version}"` };+}++/** GET /dashboards → { dashboards: [...], total }. */+export async function list() {+ const { data } = await apiRaw('GET', BASE);+ return data || { dashboards: [], total: 0 };+}++/** GET /dashboards/{id} → { doc, etag }. */+export async function get(id) {+ const { data, etag } = await apiRaw('GET', `${BASE}/${enc(id)}`);+ return { doc: data, etag };+}++/** POST /dashboards → { doc, etag }. Body per the CREATE contract. */+export async function create(body) {+ const { data, etag } = await apiRaw('POST', BASE, body);+ return { doc: data, etag };+}++/** PUT /dashboards/{id} (full replace) → { doc, etag }. */+export async function replace(id, body, version) {+ const { data, etag } = await apiRaw('PUT', `${BASE}/${enc(id)}`, body, ifMatch(version));+ return { doc: data, etag };+}++/** PATCH /dashboards/{id} (partial) → { doc, etag }. Omitted fields unchanged. */+export async function patch(id, partial, version) {+ const { data, etag } = await apiRaw('PATCH', `${BASE}/${enc(id)}`, partial, ifMatch(version));+ return { doc: data, etag };+}++/** DELETE /dashboards/{id} (soft delete). 204, no body. */+export async function remove(id, version) {+ await apiRaw('DELETE', `${BASE}/${enc(id)}`, undefined, ifMatch(version));+}diff --git a/xerj-ux/src/data/dashboard-store.js b/xerj-ux/src/data/dashboard-store.jsindex f99866e5c..39f6e3096 100644--- a/xerj-ux/src/data/dashboard-store.js+++ b/xerj-ux/src/data/dashboard-store.js@@ -1,144 +1,256 @@// ============================================================-// XERJ.ai — Dashboard metadata store+// XERJ.ai — Dashboard metadata store (backend-durable)//-// This is the thin persistent layer that turns "dashboards are-// hardcoded JS files" into "dashboards have editable metadata".+// Previously this layer wrote ONLY to localStorage['xerj.dashboards'],+// so a user-created dashboard vanished on a cache-clear or a new device+// — the durable `/_xerj-console/api/v1/dashboards` CRUD backend+// (engine/crates/xerj-console-api/src/dashboards.rs) had no caller.//-// Default dashboards (the ones shipped in src/dashboards/*.js)-// are still code — diffable, reviewable, version-controlled.-// But users can NOW:-// • rename them-// • reorder them in the nav-// • hide them-// • clone them to create a new user-owned dashboard-// • delete user dashboards (defaults can only be hidden, never deleted)+// It is now an ASYNC FACADE over that CRUD surface with a localStorage+// write-through cache://-// Everything lives under the `xerj.dashboards` localStorage key-// so it survives reloads and round-trips through export/import.+// • boot: hydrate() = GET /dashboards → in-memory map DOCS, mirrored+// to `xerj.dashboards` LS for instant next-boot paint. If the+// request fails we keep the LS cache (offline/dev still works).+// • every mutation writes optimistically to DOCS + LS, then fires the+// matching CRUD call; a 409 (stale etag) re-GETs and re-applies.+// • createUserDashboard POSTs a REAL dashboard doc (declarative+// panels[]) and returns the server-assigned uuid; offline it falls+// back to a local `user-…` id so dev keeps working.+//+// DEFAULT (code) dashboards keep their local metadata (rename / nav+// order / hidden) in the `xerj.dashboards` LS blob as before — those are+// re-derivable overrides on code, not user data. USER dashboards are the+// durable backend records.// ============================================================+import * as api from './dashboard-api.js';+const LS_KEY = 'xerj.dashboards';+const LAYOUT_PREFIX = 'xerj.layout.';/**- * Full shape of the store:- *+ * LS blob shape (v2):* {- * order: ['ai-overview', 'rag-quality', 'user-1abc', ...], // nav order- * names: { 'ai-overview': 'AI Overview (mine)' }, // per-id rename- * hidden: ['logs-overview'], // hidden from nav- * custom: {- * 'user-1abc': {- * name: 'Prod API Traffic',- * clonedFrom: 'search-discover', // default template id- * createdAt: '2026-04-14T18:20:00Z',- * dataSource: { cluster: 'prod-us', index: 'logs-prod' },- * }- * }+ * order: ['ai-overview', …, '<uuid>'], // nav order (code + user)+ * names: { '<id>': 'Custom name' }, // per-id rename override+ * hidden: ['logs-overview'], // hidden from nav+ * custom: { '<uuid>': <Dashboard doc> }, // MIRROR of DOCS (offline paint)* }+ *+ * A user Dashboard doc (backend contract):+ * { id, owner, visibility, name, section, group, cloned_from,+ * panels:[<declarative Panel>], filters_default, time_default,+ * version, created_at, updated_at, deleted_at }*/function load() {try {const raw = localStorage.getItem(LS_KEY);if (!raw) return {};- return JSON.parse(raw);- } catch {- return {};- }+ return JSON.parse(raw) || {};+ } catch { return {}; }}function save(m) {- localStorage.setItem(LS_KEY, JSON.stringify(m));+ try { localStorage.setItem(LS_KEY, JSON.stringify(m)); } catch { /* quota */ }}-// ---------- reads ----------------------------------------+// ── in-memory state ──────────────────────────────────────────────────+// Seed DOCS from the LS cache synchronously so the very first paint (in+// parseRoute / render, before hydrate resolves) shows the user's+// dashboards offline. hydrate() overwrites this from the server.+let DOCS = (() => {+ const m = load();+ return m.custom && typeof m.custom === 'object' ? { ...m.custom } : {};+})();++let onChange = null;+export function setOnChange(cb) { onChange = cb; }+function emitChange() { if (typeof onChange === 'function') { try { onChange(); } catch { /* ignore */ } } }++/** Write DOCS → LS `custom`, ensuring every user id is in `order`. */+function mirror() {+ const m = load();+ m.custom = { ...DOCS };+ m.order = Array.isArray(m.order) ? m.order.slice() : [];+ // Drop order entries for user ids no longer present, keep code ids.+ m.order = m.order.filter((id) => DOCS[id] || !isLikelyUserId(id, m));+ for (const id of Object.keys(DOCS)) if (!m.order.includes(id)) m.order.push(id);+ save(m);+}+// A user id is anything we have (or had) a custom doc for. Code ids are+// never in DOCS, so "not in DOCS and was a custom key" ⇒ removed user id.+function isLikelyUserId(id, m) {+ return !!(m.custom && Object.prototype.hasOwnProperty.call(m.custom, id) && !DOCS[id]);+}++// ── serialized per-id write queue (avoids etag races on rapid edits) ──+const queues = {};+function enqueue(id, fn) {+ const prev = queues[id] || Promise.resolve();+ const next = prev.then(fn, fn);+ queues[id] = next.catch(() => {});+ return next;+}++/** PATCH a doc, adopting the returned (version-bumped) server doc. On a+ * 409 (stale etag) re-GET and retry once with the fresh version. */+async function pushPatch(id, partial) {+ const doc = DOCS[id];+ if (!doc || doc.__local) return; // offline-only doc: nothing to push+ try {+ const { doc: fresh } = await api.patch(id, partial, doc.version);+ DOCS[id] = fresh; mirror();+ } catch (e) {+ if (e && e.status === 409) {+ try {+ const { doc: server } = await api.get(id);+ // Re-apply our field(s) on top of the server's fresh version.+ const merged = { ...server, ...partial };+ const { doc: fresh } = await api.patch(id, partial, server.version);+ DOCS[id] = fresh || merged; mirror(); emitChange();+ } catch { /* give up; optimistic local state stands */ }+ }+ // network/other error: keep optimistic local state (offline fallback)+ }+}++// ── reads ────────────────────────────────────────────────────────────/**- * Merge default dashboards with user metadata. Returns an array- * of `{ id, name, isUser, clonedFrom?, dataSource?, render }` in- * the user-defined nav order. Hidden items are excluded. Pass- * `{ includeHidden: true }` to get them too (used by MANAGE view).+ * Merge default (code) dashboards with user metadata + backend user+ * dashboards. Returns render-ready entries in nav order. User entries+ * carry `{ isUser:true, declarative, panels, doc, version, render }`.*/export function mergedDashboards(defaults, { includeHidden = false } = {}) {const m = load();const hidden = new Set(m.hidden || []);- const custom = m.custom || {};- const names = m.names || {};-- // Build a map for quick lookup.+ const names = m.names || {};const byId = Object.fromEntries(defaults.map((d) => [d.id, d]));- const orderList = Array.isArray(m.order) && m.order.length- ? m.order- : defaults.map((d) => d.id);+ const order = Array.isArray(m.order) && m.order.length ? m.order : defaults.map((d) => d.id);++ const emitUser = (id) => {+ const doc = DOCS[id] || (m.custom && m.custom[id]);+ if (!doc) return null;+ const clonedFrom = doc.cloned_from || doc.clonedFrom || null;+ const template = clonedFrom ? byId[clonedFrom] : null;+ const panels = Array.isArray(doc.panels) ? doc.panels : [];+ // Declarative = net-new (no live template) — renders from panels[]+ // via the builder. A clone of a still-present code template borrows+ // that template's render (durable, but not panel-editable).+ const declarative = !template;+ return {+ id,+ name: names[id] || doc.name,+ isUser: true,+ declarative,+ clonedFrom,+ panels,+ doc,+ version: doc.version,+ section: doc.section || 'dashboards',+ group: doc.group || 'user',+ hidden: hidden.has(id),+ render: declarative+ ? makeDeclarativeRender(doc, names[id])+ : (template.render || blankRender(doc.name)),+ };+ };const out = [];const seen = new Set();- for (const id of orderList) {+ for (const id of order) {if (hidden.has(id) && !includeHidden) { seen.add(id); continue; }- const def = byId[id];- const user = custom[id];- if (def) {- out.push({- ...def,- name: names[id] || def.name,- isUser: false,- hidden: hidden.has(id),- });- } else if (user) {- // A user-created dashboard — borrow the render from its template.- const source = user.clonedFrom ? byId[user.clonedFrom] : null;- out.push({- id,- name: names[id] || user.name,- render: source?.render || blankRender(user.name),- isUser: true,- clonedFrom: user.clonedFrom,- dataSource: user.dataSource,- hidden: hidden.has(id),- });+ if (byId[id]) {+ out.push({ ...byId[id], name: names[id] || byId[id].name, isUser: false, hidden: hidden.has(id) });+ seen.add(id);+ } else {+ const u = emitUser(id);+ if (u) { out.push(u); seen.add(id); }}- seen.add(id);}- // Append defaults the user hasn't yet placed (new ship adds).for (const def of defaults) {if (seen.has(def.id)) continue;if (hidden.has(def.id) && !includeHidden) continue;- out.push({- ...def,- name: names[def.id] || def.name,- isUser: false,- hidden: hidden.has(def.id),- });+ out.push({ ...def, name: names[def.id] || def.name, isUser: false, hidden: hidden.has(def.id) });+ seen.add(def.id);+ }+ // Freshly hydrated user docs not yet placed in `order`.+ for (const id of Object.keys(DOCS)) {+ if (seen.has(id)) continue;+ const u = emitUser(id);+ if (u && (!u.hidden || includeHidden)) { out.push(u); seen.add(id); }}return out;}-/** Lightweight fallback render used for a user-created dashboard whose- * clonedFrom template was deleted out from under it. */+/** Render fn for a declarative (net-new) user dashboard. */+function makeDeclarativeRender(doc, nameOverride) {+ return () => ({+ title: (nameOverride || doc.name || 'UNTITLED').toUpperCase(),+ kicker: 'USER DASHBOARD',+ meta: [((doc.panels && doc.panels.length) || 0) + ' PANELS'],+ isDeclarative: true,+ panels: (Array.isArray(doc.panels) ? doc.panels : []).map((p) => ({ ...p, source: 'user' })),+ });+}++/** Fallback for a clone whose template was deleted out from under it. */function blankRender(name) {return () => ({title: (name || 'BLANK').toUpperCase(),kicker: 'USER DASHBOARD',meta: ['NO TEMPLATE'],- panels: [- {- id: 'empty',- eyebrow: 'NOTHING HERE YET',- cols: 12,- render: () =>- '<div class="mono faint">This user dashboard was cloned from a template that no longer exists. Open the MANAGE view to re-point it at a different template, or delete and recreate.</div>',- },- ],+ isDeclarative: true,+ panels: [],});}-// ---------- mutations ------------------------------------+/** The live backend doc for a user dashboard (panels + version). */+export function getDoc(id) { return DOCS[id] || null; }++/** Is the given id a user-created dashboard (vs. a default)? */+export function isUserDash(id) { return !!DOCS[id]; }++/** Raw read of the LS blob — used by the MANAGE view. */+export function readStore() { return load(); }++// ── boot ─────────────────────────────────────────────────────────────++/** Pull the durable dashboard set from the backend, merge into DOCS,+ * mirror to LS. Idempotent; safe to call before app.js first paint. */+export async function hydrate() {+ try {+ const { dashboards } = await api.list();+ const next = {};+ for (const d of dashboards || []) {+ if (!d || !d.id || d.deleted_at) continue;+ if (d.visibility === 'default') continue; // managed/code-owned, read-only+ next[d.id] = d;+ }+ DOCS = next;+ mirror();+ emitChange();+ return true;+ } catch {+ // Offline: keep the DOCS seeded from the LS cache at module init.+ return false;+ }+}++// ── mutations ────────────────────────────────────────────────────────export function renameDashboard(id, name) {const m = load();m.names = m.names || {};- if (name && name.trim()) m.names[id] = name.trim();- else delete m.names[id];+ const nm = (name || '').trim();+ if (nm) m.names[id] = nm; else delete m.names[id];save(m);+ if (DOCS[id]) {+ DOCS[id] = { ...DOCS[id], name: nm || DOCS[id].name };+ mirror();+ if (!DOCS[id].__local) enqueue(id, () => pushPatch(id, { name: DOCS[id].name }));+ }}export function reorderDashboards(orderIds) {@@ -157,47 +269,92 @@ export function setHidden(id, hidden) {}/**- * Create a user-owned dashboard. If `fromId` is provided, it- * becomes a clone of that default (render inherited). Otherwise- * it's a blank shell. Returns the new id.+ * Create a user-owned dashboard as a REAL backend doc.+ * fromId → clone (borrows that code template's render; durable name)+ * no fromId → net-new declarative dashboard (empty panels[] + builder)+ * Returns the server uuid (or a local `user-…` id when offline).*/-export function createUserDashboard({ name, fromId = null, dataSource = null } = {}) {- const m = load();- m.custom = m.custom || {};- const id = 'user-' + Math.random().toString(36).slice(2, 8) + Date.now().toString(36).slice(-4);- m.custom[id] = {+export async function createUserDashboard({ name, fromId = null, dataSource = null } = {}) {+ const clonedFrom = fromId || null;+ const body = {name: name || 'Untitled',- clonedFrom: fromId,- createdAt: new Date().toISOString(),- dataSource,+ visibility: 'private',+ section: 'dashboards',+ group: 'user',+ cloned_from: clonedFrom,+ panels: [],+ filters_default: {},+ time_default: null,};- m.order = m.order || [];- m.order.push(id);+ try {+ const { doc } = await api.create(body);+ DOCS[doc.id] = doc;+ pushOrder(doc.id);+ mirror();+ emitChange();+ return doc.id;+ } catch (e) {+ // Offline fallback — local id, localStorage only (old behaviour).+ const id = 'user-' + Math.random().toString(36).slice(2, 8) + Date.now().toString(36).slice(-4);+ const now = new Date().toISOString();+ DOCS[id] = {+ id, owner: 'local', org_id: 'default', visibility: 'private',+ name: body.name, section: 'dashboards', group: 'user',+ cloned_from: clonedFrom, panels: [], filters_default: {}, time_default: null,+ version: 0, created_at: now, updated_at: now, deleted_at: null, __local: true,+ };+ pushOrder(id);+ mirror();+ emitChange();+ return id;+ }+}++function pushOrder(id) {+ const m = load();+ m.order = Array.isArray(m.order) ? m.order : [];+ if (!m.order.includes(id)) m.order.push(id);save(m);- return id;}-export function deleteUserDashboard(id) {+export async function deleteUserDashboard(id) {+ const doc = DOCS[id];+ delete DOCS[id];const m = load();- if (m.custom) delete m.custom[id];if (m.order) m.order = m.order.filter((x) => x !== id);if (m.names) delete m.names[id];if (m.hidden) m.hidden = m.hidden.filter((x) => x !== id);+ if (m.custom) delete m.custom[id];save(m);- // Also wipe any layout overrides tied to this id- localStorage.removeItem('xerj.layout.' + id);+ try { localStorage.removeItem(LAYOUT_PREFIX + id); } catch { /* ignore */ }+ emitChange();+ if (doc && !doc.__local) {+ try { await api.remove(id, doc.version); } catch { /* server prune best-effort */ }+ }}-/** Wipe every metadata edit. Defaults reappear in their original order. */-export function resetAll() {- localStorage.removeItem(LS_KEY);+/**+ * Replace a user dashboard's panels[] (add / move / resize / remove).+ * Optimistic: DOCS + LS update immediately; PATCH fires (serialised).+ */+export function patchPanels(id, panels) {+ if (!DOCS[id]) return;+ DOCS[id] = { ...DOCS[id], panels };+ mirror();+ if (!DOCS[id].__local) enqueue(id, () => pushPatch(id, { panels }));}-/** Is the given id a user-created dashboard (as opposed to a default)? */-export function isUserDash(id) {- const m = load();- return !!(m.custom && m.custom[id]);+/** Patch arbitrary top-level fields on a user doc (e.g. time_default). */+export function patchDashboard(id, partial) {+ if (!DOCS[id]) return;+ DOCS[id] = { ...DOCS[id], ...partial };+ mirror();+ if (!DOCS[id].__local) enqueue(id, () => pushPatch(id, partial));}-/** Raw read of the store — used by MANAGE view to show what's persisted. */-export function readStore() { return load(); }+/** Wipe LOCAL metadata + cache. Backend user dashboards are durable and+ * re-appear on the next hydrate() — that is the point of the rework. */+export function resetAll() {+ DOCS = {};+ try { localStorage.removeItem(LS_KEY); } catch { /* ignore */ }+}diff --git a/xerj-ux/src/data/panel-query.js b/xerj-ux/src/data/panel-query.jsnew file mode 100644index 000000000..e983acae1--- /dev/null+++ b/xerj-ux/src/data/panel-query.js@@ -0,0 +1,241 @@+// ============================================================+// XERJ.ai — Per-panel query path (declarative user panels)+//+// A user-built panel carries a declarative `query` block instead of a+// closure. This module turns that block into a single ES-compat+// `_search` body, runs it same-origin against the engine, and+// normalises the response into a small shape the declarative renderer+// (ux/panel-render.js) consumes:+//+// { total, value, series:[{t,count}], buckets:[{key,count}], hits:[...] }+//+// Results are cached by (index + body) so re-renders are synchronous+// cache hits; a subscriber (`onPanelData`) lets the app re-render when+// an in-flight query settles — the same optimistic pattern the search+// box uses. This closes the "custom dashboards have no live data" gap+// without touching the 8-dashId dispatch in backends/xerj.js.+//+// query block shape (all optional except index+kind):+// { index, kind, q, field, metric, agg, interval, size, time }+// kind : 'count' | 'metric' | 'timeseries' | 'terms' | 'search'+// metric : 'count' | 'sum' | 'avg' | 'max' | 'min'+// time : true → constrain to the global range; default off so+// sparse/seed data still shows for count/terms/metric.+// ============================================================++// rc.1 aggregation materialisation cap workaround — mirrors+// backends/xerj.js. A large `size` lifts the doc set aggs run over+// past the corpus; the `.hits` payload is discarded for agg kinds.+const AGG_BYPASS_SIZE = 9999;+const TS_FIELD = '@timestamp';++function rangeToSince(range) {+ switch (range) {+ case '1H': return 'now-1h';+ case '24H': return 'now-24h';+ case '7D': return 'now-7d';+ case '30D': return 'now-30d';+ case '90D': return 'now-90d';+ default: return 'now-24h';+ }+}+function bucketSize(range) {+ switch (range) {+ case '1H': return '1m';+ case '24H': return '1h';+ case '7D': return '6h';+ case '30D': return '1d';+ case '90D': return '1d';+ default: return '1h';+ }+}++const METRICS = new Set(['sum', 'avg', 'max', 'min']);++/** WHERE clause from the panel's free-text `q` + optional time range. */+function buildWhere(q, useTime, range) {+ const clauses = [];+ const text = (q || '').trim();+ if (text) {+ // query_string handles both `field:value` and loose text and is+ // supported by the engine's ES-compat parser.+ clauses.push({ query_string: { query: text } });+ }+ if (useTime) {+ clauses.push({ range: { [TS_FIELD]: { gte: rangeToSince(range) } } });+ }+ if (!clauses.length) return { match_all: {} };+ if (clauses.length === 1) return clauses[0];+ return { bool: { must: clauses } };+}++/** Translate a declarative panel → { index, body }. Throws on nonsense. */+export function buildBody(panel, ctx = {}) {+ const q = panel.query || {};+ const kind = q.kind || 'count';+ const range = ctx.range || '24H';+ const rawIndex = (q.index || '').trim();+ const index = !rawIndex || rawIndex === '*' ? '_all' : rawIndex;+ const useTime = q.time === true || kind === 'timeseries';+ const where = buildWhere(q.q, useTime, range);+ const metric = q.metric && METRICS.has(q.metric) ? q.metric : null;++ let body;+ if (kind === 'count') {+ body = { query: where, size: 0, track_total_hits: true };+ } else if (kind === 'metric') {+ if (!q.field) throw new Error('metric needs a field');+ const m = metric || 'avg';+ body = {+ query: where,+ size: AGG_BYPASS_SIZE,+ track_total_hits: true,+ aggs: { m: { [m]: { field: q.field } } },+ };+ } else if (kind === 'timeseries') {+ const inner = metric && q.field ? { m: { [metric]: { field: q.field } } } : undefined;+ body = {+ query: where,+ size: AGG_BYPASS_SIZE,+ track_total_hits: true,+ aggs: {+ tl: {+ date_histogram: { field: q.timeField || TS_FIELD, fixed_interval: q.interval || bucketSize(range) },+ ...(inner ? { aggs: inner } : {}),+ },+ },+ };+ } else if (kind === 'terms') {+ if (!q.field) throw new Error('terms needs a field');+ const inner = metric && q.metricField ? { m: { [metric]: { field: q.metricField } } } : undefined;+ body = {+ query: where,+ size: AGG_BYPASS_SIZE,+ track_total_hits: true,+ aggs: {+ t: {+ terms: { field: q.field, size: q.size || 8 },+ ...(inner ? { aggs: inner } : {}),+ },+ },+ };+ } else if (kind === 'search') {+ body = { query: where, size: q.size || 25, track_total_hits: true };+ } else {+ throw new Error(`unknown query kind '${kind}'`);+ }+ return { index, body, kind, metric };+}++/** Normalise an ES response into the render shape. */+function normalise(resp, built) {+ const total = resp?.hits?.total?.value ?? resp?.hits?.total ?? 0;+ const out = { total, took: resp?.took ?? 0 };+ const a = resp?.aggregations || {};+ if (built.kind === 'count') {+ out.value = total;+ } else if (built.kind === 'metric') {+ out.value = a.m?.value ?? null;+ } else if (built.kind === 'timeseries') {+ out.series = (a.tl?.buckets || []).map((b) => ({+ t: b.key_as_string || b.key,+ count: b.m ? (b.m.value ?? 0) : b.doc_count,+ }));+ } else if (built.kind === 'terms') {+ out.buckets = (a.t?.buckets || []).map((b) => ({+ key: String(b.key),+ count: b.m ? (b.m.value ?? 0) : b.doc_count,+ }));+ } else if (built.kind === 'search') {+ out.hits = (resp?.hits?.hits || []).map((h) => ({+ _id: h._id, _index: h._index, _score: h._score, _source: h._source,+ }));+ }+ return out;+}++async function runQuery(built, signal) {+ const path = `/${encodeURIComponent(built.index)}/_search`;+ const r = await fetch(path, {+ method: 'POST',+ credentials: 'same-origin',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify(built.body),+ signal,+ });+ if (!r.ok) {+ const txt = await r.text().catch(() => '');+ throw new Error(`_search ${built.index} HTTP ${r.status}: ${txt.slice(0, 160)}`);+ }+ const json = await r.json();+ if (json && json.error) {+ throw new Error(typeof json.error === 'string' ? json.error : (json.error.reason || 'search error'));+ }+ return normalise(json, built);+}++// ── cache + subscription ─────────────────────────────────────────────+const cache = new Map(); // key -> normalised result | { __error }+const inflight = new Map(); // key -> Promise+const subs = new Set();+let notifyTimer = null;++function notify() {+ if (notifyTimer) return;+ notifyTimer = setTimeout(() => {+ notifyTimer = null;+ for (const cb of subs) { try { cb(); } catch { /* ignore */ } }+ }, 30);+}++/** Subscribe to "a panel query settled". Returns an unsubscribe fn. */+export function onPanelData(cb) {+ subs.add(cb);+ return () => subs.delete(cb);+}++function keyFor(built) {+ return built.index + '|' + JSON.stringify(built.body);+}++/**+ * Synchronous cache read. Fires the query (once) if not cached and+ * returns `{status:'loading'}`; when it settles, subscribers are+ * notified so the app re-renders into a cache hit.+ *+ * status ∈ 'ready' | 'loading' | 'error' | 'unconfigured'+ */+export function panelResult(panel, ctx = {}) {+ if (!panel || !panel.query || !panel.query.index || !panel.query.kind) {+ return { status: 'unconfigured' };+ }+ let built;+ try { built = buildBody(panel, ctx); }+ catch (e) { return { status: 'unconfigured', error: String(e.message || e) }; }+ const key = keyFor(built);+ if (cache.has(key)) {+ const v = cache.get(key);+ if (v && v.__error) return { status: 'error', error: v.__error };+ return { status: 'ready', data: v };+ }+ if (!inflight.has(key)) {+ const p = runQuery(built)+ .then((res) => { cache.set(key, res); inflight.delete(key); notify(); return res; })+ .catch((err) => { cache.set(key, { __error: String(err.message || err) }); inflight.delete(key); notify(); });+ inflight.set(key, p);+ }+ return { status: 'loading' };+}++/**+ * Promise form for the builder's live preview — always returns a fresh+ * result (also seeds the shared cache so the panel paints instantly once+ * saved).+ */+export async function fetchPanel(panel, ctx = {}) {+ const built = buildBody(panel, ctx);+ const key = keyFor(built);+ const res = await runQuery(built);+ cache.set(key, res);+ return res;+}diff --git a/xerj-ux/src/ux/panel-render.js b/xerj-ux/src/ux/panel-render.jsnew file mode 100644index 000000000..1c52c51af--- /dev/null+++ b/xerj-ux/src/ux/panel-render.js@@ -0,0 +1,165 @@+// ============================================================+// XERJ.ai — Declarative panel renderer+//+// Maps (viz.type, per-panel query result) onto the EXISTING chart+// primitives — the same Series / VBar / Dist / TopN / Table / Num /+// Gauge / Heatmap / AI charts the code dashboards use — but driven by a+// per-panel result from data/panel-query.js instead of a whole-dashboard+// `data` object. This is what gives net-from-scratch user panels real,+// live data under the same visual language.+//+// It NEVER throws: every branch degrades to a typography-first note so a+// half-configured panel reads as "configure me", not "broken".+// ============================================================++import { esc } from './text.js';+import { Num, fmt } from './text.js';+import { Spark, Series, Dist, Heatmap } from './charts.js';+import { VBar, Gauge, Treemap } from './charts-ext.js';+import { TopN, Events } from './layout.js';+import { Table } from './tables.js';+import { chartTypes } from './chart-types.js';++// viz types we can feed from a generic query result.+const DATA_DRIVEN = new Set([+ 'metric', 'gauge', 'spark', 'line', 'bar', 'histogram',+ 'dist', 'topn', 'treemap', 'table', 'events',+]);++const note = (t) => `<div class="panel-empty mono faint">${esc(t)}</div>`;++/** buckets [{key,count}] or timeseries [{t,count}] → [{label,value}]. */+function toItems(d) {+ if (d.buckets && d.buckets.length) return d.buckets.map((b) => ({ label: b.key, value: b.count }));+ if (d.series && d.series.length) return d.series.map((s) => ({ label: String(s.t), value: s.count }));+ return [];+}+function toValues(d) {+ if (d.series && d.series.length) return d.series.map((s) => s.count);+ if (d.buckets && d.buckets.length) return d.buckets.map((b) => b.count);+ return [];+}+function scalar(d) {+ if (d.value != null) return d.value;+ if (d.total != null) return d.total;+ return null;+}++/**+ * Render the INNER html of a declarative panel (app.js wraps it in the+ * <section class="panel"> shell + eyebrow). `result` is the object+ * data/panel-query.js#panelResult returns.+ */+export function renderDeclarativePanel(panel, result) {+ const type = (panel.viz && panel.viz.type) || 'metric';++ if (!panel.query || !panel.query.index || !panel.query.kind) {+ return note('UNCONFIGURED · OPEN EDIT → PICK AN INDEX + QUERY');+ }+ if (!result || result.status === 'loading') {+ return `<div class="panel-empty mono faint">LOADING · ${esc((panel.query.index || '').toUpperCase())}…</div>`;+ }+ if (result.status === 'error') {+ return note('QUERY ERROR · ' + String(result.error || '').slice(0, 90));+ }+ const d = result.data || {};++ try {+ switch (type) {+ case 'metric': {+ const v = scalar(d);+ const spark = d.series && d.series.length ? Spark(toValues(d), { w: 180, h: 30 }) : '';+ return Num({ value: v == null ? '—' : fmt(v), unit: panel.query.metric || 'count', spark, emphasis: true });+ }+ case 'spark': {+ const vals = toValues(d);+ return Num({+ value: vals.length ? fmt(vals[vals.length - 1]) : (scalar(d) == null ? '—' : fmt(scalar(d))),+ unit: panel.query.metric || 'count',+ spark: vals.length ? Spark(vals, { w: 200, h: 36 }) : '',+ emphasis: false,+ });+ }+ case 'gauge': {+ const v = scalar(d) || 0;+ const vals = toValues(d);+ const max = vals.length ? Math.max(v, ...vals) : Math.max(1, v);+ return Gauge({ value: v, min: 0, max: max || 1, unit: panel.query.metric || '', label: esc(panel.query.field || '') });+ }+ case 'line': {+ const vals = toValues(d);+ if (vals.length < 2) return note('NO SERIES · USE A TIMESERIES QUERY');+ return Series(vals, { h: 140, labels: ['START', 'NOW'], unit: panel.query.metric || '' });+ }+ case 'bar':+ case 'histogram': {+ const items = toItems(d);+ if (!items.length) return note('NO DATA');+ return VBar({ items, h: 150, unit: panel.query.metric || '' });+ }+ case 'dist': {+ const items = toItems(d);+ if (!items.length) return note('NO DATA');+ return Dist({ segments: items.map((i) => ({ label: i.label, value: i.value })), width: 1200 });+ }+ case 'topn': {+ const items = toItems(d);+ if (!items.length) return note('NO DATA');+ const total = items.reduce((a, i) => a + i.value, 0);+ return TopN({+ items, total, n: panel.query.size || 8,+ filterField: panel.query.field || '',+ });+ }+ case 'treemap': {+ const items = toItems(d);+ if (!items.length) return note('NO DATA');+ return Treemap({ items });+ }+ case 'table': {+ if (d.hits && d.hits.length) {+ return Table({+ columns: ['INDEX', 'ID', 'SCORE'],+ rows: d.hits.slice(0, 20).map((h) => [h._index, h._id, h._score == null ? '—' : fmt(h._score)]),+ align: ['left', 'left', 'right'],+ });+ }+ const items = toItems(d);+ if (!items.length) return note('NO DATA');+ const total = items.reduce((a, i) => a + i.value, 0) || 1;+ return Table({+ columns: [(panel.query.field || 'KEY').toUpperCase(), 'COUNT', 'PCT'],+ rows: items.map((i) => [i.label, fmt(i.value), ((100 * i.value) / total).toFixed(1) + '%']),+ align: ['left', 'right', 'right'],+ });+ }+ case 'events': {+ const hits = d.hits || [];+ if (!hits.length) return note('NO EVENTS · USE A SEARCH QUERY');+ return Events({+ items: hits.slice(0, 12).map((h) => ({+ at: h._source?.['@timestamp'] || h._id,+ sev: (h._source?.level || 'info'),+ msg: h._source?.message || JSON.stringify(h._source || {}).slice(0, 120),+ })),+ });+ }+ default:+ // Exotic / AI viz types (embedspace, ribbon3d, chord, pcoords,+ // attention, flowband, heatmap, multiples, scatter, stacked,+ // markdown) have no generic query mapping — preview them with+ // their branded demo render so the catalog stays whole.+ if (chartTypes[type] && typeof chartTypes[type].render === 'function') {+ return chartTypes[type].render(d);+ }+ return note('UNSUPPORTED VIZ · ' + esc(type));+ }+ } catch (err) {+ return note('RENDER ERROR · ' + String(err.message || err).slice(0, 80));+ }+}++/** Is this viz type one we can drive from a query (vs. demo-only)? */+export function isDataDriven(type) {+ return DATA_DRIVEN.has(type);+}diff --git a/xerj-ux/src/xerj-console-auth.js b/xerj-ux/src/xerj-console-auth.jsindex bf6a5e0fa..428dc206f 100644--- a/xerj-ux/src/xerj-console-auth.js+++ b/xerj-ux/src/xerj-console-auth.js@@ -7,11 +7,27 @@const API = '/_xerj-console/api/v1';-export async function api(method, path, body) {+/**+ * Low-level fetch wrapper that returns the FULL parsed envelope plus the+ * concurrency etag. Callers that need `meta.etag` (dashboards CRUD →+ * optimistic If-Match) use this; the thin `api()` below is unchanged for+ * every existing call site.+ *+ * method, path — as api()+ * body — JSON-serialised when defined; a 204 (empty) body+ * yields `data: null`+ * extraHeaders — merged over the defaults (e.g. `If-Match`)+ *+ * Returns `{ data, meta, etag, status }`. `etag` prefers the `ETag`+ * response header and falls back to `meta.etag` in the body. On a non-2xx+ * the thrown Error carries `.status` and `.code` so callers can branch on+ * 409 (stale etag) / 404 / 403 without string-matching.+ */+export async function apiRaw(method, path, body, extraHeaders) {const init = {method,credentials: 'same-origin',- headers: { 'accept': 'application/json' },+ headers: { 'accept': 'application/json', ...(extraHeaders || {}) },};if (body !== undefined) {init.headers['content-type'] = 'application/json';@@ -21,12 +37,32 @@ export async function api(method, path, body) {let payload = null;try { payload = await r.json(); } catch {}if (!r.ok) {- const reason = payload && payload.error- ? `${payload.error.type}: ${payload.error.reason}`+ const err = payload && payload.error;+ // The engine emits `{type,reason}`; the shared contract documents+ // `{code,message}`. Accept either so this client survives both.+ const code = err ? (err.type || err.code) : undefined;+ const reason = err+ ? (err.reason || err.message || err.type || err.code || `HTTP ${r.status}`): `HTTP ${r.status}`;- throw new Error(reason);+ const e = new Error(code ? `${code}: ${reason}` : reason);+ e.status = r.status;+ e.code = code;+ e.payload = payload;+ throw e;}- return payload && payload.data !== undefined ? payload.data : payload;+ const bodyEtag = payload && payload.meta && payload.meta.etag;+ const etag = r.headers.get('ETag') || bodyEtag || null;+ return {+ data: payload && payload.data !== undefined ? payload.data : payload,+ meta: (payload && payload.meta) || null,+ etag,+ status: r.status,+ };+}++export async function api(method, path, body, extraHeaders) {+ const { data } = await apiRaw(method, path, body, extraHeaders);+ return data;}// ─── Magic-link redemption ───────────────────────────────────────────────────diff --git a/xerj-ux/src/xerj-console-sync.js b/xerj-ux/src/xerj-console-sync.jsindex eee5ae3a6..1dd8b6426 100644--- a/xerj-ux/src/xerj-console-sync.js+++ b/xerj-ux/src/xerj-console-sync.js@@ -22,13 +22,15 @@ import { api } from './xerj-console-auth.js';// ── Keys we mirror as a single `/prefs` document. ────────────────────────────// `xerj.search` is intentionally excluded — it's the search box's last// query, which is per-tab ephemera, not "user prefs".-// `xerj.dashboards` IS included: it carries the user's dashboard-// metadata (renames, order, hidden flags, user-cloned dashboards),-// which the demo wants to persist across sessions and machines.-// Per-dashboard panel layouts (`xerj.layout.<id>`) and per-dashboard-// filters (`xerj.filters.<id>`) are aggregated into one `layouts` and-// `filters` map respectively, since the count is unbounded and the-// /prefs schema doesn't accept dynamic key prefixes.+// `xerj.dashboards` is NO LONGER mirrored here: user dashboards now live+// in the durable `/dashboards` CRUD surface (see data/dashboard-store.js),+// not the /prefs blob. Mirroring it here caused a double-write AND the+// diff-baseline bug below silently dropped it anyway.+// Per-dashboard panel layouts (`xerj.layout.<id>`) — DEFAULT-dashboard+// column/order/hidden overrides only — and per-dashboard filters+// (`xerj.filters.<id>`) are aggregated into one `layouts` and `filters`+// map respectively, since the count is unbounded and the /prefs schema+// doesn't accept dynamic key prefixes.const PREF_KEYS = ['xerj.theme','xerj.time',@@ -38,7 +40,6 @@ const PREF_KEYS = ['xerj.refresh','xerj.mobile','xerj.edit',- 'xerj.dashboards',];const VIEWS_KEY = 'xerj.views';@@ -60,6 +61,11 @@ async function pullPrefs() {try { server = await api('GET', '/prefs'); }catch (e) { console.warn('[xerj-console-sync] /prefs unreachable:', e.message); return; }if (!server || typeof server !== 'object') return;+ // Capture the raw server doc so startPush() can baseline against what+ // the SERVER actually holds — not against current localStorage — which+ // is what fixes the "locally-present, server-absent key never pushes"+ // diff bug.+ lastServerPrefs = server;// Server doc shape mirrors a flat key/value map. Translate `theme`,// `time`, `cluster`… back into `xerj.theme`, `xerj.time`,// `xerj.cluster`… so the existing SPA reads pick them up.@@ -110,19 +116,41 @@ async function pullViews() {let lastPushedPrefs = null;let lastPushedViewsKey = '';+let lastServerPrefs = null; // raw /prefs doc captured by pullPrefslet pushTimer = null;/** Start the periodic push tick. Idempotent. */export function startPush() {if (pushTimer) return;- // Initial state — taken AFTER pullAll so we don't immediately push- // back what we just pulled.- lastPushedPrefs = snapshotPrefs();+ // Baseline against the SERVER's values only — NOT current localStorage.+ // The old code snapshotted localStorage here, so any key already present+ // locally at boot was treated as "already pushed" and never sent (the+ // reason the user's dashboards/layouts silently failed to persist). By+ // baselining from `lastServerPrefs`, every local key the server is+ // missing diffs dirty and pushes on the first tick.+ lastPushedPrefs = serverBaselinePrefs();lastPushedViewsKey = readViewsRaw();pushTimer = setInterval(() => { pushIfDirty().catch(() => {}); }, 1500);}+// Stable, order-independent JSON so two snapshots with the same content+// but different key insertion order still compare equal (no spurious push).+function sortDeep(v) {+ if (Array.isArray(v)) return v.map(sortDeep);+ if (v && typeof v === 'object') {+ const out = {};+ for (const k of Object.keys(v).sort()) out[k] = sortDeep(v[k]);+ return out;+ }+ return v;+}+function stableStringify(obj) { return JSON.stringify(sortDeep(obj)); }+function snapshotPrefs() {+ return stableStringify(buildPrefsFromLocalStorage());+}++function buildPrefsFromLocalStorage() {const out = {};for (const fullKey of PREF_KEYS) {const short = fullKey.replace(/^xerj\./, '');@@ -145,7 +173,38 @@ function snapshotPrefs() {} catch {}if (Object.keys(layouts).length) out.layouts = layouts;if (Object.keys(filters).length) out.filters = filters;- return JSON.stringify(out);+ return out;+}++// Rebuild the "already-pushed" baseline from the SERVER doc, coercing to+// the same string shape snapshotPrefs uses. Keys the server didn't return+// are OMITTED — so a locally-present-but-server-absent key diffs dirty.+function serverBaselinePrefs() {+ const server = lastServerPrefs || {};+ const out = {};+ for (const fullKey of PREF_KEYS) {+ const short = fullKey.replace(/^xerj\./, '');+ if (server[short] !== undefined && server[short] !== null) {+ out[short] = typeof server[short] === 'string' ? server[short] : JSON.stringify(server[short]);+ }+ }+ const coerceMap = (m) => {+ const o = {};+ for (const [id, raw] of Object.entries(m || {})) {+ if (raw == null) continue;+ o[id] = typeof raw === 'string' ? raw : JSON.stringify(raw);+ }+ return o;+ };+ if (server.layouts && typeof server.layouts === 'object') {+ const l = coerceMap(server.layouts);+ if (Object.keys(l).length) out.layouts = l;+ }+ if (server.filters && typeof server.filters === 'object') {+ const f = coerceMap(server.filters);+ if (Object.keys(f).length) out.filters = f;+ }+ return stableStringify(out);}function readViewsRaw() {