Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

25.0 KB
Raw Blame
import { Component, Show, createMemo, createSignal, onMount, For } from 'solid-js';
import { Card } from '@/components/shared/Card';
import {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
} from '@/components/shared/Table';
import { SectionHeader } from '@/components/shared/SectionHeader';
import { FilterSegmentedControl } from '@/components/shared/FilterToolbar';
import { AIAPI } from '@/api/ai';
import { aiRuntimeSettings, loadAIRuntimeSettings } from '@/stores/aiRuntimeState';
import { formatNumber } from '@/utils/format';
import { logger } from '@/utils/logger';
import { notificationStore } from '@/stores/notifications';
import type { AICostSummary } from '@/types/ai';
import { getAIProviderDisplayName } from '@/utils/aiProviderPresentation';
import {
  AI_COST_ASSISTANT_USE_CASE_LABEL,
  AI_COST_BUDGET_LABEL,
  AI_COST_DAILY_TOKEN_EMPTY_STATE,
  AI_COST_DAILY_USD_EMPTY_STATE,
  AI_COST_EMPTY_STATE,
  AI_COST_PANEL_DESCRIPTION,
  AI_COST_PANEL_TITLE,
  AI_COST_PATROL_USE_CASE_LABEL,
  AI_COST_PROVIDER_TABLE_EMPTY_STATE,
  AI_COST_RESET_HISTORY_LABEL,
  buildAICostExportFilename,
  getAICostBudgetNote,
  getAICostExportHistoryErrorMessage,
  getAICostLoadingState,
  getAICostRefreshErrorMessage,
  getAICostResetHistoryConfirmationMessage,
  getAICostResetHistoryErrorMessage,
  getAICostResetHistorySuccessMessage,
} from '@/utils/aiCostPresentation';

const usdFormatter = new Intl.NumberFormat(undefined, {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});

const TinySparkline: Component<{
  values: number[];
  width?: number;
  height?: number;
  stroke?: string;
}> = (props) => {
  const width = () => props.width ?? 160;
  const height = () => props.height ?? 28;
  const stroke = () => props.stroke ?? '#22c55e';

  const pathD = createMemo(() => {
    const values = props.values;
    const w = width();
    const h = height();
    if (!values || values.length === 0) return '';

    const max = Math.max(...values, 0);
    const safeMax = max <= 0 ? 1 : max;

    // For single point, draw a horizontal line across the middle
    if (values.length === 1) {
      const y = h - (Math.max(0, values[0]) / safeMax) * h;
      // Draw a short horizontal line to make the single point visible
      return `M0,${y.toFixed(2)} L${w.toFixed(2)},${y.toFixed(2)}`;
    }

    const xStep = w / (values.length - 1);
    let d = '';
    values.forEach((v, idx) => {
      const x = idx * xStep;
      const y = h - (Math.max(0, v) / safeMax) * h;
      d += `${idx === 0 ? 'M' : 'L'}${x.toFixed(2)},${y.toFixed(2)} `;
    });
    return d.trim();
  });

  return (
    <svg width={width()} height={height()} viewBox={`0 0 ${width()} ${height()}`} class="block">
      <path
        d={pathD()}
        fill="none"
        stroke={stroke()}
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
      />
    </svg>
  );
};

export const AICostDashboard: Component = () => {
  const [days, setDays] = createSignal(30);
  const [loading, setLoading] = createSignal(false);
  const [loadError, setLoadError] = createSignal<string | null>(null);
  const [summary, setSummary] = createSignal<AICostSummary | null>(null);
  const [showAllModels, setShowAllModels] = createSignal(false);
  let requestSeq = 0;

  const anyPricingKnown = createMemo(() => {
    const data = summary();
    if (!data) return false;
    return data.provider_models.some((pm) => pm.pricing_known);
  });

  const unpricedProviderModels = createMemo(() => {
    const data = summary();
    if (!data) return [];
    return (data.provider_models ?? []).filter(
      (pm) => !pm.pricing_known && (pm.total_tokens ?? 0) > 0,
    );
  });

  const estimatedTotalUSD = createMemo(() => {
    const data = summary();
    if (!data || !anyPricingKnown()) return null;
    return data.totals.estimated_usd ?? 0;
  });

  const useCaseMap = createMemo(() => {
    const data = summary();
    const map = new Map<string, { tokens: number; usd: number; pricingKnown: boolean }>();
    if (!data) return map;
    for (const uc of data.use_cases ?? []) {
      map.set(uc.use_case, {
        tokens: uc.total_tokens,
        usd: uc.estimated_usd ?? 0,
        pricingKnown: uc.pricing_known,
      });
    }
    return map;
  });

  const dailyTotals = createMemo(() => summary()?.daily_totals ?? []);
  const dailyTokenValues = createMemo(() => dailyTotals().map((d) => d.total_tokens));
  const dailyUSDValues = createMemo(() => dailyTotals().map((d) => d.estimated_usd ?? 0));

  // Trend cards average over the selected range (effective_days) so that
  // avg/day x days reconciles with the headline total. Averaging only the
  // days that recorded activity previously overstated the run-rate (e.g.
  // $0.05/day next to a $0.50/30d total that implied $0.02/day).
  const avgDailyUSD = createMemo(() => {
    const total = estimatedTotalUSD();
    const days = summary()?.effective_days;
    if (total == null || !days || days <= 0) return null;
    return total / days;
  });

  const avgDailyTokens = createMemo(() => {
    const data = summary();
    const days = data?.effective_days;
    if (!data || !days || days <= 0) return null;
    return Math.round(data.totals.total_tokens / days);
  });

  // Surface the real cost driver first: priced models by spend (desc),
  // then unpriced models by tokens (desc) so the rows the operator can
  // actually act on aren't buried under flat / unknown rows.
  const sortedProviderModels = createMemo(() => {
    const data = summary();
    if (!data) return [];
    return [...data.provider_models].sort((a, b) => {
      const aPriced = a.pricing_known ? 1 : 0;
      const bPriced = b.pricing_known ? 1 : 0;
      if (aPriced !== bPriced) return bPriced - aPriced;
      if (aPriced) return (b.estimated_usd ?? 0) - (a.estimated_usd ?? 0);
      return (b.total_tokens ?? 0) - (a.total_tokens ?? 0);
    });
  });

  // Keep the default view on the rows that carry the cost signal; the long
  // tail of flat / unpriced rows stays one click away.
  const VISIBLE_MODEL_ROWS = 10;
  const visibleProviderModels = createMemo(() => {
    const all = sortedProviderModels();
    if (showAllModels() || all.length <= VISIBLE_MODEL_ROWS) return all;
    return all.slice(0, VISIBLE_MODEL_ROWS);
  });

  const formatUSD = (usd: number) => usdFormatter.format(usd);

  const loadSummary = async (rangeDays: number) => {
    const seq = ++requestSeq;
    const isInitialLoad = summary() === null;
    setLoading(true);
    setLoadError(null);
    try {
      const data = await AIAPI.getCostSummary(rangeDays);
      if (seq !== requestSeq) return;
      setSummary(data);
    } catch (err) {
      if (seq !== requestSeq) return;
      logger.error('[AICostDashboard] Failed to load cost summary:', err);
      // Only show notification on refresh failures, not initial load
      if (!isInitialLoad) {
        notificationStore.error(getAICostRefreshErrorMessage());
      }
      const message =
        err instanceof Error && err.message ? err.message : 'Failed to load usage data';
      setLoadError(message);
    } finally {
      if (seq === requestSeq) setLoading(false);
    }
  };

  onMount(() => {
    loadSummary(days());
  });

  const loadBudgetSettings = async () => {
    try {
      await loadAIRuntimeSettings();
    } catch (err) {
      logger.debug('[AICostDashboard] Failed to load AI settings for budget:', err);
    }
  };

  onMount(() => {
    loadBudgetSettings();
  });

  const parsedBudgetUSD30d = createMemo(() => {
    const s = aiRuntimeSettings();
    const n = s?.cost_budget_usd_30d;
    if (typeof n !== 'number' || !Number.isFinite(n) || n <= 0) return null;
    return n;
  });

  const budgetForRange = createMemo(() => {
    const budget30d = parsedBudgetUSD30d();
    if (budget30d == null) return null;
    const rangeDays = days();
    return (budget30d * rangeDays) / 30;
  });

  const isOverBudget = createMemo(() => {
    const budget = budgetForRange();
    const usd = estimatedTotalUSD();
    if (budget == null || usd == null) return false;
    return usd > budget;
  });

  const resetHistory = async () => {
    if (!confirm(getAICostResetHistoryConfirmationMessage())) return;
    try {
      const result = await AIAPI.resetCostHistory();
      notificationStore.success(getAICostResetHistorySuccessMessage(result.backup_file));
      await loadSummary(days());
    } catch (err) {
      logger.error('[AICostDashboard] Failed to reset AI cost history:', err);
      notificationStore.error(getAICostResetHistoryErrorMessage());
    }
  };

  const downloadExport = async (format: 'csv' | 'json') => {
    try {
      const resp = await AIAPI.exportCostHistory(days(), format);
      if (!resp.ok) {
        throw new Error(`Export failed (${resp.status})`);
      }
      const blob = await resp.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = buildAICostExportFilename(days(), format);
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch (err) {
      logger.error('[AICostDashboard] Failed to export cost history:', err);
      notificationStore.error(getAICostExportHistoryErrorMessage());
    }
  };

  const handleRangeClick = (rangeDays: number) => {
    if (loading() || rangeDays === days()) return;
    setDays(rangeDays);
    loadSummary(rangeDays);
  };

  return (
    <Card padding="none" class="overflow-hidden border border-border" border={false}>
      <div class="bg-blue-50 dark:bg-blue-900/25 px-4 py-4 border-b border-border sm:px-6">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-center">
          <div class="flex min-w-0 items-start gap-3 sm:flex-1 sm:items-center">
            <div class="shrink-0 p-2 bg-blue-100 dark:bg-blue-900/25 rounded-md">
              <svg
                class="w-5 h-5 text-blue-600 dark:text-blue-300"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M12 8c-1.657 0-3 1.343-3 3v1a3 3 0 006 0v-1c0-1.657-1.343-3-3-3zM5 12a7 7 0 0114 0v3a2 2 0 01-2 2H7a2 2 0 01-2-2v-3z"
                />
              </svg>
            </div>
            <SectionHeader
              title={AI_COST_PANEL_TITLE}
              description={AI_COST_PANEL_DESCRIPTION}
              size="sm"
              class="min-w-0 flex-1"
            />
          </div>
          <div class="flex min-w-0 items-center gap-2 sm:shrink-0">
            <Show when={loading()}>
              <div class="shrink-0 text-xs text-muted">Loading…</div>
            </Show>
            <FilterSegmentedControl
              aria-label="Cost range"
              class="w-full justify-between sm:w-auto sm:justify-start"
              value={String(days())}
              disabled={loading()}
              onChange={(value) => handleRangeClick(Number(value))}
              options={[
                { value: '1', label: '1d' },
                { value: '7', label: '7d' },
                { value: '30', label: '30d' },
                { value: '90', label: '90d' },
                { value: '365', label: '1y' },
              ]}
            />
          </div>
        </div>
      </div>

      <div class="p-6 space-y-4">
        <Show when={!summary() && loading()}>
          <div class="text-sm text-muted">{getAICostLoadingState().text}</div>
        </Show>

        <Show when={summary()?.truncated}>
          <div class="text-xs px-3 py-2 rounded-sm border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/25 text-blue-900 dark:text-blue-100">
            Showing the last {summary()?.effective_days} days due to a {summary()?.retention_days}
            -day retention window.
          </div>
        </Show>

        <Show when={isOverBudget()}>
          <div class="text-xs px-3 py-2 rounded-sm border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/25 text-red-900 dark:text-red-100">
            Estimated spend ({formatUSD(estimatedTotalUSD() ?? 0)}) is above your budget (
            {formatUSD(budgetForRange() ?? 0)}).
          </div>
        </Show>

        <Show when={loadError() && summary()}>
          <div
            role="alert"
            aria-live="polite"
            class="flex items-center justify-between gap-3 text-xs px-3 py-2 rounded-sm border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/25 text-amber-900 dark:text-amber-100"
          >
            <div class="truncate">Couldn’t refresh. Showing last loaded data. {loadError()}</div>
            <button
              type="button"
              disabled={loading()}
              onClick={() => loadSummary(days())}
              class={`shrink-0 px-2 py-1 rounded-sm border border-amber-300 dark:border-amber-700 hover:bg-amber-100 dark:hover:bg-amber-900/25 ${loading() ? 'opacity-60 cursor-not-allowed' : ''}`}
            >
              Retry
            </button>
          </div>
        </Show>

        <Show when={!summary() && !loading() && loadError()}>
          <div class="text-sm text-muted">{loadError()}</div>
        </Show>

        <Show when={!summary() && !loading() && !loadError()}>
          <div class="text-sm text-muted">{AI_COST_EMPTY_STATE}</div>
        </Show>

        <Show when={summary()}>
          {(data) => (
            <>
              <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div class="p-3 rounded-md bg-surface-alt border border-border">
                  <div class="text-xs text-muted">Estimated spend</div>
                  <div class="text-lg font-semibold text-base-content">
                    <Show
                      when={estimatedTotalUSD() != null}
                      fallback={
                        <span class="text-muted" aria-hidden="true">
                          —
                        </span>
                      }
                    >
                      {formatUSD(estimatedTotalUSD() ?? 0)}
                    </Show>
                  </div>
                  <div class="text-[11px] text-muted mt-0.5">over {data().effective_days} days</div>
                </div>
                <div class="p-3 rounded-md bg-surface-alt border border-border">
                  <div class="text-xs text-muted">{AI_COST_BUDGET_LABEL}</div>
                  <div class="text-lg font-semibold text-base-content mt-0.5">
                    <Show
                      when={parsedBudgetUSD30d() != null}
                      fallback={
                        <span class="text-muted" aria-hidden="true">
                          —
                        </span>
                      }
                    >
                      {formatUSD(parsedBudgetUSD30d() ?? 0)}
                    </Show>
                  </div>
                  <div class="text-[11px] text-muted mt-0.5">
                    <Show when={budgetForRange() != null} fallback={<span>No budget set</span>}>
                      {getAICostBudgetNote(days())} {formatUSD(budgetForRange() ?? 0)}
                    </Show>
                  </div>
                </div>
              </div>

              <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div class="p-3 rounded-md bg-surface-alt border border-border">
                  <div class="text-xs text-muted">{AI_COST_ASSISTANT_USE_CASE_LABEL}</div>
                  <div class="text-sm font-semibold text-base-content">
                    {formatNumber(useCaseMap().get('chat')?.tokens ?? 0)} tokens
                  </div>
                  <div class="text-xs text-muted">
                    <Show when={useCaseMap().get('chat')?.pricingKnown} fallback={<span>—</span>}>
                      {formatUSD(useCaseMap().get('chat')?.usd ?? 0)}
                    </Show>
                  </div>
                </div>
                <div class="p-3 rounded-md bg-surface-alt border border-border">
                  <div class="text-xs text-muted">{AI_COST_PATROL_USE_CASE_LABEL}</div>
                  <div class="text-sm font-semibold text-base-content">
                    {formatNumber(useCaseMap().get('patrol')?.tokens ?? 0)} tokens
                  </div>
                  <div class="text-xs text-muted">
                    <Show when={useCaseMap().get('patrol')?.pricingKnown} fallback={<span>—</span>}>
                      {formatUSD(useCaseMap().get('patrol')?.usd ?? 0)}
                    </Show>
                  </div>
                </div>
              </div>

              <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div class="p-3 rounded-md bg-surface-alt border border-border">
                  <div class="flex items-center justify-between">
                    <div class="text-xs text-muted">Spend trend</div>
                    <div class="text-xs text-muted">
                      <Show
                        when={anyPricingKnown() && avgDailyUSD() != null}
                        fallback={<span>—</span>}
                      >
                        {formatUSD(avgDailyUSD() ?? 0)} avg/day
                      </Show>
                    </div>
                  </div>
                  <div class="mt-2">
                    <Show
                      when={anyPricingKnown() && dailyUSDValues().length >= 2}
                      fallback={
                        <div class="text-xs text-muted">{AI_COST_DAILY_USD_EMPTY_STATE}</div>
                      }
                    >
                      <TinySparkline values={dailyUSDValues()} stroke="#10b981" />
                    </Show>
                  </div>
                </div>
                <div class="p-3 rounded-md bg-surface-alt border border-border">
                  <div class="flex items-center justify-between">
                    <div class="text-xs text-muted">Token trend</div>
                    <div class="text-xs text-muted">
                      <Show when={avgDailyTokens() != null} fallback={<span>—</span>}>
                        {formatNumber(avgDailyTokens() ?? 0)} avg/day
                      </Show>
                    </div>
                  </div>
                  <div class="mt-2">
                    <Show
                      when={dailyTokenValues().length >= 2}
                      fallback={
                        <div class="text-xs text-muted">{AI_COST_DAILY_TOKEN_EMPTY_STATE}</div>
                      }
                    >
                      <TinySparkline values={dailyTokenValues()} stroke="#3b82f6" />
                    </Show>
                  </div>
                </div>
              </div>

              <div class="text-xs text-muted">
                USD is an estimate based on public list prices. It may differ from billing.
                <Show when={unpricedProviderModels().length > 0}>
                  <span
                    class="ml-2"
                    title={`Pricing unknown for:\n${unpricedProviderModels()
                      .map(
                        (pm) =>
                          `${getAIProviderDisplayName(pm.provider) || pm.provider}/${pm.model}`,
                      )
                      .join('\n')}`}
                  >
                    Estimated spend is partial — {unpricedProviderModels().length} model
                    {unpricedProviderModels().length === 1 ? '' : 's'} have unknown pricing.
                  </span>
                </Show>
                <Show when={summary()?.pricing_as_of}>
                  <span class="ml-2">Prices as of {summary()?.pricing_as_of}.</span>
                </Show>
              </div>

              <div class="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div class="text-xs text-muted">
                  History retention: {data().retention_days} days
                </div>
                <div class="grid grid-cols-3 gap-2 sm:flex sm:items-center">
                  <button
                    type="button"
                    disabled={loading()}
                    onClick={() => downloadExport('csv')}
                    class={`min-h-10 sm:min-h-9 px-2.5 py-2 text-sm rounded-sm border border-border hover:bg-surface-hover ${loading() ? 'opacity-60 cursor-not-allowed' : ''}`}
                  >
                    Export CSV
                  </button>
                  <button
                    type="button"
                    disabled={loading()}
                    onClick={() => downloadExport('json')}
                    class={`min-h-10 sm:min-h-9 px-2.5 py-2 text-sm rounded-sm border border-border hover:bg-surface-hover ${loading() ? 'opacity-60 cursor-not-allowed' : ''}`}
                  >
                    Export JSON
                  </button>
                  <button
                    type="button"
                    disabled={loading()}
                    onClick={resetHistory}
                    class={`min-h-10 sm:min-h-9 px-2.5 py-2 text-sm rounded-sm border border-border hover:bg-surface-hover ${loading() ? 'opacity-60 cursor-not-allowed' : ''}`}
                  >
                    {AI_COST_RESET_HISTORY_LABEL}
                  </button>
                </div>
              </div>

              <Table class="min-w-0 table-fixed text-sm">
                <TableHeader class="text-xs text-muted uppercase tracking-wide">
                  <TableRow class="border-b border-border">
                    <TableHead class="py-2 pr-2 text-left">Provider</TableHead>
                    <TableHead class="py-2 pr-2 text-left">Model</TableHead>
                    <TableHead class="px-1 py-2 text-right whitespace-nowrap">Est. USD</TableHead>
                    <TableHead class="ai-cost-detail-column px-2 py-2 text-right">Input</TableHead>
                    <TableHead class="ai-cost-detail-column px-2 py-2 text-right">Output</TableHead>
                    <TableHead class="hidden px-2 py-2 text-right sm:table-cell">Total</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  <Show when={visibleProviderModels().length === 0}>
                    <TableRow>
                      <TableCell colSpan={6} class="px-3 py-6 text-center text-sm text-muted">
                        <span class="block whitespace-normal">
                          {AI_COST_PROVIDER_TABLE_EMPTY_STATE}
                        </span>
                      </TableCell>
                    </TableRow>
                  </Show>
                  <For each={visibleProviderModels()}>
                    {(pm) => (
                      <TableRow class="border-b border-border-subtle">
                        <TableCell
                          class="truncate py-2 pr-2 font-medium text-base-content"
                          title={getAIProviderDisplayName(pm.provider) || pm.provider}
                        >
                          {getAIProviderDisplayName(pm.provider) || pm.provider}
                        </TableCell>
                        <TableCell
                          class="truncate py-2 pr-2 font-mono text-xs text-base-content"
                          title={pm.model}
                        >
                          {pm.model}
                        </TableCell>
                        <TableCell class="px-1 py-2 text-right text-base-content whitespace-nowrap">
                          <Show
                            when={pm.pricing_known}
                            fallback={
                              <span class="text-muted" aria-hidden="true">
                                —
                              </span>
                            }
                          >
                            {formatUSD(pm.estimated_usd ?? 0)}
                          </Show>
                        </TableCell>
                        <TableCell class="ai-cost-detail-column px-2 py-2 text-right text-base-content">
                          {formatNumber(pm.input_tokens)}
                        </TableCell>
                        <TableCell class="ai-cost-detail-column px-2 py-2 text-right text-base-content">
                          {formatNumber(pm.output_tokens)}
                        </TableCell>
                        <TableCell class="hidden px-2 py-2 text-right text-base-content sm:table-cell">
                          {formatNumber(pm.total_tokens)}
                        </TableCell>
                      </TableRow>
                    )}
                  </For>
                </TableBody>
              </Table>
              <Show when={sortedProviderModels().length > VISIBLE_MODEL_ROWS}>
                <button
                  type="button"
                  class="self-start text-xs text-blue-600 dark:text-blue-400 hover:underline"
                  onClick={() => setShowAllModels(!showAllModels())}
                >
                  {showAllModels()
                    ? 'Show less'
                    : `Show all ${sortedProviderModels().length} models`}
                </button>
              </Show>
            </>
          )}
        </Show>
      </div>
    </Card>
  );
};

export default AICostDashboard;