All files / src/apps/user/pages/knowledge/source SourceOverview.tsx

93.33% Statements 28/30
74.6% Branches 47/63
100% Functions 8/8
93.1% Lines 27/29

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                                                69x 69x   16x       69x 69x     6x     2x 6x                         6x 6x             6x 6x 6x 6x 6x             6x         6x                         6x         3x                                                             6x     2x             6x 6x 6x   6x                                                                                                   3x 3x                                                    
import { KpiStrip, SparkBars, type StatTileProps } from "@/components/charts";
import { MetaGrid, MetaItem, SectionCard } from "@/components/detail";
import type { Knowledge, KnowledgeStats } from "@/objects/Knowledge";
import { resourceHref } from "@/routes/resourceHref";
import { useApiHandler } from "@/services/useApiHandler";
import { formatLocalDate, parseServerDate } from "@/util/time";
import { useQuery } from "@tanstack/react-query";
import { Calendar, PackageOpen, Tag, User } from "lucide-react";
import React from "react";
import { Link } from "react-router-dom";
 
import {
  citationTitles,
  formatAgo,
  formatUntil,
  indexedShare,
  sourceStatsKey,
} from "../figures";
import { SOURCE_TYPE_PILL, sourceType } from "../sourceTypes";
import TrustPanel from "./TrustPanel";
import WhereUsedCard from "./WhereUsedCard";
 
/** A source's figures, as its card reads them — also its Overview's. */
export function useSourceStats(knowledgeId: string | null) {
  const { getApiHandler } = useApiHandler();
  const query = useQuery<KnowledgeStats | null>({
    queryKey: sourceStatsKey(knowledgeId ?? ""),
    queryFn: () => getApiHandler().knowledge_router.sourceStats(knowledgeId as string),
    enabled: !!knowledgeId,
    staleTime: 60_000,
  });
  const stats: KnowledgeStats | null | undefined = query.data;
  return { stats: stats ?? null, loading: query.isLoading };
}
 
const capitalised = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);
 
/** Whose it is, in a word: a built-in is the platform's. */
const ownerOf = (knowledge: Knowledge, builtIn: boolean) =>
  builtIn
    ? "CHAIN-R"
    : knowledge.owner_user_id
      ? "Personal"
      : knowledge.owner_organisation_id
        ? "Organisation"
        : knowledge.owner_project_id
          ? "Project"
          : "—";
 
/** The headline figures: what it holds, how much of it is searchable, how
 *  current it is, and who reaches and cites it here. */
function tilesFor(knowledge: Knowledge, stats: KnowledgeStats | null, loading: boolean) {
  const meta = sourceType(knowledge.source_type);
  const tiles: StatTileProps[] = [
    {
      label: capitalised(meta.item.many),
      value: (stats?.items ?? 0).toLocaleString(),
      loading,
    },
  ];
  Eif (knowledge.source_type === "file" || knowledge.source_type === "web") {
    const indexed = stats?.documents.by_state.indexed ?? 0;
    const total = stats?.documents.total ?? 0;
    const share = indexedShare(indexed, total);
    tiles.push({
      label: "Indexed",
      value: share === null ? "—" : `${Math.round(share * 100)}%`,
      hint: total ? `${indexed.toLocaleString()} of ${total.toLocaleString()}` : "Nothing stored yet",
      loading,
    });
  }
  tiles.push({
    label: "Last updated",
    value: stats?.last_updated_at ? formatAgo(stats.last_updated_at) : "—",
    loading,
  });
  Iif (knowledge.source_type === "web") {
    const crawl = stats?.crawl;
    tiles.push({
      label: "Next crawl",
      value: crawl?.next_due_at
        ? formatUntil(crawl.next_due_at)
        : crawl?.cadence === "manual"
          ? "By hand"
          : "Not scheduled",
      hint: crawl?.cadence ? `Refreshes ${crawl.cadence}` : undefined,
      loading,
    });
  }
  tiles.push(
    {
      label: "Repositories",
      value: (stats?.repositories.length ?? 0).toLocaleString(),
      hint: stats?.repositories.length
        ? stats.repositories.map((r) => r.name).join(", ")
        : "In none here",
      loading,
    },
    {
      label: "Agents",
      value: (stats?.agents ?? 0).toLocaleString(),
      hint: "That can retrieve from it here",
      loading,
    },
    {
      label: "Retrieved · 30 days",
      value: (stats?.retrieved ?? 0).toLocaleString(),
      hint: "Answers its passages were given to",
      loading,
    },
    {
      label: "Cited · 30 days",
      value: (stats?.citations ?? 0).toLocaleString(),
      hint:
        stats && stats.citations_daily.length ? (
          <SparkBars
            values={stats.citations_daily}
            titles={citationTitles(stats.citations_daily)}
            label="Answers citing it, per day over 30 days"
            height={16}
          />
        ) : undefined,
      loading,
    },
  );
  return tiles;
}
 
const SourceOverview: React.FC<{
  knowledge: Knowledge;
  builtIn: boolean;
  /** Nothing in it yet, and the viewer may add to it. */
  emptyHere: boolean;
  onOpenContent: () => void;
}> = ({ knowledge, builtIn, emptyHere, onOpenContent }) => {
  const { stats, loading } = useSourceStats(knowledge.id);
  const meta = sourceType(knowledge.source_type);
  const Icon = meta.Icon;
 
  return (
    <div className="space-y-5">
      <KpiStrip tiles={tilesFor(knowledge, stats, loading)} />
 
      {emptyHere && (
        <SectionCard icon={PackageOpen} title="Nothing in it yet">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <p className="text-sm text-gray-600 dark:text-gray-300">
              {knowledge.source_type === "web"
                ? "Give it the pages to keep current, or let CHAIN-R find them."
                : "Upload documents, import them from their links, or let CHAIN-R find them."}
            </p>
            <button
              type="button"
              onClick={onOpenContent}
              className="shrink-0 rounded-lg bg-gray-900 dark:bg-white px-3 py-1.5 text-xs font-medium text-white dark:text-gray-900 hover:opacity-80"
            >
              Add content
            </button>
          </div>
        </SectionCard>
      )}
 
      <SectionCard icon={Tag} title="About">
        <MetaGrid columns={3}>
          <MetaItem
            icon={Icon}
            label="Type"
            value={
              <span className={`inline-flex items-center gap-1 ${SOURCE_TYPE_PILL}`}>
                <Icon className="size-3" />
                {meta.label}
              </span>
            }
          />
          <MetaItem icon={User} label="Owner" value={ownerOf(knowledge, builtIn)} />
          <MetaItem
            icon={Calendar}
            label="Created"
            value={
              knowledge.created_at
                ? formatLocalDate(parseServerDate(knowledge.created_at))
                : "—"
            }
          />
        </MetaGrid>
        {stats && stats.repositories.length > 0 && (
          <p className="mt-4 text-xs text-gray-500 dark:text-gray-400">
            In{" "}
            {stats.repositories.map((r, i) => {
              const href = resourceHref("knowledge_repository", r.id);
              return (
                <React.Fragment key={r.id}>
                  {i > 0 && ", "}
                  {href ? (
                    <Link to={href} className="font-medium text-gray-700 dark:text-gray-200 hover:underline">
                      {r.name}
                    </Link>
                  ) : (
                    r.name
                  )}
                </React.Fragment>
              );
            })}
          </p>
        )}
      </SectionCard>
 
      <div className="grid gap-5 lg:grid-cols-2">
        <TrustPanel knowledgeId={knowledge.id} />
        <WhereUsedCard knowledgeId={knowledge.id} />
      </div>
    </div>
  );
};
 
export default SourceOverview;