No data in range.
`;
+ const max = Math.max(...data.map((d) => d.val), 1);
+ const total = data.reduce((s, d) => s + d.val, 0);
+ const rowH = 30, padR = 64, nameW = opts.nameW ?? 142;
+ // The name budget is a character count, so it has to track nameW or wide
+ // panels truncate names that had ~100 viewBox units of free gutter beside them.
+ const nameChars = opts.nameChars ?? Math.max(12, Math.floor(nameW / 7.1));
+ const W = 540, H = data.length * rowH + 6;
+ const barX = nameW + 8, barW = W - barX - padR;
+ const valFmt = opts.valFmt || fmtMoney;
+ const titleFmt = opts.titleFmt || (opts.valFmt ? valFmt : fmtMoneyFull);
+ // filterDim: by default use nameKey; pass null to opt-out of filtering
+ const filterDim = "filterDim" in opts ? opts.filterDim : nameKey;
+ const activeVals = filterDim && state.filters[filterDim];
+ const hasFilter = activeVals && activeVals.length > 0;
+ let g = "";
+ data.forEach((d, i) => {
+ const yy = i * rowH + 4;
+ const cy = yy + rowH / 2;
+ const w = Math.max(2, (d.val / max) * barW);
+ const color = opts.color || PALETTE[i % PALETTE.length];
+ const pct = total > 0 ? (d.val / total) : 0;
+ const isSelected = hasFilter && activeVals.includes(d.name);
+ const isDimmed = hasFilter && !isSelected;
+ let cls = "hbar-row";
+ if (filterDim) cls += " hbar-filterable";
+ if (isSelected) cls += " hbar-selected";
+ if (isDimmed) cls += " hbar-dimmed";
+ const isTruncated = d.name.length > nameChars;
+ const dimAttr = filterDim ? ` data-filter-dim="${esc(filterDim)}" data-filter-val="${esc(d.name)}"` : "";
+ const interactiveAttrs = filterDim
+ ? ` tabindex="0" role="button" aria-pressed="${isSelected ? 'true' : 'false'}" aria-label="Filter by ${esc(d.name)}, ${valFmt(d.val)}"`
+ : ` tabindex="0" aria-label="${esc(d.name)}, ${valFmt(d.val)}"`;
+ g += `No data in range.
`;
+ const size = 180, cx = size / 2, cy = size / 2, R = 80, r = 50;
+ let a0 = 0, g = "";
+ if (data.length === 1) {
+ g += `}] — filled area with a stroked top edge.
+ const { valueKey, color = PALETTE[0], valFmt = fmtMoney, tipFmt = valFmt, label = "Trend" } = opts;
+ const W = 760, H = 200;
+ const m = { l: 56, r: 18, t: 16, b: 34 };
+ const iw = W - m.l - m.r, ih = H - m.t - m.b;
+ const data = (rows || []).filter((r) => isFinite(r[valueKey]));
+ if (data.length === 0) return emptyChart(W, H, `${label} — no data`);
+
+ const yMax = niceMax(Math.max(...data.map((r) => r[valueKey]), 1) * 1.02, 4);
+ const n = data.length;
+ const cx = (i) => m.l + ((i + 0.5) / n) * iw;
+ const y = (v) => m.t + ih - (v / yMax) * ih;
+
+ let g = yAxisGrid(m, W, ih, yMax, 4, valFmt);
+ const pts = data.map((r, i) => `${cx(i)},${y(r[valueKey])}`);
+ const base = m.t + ih;
+ g += ` `;
+ g += ` `;
+ data.forEach((r, i) => {
+ g += `${esc(fmtMonth(r.Month))}\n${tipFmt(r[valueKey])} `;
+ });
+ g += xAxisMonthLabels(data, cx, H);
+ return svgEl(W, H, g, label);
+}
+
+function anomalyChart(rows) {
+ // rows: [{Day, Cost, Flag, Baseline}]
+ // Flattened to match lineChart/tokenTrendChart's aspect ratio (was 280) so
+ // this full-width daily chart doesn't read as taller/heavier than the other
+ // trend charts across tabs — daily granularity needs horizontal, not
+ // vertical, resolution.
+ const W = 760, H = 200;
+ const m = { l: 56, r: 18, t: 16, b: 34 };
+ const iw = W - m.l - m.r, ih = H - m.t - m.b;
+ if (!rows || rows.length === 0) return emptyChart(W, H, "Daily anomaly detection — no data");
+ const max = Math.max(...rows.map((r) => Math.max(r.Cost || 0, r.Baseline || 0)), 1) * 1.12;
+ const n = rows.length;
+ const x = (i) => m.l + (n === 1 ? iw / 2 : (i / (n - 1)) * iw);
+ const y = (v) => m.t + ih - (v / max) * ih;
+ let g = "";
+ g += yAxisGrid(m, W, ih, max, 4, fmtMoney);
+ // month x labels
+ let lastMonth = "";
+ rows.forEach((r, i) => {
+ const mo = String(r.Day).slice(0, 7);
+ if (mo !== lastMonth) {
+ lastMonth = mo;
+ g += `${esc(fmtMonth(mo))} `;
+ }
+ });
+ // baseline (dashed) + cost line
+ const base = rows.map((r, i) => `${x(i)},${y(r.Baseline || 0)}`).join(" L");
+ g += ` `;
+ const cost = rows.map((r, i) => `${x(i)},${y(r.Cost || 0)}`).join(" L");
+ g += ` `;
+ // anomaly markers
+ rows.forEach((r, i) => {
+ if (r.Flag !== 0) {
+ const up = r.Flag > 0;
+ g += `${esc(String(r.Day).slice(0, 10))}\n${fmtMoneyFull(r.Cost)} (${up ? "spike" : "drop"})\nbaseline ${fmtMoneyFull(r.Baseline)} `;
+ }
+ });
+ const legend = legendHtml([
+ { label: "Daily effective cost", color: PALETTE[0] },
+ { label: "Expected baseline", color: "var(--muted)" },
+ { label: "Spike", color: PALETTE[4] },
+ { label: "Drop", color: PALETTE[1] },
+ ]);
+ return svgEl(W, H, g, "Daily anomaly detection — cost vs expected baseline") + legend;
+}
+
+function momBars(rows) {
+ // rows: [{Month, EffChangePct}] — diverging bars (cost up = red, down = green)
+ const W = 760, H = 240;
+ const m = { l: 44, r: 14, t: 14, b: 34 };
+ const iw = W - m.l - m.r, ih = H - m.t - m.b;
+ const data = (rows || []).filter((r) => isFinite(r.EffChangePct));
+ if (data.length === 0) return emptyChart(W, H, "Month-over-month effective cost change — no data");
+ const maxAbs = Math.max(...data.map((r) => Math.abs(r.EffChangePct)), 5);
+ const n = data.length;
+ const y0 = m.t + ih / 2; // zero line
+ const cx = (i) => m.l + ((i + 0.5) / n) * iw;
+ const bw = Math.max(5, (iw / n) * 0.6);
+ const yScale = (v) => (v / maxAbs) * (ih / 2);
+ let g = ` `;
+ data.forEach((r, i) => {
+ const v = r.EffChangePct;
+ const h = Math.abs(yScale(v));
+ const yTop = v >= 0 ? y0 - h : y0;
+ const color = v > 0 ? PALETTE[4] : PALETTE[1];
+ g += `${esc(fmtMonth(r.Month))}\n${v > 0 ? "+" : ""}${v.toFixed(1)}% `;
+ });
+ g += xAxisMonthLabels(data, cx, H);
+ return svgEl(W, H, g, "Month-over-month effective cost change");
+}
+
+function forecastChart(rows, splitMonth) {
+ // rows: [{Month, Actual, Forecast}] — actual solid up to splitMonth, forecast dashed onward
+ const W = 760, H = 280;
+ const m = { l: 56, r: 18, t: 16, b: 34 };
+ const iw = W - m.l - m.r, ih = H - m.t - m.b;
+ if (!rows || rows.length === 0) return emptyChart(W, H, "Cost forecast — no data");
+ const max = Math.max(...rows.map((r) => Math.max(r.Actual || 0, r.Forecast || 0)), 1) * 1.12;
+ const n = rows.length;
+ const x = (i) => m.l + (n === 1 ? iw / 2 : (i / (n - 1)) * iw);
+ const y = (v) => m.t + ih - (v / max) * ih;
+ let g = "";
+ g += yAxisGrid(m, W, ih, max, 4, fmtMoney);
+ const splitIdx = rows.findIndex((r) => r.Month >= splitMonth);
+ const sIdx = splitIdx < 0 ? n - 1 : splitIdx;
+ // shaded forecast region
+ g += ` `;
+ // actual line up to split
+ const actualPts = rows.slice(0, sIdx + 1).map((r, i) => `${x(i)},${y(r.Actual || 0)}`);
+ if (actualPts.length > 1) g += ` `;
+ // forecast line from split onward
+ const fcPts = rows.slice(sIdx).map((r, i) => `${x(sIdx + i)},${y(r.Forecast || 0)}`);
+ if (fcPts.length > 1) g += ` `;
+ // x labels
+ g += xAxisMonthLabels(rows, x, H);
+ rows.forEach((r, i) => {
+ const isFc = i >= sIdx;
+ g += `${esc(fmtMonth(r.Month))}\n${isFc ? "forecast " + fmtMoneyFull(r.Forecast) : "actual " + fmtMoneyFull(r.Actual)} `;
+ });
+ const legend = legendHtml([
+ { label: "Actual", color: PALETTE[0] },
+ { label: "Forecast", color: PALETTE[3] },
+ ]);
+ return svgEl(W, H, g, "Cost forecast — actual vs projected") + legend;
+}
+
+/* --------------------------------------------------------------- KPI calc */
+
+function deriveKpis(d) {
+ const s = d.summary?.[0] || {};
+ const list = s.List || 0, eff = s.Effective || 0, contracted = s.Contracted || 0, billed = s.Billed || 0;
+ const savings = list - eff;
+ const esr = list > 0 ? savings / list : 0;
+ const negotiated = list - contracted;
+ const commitment = contracted - eff;
+
+ const tagMap = Object.fromEntries((d.tagged || []).map((r) => [r._t, r.Cost || 0]));
+ const tagged = tagMap.Tagged || 0, untagged = tagMap.Untagged || 0;
+ const tagTotal = tagged + untagged;
+ const untaggedPct = tagTotal > 0 ? untagged / tagTotal : 0;
+
+ const priceMap = Object.fromEntries((d.pricing || []).map((r) => [r.PricingCategory, r.Cost || 0]));
+ const committed = priceMap.Committed || 0;
+ const priceTotal = Object.values(priceMap).reduce((a, b) => a + b, 0);
+ const coverage = priceTotal > 0 ? committed / priceTotal : 0;
+
+ const trend = d.trend || [];
+ let mom = null, lastMonthVal = null, lastMonthLabel = null;
+ if (trend.length >= 1) {
+ const last = trend[trend.length - 1];
+ lastMonthVal = last.Effective || 0;
+ lastMonthLabel = fmtMonth(last.Month);
+ if (trend.length >= 2) {
+ const prev = trend[trend.length - 2].Effective || 0;
+ mom = prev > 0 ? (lastMonthVal - prev) / prev : null;
+ }
+ }
+
+ return {
+ billed, eff, list, contracted, savings, esr, negotiated, commitment,
+ tagged, untagged, untaggedPct, committed, coverage,
+ resources: s.Resources || 0, services: s.Services || 0,
+ subscriptions: s.Subscriptions || 0, regions: s.Regions || 0,
+ mom, lastMonthVal, lastMonthLabel,
+ };
+}
+
+function kpiThreshold(pct, greenMax, amberMax) {
+ if (pct < greenMax) return "threshold-green";
+ if (pct < amberMax) return "threshold-amber";
+ return "threshold-red";
+}
+
+const VALID_TABS = ["overview", "allocation", "rate", "usage", "anomaly", "tokenomics", "foundry", "agents", "ai", "capacity", "monaco"];
+
+// "Tool" tabs are experiments that don't follow the KPI dashboard pipeline
+// (no preset/filter-driven queries, no response caching) — they render their
+// own surface and manage their own state.
+const TOOL_TABS = new Set(["monaco"]);
+
+function switchTab(tabId, opts = {}) {
+ if (!VALID_TABS.includes(tabId) || (!opts.force && state.loading) || tabId === state.tab) return;
+ const leavingMonaco = state.tab === "monaco";
+ state.tab = tabId;
+ [...el("tabs").querySelectorAll("button")].forEach((b) => {
+ const active = b.dataset.tab === tabId;
+ b.classList.toggle("active", active);
+ b.setAttribute("aria-selected", active ? "true" : "false");
+ });
+ revealActiveTab();
+ const isTool = TOOL_TABS.has(tabId);
+ el("preset").hidden = isTool || tabId === "capacity" || tabId === "foundry" || tabId === "agents";
+ el("refresh").hidden = isTool;
+ el("app-footer").hidden = isTool;
+ if (isTool) el("filter-bar").hidden = true;
+ if (leavingMonaco && tabId !== "monaco") disposeMonacoEditor();
+ if (!opts.skipHash) {
+ const url = new URL(location.href);
+ url.hash = tabId === "capacity"
+ ? `tab=capacity&capacity=${state.capacityClass}`
+ : `tab=${tabId}`;
+ history.pushState({ tab: tabId }, "", url);
+ }
+ if (!opts.skipPublish) void publishCanvasState({ tab: tabId });
+ load();
+}
+
+function tabFromHash() {
+ const m = /tab=([a-z]+)/.exec(location.hash);
+ return m && VALID_TABS.includes(m[1]) ? m[1] : null;
+}
+
+function capacityClassFromHash() {
+ const match = /(?:^|&)capacity=([a-z0-9-]+)/.exec(location.hash.replace(/^#/, ""));
+ return match && CAPACITY_TABS.some((item) => item.id === match[1]) ? match[1] : null;
+}
+
+export function nextCapacityTabIndex(currentIndex, key, count = CAPACITY_TABS.length) {
+ if (!Number.isInteger(currentIndex) || currentIndex < 0 || currentIndex >= count || count < 1) return -1;
+ if (key === "Home") return 0;
+ if (key === "End") return count - 1;
+ if (key === "ArrowRight" || key === "ArrowDown") return (currentIndex + 1) % count;
+ if (key === "ArrowLeft" || key === "ArrowUp") return (currentIndex - 1 + count) % count;
+ return currentIndex;
+}
+
+function selectCapacityClass(classId, options = {}) {
+ if (!CAPACITY_TABS.some((item) => item.id === classId) || state.loading) return;
+ const changed = classId !== state.capacityClass;
+ state.capacityClass = classId;
+ if (changed) {
+ state.capacitySelections = {};
+ resetCapacityDetail();
+ }
+ if (!options.skipHash) {
+ history.pushState({ tab: "capacity", capacityClass: classId }, "", `#tab=capacity&capacity=${classId}`);
+ }
+ if (!options.skipPublish) {
+ void publishCanvasState({ capacityClass: classId, capacitySelections: state.capacitySelections });
+ }
+ if (changed || options.force) load();
+}
+
+function resetCapacityDetail() {
+ invalidateCapacitySubscriptions();
+ state.capacityDetailTab = "matrix";
+ state.capacityMatrixPage = 1;
+ state.capacitySubscriptionSearch = "";
+}
+
+function invalidateCapacitySubscriptions() {
+ if (_capacitySubscriptionAbort) _capacitySubscriptionAbort.abort();
+ _capacitySubscriptionAbort = null;
+ _capacitySubscriptionFocusResults = false;
+ state.capacitySubscriptionPage = 1;
+ state.capacitySubscriptionData = null;
+ state.capacitySubscriptionLoading = false;
+ state.capacitySubscriptionError = null;
+}
+
+function capacityMatrixFilter(classId = state.capacityClass, rows = []) {
+ const current = state.capacityMatrixFilters[classId];
+ if (current) return current;
+ const status = classId === "azure-ai" && rows.some((row) => matrixStatusMatches(row, classId, "in-use"))
+ ? "in-use"
+ : "all";
+ const initial = { status, search: "", regions: [], mark: 70 };
+ state.capacityMatrixFilters = { ...state.capacityMatrixFilters, [classId]: initial };
+ return initial;
+}
+
+// Matrix filters run against the payload in memory. Restore focus because each
+// update replaces the rendered controls.
+function setCapacityMatrixFilter(patch) {
+ const current = capacityMatrixFilter();
+ const next = { ...current, ...patch };
+ state.capacityMatrixFilters = { ...state.capacityMatrixFilters, [state.capacityClass]: next };
+ state.capacityMatrixPage = 1;
+ state.capacitySubscriptionPage = 1;
+ state.capacitySubscriptionData = null;
+ const active = document.activeElement;
+ const search = document.querySelector('[data-ui-search="matrix"]');
+ const hadSearchFocus = search && active === search;
+ const caret = hadSearchFocus ? search.selectionStart : null;
+ const lensFocus = !hadSearchFocus && active?.dataset?.uiSegment === "matrix-status" ? next.status : null;
+ const regionFocus = !hadSearchFocus && active?.dataset?.uiToggle === "matrix-region" ? active.dataset.uiValue : null;
+ const markFocus = !hadSearchFocus && active?.dataset?.uiSegment === "matrix-mark" ? String(next.mark) : null;
+ render();
+ if (state.capacityDetailTab === "subscriptions") {
+ queueMicrotask(() => void loadCapacitySubscriptions());
+ }
+ if (hadSearchFocus) {
+ const nextSearch = document.querySelector('[data-ui-search="matrix"]');
+ if (!nextSearch) return;
+ nextSearch.focus();
+ if (caret !== null) nextSearch.setSelectionRange(caret, caret);
+ return;
+ }
+ const selector = lensFocus
+ ? `[data-ui-segment="matrix-status"][data-ui-value="${CSS.escape(lensFocus)}"]`
+ : regionFocus ? `[data-ui-toggle="matrix-region"][data-ui-value="${CSS.escape(regionFocus)}"]`
+ : markFocus ? `[data-ui-segment="matrix-mark"][data-ui-value="${CSS.escape(markFocus)}"]` : null;
+ if (selector) document.querySelector(selector)?.focus();
+}
+
+function applyCapacitySelection(kind, value) {
+ if (!["quota", "metric", "demand"].includes(kind) || state.loading) return;
+ const next = { ...state.capacitySelections };
+ const selectionName = `${kind}Selection`;
+ if (!value) {
+ delete next[selectionName];
+ if (kind === "quota") delete next.metricSelection;
+ } else {
+ const payload = currentPayload();
+ const rows = kind === "demand"
+ ? payload?.demand?.selectors?.items
+ : payload?.selectors?.items;
+ const row = rows?.[Number(value)];
+ const selection = capacitySelectionFromRow(kind, state.capacityClass, row);
+ if (!selection) return;
+ next[selectionName] = selection;
+ if (kind === "quota") {
+ const metric = capacitySelectionFromRow("metric", state.capacityClass, row);
+ if (metric && Object.values(metric).every(Boolean)) next.metricSelection = metric;
+ else delete next.metricSelection;
+ }
+ }
+ state.capacitySelections = next;
+ void publishCanvasState({ capacitySelections: next });
+ load();
+}
+
+function setCapacityDetailTab(tab) {
+ if (!["matrix", "subscriptions"].includes(tab) || tab === state.capacityDetailTab) return;
+ state.capacityDetailTab = tab;
+ render();
+ document.querySelector(`[data-ui-tab="capacity-detail"][data-ui-value="${CSS.escape(tab)}"]`)?.focus();
+ if (tab === "subscriptions" && !state.capacitySubscriptionData) {
+ void loadCapacitySubscriptions();
+ }
+}
+
+function renderPreservingSubscriptionSearchFocus() {
+ const search = document.querySelector("#capacity-subscription-search");
+ const focused = search && document.activeElement === search;
+ const detailTab = document.activeElement?.dataset?.uiTab === "capacity-detail"
+ ? document.activeElement.dataset.uiValue
+ : null;
+ const caret = focused ? search.selectionStart : null;
+ render();
+ if (focused) {
+ const next = document.querySelector("#capacity-subscription-search");
+ next?.focus();
+ if (caret !== null) next?.setSelectionRange(caret, caret);
+ } else if (detailTab) {
+ document.querySelector(`[data-ui-tab="capacity-detail"][data-ui-value="${CSS.escape(detailTab)}"]`)?.focus();
+ } else if (_capacitySubscriptionFocusResults) {
+ const results = document.querySelector("#capacity-subscription-summary, #capacity-detail-panel [role=alert]");
+ if (results) {
+ results.focus();
+ _capacitySubscriptionFocusResults = false;
+ }
+ }
+}
+
+async function loadCapacitySubscriptions() {
+ if (!CAPACITY_MATRIX_CONFIG[state.capacityClass] || state.capacityDetailTab !== "subscriptions") return;
+ if (_capacitySubscriptionAbort) _capacitySubscriptionAbort.abort();
+ const controller = new AbortController();
+ _capacitySubscriptionAbort = controller;
+ state.capacitySubscriptionLoading = true;
+ state.capacitySubscriptionError = null;
+ renderPreservingSubscriptionSearchFocus();
+ try {
+ const filter = capacityMatrixFilter();
+ const response = await fetch("/api/capacity-subscriptions", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ classId: state.capacityClass,
+ status: filter.status,
+ resourceSearch: filter.search,
+ regions: filter.regions,
+ subscriptionSearch: state.capacitySubscriptionSearch,
+ page: state.capacitySubscriptionPage,
+ pageSize: 50,
+ }),
+ signal: controller.signal,
+ });
+ const body = await response.json();
+ if (!response.ok || body.error) throw new Error(body.error || "Could not load subscriptions.");
+ state.capacitySubscriptionData = body;
+ } catch (err) {
+ if (err.name === "AbortError") return;
+ state.capacitySubscriptionError = err.message || "Could not load subscriptions.";
+ } finally {
+ if (_capacitySubscriptionAbort === controller) {
+ state.capacitySubscriptionLoading = false;
+ renderPreservingSubscriptionSearchFocus();
+ }
+ }
+}
+
+function moveCapacityTabFocus(target, key) {
+ const tabs = [...document.querySelectorAll("[data-capacity-class]")];
+ const currentIndex = tabs.indexOf(target);
+ const nextIndex = nextCapacityTabIndex(currentIndex, key, tabs.length);
+ tabs.forEach((tab, index) => {
+ tab.tabIndex = index === nextIndex ? 0 : -1;
+ });
+ tabs[nextIndex]?.focus();
+}
+
+/* --------------------------------------------------------- triage strip */
+
+function buildTriageTile(title, count, cue, tabId) {
+ const isTeaser = count === null;
+ const cls = isTeaser ? "is-teaser" : count === 0 ? "threshold-green" : count <= 4 ? "threshold-amber" : "threshold-red";
+ const badge = isTeaser ? "Not loaded" : count === 0 ? "Good" : count <= 4 ? "Review" : "Urgent";
+ const display = isTeaser ? "—" : count === 0 ? "None" : fmtInt(count);
+ return `
+ ${esc(title)}
+ ${display}
+ ${badge}
+ ${esc(cue)}
+ `;
+}
+
+function renderTriageStrip(d) {
+ // Anomalies: reuse anomaly tab cache when loaded (use same cache key for consistency)
+ const anomPayload = state.cache["anomaly"]?.[cacheKey()];
+ const daily = anomPayload?.data?.daily || [];
+ const anomCount = anomPayload ? daily.filter((r) => r.Flag !== 0).length : null;
+ const anomCue = anomCount === null ? "Visit Anomalies & forecast tab to load"
+ : anomCount === 0 ? "No anomalies detected"
+ : "Review flagged cost days";
+
+ // Overspend: months in trend where effective cost rose >20% vs prior month
+ const trend = d.trend || [];
+ let overspendCount = 0;
+ for (let i = 1; i < trend.length; i++) {
+ const prev = trend[i - 1].Effective || 0;
+ const curr = trend[i].Effective || 0;
+ if (prev > 0 && curr > prev * 1.20) overspendCount++;
+ }
+ const overspendCue = overspendCount === 0
+ ? "Spend within expected range"
+ : `${overspendCount} month${overspendCount === 1 ? "" : "s"} with >20% spike`;
+
+ // Savings opportunities: underutilized commitments from rate tab cache when loaded
+ const ratePayload = state.cache["rate"]?.[cacheKey()];
+ const byCommitment = ratePayload?.data?.byCommitment || [];
+ const savingsCount = ratePayload ? byCommitment.filter((r) => (r.Unused || 0) > 0).length : null;
+ const savingsCue = savingsCount === null ? "Visit Rate optimization tab to load"
+ : savingsCount === 0 ? "Commitments fully utilized"
+ : "Underutilized commitments found";
+
+ return `
+ ${buildTriageTile("Anomalies", anomCount, anomCue, "anomaly")}
+ ${buildTriageTile("Overspend", overspendCount, overspendCue, "usage")}
+ ${buildTriageTile("Savings Opportunities", savingsCount, savingsCue, "rate")}
+
`;
+}
+
+function isPartialMonth() {
+ const now = new Date();
+ return now.getDate() < new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
+}
+
+const KPI_TIPS = {
+ "Untagged cost": "% of spend on resources missing tags. Target: <10% · Review: <25% · Urgent: ≥25%. Tagging enables accurate showback and chargeback.",
+ "Commitment waste": "% of RI/savings-plan spend on unused capacity. Target: <10% · Review: <20% · Urgent: ≥20%. Idle commitments erode net savings.",
+ "Effective savings rate": "Negotiated + commitment savings as % of list price. Higher = better. Enterprise customers typically target ≥15–20%.",
+ "Commitment coverage": "Compute spend covered by RIs or savings plans. Target: ≥60% for steady workloads. Higher coverage → lower effective rate.",
+ "Compute coverage": "On-demand core-hours offset by commitments. Target: ≥60%. Tracks whether savings plan scope is sufficient.",
+ "Anomaly days": "Days where daily cost deviated significantly from the expected baseline (STL decomposition). Review flagged dates for unexpected spend.",
+ "Hourly cost / core": "Compute effective cost per core-hour actually consumed this period — the real, paid-for unit rate.",
+ "Effective cost / core": "Compute effective cost per core-hour, including unused commitment waste spread across usage — the fully-loaded unit cost if that waste is charged back.",
+ "Unpredicted variance": "Net effective cost variance between actual spend and the anomaly baseline on flagged days (FinOps KPI: Total Unpredicted Variance of Spend). Positive = spent more than expected.",
+ "Anomaly detection rate": "Effective cost on anomaly-flagged days as % of total effective spend (FinOps KPI: Anomaly Cost %). The day-count ratio shown alongside is a separate reference stat, not the derivation of this percentage.",
+ "Last month change": "Month-over-month % change in effective cost vs. the prior month. Watch for spikes or drops that don't match expected seasonality.",
+ "Forecast next month": "Projected effective cost for next month using time-series decomposition (FinOps KPI: Cost Forecasting). Based on historical trend + seasonality, not a guarantee.",
+ "Visibility delay": "Median (P50) delay between when cost was incurred and when it appeared in the FinOps hub (FinOps KPI: Cost Visibility Delay). On local/demo data without a live Cost Management connector, a large delay is expected.",
+ "Tag policy compliance": "% of effective cost on resources with all required tag keys present and non-empty (FinOps KPI: Tagging Policy Compliance).",
+ "Subscriptions": "Distinct subscriptions (billing accounts) with cost activity in the selected period.",
+ "Allocated cost": "Effective cost with ownership attribution — a cost center, owner, or ownership tag — the complement of Unallocated cost.",
+};
+
+function kpiCard(label, value, meta, accent, thresholdClass, tier) {
+ // Hierarchy tier is now explicitly assigned by each tab's render*() call
+ // site (via the 6th `tier` argument) rather than an incomplete global
+ // label allow-list, so every tab consciously designates its own hero
+ // metric. `accent` is kept for call-site compatibility but unused.
+ const hierarchyClass = tier === "primary" ? "kpi--primary" : tier === "reference" ? "kpi--reference" : "";
+
+ // Combine threshold and hierarchy classes
+ const classArray = [thresholdClass, hierarchyClass].filter(Boolean);
+ const cls = classArray.length > 0 ? ` ${classArray.join(" ")}` : "";
+
+ const tip = KPI_TIPS[label];
+ const tipHtml = tip ? ` ? ` : "";
+
+ return `
+
${esc(label)}${tipHtml}
+
${value}
+
${meta}
+
`;
+}
+
+/* ---------------------------------------------------------------- render */
+
+function panelHtml(id, span, title, sub, body) {
+ const subHtml = sub ? `${sub}
` : "";
+ return ``;
+}
+
+function openKqlDialog(panelId) {
+ _kqlPanelId = panelId;
+ // Prefer the query the server actually executed for this panel; fall back to
+ // the static map for tabs that don't publish their queries yet.
+ const served = currentPayload()?.kql?.[PANEL_QUERY[panelId]];
+ el("kql-text").value = served || PANEL_KQL[panelId] || "";
+ el("kql-error").textContent = "";
+ const prev = document.getElementById("kql-result");
+ if (prev) prev.remove();
+ el("kql-dialog").showModal();
+}
+
+async function executeKql() {
+ const kql = el("kql-text").value.trim();
+ const errEl = el("kql-error");
+ const runBtn = el("kql-run");
+ if (!kql) return;
+ errEl.textContent = "";
+ const prev = document.getElementById("kql-result");
+ if (prev) prev.remove();
+ runBtn.disabled = true;
+ runBtn.textContent = "Running…";
+ try {
+ const res = await fetch("/api/kql", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ kql }),
+ });
+ if (!res.ok) { errEl.textContent = `Server error ${res.status}`; return; }
+ const data = await res.json();
+ if (data.error) {
+ errEl.textContent = data.error;
+ } else {
+ const rows = data.rows || [];
+ if (!rows.length) {
+ errEl.textContent = "Query returned no rows.";
+ } else {
+ el("kql-dialog").close();
+ renderKqlResultInPanel(_kqlPanelId, rows);
+ }
+ }
+ } catch (err) {
+ errEl.textContent = "Request failed: " + err.message;
+ } finally {
+ runBtn.disabled = false;
+ runBtn.textContent = "Run";
+ }
+}
+
+function renderKqlResultInPanel(panelId, rows) {
+ const panelBody = document.querySelector(`[data-panel-id="${panelId}"] .panel-body`);
+ if (!panelBody) return;
+ const cols = Object.keys(rows[0]);
+ const head = cols.map((c) => `${esc(c)} `).join("");
+ const body = rows.slice(0, 200).map((r) =>
+ `${cols.map((c) => `${esc(String(r[c] ?? ""))} `).join("")} `
+ ).join("");
+ panelBody.innerHTML = `${rows.length} rows${rows.length > 200 ? " (showing first 200)" : ""}
`;
+}
+
+function renderOverview(p) {
+ const content = el("content");
+ if (!p) return;
+ if (p.error) return renderError(p);
+ if (p.empty) {
+ content.innerHTML = `No cost data The Hub database has no rows yet. Ingest cost data, then refresh.
`;
+ return;
+ }
+ const k = deriveKpis(p.data);
+
+ const momClass = k.mom == null ? "" : k.mom > 0 ? "neg" : "pos"; // cost up = bad
+ const momTxt = k.mom == null ? "—" : `${k.mom > 0 ? "▲" : "▼"} ${fmtPct(Math.abs(k.mom))}`;
+
+ const partialHtml = isPartialMonth() ? ` · partial month ` : "";
+ const kpis = [
+ // primary KPIs first
+ kpiCard("Untagged cost", fmtPct(k.untaggedPct),
+ `${fmtMoney(k.untagged)} on untagged resources`, PALETTE[3],
+ kpiThreshold(k.untaggedPct, 0.10, 0.25), "primary"),
+ // supporting KPIs
+ kpiCard("Effective cost", fmtMoney(k.eff), `Billed ${fmtMoney(k.billed)}`, PALETTE[0]),
+ kpiCard("Total savings", fmtMoney(k.savings),
+ `${fmtPct(k.esr)} effective savings rate`, PALETTE[1]),
+ // reference KPIs
+ kpiCard("Commitment coverage", fmtPct(k.coverage),
+ `${fmtMoney(k.committed)} of compute spend`, PALETTE[5], undefined, "reference"),
+ // supporting KPIs
+ kpiCard("Tracked resources", fmtInt(k.resources),
+ `${fmtInt(k.services)} services · ${fmtInt(k.subscriptions)} subs · ${fmtInt(k.regions)} regions`, PALETTE[2]),
+ kpiCard("Latest month", k.lastMonthVal == null ? "—" : fmtMoney(k.lastMonthVal),
+ k.mom == null ? (k.lastMonthLabel ? `${esc(k.lastMonthLabel)}${partialHtml}` : (isPartialMonth() ? `partial month ` : "")) : `${momTxt} vs prior · ${esc(k.lastMonthLabel)}${partialHtml}`, PALETTE[4]),
+ ].join("");
+
+ const d = p.data;
+ const html = `
+ ${renderTriageStrip(d)}
+ ${kpis}
+
+
Understand usage & cost FinOps Framework
+
+ ${panelHtml("overview-trend", 12, "Monthly cost trend", "Billed vs effective cost by month — executive run-rate view.", lineChart(d.trend))}
+ ${panelHtml("overview-top-services", 6, "Top services by cost", "Effective cost by Azure service.", hbar(d.topServices, "ServiceName", "Cost", { label: "Top services by cost" }))}
+ ${panelHtml("overview-service-category", 6, "Cost by service category", "Where spend concentrates across categories.", hbar(d.serviceCategory, "ServiceCategory", "Cost", { label: "Cost by service category" }))}
+
+
+
Optimize usage & cost FinOps Framework
+
+ ${panelHtml("overview-top-rgs", 6, "Top resource groups", "Largest cost owners for allocation & accountability.", hbar(d.topResourceGroups, "x_ResourceGroupName", "Cost", { label: "Top resource groups" }))}
+ ${panelHtml("overview-top-regions", 6, "Cost by region", "Regional spend for placement & sustainability review.", hbar(d.topRegions, "RegionId", "Cost", { label: "Cost by region" }))}
+
+
+
Quantify business value FinOps Framework
+
+ ${panelHtml("overview-rate-coverage", 4, "Rate coverage", "Committed vs on-demand (standard) effective cost.", donut([
+ { label: "Committed", value: k.committed, color: PALETTE[1] },
+ { label: "On-demand", value: Math.max(0, k.eff - k.committed), color: PALETTE[0] },
+ ], { centerBig: fmtPct(k.coverage), centerSmall: "covered", label: "Rate coverage" }))}
+ ${panelHtml("overview-savings", 4, "Savings breakdown", "List → effective, by discount type.", savingsTable(k))}
+ ${panelHtml("overview-cost-allocation", 4, "Cost allocation", "Tagged vs untagged effective cost.", donut([
+ { label: "Tagged", value: k.tagged, color: PALETTE[1] },
+ { label: "Untagged", value: k.untagged, color: UNKNOWN_COLOR, isUnknown: true },
+ ], { centerBig: fmtPct(1 - k.untaggedPct), centerSmall: "tagged", label: "Cost allocation" }))}
+
+ `;
+ content.innerHTML = html;
+}
+
+function savingsTable(k) {
+ return costBreakdownTable([
+ { label: "List cost", val: k.list, accent: "var(--muted)" },
+ { label: "Negotiated savings", val: k.negotiated, accent: PALETTE[8] },
+ { label: "Commitment savings", val: k.commitment, accent: PALETTE[1] },
+ { label: "Effective cost", val: k.eff, accent: PALETTE[0] },
+ ], "Effective savings rate", fmtPct(k.esr));
+}
+
+/* ----------------------------------------------------- tokenomics render */
+
+function deriveTokenKpis(d) {
+ const s = d.summary?.[0] || {};
+ const tokens = s.Tokens || 0, eff = s.Effective || 0;
+ const cloud = d.totalCloud?.[0]?.Effective || 0;
+ const dir = Object.fromEntries((d.direction || []).map((r) => [r.Direction, r]));
+ const inTok = dir["Input"]?.Tokens || 0;
+ const cachedTok = dir["Cached input"]?.Tokens || 0;
+ const cachedShare = inTok + cachedTok > 0 ? cachedTok / (inTok + cachedTok) : 0;
+ return {
+ tokens, eff, cloud,
+ blendedPer1K: tokens > 0 ? eff / tokens * 1000 : 0,
+ cachedShare,
+ aiShare: cloud > 0 ? eff / cloud : 0,
+ models: s.Models || 0,
+ resources: s.Resources || 0,
+ };
+}
+
+function renderTokenomics(p) {
+ const content = el("content");
+ if (!p) return;
+ if (p.error) return renderError(p);
+ if (p.empty) {
+ content.innerHTML = `No AI token data
+
No Azure OpenAI token meters were found in the Hub database for this period.
+
Tokenomics tracks meters where x_SkuMeterSubcategory contains “OpenAI” and the SKU is billed in tokens. Ingest Azure OpenAI usage, then refresh.
`;
+ return;
+ }
+ const d = p.data;
+ const k = deriveTokenKpis(d);
+
+ const dirColors = { "Input": PALETTE[0], "Cached input": PALETTE[1], "Output": PALETTE[3], "Other": PALETTE[6] };
+ const dirSlices = (d.direction || []).map((r) => ({
+ label: r.Direction, value: r.Tokens || 0, cost: r.Cost || 0, color: dirColors[r.Direction] || PALETTE[6],
+ }));
+
+ const kpis = [
+ // reference KPIs first (no primaries in this tab)
+ kpiCard("Total tokens", fmtTokens(k.tokens), `across ${fmtInt(k.models)} model families`, PALETTE[0], undefined, "reference"),
+ // supporting KPIs
+ kpiCard("AI token cost", fmtMoney(k.eff), `${fmtPct(k.aiShare, 2)} of all cloud cost`, PALETTE[2], undefined, "primary"),
+ kpiCard("Blended rate", fmtPerM(k.blendedPer1K), `per 1M tokens (effective)`, PALETTE[5]),
+ kpiCard("Cached input", fmtPct(k.cachedShare),
+ `${fmtPct(k.cachedShare)} of input tokens cached`, PALETTE[1]),
+ kpiCard("AI resources", fmtInt(k.resources), `Azure OpenAI deployments`, PALETTE[4]),
+ kpiCard("Models in use", fmtInt(k.models), `distinct model families`, PALETTE[8]),
+ ].join("");
+
+ content.innerHTML = `
+ ${kpis}
+
+
AI token economics Token Consumption Metrics KPI
+
+ ${panelHtml("token-trend", 12, "Token volume & AI cost trend", "Monthly token consumption (bars) and effective AI cost (line).", tokenTrendChart(d.trend))}
+ ${panelHtml("token-by-model", 6, "AI cost by model", "Effective cost per model family.",
+ hbar((d.models || []).map((m) => ({ Model: m.Model, Cost: m.Cost })), "Model", "Cost", { label: "AI cost by model" }))}
+ ${panelHtml("token-direction", 6, "Token direction mix", "Input vs cached input vs output — by token volume.",
+ donut(dirSlices, {
+ centerBig: fmtTokens(k.tokens), centerSmall: "tokens",
+ valueFmt: (s) => `${fmtTokens(s.value)} · ${fmtMoney(s.cost)}`,
+ label: "Token direction mix",
+ }))}
+
+
+
Model efficiency Rate & usage optimization
+
+ ${panelHtml("token-model-table", 12, "Cost per 1M tokens by model", "Unit economics for model selection — sorted by effective cost.", tokenModelTable(d.models, k.eff))}
+
+
+
AI cost allocation Showback & chargeback
+
+ ${panelHtml("token-by-app", 12, "AI cost by application", "Azure OpenAI effective cost and token volume by application, team, environment, and cost center.", aiByAppTable(d.byApplication))}
+
+ `;
+}
+
+function tokenModelTable(models, totalCost) {
+ const rows = (models || []).filter((m) => (m.Tokens || 0) > 0);
+ if (rows.length === 0) return `No token data in range.
`;
+ const maxPer1K = Math.max(...rows.map((m) => m.CostPer1K || 0), 1e-9);
+ const body = rows.map((m, i) => {
+ const color = PALETTE[i % PALETTE.length];
+ const share = totalCost > 0 ? (m.Cost || 0) / totalCost : 0;
+ const barW = Math.max(2, ((m.CostPer1K || 0) / maxPer1K) * 90);
+ return `
+ ${swatchHtml(color)}${esc(m.Model)}
+ ${fmtTokens(m.Tokens)}
+ ${fmtMoneyFull(m.Cost)}
+ ${fmtPerM(m.CostPer1K)}
+ ${fmtPct(share)}
+ `;
+ }).join("");
+ return `
+ Model Tokens Effective cost $ / 1M tokens % of AI cost
+ ${body}
+
`;
+}
+
+function aiByAppTable(rows) {
+ const data = (rows || []).filter((r) => (r.EffectiveCost || 0) > 0);
+ if (data.length === 0) return `No tagged AI cost data. Tag Azure OpenAI resources with application, team, or environment tags.
`;
+ const totalCost = data.reduce((a, r) => a + (r.EffectiveCost || 0), 0);
+ const untaggedCount = data.filter((r) => !r.Application).length;
+ const callout = untaggedCount === data.length
+ ? `⚠ 100% of AI cost (${fmtMoney(totalCost)}) is untagged — no application-level chargeback is currently possible. Tag Azure OpenAI resources with an application tag to enable it.
`
+ : "";
+ return callout + `
+ Application Team Environment Cost center Tokens Effective cost $/1M tokens % of AI
+ ${data.map((r, i) => {
+ const share = totalCost > 0 ? (r.EffectiveCost || 0) / totalCost : 0;
+ const isUnknown = !r.Application;
+ const color = PALETTE[i % PALETTE.length];
+ return `
+ ${swatchHtml(color, isUnknown)}${esc(r.Application || "(untagged)")}
+ ${esc(r.Team || "—")}
+ ${esc(r.Environment || "—")}
+ ${esc(r.CostCenter || "—")}
+ ${fmtTokens(r.TokenCount)}
+ ${fmtMoney(r.EffectiveCost)}
+ ${fmtPerM(r.CostPer1KTokens)}
+ ${fmtPct(share)}
+ `;
+ }).join("")}
+
`;
+}
+
+function foundryAccountLabel(account) {
+ return `${account.name} · ${account.location} · ${account.resourceGroup}`;
+}
+
+function foundryPriceMetadata(payload) {
+ const summary = payload.data.summary;
+ const billingScopeNote = "Prices can't be estimated for AI resources outside this Hub's billing scope.";
+ if (payload.pricing?.status === "unavailable") {
+ return `Hub Prices() unavailable. Operational metrics are unaffected; no cost estimate was calculated. ${billingScopeNote}`;
+ }
+ if (payload.pricing?.status === "partial") {
+ return `Partial Hub Prices() coverage: ${fmtPct(summary.PriceCoverage)} of estimated tokens. ${billingScopeNote}`;
+ }
+ if (payload.pricing?.status === "empty") {
+ return `No current or previous-month Hub token rates matched. Operational metrics are unaffected. ${billingScopeNote}`;
+ }
+ if (summary.PreviousMonthEstimatedTokens > 0) {
+ return `Provisional Hub estimate: ${fmtPct(summary.PriceCoverage)} coverage; ${fmtPct(summary.PreviousMonthPriceCoverage)} uses the previous month's price sheet. ${billingScopeNote}`;
+ }
+ return `Hub Prices() estimate: ${fmtPct(summary.PriceCoverage)} token coverage. Costs() remains authoritative for billed and effective cost. ${billingScopeNote}`;
+}
+
+function foundryTiles(tiles, unit, currency) {
+ const data = tiles || [];
+ if (!data.length) return `—
`;
+ return `${data.map((tile, index) => {
+ const tileValue = tile.EstimatedCost ?? tile.Value;
+ const tileLabel = tile.Model ?? tile.Name;
+ const value = unit === "currency"
+ ? fmtCurrency(tileValue, tile.Currency || currency)
+ : foundryValue(tileValue, unit);
+ const hasCostCompanion = unit !== "currency" && "EstimatedCost" in tile;
+ const companion = tile.EstimatedCost == null
+ ? "Estimated cost —"
+ : `Estimated cost ${fmtCurrency(tile.EstimatedCost, tile.Currency || currency)}`;
+ const coverage = tile.PriceCoverage != null && tile.PriceCoverage < 1
+ ? ` · ${fmtPct(tile.PriceCoverage)} priced`
+ : "";
+ return `
+ ${esc(tileLabel)}
+ ${esc(value)}
+ ${hasCostCompanion ? `${esc(companion + coverage)} ` : ""}
+
`;
+ }).join("")}
`;
+}
+
+function foundryPanel(panel, body, footer = "") {
+ const grid = panel.gridPos;
+ const style = `grid-column:${grid.x + 1} / span ${grid.w};grid-row:${grid.y + 1} / span ${grid.h}`;
+ return `
+
+ ${body}
+ ${footer ? `${esc(footer)}
` : ""}
+ `;
+}
+
+function foundryChartOptions(panel) {
+ const calculations = {
+ 2: ["Sum", "Mean", "Max"],
+ 16: ["Sum", "Max"],
+ 7: ["Mean", "Max", "Last"],
+ 17: ["Mean", "Max", "Last"],
+ 4: ["Sum", "Mean", "Max"],
+ 5: ["Sum", "Mean", "Max"],
+ 8: ["Sum", "Mean", "Max"],
+ 14: ["Mean", "Max", "Last"],
+ };
+ return {
+ title: panel.title,
+ unit: panel.unit,
+ style: panel.style === "bars" ? "bars" : "lines",
+ fillOpacity: (Number(panel.fillOpacity) || 0) / 100,
+ calculations: calculations[panel.id] || ["Mean", "Max", "Last"],
+ companion: [4, 5, 8].includes(panel.id) ? { label: "Estimated cost" } : null,
+ };
+}
+
+function agentAuthoritativeCostSummary(costs = []) {
+ if (!costs.length) return "—";
+ return costs.map((cost) => fmtCurrency(cost.BilledCost, cost.BillingCurrency)).join(" · ");
+}
+
+function agentTimestamp(value) {
+ const date = new Date(value || "");
+ if (!Number.isFinite(date.getTime())) return "—";
+ return `${esc(fmtRelativeTime(date))} `;
+}
+
+function foundryScopeToolbar(payload, label) {
+ const accountOptions = [
+ `Entire estate · ${fmtInt(payload.accounts.length)} Foundry resources `,
+ ...payload.accounts.map((account) =>
+ `${esc(foundryAccountLabel(account))} `
+ ),
+ ].join("");
+ const presetButtons = [
+ ["24h", "24H"],
+ ["7d", "7D"],
+ ["30d", "30D"],
+ ["93d", "93D"],
+ ].map(([id, text]) =>
+ `${text} `
+ ).join("");
+ return ``;
+}
+
+function agentTrendSeries(rows, valueField, nameField = "AgentName") {
+ const series = new Map();
+ for (const row of rows || []) {
+ const bucket = row.BucketStart;
+ if (!bucket) continue;
+ const name = String(row[nameField] || "All agents");
+ const current = series.get(name) || new Map();
+ current.set(bucket, (current.get(bucket) || 0) + Number(row[valueField] || 0));
+ series.set(name, current);
+ }
+ return [...series].map(([Name, points]) => ({
+ Name,
+ Points: [...points].map(([Bucket, Value]) => ({ Bucket, Value }))
+ .sort((left, right) => left.Bucket.localeCompare(right.Bucket)),
+ }));
+}
+
+function agentTokenTrendSeries(rows) {
+ const components = [
+ ["Uncached input tokens", "UncachedInputTokens", "UncachedInputCost"],
+ ["Cached input tokens", "CachedInputTokens", "CachedInputCost"],
+ ["Output tokens", "OutputTokens", "OutputCost"],
+ ];
+ return components.map(([Name, tokenField, costField]) => {
+ const buckets = new Map();
+ for (const row of rows || []) {
+ const current = buckets.get(row.BucketStart) || {
+ Value: 0,
+ Cost: 0,
+ HasCost: false,
+ Currencies: new Set(),
+ };
+ const tokens = tokenField === "UncachedInputTokens"
+ ? Math.max(0, Number(row.InputTokens || 0) - Number(row.CachedInputTokens || 0))
+ : Number(row[tokenField] || 0);
+ current.Value += tokens;
+ if (row[costField] != null) {
+ current.Cost += Number(row[costField]);
+ current.HasCost = true;
+ if (row.Currency) current.Currencies.add(row.Currency);
+ }
+ buckets.set(row.BucketStart, current);
+ }
+ return {
+ Name,
+ Points: [...buckets].map(([Bucket, bucket]) => ({
+ Bucket,
+ Value: bucket.Value,
+ Cost: bucket.HasCost && bucket.Currencies.size <= 1 ? bucket.Cost : null,
+ Currency: bucket.Currencies.size === 1 ? [...bucket.Currencies][0] : null,
+ }))
+ .sort((left, right) => left.Bucket.localeCompare(right.Bucket)),
+ };
+ });
+}
+
+function agentDailyCostSeries(rows) {
+ return agentTrendSeries((rows || []).map((row) => ({
+ ...row,
+ BucketStart: row.BucketStart ? `${String(row.BucketStart).slice(0, 10)}T00:00:00Z` : null,
+ })), "EstimatedCost");
+}
+
+function agentPanel(title, body, wide = false, note = "") {
+ return `
+
+ ${body}
+ ${note ? `${esc(note)}
` : ""}
+ `;
+}
+
+function agentEstimatedComponent(row, field) {
+ return row?.[field] == null ? "—" : fmtCurrency(row[field], row.Currency);
+}
+
+function renderFoundry(payload) {
+ const content = el("content");
+ if (!payload) return;
+ if (payload.error) return renderError(payload);
+ if (payload.empty) {
+ content.innerHTML = `No AI Foundry resources Azure Resource Graph found no accessible Cognitive Services accounts in the configured tenant.
`;
+ return;
+ }
+
+ const d = payload.data;
+ const currency = d.summary?.Currency;
+
+ const panelData = {
+ 13: d.stats.costs,
+ 11: d.stats.inputTokens,
+ 12: d.stats.outputTokens,
+ 2: d.charts.modelRequests,
+ 16: d.charts.requestErrors,
+ 7: d.charts.latency,
+ 17: d.charts.tokensPerSecond,
+ 4: d.charts.inputTokens,
+ 5: d.charts.outputTokens,
+ 8: d.charts.totalTokens,
+ 14: d.charts.cacheMatchRate,
+ };
+ const panels = payload.panels.map((panel) => {
+ if (panel.id === 13) {
+ return foundryPanel(
+ panel,
+ foundryTiles(panelData[panel.id], panel.unit, currency),
+ foundryPriceMetadata(payload)
+ );
+ }
+ if (panel.id === 11 || panel.id === 12) {
+ return foundryPanel(panel, foundryTiles(panelData[panel.id], panel.unit, currency));
+ }
+ return foundryPanel(
+ panel,
+ foundryMetricChart(panelData[panel.id], foundryChartOptions(panel))
+ );
+ }).join("");
+
+ content.innerHTML = `
+ ${foundryScopeToolbar(payload, "AI Foundry metric scope")}
+ ${panels}
+ `;
+}
+
+function renderAgents(payload) {
+ const content = el("content");
+ if (!payload) return;
+ if (payload.error) return renderError(payload);
+ const summary = payload.summary || {};
+ const estimate = summary.EstimatedCost == null
+ ? "—"
+ : fmtCurrency(summary.EstimatedCost, summary.Currency);
+ const agentRows = payload.agents || [];
+ const tokenRows = payload.charts?.tokens || [];
+ const costRows = payload.charts?.estimatedCost || [];
+ const latencyRows = payload.charts?.latency || [];
+ const operationsRows = payload.charts?.throughput || [];
+ const successRows = payload.charts?.success || [];
+ const costSeries = agentDailyCostSeries(costRows);
+ const resultSeries = [
+ ...agentTrendSeries(successRows, "Successes").map((row) => ({ ...row, Name: `${row.Name} · success` })),
+ ...agentTrendSeries(successRows, "Errors").map((row) => ({ ...row, Name: `${row.Name} · errors` })),
+ ];
+ const kpis = [
+ [estimate, "Estimated run cost", `Prices() · ${fmtPct(summary.PriceCoverage || 0)} coverage`],
+ [agentAuthoritativeCostSummary(summary.AuthoritativeCosts), "Authoritative billed cost", "Exact Costs() matches only"],
+ [fmtInt(summary.Operations || 0), "Agent operations", `${fmtInt(summary.AgentCount || 0)} discovered agents`],
+ [fmtPct(summary.SuccessRate || 0), "Success rate", `${fmtInt(summary.Errors || 0)} errors`],
+ [foundryValue(summary.AverageLatencyMs || 0, "ms"), "Average run latency", "Invoke-agent spans"],
+ [fmtInt(Math.max(0, Number(summary.InputTokens || 0) - Number(summary.CachedInputTokens || 0))),
+ "Uncached input tokens", `Estimated ${agentEstimatedComponent(summary, "UncachedInputCost")}`],
+ [fmtInt(summary.CachedInputTokens || 0), "Cached input tokens",
+ `Estimated ${agentEstimatedComponent(summary, "CachedInputCost")} · ${fmtPct(summary.CacheRate || 0)} of input`],
+ [fmtInt(summary.OutputTokens || 0), "Output tokens",
+ `Estimated ${agentEstimatedComponent(summary, "OutputCost")}`],
+ ].map(([value, label, meta]) => `${esc(value)} ${esc(label)} ${esc(meta)}
`).join("");
+
+ const agentTable = agentRows.length
+ ? ``
+ : `No Foundry agent telemetry No Foundry agent identity was found in the selected scope and time range.
`;
+
+ const modelTable = (payload.models || []).length
+ ? ``
+ : `No chat model usage Chat spans did not report model and token fields.
`;
+
+ const finishTable = (payload.finishReasons || []).length
+ ? `Finish reason Agent Chats
+ ${payload.finishReasons.slice(0, 12).map((row) => `${nameCell(row.FinishReason, 32)}
+ ${nameCell(row.AgentName || row.AgentKey, 28)} ${fmtInt(row.Count)} `).join("")}
`
+ : `No finish reasons This field wasn't reported by chat spans.
`;
+ const toolTable = (payload.tools || []).length
+ ? `Tool Agent Calls Errors Average latency
+ ${payload.tools.slice(0, 15).map((row) => `${nameCell(row.ToolName, 30)}
+ ${nameCell(row.AgentName || row.AgentKey, 26)} ${fmtInt(row.Calls)}
+ ${fmtInt(row.Errors)} ${foundryValue(row.AverageLatencyMs, "ms")} `).join("")}
`
+ : `No tool spans No execute_tool operations were reported.
`;
+
+ const recentRuns = (payload.recentRuns || []).length
+ ? ``
+ : `No recent runs No invoke_agent operations were reported.
`;
+
+ const recentErrors = (payload.recentErrors || []).length
+ ? ``
+ : `No recent errors No failed invoke_agent operations were found.
`;
+
+ content.innerHTML = `
+ ${foundryScopeToolbar(payload, "Agent telemetry scope")}
+
+ Estimated run cost uses trace token usage and Hub Prices() rates. Authoritative billed cost is shown separately only for exact Costs() resource matches.
+
+ ${agentPanel("Token consumption over time", foundryMetricChart(agentTokenTrendSeries(tokenRows), {
+ title: "Token consumption over time", unit: "short", style: "bars", fillOpacity: 0.58, calculations: ["Sum", "Mean", "Max"],
+ companion: { label: "Estimated cost" },
+ }))}
+ ${agentPanel("Daily estimated run cost", foundryMetricChart(costSeries, {
+ title: "Daily estimated run cost", unit: "currency", style: "bars", fillOpacity: 0.65, calculations: ["Sum", "Mean", "Max"],
+ }), false, "Price-sheet estimate from chat token spans. This is not Costs().")}
+ ${agentPanel("Agent response time trends", foundryMetricChart(agentTrendSeries(latencyRows, "AverageLatencyMs"), {
+ title: "Agent response time trends", unit: "ms", style: "lines", fillOpacity: 0.14, calculations: ["Mean", "Max", "Last"],
+ }))}
+ ${agentPanel("Success, errors, and throughput", foundryMetricChart([
+ ...agentTrendSeries(operationsRows, "Operations"),
+ ...resultSeries,
+ ], {
+ title: "Success, errors, and throughput", unit: "short", style: "lines", fillOpacity: 0.12, calculations: ["Sum", "Mean", "Max"],
+ }))}
+ ${agentPanel("Agent performance", agentTable, true)}
+ ${agentPanel("Model, latency, and cache insights", modelTable, true)}
+ ${agentPanel("Chat finish reasons", finishTable)}
+ ${agentPanel("Tool usage leaderboard", toolTable)}
+ ${agentPanel("Recent runs", recentRuns, true)}
+ ${agentPanel("Recent errors", recentErrors, true)}
+
+ ${fmtInt(payload.workspaceCount || 0)} accessible workspaces queried. Every panel and control derives from the same cached tenant and time-range result.
+ `;
+}
+
+/* --------------------------------------------- AI & emerging workloads render */
+
+// Middle-ellipsis a cell value and expose the full string on hover, so long
+// meter and series names shorten predictably instead of overflowing the
+// `white-space: nowrap` table cells.
+function nameCell(value, n) {
+ // `??` alone lets an empty string through, which renders as a blank cell and
+ // reads as a rendering failure rather than as absent data.
+ const s = String(value ?? "").trim() || "—";
+ const short = trunc(s, n);
+ return short === s ? esc(s) : `${esc(short)} `;
+}
+
+// Wrap a table that can exceed its panel width. The first column stays pinned
+// while the numeric columns scroll, so a row never loses its label.
+function wideTable(html) {
+ return `${html}
`;
+}
+
+function aiCapabilityTable(rows, estate) {
+ const money = moneyColumn(rows, "Cost");
+ return wideTable(tableHtml([
+ { label: "Capability", align: "left", get: (r) =>
+ `${swatchHtml(aiColor(r.Capability))}${nameCell(r.Capability, 26)} ` },
+ { label: "Services", get: (r) => fmtInt(r.Services) },
+ { label: "Cost", get: (r) => money(r.Cost) },
+ { label: "Share", get: (r) => estate > 0 ? fmtShare(r.Cost / estate, 1) : "—" },
+ ], rows, "No AI/ML estate cost in range."));
+}
+
+function aiModelBenchTable(rows) {
+ const money = moneyColumn(rows, "Cost");
+ const rate = rateColumn(rows, "Cpmt");
+ return wideTable(tableHtml([
+ { label: "Model family", align: "left", get: (r) => nameCell(r.Family, 26) },
+ { label: "Tokens", get: (r) => fmtTokens(r.Tokens) },
+ { label: "Cost", get: (r) => money(r.Cost) },
+ { label: "$ / 1M tokens", get: (r) => rate(r.Cpmt) },
+ ], rows, "No foundation model token meters in range."));
+}
+
+function aiDirectionTable(rows) {
+ const rate = rateColumn(rows, "Cpmt");
+ const total = (rows || []).reduce((s, r) => s + (r.Tokens || 0), 0);
+ return wideTable(tableHtml([
+ { label: "Direction", align: "left", get: (r) => nameCell(r.Direction, 26) },
+ { label: "Tokens", get: (r) => fmtTokens(r.Tokens) },
+ { label: "Share", get: (r) => total > 0 ? fmtShare(r.Tokens / total, 1) : "—" },
+ { label: "$ / 1M tokens", get: (r) => rate(r.Cpmt) },
+ ], rows, "No foundation model token meters in range."));
+}
+
+export function deriveAiKpis(d, lastClosedMonth) {
+ const months = d.monthly || [];
+ const sum = (key) => months.reduce((s, r) => s + (r[key] || 0), 0);
+ const cloud = sum("Cloud"), estate = sum("Estate"), mlGpu = sum("MlGpu");
+ const tokens = sum("Tokens"), tokenCost = sum("TokenCost");
+
+ // Anchor month-over-month to the last *closed* month reported by the server.
+ // The newest month in the window is normally a partial ingestion month, and
+ // comparing it against a full month reports a collapse that isn't real.
+ const closedIdx = lastClosedMonth ? months.findIndex((r) => r.Month === lastClosedMonth) : -1;
+ const closed = closedIdx >= 0 ? months[closedIdx] : null;
+ const prior = closedIdx > 0 ? months[closedIdx - 1] : null;
+ const mom = closed && prior && prior.Estate > 0 ? (closed.Estate - prior.Estate) / prior.Estate : null;
+
+ const a = (d.allocation || [])[0] || {};
+ const allocTotal = a.Total || 0;
+ const appCoverage = allocTotal > 0 ? (a.App || 0) / allocTotal : null;
+
+ const posture = (d.posture || [])[0] || {};
+
+ return {
+ cloud, estate, mlGpu, tokens, tokenCost,
+ estateShare: cloud > 0 ? estate / cloud : 0,
+ mlGpuShare: estate > 0 ? mlGpu / estate : 0,
+ cpmt: tokens > 0 ? (tokenCost / tokens) * 1000000 : null,
+ mom, closedMonth: lastClosedMonth, hasClosedMonth: !!closed,
+ partialMonth: months.length > 0 && months[months.length - 1].Month !== lastClosedMonth
+ ? months[months.length - 1].Month : null,
+ alloc: a, allocTotal, appCoverage,
+ committedShare: posture.Total > 0 ? (posture.Committed || 0) / posture.Total : null,
+ recommendations: ((d.recommendations || [])[0] || {}).Count ?? 0,
+ transactions: ((d.transactions || [])[0] || {}).Count ?? 0,
+ };
+}
+
+function aiAllocationTable(k) {
+ const rows = [
+ { Dimension: "Application tag", Covered: k.alloc.App || 0 },
+ { Dimension: "Owner / team tag", Covered: k.alloc.Owner || 0 },
+ { Dimension: "Cost center", Covered: k.alloc.CostCenter || 0 },
+ { Dimension: "Resource group", Covered: k.alloc.ResourceGroup || 0 },
+ ];
+ if (k.allocTotal <= 0) return `No AI/ML estate cost in range.
`;
+ const money = moneyColumn(rows, "Covered");
+ return wideTable(tableHtml([
+ { label: "Dimension", align: "left", get: (r) => esc(r.Dimension) },
+ { label: "Covered cost", get: (r) => money(r.Covered) },
+ { label: "Coverage", get: (r) => {
+ const pct = r.Covered / k.allocTotal;
+ const cls = pct >= 0.85 ? "pos" : pct >= 0.65 ? "warn" : "neg";
+ return `${fmtShare(pct)} `;
+ } },
+ ], rows));
+}
+
+function aiPostureTable(k) {
+ // Counts are descriptive: a zero means no AI-scoped records were ingested,
+ // which is a different statement from "no opportunity exists".
+ const rows = [
+ {
+ Signal: "Commitment coverage",
+ Value: k.committedShare == null ? "—" : fmtPct(k.committedShare),
+ Note: k.committedShare ? "AI/ML estate cost on a commitment discount" : "No AI/ML spend is on a commitment discount",
+ },
+ {
+ Signal: "AI-scoped rate recommendations",
+ Value: fmtInt(k.recommendations),
+ Note: k.recommendations > 0 ? "Open recommendations touching AI/ML resource types" : "None ingested for AI/ML resource types",
+ },
+ {
+ Signal: "AI-scoped commitment transactions",
+ Value: fmtInt(k.transactions),
+ Note: k.transactions > 0 ? "Purchase or refund events matching AI/GPU descriptions" : "None ingested matching AI/GPU descriptions",
+ },
+ ];
+ return wideTable(tableHtml([
+ { label: "Signal", align: "left", get: (r) => esc(r.Signal) },
+ { label: "Value", get: (r) => r.Value },
+ { label: "Detail", align: "left", get: (r) => `${esc(r.Note)} ` },
+ ], rows));
+}
+
+function aiDriversTable(rows, k) {
+ const money = moneyColumn(rows, "Prev", "Cost");
+ const delta = moneyColumn(rows, "Change");
+ // Below half a cent the change is a rounding artefact, not a movement: format
+ // it as a flat zero so it can't render as a signed "-$0.00 (-0.0%)" and can't
+ // pick up a directional colour.
+ const EPS = 0.005;
+ return wideTable(tableHtml([
+ { label: "Service", align: "left", get: (r) => nameCell(r.Service, 26) },
+ { label: "Meter", align: "left", get: (r) => nameCell(r.Meter, 26) },
+ { label: "Prior month", get: (r) => money(r.Prev) },
+ { label: k.closedMonth ? fmtMonth(k.closedMonth) : "Latest month", get: (r) => money(r.Cost) },
+ { label: "Change", get: (r) => {
+ const chg = Math.abs(r.Change || 0) < EPS ? 0 : r.Change;
+ const cls = chg > 0 ? "neg" : chg < 0 ? "pos" : "muted";
+ if (chg === 0) return `no change `;
+ // A zero baseline has no percentage; say so rather than leaving the
+ // cell ragged against the rows that carry one.
+ const pct = r.Prev > 0
+ ? ` (${chg > 0 ? "+" : ""}${fmtShare(chg / r.Prev, 1)})`
+ : ` (new)`;
+ return `${chg > 0 ? "+" : ""}${delta(chg)}${pct} `;
+ } },
+ ], rows, "No month-over-month movement in range."));
+}
+
+function renderAi(p) {
+ const content = el("content");
+ if (!p) return;
+ if (p.error) return renderError(p);
+ if (p.empty) {
+ content.innerHTML = `No AI or emerging workload data
+
No AI, machine learning, or GPU-accelerated spend was found in the Hub database for this period.
+
This view scopes to the AI and Machine Learning service category, Azure AI Search, Azure Databricks, and GPU VM series (NC/ND/NV/NG). Ingest cost data covering those workloads, then refresh.
`;
+ return;
+ }
+ const d = p.data;
+ const k = deriveAiKpis(d, p.lastClosedMonth);
+
+ const momTxt = k.mom == null ? null : `${k.mom > 0 ? "+" : ""}${fmtPct(k.mom, 1)}`;
+ const momCls = k.mom == null ? "muted" : k.mom > 0 ? "neg" : "pos";
+ const estateMeta = momTxt
+ ? `${momTxt} vs prior · ${esc(fmtMonth(k.closedMonth))}`
+ : `${fmtPct(k.estateShare, 1)} of all cloud cost`;
+
+ const covCls = k.appCoverage == null ? undefined
+ : k.appCoverage >= 0.85 ? "threshold-green" : k.appCoverage >= 0.65 ? "threshold-amber" : "threshold-red";
+
+ const cpmtTrend = (d.monthly || [])
+ .filter((r) => (r.Tokens || 0) > 0)
+ .map((r) => ({ Month: r.Month, Cpmt: (r.TokenCost / r.Tokens) * 1000000 }));
+
+ const kpis = [
+ kpiCard("AI/ML estate spend", fmtMoney(k.estate), estateMeta, PALETTE[2], undefined, "primary"),
+ kpiCard("ML & GPU compute", fmtMoney(k.mlGpu), `${fmtPct(k.mlGpuShare, 1)} of AI/ML estate`, PALETTE[9]),
+ kpiCard("Token volume", fmtTokens(k.tokens), `${fmtMoney(k.tokenCost)} in token meters`, PALETTE[0]),
+ kpiCard("Cost per 1M tokens", k.cpmt == null ? "—" : fmtRate(k.cpmt),
+ k.cpmt == null ? "No token meters in range" : "Blended across all model families", PALETTE[5]),
+ kpiCard("AI allocation coverage", k.appCoverage == null ? "—" : fmtPct(k.appCoverage),
+ k.appCoverage == null ? "No AI/ML estate cost in range" : "Carrying an application tag",
+ PALETTE[3], covCls),
+ kpiCard("AI share of cloud", fmtPct(k.estateShare, 1), `${fmtMoney(k.estate)} of ${fmtMoney(k.cloud)}`, PALETTE[1], undefined, "reference"),
+ ].join("");
+
+ // One money scale per detail table, derived from that table's own maximum.
+ const mlGpuMoney = moneyColumn(d.mlGpu, "Cost");
+ const mlUnitMoney = moneyColumn(d.mlUnit, "Cost");
+ const mlUnitVmRate = rateColumn(d.mlUnit, "PerVmHour");
+ const mlUnitCoreRate = rateColumn(d.mlUnit, "Per1KCoreHours");
+ const searchMoney = moneyColumn(d.search, "Cost");
+ const cognitiveMoney = moneyColumn(d.cognitive, "Cost");
+
+ const partialNote = k.partialMonth
+ ? ` Month-over-month figures compare ${esc(fmtMonth(k.closedMonth))} against the month before it; ${esc(fmtMonth(k.partialMonth))} is still ingesting and is excluded from those comparisons.`
+ : "";
+
+ content.innerHTML = `
+ ${kpis}
+
+ This view scopes to the AI and Machine Learning service category plus Azure AI Search, Azure Databricks, and GPU VM series (NC/ND/NV/NG). GPU capacity bought outside those services — or AI work running on general-purpose compute — will not appear here.${partialNote}
+
+
AI/ML estate Workload composition
+
+ ${panelHtml("ai-capability-trend", 12, "AI spend by capability over time", "Monthly effective cost split across AI capability groups.", aiCapabilityChart(d.capabilityTrend))}
+ ${panelHtml("ai-capability", 6, "Estate composition", "Effective cost and distinct services per capability.", aiCapabilityTable(d.capability, k.estate))}
+ ${panelHtml("ai-by-service", 6, "Estate spend by service", "Top billing services in the AI/ML estate.",
+ hbar(d.byService, "Service", "Cost", { filterDim: "ServiceName", nameW: 210, color: PALETTE[2], label: "AI/ML estate spend by service" }))}
+
+
+
Token & model economics Unit economics
+
+ ${panelHtml("ai-token-demand", 6, "Token demand", "Monthly token volume across all foundation model meters.",
+ monthAreaChart(d.monthly, { valueKey: "Tokens", color: PALETTE[2], valFmt: fmtTokens, label: "Monthly token volume" }))}
+ ${panelHtml("ai-cpmt-trend", 6, "Cost per 1M tokens", "Blended effective rate — the direction of travel matters more than the level.",
+ monthAreaChart(cpmtTrend, { valueKey: "Cpmt", color: PALETTE[5], valFmt: axisRate, tipFmt: fmtRate, label: "Blended cost per 1M tokens" }))}
+ ${panelHtml("ai-model-bench", 6, "Model family benchmark", "Cost per 1M tokens by model family — the input to model selection.", aiModelBenchTable(d.modelBench))}
+ ${panelHtml("ai-direction", 6, "Token direction mix", "Input, cached input, output, and embedding meters.", aiDirectionTable(d.direction))}
+
+
+
Workload detail Compute, retrieval & applied AI
+
+ ${panelHtml("ai-ml-gpu", 12, "ML platform & GPU compute", "Components behind machine learning and accelerated compute spend.",
+ wideTable(tableHtml([
+ { label: "Component", align: "left", get: (r) => nameCell(r.Component, 28) },
+ { label: "Unit", align: "left", get: (r) => nameCell(r.Unit, 16) },
+ { label: "Quantity", get: (r) => fmtQty(r.Quantity) },
+ { label: "Cost", get: (r) => mlGpuMoney(r.Cost) },
+ ], d.mlGpu)))}
+ ${panelHtml("ai-search", 12, "AI Search / retrieval", "Azure AI Search meters supporting retrieval-augmented generation.",
+ wideTable(tableHtml([
+ { label: "Meter", align: "left", get: (r) => nameCell(r.Meter, 28) },
+ { label: "Unit", align: "left", get: (r) => nameCell(r.Unit, 16) },
+ { label: "Quantity", get: (r) => fmtQty(r.Quantity) },
+ { label: "Cost", get: (r) => searchMoney(r.Cost) },
+ ], d.search, "No Azure AI Search meters in range.")))}
+ ${panelHtml("ai-ml-unit", 6, "ML compute unit economics", "Effective rate per VM-hour and per 1K core-hours by VM series.",
+ wideTable(tableHtml([
+ { label: "Series", align: "left", get: (r) => nameCell(r.Series, 24) },
+ { label: "VM hours", get: (r) => fmtQty(r.VmHours) },
+ { label: "$ / VM-hour", get: (r) => mlUnitVmRate(r.PerVmHour) },
+ { label: "$ / 1K core-hours", get: (r) => mlUnitCoreRate(r.Per1KCoreHours) },
+ { label: "Cost", get: (r) => mlUnitMoney(r.Cost) },
+ ], d.mlUnit, "No ML virtual machine meters in range.")))}
+ ${panelHtml("ai-cognitive", 6, "Cognitive & applied AI", "Speech, vision, language, and video services, excluding token meters.",
+ wideTable(tableHtml([
+ { label: "Service", align: "left", get: (r) => nameCell(r.Service, 30) },
+ { label: "Quantity", get: (r) => fmtQty(r.Units) },
+ { label: "Cost", get: (r) => cognitiveMoney(r.Cost) },
+ ], d.cognitive, "No cognitive or applied AI meters in range.")))}
+
+
+
Allocation & posture Accountability & rate optimization
+
+ ${panelHtml("ai-allocation", 6, "Allocation coverage", "Share of AI/ML estate cost carrying each accountability dimension.", aiAllocationTable(k))}
+ ${panelHtml("ai-by-owner", 6, "Estate spend by owner", "Owner or team tag, falling back to cost center then resource group. Tag values are folded case-insensitively.",
+ hbar(d.byOwner, "Owner", "Cost", { filterDim: null, nameW: 210, color: PALETTE[2], label: "AI/ML estate spend by owner" }))}
+ ${panelHtml("ai-posture", 12, "Commitment & rate posture", "Whether AI/ML spend is on a commitment, and which AI-scoped rate signals were ingested.", aiPostureTable(k))}
+ ${panelHtml("ai-drivers", 12, "Top movers", `Largest AI/ML meters, ${k.closedMonth ? `${esc(fmtMonth(k.closedMonth))} against the month before it` : "latest month against the month before it"}.`, aiDriversTable(d.drivers, k))}
+
+ `;
+}
+
+/* --------------------------------------------- anomalies & forecast render */
+
+function renderAnomaly(p) {
+ const content = el("content");
+ if (!p) return;
+ if (p.error) return renderError(p);
+ if (p.empty) {
+ content.innerHTML = `No cost data The Hub database has no rows yet.
`;
+ return;
+ }
+ const d = p.data;
+ const daily = d.daily || [];
+ const anomDays = daily.filter((r) => r.Flag !== 0);
+ const totalCost = daily.reduce((a, r) => a + (r.Cost || 0), 0);
+ const anomCost = anomDays.reduce((a, r) => a + (r.Cost || 0), 0);
+ const variance = Math.abs(anomDays.reduce((a, r) => a + ((r.Cost || 0) - (r.Baseline || 0)), 0));
+ const rate = totalCost > 0 ? anomCost / totalCost : 0;
+
+ const fc = d.forecast || [];
+ const dataMaxMonth = (p.window?.dataMax || "").slice(0, 7);
+ const nextFc = fc.find((r) => r.Month > dataMaxMonth);
+
+ const mc = (d.monthlyChange || []).filter((r) => isFinite(r.EffChangePct));
+ // last complete month (skip the partial dataMax month for the headline KPI)
+ const completeMc = mc.filter((r) => r.Month < dataMaxMonth);
+ const lastMc = completeMc[completeMc.length - 1] || mc[mc.length - 1];
+
+ const fr = d.freshness?.[0] || {};
+ const p50Days = fr.P50 != null ? fr.P50 / 24 : null;
+
+ const mcClass = lastMc == null ? "" : lastMc.EffChangePct > 0 ? "neg" : "pos"; // cost up = bad
+ const mcArrow = lastMc == null ? "" : lastMc.EffChangePct > 0 ? "▲" : "▼";
+ const mcValue = lastMc == null ? "—" : `${mcArrow} ${fmtPct(Math.abs(lastMc.EffChangePct) / 100)} `;
+
+ const kpis = [
+ // reference KPIs first (no primaries in this tab)
+ kpiCard("Anomaly days", fmtInt(anomDays.length),
+ `${fmtMoney(anomCost)} on flagged days`, undefined, undefined, "reference"),
+ // supporting KPIs
+ kpiCard("Anomaly detection rate", fmtPct(rate, 2),
+ `% of effective spend on flagged days · ${fmtInt(anomDays.length)} of ${fmtInt(daily.length)} days flagged`, undefined),
+ kpiCard("Unpredicted variance", fmtMoney(variance),
+ `net spend vs baseline on anomaly days`, undefined),
+ kpiCard("Last month change", mcValue,
+ lastMc ? `effective cost · ${esc(fmtMonth(lastMc.Month))}` : "", undefined),
+ kpiCard("Forecast next month", nextFc ? fmtMoney(nextFc.Forecast) : "—",
+ nextFc ? `projected · ${esc(fmtMonth(nextFc.Month))}` : "", undefined),
+ kpiCard("Visibility delay", p50Days != null ? `${p50Days.toFixed(0)}d` : "—",
+ `median ingestion lag (P50)`, undefined),
+ ].join("");
+
+ const triageCallout = anomDays.length > 0
+ ? `⚠ ${fmtInt(anomDays.length)} anomal${anomDays.length === 1 ? "y day" : "y days"} detected — ${fmtMoney(anomCost)} in flagged spend. Review the chart below.
`
+ : "";
+
+ content.innerHTML = `
+ ${triageCallout}
+ ${kpis}
+
+
Cost anomalies Anomaly management capability
+
+ ${panelHtml("anomaly-daily", 12, "Daily cost & detected anomalies", "Daily effective cost vs the expected baseline (STL decomposition); markers flag spikes & drops.", anomalyChart(daily))}
+
+
+
Trend & forecast Forecasting · Data freshness
+
+ ${panelHtml("anomaly-mom", 6, "Month-over-month change", "Effective cost % change vs prior month (red = increase).", momBars(mc))}
+ ${panelHtml("anomaly-forecast", 6, "Cost forecast", "Monthly effective cost, actual vs forecast (next 3 months).", forecastChart(fc, dataMaxMonth))}
+
+ `;
+}
+
+/* ----------------------------------------------- usage & unit economics render */
+
+function renderUsage(p) {
+ const content = el("content");
+ if (!p) return;
+ if (p.error) return renderError(p);
+ if (p.empty) {
+ content.innerHTML = `No cost data The Hub database has no rows yet.
`;
+ return;
+ }
+ const d = p.data;
+ const c = d.compute?.[0] || {};
+ const s = d.storage?.[0] || {};
+ const coreHours = c.CoreHours || 0;
+ const hourlyPerCore = coreHours > 0 ? c.ComputeEff / coreHours : 0;
+ const effPerCore = coreHours > 0 ? (c.ComputeEff + (c.UnusedCommit || 0)) / coreHours : 0;
+ const gbMonths = s.GBMonths || 0;
+ const perGB = gbMonths > 0 ? s.Cost / gbMonths : 0;
+ const total = d.total?.[0]?.Total || 0;
+
+ const kpis = [
+ kpiCard("Hourly cost / core", `$${hourlyPerCore.toFixed(3)}`,
+ `per consumed vCPU-hour`, PALETTE[0], undefined, "primary"),
+ kpiCard("Effective cost / core", `$${effPerCore.toFixed(3)}`,
+ `incl. unused commitment`, PALETTE[2], undefined, "reference"),
+ kpiCard("Compute core-hours", fmtTokens(coreHours),
+ `${fmtMoney(c.ComputeEff)} VM usage`, PALETTE[1]),
+ kpiCard("Storage rate", `$${(perGB * 1024).toFixed(3)}`,
+ `per TB-month (effective)`, PALETTE[5]),
+ kpiCard("Storage volume", `${fmtTokens(gbMonths)}`,
+ `GB-months stored`, PALETTE[8]),
+ kpiCard("Storage cost", fmtMoney(s.Cost),
+ `effective storage spend`, PALETTE[3]),
+ ].join("");
+
+ const typeRows = (d.topResourceTypes || []).map((r) => ({
+ type: r.ResourceType, count: r.Resources || 0, cost: r.Cost || 0,
+ pct: total > 0 ? (r.Cost || 0) / total : 0,
+ }));
+ const typeTable = tableHtml([
+ { label: "Resource type", align: "left", get: (r, i) => `${swatchHtml(PALETTE[i % PALETTE.length])}${esc(r.type)} ` },
+ { label: "Resources", get: (r) => fmtInt(r.count) },
+ { label: "Effective cost", get: (r) => fmtMoneyFull(r.cost) },
+ { label: "% of total", get: (r) => fmtPct(r.pct) },
+ ], typeRows);
+
+ const tierColors = { "Frequent": PALETTE[1], "Infrequent": PALETTE[5], "Unclassified": UNKNOWN_COLOR };
+ const tierSlices = (d.storageTiers || []).map((r) => ({ label: r.Tier, value: r.Cost || 0, color: tierColors[r.Tier] || PALETTE[6], isUnknown: r.Tier === "Unclassified" }));
+ const freqShare = (() => {
+ const t = tierSlices.reduce((a, x) => a + x.value, 0);
+ const f = (d.storageTiers || []).find((r) => r.Tier === "Frequent");
+ return t > 0 ? (f?.Cost || 0) / t : 0;
+ })();
+
+ content.innerHTML = `
+ ${kpis}
+
+
Usage & unit economics Usage optimization · Unit economics
+
+ ${panelHtml("usage-top-types", 12, "Top resource types by cost", "Resource count and effective spend per resource type.", typeTable)}
+ ${panelHtml("usage-per-core-series", 6, "Compute cost per core by VM series", "Effective cost per vCPU-hour — highlights expensive (e.g. GPU) cores.",
+ hbar(d.perCoreSeries, "x_SkuMeterSubcategory", "PerCore", { valFmt: (v) => `$${v.toFixed(3)}`, label: "Compute cost per core by VM series" }))}
+ ${panelHtml("usage-storage-tiers", 6, `Storage tier distribution`, `Effective storage cost by access tier (${fmtPct(freqShare)} classified frequent).`,
+ donut(tierSlices, { centerBig: fmtMoney(s.Cost), centerSmall: "storage", label: "Storage tier distribution" }))}
+
+ `;
+}
+
+function renderRate(p) {
+ const content = el("content");
+ if (!p) return;
+ if (p.error) return renderError(p);
+ if (p.empty) {
+ content.innerHTML = `No cost data The Hub database has no rows yet.
`;
+ return;
+ }
+ const d = p.data;
+ const s = d.savings?.[0] || {};
+ const cm = d.commitment?.[0] || {};
+ const cc = d.computeCoverage?.[0] || {};
+ const esr = s.List > 0 ? s.Total / s.List : 0;
+ const cmTotal = cm.Total || 0;
+ const util = cmTotal > 0 ? (cmTotal - (cm.Unused || 0)) / cmTotal : 0;
+ const waste = cmTotal > 0 ? (cm.Unused || 0) / cmTotal : 0;
+ const coverage = cc.Contracted > 0 ? cc.Committed / cc.Contracted : 0;
+ const coreTotal = (d.coreHours || []).reduce((a, r) => a + (r.CoreHours || 0), 0);
+ const committedCore = (d.coreHours || []).filter((r) => r.t !== "On Demand").reduce((a, r) => a + (r.CoreHours || 0), 0);
+ const coreShare = coreTotal > 0 ? committedCore / coreTotal : 0;
+ // Single source of truth for "Commitment waste" coloring: derive the meta
+ // text color from the same threshold the card border uses, instead of a
+ // separately hardcoded 0.1 cutoff that could silently drift out of sync.
+ const wasteThreshold = kpiThreshold(waste, 0.10, 0.20);
+ const wasteMetaCls = wasteThreshold === "threshold-red" ? "neg" : wasteThreshold === "threshold-amber" ? "warn" : "pos";
+
+ const kpis = [
+ // primary KPIs first
+ kpiCard("Effective savings rate", fmtPct(esr),
+ `${fmtMoney(s.Total)} total savings · vs. list price`, PALETTE[1], undefined, "primary"),
+ kpiCard("Commitment waste", fmtPct(waste),
+ `${fmtMoney(cm.Unused)} unused · of commitment spend`, PALETTE[3],
+ wasteThreshold, "primary"),
+ // supporting KPIs
+ kpiCard("Total savings", fmtMoney(s.Total),
+ `of ${fmtMoney(s.List)} list cost`, PALETTE[2]),
+ (() => {
+ const cusRow = (d.commitmentUtilScore || []).find((r) => r.CommitmentDiscountName === '(Grand Total)');
+ const cusScore = cusRow ? cusRow.Score / 100 : util;
+ return kpiCard("Commitment utilization", fmtPct(cusScore),
+ cusRow
+ ? `${fmtMoney(cusRow.Amount)} utilized of ${fmtMoney(cusRow.Potential)} potential`
+ : `${fmtMoney(cmTotal - (cm.Unused || 0))} of ${fmtMoney(cmTotal)} used`,
+ PALETTE[0]);
+ })(),
+ // reference KPIs
+ kpiCard("Compute coverage", fmtPct(coverage),
+ `compute spend on commitments`, PALETTE[5], undefined, "reference"),
+ // supporting KPIs
+ kpiCard("Committed core-hours", fmtPct(coreShare),
+ `RI + savings plan vs on-demand`, PALETTE[8], undefined, "reference"),
+ ].join("");
+
+ const savingsBreak = costBreakdownTable([
+ { label: "List cost (excl. commitment purchases)", val: s.List, accent: "var(--muted)" },
+ { label: "Negotiated savings", val: s.Negotiated, accent: PALETTE[8] },
+ { label: "Commitment savings", val: s.Commitment, accent: PALETTE[1] },
+ { label: "Effective cost", val: s.Effective, accent: PALETTE[0] },
+ ], "Effective savings rate", fmtPct(esr));
+
+ const coreColors = { "On Demand": PALETTE[0], "Reservation": PALETTE[1], "Savings Plan": PALETTE[4] };
+ const coreSlices = (d.coreHours || []).map((r) => ({ label: r.t, value: r.CoreHours || 0, color: coreColors[r.t] || PALETTE[6] }));
+
+ const underutilCount = (d.byCommitment || []).filter((r) => (r.Unused || 0) > 0).length;
+ const rateCallout = underutilCount > 0
+ ? `⚠ ${fmtInt(underutilCount)} underutilized commitment${underutilCount === 1 ? "" : "s"} found — ${fmtMoney(cm.Unused)} in unused spend. See the commitments panel below.
`
+ : "";
+
+ content.innerHTML = `
+ ${rateCallout}
+ ${kpis}
+
+
Rate optimization Rate optimization capability
+
+ ${panelHtml("rate-savings", 6, "Savings breakdown", "List → effective cost by discount type (effective savings rate).", savingsBreak)}
+ ${panelHtml("rate-commit-util", 6, "Commitment utilization", "Used vs unused commitment effective cost.",
+ donut([
+ { label: "Used", value: cmTotal - (cm.Unused || 0), color: PALETTE[1] },
+ { label: "Unused (waste)", value: cm.Unused || 0, color: PALETTE[3] },
+ ], { centerBig: fmtPct(util), centerSmall: "utilized", label: "Commitment utilization" }))}
+ ${panelHtml("rate-core-hours", 6, "Core-hour coverage", "Consumed core-hours by commitment type.",
+ donut(coreSlices, {
+ centerBig: fmtPct(coreShare), centerSmall: "committed",
+ valueFmt: (s) => `${fmtTokens(s.value)} core-hrs`,
+ label: "Core-hour coverage",
+ }))}
+ ${panelHtml("rate-underutil", 6, "Underutilized commitments", "Reservations & plans with the most unused cost.",
+ hbar(d.byCommitment, "CommitmentDiscountName", "Unused", { label: "Underutilized commitments" }))}
+
+
+
Commitment transactions Rate optimization · Commitment purchasing
+
+ ${panelHtml("rate-commit-score", 6, "Commitment utilization score", "Per-commitment utilization (used vs potential) from the formal CUS KPI.", commitUtilTable(d.commitmentUtilScore))}
+ ${panelHtml("rate-top-txns", 6, "Top commitment transactions", "Largest RI and savings plan purchases by billed cost. Effective cost is $0 by design — amortization credits the cost to the months the commitment is consumed, not the purchase month.", topCommitTxnTable(d.topCommitmentTxns))}
+
+ `;
+}
+
+function commitUtilTable(rows) {
+ const data = (rows || []).filter((r) => r.CommitmentDiscountName !== '(Grand Total)' && (r.Potential || 0) > 0);
+ if (data.length === 0) return `No commitment data in range.
`;
+ return `
+ Commitment Type Score Utilized Potential
+ ${data.map((r) => {
+ const score = r.Score || 0;
+ const cls = score < 70 ? "neg" : score < 90 ? "warn" : "pos";
+ const barW = Math.max(2, (score / 100) * 90);
+ return `
+ ${esc(r.CommitmentDiscountName)}
+ ${esc(r.CommitmentDiscountType || r.CommitmentDiscountCategory || "")}
+ ${fmtPct(score / 100)}
+ ${fmtMoney(r.Amount)}
+ ${fmtMoney(r.Potential)}
+ `;
+ }).join("")}
+
`;
+}
+
+function topCommitTxnTable(rows) {
+ const data = rows || [];
+ if (data.length === 0) return `No commitment transactions in range.
`;
+ return `
+ Commitment Type Billed cost Effective cost
+ ${data.map((r) => `
+ ${esc(r.CommitmentDiscountName || "(unknown)")}
+ ${esc(r.CommitmentDiscountType || "")}
+ ${fmtMoney(r.BilledCost)}
+ ${fmtMoney(r.EffectiveCost)}
+ `).join("")}
+
`;
+}
+
+/* ----------------------------------------------------- allocation render */
+
+function renderAllocation(p) {
+ const content = el("content");
+ if (!p) return;
+ if (p.error) return renderError(p);
+ if (p.empty) {
+ content.innerHTML = `No cost data The Hub database has no rows yet.
`;
+ return;
+ }
+ const d = p.data;
+ const c = d.core?.[0] || {};
+ const total = c.Total || 0;
+ const aai = total > 0 ? c.Attributed / total : 0;
+ const untaggedPct = total > 0 ? c.Untagged / total : 0;
+ const unallocPct = total > 0 ? (total - c.Attributed) / total : 0;
+ const compliancePct = total > 0 ? c.Compliant / total : 0;
+
+ const kpis = [
+ // primary KPIs first
+ kpiCard("Untagged cost", fmtPct(untaggedPct),
+ `${fmtMoney(c.Untagged)} with no tags`, PALETTE[3],
+ kpiThreshold(untaggedPct, 0.10, 0.25), "primary"),
+ // supporting KPIs
+ kpiCard("Allocation accuracy", fmtPct(aai),
+ `directly attributed effective cost`, PALETTE[1]),
+ kpiCard("Unallocated cost", fmtPct(unallocPct),
+ `${fmtMoney(total - c.Attributed)} lacks ownership attribution`, PALETTE[4]),
+ kpiCard("Tag policy compliance", fmtPct(compliancePct),
+ `keys: CostCenter · env · org`, PALETTE[5]),
+ kpiCard("Subscriptions", fmtInt(c.Subs),
+ `billing scopes in range`, PALETTE[0]),
+ kpiCard("Allocated cost", fmtMoney(c.Attributed),
+ `of ${fmtMoney(total)} total`, PALETTE[2]),
+ ].join("");
+
+ const hierRows = (d.hierarchy || []).map((r) => ({
+ org: r.Org || "—", project: r.Project || "—", env: r.Env || "—", cost: r.Cost || 0,
+ pct: total > 0 ? (r.Cost || 0) / total : 0,
+ }));
+ const hierTable = tableHtml([
+ {
+ label: "Org", align: "left", get: (r, i) => {
+ const isUnknown = r.org === "—" && r.project === "—" && r.env === "—";
+ return `${swatchHtml(PALETTE[i % PALETTE.length], isUnknown)}${esc(r.org)} `;
+ },
+ },
+ { label: "Project", align: "left", get: (r) => esc(r.project) },
+ { label: "Environment", align: "left", get: (r) => esc(r.env) },
+ { label: "Effective cost", get: (r) => fmtMoneyFull(r.cost) },
+ { label: "% of total", get: (r) => fmtPct(r.pct) },
+ ], hierRows);
+
+ // Flag case-variant duplicate tag keys (e.g. "CostCenter" vs "costcenter")
+ // so the governance issue is called out, not hidden by treating them as
+ // separate keys.
+ const tagKeyRows = d.tagKeys || [];
+ const lowerCounts = {};
+ tagKeyRows.forEach((r) => { const lk = String(r.k).toLowerCase(); lowerCounts[lk] = (lowerCounts[lk] || 0) + 1; });
+ const dupKeys = tagKeyRows.filter((r) => lowerCounts[String(r.k).toLowerCase()] > 1).map((r) => r.k);
+ const tagKeyNote = dupKeys.length > 0
+ ? ` Note: ${dupKeys.map((k) => `${esc(k)}`).join(" vs ")} are case-variant duplicates of the same governance key — likely inconsistent tagging, not distinct keys.`
+ : "";
+
+ content.innerHTML = `
+ ${kpis}
+
+
Cost allocation Allocation capability
+
+ ${panelHtml("alloc-hierarchy", 8, "Cost by financial hierarchy", "Org → project → environment (from resource tags), with share of total.", hierTable)}
+ ${panelHtml("alloc-tagging", 4, "Tagging coverage", "Tagged vs untagged effective cost.",
+ donut([
+ { label: "Tagged", value: total - c.Untagged, color: PALETTE[1] },
+ { label: "Untagged", value: c.Untagged, color: UNKNOWN_COLOR, isUnknown: true },
+ ], { centerBig: fmtPct(1 - untaggedPct), centerSmall: "tagged", label: "Tagging coverage" }))}
+ ${panelHtml("alloc-tag-keys", 6, "Cost by tag key", `Effective cost touched by each governance tag.${tagKeyNote}`, hbar(d.tagKeys, "k", "Cost", { filterDim: null, label: "Cost by tag key" }))}
+ ${panelHtml("alloc-by-subscription", 6, "Cost by subscription", "Spend per billing scope for showback.", hbar(d.bySubscription, "SubAccountName", "Cost", { label: "Cost by subscription" }))}
+
+ `;
+}
+
+const CAPACITY_ACTIONS = Object.freeze({
+ "app-service": "Validate region access and SKU availability separately before requesting an exact SKU quota increase.",
+ "azure-ai": "Validate model availability, deployment scope, and actual capacity separately from the provider quota row.",
+ compute: "Check both total regional and applicable VM-family vCPU quota, then validate SKU, zone, and physical capacity separately.",
+ "azure-sql": "Use the exact SQL metric and service workflow. Validate region and zone-redundant access separately; do not treat countdown or negative-limit rows as generic utilization.",
+ storage: "Validate ingestion and expected subscription-region coverage before drawing a Storage quota conclusion.",
+ "capacity-reservations": "Inspect reservation quantity, SKU, zones, sharing, associations, and utilization in Azure; inventory count is not reserved capacity.",
+ "premium-ssd-v2": "Inspect disk zone, attachment, IOPS, throughput, and service quota separately; observed GiB is inventory, not quota.",
+});
+
+const CAPACITY_STATE_LABELS = Object.freeze({
+ healthy: "Healthy",
+ watch: "Watch",
+ action: "Action",
+ exhausted: "Exhausted",
+ restricted: "Region restricted",
+ "zone-restricted": "All zones restricted",
+ "no-entitlement": "No quota",
+ inventory: "Observed inventory",
+ unclassified: "Unknown or unclassified",
+ stale: "Stale",
+ invalid: "Invalid or conflict",
+});
+
+export function capacitySelectionFromRow(kind, classId, row) {
+ if (!row || typeof row !== "object") return null;
+ if (kind === "quota") {
+ if (classId === "capacity-reservations" || classId === "premium-ssd-v2") {
+ return { resourceId: String(row.ResourceId || "") };
+ }
+ return {
+ subAccountId: String(row.SubAccountId || ""),
+ location: String(row.location || ""),
+ resourceName: String(row.ResourceName || ""),
+ unit: String(row.unit || ""),
+ sourceVersion: String(row.x_SourceVersion || ""),
+ };
+ }
+ if (kind === "metric") {
+ return {
+ resourceName: String(row.ResourceName || ""),
+ unit: String(row.unit || ""),
+ sourceVersion: String(row.x_SourceVersion || ""),
+ };
+ }
+ const selection = {
+ meterCategory: String(row.x_SkuMeterCategory || ""),
+ meterSubcategory: String(row.x_SkuMeterSubcategory || ""),
+ meter: String(row.SkuMeter || ""),
+ priceId: String(row.SkuPriceId || ""),
+ currency: String(row.BillingCurrency || ""),
+ };
+ if (classId === "premium-ssd-v2") selection.resourceId = String(row.InventoryResourceId || "");
+ else selection.unit = String(row.ConsumedUnit || "");
+ if (classId === "capacity-reservations") {
+ selection.capacityReservationId = String(row.CapacityReservationId || "");
+ selection.capacityReservationStatus = String(row.CapacityReservationStatus || "");
+ }
+ return selection;
+}
+
+function sameCapacitySelection(left, right) {
+ return JSON.stringify(left || null) === JSON.stringify(right || null);
+}
+
+function capacityNavigationHtml() {
+ return `
+ ${CAPACITY_TABS.map((item) => {
+ const active = item.id === state.capacityClass;
+ return `${esc(item.label)} `;
+ }).join("")}
+ `;
+}
+
+function capacityPanel(title, subtitle, body, wide = false) {
+ return `
+ ${esc(title)} ${subtitle ? `${esc(subtitle)}
` : ""}
+ ${body}
+ `;
+}
+
+function capacityStateToken(semantic = {}) {
+ const stateName = semantic.state || "unclassified";
+ const label = CAPACITY_STATE_LABELS[stateName] || stateName;
+ return `${esc(label)} `;
+}
+
+function capacityHomeTable(classes) {
+ const rows = classes || [];
+ return ``;
+}
+
+function capacitySelectorHtml(kind, classId, items, currentSelection) {
+ const isDemand = kind === "demand";
+ const isMetric = kind === "metric";
+ const label = isDemand ? "Billed demand series" : isMetric ? "Quota metric" : "Quota or inventory series";
+ const options = (items || []).map((row, index) => {
+ const selection = capacitySelectionFromRow(kind, classId, row);
+ const selected = sameCapacitySelection(selection, currentSelection);
+ const display = isDemand
+ ? classId === "premium-ssd-v2"
+ ? `${row.DiskName || row.InventoryResourceId} · ${row.SkuMeter || "No matched cost"} · ${row.BillingCurrency || "—"}`
+ : `${row.SkuMeter || row.x_SkuMeterSubcategory || "Unknown meter"} · ${row.ConsumedUnit || "—"} · ${row.BillingCurrency || "—"}`
+ : isMetric
+ ? `${row.displayName || row.ResourceName || "Unknown metric"} · ${row.unit || "—"}`
+ : `${row.ResourceName || row.displayName || "Unknown"} · ${row.SubAccountId || "—"} · ${row.location || "—"}`;
+ const disabled = Object.values(selection || {}).some((value) => !value);
+ return `${esc(display)} `;
+ }).join("");
+ return `
+ ${esc(label)}
+
+ Select an exact ${isDemand ? "meter" : isMetric ? "metric" : "source"} key
+ ${options}
+
+ `;
+}
+
+function formatCapacityValue(value) {
+ const number = Number(value);
+ if (!Number.isFinite(number)) return "—";
+ return number.toLocaleString("en-US", { maximumFractionDigits: 2 });
+}
+
+function capacityCurrentTable(payload) {
+ const inventory = payload.contract?.quotaType === "inventory";
+ const rows = payload.table?.rows || [];
+ const columns = [
+ { label: "Subscription", align: "left", get: (row) => esc(trunc(row.SubAccountId || "—", 28)) },
+ { label: "Region", align: "left", get: (row) => esc(row.location || "—") },
+ { label: inventory ? "Resource" : "Metric", align: "left", get: (row) => `${esc(row.displayName || row.ResourceName || "—")} ` },
+ { label: inventory && payload.classId === "premium-ssd-v2" ? "Size GiB" : "Current", get: (row) => inventory && payload.classId === "capacity-reservations" ? "Observed" : formatCapacityValue(row.currentValue) },
+ { label: "Limit", get: (row) => inventory ? "Not applicable" : formatCapacityValue(row.limit) },
+ { label: "Unit", get: (row) => inventory && payload.classId === "premium-ssd-v2" ? "GiB" : esc(row.unit || "—") },
+ { label: "Quota status", align: "left", get: (row) => `${capacityStateToken(row.semantic)}${esc(row.semantic?.sourceNote || "")} ` },
+ { label: "Ingested", get: (row) => esc(fmtRelativeTime(new Date(row.x_IngestionTime))) },
+ ];
+ return `${tableHtml(columns, rows, payload.contract?.emptyLabel)}
`;
+}
+
+export function capacityHeatmapCell(row, classId) {
+ if (classId === "capacity-reservations") {
+ return { value: Number(row.ObservedObjects || 0), text: `${fmtInt(row.ObservedObjects)} groups`, state: "inventory" };
+ }
+ if (classId === "premium-ssd-v2") {
+ return { value: Number(row.ObservedGiB || 0), text: `${formatCapacityValue(row.ObservedGiB)} GiB`, state: "inventory" };
+ }
+ const semantic = row.semantic || {};
+ return {
+ value: semantic.utilizationPercent,
+ text: Number.isFinite(semantic.utilizationPercent) ? `${semantic.utilizationPercent.toFixed(1)}%` : (CAPACITY_STATE_LABELS[semantic.state] || "Not reported"),
+ state: semantic.state || "unclassified",
+ };
+}
+
+function capacityHeatmap(payload) {
+ const heatmap = payload.heatmap || {};
+ if (heatmap.status === "heatmap-disabled") {
+ return `Heatmap disabled. More than ${fmtInt(heatmap.limit)} observed cells matched. Refine the filters; no partial matrix was rendered.
`;
+ }
+ if (heatmap.status === "no-selection") {
+ return `Select one exact quota metric to enable the subscription-by-region matrix.
`;
+ }
+ const rows = heatmap.rows || [];
+ if (!rows.length) return `No quota data is available for this selection.
`;
+ if (payload.contract?.quotaType !== "inventory" && !rows.some((row) => row.semantic?.capability === "enabled")) {
+ return `Heatmap unavailable. The selected metric is descriptive-only and cannot receive quota-health color.
`;
+ }
+ const subscriptions = [...new Set(rows.map((row) => row.SubAccountId || "Unknown subscription"))].sort();
+ const regions = [...new Set(rows.map((row) => row.location || "Unknown region"))].sort();
+ const cells = new Map(rows.map((row) => [`${row.SubAccountId || "Unknown subscription"}|${row.location || "Unknown region"}`, row]));
+ return ``;
+}
+
+export const MATRIX_STATUS_FILTERS = Object.freeze([
+ { id: "in-use", label: "In use" },
+ { id: "at-limit", label: "At limit" },
+ { id: "available", label: "Available" },
+ { id: "all", label: "All" },
+]);
+const COMPUTE_MATRIX_STATUS_FILTERS = Object.freeze([
+ MATRIX_STATUS_FILTERS[0],
+ MATRIX_STATUS_FILTERS[1],
+ MATRIX_STATUS_FILTERS[2],
+ { id: "restricted", label: "Restricted" },
+ MATRIX_STATUS_FILTERS[3],
+]);
+
+export const HIGH_WATER_MARKS = [60, 70, 80, 90];
+export const DEFAULT_HIGH_WATER_MARK = 70;
+
+const CAPACITY_MATRIX_CONFIG = Object.freeze({
+ compute: Object.freeze({
+ payloadKey: "familyHeatmap",
+ rowHeader: "VM family",
+ searchLabel: "VM family",
+ searchPlaceholder: "Filter by family, such as Dsv5",
+ pairLabel: "family and region combinations",
+ panelTitle: "Estate quota by VM family and region",
+ panelSubtitle: "Provider-reported usage, quota, and headroom from ComputeUsage rows.",
+ detailTab: "Family and region",
+ description: "VM family quota by region across the estate. The left bar and AZ labels use the smallest-vCPU SKU in each family. The percentage is provider-reported family quota utilization. Values are summed across subscriptions.",
+ ariaLabel: "VM family by region matrix, scrollable",
+ empty: "No Compute family quota was reported for this scope. Check ComputeUsage ingestion.",
+ disabled: "Family view disabled.",
+ key: (row) => row.FamilyKey,
+ label: (row) => row.Family || row.FamilyKey,
+ searchText: (row) => `${row.Family || ""} ${row.FamilyKey || ""}`,
+ used: (row) => Number(row.CoresUsed || 0),
+ total: (row) => Number(row.CoresTotal || 0),
+ }),
+ "app-service": Object.freeze({
+ payloadKey: "appServiceHeatmap",
+ rowHeader: "App Service plan SKU",
+ searchLabel: "Plan SKU",
+ searchPlaceholder: "Filter by SKU, such as P1v4",
+ pairLabel: "SKU and region combinations",
+ panelTitle: "Estate quota by plan SKU and region",
+ panelSubtitle: "Provider-reported App Service instance usage, quota, and headroom.",
+ detailTab: "SKU and region",
+ description: "App Service quota by exact plan SKU and region across the estate. Total Regional VMs and the selected SKU both constrain deployment. Quota does not prove physical capacity.",
+ ariaLabel: "App Service plan SKU by region matrix, scrollable",
+ empty: "No App Service SKU quota was reported for this scope. Check AppServiceUsage ingestion.",
+ disabled: "App Service view disabled.",
+ key: (row) => row.SkuKey,
+ label: (row) => row.Sku || row.SkuKey,
+ searchText: (row) => `${row.Sku || ""} ${row.SkuKey || ""} ${row.Unit || ""}`,
+ used: (row) => Number(row.UsedInstances || 0),
+ total: (row) => Number(row.QuotaInstances || 0),
+ subscriptionCoverage: true,
+ }),
+ "azure-sql": Object.freeze({
+ payloadKey: "azureSqlHeatmap",
+ rowHeader: "Azure SQL quota",
+ searchLabel: "Quota",
+ searchPlaceholder: "Filter by quota, such as vCore or server",
+ pairLabel: "quota and region combinations",
+ panelTitle: "Estate quota by Azure SQL metric and region",
+ panelSubtitle: "Provider-reported regional quota for Azure SQL Database, Synapse, and SQL Managed Instance.",
+ detailTab: "Quota and region",
+ description: "Current regional quota only. Legacy subnet and single-vCore counters and subscription-wide free-offer counters are excluded. A zero or negative limit does not receive utilization arithmetic. Quota doesn't prove region or zone-redundant access.",
+ ariaLabel: "Azure SQL quota by region matrix, scrollable",
+ empty: "No supported Azure SQL regional quota was reported for this scope. Check SqlSubscriptionUsage ingestion.",
+ disabled: "Azure SQL view disabled.",
+ key: (row) => row.MetricKey,
+ label: (row) => row.Metric || row.MetricKey,
+ searchText: (row) => `${row.Metric || ""} ${row.MetricKey || ""} ${row.Unit || ""}`,
+ used: (row) => Number(row.Used || 0),
+ total: (row) => Number(row.Quota || 0),
+ subscriptionCoverage: true,
+ }),
+ "azure-ai": Object.freeze({
+ payloadKey: "azureAiHeatmap",
+ rowHeader: "Azure AI model quota",
+ searchLabel: "Model",
+ searchPlaceholder: "Filter by model or tier, such as gpt-4o or GlobalStandard",
+ pairLabel: "model and region combinations",
+ panelTitle: "Estate quota by Azure AI model and region",
+ panelSubtitle: "Provider-reported quota per model deployment tier from Azure AI Foundry and Cognitive Services.",
+ detailTab: "Model and region",
+ description: "Quota by exact model, deployment tier, and region across the estate. Each model/tier pool is independent, so quota is never summed across models. Units vary by model (tokens per minute, requests per minute, provisioned throughput units, and similar); the reported percentage is that model's own utilization.",
+ ariaLabel: "Azure AI model by region matrix, scrollable",
+ empty: "No Azure AI quota was reported for this scope. Check CognitiveServicesUsage ingestion.",
+ disabled: "Azure AI view disabled.",
+ key: (row) => row.ModelKey,
+ label: (row) => row.Model || row.ModelKey,
+ searchText: (row) => `${row.Model || ""} ${row.ModelKey || ""} ${row.Unit || ""}`,
+ used: (row) => Number(row.Used || 0),
+ total: (row) => Number(row.Quota || 0),
+ subscriptionCoverage: true,
+ }),
+});
+
+function matrixStatusMatches(row, classId, status) {
+ const config = CAPACITY_MATRIX_CONFIG[classId];
+ if (!config || status === "all") return true;
+ if (status === "in-use") return config.used(row) > 0;
+ if (status === "at-limit") {
+ return config.subscriptionCoverage
+ ? Number(row.AtLimitSubscriptions || 0) > 0
+ : config.total(row) > 0 && config.used(row) >= config.total(row);
+ }
+ if (status === "available") {
+ return classId === "compute"
+ ? row.semantic?.offerState === "available" && config.total(row) > config.used(row)
+ : Number(row.QuotaSubscriptions || 0) > Number(row.AtLimitSubscriptions || 0);
+ }
+ if (status === "restricted") {
+ return classId === "compute" && (
+ Boolean(row.semantic?.regionRestricted)
+ || (Array.isArray(row.semantic?.zonesRestricted) && row.semantic.zonesRestricted.length > 0)
+ );
+ }
+ return status === "no-quota"
+ ? config.subscriptionCoverage
+ ? Number(row.QuotaSubscriptions || 0) <= 0
+ : config.total(row) <= 0
+ : true;
+}
+
+function compareCapacityMatrixRows(left, right, classId) {
+ const config = CAPACITY_MATRIX_CONFIG[classId];
+ const priority = (row) => {
+ if (matrixStatusMatches(row, classId, "at-limit")) return 0;
+ if (matrixStatusMatches(row, classId, "restricted")) return 1;
+ if (matrixStatusMatches(row, classId, "in-use")) return 2;
+ if (matrixStatusMatches(row, classId, "available")) return 3;
+ if (matrixStatusMatches(row, classId, "no-quota")) return 4;
+ return 5;
+ };
+ const priorityOrder = priority(left) - priority(right);
+ if (priorityOrder) return priorityOrder;
+ const leftUtilization = Number.isFinite(left.semantic?.utilizationPercent)
+ ? left.semantic.utilizationPercent
+ : -1;
+ const rightUtilization = Number.isFinite(right.semantic?.utilizationPercent)
+ ? right.semantic.utilizationPercent
+ : -1;
+ if (leftUtilization !== rightUtilization) return rightUtilization - leftUtilization;
+ const usedOrder = config.used(right) - config.used(left);
+ if (usedOrder) return usedOrder;
+ const labelOrder = config.label(left).localeCompare(config.label(right), undefined, {
+ numeric: true,
+ sensitivity: "base",
+ });
+ return labelOrder || String(left.Location || "").localeCompare(String(right.Location || ""), undefined, {
+ numeric: true,
+ sensitivity: "base",
+ });
+}
+
+function sortCapacityMatrixRows(rows, classId) {
+ return [...rows].sort((left, right) => compareCapacityMatrixRows(left, right, classId));
+}
+
+function matrixStatusFilters(classId) {
+ return classId === "compute" ? COMPUTE_MATRIX_STATUS_FILTERS : MATRIX_STATUS_FILTERS;
+}
+
+export const FAMILY_STATUS_FILTERS = COMPUTE_MATRIX_STATUS_FILTERS.map((lens) => ({
+ ...lens,
+ match: (row) => matrixStatusMatches(row, "compute", lens.id),
+}));
+
+export function capacityDemandTier(utilizationPercent, mark = DEFAULT_HIGH_WATER_MARK) {
+ if (!Number.isFinite(utilizationPercent)) return "none";
+ if (utilizationPercent >= 100) return "exhausted";
+ return utilizationPercent >= mark ? "over" : "under";
+}
+
+export function familyDemandTier(utilizationPercent, mark = DEFAULT_HIGH_WATER_MARK) {
+ return capacityDemandTier(utilizationPercent, mark);
+}
+
+export function filterCapacityMatrixRows(rows, classId, filter = {}) {
+ const config = CAPACITY_MATRIX_CONFIG[classId];
+ if (!config) return [];
+ const list = Array.isArray(rows) ? rows : [];
+ const status = ["in-use", "at-limit", "available", "restricted", "no-quota", "all"].includes(filter.status)
+ ? filter.status
+ : "all";
+ const needle = String(filter.search || "").trim().toLowerCase();
+ const regions = Array.isArray(filter.regions) ? filter.regions : [];
+ return list.filter((row) => {
+ if (!matrixStatusMatches(row, classId, status)) return false;
+ if (regions.length && !regions.includes(row.Location || "Unknown region")) return false;
+ return !needle || config.searchText(row).toLowerCase().includes(needle);
+ });
+}
+
+export function filterFamilyRows(rows, filter = {}) {
+ return filterCapacityMatrixRows(rows, "compute", filter);
+}
+
+function matrixFilterBar(rows, classId, config, filter, shownCells) {
+ const lenses = matrixStatusFilters(classId);
+ const counts = new Map(lenses.map((lens) => [
+ lens.id,
+ rows.filter((row) => matrixStatusMatches(row, classId, lens.id)).length,
+ ]));
+ const status = uiSegmentedControl({
+ name: "matrix-status",
+ label: "Show",
+ labelId: `${classId}-matrix-status-label`,
+ selected: filter.status,
+ items: lenses.map((lens) => ({
+ value: lens.id,
+ label: lens.label,
+ count: fmtInt(counts.get(lens.id) || 0),
+ })),
+ });
+ const search = uiSearchField({
+ name: "matrix",
+ id: `${classId}-matrix-search`,
+ label: config.searchLabel,
+ value: filter.search,
+ placeholder: config.searchPlaceholder,
+ });
+ const reachable = filterCapacityMatrixRows(rows, classId, { ...filter, regions: [] });
+ const regions = [...new Set(reachable.map((row) => row.Location || "Unknown region"))].sort();
+ const regionControl = regions.length > 1
+ ? uiToggleList({
+ name: "matrix-region",
+ label: "Region",
+ labelId: `${classId}-matrix-region-label`,
+ selected: filter.regions,
+ items: regions.map((region) => ({ value: region, label: region })),
+ })
+ : "";
+ const mark = Number(filter.mark) || DEFAULT_HIGH_WATER_MARK;
+ const markControl = uiSegmentedControl({
+ name: "matrix-mark",
+ label: "High-water mark",
+ labelId: `${classId}-matrix-mark-label`,
+ selected: mark,
+ items: HIGH_WATER_MARKS.map((value) => ({
+ value,
+ label: `${value}%`,
+ count: fmtInt(rows.filter((row) => Number.isFinite(row.semantic?.utilizationPercent)
+ && capacityDemandTier(row.semantic.utilizationPercent, value) !== "under").length),
+ })),
+ });
+ const filtered = filter.status !== "all" || filter.search || filter.regions.length;
+ return uiFilterBar({
+ ariaLabel: `${config.rowHeader} matrix filters`,
+ controls: `${status}${search}${regionControl}${markControl}`,
+ summary: `${fmtInt(shownCells)} of ${fmtInt(rows.length)} cells`,
+ resetLabel: filtered ? "Clear filters" : null,
+ resetAction: "matrix-reset",
+ });
+}
+
+function matrixLegend(classId, mark) {
+ const supplyItems = classId === "compute"
+ ? [
+ ["open", "Region and AZ available"],
+ ["partial", "One or more AZs restricted"],
+ ["blocked", "Region restricted"],
+ ["none", "No quota or offer status"],
+ ]
+ : classId === "app-service" ? [
+ ["open", "All subscriptions have SKU quota"],
+ ["partial", "One or more subscriptions lack quota"],
+ ["blocked", "One or more subscriptions are at limit"],
+ ["none", "No SKU quota reported"],
+ ] : [
+ ["open", "All subscriptions have usable quota"],
+ ["partial", "One or more subscriptions lack usable quota"],
+ ["blocked", "One or more subscriptions are at limit"],
+ ["none", "No usable quota reported"],
+ ];
+ const supply = supplyItems.map(([id, label]) =>
+ ` ${esc(label)} `
+ ).join("");
+ const demand = [
+ ["under", `Under ${mark}%`],
+ ["over", `Over ${mark}% mark`],
+ ["exhausted", "At or over 100%"],
+ ].map(([id, label]) =>
+ `00% ${esc(label)} `
+ ).join("");
+ return `
+
${classId === "compute" ? "Offer status" : "Quota status"}, the left bar
+
Quota utilization, the percentage
+
`;
+}
+
+function matrixAlarm(semantic, mark) {
+ const tier = capacityDemandTier(semantic.utilizationPercent, mark);
+ const note = tier === "over" ? `Over ${mark}% mark `
+ : tier === "exhausted" ? `Quota exhausted `
+ : "";
+ return { tier, note };
+}
+
+function computeMatrixCell(row, label, region, mark) {
+ const semantic = row.semantic || {};
+ const detail = Number.isFinite(semantic.headroomCores) ? `${fmtInt(semantic.headroomCores)} cores free` : "";
+ const { tier, note } = matrixAlarm(semantic, mark);
+ const statusClass = semantic.offerState === "region-restricted" ? "danger"
+ : semantic.offerState === "zone-restricted" ? "warning"
+ : semantic.offerState === "available" ? "available"
+ : "muted";
+ const zones = (semantic.zoneStates || []).map((item) =>
+ `AZ ${esc(item.zone)} · ${item.restricted ? "Restricted" : "Available"} `
+ ).join("");
+ const representative = semantic.representativeSkus?.length ? semantic.representativeSkus.join(", ") : "not reported";
+ const title = `${label} · ${region} · ${fmtInt(row.CoresUsed)} of ${fmtInt(row.CoresTotal)} cores · ${semantic.offerText} · Representative SKU: ${representative}`;
+ return `
+ ${esc(semantic.text || "Not reported")}
+ ${esc(semantic.offerText || "Offer status not reported")}
+ ${zones}${note}${esc(detail)}
+ `;
+}
+
+function appServiceMatrixCell(row, label, region, mark) {
+ const semantic = row.semantic || {};
+ const detail = Number.isFinite(semantic.headroomInstances) ? `${fmtInt(semantic.headroomInstances)} instances free` : "";
+ const { tier, note } = matrixAlarm(semantic, mark);
+ const statusClass = semantic.supply === "blocked" ? "danger"
+ : semantic.supply === "partial" ? "warning"
+ : semantic.supply === "open" ? "available"
+ : "muted";
+ const title = `${label} · ${region} · ${fmtInt(row.UsedInstances)} of ${fmtInt(row.QuotaInstances)} instances · ${semantic.quotaText}`;
+ return `
+ ${esc(semantic.text || "Not reported")}
+ ${esc(semantic.quotaText || "Quota not reported")}
+ ${note}${esc(detail)}
+ `;
+}
+
+function azureSqlMatrixCell(row, label, region, mark) {
+ const semantic = row.semantic || {};
+ const detail = Number.isFinite(semantic.headroomUnits)
+ ? `${fmtInt(semantic.headroomUnits)} ${semantic.unitLabel || "units"} free`
+ : "";
+ const { tier, note } = matrixAlarm(semantic, mark);
+ const statusClass = semantic.supply === "blocked" ? "danger"
+ : semantic.supply === "partial" ? "warning"
+ : semantic.supply === "open" ? "available"
+ : "muted";
+ const title = `${label} · ${region} · ${fmtInt(row.Used)} of ${fmtInt(row.Quota)} ${semantic.unitLabel || "units"} · ${semantic.quotaText}`;
+ return `
+ ${esc(semantic.text || "Not reported")}
+ ${esc(semantic.quotaText || "Quota not reported")}
+ ${note}${esc(detail)}
+ `;
+}
+
+function azureAiMatrixCell(row, label, region, mark) {
+ const semantic = row.semantic || {};
+ const detail = Number.isFinite(semantic.headroomUnits)
+ ? `${fmtInt(semantic.headroomUnits)} ${semantic.unitLabel || "units"} free`
+ : "";
+ const { tier, note } = matrixAlarm(semantic, mark);
+ const statusClass = semantic.supply === "blocked" ? "danger"
+ : semantic.supply === "partial" ? "warning"
+ : semantic.supply === "open" ? "available"
+ : "muted";
+ const title = `${label} · ${region} · ${fmtInt(row.Used)} of ${fmtInt(row.Quota)} ${semantic.unitLabel || "units"} · ${semantic.quotaText}`;
+ return `
+ ${esc(semantic.text || "Not reported")}
+ ${esc(semantic.quotaText || "Quota not reported")}
+ ${note}${esc(detail)}
+ `;
+}
+
+function capacityMatrix(payload) {
+ const config = CAPACITY_MATRIX_CONFIG[payload.classId];
+ const matrix = payload[config.payloadKey] || {};
+ if (matrix.status === "heatmap-disabled") {
+ return `${esc(config.disabled)} More than ${fmtInt(matrix.limit)} ${esc(config.pairLabel)} matched. Narrow the subscription or region filter.
`;
+ }
+ const rows = matrix.rows || [];
+ if (!rows.length) return `${esc(config.empty)}
`;
+ const filter = capacityMatrixFilter(payload.classId, rows);
+ const visible = sortCapacityMatrixRows(
+ filterCapacityMatrixRows(rows, payload.classId, filter),
+ payload.classId,
+ );
+ const filterBar = matrixFilterBar(rows, payload.classId, config, filter, visible.length);
+ if (!visible.length) {
+ return `${filterBar}No ${esc(config.pairLabel)} match these filters. Clear them to see all ${fmtInt(rows.length)} cells.
`;
+ }
+ const matrixRows = [...new Map(visible.map((row) => [
+ config.key(row),
+ { key: config.key(row), label: config.label(row), title: config.key(row) },
+ ])).values()];
+ const regions = [...new Set(visible.map((row) => row.Location || "Unknown region"))].sort();
+ const cells = new Map(visible.map((row) => [`${config.key(row)}|${row.Location || "Unknown region"}`, row]));
+ const mark = Number(filter.mark) || DEFAULT_HIGH_WATER_MARK;
+ const noteId = `${payload.classId}-matrix-note`;
+ return `${filterBar}
+ ${esc(config.description)}
+ ${matrixLegend(payload.classId, mark)}
+ ${uiDataMatrix({
+ ariaLabel: config.ariaLabel,
+ descriptionId: noteId,
+ rowHeader: config.rowHeader,
+ rows: matrixRows,
+ columns: regions,
+ renderCell: (matrixRow, region) => {
+ const row = cells.get(`${matrixRow.key}|${region}`);
+ if (!row) return "";
+ if (payload.classId === "compute") return computeMatrixCell(row, matrixRow.label, region, mark);
+ if (payload.classId === "app-service") return appServiceMatrixCell(row, matrixRow.label, region, mark);
+ if (payload.classId === "azure-ai") return azureAiMatrixCell(row, matrixRow.label, region, mark);
+ return azureSqlMatrixCell(row, matrixRow.label, region, mark);
+ },
+ })}`;
+}
+
+function capacityMatrixDetail(payload) {
+ const config = CAPACITY_MATRIX_CONFIG[payload.classId];
+ const rows = sortCapacityMatrixRows(
+ filterCapacityMatrixRows(payload[config.payloadKey]?.rows || [], payload.classId, capacityMatrixFilter(payload.classId)),
+ payload.classId,
+ );
+ if (!rows.length) return `No ${esc(config.pairLabel)} match the filters above.
`;
+ const pageSize = 50;
+ const totalPages = Math.ceil(rows.length / pageSize);
+ const page = Math.min(state.capacityMatrixPage, totalPages);
+ const pageRows = rows.slice((page - 1) * pageSize, page * pageSize);
+ const columns = payload.classId === "compute"
+ ? [
+ { label: "VM family", align: "left", get: (row) => esc(row.Family || row.FamilyKey || "—") },
+ { label: "Region", align: "left", get: (row) => esc(row.Location || "—") },
+ { label: "Used cores", get: (row) => fmtInt(row.CoresUsed) },
+ { label: "Quota", get: (row) => fmtInt(row.CoresTotal) },
+ { label: "Headroom", get: (row) => Number.isFinite(row.semantic?.headroomCores) ? fmtInt(row.semantic.headroomCores) : "—" },
+ { label: "Subscriptions", get: (row) => fmtInt(row.Subscriptions) },
+ { label: "Utilization", get: (row) => esc(row.semantic?.text || "—") },
+ { label: "Quota status", align: "left", get: (row) => capacityStateToken(row.semantic) },
+ { label: "Offer status", align: "left", get: (row) => esc(row.semantic?.offerText || "Not reported") },
+ { label: "Availability zones", align: "left", get: (row) => esc((row.semantic?.zoneStates || []).map((item) => `AZ ${item.zone} ${item.restricted ? "Restricted" : "Available"}`).join(", ") || "None") },
+ { label: "Representative SKU", align: "left", get: (row) => esc(row.semantic?.representativeSkus?.join(", ") || "Not reported") },
+ ]
+ : payload.classId === "app-service" ? [
+ { label: "Plan SKU", align: "left", get: (row) => esc(row.Sku || row.SkuKey || "—") },
+ { label: "Region", align: "left", get: (row) => esc(row.Location || "—") },
+ { label: "Used instances", get: (row) => fmtInt(row.UsedInstances) },
+ { label: "Quota", get: (row) => fmtInt(row.QuotaInstances) },
+ { label: "Headroom", get: (row) => Number.isFinite(row.semantic?.headroomInstances) ? fmtInt(row.semantic.headroomInstances) : "—" },
+ { label: "Subscriptions", get: (row) => fmtInt(row.Subscriptions) },
+ { label: "At limit", get: (row) => fmtInt(row.AtLimitSubscriptions) },
+ { label: "No quota", get: (row) => fmtInt(row.NoQuotaSubscriptions) },
+ { label: "Utilization", get: (row) => esc(row.semantic?.text || "—") },
+ { label: "Quota coverage", align: "left", get: (row) => esc(row.semantic?.quotaText || "Not reported") },
+ ] : payload.classId === "azure-sql" ? [
+ { label: "Quota metric", align: "left", get: (row) => esc(row.Metric || row.MetricKey || "—") },
+ { label: "Region", align: "left", get: (row) => esc(row.Location || "—") },
+ { label: "Used", get: (row) => fmtInt(row.Used) },
+ { label: "Quota", get: (row) => fmtInt(row.Quota) },
+ { label: "Headroom", get: (row) => Number.isFinite(row.semantic?.headroomUnits) ? fmtInt(row.semantic.headroomUnits) : "—" },
+ { label: "Unit", align: "left", get: (row) => esc(row.semantic?.unitLabel || row.Unit || "—") },
+ { label: "Subscriptions", get: (row) => fmtInt(row.Subscriptions) },
+ { label: "At limit", get: (row) => fmtInt(row.AtLimitSubscriptions) },
+ { label: "No usable quota", get: (row) => fmtInt(row.NoQuotaSubscriptions) },
+ { label: "Negative limit", get: (row) => fmtInt(row.NegativeLimitSubscriptions) },
+ { label: "Utilization", get: (row) => esc(row.semantic?.text || "—") },
+ { label: "Quota coverage", align: "left", get: (row) => esc(row.semantic?.quotaText || "Not reported") },
+ ] : [
+ { label: "Model", align: "left", get: (row) => esc(row.Model || row.ModelKey || "—") },
+ { label: "Region", align: "left", get: (row) => esc(row.Location || "—") },
+ { label: "Used", get: (row) => fmtInt(row.Used) },
+ { label: "Quota", get: (row) => fmtInt(row.Quota) },
+ { label: "Headroom", get: (row) => Number.isFinite(row.semantic?.headroomUnits) ? fmtInt(row.semantic.headroomUnits) : "—" },
+ { label: "Subscriptions", get: (row) => fmtInt(row.Subscriptions) },
+ { label: "At limit", get: (row) => fmtInt(row.AtLimitSubscriptions) },
+ { label: "No usable quota", get: (row) => fmtInt(row.NoQuotaSubscriptions) },
+ { label: "Utilization", get: (row) => esc(row.semantic?.text || "—") },
+ { label: "Quota coverage", align: "left", get: (row) => esc(row.semantic?.quotaText || "Not reported") },
+ ];
+ const table = `${tableHtml(columns, pageRows, `No ${config.pairLabel} match the filters above.`)}
`;
+ const pagination = uiPagination({
+ name: "matrix",
+ page,
+ totalPages,
+ label: `${config.detailTab} pages`,
+ });
+ return `${fmtInt(rows.length)} matching ${esc(config.pairLabel)} · Highest risk and utilization first
${table}${pagination}`;
+}
+
+function capacitySubscriptionDetail(payload) {
+ const config = CAPACITY_MATRIX_CONFIG[payload.classId];
+ const search = `
+ ${uiSearchField({
+ name: "subscription",
+ id: "capacity-subscription-search",
+ label: "Subscription",
+ value: state.capacitySubscriptionSearch,
+ placeholder: "Search by subscription ID",
+ })}
+ Matches the Show, ${esc(config.searchLabel)}, and region filters above.
+
`;
+ if (state.capacitySubscriptionLoading) return `${search}Loading matching subscriptions…
`;
+ if (state.capacitySubscriptionError) {
+ return `${search}Subscriptions unavailable. ${esc(state.capacitySubscriptionError)}
`;
+ }
+ const data = state.capacitySubscriptionData;
+ if (!data) return `${search}Select this tab to load matching subscriptions.
`;
+ const rows = data.rows || [];
+ const totalPages = Number(data.totalPages || 0);
+ const summary = `${fmtInt(data.totalSubscriptions)} matching subscriptions
`;
+ if (!rows.length) return `${search}${summary}No subscription matches these filters.
`;
+ const columns = payload.classId === "compute"
+ ? [
+ { label: "Subscription ID", align: "left", get: (row) => `${esc(row.SubscriptionId || "—")} ` },
+ { label: "Families", get: (row) => fmtInt(row.Families) },
+ { label: "Regions", get: (row) => fmtInt(row.Regions) },
+ { label: "Used cores", get: (row) => fmtInt(row.CoresUsed) },
+ { label: "Quota", get: (row) => fmtInt(row.CoresTotal) },
+ { label: "Headroom", get: (row) => row.HeadroomCores != null && Number.isFinite(Number(row.HeadroomCores)) ? fmtInt(row.HeadroomCores) : "—" },
+ { label: "Last ingested", get: (row) => row.LastIngestion ? esc(fmtRelativeTime(new Date(row.LastIngestion))) : "—" },
+ ]
+ : payload.classId === "app-service" ? [
+ { label: "Subscription ID", align: "left", get: (row) => `${esc(row.SubscriptionId || "—")} ` },
+ { label: "SKUs", get: (row) => fmtInt(row.Skus) },
+ { label: "Regions", get: (row) => fmtInt(row.Regions) },
+ { label: "SKU-region pairs", get: (row) => fmtInt(row.SkuRegionPairs) },
+ { label: "In use", get: (row) => fmtInt(row.InUsePairs) },
+ { label: "At limit", get: (row) => fmtInt(row.AtLimitPairs) },
+ { label: "No quota", get: (row) => fmtInt(row.NoQuotaPairs) },
+ { label: "Last ingested", get: (row) => row.LastIngestion ? esc(fmtRelativeTime(new Date(row.LastIngestion))) : "—" },
+ ] : payload.classId === "azure-sql" ? [
+ { label: "Subscription ID", align: "left", get: (row) => `${esc(row.SubscriptionId || "—")} ` },
+ { label: "Quotas", get: (row) => fmtInt(row.Metrics) },
+ { label: "Regions", get: (row) => fmtInt(row.Regions) },
+ { label: "Quota-region pairs", get: (row) => fmtInt(row.MetricRegionPairs) },
+ { label: "In use", get: (row) => fmtInt(row.InUsePairs) },
+ { label: "At limit", get: (row) => fmtInt(row.AtLimitPairs) },
+ { label: "No usable quota", get: (row) => fmtInt(row.NoQuotaPairs) },
+ { label: "Negative limit", get: (row) => fmtInt(row.NegativeLimitPairs) },
+ { label: "Last ingested", get: (row) => row.LastIngestion ? esc(fmtRelativeTime(new Date(row.LastIngestion))) : "—" },
+ ] : [
+ { label: "Subscription ID", align: "left", get: (row) => `${esc(row.SubscriptionId || "—")} ` },
+ { label: "Models", get: (row) => fmtInt(row.Models) },
+ { label: "Regions", get: (row) => fmtInt(row.Regions) },
+ { label: "Model-region pairs", get: (row) => fmtInt(row.ModelRegionPairs) },
+ { label: "In use", get: (row) => fmtInt(row.InUsePairs) },
+ { label: "At limit", get: (row) => fmtInt(row.AtLimitPairs) },
+ { label: "No usable quota", get: (row) => fmtInt(row.NoQuotaPairs) },
+ { label: "Last ingested", get: (row) => row.LastIngestion ? esc(fmtRelativeTime(new Date(row.LastIngestion))) : "—" },
+ ];
+ const table = `${tableHtml(columns, rows, "No subscription matches these filters.")}
`;
+ return `${search}${summary}${table}${uiPagination({
+ name: "subscriptions",
+ page: Number(data.page || 1),
+ totalPages,
+ label: "Subscription pages",
+ })}`;
+}
+
+function capacityMatrixDetailTabs(payload) {
+ const config = CAPACITY_MATRIX_CONFIG[payload.classId];
+ const tab = state.capacityDetailTab;
+ return uiTabList({
+ name: "capacity-detail",
+ label: `${payload.contract?.title || payload.classId} detail`,
+ tabs: [
+ { id: "matrix", label: config.detailTab },
+ { id: "subscriptions", label: "Subscriptions" },
+ ],
+ active: tab,
+ panelId: "capacity-detail-panel",
+ panel: tab === "subscriptions" ? capacitySubscriptionDetail(payload) : capacityMatrixDetail(payload),
+ });
+}
+
+function capacityHistory(payload) {
+ const history = payload.history || {};
+ if (history.status === "no-selection") return `Select one exact source row to view its observed history.
`;
+ if (history.status === "disabled") return `History is disabled. ${esc(history.reasonCode || "")}
`;
+ if (history.mode === "current-only") {
+ return `Collecting ${payload.contract?.quotaType === "inventory" ? "inventory" : "quota"} history — 1 day available. Trend, growth, forecast, runway, and breach dates remain disabled.
`;
+ }
+ return tableHtml([
+ { label: "UTC day", align: "left", get: (row) => esc(String(row.Day || "").slice(0, 10)) },
+ { label: "Current", get: (row) => formatCapacityValue(row.currentValue) },
+ { label: "Limit", get: (row) => payload.contract?.quotaType === "inventory" ? "Not applicable" : formatCapacityValue(row.limit) },
+ { label: "Unit", get: (row) => payload.classId === "premium-ssd-v2" ? "GiB" : esc(row.unit || "—") },
+ { label: "Ingested", get: (row) => esc(String(row.x_IngestionTime || "")) },
+ ], history.points || [], "No history is available for this exact source key.");
+}
+
+function capacityDemandHistory(payload) {
+ const series = payload.series || {};
+ if (series.status === "disabled") {
+ return `Billed-demand series disabled. ${esc(series.reasonCode || "")}
`;
+ }
+ if (series.status === "no-selection") {
+ return `Select one exact meter, unit, price, and currency series. Different meters and currencies are never combined.
`;
+ }
+ const isDisk = payload.classId === "premium-ssd-v2";
+ return tableHtml([
+ { label: "UTC day", align: "left", get: (row) => esc(String(row.Day || "").slice(0, 10)) },
+ ...(isDisk ? [] : [{ label: "Billed quantity", get: (row) => formatCapacityValue(row.BilledQuantity) }]),
+ { label: "Unit", get: (row) => isDisk ? "Not classified" : esc(row.ConsumedUnit || series.unit || "—") },
+ { label: "Effective cost", get: (row) => `${formatCapacityValue(row.EffectiveCost)} ${esc(row.BillingCurrency || "")}` },
+ { label: "Rows", get: (row) => fmtInt(row.Rows) },
+ ], series.points || [], "No billed usage matched this exact series.");
+}
+
+function capacityReconciliation(payload) {
+ const rows = payload.reconciliation?.rows || [];
+ return tableHtml([
+ { label: "Capacity reservation group", align: "left", get: (row) => `${esc(row.GroupName || trunc(row.GroupResourceId, 36))} ` },
+ { label: "Match", align: "left", get: (row) => esc(row.ReconciliationState || "unknown") },
+ { label: "Used hours", get: (row) => formatCapacityValue(row.UsedHours) },
+ { label: "Unused hours", get: (row) => formatCapacityValue(row.UnusedHours) },
+ { label: "Reservations", get: (row) => fmtInt(row.ReservationCount) },
+ { label: "Linked resources", get: (row) => fmtInt(row.LinkedResources) },
+ { label: "Currency", get: (row) => esc(row.BillingCurrency || "—") },
+ ], rows, "No capacity reservation inventory or linked billing data is available.");
+}
+
+function renderCapacity(payload) {
+ const content = el("content");
+ if (!payload) return;
+ if (payload.error) return renderError(payload);
+ const nav = capacityNavigationHtml();
+ if (payload.classId === "home") {
+ content.innerHTML = `${nav}
+
+ ${capacityPanel("Quota coverage", "Seven independent quota areas; no combined health score or ranking.", capacityHomeTable(payload.classes))}
+ `;
+ return;
+ }
+
+ const rows = payload.table?.rows || [];
+ const statusCounts = rows.reduce((counts, row) => {
+ const key = row.semantic?.state || "unclassified";
+ counts[key] = (counts[key] || 0) + 1;
+ return counts;
+ }, {});
+ const enabledCount = rows.filter((row) => row.semantic?.capability === "enabled").length;
+ const coverage = payload.coverage || {};
+ const notReported = coverage.state === "not-reported"
+ ? `Not reported — collection outcome unknown. ${esc(payload.contract?.emptyLabel || "")}
`
+ : "";
+ const schemaWarnings = [payload.schema?.quota, payload.schema?.costs]
+ .filter((schema) => schema && !schema.available)
+ .map((schema) => `${schema.source}: ${schema.missingFields.join(", ")}`);
+ const schemaNotice = schemaWarnings.length
+ ? `Source fields unavailable. ${esc(schemaWarnings.join(" · "))}
`
+ : "";
+ const quotaSelectors = payload.selectors?.items || [];
+ const demandSelectors = payload.demand?.selectors?.items || [];
+ const familyRows = payload.familyHeatmap?.rows || [];
+ const appServiceRows = payload.appServiceHeatmap?.rows || [];
+ const azureSqlRows = payload.azureSqlHeatmap?.rows || [];
+ const azureAiRows = payload.azureAiHeatmap?.rows || [];
+ const matrixClass = Boolean(CAPACITY_MATRIX_CONFIG[payload.classId]);
+ const kpis = payload.classId === "compute"
+ ? [
+ kpiCard("Family-region pairs", fmtInt(familyRows.length), "Estate totals; subscriptions are aggregated before display"),
+ kpiCard("In use", fmtInt(familyRows.filter((row) => matrixStatusMatches(row, "compute", "in-use")).length), "Family and region pairs using cores"),
+ kpiCard("At limit", fmtInt(familyRows.filter((row) => matrixStatusMatches(row, "compute", "at-limit")).length), "Provider-reported usage is at or over quota"),
+ kpiCard("No quota", fmtInt(familyRows.filter((row) => matrixStatusMatches(row, "compute", "no-quota")).length), "No regional family quota"),
+ ].join("")
+ : payload.classId === "app-service"
+ ? [
+ kpiCard("Quota-region pairs", fmtInt(appServiceRows.length), "Exact plan SKU and Total Regional VMs rows"),
+ kpiCard("In use", fmtInt(appServiceRows.filter((row) => matrixStatusMatches(row, "app-service", "in-use")).length), "SKU and region pairs using instances"),
+ kpiCard("At limit", fmtInt(appServiceRows.filter((row) => matrixStatusMatches(row, "app-service", "at-limit")).length), "One or more subscriptions are at quota"),
+ kpiCard("No quota", fmtInt(appServiceRows.filter((row) => matrixStatusMatches(row, "app-service", "no-quota")).length), "No subscription has quota for the SKU and region"),
+ ].join("")
+ : payload.classId === "azure-sql"
+ ? [
+ kpiCard("Quota-region pairs", fmtInt(azureSqlRows.length), "Current supported regional quota metrics"),
+ kpiCard("In use", fmtInt(azureSqlRows.filter((row) => matrixStatusMatches(row, "azure-sql", "in-use")).length), "Quota and region pairs with provider-reported usage"),
+ kpiCard("At limit", fmtInt(azureSqlRows.filter((row) => matrixStatusMatches(row, "azure-sql", "at-limit")).length), "One or more subscriptions are at quota"),
+ kpiCard("No usable quota", fmtInt(azureSqlRows.filter((row) => matrixStatusMatches(row, "azure-sql", "no-quota")).length), "Only zero, negative, or missing limits were reported"),
+ ].join("")
+ : payload.classId === "azure-ai"
+ ? [
+ kpiCard("Model-region pairs", fmtInt(azureAiRows.length), "Exact model, deployment tier, and region rows"),
+ kpiCard("In use", fmtInt(azureAiRows.filter((row) => matrixStatusMatches(row, "azure-ai", "in-use")).length), "Model and region pairs with provider-reported usage"),
+ kpiCard("At limit", fmtInt(azureAiRows.filter((row) => matrixStatusMatches(row, "azure-ai", "at-limit")).length), "One or more subscriptions are at quota"),
+ kpiCard("No usable quota", fmtInt(azureAiRows.filter((row) => matrixStatusMatches(row, "azure-ai", "no-quota")).length), "No subscription reported usable quota for the model and region"),
+ ].join("")
+ : [
+ kpiCard("Observations", fmtInt(coverage.observations), `${fmtInt(coverage.resources)} current resource keys`, undefined, undefined, "reference"),
+ kpiCard("Snapshot days", fmtInt(coverage.distinctDays), coverage.distinctDays < 2 ? "No trend can be inferred" : "Compatible history is evaluated per exact key"),
+ kpiCard("Latest ingestion", coverage.lastObservation ? esc(fmtRelativeTime(new Date(coverage.lastObservation))) : "—", "ADX arrival time, not provider observation time"),
+ kpiCard("Enabled", fmtInt(enabledCount), "Rows with approved semantics"),
+ kpiCard("Unclassified", fmtInt(statusCounts.unclassified), "Raw rows retained; registry review required"),
+ kpiCard("Stale", fmtInt(statusCounts.stale), "Older than 48 hours; arithmetic disabled"),
+ ].join("");
+ const selectors = payload.classId === "compute"
+ ? capacitySelectorHtml("metric", payload.classId, quotaSelectors, state.capacitySelections.metricSelection)
+ : matrixClass
+ ? ""
+ : `${capacitySelectorHtml("quota", payload.classId, quotaSelectors, state.capacitySelections.quotaSelection)}
+ ${capacitySelectorHtml("demand", payload.classId, demandSelectors, state.capacitySelections.demandSelection)}`;
+
+ content.innerHTML = `${nav}
+
+ ${notReported}${schemaNotice}
+ Next action: ${esc(CAPACITY_ACTIONS[payload.classId] || "Review the source rows before taking action.")}
+ ${kpis}
+ ${selectors ? `${selectors}
` : ""}
+
+ ${matrixClass
+ ? capacityPanel(CAPACITY_MATRIX_CONFIG[payload.classId].panelTitle, CAPACITY_MATRIX_CONFIG[payload.classId].panelSubtitle, capacityMatrix(payload), true)
+ : ""}
+ ${matrixClass
+ ? capacityPanel("Filtered quota detail", "Every row matches the matrix controls above. Switch to Subscriptions for server-paged detail across the full estate.", capacityMatrixDetailTabs(payload), true)
+ : capacityPanel("Current quota", `${payload.table?.rowLimit || 250}-row bound${payload.table?.truncated ? " reached" : ""}. Raw rows remain visible when calculations are disabled.`, capacityCurrentTable(payload))}
+ ${matrixClass ? "" : capacityPanel("Observed history", "Ingestion time is ADX arrival time. Missing days are not inferred.", capacityHistory(payload))}
+ ${["app-service", "azure-sql"].includes(payload.classId) ? "" : capacityPanel("Subscription × region", "Quota color is available only for exact enabled metrics. Inventory uses neutral density.", capacityHeatmap(payload))}
+ ${matrixClass ? "" : capacityPanel("Parallel billed demand", payload.demand?.capability?.sourceNote || "Billed usage stays separate from quota.", capacityDemandHistory(payload))}
+ ${payload.classId === "capacity-reservations"
+ ? capacityPanel("Inventory and billing reconciliation", "Used and Unused are accounting statuses, not reserved-capacity utilization.", capacityReconciliation(payload))
+ : ""}
+
+ `;
+}
+
+function renderError(p) {
+ if (state.tab === "foundry" || state.tab === "agents") {
+ el("content").innerHTML = `
+
Can’t load Azure AI operations
+
Set the tenant ID in Settings, then sign in to that tenant with Azure CLI.
+
+ Show error detail
+ ${esc(p.error)}
+
+
`;
+ return;
+ }
+ el("content").innerHTML = `
+
Can’t reach the FinOps hub
+
The dashboard queried ${esc(p.clusterUri || "")} (database ${esc(p.database || "Hub")}) but the request failed.
+
+
Start the Kusto emulator, then run:
+
+ Initialize-FinOpsHubLocal
+ Copy
+
+
Then refresh this dashboard.
+
+
+ Show error detail
+ ${esc(p.error)}
+
+
`;
+}
+
+/* ------------------------------------------------------- experimental tabs */
+
+const KUSTO_MONACO_VERSION = "15.0.0";
+
+let _monacoEditor = null;
+let _monacoModel = null;
+let _monacoApi = null;
+
+/**
+ * @kusto/monaco-kusto's jsdelivr `+esm` bundle imports its own pinned copy of
+ * "monaco-editor" by exact CDN URL (version + subpath baked in at jsdelivr's
+ * build time). Since browser ES module caching is keyed by exact URL string,
+ * importing monaco-editor via any other URL -- even the "same" version --
+ * yields a second, unrelated monaco instance, and `monaco.languages.kusto`
+ * never registers on the one our own code holds. So instead of guessing a
+ * monaco-editor version/path, discover the exact specifier kusto-monaco uses
+ * and import through that.
+ */
+async function resolveSharedMonacoEditorUrl() {
+ const kustoBundleUrl = `https://cdn.jsdelivr.net/npm/@kusto/monaco-kusto@${KUSTO_MONACO_VERSION}/+esm`;
+ const kustoBundleSrc = await fetch(kustoBundleUrl).then((r) => r.text());
+ const match = /from"(\/npm\/monaco-editor@[^"]+)"/.exec(kustoBundleSrc);
+ if (!match) throw new Error("could not locate monaco-editor import in @kusto/monaco-kusto bundle");
+ return { kustoBundleUrl, monacoEditorUrl: `https://cdn.jsdelivr.net${match[1]}` };
+}
+
+/**
+ * Chromium refuses to construct a Worker (classic or module) from a
+ * cross-origin script URL at all, even with permissive CORS headers -- so
+ * `new Worker("https://cdn.jsdelivr.net/...")` throws a SecurityError
+ * unconditionally. Work around this by fetching the script ourselves and
+ * handing the browser a same-origin `blob:` URL instead. jsdelivr's `+esm`
+ * bundles reference their own dependencies via root-relative specifiers
+ * (e.g. `"/npm/..."`), which don't resolve against a `blob:` base, so those
+ * are rewritten to fully-qualified jsdelivr URLs first.
+ */
+async function blobWorkerUrl(scriptUrl) {
+ let src = await fetch(scriptUrl).then((r) => r.text());
+ src = src.replace(/(["'])\/npm\//g, "$1https://cdn.jsdelivr.net/npm/");
+ return URL.createObjectURL(new Blob([src], { type: "text/javascript" }));
+}
+
+function disposeMonacoEditor() {
+ // editor.dispose() only tears down the view widget -- the text model is a
+ // separate disposable and leaks (along with its worker) if not disposed
+ // too, which matters here since renderMonacoTab() re-creates both every
+ // time the tab is (re-)entered, e.g. after a cluster switch.
+ if (_monacoEditor) {
+ try { _monacoEditor.dispose(); } catch { /* best-effort cleanup */ }
+ _monacoEditor = null;
+ }
+ if (_monacoModel) {
+ try { _monacoModel.dispose(); } catch { /* best-effort cleanup */ }
+ _monacoModel = null;
+ }
+}
+
+async function renderMonacoTab() {
+ const content = el("content");
+ content.innerHTML = `
+
+ `;
+
+ const statusEl = el("monaco-status");
+ const hostEl = el("monaco-host");
+
+ try {
+ if (!_monacoApi) {
+ statusEl.textContent = "Loading query editor + KQL language support from CDN…";
+ const { kustoBundleUrl, monacoEditorUrl } = await resolveSharedMonacoEditorUrl();
+ const monacoBase = monacoEditorUrl.replace(/\/esm\/.*$/, "");
+ // Import monaco-editor via the exact URL @kusto/monaco-kusto itself
+ // imports it from, so both packages share one module instance
+ // (required for monaco.languages.kusto to register on our copy).
+ _monacoApi = await import(monacoEditorUrl);
+ const [genericWorkerUrl, kustoWorkerUrl] = await Promise.all([
+ blobWorkerUrl(`${monacoBase}/esm/vs/editor/editor.worker.js/+esm`),
+ blobWorkerUrl(`https://cdn.jsdelivr.net/npm/@kusto/monaco-kusto@${KUSTO_MONACO_VERSION}/release/esm/kusto.worker.js/+esm`),
+ ]);
+ self.MonacoEnvironment = {
+ getWorker(_moduleId, label) {
+ return new Worker(label === "kusto" ? kustoWorkerUrl : genericWorkerUrl, { type: "module" });
+ },
+ };
+ await import(kustoBundleUrl);
+ }
+ const monaco = _monacoApi;
+
+ disposeMonacoEditor();
+ // Seed from whatever was last saved server-side (survives page reloads,
+ // including the host restarting this extension's server process), not a
+ // hardcoded sample -- see saveQueryState() below for how it gets there.
+ const initialQuery = (window.__cfg && window.__cfg.lastQuery) || "Costs\n| take 20";
+ const model = monaco.editor.createModel(initialQuery, "kusto");
+ _monacoModel = model;
+ _monacoEditor = monaco.editor.create(hostEl, {
+ model,
+ theme: document.documentElement.getAttribute("data-color-mode") === "dark" ? "vs-dark" : "vs",
+ automaticLayout: true,
+ minimap: { enabled: false },
+ fontSize: 13,
+ });
+ _monacoEditor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, () => runMonacoQuery());
+ _monacoEditor.onDidChangeModelContent(() => scheduleQueryStateSave(_monacoEditor.getValue()));
+
+ statusEl.textContent = "Fetching database schema…";
+ try {
+ const cfg = window.__cfg || {};
+ const schemaRes = await fetch("/api/schema").then((r) => r.json());
+ const kustoLang = monaco.languages?.kusto;
+ if (schemaRes.schema && kustoLang?.getKustoWorker) {
+ const workerAccessor = await kustoLang.getKustoWorker();
+ const worker = await workerAccessor(model.uri);
+ await worker.setSchemaFromShowSchema(schemaRes.schema, cfg.clusterUri || "", cfg.database || "Hub");
+ statusEl.textContent = `Ready — schema loaded from ${esc(cfg.database || "Hub")}.`;
+ } else {
+ statusEl.textContent = schemaRes.error
+ ? `Ready — schema unavailable: ${esc(schemaRes.error)}`
+ : "Ready — KQL language service didn't register (autocomplete may be limited).";
+ }
+ } catch (schemaErr) {
+ statusEl.textContent = `Ready — schema load failed: ${esc(schemaErr.message || String(schemaErr))}`;
+ }
+ } catch (err) {
+ // Graceful fallback: never leave the tab blank if the CDN load fails
+ // (e.g. cross-origin module workers unsupported in this webview).
+ const initialQuery = (window.__cfg && window.__cfg.lastQuery) || "Costs\n| take 20";
+ hostEl.innerHTML = ``;
+ el("monaco-fallback").addEventListener("input", (e) => scheduleQueryStateSave(e.target.value));
+ statusEl.textContent = `Query editor failed to load here (${esc(err.message || String(err))}) — using a plain text editor instead.`;
+ }
+ el("monaco-run").addEventListener("click", () => runMonacoQuery());
+}
+
+// Debounced autosave of the query editor's text to the server (see
+// /api/query-state in extension.mjs), so an in-progress, unrun query
+// survives a page reload -- e.g. the host restarting this extension's server
+// process, which reassigns its ephemeral port and forces a fresh load.
+let _queryStateSaveTimer = null;
+function scheduleQueryStateSave(query) {
+ clearTimeout(_queryStateSaveTimer);
+ _queryStateSaveTimer = setTimeout(() => {
+ fetch("/api/query-state", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ query }),
+ }).catch(() => { /* best-effort; the next successful save will catch up */ });
+ }, 600);
+}
+
+async function runMonacoQuery() {
+ const runBtn = el("monaco-run");
+ const statusEl = el("monaco-status");
+ const resultEl = el("monaco-result");
+ const kql = _monacoEditor ? _monacoEditor.getValue().trim() : (el("monaco-fallback")?.value || "").trim();
+ if (!kql) return;
+ runBtn.disabled = true;
+ const prevStatus = statusEl.textContent;
+ statusEl.textContent = "Running…";
+ try {
+ const res = await fetch("/api/kql", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ kql }),
+ });
+ const data = await res.json();
+ if (data.error) {
+ resultEl.innerHTML = `${esc(data.error)}
`;
+ } else {
+ const rows = data.rows || [];
+ if (!rows.length) {
+ resultEl.innerHTML = `Query returned no rows.
`;
+ } else {
+ const cols = Object.keys(rows[0]);
+ const head = cols.map((c) => `${esc(c)} `).join("");
+ const body = rows.slice(0, 200).map((r) =>
+ `${cols.map((c) => `${esc(String(r[c] ?? ""))} `).join("")} `
+ ).join("");
+ const note = rows.length > 200 ? ` (showing first 200)` : "";
+ resultEl.innerHTML = `${rows.length} rows${note}
`;
+ }
+ }
+ } catch (err) {
+ resultEl.innerHTML = `Request failed: ${esc(err.message)}
`;
+ } finally {
+ runBtn.disabled = false;
+ statusEl.textContent = prevStatus;
+ }
+}
+
+/* ----------------------------------------------------------------- driver */
+
+function currentPayload() {
+ return state.cache[state.tab]?.[cacheKey()];
+}
+
+function render() {
+ const p = currentPayload();
+ if (!p) return;
+ try {
+ if (p.error) renderError(p);
+ else if (state.tab === "tokenomics") renderTokenomics(p);
+ else if (state.tab === "ai") renderAi(p);
+ else if (state.tab === "allocation") renderAllocation(p);
+ else if (state.tab === "rate") renderRate(p);
+ else if (state.tab === "usage") renderUsage(p);
+ else if (state.tab === "anomaly") renderAnomaly(p);
+ else if (state.tab === "capacity") renderCapacity(p);
+ else if (state.tab === "foundry") renderFoundry(p);
+ else if (state.tab === "agents") renderAgents(p);
+ else renderOverview(p);
+ } catch (err) {
+ console.error("[ftk-dashboard] render error:", err);
+ renderError({ error: `Render error in ${state.tab}: ${err.message}` });
+ }
+}
+
+async function load() {
+ const tab = state.tab;
+ if (TOOL_TABS.has(tab)) {
+ el("source-line").textContent = "Experimental tab — not part of the FinOps KPI pipeline.";
+ el("footer-meta").textContent = "";
+ renderMonacoTab();
+ return;
+ }
+ const key = cacheKey();
+ if (state.cache[tab]?.[key]) { updateChrome(); render(); return; }
+
+ // Cancel any in-flight request for a superseded tab/preset
+ if (_loadAbort) _loadAbort.abort();
+ _loadAbort = new AbortController();
+ const { signal } = _loadAbort;
+
+ state.cache[tab] = state.cache[tab] || {};
+ state.loading = true;
+ setRefreshSpinning(true);
+ const contentEl = el("content");
+ contentEl.setAttribute("aria-busy", "true");
+ contentEl.innerHTML = `
+
+
+
+ `;
+ try {
+ const res = await fetch("/api/view", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: tab,
+ preset: tab === "foundry" || tab === "agents" ? state.foundryPreset : state.preset,
+ filters: state.filters,
+ ...(tab === "capacity"
+ ? { capacityClass: state.capacityClass, capacitySelections: state.capacitySelections }
+ : {}),
+ ...(tab === "foundry" || tab === "agents" ? { accountId: state.foundryAccountId } : {}),
+ ...(tab === "agents" ? { forceRefresh: state.forceRefresh } : {}),
+ }),
+ signal,
+ });
+ state.cache[tab][key] = await res.json();
+ } catch (err) {
+ if (err.name === "AbortError") return; // superseded by a newer load(); discard silently
+ console.error("[ftk-dashboard] fetch failed:", err);
+ state.cache[tab][key] = {
+ error: tab === "foundry" || tab === "agents"
+ ? "Could not load Azure AI operational data. Check the tenant ID and Azure CLI authentication."
+ : "Could not load data. Check the FinOps hub connection and authentication.",
+ };
+ } finally {
+ if (tab === "agents") state.forceRefresh = false;
+ state.loading = false;
+ setRefreshSpinning(false);
+ el("content")?.setAttribute("aria-busy", "false");
+ }
+ updateChrome();
+ render();
+ if (tab === "capacity" && ["compute", "app-service"].includes(state.capacityClass) &&
+ state.capacityDetailTab === "subscriptions" && !state.capacitySubscriptionData) {
+ void loadCapacitySubscriptions();
+ }
+}
+
+function setRefreshSpinning(on) {
+ const b = el("refresh");
+ if (b) b.innerHTML = on ? `↻ Refresh` : `↻ Refresh`;
+}
+
+function renderDiagnosticRail() {
+ const railEl = el("diagnostic-rail");
+ if (!railEl) return;
+ const { rows, health, refreshedAt, dataset } = queryState;
+ const relTime = fmtRelativeTime(refreshedAt);
+ const absTime = refreshedAt ? refreshedAt.toLocaleString() : "";
+ const rowTxt = `${fmtInt(rows)} rows`;
+ const healthLabel = health === "error" ? "● error" : health === "warn" ? "● warn" : "● ok";
+ railEl.innerHTML =
+ `${esc(dataset)} ` +
+ `· ` +
+ `${rowTxt} ` +
+ `· ` +
+ `${healthLabel} ` +
+ `· ` +
+ `${esc(relTime)} `;
+}
+
+function updateChrome() {
+ const p = currentPayload();
+ const w = p && p.window;
+ if (p && state.tab === "agents" && !p.error) {
+ el("source-line").innerHTML =
+ `Microsoft Foundry agent traces · Hub Prices() estimates · exact Costs() matches shown separately`;
+ el("footer-meta").textContent = `${w?.start || ""} → ${w?.end || ""} · ${p.workspaceCount || 0} workspaces`;
+ queryState.rows = (p.agents?.length || 0) + (p.recentRuns?.length || 0) + (p.recentErrors?.length || 0);
+ queryState.health = p.diagnostics?.length ? "warn" : "ok";
+ queryState.refreshedAt = p.generatedAt ? new Date(p.generatedAt) : new Date();
+ queryState.dataset = "Agent operations";
+ renderDiagnosticRail();
+ } else if (p && state.tab === "foundry" && !p.error && !p.empty) {
+ el("source-line").innerHTML =
+ `Azure Monitor platform metrics · Hub Prices() estimates · ${p.selectedAccountId ? "one Foundry resource" : "Foundry estate"}`;
+ el("footer-meta").textContent = `${w?.start || ""} → ${w?.end || ""} · ${w?.interval || ""}`;
+ queryState.rows = Object.values(p.data?.charts || {}).reduce((sum, series) =>
+ sum + series.reduce((seriesSum, item) => seriesSum + item.Points.length, 0), 0);
+ queryState.health = p.data?.diagnostics?.length ? "warn" : "ok";
+ queryState.refreshedAt = p.generatedAt ? new Date(p.generatedAt) : new Date();
+ queryState.dataset = "AI Foundry operations";
+ renderDiagnosticRail();
+ } else if (p && state.tab === "foundry" && p.empty) {
+ el("source-line").textContent = "Azure Resource Graph · no AI Foundry resources found.";
+ el("footer-meta").textContent = "";
+ queryState.rows = 0;
+ queryState.health = "warn";
+ queryState.refreshedAt = p.generatedAt ? new Date(p.generatedAt) : new Date();
+ queryState.dataset = "AI Foundry account discovery";
+ renderDiagnosticRail();
+ } else if (w && w.dataMin) {
+ el("source-line").innerHTML =
+ `Hub database · ${esc(window.__cfg?.clusterUri || "localhost:8082")}`;
+ queryState.dataset = `Hub database · ${fmtDayRange(w.dataMin, w.dataMax)}`;
+ queryState.rows = w.rows || 0;
+ queryState.health = queryState.rows === 0 ? "warn" : "ok";
+ queryState.refreshedAt = p.generatedAt ? new Date(p.generatedAt) : new Date();
+ el("footer-meta").textContent = `window ${w.start} → ${w.end}`;
+ renderDiagnosticRail();
+ } else if (p && p.error) {
+ el("source-line").textContent = "Connection failed — see panel below.";
+ el("footer-meta").textContent = "";
+ queryState.rows = 0;
+ queryState.health = "error";
+ queryState.refreshedAt = new Date();
+ queryState.dataset = state.tab === "foundry" || state.tab === "agents" ? "Azure Monitor" : "Hub database";
+ renderDiagnosticRail();
+ } else if (p && state.tab === "capacity") {
+ const observations = p.classId === "home"
+ ? (p.classes || []).reduce((sum, item) => sum + Number(item.summary?.Observations || 0), 0)
+ : Number(p.coverage?.observations || 0);
+ el("source-line").innerHTML =
+ `Hub capacity · ${esc(window.__cfg?.clusterUri || "localhost:8082")}`;
+ el("footer-meta").textContent = p.classId === "home" ? "seven quota areas" : p.contract?.title || p.classId;
+ queryState.rows = observations;
+ queryState.health = p.error ? "error" : observations > 0 ? "ok" : "warn";
+ queryState.refreshedAt = p.generatedAt ? new Date(p.generatedAt) : new Date();
+ queryState.dataset = p.classId === "home" ? "Capacity overview" : p.contract?.title || "Capacity";
+ renderDiagnosticRail();
+ }
+}
+
+/** Open the connection-settings dialog, prefilled from the current config. */
+function openSettingsDialog() {
+ el("settings-cluster").value = window.__cfg?.clusterUri || "";
+ el("settings-database").value = window.__cfg?.database || "";
+ el("settings-tenant").value = window.__cfg?.tenantId || "";
+ el("settings-error").textContent = "";
+ el("settings-dialog").showModal();
+ el("settings-cluster").focus();
+}
+
+/** POST the edited connection settings, then reconnect and re-query. */
+async function saveSettings() {
+ const clusterUri = el("settings-cluster").value.trim();
+ const database = el("settings-database").value.trim();
+ const tenantId = el("settings-tenant").value.trim();
+ if (!clusterUri) {
+ el("settings-error").textContent = "Cluster URI is required.";
+ return;
+ }
+ const btn = el("settings-save");
+ const original = btn.textContent;
+ btn.disabled = true;
+ btn.textContent = "Saving…";
+ try {
+ const res = await fetch("/api/config", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ clusterUri, database: database || "Hub", tenantId }),
+ });
+ const body = await res.json();
+ if (!res.ok || body.error) throw new Error(body.error || "Save failed");
+ window.__cfg = body;
+ el("settings-dialog").close();
+ state.cache = {}; // stale data belongs to the old connection
+ invalidateCapacitySubscriptions();
+ load();
+ } catch (err) {
+ el("settings-error").textContent = err.message || "Could not save settings.";
+ } finally {
+ btn.disabled = false;
+ btn.textContent = original;
+ }
+}
+
+function wireControls() {
+ el("preset").addEventListener("click", (e) => {
+ const btn = e.target.closest("button[data-preset]");
+ if (!btn || state.loading) return;
+ state.preset = btn.dataset.preset;
+ [...el("preset").querySelectorAll("button")].forEach((b) => b.classList.toggle("active", b === btn));
+ void publishCanvasState({ preset: state.preset });
+ load();
+ });
+ el("tabs").addEventListener("click", (e) => {
+ const btn = e.target.closest("button[data-tab]");
+ if (btn) switchTab(btn.dataset.tab);
+ });
+ el("refresh").addEventListener("click", () => {
+ if (state.loading) return;
+ if (state.cache[state.tab]) delete state.cache[state.tab][cacheKey()]; // force re-query
+ if (state.tab === "capacity" && ["compute", "app-service"].includes(state.capacityClass)) invalidateCapacitySubscriptions();
+ if (state.tab === "agents") state.forceRefresh = true;
+ load();
+ });
+
+ // Settings dialog controls
+ el("settings-open").addEventListener("click", openSettingsDialog);
+ el("settings-close").addEventListener("click", () => el("settings-dialog").close());
+ el("settings-save").addEventListener("click", saveSettings);
+
+ // KQL dialog controls
+ el("kql-close").addEventListener("click", () => el("kql-dialog").close());
+ el("kql-copy").addEventListener("click", () => {
+ const btn = el("kql-copy");
+ navigator.clipboard.writeText(el("kql-text").value)
+ .then(() => { btn.textContent = "Copied!"; setTimeout(() => { btn.textContent = "Copy"; }, 1500); })
+ .catch(() => { btn.textContent = "Failed"; setTimeout(() => { btn.textContent = "Copy"; }, 1500); });
+ });
+ el("kql-run").addEventListener("click", executeKql);
+
+ // KQL escape-hatch buttons (event delegation — buttons injected by panelHtml)
+ document.addEventListener("click", (e) => {
+ const foundryPreset = e.target.closest("[data-foundry-preset]");
+ if (foundryPreset && !state.loading) {
+ state.foundryPreset = foundryPreset.dataset.foundryPreset;
+ void publishCanvasState({ foundryPreset: state.foundryPreset });
+ load();
+ return;
+ }
+ const capacityTab = e.target.closest("[data-capacity-class]");
+ if (capacityTab) {
+ selectCapacityClass(capacityTab.dataset.capacityClass);
+ return;
+ }
+ const btn = e.target.closest(".kql-btn[data-panel-id]");
+ if (btn) openKqlDialog(btn.dataset.panelId);
+ // hbar click-to-filter
+ const hbarRow = e.target.closest(".hbar-filterable[data-filter-dim]");
+ if (hbarRow) {
+ const dim = hbarRow.dataset.filterDim;
+ const val = hbarRow.dataset.filterVal;
+ if (dim && val) toggleFilter(dim, val);
+ }
+ // chip remove
+ const chipRemove = e.target.closest(".chip-remove[data-dim]");
+ if (chipRemove) {
+ const dim = chipRemove.dataset.dim;
+ const val = chipRemove.dataset.val;
+ if (dim && val) toggleFilter(dim, val);
+ }
+ // reset all
+ if (e.target.closest("#filter-reset")) clearFilters();
+
+ const matrixStatus = e.target.closest('[data-ui-segment="matrix-status"]');
+ if (matrixStatus) {
+ setCapacityMatrixFilter({ status: matrixStatus.dataset.uiValue });
+ return;
+ }
+ const regionChip = e.target.closest('[data-ui-toggle="matrix-region"]');
+ if (regionChip) {
+ const region = regionChip.dataset.uiValue;
+ const current = capacityMatrixFilter().regions;
+ setCapacityMatrixFilter({
+ regions: current.includes(region) ? current.filter((item) => item !== region) : [...current, region],
+ });
+ return;
+ }
+ const markChip = e.target.closest('[data-ui-segment="matrix-mark"]');
+ if (markChip) {
+ setCapacityMatrixFilter({ mark: Number(markChip.dataset.uiValue) });
+ return;
+ }
+ if (e.target.closest('[data-ui-action="matrix-reset"]')) {
+ setCapacityMatrixFilter({ status: "all", search: "", regions: [] });
+ return;
+ }
+ const detailTab = e.target.closest('[data-ui-tab="capacity-detail"]');
+ if (detailTab) {
+ setCapacityDetailTab(detailTab.dataset.uiValue);
+ return;
+ }
+ const subscriptionPage = e.target.closest('[data-ui-page="subscriptions"]');
+ if (subscriptionPage && !subscriptionPage.disabled) {
+ state.capacitySubscriptionPage = Number(subscriptionPage.dataset.uiValue);
+ _capacitySubscriptionFocusResults = true;
+ void loadCapacitySubscriptions();
+ return;
+ }
+ const matrixPage = e.target.closest('[data-ui-page="matrix"]');
+ if (matrixPage && !matrixPage.disabled) {
+ state.capacityMatrixPage = Number(matrixPage.dataset.uiValue);
+ render();
+ document.querySelector("#capacity-matrix-summary")?.focus();
+ }
+ });
+
+ document.addEventListener("change", (e) => {
+ const foundryAccount = e.target.closest("select[data-foundry-account]");
+ if (foundryAccount && !state.loading) {
+ state.foundryAccountId = foundryAccount.value || null;
+ void publishCanvasState({ foundryAccountId: state.foundryAccountId });
+ load();
+ return;
+ }
+ const selector = e.target.closest("select[data-capacity-selector]");
+ if (selector) applyCapacitySelection(selector.dataset.capacitySelector, selector.value);
+ });
+
+ let matrixSearchTimer;
+ let subscriptionSearchTimer;
+ document.addEventListener("input", (e) => {
+ const search = e.target.closest('[data-ui-search="matrix"]');
+ if (search) {
+ clearTimeout(matrixSearchTimer);
+ const value = search.value;
+ matrixSearchTimer = setTimeout(() => setCapacityMatrixFilter({ search: value }), 160);
+ return;
+ }
+ const subscriptionSearch = e.target.closest('[data-ui-search="subscription"]');
+ if (subscriptionSearch) {
+ clearTimeout(subscriptionSearchTimer);
+ const value = subscriptionSearch.value;
+ subscriptionSearchTimer = setTimeout(() => {
+ state.capacitySubscriptionSearch = value;
+ state.capacitySubscriptionPage = 1;
+ void loadCapacitySubscriptions();
+ }, 250);
+ }
+ });
+
+ // Keyboard activation and roving focus for interactive data controls.
+ document.addEventListener("keydown", (e) => {
+ const detailTab = e.target.closest('[data-ui-tab="capacity-detail"]');
+ if (detailTab && ["ArrowLeft", "ArrowRight", "Home", "End"].includes(e.key)) {
+ e.preventDefault();
+ const tabs = ["matrix", "subscriptions"];
+ const current = tabs.indexOf(detailTab.dataset.uiValue);
+ const next = e.key === "Home" ? 0
+ : e.key === "End" ? tabs.length - 1
+ : e.key === "ArrowRight" ? (current + 1) % tabs.length
+ : (current - 1 + tabs.length) % tabs.length;
+ setCapacityDetailTab(tabs[next]);
+ return;
+ }
+ const segment = e.target.closest("[data-ui-segment]");
+ if (segment && ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(e.key)) {
+ e.preventDefault();
+ const order = segment.dataset.uiSegment === "matrix-status"
+ ? matrixStatusFilters(state.capacityClass).map((item) => item.id)
+ : segment.dataset.uiSegment === "matrix-mark"
+ ? HIGH_WATER_MARKS.map(String)
+ : [];
+ if (!order.length) return;
+ const index = order.indexOf(segment.dataset.uiValue);
+ const next = nextCapacityTabIndex(index, e.key, order.length);
+ if (next >= 0) {
+ setCapacityMatrixFilter(segment.dataset.uiSegment === "matrix-status"
+ ? { status: order[next] }
+ : { mark: Number(order[next]) });
+ }
+ return;
+ }
+ const capacityTab = e.target.closest("[data-capacity-class]");
+ if (capacityTab) {
+ if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(e.key)) {
+ e.preventDefault();
+ moveCapacityTabFocus(capacityTab, e.key);
+ return;
+ }
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ selectCapacityClass(capacityTab.dataset.capacityClass);
+ return;
+ }
+ }
+ if (e.key !== "Enter" && e.key !== " ") return;
+ const hbarRow = e.target.closest(".hbar-filterable[data-filter-dim]");
+ if (hbarRow) {
+ e.preventDefault();
+ const dim = hbarRow.dataset.filterDim;
+ const val = hbarRow.dataset.filterVal;
+ if (dim && val) toggleFilter(dim, val);
+ }
+ });
+
+ let t;
+ window.addEventListener("resize", () => { clearTimeout(t); t = setTimeout(render, 180); });
+}
+
+async function init() {
+ try {
+ const [cfg, sharedState] = await Promise.all([
+ fetch("/api/config").then((r) => r.json()),
+ fetch("/api/session-state").then((r) => r.json()),
+ ]);
+ window.__cfg = cfg;
+ if (Number.isInteger(sharedState.revision)) {
+ state.tab = sharedState.tab;
+ state.preset = sharedState.preset;
+ state.filters = sharedState.filters || {};
+ state.capacityClass = sharedState.capacityClass || "home";
+ state.capacitySelections = sharedState.capacitySelections || {};
+ state.foundryPreset = sharedState.foundryPreset || "7d";
+ state.foundryAccountId = sharedState.foundryAccountId || null;
+ state.revision = sharedState.revision;
+ }
+ } catch { window.__cfg = {}; }
+ wireControls();
+ syncCanvasControls();
+
+ // Restore tab from URL hash (bookmarking / back-forward support), or
+ // normalize the hash to reflect the default tab so the URL is always
+ // shareable.
+ const initialTab = tabFromHash();
+ const initialCapacityClass = capacityClassFromHash();
+ if (initialCapacityClass) state.capacityClass = initialCapacityClass;
+ const initialHash = (initialTab || state.tab) === "capacity"
+ ? `#tab=capacity&capacity=${state.capacityClass}`
+ : `#tab=${initialTab || state.tab}`;
+ if (initialTab && initialTab !== state.tab) {
+ switchTab(initialTab, { skipHash: true });
+ history.replaceState({ tab: initialTab, capacityClass: state.capacityClass }, "", initialHash);
+ } else {
+ history.replaceState({ tab: state.tab, capacityClass: state.capacityClass }, "", initialHash);
+ revealActiveTab();
+ load();
+ }
+
+ window.addEventListener("popstate", () => {
+ const tab = tabFromHash() || "overview";
+ const capacityClass = capacityClassFromHash() || "home";
+ if (tab === "capacity") state.capacityClass = capacityClass;
+ if (tab !== state.tab) switchTab(tab, { skipHash: true });
+ else if (tab === "capacity") selectCapacityClass(capacityClass, { skipHash: true, skipPublish: true, force: true });
+ });
+ setInterval(pollCanvasState, 1000);
+}
+
+if (typeof window !== "undefined" && typeof document !== "undefined") init();
diff --git a/.github/extensions/ftk-local-dashboard/public/index.html b/.github/extensions/ftk-local-dashboard/public/index.html
new file mode 100644
index 000000000..9981ac1aa
--- /dev/null
+++ b/.github/extensions/ftk-local-dashboard/public/index.html
@@ -0,0 +1,104 @@
+
+
+
+
+
+ FinOps hub dashboard
+
+
+
+
+
+
+
+ Cost overview
+ Allocation
+ Rate optimization
+ Usage & unit economics
+ Anomalies & forecast
+ Tokenomics
+ AI Foundry
+ Foundry agents
+ AI & emerging workloads
+ Supply
+ Query editor
+
+
+
+
Filtered by
+
+
Reset all
+
+
+
+ Loading cost data…
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.github/extensions/ftk-local-dashboard/public/ui.css b/.github/extensions/ftk-local-dashboard/public/ui.css
new file mode 100644
index 000000000..1f695a04c
--- /dev/null
+++ b/.github/extensions/ftk-local-dashboard/public/ui.css
@@ -0,0 +1,266 @@
+.ui-filter-bar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ gap: 10px 16px;
+ margin-bottom: 12px;
+}
+
+.ui-control-group {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ min-width: 0;
+}
+
+.ui-control-label {
+ color: var(--muted);
+ font-size: 10.5px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+}
+
+.ui-segments {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+}
+
+.ui-segments--scroll {
+ max-height: 74px;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ scrollbar-width: thin;
+}
+
+.ui-segment,
+.ui-button {
+ min-height: 28px;
+ border: 1px solid var(--grid);
+ background: transparent;
+ color: var(--text);
+ font: inherit;
+ font-size: 11.5px;
+ cursor: pointer;
+}
+
+.ui-segment {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 6px;
+ padding: 4px 10px;
+ border-radius: 999px;
+}
+
+.ui-button {
+ padding: 4px 10px;
+ border-radius: 6px;
+}
+
+.ui-segment:hover,
+.ui-button:hover { border-color: var(--muted); }
+
+.ui-segment[aria-checked="true"],
+.ui-segment[aria-pressed="true"],
+.ui-segment[aria-selected="true"] {
+ border-color: var(--accent, var(--text));
+ background: color-mix(in srgb, var(--muted) 14%, transparent);
+ font-weight: 600;
+}
+
+.ui-segment-count {
+ color: var(--muted);
+ font-size: 10.5px;
+ font-variant-numeric: tabular-nums;
+}
+
+.ui-segment[aria-checked="true"] .ui-segment-count,
+.ui-segment[aria-pressed="true"] .ui-segment-count,
+.ui-segment[aria-selected="true"] .ui-segment-count { color: inherit; }
+
+.ui-search {
+ min-width: 190px;
+ min-height: 28px;
+ padding: 4px 9px;
+ border: 1px solid var(--grid);
+ border-radius: 6px;
+ background: var(--card-bg);
+ color: var(--text);
+ font: inherit;
+ font-size: 12px;
+}
+
+.ui-segment:focus-visible,
+.ui-button:focus-visible,
+.ui-search:focus-visible {
+ outline: 2px solid var(--accent, var(--text));
+ outline-offset: 2px;
+}
+
+.ui-button:disabled { opacity: 0.45; cursor: not-allowed; }
+
+.ui-filter-summary {
+ margin-left: auto;
+ color: var(--muted);
+ font-size: 11.5px;
+ font-variant-numeric: tabular-nums;
+}
+
+.ui-filter-summary .ui-button { margin-left: 8px; }
+
+.ui-tabs {
+ display: flex;
+ gap: 4px;
+ margin-bottom: 12px;
+}
+
+.ui-pagination {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 10px;
+ margin-top: 10px;
+ color: var(--muted);
+ font-size: 11.5px;
+ font-variant-numeric: tabular-nums;
+}
+
+.ui-matrix-viewport {
+ max-height: min(70vh, 620px);
+ overflow: auto;
+ overscroll-behavior: contain;
+ scrollbar-gutter: stable;
+ border: 1px solid var(--grid);
+ border-radius: var(--radius);
+ scrollbar-width: auto;
+ scrollbar-color: color-mix(in srgb, var(--muted) 45%, transparent) transparent;
+}
+
+.ui-matrix-viewport::-webkit-scrollbar { width: 12px; height: 12px; }
+.ui-matrix-viewport::-webkit-scrollbar-track { background: color-mix(in srgb, var(--muted) 10%, transparent); }
+.ui-matrix-viewport::-webkit-scrollbar-thumb {
+ border: 3px solid var(--card-bg);
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--muted) 45%, transparent);
+}
+.ui-matrix-viewport::-webkit-scrollbar-thumb:hover { background: color-mix(in srgb, var(--muted) 70%, transparent); }
+.ui-matrix-viewport::-webkit-scrollbar-corner { background: var(--card-bg); }
+
+.ui-matrix {
+ width: auto;
+ border-spacing: 0;
+ border-collapse: separate;
+ font-size: 12px;
+}
+
+.ui-matrix th {
+ min-width: 120px;
+ padding: 7px;
+ color: var(--muted);
+ font-size: 11px;
+ text-align: left;
+}
+
+.ui-matrix thead th {
+ position: sticky;
+ top: 0;
+ z-index: 2;
+ border-bottom: 1px solid var(--grid);
+ background: var(--card-bg);
+ white-space: nowrap;
+}
+
+.ui-matrix tbody th:first-child {
+ position: sticky;
+ left: 0;
+ z-index: 1;
+ min-width: 200px;
+ border-right: 1px solid var(--grid);
+ border-bottom: 1px solid var(--grid);
+ background: var(--card-bg);
+}
+
+.ui-matrix thead th:first-child {
+ z-index: 3;
+ min-width: 200px;
+ border-right: 1px solid var(--grid);
+}
+
+.ui-matrix-cell {
+ min-width: 132px;
+ padding: 9px;
+ border-width: 0 1px 1px 0;
+ border-style: solid;
+ border-color: var(--grid);
+ background: color-mix(in srgb, var(--muted) 5%, var(--card-bg));
+}
+
+.ui-matrix-cell strong,
+.ui-matrix-cell span { display: block; overflow-wrap: anywhere; }
+.ui-matrix-cell strong { font-variant-numeric: tabular-nums; }
+.ui-matrix-cell span { margin-top: 3px; color: var(--muted); font-size: 11px; }
+.ui-matrix-cell--missing { color: var(--muted); }
+
+.ui-matrix-cell.capacity-supply--open { box-shadow: inset 3px 0 0 color-mix(in srgb, var(--pos) 55%, transparent); }
+.ui-matrix-cell.capacity-supply--partial { box-shadow: inset 3px 0 0 var(--warn); }
+.ui-matrix-cell.capacity-supply--blocked {
+ box-shadow: inset 3px 0 0 var(--neg);
+ background: color-mix(in srgb, var(--neg) 7%, var(--card-bg));
+}
+.ui-matrix-cell--missing,
+.ui-matrix-cell.capacity-supply--none { box-shadow: inset 3px 0 0 color-mix(in srgb, var(--muted) 35%, transparent); }
+
+.ui-matrix-note {
+ margin: 0 0 8px;
+ color: var(--muted);
+ font-size: 11.5px;
+}
+
+.ui-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 28px;
+ margin: 0 0 10px;
+ color: var(--muted);
+ font-size: 11px;
+}
+
+.ui-legend-group { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 12px; }
+.ui-legend-title { color: var(--text-color-default, #1f2328); font-weight: 600; }
+.ui-legend ul { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 0; padding: 0; list-style: none; }
+.ui-legend li { display: flex; align-items: center; gap: 5px; }
+.ui-legend-bar { width: 3px; height: 12px; border-radius: 1px; background: var(--grid); }
+.ui-legend-bar--open { background: color-mix(in srgb, var(--pos) 55%, transparent); }
+.ui-legend-bar--partial { background: var(--warn); }
+.ui-legend-bar--blocked { background: var(--neg); }
+.ui-legend-bar--none { background: color-mix(in srgb, var(--muted) 35%, transparent); }
+.ui-legend-ink { font-size: 11px; font-variant-numeric: tabular-nums; }
+.ui-legend-ink.capacity-demand--under { color: var(--text-color-default, #1f2328); }
+.ui-legend-ink.capacity-demand--over,
+.ui-legend-ink.capacity-demand--exhausted { color: var(--neg-ink); font-weight: 700; }
+.ui-legend-ink.capacity-demand--exhausted { text-decoration: underline; text-decoration-thickness: 2px; }
+
+.ui-matrix-cell .capacity-offer-status { margin-top: 4px; font-weight: 600; }
+.ui-matrix-cell .capacity-offer-status--restricted { color: var(--neg-ink); }
+.ui-matrix-cell .capacity-offer-status--warning,
+.ui-matrix-cell .capacity-zone--restricted { color: var(--warn-ink); font-weight: 600; }
+.ui-matrix-cell .capacity-offer-status--available,
+.ui-matrix-cell .capacity-zone--available { color: var(--muted); }
+.ui-matrix-cell .capacity-zone { margin-top: 2px; font-size: 10.5px; white-space: nowrap; }
+.ui-matrix-cell .capacity-cell-mark { color: var(--neg-ink); font-weight: 600; }
+.ui-matrix-cell .capacity-cell-detail { color: var(--muted); font-size: 11px; }
+.ui-matrix-cell.capacity-demand--over strong { color: var(--neg-ink); font-weight: 700; }
+.ui-matrix-cell.capacity-demand--exhausted strong {
+ color: var(--neg-ink);
+ font-weight: 700;
+ text-decoration: underline;
+ text-decoration-thickness: 2px;
+ text-underline-offset: 2px;
+}
+
+.ui-cell-status { margin-top: 4px; font-weight: 600; }
+.ui-cell-status--danger { color: var(--neg-ink) !important; }
+.ui-cell-status--warning { color: var(--warn-ink) !important; }
+.ui-cell-status--available,
+.ui-cell-status--muted { color: var(--muted); }
diff --git a/.github/extensions/ftk-local-dashboard/public/ui.js b/.github/extensions/ftk-local-dashboard/public/ui.js
new file mode 100644
index 000000000..9f1d0bf2c
--- /dev/null
+++ b/.github/extensions/ftk-local-dashboard/public/ui.js
@@ -0,0 +1,111 @@
+"use strict";
+
+function escapeHtml(value) {
+ return String(value ?? "").replace(/[&<>"']/g, (char) => ({
+ "&": "&",
+ "<": "<",
+ ">": ">",
+ '"': """,
+ "'": "'",
+ })[char]);
+}
+
+function controlName(value) {
+ const name = String(value ?? "");
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) throw new Error(`Invalid UI control name '${name}'.`);
+ return name;
+}
+
+export function uiSegmentedControl({ name, label, labelId, items = [], selected }) {
+ const control = controlName(name);
+ return `
+
${escapeHtml(label)}
+
+ ${items.map((item) => {
+ const active = String(item.value) === String(selected);
+ return `${escapeHtml(item.label)}
+ ${item.count == null ? "" : `${escapeHtml(item.count)} `} `;
+ }).join("")}
+
+
`;
+}
+
+export function uiToggleList({ name, label, labelId, items = [], selected = [] }) {
+ const control = controlName(name);
+ const selectedValues = new Set(selected.map(String));
+ return `
+
${escapeHtml(label)}
+
+ ${items.map((item) => `${escapeHtml(item.label)} `).join("")}
+
+
`;
+}
+
+export function uiSearchField({ name, id, label, value = "", placeholder = "" }) {
+ const control = controlName(name);
+ return `
+ ${escapeHtml(label)}
+
+ `;
+}
+
+export function uiFilterBar({ ariaLabel, controls, summary, resetLabel = null, resetAction = "reset" }) {
+ const action = controlName(resetAction);
+ return `
+ ${controls}
+
${escapeHtml(summary)}
+ ${resetLabel ? `${escapeHtml(resetLabel)} ` : ""}
+
+
`;
+}
+
+export function uiTabList({ name, label, tabs = [], active, panelId, panel }) {
+ const control = controlName(name);
+ return `
+ ${tabs.map((tab) => {
+ const selected = tab.id === active;
+ return `${escapeHtml(tab.label)} `;
+ }).join("")}
+
+ ${panel}
`;
+}
+
+export function uiPagination({ name, page, totalPages, label }) {
+ if (totalPages <= 1) return "";
+ const control = controlName(name);
+ return ``;
+}
+
+export function uiDataMatrix({
+ ariaLabel,
+ descriptionId,
+ rowHeader,
+ rows = [],
+ columns = [],
+ renderCell,
+ missingText = "Not reported",
+}) {
+ return `
+
+ ${escapeHtml(rowHeader)} ${columns.map((column) => `${escapeHtml(column)} `).join("")}
+ ${rows.map((row) => `
+ ${escapeHtml(row.label)}
+ ${columns.map((column) => renderCell(row, column) || `${escapeHtml(missingText)} `).join("")}
+ `).join("")}
+
+
`;
+}
diff --git a/.github/extensions/ftk-local-dashboard/test/ftk-local-dashboard.test.mjs b/.github/extensions/ftk-local-dashboard/test/ftk-local-dashboard.test.mjs
new file mode 100644
index 000000000..af6f29ce8
--- /dev/null
+++ b/.github/extensions/ftk-local-dashboard/test/ftk-local-dashboard.test.mjs
@@ -0,0 +1,2674 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { createServer } from "node:http";
+import test from "node:test";
+
+process.env.FTK_LOCAL_DASHBOARD_TEST = "1";
+
+const kusto = await import("../kusto.mjs");
+const azureMonitor = await import("../azure-monitor.mjs");
+const extension = await import("../extension.mjs");
+const app = await import("../public/app.js");
+const ui = await import("../public/ui.js");
+
+const QUOTA_SCHEMA_FIELDS = [
+ "ResourceId", "ResourceName", "SubAccountId", "location", "currentValue",
+ "limit", "unit", "x_SourceType", "x_SourceVersion", "x_IngestionTime",
+];
+const COST_SCHEMA_FIELDS = [
+ "ChargePeriodStart", "ProviderName", "ChargeCategory", "ResourceId",
+ "SubAccountId", "RegionId", "x_ResourceType", "x_SkuMeterCategory",
+ "x_SkuMeterSubcategory", "SkuMeter", "SkuPriceId", "EffectiveCost",
+ "BillingCurrency", "ConsumedQuantity", "ConsumedUnit",
+ "CapacityReservationId", "CapacityReservationStatus",
+];
+
+function kustoResponse(rows, columns = rows[0] ? Object.keys(rows[0]) : []) {
+ return new Response(JSON.stringify({
+ Tables: [{
+ TableName: "Table_0",
+ Columns: columns.map((ColumnName) => ({ ColumnName })),
+ Rows: rows.map((row) => columns.map((column) => row[column])),
+ }],
+ }), { headers: { "Content-Type": "application/json" } });
+}
+
+async function startCapacityServer(t, options = {}) {
+ const quotaFields = options.quotaFields || QUOTA_SCHEMA_FIELDS;
+ const costFields = options.costFields || COST_SCHEMA_FIELDS;
+ const server = createServer(async (req, res) => {
+ let body = "";
+ for await (const chunk of req) body += chunk;
+ const { csl } = JSON.parse(body);
+ const fields = csl.includes("Quota()") && csl.includes("| getschema")
+ ? quotaFields
+ : csl.startsWith("Costs() | getschema")
+ ? costFields
+ : null;
+ const rows = fields
+ ? fields.map((ColumnName) => ({ ColumnName, ColumnType: "System.String" }))
+ : typeof options.rows === "function"
+ ? options.rows(csl)
+ : [];
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(await kustoResponse(rows).text());
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => server.close());
+ return `http://127.0.0.1:${server.address().port}`;
+}
+
+test("connection validation permits only local loopback or remote Kusto origins", () => {
+ assert.deepEqual(
+ kusto.normalizeConnection("http://LOCALHOST:8082/", " Hub "),
+ { clusterUri: "http://localhost:8082", database: "Hub", tenantId: null, mode: "local", authentication: "none" }
+ );
+ assert.deepEqual(
+ kusto.normalizeConnection(
+ "https://example-cluster.westus.kusto.windows.net",
+ "Hub",
+ "72F988BF-86F1-41AF-91AB-2D7CD011DB47"
+ ),
+ {
+ clusterUri: "https://example-cluster.westus.kusto.windows.net",
+ database: "Hub",
+ tenantId: "72f988bf-86f1-41af-91ab-2d7cd011db47",
+ mode: "remote",
+ authentication: "azure-cli",
+ }
+ );
+ assert.equal(
+ kusto.normalizeConnection(
+ "http://localhost:8082",
+ "Hub",
+ "72F988BF-86F1-41AF-91AB-2D7CD011DB47"
+ ).tenantId,
+ "72f988bf-86f1-41af-91ab-2d7cd011db47"
+ );
+ assert.throws(
+ () => kusto.normalizeConnection("https://example-cluster.westus.kusto.windows.net", "Hub", "not-a-tenant"),
+ /valid Microsoft Entra tenant GUID/
+ );
+ assert.deepEqual(
+ kusto.azureCliTokenArgs("72F988BF-86F1-41AF-91AB-2D7CD011DB47"),
+ [
+ "account", "get-access-token",
+ "--resource", "https://api.kusto.windows.net",
+ "--tenant", "72f988bf-86f1-41af-91ab-2d7cd011db47",
+ "--output", "json",
+ ]
+ );
+ for (const uri of [
+ "http://example.com",
+ "https://example.com",
+ "https://kusto.windows.net",
+ "https://user:pass@cluster.westus.kusto.windows.net",
+ "https://cluster.westus.kusto.windows.net/path",
+ "https://cluster.westus.kusto.windows.net?x=1",
+ ]) {
+ assert.throws(() => kusto.normalizeConnection(uri, "Hub"));
+ }
+});
+
+test("AI Foundry Azure CLI tokens are tenant-scoped and resource-bound", () => {
+ const tenant = "72F988BF-86F1-41AF-91AB-2D7CD011DB47";
+ assert.deepEqual(
+ azureMonitor.azureMonitorTokenArgs("https://metrics.monitor.azure.com/", tenant),
+ [
+ "account", "get-access-token",
+ "--resource", "https://metrics.monitor.azure.com/",
+ "--tenant", tenant.toLowerCase(),
+ "--output", "json",
+ ]
+ );
+ assert.ok(
+ azureMonitor.azureMonitorTokenArgs("https://management.azure.com/", tenant)
+ .includes("https://management.azure.com/")
+ );
+ assert.ok(
+ azureMonitor.azureMonitorTokenArgs("https://api.loganalytics.io", tenant)
+ .includes("https://api.loganalytics.io")
+ );
+ assert.throws(() => azureMonitor.normalizeAzureTenantId("organizations"), /tenant GUID/);
+ assert.throws(
+ () => azureMonitor.azureMonitorTokenArgs("https://management.core.windows.net/", tenant),
+ /Unsupported Azure token resource/
+ );
+});
+
+test("persisted configuration ignores the retired Azure Monitor tenant field", () => {
+ assert.equal(
+ extension.normalizePersistedConfig({ monitorTenantId: "11111111-2222-4333-8444-555555555555" }).monitorTenantId,
+ undefined
+ );
+ assert.equal(extension.normalizePersistedConfig({ tenantId: "11111111-2222-4333-8444-555555555555" }).tenantId,
+ "11111111-2222-4333-8444-555555555555");
+});
+
+test("AI Foundry metrics preserve dimensions, reconcile TotalTokens, and price explicit blocks", () => {
+ const metric = (name, metadata, data, valueKey = "total") => ({
+ name: { value: name },
+ errorCode: "Success",
+ timeseries: [{
+ metadatavalues: Object.entries(metadata).map(([key, value]) => ({ name: { value: key }, value })),
+ data: data.map(([timeStamp, value]) => ({ timeStamp, [valueKey]: value })),
+ }],
+ });
+ const identity = { ModelDeploymentName: "chat-prod" };
+ const timestamp = "2026-03-01T00:00:00Z";
+ const subscriptionId = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee";
+ const accountId = `/subscriptions/${subscriptionId}/resourceGroups/ai-rg/providers/Microsoft.CognitiveServices/accounts/foundry`;
+ const resource = (value) => ({ resourceid: accountId, value });
+ const payloads = [
+ {
+ group: "tokens",
+ payload: {
+ values: [resource([
+ metric("InputTokens", identity, [[timestamp, 1000]]),
+ metric("OutputTokens", identity, [[timestamp, 500]]),
+ metric("TotalTokens", identity, [[timestamp, 1500]]),
+ ])],
+ },
+ },
+ {
+ group: "requests",
+ payload: {
+ values: [resource([metric("ModelRequests", identity, [[timestamp, 12]])])],
+ },
+ },
+ {
+ group: "request-errors",
+ payload: {
+ values: [resource([metric("ModelRequests", { StatusCode: "429" }, [[timestamp, 2]])])],
+ },
+ },
+ {
+ group: "latency",
+ payload: {
+ values: [resource([
+ metric("TimeToLastByte", identity, [[timestamp, 250]], "average"),
+ metric("AzureOpenAITTLTInMS", identity, [[timestamp, 275]], "average"),
+ ])],
+ },
+ },
+ {
+ group: "throughput",
+ payload: {
+ values: [resource([
+ metric("AzureOpenAITokenPerSecond", identity, [[timestamp, 40]], "average"),
+ ])],
+ },
+ },
+ ];
+ const prices = [
+ {
+ SubAccountId: subscriptionId,
+ Direction: "Input",
+ Variant: "Standard",
+ ModelText: "GPT-4o 2024-08-06 input tokens",
+ PriceRegionId: "eastus",
+ PriceScope: "Regional",
+ SelectedUnitPrice: 0.002,
+ x_PricingBlockSize: 1000,
+ PricingCurrency: "USD",
+ PriceSource: "Contracted",
+ ScopeMatch: true,
+ ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-01-01T00:00:00Z",
+ x_EffectivePeriodEnd: null,
+ },
+ {
+ SubAccountId: subscriptionId,
+ Direction: "Output",
+ Variant: "Standard",
+ ModelText: "GPT-4o 2024-08-06 output tokens",
+ PriceRegionId: "eastus",
+ PriceScope: "Regional",
+ SelectedUnitPrice: 0.008,
+ x_PricingBlockSize: 1000,
+ PricingCurrency: "USD",
+ PriceSource: "Contracted",
+ ScopeMatch: true,
+ ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-01-01T00:00:00Z",
+ x_EffectivePeriodEnd: null,
+ },
+ ];
+ const flattened = azureMonitor.flattenMetricBatch(payloads);
+ const account = {
+ id: accountId,
+ name: "foundry",
+ resourceGroup: "ai-rg",
+ subscriptionId,
+ location: "eastus",
+ kind: "AIServices",
+ sku: "S0",
+ };
+ const deployment = {
+ name: "chat-prod",
+ skuName: "Standard",
+ modelName: "gpt-4o",
+ modelVersion: "2024-08-06",
+ };
+ const result = azureMonitor.summarizeFoundryMetrics(
+ flattened,
+ [account],
+ new Map([[accountId.toLowerCase(), [deployment]]]),
+ new Map([[subscriptionId, prices]])
+ );
+ assert.equal(result.summary.TotalTokens, 1500);
+ assert.equal(result.summary.InputTokens, 1000);
+ assert.equal(result.summary.OutputTokens, 500);
+ assert.equal(result.summary.Requests, 12);
+ assert.equal(result.summary.Errors, 2);
+ assert.equal(result.summary.ErrorRate, 2 / 12);
+ assert.equal(result.summary.EstimatedCost, 0.006);
+ assert.equal(result.summary.InputEstimatedCost, 0.002);
+ assert.equal(result.summary.OutputEstimatedCost, 0.004);
+ assert.equal(result.summary.PriceCoverage, 1);
+ assert.equal(result.stats.inputTokens[0].EstimatedCost, 0.002);
+ assert.equal(result.stats.outputTokens[0].EstimatedCost, 0.004);
+ assert.equal(result.charts.inputTokens[0].Points[0].Cost, 0.002);
+ assert.equal(result.charts.outputTokens[0].Points[0].Cost, 0.004);
+ assert.equal(result.charts.totalTokens[0].Points[0].Cost, 0.006);
+ assert.equal(result.charts.latency.find((series) => series.Name.includes("Time to last byte")).Points[0].Value, 250);
+ assert.equal(result.charts.tokensPerSecond[0].Points[0].Value, 40);
+});
+
+test("AI Foundry price matching rejects specialized, missing-block, and disagreeing rates", () => {
+ const base = {
+ Direction: "Input",
+ Variant: "Standard",
+ ModelText: "GPT-4o 2024-08-06 input tokens",
+ PriceRegionId: "eastus",
+ PriceScope: "Regional",
+ SelectedUnitPrice: 0.002,
+ x_PricingBlockSize: 1000,
+ PricingCurrency: "USD",
+ ScopeMatch: true,
+ ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-01-01T00:00:00Z",
+ x_EffectivePeriodEnd: null,
+ };
+ const deployment = {
+ name: "chat-prod",
+ skuName: "Standard",
+ modelName: "gpt-4o",
+ modelVersion: "2024-08-06",
+ };
+ assert.equal(
+ azureMonitor.matchFoundryPrice("gpt-4o", "2024-08-06", "Input", "eastus", [{ ...base, Variant: "Batch" }], deployment, "2026-03-01T00:00:00Z").status,
+ "unmatched"
+ );
+ assert.equal(
+ azureMonitor.matchFoundryPrice("gpt-4o", "2024-08-06", "Input", "eastus", [{ ...base, x_PricingBlockSize: null }], deployment, "2026-03-01T00:00:00Z").status,
+ "unmatched"
+ );
+ assert.equal(
+ azureMonitor.matchFoundryPrice("gpt-4o", "2024-08-06", "Input", "eastus", [
+ base,
+ { ...base, SelectedUnitPrice: 0.003, BillingAccountId: "different" },
+ ], deployment, "2026-03-01T00:00:00Z").status,
+ "ambiguous"
+ );
+ assert.equal(
+ azureMonitor.matchFoundryPrice("gpt-4o", "", "Input", "eastus", [base], deployment, "2026-03-01T00:00:00Z").status,
+ "unmatched"
+ );
+ assert.equal(
+ azureMonitor.matchFoundryPrice("gpt-4o", "2024-08-06", "Input", "eastus", [
+ { ...base, ScopeMatch: false },
+ ], deployment, "2026-03-01T00:00:00Z").status,
+ "unmatched"
+ );
+ assert.equal(
+ azureMonitor.matchFoundryPrice(
+ "gpt-4.1",
+ "2025-04-14",
+ "Input",
+ "eastus",
+ [{ ...base, ModelText: "GPT-4.1-mini 2025-04-14 input tokens" }],
+ { ...deployment, modelName: "gpt-4.1", modelVersion: "2025-04-14" },
+ "2026-03-01T00:00:00Z"
+ ).status,
+ "unmatched",
+ "a base model must not use a suffixed model's price"
+ );
+ const previousMonth = {
+ ...base,
+ x_EffectivePeriodStart: "2026-08-01T00:00:00Z",
+ x_EffectivePeriodEnd: "2026-09-01T00:00:00Z",
+ };
+ const fallback = azureMonitor.matchFoundryPrice(
+ "gpt-4o",
+ "2024-08-06",
+ "Input",
+ "eastus",
+ [previousMonth],
+ deployment,
+ "2026-09-02T00:00:00Z"
+ );
+ assert.equal(fallback.status, "matched");
+ assert.equal(fallback.rateBasis, "previous-month");
+ assert.match(fallback.reason, /previous month's rate/);
+ assert.equal(
+ azureMonitor.matchFoundryPrice(
+ "gpt-4o",
+ "2024-08-06",
+ "Input",
+ "eastus",
+ [previousMonth],
+ deployment,
+ "2026-10-01T00:00:00Z"
+ ).status,
+ "unmatched",
+ "the fallback must not use a price sheet older than the previous month"
+ );
+ const currentMonth = {
+ ...base,
+ SelectedUnitPrice: 0.003,
+ x_EffectivePeriodStart: "2026-09-01T00:00:00Z",
+ x_EffectivePeriodEnd: "2026-10-01T00:00:00Z",
+ };
+ const current = azureMonitor.matchFoundryPrice(
+ "gpt-4o",
+ "2024-08-06",
+ "Input",
+ "eastus",
+ [previousMonth, currentMonth],
+ deployment,
+ "2026-09-02T00:00:00Z"
+ );
+ assert.equal(current.status, "matched");
+ assert.equal(current.rateBasis, "active");
+ assert.equal(current.unitPricePerToken, 0.000003);
+ const cached = azureMonitor.matchFoundryPrice(
+ "gpt-4o",
+ "2024-08-06",
+ "Cached input",
+ "eastus",
+ [{ ...base, Variant: "Cached", ModelText: "GPT-4o 2024-08-06 cached input tokens", SelectedUnitPrice: 0.0005 }],
+ deployment,
+ "2026-03-01T00:00:00Z"
+ );
+ assert.equal(cached.status, "matched");
+ assert.equal(cached.unitPricePerToken, 0.0000005);
+ assert.equal(
+ azureMonitor.matchFoundryPrice(
+ "gpt-4o",
+ "2024-08-06",
+ "Cached input",
+ "eastus",
+ [{
+ ...base,
+ Variant: "Cached",
+ ModelText: "GPT-4o 2024-08-06 LongCo Cd Inp tokens",
+ SkuMeter: "GPT-4o 2024-08-06 LongCo Cd Inp tokens",
+ }],
+ deployment,
+ "2026-03-01T00:00:00Z"
+ ).status,
+ "unmatched",
+ "cached-input estimates must not mix in long-context cache meters"
+ );
+
+ const lunaDeployment = {
+ name: "gpt-5.6-luna",
+ skuName: "GlobalStandard",
+ modelName: "gpt-5.6-luna",
+ modelVersion: "2026-07-09",
+ };
+ const lunaPrice = {
+ Direction: "Input",
+ Variant: "Standard",
+ ModelText: "5.6 luna ShortCo Inp Std Gl 1M Tokens",
+ SkuMeter: "5.6 luna ShortCo Inp Std Gl 1M Tokens",
+ PriceScope: "Global",
+ SelectedUnitPrice: 2,
+ x_PricingBlockSize: 10000000,
+ PricingCurrency: "USD",
+ ScopeMatch: true,
+ ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-08-01T00:00:00Z",
+ x_EffectivePeriodEnd: "2026-09-01T00:00:00Z",
+ };
+ const luna = azureMonitor.matchFoundryPrice(
+ "gpt-5.6-luna",
+ "2026-07-09",
+ "Input",
+ "eastus",
+ [lunaPrice],
+ lunaDeployment,
+ "2026-09-02T00:00:00Z"
+ );
+ assert.equal(luna.status, "matched");
+ assert.equal(luna.rateBasis, "previous-month");
+ assert.equal(luna.unitPricePerToken, 0.0000002);
+ assert.equal(
+ azureMonitor.matchFoundryPrice(
+ "gpt-5.6-luna",
+ "2026-07-09",
+ "Input",
+ "eastus",
+ [{ ...lunaPrice, ModelText: "5.6 luna LongCo Inp Std Gl 1M Tokens", SkuMeter: "5.6 luna LongCo Inp Std Gl 1M Tokens" }],
+ lunaDeployment,
+ "2026-09-02T00:00:00Z"
+ ).status,
+ "unmatched",
+ "the canonical estimate must not mix long-context rates into undifferentiated token metrics"
+ );
+});
+
+test("agent token pricing reports partial coverage without treating estimates as billed cost", () => {
+ const account = {
+ id: "/subscriptions/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee/resourceGroups/ai/providers/Microsoft.CognitiveServices/accounts/foundry",
+ subscriptionId: "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee",
+ location: "eastus",
+ };
+ const deployment = {
+ name: "chat-prod", skuName: "Standard", modelName: "gpt-4o", modelVersion: "2024-08-06",
+ };
+ const price = {
+ Direction: "Input", Variant: "Standard", ModelText: "GPT-4o 2024-08-06 input tokens",
+ PriceRegionId: "eastus", PriceScope: "Regional", SelectedUnitPrice: 0.002,
+ x_PricingBlockSize: 1000, PricingCurrency: "USD", ScopeMatch: true, ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-01-01T00:00:00Z", x_EffectivePeriodEnd: null,
+ };
+ const result = azureMonitor.priceAgentTokenUsage(
+ {
+ AccountId: account.id, Model: "chat-prod", InputTokens: 1000,
+ CachedInputTokens: 0, OutputTokens: 500,
+ },
+ [account],
+ new Map([[account.id.toLowerCase(), [deployment]]]),
+ new Map([[account.subscriptionId, [price]]]),
+ "2026-03-01T00:00:00Z"
+ );
+ assert.equal(result.PriceStatus, "partial");
+ assert.equal(result.PriceCoverage, 2 / 3);
+ assert.equal(result.EstimatedCost, 0.002);
+ assert.equal("BilledCost" in result, false);
+});
+
+test("AI Foundry dashboard batches platform metrics and supports estate drill-down", async () => {
+ const tenantId = "11111111-2222-4333-8444-555555555555";
+ const subscriptionId = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee";
+ const accountA = `/subscriptions/${subscriptionId}/resourceGroups/ai-rg/providers/Microsoft.CognitiveServices/accounts/foundry-a`;
+ const accountB = `/subscriptions/${subscriptionId}/resourceGroups/ai-rg/providers/Microsoft.CognitiveServices/accounts/foundry-b`;
+ const accounts = [
+ { id: accountA, name: "foundry-a", resourceGroup: "ai-rg", subscriptionId, location: "eastus", kind: "AIServices", sku: "S0" },
+ { id: accountB, name: "foundry-b", resourceGroup: "ai-rg", subscriptionId, location: "eastus", kind: "AIServices", sku: "S0" },
+ ];
+ const tokenCalls = [];
+ const fetchCalls = [];
+ const execFileFn = async (_file, args) => {
+ tokenCalls.push(args);
+ return {
+ stdout: JSON.stringify({
+ accessToken: `token-${tokenCalls.length}`,
+ expires_on: Math.floor(Date.now() / 1000) + 3600,
+ }),
+ };
+ };
+ const metricPayload = (url, resourceIds) => {
+ const parsed = new URL(url);
+ const metricNames = parsed.searchParams.get("metricnames").split(",");
+ const filter = parsed.searchParams.get("filter");
+ return {
+ values: resourceIds.map((resourceId, accountIndex) => ({
+ resourceid: resourceId,
+ value: metricNames.map((metricName) => {
+ const base = accountIndex + 1;
+ const modelName = accountIndex ? "gpt-4o-mini" : "gpt-4o";
+ const modelVersion = accountIndex ? "2024-07-18" : "2024-08-06";
+ const values = {
+ InputTokens: 1000 * base,
+ OutputTokens: 500 * base,
+ TotalTokens: 1500 * base,
+ TimeToLastByte: 200 * base,
+ AzureOpenAITTLTInMS: 250 * base,
+ AzureOpenAITokenPerSecond: 40 * base,
+ AzureOpenAIContextTokensCacheMatchRate: 80,
+ };
+ const metadata = [
+ { name: { value: "ModelDeploymentName" }, value: "chat-prod" },
+ { name: { value: "ModelName" }, value: modelName },
+ { name: { value: "ModelVersion" }, value: modelVersion },
+ ];
+ const timeseries = metricName === "ModelRequests"
+ ? [
+ {
+ metadatavalues: [...metadata, { name: { value: "StatusCode" }, value: "200" }],
+ data: [{ timeStamp: "2026-03-01T12:00:00Z", total: 9 * base }],
+ },
+ {
+ metadatavalues: [...metadata, { name: { value: "StatusCode" }, value: "429" }],
+ data: [{ timeStamp: "2026-03-01T12:00:00Z", total: base }],
+ },
+ ]
+ : [{
+ metadatavalues: metadata,
+ data: [{
+ timeStamp: "2026-03-01T12:00:00Z",
+ [["InputTokens", "OutputTokens", "TotalTokens"].includes(metricName) ? "total" : "average"]:
+ values[metricName],
+ }],
+ }];
+ return {
+ name: { value: metricName },
+ timeseries,
+ };
+ }),
+ })),
+ };
+ };
+ const fetchFn = async (url, init = {}) => {
+ const target = String(url);
+ fetchCalls.push({ url: target, init });
+ if (target.includes("Microsoft.ResourceGraph")) {
+ return Response.json({ data: accounts });
+ }
+ if (target.includes("/batch?")) {
+ const requests = JSON.parse(init.body).requests;
+ return Response.json({
+ responses: requests.map((request, index) => ({
+ httpStatusCode: 200,
+ content: {
+ value: [{
+ name: "chat-prod",
+ sku: { name: "GlobalStandard" },
+ properties: {
+ model: {
+ name: index ? "gpt-4o-mini" : "gpt-4o",
+ version: index ? "2024-07-18" : "2024-08-06",
+ format: "OpenAI",
+ },
+ provisioningState: "Succeeded",
+ },
+ }],
+ },
+ })),
+ });
+ }
+ if (target.includes(".metrics.monitor.azure.com/")) {
+ return Response.json(metricPayload(target, JSON.parse(init.body).resourceids));
+ }
+ throw new Error(`Unexpected test URL: ${url}`);
+ };
+ const priceRows = [
+ {
+ SubAccountId: subscriptionId,
+ Direction: "Input",
+ Variant: "Standard",
+ ModelText: "GPT-4o 2024-08-06 input tokens",
+ PriceScope: "Global",
+ SelectedUnitPrice: 0.002,
+ x_PricingBlockSize: 1000,
+ PricingCurrency: "USD",
+ ScopeMatch: true,
+ ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-03-01T00:00:00Z",
+ x_EffectivePeriodEnd: "2026-04-01T00:00:00Z",
+ },
+ {
+ SubAccountId: subscriptionId,
+ Direction: "Output",
+ Variant: "Standard",
+ ModelText: "GPT-4o 2024-08-06 output tokens",
+ PriceScope: "Global",
+ SelectedUnitPrice: 0.008,
+ x_PricingBlockSize: 1000,
+ PricingCurrency: "USD",
+ ScopeMatch: true,
+ ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-03-01T00:00:00Z",
+ x_EffectivePeriodEnd: "2026-04-01T00:00:00Z",
+ },
+ {
+ SubAccountId: subscriptionId,
+ Direction: "Input",
+ Variant: "Standard",
+ ModelText: "GPT-4o-mini 2024-07-18 input tokens",
+ PriceScope: "Global",
+ SelectedUnitPrice: 0.002,
+ x_PricingBlockSize: 1000,
+ PricingCurrency: "USD",
+ ScopeMatch: true,
+ ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-03-01T00:00:00Z",
+ x_EffectivePeriodEnd: "2026-04-01T00:00:00Z",
+ },
+ {
+ SubAccountId: subscriptionId,
+ Direction: "Output",
+ Variant: "Standard",
+ ModelText: "GPT-4o-mini 2024-07-18 output tokens",
+ PriceScope: "Global",
+ SelectedUnitPrice: 0.008,
+ x_PricingBlockSize: 1000,
+ PricingCurrency: "USD",
+ ScopeMatch: true,
+ ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-03-01T00:00:00Z",
+ x_EffectivePeriodEnd: "2026-04-01T00:00:00Z",
+ },
+ ];
+ const priceCalls = [];
+ const common = {
+ connection: {},
+ database: "Hub",
+ tenantId,
+ preset: "24h",
+ getPrices: async (_connection, _database, subscriptionIds, options) => {
+ priceCalls.push({ subscriptionIds, models: options.models });
+ return priceRows;
+ },
+ options: { execFileFn, fetchFn, now: "2026-03-02T00:00:00Z" },
+ };
+ const payload = await azureMonitor.getFoundryDashboard(common);
+ assert.equal(payload.selectedAccountId, null);
+ assert.equal(payload.accounts.length, 2);
+ assert.equal(payload.panels.length, 11);
+ assert.equal(payload.data.summary.InputTokens, 3000);
+ assert.equal(payload.data.summary.OutputTokens, 1500);
+ assert.equal(payload.data.summary.TotalTokens, 4500);
+ assert.equal(payload.data.summary.Requests, 30);
+ assert.equal(payload.data.summary.Errors, 3);
+ assert.ok(Math.abs(payload.data.summary.EstimatedCost - 0.018) < 1e-12);
+ assert.equal(payload.data.summary.PriceCoverage, 1);
+ assert.equal(payload.data.charts.modelRequests.length, 2);
+ assert.equal(payload.data.charts.requestErrors[0].Points[0].Value, 3);
+ assert.equal(payload.data.charts.latency.length, 4);
+ assert.equal(payload.data.charts.tokensPerSecond.length, 2);
+ assert.equal(payload.data.charts.cacheMatchRate.length, 2);
+ assert.deepEqual(payload.data.stats.costs.map((row) => row.Model).sort(), ["gpt-4o", "gpt-4o-mini"]);
+ assert.equal("agents" in payload, false);
+ assert.deepEqual(priceCalls, [{
+ subscriptionIds: [subscriptionId],
+ models: ["gpt-4o", "gpt-4o-mini"],
+ }]);
+ assert.equal(tokenCalls.length, 2);
+ assert.ok(tokenCalls.some((args) => args.includes("https://management.azure.com/")));
+ assert.ok(tokenCalls.some((args) => args.includes("https://metrics.monitor.azure.com/")));
+ assert.equal(fetchCalls.filter((call) => call.url.includes(".metrics.monitor.azure.com/")).length, 1);
+ assert.equal(fetchCalls.filter((call) => call.url.includes("/batch?")).length, 1);
+ assert.ok(fetchCalls.filter((call) => call.url.includes(".metrics.monitor.azure.com/"))
+ .every((call) => JSON.parse(call.init.body).resourceids.length === 2));
+ assert.ok(fetchCalls.every((call) => !call.url.includes("applicationinsights")));
+ assert.ok(fetchCalls.every((call) => !call.url.includes("loganalytics")));
+
+ const scoped = await azureMonitor.getFoundryDashboard({ ...common, accountId: accountB });
+ assert.equal(scoped.selectedAccountId, accountB);
+ assert.equal(scoped.data.summary.AccountCount, 1);
+ assert.equal(scoped.data.summary.TotalTokens, 3000);
+ assert.ok(scoped.data.charts.modelRequests.every((series) => !series.Name.includes(" / ")));
+ assert.equal(fetchCalls.filter((call) => call.url.includes(".metrics.monitor.azure.com/")).length, 1);
+});
+
+test("AI Foundry panel contract matches the canonical Grafana export", () => {
+ assert.deepEqual(
+ azureMonitor.FOUNDRY_PANEL_CONTRACT.map(({ id, title, type, gridPos, unit, style, fillOpacity }) =>
+ ({ id, title, type, gridPos, unit, style, fillOpacity })),
+ [
+ { id: 13, title: "Estimated Cost", type: "stat", gridPos: { h: 4, w: 24, x: 0, y: 0 }, unit: "currency", style: undefined, fillOpacity: undefined },
+ { id: 11, title: "Input Tokens (total)", type: "stat", gridPos: { h: 5, w: 24, x: 0, y: 4 }, unit: "short", style: undefined, fillOpacity: undefined },
+ { id: 12, title: "Output Tokens (total)", type: "stat", gridPos: { h: 5, w: 24, x: 0, y: 9 }, unit: "short", style: undefined, fillOpacity: undefined },
+ { id: 2, title: "Model Requests", type: "timeseries", gridPos: { h: 10, w: 12, x: 0, y: 14 }, unit: "short", style: "bars", fillOpacity: 60 },
+ { id: 16, title: "Non-200 Model Requests (Throttling & Errors)", type: "timeseries", gridPos: { h: 10, w: 12, x: 12, y: 14 }, unit: "short", style: "bars", fillOpacity: 80 },
+ { id: 7, title: "Average Latency (Time to Last Byte)", type: "timeseries", gridPos: { h: 10, w: 12, x: 0, y: 24 }, unit: "ms", style: "lines", fillOpacity: 21 },
+ { id: 17, title: "Tokens per Second (OpenAI models)", type: "timeseries", gridPos: { h: 10, w: 12, x: 12, y: 24 }, unit: "short", style: "lines", fillOpacity: 10 },
+ { id: 4, title: "Input Tokens", type: "timeseries", gridPos: { h: 10, w: 12, x: 0, y: 34 }, unit: "short", style: "bars", fillOpacity: 60 },
+ { id: 5, title: "Output Tokens", type: "timeseries", gridPos: { h: 10, w: 12, x: 12, y: 34 }, unit: "short", style: "bars", fillOpacity: 60 },
+ { id: 8, title: "Total Tokens", type: "timeseries", gridPos: { h: 10, w: 12, x: 0, y: 44 }, unit: "short", style: "bars", fillOpacity: 60 },
+ { id: 14, title: "Token Cache Match Rate (OpenAI models)", type: "timeseries", gridPos: { h: 10, w: 12, x: 12, y: 44 }, unit: "percent", style: "lines", fillOpacity: 21 },
+ ]
+ );
+});
+
+test("AI Foundry Hub price query is bounded and preserves pricing identity", async () => {
+ let query = "";
+ await kusto.getFoundryPriceCatalog(
+ { clusterUri: "http://localhost:8082", database: "Hub" },
+ "Hub",
+ [
+ "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee",
+ "11111111-2222-4333-8444-555555555555",
+ ],
+ {
+ fetchImpl: async (_url, init) => {
+ query = JSON.parse(init.body).csl;
+ return kustoResponse([]);
+ },
+ start: "2026-01-01T00:00:00Z",
+ end: "2026-03-01T00:00:00Z",
+ models: ["gpt-5.6-luna"],
+ }
+ );
+ assert.match(query, /Prices\(\)/);
+ assert.match(query, /x_PricingBlockSize/);
+ assert.match(query, /lookup kind=leftouter regions/);
+ assert.match(query, /lookup kind=inner scope/);
+ assert.match(query, /ResourceLocation/);
+ assert.match(query, /ScopeSubAccountId in \(targetSubscriptions\)/);
+ assert.match(query, /PricingUnit has 'Tokens'/);
+ assert.match(query, /SkuMeter has_all \("5\.6", "luna"\)/);
+ assert.doesNotMatch(query, /OriginalValue|x_SkuMeterName|x_PricingCurrency/);
+ assert.match(query, /x_SkuPriceType =~ 'Consumption'/);
+ assert.match(query, /Variant=case/);
+ assert.match(query, /SkuMeter has_any \('Cached', 'Cache', 'Cd', 'Wr'\), 'Cached'/);
+ assert.ok(
+ query.indexOf("SkuMeter has 'LongCo', 'LongContext'") <
+ query.indexOf("SkuMeter has_any ('Cached', 'Cache', 'Cd', 'Wr'), 'Cached'"),
+ "specialized meters must be classified before generic cached-input meters"
+ );
+ assert.match(query, /PriceScope=case/);
+ assert.match(query, /SkuMeter has 'Gl'/);
+ assert.match(query, /'Opt'\), 'Output'/);
+ assert.match(query, /ScopeCurrency/);
+ assert.match(query, /where ScopeMatch and PricingCurrency =~ ScopeCurrency/);
+ assert.match(query, /x_SkuMeterId/);
+ assert.match(query, /x_EffectivePeriodStart < metricEnd/);
+ assert.match(query, /metricStart < datetime_add\('month', 1, x_EffectivePeriodEnd\)/);
+ assert.match(query, /ScopeBillingAccountId/);
+ assert.match(query, /ScopeBillingProfileId/);
+ assert.match(query, /x_BillingAccountId/);
+ assert.match(query, /x_BillingProfileId/);
+ assert.match(query, /take 10000/);
+ assert.doesNotMatch(query, /\|\s*join(?!\s+kind=)/);
+});
+
+test("AI Foundry agent cost query keeps Hub work bounded", () => {
+ const query = kusto.buildFoundryAgentCostsQuery({
+ start: "2026-02-01T00:00:00Z",
+ end: "2026-03-01T00:00:00Z",
+ });
+ assert.match(query, /Costs\(\)/);
+ assert.match(query, /ChargePeriodStart >= CostStart and ChargePeriodStart < ActivityEnd/);
+ assert.match(query, /x_SkuMeterSubcategory has 'Agent'/);
+ assert.match(query, /by AgentResourceId, BillingCurrency/);
+ assert.doesNotMatch(query, /AppTraces|AppDependencies|macro-expand|\|\s*join(?!\s+kind=)/);
+ assert.throws(
+ () => kusto.buildFoundryAgentCostsQuery({
+ start: "invalid",
+ end: "2026-03-01T00:00:00Z",
+ }),
+ /valid start and end time/
+ );
+});
+
+test("Foundry agents dashboard shares rich telemetry across account scopes and keeps billed cost separate", async () => {
+ const tenantId = "99999999-2222-4333-8444-555555555555";
+ const subscriptionId = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee";
+ const accountId = `/subscriptions/${subscriptionId}/resourceGroups/ai-rg/providers/Microsoft.CognitiveServices/accounts/foundry-a`;
+ const projectId = `${accountId}/projects/finops`;
+ const workspaceId = `/subscriptions/${subscriptionId}/resourceGroups/monitor-rg/providers/Microsoft.OperationalInsights/workspaces/law-prod`;
+ const discoveryRows = [
+ {
+ ResourceKind: "account", id: accountId, name: "foundry-a", resourceGroup: "ai-rg",
+ subscriptionId, location: "eastus", kind: "AIServices", sku: "S0",
+ },
+ {
+ ResourceKind: "deployment", id: `${accountId}/deployments/chat-prod`, name: "foundry-a/chat-prod",
+ subscriptionId, location: "eastus", sku: "GlobalStandard", modelName: "gpt-4o",
+ modelVersion: "2024-08-06", modelFormat: "OpenAI", provisioningState: "Succeeded",
+ },
+ {
+ ResourceKind: "project", id: projectId, name: "finops",
+ subscriptionId, location: "eastus",
+ },
+ {
+ ResourceKind: "workspace", id: workspaceId, name: "law-prod", resourceGroup: "monitor-rg",
+ subscriptionId, location: "westus", customerId: "11111111-2222-4333-8444-555555555555",
+ },
+ {
+ ResourceKind: "workspace", id: workspaceId.toLowerCase(), name: "law-prod", resourceGroup: "monitor-rg",
+ subscriptionId, location: "westus", customerId: "11111111-2222-4333-8444-555555555555",
+ },
+ {
+ ResourceKind: "application-insights",
+ id: `/subscriptions/${subscriptionId}/resourceGroups/monitor-rg/providers/Microsoft.Insights/components/appi-prod`,
+ name: "appi-prod",
+ workspaceResourceId: workspaceId,
+ },
+ ];
+ const priceRows = [
+ {
+ RowType: "Price", SubAccountId: subscriptionId,
+ Direction: "Input", Variant: "Standard", ModelText: "GPT-4o 2024-08-06 input tokens",
+ PriceScope: "Global", SelectedUnitPrice: 0.002, x_PricingBlockSize: 1000,
+ PricingCurrency: "USD", ScopeMatch: true, ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-02-01T00:00:00Z", x_EffectivePeriodEnd: null,
+ },
+ {
+ RowType: "Price", SubAccountId: subscriptionId,
+ Direction: "Input", Variant: "Cached", ModelText: "GPT-4o 2024-08-06 cached input tokens",
+ PriceScope: "Global", SelectedUnitPrice: 0.0005, x_PricingBlockSize: 1000,
+ PricingCurrency: "USD", ScopeMatch: true, ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-02-01T00:00:00Z", x_EffectivePeriodEnd: null,
+ },
+ {
+ RowType: "Price", SubAccountId: subscriptionId,
+ Direction: "Output", Variant: "Standard", ModelText: "GPT-4o 2024-08-06 output tokens",
+ PriceScope: "Global", SelectedUnitPrice: 0.008, x_PricingBlockSize: 1000,
+ PricingCurrency: "USD", ScopeMatch: true, ScopeCurrency: "USD",
+ x_EffectivePeriodStart: "2026-02-01T00:00:00Z", x_EffectivePeriodEnd: null,
+ },
+ ];
+ const telemetryRows = [
+ {
+ RowType: "AgentSummary", AgentKey: "finops-hub-demo-foundry-agent:3",
+ AgentName: "foundry-agent", AgentId: "finops-hub-demo-foundry-agent:3",
+ FoundryProjectId: projectId, ActivityEvents: 20, Operations: 1, Successes: 1, Errors: 0,
+ TotalDurationMs: 400, AverageLatencyMs: 400, P95LatencyMs: 400,
+ InputTokens: 1000, CachedInputTokens: 200, OutputTokens: 300, LastSeen: "2026-03-01T23:56:00Z",
+ },
+ {
+ RowType: "TokenBucket", BucketStart: "2026-03-01T23:00:00Z", AgentKey: "finops-hub-demo-foundry-agent:3",
+ AgentName: "foundry-agent", AgentId: "finops-hub-demo-foundry-agent:3", FoundryProjectId: projectId,
+ Model: "gpt-4o-2024-08-06", InputTokens: 1000, CachedInputTokens: 200, OutputTokens: 300,
+ },
+ {
+ RowType: "ModelUsage", AgentKey: "finops-hub-demo-foundry-agent:3", AgentName: "foundry-agent",
+ AgentId: "finops-hub-demo-foundry-agent:3", FoundryProjectId: projectId, Model: "gpt-4o-2024-08-06",
+ Chats: 1, InputTokens: 1000, CachedInputTokens: 200, OutputTokens: 300,
+ AverageLatencyMs: 300, P95LatencyMs: 300, LastSeen: "2026-03-01T23:56:00Z",
+ },
+ {
+ RowType: "Run", Timestamp: "2026-03-01T23:56:00Z", TraceId: "trace-1",
+ AgentKey: "finops-hub-demo-foundry-agent:3", AgentName: "foundry-agent",
+ AgentId: "finops-hub-demo-foundry-agent:3", FoundryProjectId: projectId, Model: "gpt-4o-2024-08-06",
+ InputTokens: 1000, CachedInputTokens: 200, OutputTokens: 300, DurationMs: 400, Success: true,
+ },
+ {
+ RowType: "FinishReason", AgentKey: "finops-hub-demo-foundry-agent:3", AgentName: "foundry-agent",
+ FoundryProjectId: projectId, FinishReason: "[\"stop\"]", Count: 1,
+ },
+ {
+ RowType: "Tool", AgentKey: "finops-hub-demo-foundry-agent:3", AgentName: "foundry-agent",
+ FoundryProjectId: projectId, ToolName: "Costs", Calls: 2, Errors: 0, AverageLatencyMs: 50,
+ },
+ ...priceRows,
+ ];
+ let discoveryCalls = 0;
+ let connectionCalls = 0;
+ let kustoCalls = 0;
+ const fetchFn = async (url, init = {}) => {
+ const target = String(url);
+ if (target.includes("Microsoft.ResourceGraph")) {
+ const query = JSON.parse(init.body).query;
+ discoveryCalls += 1;
+ assert.match(query, /microsoft\.cognitiveservices\/accounts\/deployments/);
+ assert.match(query, /microsoft\.cognitiveservices\/accounts\/projects/);
+ assert.doesNotMatch(query, /microsoft\.app\/agents/);
+ assert.match(query, /microsoft\.insights\/components/);
+ assert.match(query, /microsoft\.operationalinsights\/workspaces/);
+ return Response.json({ data: discoveryRows });
+ }
+ if (target.includes("management.azure.com/batch")) {
+ const requests = JSON.parse(init.body).requests;
+ connectionCalls += 1;
+ assert.equal(requests.length, 1);
+ assert.match(requests[0].relativeUrl, /\/projects\/finops\/connections\?category=AppInsights&api-version=2025-06-01$/);
+ return Response.json({
+ responses: [{
+ httpStatusCode: 200,
+ content: {
+ value: [{
+ properties: {
+ category: "AppInsights",
+ target: `/subscriptions/${subscriptionId}/resourceGroups/monitor-rg/providers/Microsoft.Insights/components/appi-prod`,
+ },
+ }],
+ },
+ }],
+ });
+ }
+ throw new Error(`Unexpected test URL: ${url}`);
+ };
+ const runQuery = async (_connection, _database, query, queryOptions) => {
+ kustoCalls += 1;
+ assert.match(query, /^set query_results_cache_max_age = time\(30s\);/);
+ assert.match(query, /let MonitorWorkspaces = entity_group/);
+ assert.match(query, /macro-expand kind=inner isfuzzy=true MonitorWorkspaces/);
+ assert.match(query, /let Base = materialize\(/);
+ assert.match(query, /isnotempty\(AgentKey\) and isnotempty\(FoundryProjectId\)/);
+ assert.match(query, /adx\.monitor\.azure\.com\/subscriptions/);
+ assert.match(query, /SourceTable endswith 'AppDependencies'/);
+ assert.match(query, /OperationName =~ 'chat'/);
+ assert.match(query, /OperationName =~ 'execute_tool'/);
+ assert.match(query, /join kind=leftouter RunModels/);
+ assert.match(query, /let CostRows = materialize\(/);
+ assert.match(query, /let BilledCostRows = CostRows/);
+ assert.match(query, /let PriceRows = Prices\(\)/);
+ assert.match(query, /ScopeBillingAccountId/);
+ assert.match(query, /ScopeBillingProfileId/);
+ assert.match(query, /union AgentRows, BilledCostRows/);
+ assert.equal(queryOptions.maxResponseBytes, 16 * 1024 * 1024);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ return telemetryRows;
+ };
+ const common = {
+ connection: { clusterUri: "http://localhost:8082", database: "Hub" },
+ database: "Hub",
+ tenantId,
+ preset: "7d",
+ runQuery,
+ options: {
+ fetchFn,
+ execFileFn: async () => ({
+ stdout: JSON.stringify({ accessToken: "token", expires_on: Math.floor(Date.now() / 1000) + 3600 }),
+ }),
+ now: "2026-03-02T00:00:00Z",
+ agentCacheTtlMs: 1000,
+ },
+ };
+ const [estate, account] = await Promise.all([
+ azureMonitor.getAgentsDashboard(common),
+ azureMonitor.getAgentsDashboard({ ...common, accountId }),
+ ]);
+ assert.equal(discoveryCalls, 1);
+ assert.equal(connectionCalls, 1);
+ assert.equal(kustoCalls, 1);
+ assert.equal(estate.workspaceCount, 1);
+ assert.equal(estate.summary.AgentCount, 1);
+ assert.equal(account.summary.AgentCount, 1);
+ assert.equal(account.agents[0].AgentName, "foundry-agent");
+ assert.equal(account.recentRuns[0].TraceId, "trace-1");
+ assert.ok(Math.abs(account.recentRuns[0].EstimatedCost - 0.0041) < 1e-12);
+ assert.equal(account.recentRuns[0].UncachedInputTokens, 800);
+ assert.ok(Math.abs(account.recentRuns[0].UncachedInputCost - 0.0016) < 1e-12);
+ assert.ok(Math.abs(account.recentRuns[0].CachedInputCost - 0.0001) < 1e-12);
+ assert.ok(Math.abs(account.recentRuns[0].OutputCost - 0.0024) < 1e-12);
+ assert.equal(account.recentRuns[0].PriceCoverage, 1);
+ assert.ok(Math.abs(account.summary.UncachedInputCost - 0.0016) < 1e-12);
+ assert.ok(Math.abs(account.summary.CachedInputCost - 0.0001) < 1e-12);
+ assert.ok(Math.abs(account.summary.OutputCost - 0.0024) < 1e-12);
+ assert.ok(Math.abs(account.agents[0].UncachedInputCost - 0.0016) < 1e-12);
+ assert.ok(Math.abs(account.models[0].CachedInputCost - 0.0001) < 1e-12);
+ assert.ok(Math.abs(account.charts.tokens[0].OutputCost - 0.0024) < 1e-12);
+ assert.equal(account.agents[0].BilledCostStatus, "Not an ARM resource identity");
+ assert.equal(estate.agents[0].AgentType, "Microsoft Foundry agent");
+});
+
+test("local dashboard semantics stay unauthenticated and preserve the payload shape", async (t) => {
+ const requests = [];
+ const server = createServer(async (req, res) => {
+ let body = "";
+ for await (const chunk of req) body += chunk;
+ const { csl } = JSON.parse(body);
+ requests.push(req.headers);
+ const rows = csl.includes("MinDate=min")
+ ? [{ MinDate: "2025-01-01T00:00:00Z", MaxDate: "2025-04-01T00:00:00Z", Rows: 4 }]
+ : [];
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(await kustoResponse(rows, columns).text());
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => server.close());
+
+ const { port } = server.address();
+ const payload = await kusto.getDashboard(`http://127.0.0.1:${port}`, "Hub");
+ assert.equal(payload.empty, false);
+ assert.deepEqual(Object.keys(payload.data), [
+ "summary", "tagged", "pricing", "trend", "serviceCategory",
+ "topServices", "topResourceGroups", "topRegions", "chargeCategory",
+ ]);
+ assert.equal(requests.length, 10);
+ assert.ok(requests.every((headers) => headers.authorization === undefined));
+ assert.ok(requests.every((headers) => headers["x-ms-readonly"] === "true"));
+});
+
+test("remote requests deduplicate tokens, add read-only headers, and recover after failure", async () => {
+ kusto.resetKustoAuthForTests();
+ const tenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47";
+ const providerCalls = [];
+ let release;
+ const provider = async (requestedTenantId) => {
+ providerCalls.push(requestedTenantId);
+ await new Promise((resolve) => { release = resolve; });
+ return { accessToken: "secret-token", expires_on: Math.floor(Date.now() / 1000) + 3600 };
+ };
+ const seen = [];
+ const fetchImpl = async (_url, options) => {
+ seen.push(options.headers);
+ return kustoResponse([{ Ready: 1 }]);
+ };
+ const connection = { clusterUri: "https://cluster.westus.kusto.windows.net", tenantId };
+ const first = kusto.runQuery(connection, "Hub", "print Ready=1", { tokenProvider: provider, fetchImpl });
+ const second = kusto.runQuery(connection, "Hub", "print Ready=1", { tokenProvider: provider, fetchImpl });
+ await new Promise((resolve) => setImmediate(resolve));
+ release();
+ await Promise.all([first, second]);
+ assert.deepEqual(providerCalls, [tenantId]);
+ assert.equal(seen.length, 2);
+ assert.ok(seen.every((headers) => headers.Authorization === "Bearer secret-token"));
+ assert.ok(seen.every((headers) => headers["x-ms-readonly"] === "true"));
+ assert.notEqual(seen[0]["x-ms-client-request-id"], seen[1]["x-ms-client-request-id"]);
+
+ const otherTenantId = "91700184-c314-4dc9-bb7e-a411df456a1e";
+ const otherTenantCalls = [];
+ await kusto.runQuery(
+ { clusterUri: connection.clusterUri, tenantId: otherTenantId },
+ "Hub",
+ "print Ready=1",
+ {
+ tokenProvider: async (requestedTenantId) => {
+ otherTenantCalls.push(requestedTenantId);
+ return { accessToken: "other-secret-token", expires_on: Math.floor(Date.now() / 1000) + 3600 };
+ },
+ fetchImpl,
+ }
+ );
+ assert.deepEqual(otherTenantCalls, [otherTenantId]);
+
+ kusto.resetKustoAuthForTests();
+ await assert.rejects(() => kusto.runQuery(
+ connection,
+ "Hub",
+ "print Ready=1",
+ { tokenProvider: async () => { throw new Error("temporary"); }, fetchImpl }
+ ));
+ await kusto.runQuery(
+ connection,
+ "Hub",
+ "print Ready=1",
+ {
+ tokenProvider: async () => ({ accessToken: "recovered", expires_on: Math.floor(Date.now() / 1000) + 3600 }),
+ fetchImpl,
+ }
+ );
+});
+
+test("remote transport bounds concurrent Kusto requests", async () => {
+ kusto.resetKustoAuthForTests();
+ const connection = {
+ clusterUri: "https://cluster.westus.kusto.windows.net",
+ tenantId: "72f988bf-86f1-41af-91ab-2d7cd011db47",
+ };
+ let active = 0;
+ let maximum = 0;
+ const fetchImpl = async () => {
+ active++;
+ maximum = Math.max(maximum, active);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ active--;
+ return kustoResponse([{ Ready: 1 }]);
+ };
+ await Promise.all(Array.from({ length: 12 }, (_, index) => kusto.runQuery(
+ connection,
+ "Hub",
+ `print Ready=${index}`,
+ {
+ tokenProvider: async () => ({
+ accessToken: "secret-token",
+ expires_on: Math.floor(Date.now() / 1000) + 3600,
+ }),
+ fetchImpl,
+ }
+ )));
+ assert.equal(maximum, 1);
+});
+
+test("remote transport retries transient fetch failures", async () => {
+ kusto.resetKustoAuthForTests();
+ let attempts = 0;
+ const result = await kusto.runQuery(
+ {
+ clusterUri: "https://cluster.westus.kusto.windows.net",
+ tenantId: "72f988bf-86f1-41af-91ab-2d7cd011db47",
+ },
+ "Hub",
+ "print Ready=1",
+ {
+ tokenProvider: async () => ({
+ accessToken: "secret-token",
+ expires_on: Math.floor(Date.now() / 1000) + 3600,
+ }),
+ fetchImpl: async () => {
+ attempts++;
+ if (attempts < 3) throw new TypeError("fetch failed");
+ return kustoResponse([{ Ready: 1 }]);
+ },
+ }
+ );
+ assert.equal(attempts, 3);
+ assert.deepEqual(result, [{ Ready: 1 }]);
+});
+
+test("transport errors are actionable and authentication failures redact provider output", async () => {
+ await assert.rejects(
+ () => kusto.runQuery("http://localhost:8082", "Hub", "print Ready=1", {
+ fetchImpl: async () => { throw new Error("ECONNREFUSED"); },
+ }),
+ /Could not reach Kusto at http:\/\/localhost:8082: ECONNREFUSED/
+ );
+
+ kusto.resetKustoAuthForTests();
+ await assert.rejects(
+ () => kusto.runQuery("https://cluster.westus.kusto.windows.net", "Hub", "print Ready=1"),
+ /Tenant ID is required for remote hubs/
+ );
+ await assert.rejects(
+ () => kusto.runQuery({
+ clusterUri: "https://cluster.westus.kusto.windows.net",
+ tenantId: "72f988bf-86f1-41af-91ab-2d7cd011db47",
+ }, "Hub", "print Ready=1", {
+ tokenProvider: async () => { throw new Error("secret-token-value"); },
+ fetchImpl: async () => assert.fail("fetch must not run without a token"),
+ }),
+ (err) => /Azure CLI could not acquire/.test(err.message) && !err.message.includes("secret-token-value")
+ );
+});
+
+test("response parsing detects partial failures and enforces the byte limit before parsing", async () => {
+ const partialResponse = {
+ Tables: [
+ { TableName: "Table_0", Columns: [{ ColumnName: "Value" }], Rows: [[1]] },
+ {
+ TableName: "Table_2",
+ Columns: [
+ { ColumnName: "Severity" },
+ { ColumnName: "StatusCode" },
+ { ColumnName: "StatusDescription" },
+ ],
+ Rows: [[2, -1, "Partial query failure"]],
+ },
+ ],
+ };
+ assert.throws(() => kusto.parseKustoResponse(partialResponse), /Partial query failure/);
+ const partialRows = kusto.parseKustoResponse(partialResponse, { allowPartialResults: true });
+ assert.deepEqual(partialRows, [{ Value: 1 }]);
+ assert.deepEqual(partialRows.queryWarnings, [
+ "One or more remote workspaces failed during the federated query. Results are partial.",
+ ]);
+ await assert.rejects(() => kusto.readBoundedBody(new Response("12345"), 4), /4-byte limit/);
+});
+
+test("filter encoding keeps adversarial values inside one Kusto string literal", () => {
+ const values = [
+ "O'Reilly",
+ "back\\slash",
+ "line\r\nbreak",
+ "x; .drop table Costs",
+ "// comment",
+ "/* comment */",
+ "東京",
+ ".show tables",
+ ];
+ const where = kusto.buildFilterWhere({ ServiceName: values });
+ for (const value of values) assert.ok(where.includes(JSON.stringify(value)));
+ assert.equal((where.match(/\| where/g) || []).length, 1);
+ assert.throws(() => kusto.buildFilterWhere({ BadColumn: ["x"] }), /Unsupported filter/);
+ assert.throws(() => kusto.validateFilters({ ServiceName: Array(9).fill("x") }), /at most 8/);
+});
+
+test("capacity registry is exact, versioned, and fail-closed", () => {
+ assert.equal(Object.keys(kusto.CAPACITY_CLASS_REGISTRY).length, 7);
+ assert.equal(Object.keys(kusto.CAPACITY_METRIC_REGISTRY).length, 8);
+
+ const enabled = kusto.resolveCapacityMetric({
+ x_SourceType: " computeusage ",
+ x_SourceVersion: "1.0-USAGE",
+ ResourceName: " CORES ",
+ unit: " count ",
+ });
+ assert.equal(enabled.capability, "enabled");
+ assert.equal(enabled.metricRole, "total-regional-vcpu");
+ const sqlEnabled = kusto.resolveCapacityMetric({
+ x_SourceType: "SqlSubscriptionUsage",
+ x_SourceVersion: "1.0-sql",
+ ResourceName: "RegionalVCoreQuotaForSQLDBAndDW",
+ unit: "Count",
+ });
+ assert.equal(sqlEnabled.capability, "enabled");
+ assert.equal(sqlEnabled.metricRole, "sql-database-vcore");
+
+ assert.deepEqual(
+ kusto.resolveCapacityMetric({
+ x_SourceType: "ComputeUsage",
+ x_SourceVersion: "1.0-usage",
+ ResourceName: "cores-extra",
+ unit: "Count",
+ }).capability,
+ "descriptive-only"
+ );
+ assert.equal(kusto.resolveCapacityMetric({
+ x_SourceType: "ComputeUsage",
+ x_SourceVersion: "2.0-usage",
+ ResourceName: "cores",
+ unit: "Count",
+ }).reasonCode, "source-version-mismatch");
+ assert.equal(kusto.resolveCapacityMetric({
+ x_SourceType: "AppServiceUsage",
+ x_SourceVersion: "1.0-usage",
+ ResourceName: "P1v3",
+ unit: "Instances",
+ }).reasonCode, "unclassified-metric");
+ assert.equal(kusto.resolveCapacityMetric({
+ x_SourceType: "UnknownUsage",
+ x_SourceVersion: "1.0",
+ ResourceName: "cores",
+ unit: "Count",
+ }).capability, "disabled");
+});
+
+test("capacity observation precedence handles invalid, stale, unclassified, and limit states", () => {
+ const now = new Date("2026-08-23T12:00:00Z");
+ const base = {
+ x_SourceType: "ComputeUsage",
+ x_SourceVersion: "1.0-usage",
+ ResourceName: "cores",
+ unit: "Count",
+ currentValue: 79,
+ limit: 100,
+ x_IngestionTime: "2026-08-23T10:00:00Z",
+ };
+ assert.equal(kusto.classifyCapacityObservation(base, now).state, "healthy");
+ assert.equal(kusto.classifyCapacityObservation({ ...base, currentValue: 80 }, now).state, "watch");
+ assert.equal(kusto.classifyCapacityObservation({ ...base, currentValue: 90 }, now).state, "action");
+ assert.equal(kusto.classifyCapacityObservation({ ...base, currentValue: 100 }, now).state, "exhausted");
+ assert.equal(kusto.classifyCapacityObservation({ ...base, currentValue: 0, limit: 0 }, now).state, "no-entitlement");
+ assert.equal(kusto.classifyCapacityObservation({ ...base, currentValue: 1, limit: 0 }, now).reasonCode, "conflicting-provider-values");
+ assert.equal(kusto.classifyCapacityObservation({ ...base, currentValue: null, x_IngestionTime: "2026-08-20T10:00:00Z" }, now).reasonCode, "invalid-provider-values");
+ assert.equal(kusto.classifyCapacityObservation({ ...base, x_IngestionTime: "2026-08-21T12:00:00Z" }, now).state, "healthy");
+ assert.equal(kusto.classifyCapacityObservation({ ...base, x_IngestionTime: "2026-08-21T11:59:59Z" }, now).state, "stale");
+
+ const unknown = { ...base, ResourceName: "regionalFamilyCores" };
+ assert.equal(kusto.classifyCapacityObservation(unknown, now).state, "unclassified");
+ assert.equal(kusto.classifyCapacityObservation({ ...unknown, x_IngestionTime: "2026-08-20T10:00:00Z" }, now).state, "stale");
+
+ const sqlNegative = kusto.classifyCapacityObservation({
+ ...base,
+ x_SourceType: "SqlSubscriptionUsage",
+ x_SourceVersion: "1.0-sql",
+ ResourceName: "RegionalVCoreQuotaForSQLDBAndDW",
+ limit: -1,
+ }, now);
+ assert.equal(sqlNegative.state, "invalid");
+ assert.equal(sqlNegative.reasonCode, "unexpected-negative-limit");
+ assert.match(sqlNegative.sourceNote, /interpretation unverified/i);
+});
+
+test("inventory observations never receive quota arithmetic", () => {
+ const result = kusto.classifyCapacityObservation({
+ x_SourceType: "PremiumSSDv2Disk",
+ x_SourceVersion: "1.0-disk",
+ ResourceId: "/subscriptions/s/resourceGroups/rg/providers/Microsoft.Compute/disks/d1",
+ ResourceName: "d1",
+ unit: "",
+ currentValue: 128,
+ limit: null,
+ x_IngestionTime: "2026-08-23T10:00:00Z",
+ }, new Date("2026-08-23T12:00:00Z"));
+ assert.equal(result.state, "inventory");
+ assert.equal(result.currentValue, 128);
+ assert.equal(result.limit, null);
+ assert.equal(result.utilizationPercent, null);
+ assert.equal(result.headroom, null);
+});
+
+test("capacity history gates activate only supported readings", () => {
+ assert.equal(kusto.resolveCapacityHistoryCapability(1).mode, "current-only");
+ assert.equal(kusto.resolveCapacityHistoryCapability(2).mode, "observed-delta");
+ assert.equal(kusto.resolveCapacityHistoryCapability(3).mode, "provisional-runway");
+ assert.equal(kusto.resolveCapacityHistoryCapability(7).mode, "trend-runway");
+ assert.equal(kusto.resolveCapacityHistoryCapability(7, { quotaType: "inventory" }).mode, "observed-history");
+});
+
+test("capacity KQL is bounded and preserves semantic dimensions", () => {
+ const current = kusto.buildCapacityCurrentQuery("compute");
+ const selectors = kusto.buildCapacitySelectorQuery("compute");
+ const subscriptions = kusto.buildComputeSubscriptionQuery({
+ status: "in-use",
+ familySearch: "Dsv5",
+ regions: ["eastus"],
+ subscriptionSearch: "64e3",
+ page: 2,
+ pageSize: 50,
+ });
+ const appService = kusto.buildAppServiceSkuQuery({ SubAccountId: ["abc"], location: ["eastus"] });
+ const appServiceSubscriptions = kusto.buildAppServiceSubscriptionQuery({
+ status: "no-quota",
+ skuSearch: "P1v4",
+ regions: ["eastus"],
+ subscriptionSearch: "64e3",
+ page: 2,
+ pageSize: 50,
+ });
+ const azureSql = kusto.buildAzureSqlQuotaQuery({ SubAccountId: ["abc"], location: ["eastus"] });
+ const azureSqlSubscriptions = kusto.buildAzureSqlSubscriptionQuery({
+ status: "no-quota",
+ resourceSearch: "vCore",
+ regions: ["eastus"],
+ subscriptionSearch: "64e3",
+ page: 2,
+ pageSize: 50,
+ });
+ const heatmap = kusto.buildCapacityHeatmapQuery("compute", {
+ resourceName: "cores",
+ unit: "Count",
+ sourceVersion: "1.0-usage",
+ });
+ const reconciliation = kusto.buildCapacityReservationReconciliationQuery();
+ const disk = kusto.buildCapacityDemandSelectorQuery("premium-ssd-v2");
+
+ assert.match(current, /\| take 251$/);
+ assert.match(selectors, /\| take 501$/);
+ assert.match(selectors, /summarize displayName=take_any\(displayName\).+by ResourceName, unit, x_SourceType, x_SourceVersion/s);
+ assert.match(selectors, /NAME: Compute quota usage/);
+ assert.match(subscriptions, /where CoresUsed > 0/);
+ assert.match(subscriptions, /Family contains "Dsv5"/);
+ assert.match(subscriptions, /Location in~ \("eastus"\)/);
+ assert.match(subscriptions, /SubscriptionId startswith "64e3"/);
+ assert.match(subscriptions, /NAME: Compute VM family quota usage/);
+ assert.doesNotMatch(subscriptions, /ComputeQuota\(\)|Costs\(\)/);
+ assert.match(subscriptions, /RowNumber between \(51 \.\. 100\)/);
+ assert.match(subscriptions, /real\(null\)/);
+ assert.match(subscriptions, /\| take 50$/);
+ assert.throws(() => kusto.buildComputeSubscriptionQuery({ regions: "eastus" }), /must be an array/);
+ assert.match(appService, /NAME: App Service quota usage/);
+ assert.match(appService, /SkuKey=ResourceName, Unit=unit, Location=location/);
+ assert.match(appService, /NoQuotaSubscriptions=dcountif\(SubAccountId, coalesce\(limit, 0\.0\) <= 0\)/);
+ assert.match(appService, /where SubAccountId in~ \("abc"\)/);
+ assert.match(appService, /where location in~ \("eastus"\)/);
+ assert.match(appService, new RegExp(`take ${kusto.CAPACITY_LIMITS.familyCells + 1}`));
+ assert.match(appServiceSubscriptions, /coalesce\(limit, 0\.0\) <= 0/);
+ assert.match(appServiceSubscriptions, /ResourceName contains "P1v4"/);
+ assert.match(appServiceSubscriptions, /location in~ \("eastus"\)/);
+ assert.match(appServiceSubscriptions, /SubAccountId startswith "64e3"/);
+ assert.match(appServiceSubscriptions, /RowNumber between \(51 \.\. 100\)/);
+ assert.match(appServiceSubscriptions, /\| take 50$/);
+ assert.doesNotMatch(appServiceSubscriptions, /Costs\(\)/);
+ assert.doesNotMatch(appServiceSubscriptions, /sum\(currentValue\)|sum\(limit\)|HeadroomInstances/);
+ assert.match(appServiceSubscriptions, /SkuRegionPairs=count\(\)/);
+ assert.match(azureSql, /NAME: SQL subscription quota usage/);
+ assert.match(azureSql, /Metric=take_any\(QuotaMetric\)/);
+ assert.match(azureSql, /Used=sumif\(currentValue, limit > 0\)/);
+ assert.match(azureSql, /NegativeLimitSubscriptions=dcountif\(SubAccountId, limit < 0\)/);
+ assert.match(azureSql, /where SubAccountId in~ \("abc"\)/);
+ assert.match(azureSql, /where location in~ \("eastus"\)/);
+ assert.match(azureSql, new RegExp(`take ${kusto.CAPACITY_LIMITS.familyCells + 1}`));
+ assert.match(azureSqlSubscriptions, /coalesce\(limit, 0\.0\) <= 0/);
+ assert.match(azureSqlSubscriptions, /ResourceName contains "vCore"/);
+ assert.match(azureSqlSubscriptions, /location in~ \("eastus"\)/);
+ assert.match(azureSqlSubscriptions, /SubAccountId startswith "64e3"/);
+ assert.match(azureSqlSubscriptions, /MetricRegionPairs=count\(\)/);
+ assert.match(azureSqlSubscriptions, /RowNumber between \(51 \.\. 100\)/);
+ assert.match(azureSqlSubscriptions, /\| take 50$/);
+ assert.doesNotMatch(azureSqlSubscriptions, /Costs\(\)/);
+ assert.match(heatmap, /\| take 501$/);
+ assert.throws(
+ () => kusto.buildCapacityDemandSelectorQuery("compute"),
+ /Compute billed-demand queries are not supported/
+ );
+ assert.throws(
+ () => kusto.buildCapacityDemandHistoryQuery("compute", {}),
+ /Compute billed-demand queries are not supported/
+ );
+ assert.throws(
+ () => kusto.buildCapacityDemandCoverageQuery("compute"),
+ /Compute billed-demand queries are not supported/
+ );
+ assert.match(reconciliation, /\| join kind=fullouter billed on GroupKey/);
+ assert.match(reconciliation, /inventory-only/);
+ assert.match(reconciliation, /cost-only/);
+ assert.match(disk, /\| join kind=leftouter diskCost on JoinResourceId/);
+ assert.match(disk, /InventoryResourceId/);
+});
+
+test("all seven capacity classes return the bounded payload contract", async (t) => {
+ const clusterUri = await startCapacityServer(t);
+ for (const classId of Object.keys(kusto.CAPACITY_CLASS_REGISTRY)) {
+ const payload = await kusto.getCapacity(clusterUri, "Hub", classId);
+ assert.equal(payload.classId, classId);
+ assert.equal(payload.contract.id, classId);
+ assert.equal(payload.schema.quota.available, true);
+ if (["compute", "app-service", "azure-sql", "azure-ai"].includes(classId)) {
+ assert.equal(payload.schema.costs, undefined);
+ assert.equal(payload.series.status, "not-applicable");
+ assert.equal(payload.demand.capability.reasonCode, "class-uses-quota-only");
+ } else {
+ assert.equal(payload.schema.costs.available, true);
+ }
+ assert.equal(payload.table.rowLimit, 250);
+ assert.equal(payload.selectors.itemLimit, 500);
+ assert.equal(payload.history.pointLimit, 430);
+ assert.equal(payload.heatmap.limit, 500);
+ assert.equal(payload.series.pointLimit, 430);
+ assert.equal(payload.demand.selectors.itemLimit, 500);
+ }
+});
+
+test("missing schema fields disable only panels that depend on that source", async (t) => {
+ const missingQuota = await startCapacityServer(t, {
+ quotaFields: QUOTA_SCHEMA_FIELDS.filter((field) => field !== "x_SourceVersion"),
+ });
+ const quotaPayload = await kusto.getCapacity(missingQuota, "Hub", "compute");
+ assert.equal(quotaPayload.schema.quota.available, false);
+ assert.equal(quotaPayload.schema.costs, undefined);
+ assert.equal(quotaPayload.capability.mode, "disabled");
+ assert.equal(quotaPayload.history.status, "disabled");
+ assert.equal(quotaPayload.demand.capability.mode, "disabled");
+ assert.equal(quotaPayload.demand.capability.reasonCode, "class-uses-quota-only");
+
+ const missingCost = await startCapacityServer(t, {
+ costFields: COST_SCHEMA_FIELDS.filter((field) => field !== "BillingCurrency"),
+ });
+ const appServicePayload = await kusto.getCapacity(missingCost, "Hub", "app-service");
+ assert.equal(appServicePayload.schema.quota.available, true);
+ assert.equal(appServicePayload.schema.costs, undefined);
+ assert.equal(appServicePayload.history.status, "no-selection");
+ assert.equal(appServicePayload.demand.capability.reasonCode, "class-uses-quota-only");
+ assert.equal(appServicePayload.series.status, "not-applicable");
+
+ const costPayload = await kusto.getCapacity(missingCost, "Hub", "storage");
+ assert.equal(costPayload.schema.quota.available, true);
+ assert.equal(costPayload.schema.costs.available, false);
+ assert.equal(costPayload.capability.mode, "descriptive-only");
+ assert.equal(costPayload.history.status, "no-selection");
+ assert.equal(costPayload.demand.capability.mode, "disabled");
+ assert.equal(costPayload.series.status, "disabled");
+});
+
+test("capacity selections reject unknown fields and keys outside the selector catalog", async (t) => {
+ assert.throws(
+ () => extension.validateViewInput({
+ name: "capacity",
+ capacityClass: "compute",
+ capacitySelections: { quotaSelection: { resourceName: "cores", injected: "value" } },
+ }),
+ /Unsupported quotaSelection field/
+ );
+ assert.throws(
+ () => extension.validateViewInput({ name: "capacity", capacityClass: "unknown" }),
+ /Unsupported capacity class/
+ );
+
+ const selectorRow = {
+ ResourceId: "/subscriptions/one/providers/Microsoft.Compute/locations/eastus/usages/cores",
+ ResourceName: "cores",
+ SubAccountId: "one",
+ location: "eastus",
+ unit: "Count",
+ x_SourceType: "ComputeUsage",
+ x_SourceVersion: "1.0-usage",
+ x_IngestionTime: "2026-08-23T12:00:00Z",
+ };
+ const clusterUri = await startCapacityServer(t, { rows: () => [selectorRow] });
+ await assert.rejects(
+ () => kusto.getCapacity(clusterUri, "Hub", "compute", {
+ quotaSelection: {
+ subAccountId: "one",
+ location: "westus",
+ resourceName: "cores",
+ unit: "Count",
+ sourceVersion: "1.0-usage",
+ },
+ }),
+ /not present in the bounded selector catalog/
+ );
+});
+
+test("capacity navigation, selection, and heatmap helpers preserve accessible text parity", () => {
+ assert.equal(app.nextCapacityTabIndex(0, "ArrowLeft"), 7);
+ assert.equal(app.nextCapacityTabIndex(7, "ArrowRight"), 0);
+ assert.equal(app.nextCapacityTabIndex(4, "Home"), 0);
+ assert.equal(app.nextCapacityTabIndex(2, "End"), 7);
+ assert.equal(app.nextCapacityTabIndex(3, "Enter"), 3);
+
+ const sourceRow = {
+ SubAccountId: "subscription",
+ location: "eastus",
+ ResourceName: "cores",
+ unit: "Count",
+ x_SourceVersion: "1.0-usage",
+ };
+ assert.deepEqual(app.capacitySelectionFromRow("quota", "compute", sourceRow), {
+ subAccountId: "subscription",
+ location: "eastus",
+ resourceName: "cores",
+ unit: "Count",
+ sourceVersion: "1.0-usage",
+ });
+ assert.deepEqual(app.capacitySelectionFromRow("metric", "compute", sourceRow), {
+ resourceName: "cores",
+ unit: "Count",
+ sourceVersion: "1.0-usage",
+ });
+ assert.deepEqual(app.capacityHeatmapCell({
+ semantic: { utilizationPercent: 91.25, state: "action" },
+ }, "compute"), {
+ value: 91.25,
+ text: "91.3%",
+ state: "action",
+ });
+});
+
+test("capacity markup retains module loading, shared controls, and visible text states", async () => {
+ const [html, source, uiSource, extensionSource, css, uiCss] = await Promise.all([
+ readFile(new URL("../public/index.html", import.meta.url), "utf8"),
+ readFile(new URL("../public/app.js", import.meta.url), "utf8"),
+ readFile(new URL("../public/ui.js", import.meta.url), "utf8"),
+ readFile(new URL("../extension.mjs", import.meta.url), "utf8"),
+ readFile(new URL("../public/app.css", import.meta.url), "utf8"),
+ readFile(new URL("../public/ui.css", import.meta.url), "utf8"),
+ ]);
+ assert.match(html, /data-tab="capacity"/);
+ assert.match(html, / /);
+ assert.match(html, /