All files / src/apps/user/pages/models Model.tsx

72.72% Statements 24/33
51.85% Branches 42/81
63.63% Functions 7/11
73.33% Lines 22/30

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                                                                              1x                                         1x 6x 6x 6x           6x     3x 3x         6x   6x     6x           6x           6x                                 6x               6x                                                                           18x                                                           3x 3x                                               3x 3x                                                                                                   9x                                                                                                                 24x                                                                              
import SubPage from "@/components/page/SubPage/SubPage";
import MakerLogo from "@/components/img/MakerLogo/MakerLogo";
import {
  dataRegionMeta,
  formatCostPerMToken,
  formatKnowledgeCutoff,
  modelDisplayName,
  modelEffortMeta,
  modelLatencyMeta,
} from "@/objects/Model";
import { makerKey, modelMaker, servedBy } from "@/objects/modelOrigin";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import {
  BotMessageSquare,
  BrainCog,
  Calendar,
  Cpu,
  Hash,
  MapPin,
  Server,
  Sparkles,
  Tag,
} from "lucide-react";
import React from "react";
import { Link, useParams } from "react-router-dom";
import {
  CopyButton,
  MetaItem,
  SectionCard,
  Skeleton,
  useResourceId,
} from "@/components/detail";
import { parseServerDate } from "@/util/time";
 
// ─── Shared primitives ────────────────────────────────────────────────────────
 
const TagPill: React.FC<{
  label: string;
  variant: "capability" | "limitation";
}> = ({ label, variant }) => (
  <span
    className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${
      variant === "capability"
        ? "bg-emerald-50 dark:bg-emerald-950/40 text-emerald-700 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-800"
        : "bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300 border border-amber-200 dark:border-amber-800"
    }`}
  >
    {label}
  </span>
);
 
// ─── Copy button ──────────────────────────────────────────────────────────────
 
// ─── Loading skeleton ─────────────────────────────────────────────────────────
 
// ─── ModelViewer ──────────────────────────────────────────────────────────────
 
const ModelViewer: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const { modelId } = useParams();
  const decodedModelId = useResourceId("modelId");
 
  const {
    data: model,
    error,
    isLoading,
  } = useQuery({
    queryKey: [QUERY_KEYS.GET.MODEL_BY_ID, decodedModelId],
    queryFn: async () => {
      Iif (!decodedModelId) return null;
      return getApiHandler().model_router.id(decodedModelId);
    },
    enabled: !!decodedModelId,
  });
 
  Iif (!modelId)
    return <div className="p-4 text-red-500">Invalid model ID.</div>;
  Iif (error)
    return <div className="p-4 text-red-500">Error: {error.toString()}</div>;
 
  const chatLink = APP_ROUTES.USER.INFERENCE.MODELS.chat.replace(
    ROUTE_PARAMS.MODEL.id,
    modelId,
  );
 
  // Config entries worth displaying (non-empty values)
  const configEntries = model
    ? Object.entries(model.config ?? {}).filter(
        ([, v]) => v !== null && v !== "",
      )
    : [];
 
  const actionLinks = isLoading
    ? []
    : [
        ...(model?.is_available && !model.is_embedding
          ? [
              <Link
                to={chatLink}
                className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gray-900 dark:bg-white text-white dark:text-gray-900 text-sm font-medium hover:opacity-80 transition-opacity"
              >
                <BotMessageSquare className="size-4" />
                Chat
              </Link>,
            ]
          : []),
        ...(model ? [<CopyButton value={model.model_name} />] : []),
      ];
 
  const capabilityTags = model
    ? ([
        model.is_chat && "Chat",
        model.is_vision && "Vision",
        model.is_embedding && "Embedding",
      ].filter(Boolean) as string[])
    : [];
 
  return (
    <SubPage
      back={APP_ROUTES.USER.INFERENCE.models}
      title={
        isLoading ? (
          <Skeleton className="h-7 w-48" />
        ) : (
          <span className="flex items-center gap-3">
            {model ? modelDisplayName(model) : "—"}
            {model?.is_embedding && (
              <span className="text-xs font-normal px-2 py-0.5 rounded-full bg-violet-100 dark:bg-violet-900/40 text-violet-700 dark:text-violet-300 border border-violet-200 dark:border-violet-800">
                Embedding
              </span>
            )}
            {!model?.is_embedding && (
              <span className="text-xs font-normal px-2 py-0.5 rounded-full bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-800">
                Inference
              </span>
            )}
          </span>
        )
      }
      title_icon={
        model ? (
          <MakerLogo
            maker={makerKey(model.provider?.name, model.model_name)}
            className="size-12"
          />
        ) : (
          <BrainCog className="size-12 text-gray-400 dark:text-gray-500" />
        )
      }
      links={actionLinks}
    >
      {/* Metadata strip */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-5 p-5 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm mb-6">
        {isLoading ? (
          Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="flex flex-col gap-1.5">
              <Skeleton className="h-3 w-16" />
              <Skeleton className="h-4 w-24" />
            </div>
          ))
        ) : (
          <>
            <MetaItem
              icon={Hash}
              label="Model ID"
              value={
                <code className="text-xs bg-gray-100 dark:bg-gray-700 px-1.5 py-0.5 rounded font-mono">
                  {model?.model_name ?? "—"}
                </code>
              }
            />
            <MetaItem
              icon={Tag}
              label="Made by"
              value={model ? modelMaker(model) : "—"}
            />
            <MetaItem
              icon={Server}
              label="Runs on"
              value={model ? servedBy(model) : "—"}
            />
            <MetaItem
              icon={Sparkles}
              label="Effort"
              value={(() => {
                const effort = modelEffortMeta(model?.effort);
                Eif (!effort) return "—";
                return (
                  <span
                    title={`${effort.description} (${effort.examples})`}
                    className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${effort.badge}`}
                  >
                    {effort.label}
                  </span>
                );
              })()}
            />
            <MetaItem
              icon={Cpu}
              label="Context window"
              value={
                model?.context_window
                  ? `${model.context_window.toLocaleString()} tokens`
                  : "—"
              }
            />
            <MetaItem
              icon={MapPin}
              label="Data region"
              value={(() => {
                const region = dataRegionMeta(model?.data_region);
                Eif (!region) return "—";
                return (
                  <span
                    className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${region.badge}`}
                  >
                    {region.label}
                  </span>
                );
              })()}
            />
            <MetaItem
              icon={Calendar}
              label="Registered"
              value={
                model?.created_at
                  ? parseServerDate(model.created_at).toLocaleDateString(undefined, {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                    })
                  : "—"
              }
            />
          </>
        )}
      </div>
 
      {/* Capability tags */}
      {!isLoading && capabilityTags.length > 0 && (
        <div className="flex flex-wrap gap-2 mb-4">
          {capabilityTags.map((cap) => (
            <TagPill key={cap} label={cap} variant="capability" />
          ))}
        </div>
      )}
 
      {/* Description */}
      {!isLoading && model?.description && (
        <SectionCard icon={Tag} title="Description" className="mb-4">
          <p className="text-sm text-gray-700 dark:text-gray-300">
            {model.description}
          </p>
        </SectionCard>
      )}
 
      {/* Specs */}
      <SectionCard icon={Cpu} title="Specifications" className="mb-4">
        {isLoading ? (
          <div className="space-y-2">
            {Array.from({ length: 3 }).map((_, i) => (
              <Skeleton key={i} className="h-4 w-full" />
            ))}
          </div>
        ) : (
          <div className="divide-y divide-gray-100 dark:divide-gray-700 -my-1">
            {[
              [
                "Max output tokens",
                model?.max_output_tokens?.toLocaleString() ?? "—",
              ],
              // A band relative to the rest of the catalogue, not a
              // measurement — labelled as such so it is not read as one.
              [
                "Comparative latency",
                modelLatencyMeta(model?.latency)?.label ?? "—",
              ],
              // "Reliable", not "training data": the date through which the
              // provider vouches for what the model knows.
              [
                "Reliable knowledge cutoff",
                formatKnowledgeCutoff(model?.knowledge_cutoff),
              ],
              ["Input cost", formatCostPerMToken(model?.input_cost_per_token)],
              [
                "Output cost",
                formatCostPerMToken(model?.output_cost_per_token),
              ],
              // Cached and cache-write tokens bill at their own per-model
              // rates — what svc-ai prices each call's cache use at.
              [
                "Cached input cost",
                formatCostPerMToken(model?.cache_read_cost_per_token),
              ],
              [
                "Cache write cost",
                formatCostPerMToken(model?.cache_write_cost_per_token),
              ],
              ...(model?.cache_write_1h_cost_per_token
                ? [
                    [
                      "1-hour cache write cost",
                      formatCostPerMToken(model.cache_write_1h_cost_per_token),
                    ],
                  ]
                : []),
              ...(model?.long_context_threshold
                ? [
                    [
                      "Long-context pricing",
                      `Over ${(model.long_context_threshold / 1000).toLocaleString()}K prompt tokens: ` +
                        `${Number(model.long_context_input_multiplier ?? 1)}× input, ` +
                        `${Number(model.long_context_output_multiplier ?? 1)}× output`,
                    ],
                  ]
                : []),
              ["Available", model?.is_available ? "Yes" : "No"],
            ].map(([key, value]) => (
              <div
                key={key}
                className="flex items-center justify-between py-2.5 text-sm"
              >
                <span className="text-gray-500 dark:text-gray-400">{key}</span>
                <span className="text-gray-800 dark:text-gray-200 font-medium">
                  {value}
                </span>
              </div>
            ))}
          </div>
        )}
      </SectionCard>
 
      {/* Config — only shown if non-empty */}
      {!isLoading && configEntries.length > 0 && (
        <SectionCard icon={Cpu} title="Configuration">
          <div className="divide-y divide-gray-100 dark:divide-gray-700 -my-1">
            {configEntries.map(([key, value]) => (
              <div
                key={key}
                className="flex items-center justify-between py-2.5 text-sm"
              >
                <span className="text-gray-500 dark:text-gray-400 font-mono text-xs">
                  {key}
                </span>
                <span className="text-gray-800 dark:text-gray-200 font-medium text-xs font-mono">
                  {String(value)}
                </span>
              </div>
            ))}
          </div>
        </SectionCard>
      )}
    </SubPage>
  );
};
 
export default ModelViewer;