All files / src/components/dashboard/widgets PlatformWidgets.tsx

47.88% Statements 68/142
47.36% Branches 72/152
39.47% Functions 15/38
47.72% Lines 63/132

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638                                                                                7x 15x         7x 2x                             7x                                                                                                             7x                     7x 6x 6x 6x 6x   6x   1x     6x         6x           6x 6x   6x 3x     3x       6x 6x       6x           6x                                               7x                                                                                                                                                                                                                                                                   7x 8x 1x   1x 2x                 7x         22x 19x 18x     7x       23x 23x 23x 23x 23x 23x 23x 23x   23x                   12x                   23x           23x   12x       23x   23x       23x 11x   10x 12x       10x 5x                           5x 1x     4x 4x     7x                                                                                                                                                           7x     7x                                                                                                                                                                                                                                                        
import {
  BreakdownConfig,
  ChartConfig,
  ResourceListConfig,
  StatConfig,
} from "@/objects/Dashboard";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import {
  Breakdown,
  LLMInvocationRecord,
  StatsCatalogue,
  TraceStats,
  UsageStats,
  WebSearchDomainStats,
} from "@/services/api/routers/StatsRouter";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import React from "react";
import { Link } from "react-router-dom";
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { TONES } from "@/components/appearance/tones";
import { formatUsd, useSpend } from "@/components/cost";
import { WidgetBodyProps } from "./types";
import { parseServerDate } from "@/util/time";
import { MCP_AVAILABLE } from "@/util/mcp";
 
const Spinner = () => (
  <div className="h-full flex items-center justify-center text-gray-300 dark:text-gray-600">
    <Loader2 className="w-4 h-4 animate-spin" />
  </div>
);
 
const Empty: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <p className="text-xs text-gray-400 dark:text-gray-500 italic">{children}</p>
);
 
// ─── Stat ─────────────────────────────────────────────────────────────────────
 
/** Labels and formatting per metric, so a tile reads without a legend. */
const METRICS: Record<
  string,
  {
    label: string;
    format: (n: number) => string;
    /** `ledger`: the viewer's spend from the usage ledger (`useSpend`),
     *  the figure Overview, Stats and every cost card show. */
    source: "usage" | "trace" | "ledger";
  }
> = {
  total_tokens: {
    label: "Total tokens",
    format: (n) => n.toLocaleString(),
    source: "usage",
  },
  input_tokens: {
    label: "Input tokens",
    format: (n) => n.toLocaleString(),
    source: "usage",
  },
  output_tokens: {
    label: "Output tokens",
    format: (n) => n.toLocaleString(),
    source: "usage",
  },
  invocation_count: {
    label: "Invocations",
    format: (n) => n.toLocaleString(),
    source: "usage",
  },
  error_count: {
    label: "Errors",
    format: (n) => n.toLocaleString(),
    source: "usage",
  },
  avg_latency_ms: {
    label: "Avg latency",
    format: (n) => `${Math.round(n).toLocaleString()} ms`,
    source: "usage",
  },
  estimated_cost_usd: {
    label: "Your spend",
    format: formatUsd,
    source: "ledger",
  },
  llm_invocation_count: {
    label: "LLM calls",
    format: (n) => n.toLocaleString(),
    source: "trace",
  },
  tool_invocation_count: {
    label: "Tool calls",
    format: (n) => n.toLocaleString(),
    source: "trace",
  },
};
 
/** Captions for the ledger-backed metrics, keyed as the catalogue keys them.
 *
 *  A fallback only — the editor labels its pickers from the catalogue the
 *  backend serves. A tile still has to caption itself when it renders before
 *  the catalogue has loaded, and an unknown key falls through to the key
 *  itself rather than to a wrong name.
 */
const METRIC_LABELS: Record<string, string> = {
  invocations: "Invocations",
  input_tokens: "Input tokens",
  output_tokens: "Output tokens",
  total_tokens: "Total tokens",
  estimated_cost_usd: "Estimated spend",
  avg_latency_ms: "Average latency",
  errors: "Errors",
  error_rate: "Error rate",
};
 
export const StatWidgetBody: React.FC<WidgetBodyProps> = ({ widget, tone }) => {
  const { getApiHandler } = useApiHandler();
  const config = widget.config as unknown as StatConfig;
  const metric = METRICS[config?.metric] ?? METRICS.total_tokens;
  const period = config?.period === "all_time" ? "all_time" : "this_month";
 
  const usageQuery = useQuery({
    queryKey: [QUERY_KEYS.GET.USAGE_STATS],
    queryFn: () => getApiHandler().stats_router.getUsage(),
    enabled: metric.source === "usage",
  });
  const traceQuery = useQuery({
    queryKey: [QUERY_KEYS.GET.TRACE_STATS],
    queryFn: () => getApiHandler().stats_router.getTraces(),
    enabled: metric.source === "trace",
  });
  const spend = useSpend(
    { period },
    { enabled: metric.source === "ledger" },
  );
 
  // Bound explicitly: TS 5.0.2 cannot infer react-query v5's generic here.
  const usage: UsageStats | null = (usageQuery.data as UsageStats | null) ?? null;
  const traces: TraceStats | null = (traceQuery.data as TraceStats | null) ?? null;
 
  if (usageQuery.isLoading || traceQuery.isLoading || spend.isLoading)
    return <Spinner />;
 
  const bucket: Record<string, unknown> | null =
    metric.source === "usage"
      ? ((usage?.[period] ?? null) as Record<string, unknown> | null)
      : ((traces?.[period] ?? null) as Record<string, unknown> | null);
 
  const raw = bucket ? bucket[config?.metric ?? "total_tokens"] : null;
  const value = typeof raw === "number" ? raw : null;
  // Spend says "≥" when part of it could not be priced, and "Unknown" when
  // none of it could — never a number formatted from a missing one.
  const text =
    metric.source === "ledger"
      ? (spend.figure?.text ?? "—")
      : value === null
        ? "—"
        : metric.format(value);
 
  return (
    <div className="h-full flex flex-col justify-center">
      <p
        className={`text-2xl font-bold leading-none ${TONES[tone].fg} truncate`}
      >
        {text}
      </p>
      <p className="mt-1.5 text-[11px] text-gray-500 dark:text-gray-400 truncate">
        {metric.source === "ledger" ? spend.label : metric.label}
      </p>
      <p className="text-[11px] text-gray-400 dark:text-gray-500">
        {period === "all_time" ? "All time" : "This month"}
      </p>
    </div>
  );
};
 
// ─── Chart ────────────────────────────────────────────────────────────────────
 
interface ChartPoint {
  label: string;
  value: number;
}
 
export const ChartWidgetBody: React.FC<WidgetBodyProps> = ({
  widget,
  tone,
}) => {
  const { getApiHandler } = useApiHandler();
  const config = widget.config as unknown as ChartConfig;
  const source = config?.source ?? "llm_invocations";
  const limit = config?.limit ?? 50;
 
  const invocationQuery = useQuery({
    queryKey: [QUERY_KEYS.GET.LLM_INVOCATIONS, limit],
    queryFn: () => getApiHandler().stats_router.listInvocations(undefined, limit),
    enabled: source === "llm_invocations",
  });
  const domainQuery = useQuery({
    queryKey: [QUERY_KEYS.GET.WEB_SEARCH_DOMAIN_STATS, limit],
    queryFn: () => getApiHandler().stats_router.getWebSearchDomains(limit),
    enabled: source === "web_search_domains",
  });
 
  const points: ChartPoint[] = React.useMemo(() => {
    if (source === "web_search_domains") {
      const data = (domainQuery.data as WebSearchDomainStats | null) ?? null;
      return (data?.domains ?? []).map((d) => ({
        label: d.domain,
        value:
          config?.metric === "avg_trust_score"
            ? Number(((d.avg_trust_score ?? 0) * 100).toFixed(1))
            : d.visit_count,
      }));
    }
 
    const records =
      (invocationQuery.data as LLMInvocationRecord[] | null) ?? [];
    const key = (config?.metric ?? "total_tokens") as keyof LLMInvocationRecord;
    // Oldest first so the x-axis reads left to right.
    return [...records]
      .reverse()
      .map((record) => {
        const raw = record[key];
        return {
          label: record.created_at
            ? parseServerDate(record.created_at).toLocaleDateString(undefined, {
                month: "short",
                day: "numeric",
              })
            : "—",
          value: typeof raw === "number" ? raw : 0,
        };
      });
  }, [source, config?.metric, domainQuery.data, invocationQuery.data]);
 
  if (invocationQuery.isLoading || domainQuery.isLoading) return <Spinner />;
  if (points.length === 0) {
    return <Empty>No data recorded yet.</Empty>;
  }
 
  const colour = TONES[tone].hex;
  const axisProps = {
    tick: { fontSize: 10, fill: "currentColor" },
    stroke: "currentColor",
    className: "text-gray-400 dark:text-gray-500",
  };
  const tooltip = (
    <Tooltip
      contentStyle={{
        fontSize: 11,
        borderRadius: 8,
        border: "1px solid rgba(148,163,184,0.3)",
      }}
    />
  );
 
  return (
    <ResponsiveContainer width="100%" height="100%">
      {config?.chart_type === "bar" ? (
        <BarChart data={points} margin={{ top: 4, right: 4, bottom: 0, left: -16 }}>
          <CartesianGrid strokeDasharray="3 3" opacity={0.15} vertical={false} />
          <XAxis dataKey="label" {...axisProps} />
          <YAxis {...axisProps} width={44} />
          {tooltip}
          <Bar dataKey="value" fill={colour} radius={[4, 4, 0, 0]} />
        </BarChart>
      ) : config?.chart_type === "line" ? (
        <LineChart data={points} margin={{ top: 4, right: 4, bottom: 0, left: -16 }}>
          <CartesianGrid strokeDasharray="3 3" opacity={0.15} vertical={false} />
          <XAxis dataKey="label" {...axisProps} />
          <YAxis {...axisProps} width={44} />
          {tooltip}
          <Line
            type="monotone"
            dataKey="value"
            stroke={colour}
            strokeWidth={2}
            dot={false}
          />
        </LineChart>
      ) : (
        <AreaChart data={points} margin={{ top: 4, right: 4, bottom: 0, left: -16 }}>
          <defs>
            <linearGradient id={`fill-${widget.id}`} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={colour} stopOpacity={0.35} />
              <stop offset="100%" stopColor={colour} stopOpacity={0.02} />
            </linearGradient>
          </defs>
          <CartesianGrid strokeDasharray="3 3" opacity={0.15} vertical={false} />
          <XAxis dataKey="label" {...axisProps} />
          <YAxis {...axisProps} width={44} />
          {tooltip}
          <Area
            type="monotone"
            dataKey="value"
            stroke={colour}
            strokeWidth={2}
            fill={`url(#fill-${widget.id})`}
          />
        </AreaChart>
      )}
    </ResponsiveContainer>
  );
};
 
// ─── Breakdown ────────────────────────────────────────────────────────────────
 
/** How each unit reads as text.
 *
 *  Keyed by the unit the *backend* declares on the metric rather than by the
 *  metric name, so a metric added there formats correctly here without this
 *  app learning its name — which is the whole point of serving the catalogue.
 */
const UNIT_FORMATS: Record<string, (n: number) => string> = {
  count: (n) => n.toLocaleString(),
  tokens: (n) => n.toLocaleString(),
  usd: formatUsd,
  ms: (n) => `${Math.round(n).toLocaleString()} ms`,
  percent: (n) => `${n.toFixed(1)}%`,
};
 
/** A figure in its unit, or an em dash when there is nothing to report.
 *
 *  A null is not a zero: an unpriced model has *no* cost estimate, and
 *  printing "$0.00" for it would state something false. `zeroIsMeaningful`
 *  is the backend's own answer to which of the two a metric is.
 */
export const formatMetricValue = (
  value: number | null | undefined,
  unit: string,
  zeroIsMeaningful = true,
): string => {
  if (value === null || value === undefined) return "—";
  if (!zeroIsMeaningful && value === 0) return "—";
  return (UNIT_FORMATS[unit] ?? UNIT_FORMATS.count)(value);
};
 
export const BreakdownWidgetBody: React.FC<WidgetBodyProps> = ({
  widget,
  tone,
}) => {
  const { getApiHandler } = useApiHandler();
  const config = widget.config as unknown as BreakdownConfig;
  const metric = config?.metric ?? "estimated_cost_usd";
  const dimension = config?.dimension ?? null;
  const period = config?.period ?? "this_month";
  const display = config?.display ?? "bar";
  const limit = config?.limit ?? 5;
  const filters = React.useMemo(() => config?.filters ?? [], [config?.filters]);
 
  const { data, isLoading } = useQuery({
    queryKey: [
      QUERY_KEYS.GET.STATS_BREAKDOWN,
      metric,
      dimension,
      period,
      limit,
      filters.join("|"),
    ],
    queryFn: () =>
      getApiHandler().stats_router.getBreakdown({
        metric,
        dimension,
        period,
        limit,
        filters,
      }),
  });
 
  // Bound explicitly: TS 5.0.2 cannot infer react-query v5's generic here.
  const breakdown: Breakdown | null = (data as Breakdown | null) ?? null;
 
  // The metric's own label, from the catalogue the editor reads too (same
  // key, so one request serves both). The map below it only covers a tile
  // drawn before the catalogue arrives; governance and review metrics are
  // not in it, and captioned "pending_flags" until this was read.
  const { data: catalogueData } = useQuery({
    queryKey: [QUERY_KEYS.GET.STATS_CATALOGUE],
    queryFn: () => getApiHandler().stats_router.getCatalogue(),
    staleTime: Infinity,
  });
  const catalogue: StatsCatalogue | null =
    (catalogueData as StatsCatalogue | null) ?? null;
  const metricLabel =
    catalogue?.metrics.find((entry) => entry.key === metric)?.label ??
    METRIC_LABELS[metric] ??
    metric;
 
  if (isLoading) return <Spinner />;
  if (!breakdown) return <Empty>No data recorded yet.</Empty>;
 
  const format = (value: number | null) =>
    formatMetricValue(value, breakdown.unit, breakdown.zero_is_meaningful);
 
  // A single figure — the same query without a GROUP BY, so a tile and the
  // chart beside it can never disagree about what "this month" means.
  if (display === "value" || !dimension) {
    return (
      <div className="h-full flex flex-col justify-center">
        <p
          className={`text-2xl font-bold leading-none ${TONES[tone].fg} truncate`}
        >
          {format(breakdown.total)}
        </p>
        <p className="mt-1.5 text-[11px] text-gray-500 dark:text-gray-400 truncate">
          {metricLabel}
        </p>
      </div>
    );
  }
 
  if (breakdown.buckets.length === 0) {
    return <Empty>Nothing recorded in this period.</Empty>;
  }
 
  Eif (display === "list") {
    return (
      <ul className="space-y-0.5">
        {breakdown.buckets.map((bucket) => (
          <li
            key={bucket.key}
            className="flex items-baseline justify-between gap-2 rounded-lg px-2 py-1.5 text-xs"
          >
            <span
              className="truncate text-gray-700 dark:text-gray-200"
              title={bucket.missing ? "This resource has been deleted." : undefined}
            >
              {bucket.label}
              {bucket.missing && (
                <span className="ml-1 text-gray-400 dark:text-gray-500">
                  (deleted)
                </span>
              )}
            </span>
            <span
              className={`shrink-0 font-medium tabular-nums ${TONES[tone].fg}`}
            >
              {format(bucket.value)}
            </span>
          </li>
        ))}
      </ul>
    );
  }
 
  const points = breakdown.buckets.map((bucket) => ({
    label: bucket.label,
    value: bucket.value ?? 0,
  }));
  const colour = TONES[tone].hex;
 
  return (
    <ResponsiveContainer width="100%" height="100%">
      <BarChart
        data={points}
        layout="vertical"
        margin={{ top: 4, right: 8, bottom: 0, left: 4 }}
      >
        <CartesianGrid strokeDasharray="3 3" opacity={0.15} horizontal={false} />
        <XAxis
          type="number"
          tick={{ fontSize: 10, fill: "currentColor" }}
          stroke="currentColor"
          className="text-gray-400 dark:text-gray-500"
        />
        {/* Horizontal bars, unlike the chart widget's vertical ones: the axis
            here is names rather than time, and a name has to be readable. */}
        <YAxis
          type="category"
          dataKey="label"
          width={84}
          tick={{ fontSize: 10, fill: "currentColor" }}
          stroke="currentColor"
          className="text-gray-400 dark:text-gray-500"
        />
        <Tooltip
          formatter={(value) => format(typeof value === "number" ? value : null)}
          contentStyle={{
            fontSize: 11,
            borderRadius: 8,
            border: "1px solid rgba(148,163,184,0.3)",
          }}
        />
        <Bar dataKey="value" fill={colour} radius={[0, 4, 4, 0]} />
      </BarChart>
    </ResponsiveContainer>
  );
};
 
// ─── Resource list ────────────────────────────────────────────────────────────
 
interface ResourceRow {
  id: string;
  name: string;
  href: string;
}
 
const withId = (template: string, id: string, param: string) =>
  template.replace(param, id);
 
export const ResourceListWidgetBody: React.FC<WidgetBodyProps> = ({
  widget,
}) => {
  const { getApiHandler } = useApiHandler();
  const config = widget.config as unknown as ResourceListConfig;
  const resource = config?.resource ?? "agents";
  const limit = config?.limit ?? 5;
 
  const { data, isLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.DASHBOARD_BY_ID, "resource-list", resource],
    queryFn: async () => {
      const api = getApiHandler();
      switch (resource) {
        case "knowledge":
          return api.knowledge_router.list();
        case "toolkits":
          return api.toolkit_router.list();
        case "skillsets":
          return api.skillset_router.list();
        case "conversations":
          return api.conversation_router.list();
        case "projects":
          return api.project_router.list();
        default:
          return api.agent_router.list();
      }
    },
    // A tile saved before toolkits were withdrawn (util/mcp.ts) asks for
    // nothing: it says they are coming soon instead.
    enabled: MCP_AVAILABLE || resource !== "toolkits",
  });
 
  const rows: ResourceRow[] = React.useMemo(() => {
    const items = (data as Record<string, unknown>[] | null) ?? [];
    return items.slice(0, limit).map((item) => {
      const id = String(item.id ?? "");
      const name = String(item.name ?? item.title ?? "Untitled");
      switch (resource) {
        case "knowledge":
          return {
            id,
            name,
            href: withId(
              APP_ROUTES.USER.KNOWLEDGE.id,
              id,
              ROUTE_PARAMS.KNOWLEDGE.id,
            ),
          };
        case "toolkits":
          return {
            id,
            name,
            href: withId(
              APP_ROUTES.USER.INFERENCE.TOOLKITS.id,
              id,
              ROUTE_PARAMS.TOOLKIT.id,
            ),
          };
        case "skillsets":
          return {
            id,
            name,
            href: withId(
              APP_ROUTES.USER.INFERENCE.SKILLSETS.id,
              id,
              ROUTE_PARAMS.SKILLSET.id,
            ),
          };
        case "conversations":
          return {
            id,
            name: name === "Untitled" ? `Chat ${id.slice(0, 8)}` : name,
            href: `${APP_ROUTES.USER.activity}?conversation=${id}`,
          };
        case "projects":
          return {
            id,
            name,
            href: withId(
              APP_ROUTES.USER.PROJECTS.id,
              id,
              ROUTE_PARAMS.PROJECT.id,
            ),
          };
        default:
          return {
            id,
            name,
            href: withId(
              APP_ROUTES.USER.INFERENCE.AGENTS.id,
              id,
              ROUTE_PARAMS.AGENT.id,
            ),
          };
      }
    });
  }, [data, limit, resource]);
 
  if (resource === "toolkits" && !MCP_AVAILABLE) {
    return (
      <Empty>
        Toolkits are coming soon — MCP servers are not available in this
        release.
      </Empty>
    );
  }
  if (isLoading) return <Spinner />;
  if (rows.length === 0) return <Empty>Nothing here yet.</Empty>;
 
  return (
    <ul className="space-y-0.5">
      {rows.map((row) => (
        <li key={row.id}>
          <Link
            to={row.href}
            className="block truncate rounded-lg px-2 py-1.5 text-xs text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/60 transition-colors"
          >
            {row.name}
          </Link>
        </li>
      ))}
    </ul>
  );
};