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 | 3x 3x 3x 3x 75x 75x 75x 75x 75x 75x 75x 75x 75x 27x 75x 75x 27x 75x 75x 27x 75x 75x 47x 75x 75x 75x 75x 75x 75x 36x 75x 3x 3x 1x 1x 1x 75x 13x 75x 16x 75x 75x 75x 75x 75x 2x 8x 75x 3x 2x 2x 6x 75x 1x 1x 1x 1x 75x 1x 1x 75x 75x 1x 1x 75x 3x 3x 1x 1x 75x 3x 1x 75x 48x 1x 1x | import { AppearanceSwatch } from "@/components/appearance/AppearancePicker";
import { REPOSITORY_ICON_REGISTRY } from "@/components/appearance/icons";
import BuiltInBadge from "@/components/badge/BuiltInBadge";
import {
ConfirmDialog,
DetailPage,
DetailTabs,
Strong,
useDetailTab,
useResourceId,
} from "@/components/detail";
import { MoveToShared } from "@/components/owner";
import { isSystemManaged } from "@/objects/Doc";
import type {
Knowledge,
KnowledgeRepository,
KnowledgeStats,
RepositoryStatsDetail,
} from "@/objects/Knowledge";
import { APP_ROUTES } from "@/routes/const";
import { INCLUDE_SYSTEM, QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { errorDetail } from "@/util/apiError";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { BarChart3, BookCopy, Bot, LayoutDashboard, Pencil, Trash2 } from "lucide-react";
import React, { useEffect, useMemo, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { CategoryBadge } from "./cardParts";
import { heldAs, isKnowledgeCategory, knowledgeCategory, mayJoin } from "./categories";
import {
repositoryKey,
repositoryMembersKey,
repositoryStatsKey,
sourceKey,
} from "./figures";
import RepositoryAgentsCard from "./RepositoryAgentsCard";
import RepositoryDetailsModal, { type NewRepository } from "./RepositoryDetailsModal";
import RepositoryOverview from "./repository/RepositoryOverview";
import RepositorySources from "./repository/RepositorySources";
import UsagePanel from "./source/UsagePanel";
/**
* A knowledge repository's page, on the detail kit: its figures, the map of
* how its sources connect and their trust (Overview); its sources as a
* table, added and removed here (Sources); what answers drew on it (Usage);
* and which of the viewer's agents use it (Agents). The tab is in the
* address (`?tab=`); the edit history sits under every one.
*/
const BACK_PATH = APP_ROUTES.USER.KNOWLEDGE.repositories;
const TABS = ["overview", "sources", "usage", "agents"] as const;
const ACTION =
"flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg border transition-colors";
const RepositoryViewer: React.FC = () => {
const repositoryId = useResourceId("repositoryId");
const { getApiHandler } = useApiHandler();
const api = getApiHandler().repository_router;
const queryClient = useQueryClient();
const navigate = useNavigate();
const [tab, setTab] = useDetailTab(TABS);
const [editing, setEditing] = useState(false);
const [confirmingDelete, setConfirmingDelete] = useState(false);
const { data, error, isLoading } = useQuery<KnowledgeRepository | null>({
queryKey: repositoryKey(repositoryId ?? ""),
queryFn: () => api.getById(repositoryId as string),
enabled: !!repositoryId,
});
const repository: KnowledgeRepository | null | undefined = data;
const { data: membersData, isLoading: membersLoading } = useQuery<Knowledge[]>({
queryKey: repositoryMembersKey(repositoryId ?? ""),
queryFn: () => api.listKnowledge(repositoryId as string),
enabled: !!repositoryId,
});
const members: Knowledge[] = membersData ?? [];
const { data: statsData, isLoading: statsLoading } = useQuery<RepositoryStatsDetail | null>({
queryKey: repositoryStatsKey(repositoryId ?? ""),
queryFn: () => api.repositoryStats(repositoryId as string),
enabled: !!repositoryId,
staleTime: 60_000,
});
const detail: RepositoryStatsDetail | null | undefined = statsData;
const figures = useMemo(
() => new Map<string, KnowledgeStats>((detail?.sources ?? []).map((s) => [s.knowledge_id, s])),
[detail],
);
// A built-in repository (CHAINR Bot's guide, News): readable by everyone,
// changeable by no one. The API refuses every write, so none is offered —
// its sources still open, read-only, in the knowledge viewer.
const builtIn = isSystemManaged(repository);
// Nor one the viewer may not change here: what a project inherits, or a
// level that does not allow it (svc-core says, `can_change`).
const mayChange = !!repository && !builtIn && repository.can_change !== false;
// A recommendation's "Make it Temporal" opens the details here with the
// kind filled in (`?category=`); nothing changes until Save.
const [params, setParams] = useSearchParams();
const suggested = params.get("category");
const suggestedCategory = isKnowledgeCategory(suggested) ? suggested : null;
useEffect(() => {
if (suggestedCategory && mayChange) setEditing(true);
}, [suggestedCategory, mayChange]);
const closeEditing = () => {
setEditing(false);
if (params.has("category")) {
const next = new URLSearchParams(params);
next.delete("category");
setParams(next, { replace: true });
}
};
const { data: allKnowledgeData } = useQuery({
queryKey: [QUERY_KEYS.GET.KNOWLEDGE],
queryFn: () => getApiHandler().knowledge_router.list(undefined),
enabled: mayChange,
});
// Every repository, to offer only the sources that may join this one: one
// already in a repository of another kind would be refused.
const { data: allRepositoriesData } = useQuery<KnowledgeRepository[]>({
queryKey: [QUERY_KEYS.GET.REPOSITORIES, INCLUDE_SYSTEM],
queryFn: () => api.list({ includeSystem: true }),
enabled: mayChange,
});
const memberIds = new Set(members.map((kb) => kb.id));
const allKnowledge = (allKnowledgeData as Knowledge[] | null) ?? [];
const held = heldAs(
allRepositoriesData ?? [],
new Set(allKnowledge.filter(isSystemManaged).map((kb) => kb.id)),
);
const available = allKnowledge.filter(
(kb) => !memberIds.has(kb.id) && mayJoin(held, kb.id, repository?.category),
);
/** A source joining or leaving changes the repository's figures, map and
* trust (all under its key), the lists' figures, and the source's own
* "in these repositories". */
const refreshAfterMembership = (knowledgeId: string) =>
Promise.all(
[
repositoryKey(repositoryId as string),
[QUERY_KEYS.GET.REPOSITORIES],
[QUERY_KEYS.GET.KNOWLEDGE],
sourceKey(knowledgeId),
].map((queryKey) => queryClient.invalidateQueries({ queryKey })),
);
const updateMutation = useMutation({
mutationFn: (patch: NewRepository) => api.update(repositoryId as string, patch),
onSuccess: async () => {
closeEditing();
await Promise.all(
[
repositoryKey(repositoryId as string),
[QUERY_KEYS.GET.REPOSITORIES],
[QUERY_KEYS.GET.KNOWLEDGE_RECOMMENDATIONS],
].map((queryKey) =>
queryClient.invalidateQueries({ queryKey }),
),
);
},
});
const deleteMutation = useMutation({
mutationFn: () => api.delete(repositoryId as string),
onSuccess: async () => {
setConfirmingDelete(false);
await queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.REPOSITORIES] });
void navigate(BACK_PATH);
},
});
const addMutation = useMutation({
mutationFn: (knowledgeId: string) => api.addKnowledge(repositoryId as string, knowledgeId),
onSuccess: (_, knowledgeId) => refreshAfterMembership(knowledgeId),
});
const addError = addMutation.error
? errorDetail(addMutation.error, "The source could not be added.")
: null;
const removeMutation = useMutation({
mutationFn: (knowledgeId: string) => api.removeKnowledge(repositoryId as string, knowledgeId),
onSuccess: (_, knowledgeId) => refreshAfterMembership(knowledgeId),
});
const actions = mayChange
? [
<MoveToShared key="move" kind="repository" resource={repository as KnowledgeRepository} />,
<button
key="edit"
type="button"
onClick={() => {
updateMutation.reset();
setEditing(true);
}}
className={`${ACTION} border-gray-200 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700`}
>
<Pencil className="size-3.5" />
Edit
</button>,
<button
key="delete"
type="button"
onClick={() => {
deleteMutation.reset();
setConfirmingDelete(true);
}}
className={`${ACTION} border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/40`}
>
<Trash2 className="size-3.5" />
Delete
</button>,
]
: [];
const overlay = repository ? (
<>
{editing && (
<RepositoryDetailsModal
title="Edit repository"
confirmLabel="Save"
loadingLabel="Saving…"
initial={{
name: repository.name,
description: repository.description ?? "",
icon: repository.icon ?? REPOSITORY_ICON_REGISTRY.fallback,
accent: repository.accent ?? "slate",
category: suggestedCategory ?? knowledgeCategory(repository.category).key,
}}
loading={updateMutation.isPending}
error={
updateMutation.error
? errorDetail(updateMutation.error, "The repository could not be saved.")
: null
}
onClose={closeEditing}
onSubmit={(values) => updateMutation.mutate(values)}
/>
)}
{confirmingDelete && (
<ConfirmDialog
title="Delete this repository?"
icon={Trash2}
destructive
body={
<>
<Strong>{repository.name}</Strong> is deleted, and every agent
granted it stops reading through it. Its sources are kept, with
everything they hold. Its edit history is kept.
</>
}
confirmLabel="Delete repository"
loadingLabel="Deleting…"
loading={deleteMutation.isPending}
error={
deleteMutation.error
? errorDetail(deleteMutation.error, "Could not delete the repository.")
: null
}
onConfirm={() => deleteMutation.mutate()}
onCancel={() => setConfirmingDelete(false)}
/>
)}
</>
) : null;
return (
<DetailPage<KnowledgeRepository>
resource={repository}
loading={!!repositoryId && isLoading}
error={error}
title={
repository ? (
<>
{repository.name}
{builtIn && <BuiltInBadge className="ml-2 align-middle" />}
<span className="ml-2 align-middle">
<CategoryBadge category={repository.category} />
</span>
</>
) : undefined
}
icon={
<AppearanceSwatch
registry={REPOSITORY_ICON_REGISTRY}
icon={repository?.icon}
accent={repository?.accent}
size="lg"
/>
}
description={repository?.description || undefined}
back={BACK_PATH}
label="repository"
actions={actions}
resourceId={repositoryId}
history={{
source: api,
queryKey: QUERY_KEYS.GET.REPOSITORY_HISTORY,
fieldLabels: {
name: "Name",
description: "Description",
icon: "Icon",
accent: "Colour",
category: "Kind of knowledge",
knowledge: "Sources",
},
}}
overlay={overlay}
>
{(repo) => (
<>
{builtIn && (
<p
role="note"
className="text-xs leading-relaxed text-indigo-900 dark:text-indigo-200 rounded-xl border border-indigo-200 dark:border-indigo-800/70 bg-indigo-50/70 dark:bg-indigo-950/30 px-4 py-3"
>
Built in to CHAIN-R: maintained by the platform and updated with
its releases, so it cannot be edited or deleted. Switch it on for
any of your own agents on the Agents tab.
</p>
)}
{addError && (
<p
role="alert"
className="text-sm text-red-600 dark:text-red-400 rounded-xl border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 px-4 py-2"
>
{addError}
</p>
)}
<DetailTabs
tabs={[
{ key: "overview", label: "Overview", Icon: LayoutDashboard },
{ key: "sources", label: "Sources", Icon: BookCopy, count: members.length },
{ key: "usage", label: "Usage", Icon: BarChart3 },
{ key: "agents", label: "Agents", Icon: Bot },
]}
active={tab}
onChange={setTab}
/>
{tab === "overview" && (
<RepositoryOverview
repositoryId={repo.id}
stats={detail?.repository ?? null}
figures={figures}
members={members}
loading={statsLoading}
onAdd={mayChange ? (id) => addMutation.mutate(id) : undefined}
adding={addMutation.isPending}
/>
)}
{tab === "sources" && (
<RepositorySources
members={members}
loading={membersLoading}
figures={figures}
available={mayChange ? available : undefined}
onAdd={mayChange ? (id) => addMutation.mutate(id) : undefined}
onRemove={mayChange ? (id) => removeMutation.mutate(id) : undefined}
removing={removeMutation.isPending}
/>
)}
{tab === "usage" && (
<UsagePanel
queryKey={[...repositoryKey(repo.id), "usage"]}
fetch={(days) => api.usage(repo.id, days)}
costSource="knowledge_repository"
sourceId={repo.id}
noun="repository"
/>
)}
{tab === "agents" && <RepositoryAgentsCard repositoryId={repo.id} builtIn={builtIn} />}
</>
)}
</DetailPage>
);
};
export default RepositoryViewer;
|