Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

6.4 KB
Raw Blame
import { memo } from 'react';
import { Link } from 'react-router';
import { Wrench, ArrowRight } from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import * as api from '../../../services/api';
import { useSocketResource } from '../../../hooks/useSocketResource';
import { formatDurationMs } from '../../../utils/formatters';

const RESOURCE_EVENTS = ['cos:tasks:changed'];

// Auto-fix telemetry (issue #2328). Self-fetches the aggregated
// GET /api/autofix/metrics (derived server-side from persisted
// metadata.diagnostics) — this data is NOT part of dashboardState, so unlike
// the dashboardState-slice widgets this one owns its own subscription. Renders the
// overall auto-fix success rate, a daily success-rate trend sparkline, the
// fallback-tier breakdown, and median time-to-recovery.

const TIER_COLORS = {
  1: 'rgb(var(--port-success))', // config/env (cheapest fix)
  2: 'rgb(var(--port-accent))', // schema/type
  3: 'rgb(var(--port-warning))', // constrained-agent-retry
  4: 'rgb(var(--port-error))', // escalate
};

// Render a rate in [0,1] as a percent string, or an em dash for the null
// sentinel ("no data yet" must not read as 0%).
const pct = (rate) => (rate == null ? '—' : `${Math.round(rate * 100)}%`);

// Stable serialization of every slice the widget renders — the resource comparison key.
// Deliberately omits the server's `generatedAt` wall clock (changes every read)
// so identical data doesn't force a re-render, while any change to the rendered
// tiers / trend / recovery summary does.
const renderKey = (d) =>
  JSON.stringify({
    total: d?.total ?? null,
    overall: d?.overall ?? null,
    byTier: d?.byTier ?? null,
    timeToRecovery: d?.timeToRecovery ?? null,
    trend: d?.trend ?? null,
  });

// Inline SVG sparkline of the daily success-rate trend. No chart dependency —
// a handful of points plotted on a 0–100 y-axis. Days with a null rate (no
// denominator) are skipped so a gap doesn't read as 0%.
function TrendSparkline({ trend }) {
  const points = (trend || []).filter((d) => d.successRate != null);
  if (points.length < 2) return null;

  const W = 120;
  const H = 28;
  const stepX = W / (points.length - 1);
  const coords = points.map((d, i) => {
    const x = i * stepX;
    const y = H - d.successRate * H; // 0% at bottom, 100% at top
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  });
  const last = points[points.length - 1];
  const lastX = (points.length - 1) * stepX;
  const lastY = H - last.successRate * H;

  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      width={W}
      height={H}
      className="overflow-visible"
      role="img"
      aria-label={`Success-rate trend, latest ${pct(last.successRate)}`}
    >
      <polyline
        points={coords.join(' ')}
        fill="none"
        style={{ stroke: 'rgb(var(--port-accent))' }}
        strokeWidth="1.5"
        strokeLinejoin="round"
        strokeLinecap="round"
      />
      <circle cx={lastX} cy={lastY} r="2" style={{ fill: 'rgb(var(--port-accent))' }} />
    </svg>
  );
}

function AutoFixMetricsWidget() {
  const { data, loading } = useSocketResource(
    () => api.getAutoFixMetrics({ silent: true }),
    {
      namespace: 'cos', events: RESOURCE_EVENTS,
      // Skip the re-render only when EVERY rendered slice is byte-identical.
      // `generatedAt` is the server's wall clock and changes every read, so it
      // must be excluded — but the comparison otherwise serializes the full
      // rendered payload (overall, per-tier rows, the trend series, the
      // time-to-recovery summary) so a tier redistribution or a same-length
      // trend whose values shifted still re-renders. The payload is tiny (a
      // few tiers + ≤30 trend days), so stringifying each snapshot is negligible.
      compare: (prev, next) => renderKey(prev) === renderKey(next),
    },
  );

  const header = (
    <div className="flex items-center gap-2 mb-3">
      <Wrench size={16} className="text-gray-500" />
      <h3 className="text-sm font-semibold text-white">Auto-Fix Telemetry</h3>
      <Link to="/cos" className="ml-auto flex items-center gap-1 text-xs text-port-accent hover:underline">
        Open <ArrowRight size={12} />
      </Link>
    </div>
  );

  const shell = (children) => (
    <div className="bg-port-card border border-port-border rounded-xl p-4 h-full">
      {header}
      {children}
    </div>
  );

  if (loading && !data) {
    return shell(<div className="text-xs"><BrailleSpinner text="Loading" /></div>);
  }

  // Empty state — no diagnostics-bearing tasks yet. Distinct from a 0% rate.
  if (!data || data.total === 0) {
    return shell(
      <div className="text-xs text-gray-500">
        No auto-fix activity yet. Provider/agent failures that trigger an
        investigation task will show up here, broken out by fallback tier and
        recovery rate.
      </div>,
    );
  }

  const { total, overall, byTier, timeToRecovery, trend } = data;

  return shell(
    <>
      <div className="flex items-end gap-3 mb-3">
        <div>
          <div className="text-2xl font-bold text-white leading-none">{pct(overall.successRate)}</div>
          <div className="text-xs text-gray-500 mt-1">
            {overall.resolved}/{total} recovered
          </div>
        </div>
        <div className="ml-auto">
          <TrendSparkline trend={trend} />
        </div>
      </div>

      <div className="space-y-1.5 mb-3">
        {(byTier || []).map((t) => (
          <div key={t.tier} className="flex items-center gap-2 text-xs">
            <span
              className="inline-block w-2 h-2 rounded-full shrink-0"
              style={{ backgroundColor: TIER_COLORS[t.tier] || 'rgb(var(--port-text-muted))' }}
              aria-hidden="true"
            />
            <span className="text-gray-300 flex-1 truncate" title={t.label}>
              T{t.tier} · {t.strategy}
            </span>
            <span className="text-gray-500 tabular-nums">
              {t.resolved}/{t.total}
            </span>
            <span className="text-gray-400 tabular-nums w-9 text-right">{pct(t.successRate)}</span>
          </div>
        ))}
      </div>

      <div className="flex items-center justify-between text-xs border-t border-port-border pt-2">
        <span className="text-gray-500">Median recovery</span>
        <span className="text-gray-300 tabular-nums">
          {timeToRecovery ? formatDurationMs(timeToRecovery.medianMs) : '—'}
        </span>
      </div>
    </>,
  );
}

export default memo(AutoFixMetricsWidget);