All files / src/components/cost ResourceCostCard.tsx

83.33% Statements 10/12
34.48% Branches 10/29
60% Functions 3/5
83.33% Lines 10/12

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                                          34x                               34x             20x 20x 20x     8x                 20x 20x             20x                         80x                                                                                                                                                              
import { SectionCard, Skeleton } from "@/components/detail";
import { CostPeriod, CostSource, ResourceCost } from "@/objects/Cost";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import { AlertTriangle, Coins } from "lucide-react";
import React, { useState } from "react";
import DailyCostBars from "./DailyCostBars";
import { describeCost, formatCount, formatUsd } from "./format";
 
/**
 * What one resource has cost — the card every page that invokes a model
 * carries (agent, skill, dashboard, evaluation).
 *
 * Reads `GET /app/stats/cost` by *source*: the resource the spend is
 * attributed to, so a dashboard's card counts its tiles' calls whichever
 * agent they borrowed. The figure is what svc-ai measured — every model call
 * priced on the model that made it — and says "≥" when some of it could not
 * be priced. See `docs/guides/cost-monitoring.md`.
 */
 
const PERIODS: { key: CostPeriod; label: string }[] = [
  { key: "last_7_days", label: "7d" },
  { key: "last_30_days", label: "30d" },
  { key: "this_month", label: "Month" },
  { key: "all_time", label: "All" },
];
 
export interface ResourceCostCardProps {
  source: CostSource;
  sourceId: string;
  /** "agent", "skill" — used in the empty state. */
  noun: string;
  className?: string;
  defaultPeriod?: CostPeriod;
}
 
const ResourceCostCard: React.FC<ResourceCostCardProps> = ({
  source,
  sourceId,
  noun,
  className,
  defaultPeriod = "last_30_days",
}) => {
  const { getApiHandler } = useApiHandler();
  const [period, setPeriod] = useState<CostPeriod>(defaultPeriod);
  const { data, isLoading } = useQuery<ResourceCost | null>({
    queryKey: [QUERY_KEYS.GET.RESOURCE_COST, source, sourceId, period],
    queryFn: () =>
      getApiHandler().stats_router.getCost({
        source_type: source,
        source_id: sourceId,
        period,
      }),
  });
  // Anything not shaped like a cost answer — an error body, a proxy page —
  // is "unavailable", never a figure read off missing fields.
  const cost: ResourceCost | null =
    data && typeof data.invocations === "number" ? data : null;
  const figure = cost
    ? describeCost({
        cost_usd: cost.cost_usd,
        unpriced: cost.unpriced_calls + cost.unpriced_invocations,
      })
    : null;
 
  return (
    <SectionCard
      icon={Coins}
      title="Cost"
      subtitle={cost?.period_label}
      className={className}
      action={
        <div
          role="tablist"
          aria-label="Cost period"
          className="flex rounded-lg border border-gray-200 dark:border-gray-600 p-0.5"
        >
          {PERIODS.map((p) => (
            <button
              key={p.key}
              type="button"
              role="tab"
              aria-selected={period === p.key}
              onClick={() => setPeriod(p.key)}
              className={`px-2 py-0.5 rounded-md text-[11px] font-medium transition-colors ${
                period === p.key
                  ? "bg-gray-900 dark:bg-white text-white dark:text-gray-900"
                  : "text-gray-500 dark:text-gray-400 hover:text-gray-700"
              }`}
            >
              {p.label}
            </button>
          ))}
        </div>
      }
    >
      {isLoading ? (
        <div className="space-y-2">
          <Skeleton className="h-8 w-32" />
          <Skeleton className="h-14 w-full" />
        </div>
      ) : !cost ? (
        <p className="text-sm text-gray-400 italic">Cost is unavailable.</p>
      ) : cost.invocations === 0 ? (
        <p className="text-sm text-gray-400 dark:text-gray-500 italic">
          This {noun} has not called a model in this period.
        </p>
      ) : (
        <div className="space-y-4">
          <div className="flex flex-wrap items-end gap-x-6 gap-y-2">
            <div>
              <div
                className={`text-2xl font-semibold tabular-nums ${
                  figure?.unknown
                    ? "text-gray-400"
                    : "text-gray-900 dark:text-gray-100"
                }`}
              >
                {figure?.text}
              </div>
              <div className="text-[11px] text-gray-500 dark:text-gray-400">
                {cost.invocations.toLocaleString()} invocation
                {cost.invocations === 1 ? "" : "s"} ·{" "}
                {formatCount(cost.llm_calls)} model calls ·{" "}
                {formatCount(cost.input_tokens + cost.output_tokens)} tokens
                {cost.failed_invocations > 0 &&
                  ` · ${cost.failed_invocations} failed`}
              </div>
            </div>
            {cost.by_execution_type.length > 1 && (
              <ul className="text-[11px] text-gray-600 dark:text-gray-300 space-y-0.5">
                {cost.by_execution_type.map((slice) => (
                  <li key={slice.key ?? "none"} className="tabular-nums">
                    <span className="text-gray-500 dark:text-gray-400">
                      {slice.label}
                    </span>{" "}
                    {slice.cost_usd === null ? "unpriced" : formatUsd(slice.cost_usd)}
                  </li>
                ))}
              </ul>
            )}
          </div>
          <DailyCostBars days={cost.daily} />
          {figure?.lowerBound && (
            <p className="flex items-start gap-1.5 text-[11px] text-amber-700 dark:text-amber-300">
              <AlertTriangle className="size-3.5 shrink-0 mt-px" />
              Some calls used a model with no price in the catalogue, so the
              real figure is higher. Add the model's prices to count them.
            </p>
          )}
        </div>
      )}
    </SectionCard>
  );
};
 
export default ResourceCostCard;