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 | 3x 34x 24x 10x 3x 34x 2x 34x 3x 34x 34x 34x 34x 34x 34x 34x 3x 3x 3x 3x 42x 40x 40x 3x 3x 3x 37x 37x 37x 37x 37x 74x 47x 47x 47x 47x 74x 24x 74x 24x 24x 24x 24x 37x 37x 37x 29x 37x 25x 25x 36x 25x 37x 29x 174x 74x 37x 37x 40x 40x 37x 37x 1x 37x 40x 2x 40x 34x 7x 27x | import { OriginBadge } from "@/components/owner";
import { encodeResourceId } from "@/components/detail";
import BuiltInBadge from "@/components/badge/BuiltInBadge";
import GeneratedMark from "@/components/badge/GeneratedMark";
import GenerateKnowledgeModal from "@/apps/user/pages/knowledge/GenerateKnowledgeModal";
import {
SOURCE_TYPE_TILE,
itemCount,
sourceType,
} from "@/apps/user/pages/knowledge/sourceTypes";
import {
collectionSection,
CreateButton,
FilterSelect,
GenerateButton,
ResourceCollection,
SegmentedFilter,
SortSelect,
useCollectionFilters,
} from "@/components/collection";
import { isSystemManaged } from "@/objects/Doc";
import { Knowledge, KnowledgeStats } from "@/objects/Knowledge";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import {
BookCopy,
ChevronRight,
FolderGit2,
FolderMinus,
Lightbulb,
MessageSquareOff,
TriangleAlert,
} from "lucide-react";
import React, { useCallback, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { CitationsFigure, Figure, HealthBadge, IndexedFigure } from "./cardParts";
import { attentionReasons, formatAgo, sourceHealth, useKnowledgeStats } from "./figures";
import KnowledgeSummary from "./KnowledgeSummary";
import RecommendationList, {
useKnowledgeRecommendations,
} from "./recommendations/RecommendationList";
export interface KnowledgeGridProps {
/** The user's own sources — what every count on the page is about. */
knowledge: Knowledge[];
/** The platform's sources, behind its built-in repositories (the CHAIN-R
* User Guide, News): listed apart, above the user's own, and read-only. */
builtIn?: Knowledge[];
/** Which built-in repository each built-in source belongs to, by id. */
builtInRepositoryNames?: Map<string, string[]>;
loading?: boolean;
/** Intro copy for the collection — the Knowledge page's Sources tab
* explains sources here, where a sidebar used to. */
description?: React.ReactNode;
}
// ─── Knowledge card ───────────────────────────────────────────────────────────
/** What a card's figures strip shows of what a source holds: how much of
* it is indexed (documents, pages), or a graph's entities. */
const HoldsFigure: React.FC<{ item: Knowledge; stats?: KnowledgeStats }> = ({
item,
stats,
}) => {
if (item.source_type === "file" || item.source_type === "web") {
return (
<IndexedFigure
indexed={stats?.documents.by_state.indexed ?? 0}
total={stats?.documents.total ?? 0}
noun={sourceType(item.source_type).item.many}
/>
);
}
return (
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100 tabular-nums">
{item.source_type === "graph" ? itemCount("graph", stats?.items ?? 0) : "—"}
</span>
);
};
/** "In Policies, Regulation", from the figures (this workspace's
* repositories) or, for a built-in, its built-in repository. */
const repositoryLine = (stats?: KnowledgeStats, builtInNames?: string[]) => {
const names = builtInNames?.length
? builtInNames
: (stats?.repositories ?? []).map((r) => r.name);
return names.length ? `In ${names.join(", ")}` : null;
};
const KnowledgeCard: React.FC<{
item: Knowledge;
stats?: KnowledgeStats;
statsLoading: boolean;
/** Set for a built-in source: the built-in repositories it belongs to. */
repositoryNames?: string[];
}> = ({ item, stats, statsLoading, repositoryNames }) => {
const builtIn = isSystemManaged(item);
const href = APP_ROUTES.USER.KNOWLEDGE.id.replace(
ROUTE_PARAMS.KNOWLEDGE.id,
encodeResourceId(item.id),
);
const meta = sourceType(item.source_type);
const Icon = meta.Icon;
const inRepository = repositoryLine(stats, repositoryNames);
const summary = stats?.config_summary;
return (
<div className="group flex flex-col rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm hover:shadow-md hover:border-gray-300 dark:hover:border-gray-500 transition-all overflow-hidden">
<Link to={href} className="flex-1 p-5 flex flex-col gap-4">
<div className="flex items-start justify-between gap-3">
<div className="flex items-start gap-3 min-w-0">
<GeneratedMark
generated={item.is_ai_generated}
label="AI generated knowledge base"
>
<div className={`p-2 ${SOURCE_TYPE_TILE}`}>
<Icon className="size-5" />
</div>
</GeneratedMark>
<div className="min-w-0">
{/* Two lines rather than one: names that share a prefix ("European
Commission — …") are otherwise cut to the same few words. */}
<div className="text-sm font-semibold text-gray-900 dark:text-gray-100 line-clamp-2 break-words">
{item.name}
</div>
<OriginBadge resource={item} className="mt-1" />
<div className="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-gray-400 dark:text-gray-500 mt-0.5">
<span className="flex items-center gap-1">
<Icon className="size-3 shrink-0" />
{meta.label}
</span>
{builtIn && <BuiltInBadge size="sm" />}
</div>
</div>
</div>
{!statsLoading && (
<span className="shrink-0">
<HealthBadge
health={sourceHealth(item.source_type, stats)}
reasons={attentionReasons(stats)}
/>
</span>
)}
</div>
{item.description ? (
<p className="text-xs text-gray-500 dark:text-gray-400 line-clamp-2 leading-relaxed">
{item.description}
</p>
) : (
<p className="text-xs text-gray-300 dark:text-gray-600 italic">
No description.
</p>
)}
{summary && (
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 dark:bg-gray-700/50 min-w-0">
<Icon className="size-3 text-gray-400 dark:text-gray-500 shrink-0" />
<code className="text-xs text-gray-500 dark:text-gray-400 font-mono truncate">
{summary}
</code>
</div>
)}
<div className="mt-auto grid grid-cols-3 gap-3 pt-3 border-t border-gray-100 dark:border-gray-700">
<Figure
label={item.source_type === "graph" ? "Holds" : "Indexed"}
loading={statsLoading}
>
<HoldsFigure item={item} stats={stats} />
</Figure>
<Figure label="Updated" loading={statsLoading}>
<span className="text-sm text-gray-700 dark:text-gray-300 truncate block">
{stats?.last_updated_at ? formatAgo(stats.last_updated_at) : "—"}
</span>
</Figure>
<Figure label="Cited · 30 days" loading={statsLoading}>
<CitationsFigure
daily={stats?.citations_daily ?? []}
total={stats?.citations ?? 0}
retrieved={stats?.retrieved}
/>
</Figure>
</div>
</Link>
<div className="flex items-center justify-between gap-3 px-5 py-3 border-t border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
<span className="flex items-center gap-1 min-w-0 text-[10px] text-gray-400 dark:text-gray-500">
<FolderGit2 className="size-3 shrink-0" />
<span className="truncate">{inRepository ?? "In no repository"}</span>
{!builtIn && stats && stats.agents > 0 && (
<span className="shrink-0">
{" · "}
{stats.agents} agent{stats.agents !== 1 ? "s" : ""}
</span>
)}
</span>
<Link
to={href}
className="flex items-center gap-1 shrink-0 text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
>
View
<ChevronRight className="size-3.5" />
</Link>
</div>
</div>
);
};
// ─── Knowledge row ────────────────────────────────────────────────────────────
const KnowledgeRow: React.FC<{
item: Knowledge;
stats?: KnowledgeStats;
statsLoading: boolean;
repositoryNames?: string[];
}> = ({ item, stats, statsLoading, repositoryNames }) => {
const builtIn = isSystemManaged(item);
const inRepository = repositoryLine(stats, repositoryNames);
const href = APP_ROUTES.USER.KNOWLEDGE.id.replace(
ROUTE_PARAMS.KNOWLEDGE.id,
encodeResourceId(item.id),
);
const meta = sourceType(item.source_type);
const Icon = meta.Icon;
return (
<Link
to={href}
className="flex items-center gap-4 px-4 py-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 hover:border-gray-300 dark:hover:border-gray-500 hover:shadow-sm transition-all group"
>
<GeneratedMark
generated={item.is_ai_generated}
size="sm"
label="AI generated knowledge base"
>
<div className={`p-1.5 ${SOURCE_TYPE_TILE}`}>
<Icon className="size-4" />
</div>
</GeneratedMark>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5 min-w-0">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100 line-clamp-2 break-words">
{item.name}
</div>
<OriginBadge resource={item} />
</div>
{builtIn ? (
<div className="flex items-center gap-1.5 min-w-0 mt-0.5">
<BuiltInBadge size="sm" />
{inRepository && (
<span className="text-xs text-gray-400 dark:text-gray-500 truncate">
{inRepository}
</span>
)}
</div>
) : item.description ? (
<div className="text-xs text-gray-400 dark:text-gray-500 truncate mt-0.5">
{item.description}
</div>
) : (
<div className="text-xs text-gray-300 dark:text-gray-600 italic mt-0.5">
No description.
</div>
)}
</div>
<span className="hidden sm:block shrink-0 text-xs text-gray-400 dark:text-gray-500 tabular-nums">
{stats ? itemCount(item.source_type, stats.items) : meta.label}
</span>
{stats && (
<span className="hidden lg:block shrink-0">
<CitationsFigure
daily={stats.citations_daily}
total={stats.citations}
retrieved={stats.retrieved}
/>
</span>
)}
{!statsLoading && (
<span className="shrink-0">
<HealthBadge
health={sourceHealth(item.source_type, stats)}
reasons={attentionReasons(stats)}
/>
</span>
)}
<ChevronRight className="size-3.5 text-gray-400 dark:text-gray-500 group-hover:text-gray-700 dark:group-hover:text-gray-300 shrink-0 transition-colors" />
</Link>
);
};
// ─── KnowledgeGrid ────────────────────────────────────────────────────────────
const SOURCE_FILTERS = ["all", "file", "graph", "web", "db", "api"] as const;
type SortKey = "recent" | "name" | "type" | "cited";
const SORT_OPTIONS: { value: SortKey; label: string }[] = [
{ value: "recent", label: "Newest first" },
{ value: "name", label: "Name (A-Z)" },
{ value: "type", label: "Source type" },
{ value: "cited", label: "Most cited" },
];
/** The summary strip's steps (`?show=`): what is worth acting on. Each
* filters the list, but "What to improve", which shows the workspace's
* recommendations under the strip. */
type FilterKey = "attention" | "unshelved" | "uncited";
type ShowKey = "all" | "improve" | FilterKey;
const SHOWS: Record<FilterKey, (stats?: KnowledgeStats) => boolean> = {
attention: (stats) => (stats?.attention.length ?? 0) > 0,
unshelved: (stats) => !stats?.repositories.length,
uncited: (stats) => !stats?.citations,
};
const ORIGIN_OPTIONS = [
{ value: "all", label: "Any origin" },
{ value: "generated", label: "AI generated" },
{ value: "manual", label: "Hand-built" },
];
const NO_BUILT_INS: Knowledge[] = [];
const KnowledgeGrid: React.FC<KnowledgeGridProps> = ({
knowledge,
builtIn = NO_BUILT_INS,
builtInRepositoryNames,
loading,
description,
}) => {
const [showGenerateModal, setShowGenerateModal] = useState(false);
// Sort is excluded from the active-filter count: reordering hides nothing.
const collection = useCollectionFilters<{
type: string;
origin: string;
sort: SortKey;
show: ShowKey;
}>({
defaults: { type: "all", origin: "all", sort: "recent", show: "all" },
unfiltered: ["sort"],
});
const { filters, setFilter, matches } = collection;
// Every source's figures, in one request.
const { byId: statsById, loading: statsLoading } = useKnowledgeStats();
// One filter over both groups, so the toolbar narrows the built-in
// sources exactly as it narrows the user's own.
const shownOf = useCallback(
(list: Knowledge[]) => {
const filtered = list.filter((k) => {
const matchesType =
filters.type === "all" || k.source_type === filters.type;
const matchesOrigin =
filters.origin === "all" ||
(filters.origin === "generated"
? !!k.is_ai_generated
: !k.is_ai_generated);
const matchesShow =
filters.show === "all" ||
filters.show === "improve" ||
SHOWS[filters.show](statsById.get(k.id));
return (
matchesType &&
matchesOrigin &&
matchesShow &&
matches(k.name, k.description)
);
});
const byName = (a: Knowledge, b: Knowledge) =>
a.name.localeCompare(b.name);
return [...filtered].sort((a, b) => {
Iif (filters.sort === "name") return byName(a, b);
Iif (filters.sort === "type")
return a.source_type.localeCompare(b.source_type) || byName(a, b);
Iif (filters.sort === "cited")
return (
(statsById.get(b.id)?.citations ?? 0) -
(statsById.get(a.id)?.citations ?? 0) || byName(a, b)
);
return (
(b.created_at ?? "").localeCompare(a.created_at ?? "") ||
byName(a, b)
);
});
},
[filters, matches, statsById],
);
const visible = useMemo(() => shownOf(knowledge), [shownOf, knowledge]);
const visibleBuiltIn = useMemo(() => shownOf(builtIn), [shownOf, builtIn]);
// The stats are the user's own; the type filter covers everything listed,
// built-in sources included, since it narrows both groups.
const ownTypes = useMemo(
() => new Set(knowledge.map((k) => k.source_type)),
[knowledge],
);
const countByType = useMemo(() => {
const counts = new Map<string, number>();
for (const k of [...knowledge, ...builtIn])
counts.set(k.source_type, (counts.get(k.source_type) ?? 0) + 1);
return counts;
}, [knowledge, builtIn]);
// A type from the URL with nothing in it still gets a segment, so the
// filter that emptied the list is visible next to the empty state rather
// than implied.
const typeFilterOptions = useMemo(
() =>
SOURCE_FILTERS.filter(
(f) => f === "all" || countByType.has(f) || f === filters.type,
).map((f) => ({
value: f as string,
label: f === "all" ? "All" : sourceType(f).label,
count:
f === "all"
? knowledge.length + builtIn.length
: (countByType.get(f) ?? 0),
})),
[countByType, knowledge.length, builtIn.length, filters.type],
);
const createButton = (
<CreateButton
label="New Knowledge Base"
to={APP_ROUTES.USER.KNOWLEDGE.new}
/>
);
const generateButton = (
<GenerateButton onClick={() => setShowGenerateModal(true)} />
);
// The strip counts the workspace's own sources, as every count here does;
// its filters narrow the built-in ones too.
const ownStats = knowledge.map((k) => statsById.get(k.id));
const citedTimes = ownStats.reduce((sum, st) => sum + (st?.citations ?? 0), 0);
const { data: recommendations } = useKnowledgeRecommendations();
const summary = (
<div className="space-y-3">
<KnowledgeSummary
label="Sources worth a look"
loading={loading || statsLoading}
selected={filters.show}
onSelect={(key) => setFilter("show", key as ShowKey)}
headline={
<>
Your sources were cited{" "}
<strong className="font-semibold text-gray-900 dark:text-gray-100 tabular-nums">
{citedTimes.toLocaleString()}
</strong>{" "}
{citedTimes === 1 ? "time" : "times"} in the last 30 days.
</>
}
steps={[
{
key: "attention",
label: "Needs attention",
hint: "Blocked here, behind its refresh, or failing to index",
count: ownStats.filter(SHOWS.attention).length,
Icon: TriangleAlert,
warns: true,
},
{
key: "unshelved",
label: "In no repository",
hint: "Indexed, but no agent can be granted it",
count: ownStats.filter(SHOWS.unshelved).length,
Icon: FolderMinus,
},
{
key: "uncited",
label: "Not cited in 30 days",
hint: "No answer drew on it",
count: ownStats.filter(SHOWS.uncited).length,
Icon: MessageSquareOff,
},
{
key: "improve",
label: "What to improve",
hint: "From what agents asked and how knowledge is used",
count: recommendations?.items.length ?? 0,
Icon: Lightbulb,
},
]}
/>
{filters.show === "improve" && <RecommendationList />}
</div>
);
return (
<>
{showGenerateModal && (
<GenerateKnowledgeModal
mode="sources"
onClose={() => setShowGenerateModal(false)}
/>
)}
<ResourceCollection<Knowledge>
description={description}
stats={[
{ label: "Knowledge Bases", value: knowledge.length, loading },
{ label: "Source types", value: ownTypes.size, loading },
{
label: "AI generated",
value: knowledge.filter((k) => k.is_ai_generated).length,
loading,
},
]}
summary={summary}
shown={visible.length + visibleBuiltIn.length}
search={{
value: collection.search,
onChange: collection.setSearch,
placeholder: "Search by name or description…",
}}
filters={
<>
{(countByType.size > 1 || filters.type !== "all") && (
<SegmentedFilter
value={filters.type}
onChange={(value) => setFilter("type", value)}
options={typeFilterOptions}
/>
)}
<SortSelect
value={filters.sort}
onChange={(value) => setFilter("sort", value)}
options={SORT_OPTIONS}
defaultValue="recent"
/>
{knowledge.some((k) => k.is_ai_generated) && (
<FilterSelect
value={filters.origin}
onValueChange={(value) => setFilter("origin", value)}
placeholder="Any origin"
options={ORIGIN_OPTIONS}
active={filters.origin !== "all"}
/>
)}
</>
}
{...collection.toolbarProps}
actions={
<>
{generateButton}
{createButton}
</>
}
renderCard={(item) => (
<KnowledgeCard
item={item}
stats={statsById.get(item.id)}
statsLoading={statsLoading}
repositoryNames={builtInRepositoryNames?.get(item.id)}
/>
)}
renderRow={(item) => (
<KnowledgeRow
item={item}
stats={statsById.get(item.id)}
statsLoading={statsLoading}
repositoryNames={builtInRepositoryNames?.get(item.id)}
/>
)}
loading={loading}
listVariant="rows"
sections={[
collectionSection<Knowledge>({
label: "Built-in",
items: visibleBuiltIn,
itemKey: (item) => item.id,
loading,
skeletonCount: 3,
hideWhenEmpty: true,
empty: { Icon: BookCopy, title: "No built-in sources." },
}),
collectionSection<Knowledge>({
label: "Your sources",
items: visible,
itemKey: (item) => item.id,
loading,
skeletonCount: 3,
empty: {
Icon: BookCopy,
title: "No knowledge bases of your own yet.",
hint:
builtIn.length > 0
? "The built-in sources above come with CHAIN-R's repositories and are ready to use. Create a knowledge base of your own to ground agents in your data — or describe what your agents need to know and let the AI propose the sources."
: "Create a knowledge base to start building your AI context — or describe what your agents need to know and let the AI propose the sources.",
dashed: true,
action: (
<div className="flex items-center gap-2">
{generateButton}
{createButton}
</div>
),
},
emptyFilteredTitle: "No knowledge bases match your filters.",
emptyFilteredHint: "Try adjusting your search or filters.",
}),
]}
/>
</>
);
};
export default KnowledgeGrid;
|