All files / src/apps/user/pages/knowledge figures.ts

85.26% Statements 81/95
80.39% Branches 41/51
92.85% Functions 26/28
89.55% Lines 60/67

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                              13x 13x               296x 142x 69x 13x 13x 13x       346x 75x 75x 76x 41x       13x     76x 76x   27x       76x 76x 54x     76x       39x 39x   16x     39x 39x 30x     39x               13x           49x 3x   13x       59x 22x 19x 18x 29x 15x 2x         25x 6x 4x 1x       13x 88x         24x 24x 446x 446x 446x         446x           43x 43x 43x 43x 43x 43x 43x 43x 21x                                  
import type { KnowledgeStats, RepositoryStats } from "@/objects/Knowledge";
import { INCLUDE_SYSTEM, QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { parseServerDate } from "@/util/time";
import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
 
/**
 * The knowledge pages' figures (svc-core `GET /knowledge/stats`,
 * `/repositories/stats`): one request per list, whatever its length — the
 * Sources cards used to ask for each card's documents.
 *
 * Keyed under each list's own prefix, so whatever invalidates the list
 * (an upload, a source added to a repository) refreshes its figures too.
 */
export const KNOWLEDGE_STATS_KEY = [QUERY_KEYS.GET.KNOWLEDGE, "stats", INCLUDE_SYSTEM];
export const REPOSITORY_STATS_KEY = [
  QUERY_KEYS.GET.REPOSITORIES,
  "stats",
  INCLUDE_SYSTEM,
];
 
/** One source's queries, all under `[KNOWLEDGE_BY_ID, id]`: invalidating
 *  the source refreshes its documents, figures, usage and trust with it. */
export const sourceKey = (id: string) => [QUERY_KEYS.GET.KNOWLEDGE_BY_ID, id];
export const documentsKey = (id: string) => [...sourceKey(id), "docs"];
export const sourceStatsKey = (id: string) => [...sourceKey(id), "stats"];
export const sourceUsageKey = (id: string, days: number) => [...sourceKey(id), "usage", days];
export const sourceTrustKey = (id: string) => [...sourceKey(id), "trust"];
export const TRUST_SIGNALS_KEY = [QUERY_KEYS.GET.KNOWLEDGE, "trust-signals"];
 
/** One repository's queries, all under `[REPOSITORY_BY_ID, id]`, which every
 *  change to it (a source added or removed, an edit) already invalidates. */
export const repositoryKey = (id: string) => [QUERY_KEYS.GET.REPOSITORY_BY_ID, id];
export const repositoryMembersKey = (id: string) => [...repositoryKey(id), "knowledge"];
export const repositoryStatsKey = (id: string) => [...repositoryKey(id), "stats"];
export const repositoryMapKey = (id: string) => [...repositoryKey(id), "map"];
export const repositoryTrustKey = (id: string) => [...repositoryKey(id), "trust"];
 
/** Figures change as answers are given and crawls run, not as the page is
 *  read: a minute is fresh enough. */
const STALE_MS = 60_000;
 
export function useKnowledgeStats() {
  const { getApiHandler } = useApiHandler();
  const query = useQuery<KnowledgeStats[]>({
    queryKey: KNOWLEDGE_STATS_KEY,
    queryFn: () => getApiHandler().knowledge_router.stats({ includeSystem: true }),
    staleTime: STALE_MS,
  });
  // Typed here: TypeScript cannot infer react-query v5's return type.
  const data: KnowledgeStats[] | undefined = query.data;
  const byId = useMemo(
    () => new Map<string, KnowledgeStats>((data ?? []).map((s) => [s.knowledge_id, s])),
    [data],
  );
  return { byId, loading: query.isLoading };
}
 
export function useRepositoryStats() {
  const { getApiHandler } = useApiHandler();
  const query = useQuery<RepositoryStats[]>({
    queryKey: REPOSITORY_STATS_KEY,
    queryFn: () => getApiHandler().repository_router.stats({ includeSystem: true }),
    staleTime: STALE_MS,
  });
  const data: RepositoryStats[] | undefined = query.data;
  const byId = useMemo(
    () => new Map<string, RepositoryStats>((data ?? []).map((s) => [s.repository_id, s])),
    [data],
  );
  return { byId, loading: query.isLoading };
}
 
/**
 * Why a source needs attention, in a card's words — keyed by the trust
 * signal that said so (svc-core `services/knowledge/trust.py`'s attention
 * signals, pinned by `figures.test.ts`).
 */
export const ATTENTION_REASON: Record<string, string> = {
  tools_rules: "A Tools rule here blocks one of its sites",
  freshness: "Behind its refresh",
  index_health: "Documents could not be indexed",
};
 
export const attentionReasons = (stats?: KnowledgeStats | null): string[] =>
  (stats?.attention ?? []).map((key) => ATTENTION_REASON[key] ?? key);
 
const IN_FLIGHT = ["pending", "indexing", "importing", "held"];
 
/** A source's state at a glance (`SOURCE_HEALTH`). */
export function sourceHealth(sourceType: string, stats?: KnowledgeStats | null): string {
  if (!stats) return "empty";
  if (stats.attention.length) return "attention";
  if (sourceType === "db" || sourceType === "api") return "in_place";
  if (stats.items === 0) return "empty";
  if (IN_FLIGHT.some((state) => (stats.documents.by_state[state] ?? 0) > 0))
    return "indexing";
  return "ready";
}
 
/** A repository's state at a glance (`SOURCE_HEALTH`). */
export function repositoryHealth(stats?: RepositoryStats | null): string {
  if (!stats || stats.sources === 0) return "empty";
  if (stats.attention_sources > 0) return "attention";
  if (stats.documents_indexed < stats.documents_total) return "indexing";
  return "ready";
}
 
/** How much of what it holds is searchable, 0–1; null with nothing to index. */
export const indexedShare = (indexed: number, total: number): number | null =>
  total > 0 ? indexed / total : null;
 
/** Each day of a citations series, for its column's hover: "23 Oct: 3
 *  answers". The series ends today (UTC), oldest first. */
export function citationTitles(daily: number[], now: Date = new Date()): string[] {
  const [year, month, date] = [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()];
  return daily.map((answers, i) => {
    const back = daily.length - 1 - i;
    const day = new Date(Date.UTC(year, month, date - back));
    const label = day.toLocaleDateString(undefined, {
      day: "numeric",
      month: "short",
      timeZone: "UTC",
    });
    return `${label}: ${answers.toLocaleString()} ${answers === 1 ? "answer" : "answers"}`;
  });
}
 
/** "just now", "5m ago", "3d ago", then the date. */
export function formatAgo(iso: string, now: number = Date.now()): string {
  const diff = now - parseServerDate(iso).getTime();
  const mins = Math.floor(diff / 60000);
  Iif (mins < 1) return "just now";
  Iif (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  Iif (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 30) return `${days}d ago`;
  return parseServerDate(iso).toLocaleDateString(undefined, {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}
 
/** When something is next due: "in 3h", "in 2d", or "due now". */
export function formatUntil(iso: string, now: number = Date.now()): string {
  const diff = parseServerDate(iso).getTime() - now;
  if (diff <= 60_000) return "due now";
  const mins = Math.round(diff / 60000);
  if (mins < 60) return `in ${mins}m`;
  const hrs = Math.round(mins / 60);
  if (hrs < 48) return `in ${hrs}h`;
  return `in ${Math.round(hrs / 24)}d`;
}