All files / src/apps/user/pages/agents SystemAgent.tsx

92.3% Statements 60/65
88% Branches 44/50
82.75% Functions 24/29
91.8% Lines 56/61

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                                                                                                                                          2x                 2x     20x 20x   10x   20x   10x   20x   20x 10x                                               10x           2x 10x 10x   10x   10x   10x                             10x                                     2x 10x 10x 9x         10x                               27x                     27x                                                           2x                     2x 25x 25x 25x 25x 25x   25x   11x         25x   20x   9x         25x 25x   25x 25x         25x 1x   1x 1x       25x                 1x                                               26x                                                                                     2x                                                       1x                               2x       10x 10x       10x   10x                                                                                             10x                                                                                                                                                    
import BuiltInBadge from "@/components/badge/BuiltInBadge";
import { AppearanceSwatch } from "@/components/appearance/AppearancePicker";
import {
  AGENT_ICON_REGISTRY,
  REPOSITORY_ICON_REGISTRY,
} from "@/components/appearance/icons";
import {
  ConfirmDialog,
  CopyButton,
  DetailPage,
  encodeResourceId,
  MEMORY_STATE,
  MetaGrid,
  MetaItem,
  SectionCard,
  SkeletonLines,
  StatusBadge,
} from "@/components/detail";
import {
  MEMORY_KIND_LABELS,
  memoryHeadline,
  memoryKind,
  memoryState,
  memoryStateLabel,
} from "@/util/agentMemory";
import { Agent, AgentMemory, AgentRepository } from "@/objects/Agent";
import { Knowledge, KnowledgeRepository } from "@/objects/Knowledge";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { parseServerDate } from "@/util/time";
import { groupedByKind, platformWebSources } from "@/util/platformWebSources";
import { newRuleHref } from "../rules/links";
import SourceDocumentList from "../knowledge/SourceDocumentList";
import { BotBenchmark } from "../evaluation/Benchmark";
import EvaluateAgentModal from "../evaluation/EvaluateAgentModal";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  BadgeCheck,
  BookOpen,
  Brain,
  BotMessageSquare,
  ChevronDown,
  ChevronUp,
  Cpu,
  FileText,
  FlaskConical,
  Gauge,
  Globe,
  Lock,
  ShieldCheck,
  Trash2,
} from "lucide-react";
import React, { useMemo, useState } from "react";
import { Link } from "react-router-dom";
 
/**
 * A platform-managed agent's page — CHAINR Bot.
 *
 * Deliberately not the ordinary agent page with its controls hidden. That
 * page is an editor: inline fields, grant pickers, a delete button, tabs of
 * things to attach. Every one of those would fail against a system agent
 * (the API refuses writes with 403), and a page of disabled controls reads
 * as "you lack permission" rather than "this is the platform's". This one is
 * a description instead: what the bot is, what it answers from, what it
 * remembers about *you* — the one thing here the user does control — and
 * its release history.
 */
 
const HISTORY_FIELD_LABELS = {
  name: "Name",
  description: "Description",
  system_prompt: "Instructions",
  ai_model_id: "Model",
};
 
// ─── Knowledge ────────────────────────────────────────────────────────────────
 
const GrantedRepository: React.FC<{ repositoryId: string }> = ({
  repositoryId,
}) => {
  const { getApiHandler } = useApiHandler();
  const { data: repository } = useQuery<KnowledgeRepository | null>({
    queryKey: [QUERY_KEYS.GET.REPOSITORY_BY_ID, repositoryId],
    queryFn: () => getApiHandler().repository_router.getById(repositoryId),
  });
  const { data: sourceData } = useQuery<Knowledge[]>({
    queryKey: [QUERY_KEYS.GET.REPOSITORY_BY_ID, repositoryId, "knowledge"],
    queryFn: () => getApiHandler().repository_router.listKnowledge(repositoryId),
  });
  const sources: Knowledge[] = sourceData ?? [];
 
  if (!repository) return <SkeletonLines count={2} />;
  return (
    <div className="flex flex-col gap-3">
      <div className="flex items-start gap-3">
        <AppearanceSwatch
          registry={REPOSITORY_ICON_REGISTRY}
          icon={repository.icon}
          accent={repository.accent}
          size="md"
        />
        <div className="min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-sm font-medium text-gray-900 dark:text-gray-100">
              {repository.name}
            </span>
            {repository.is_system && <BuiltInBadge size="sm" />}
          </div>
          {repository.description && (
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
              {repository.description}
            </p>
          )}
        </div>
      </div>
      {sources.map((source) => (
        <SourceDocumentList key={source.id} knowledge={source} />
      ))}
    </div>
  );
};
 
const KnowledgeSection: React.FC<{ agentId: string }> = ({ agentId }) => {
  const { getApiHandler } = useApiHandler();
  const { data, isLoading } = useQuery<AgentRepository[]>({
    queryKey: [QUERY_KEYS.GET.AGENT_REPOSITORIES, agentId],
    queryFn: () => getApiHandler().agent_router.listAgentRepositories(agentId),
  });
  const grants: AgentRepository[] = data ?? [];
 
  return (
    <SectionCard
      icon={BookOpen}
      title="What it answers from"
      subtitle="Read-only knowledge maintained by CHAIN-R. It cannot see your own documents."
    >
      {isLoading ? (
        <SkeletonLines count={3} />
      ) : grants.length === 0 ? (
        <p className="text-xs text-gray-400 dark:text-gray-500">
          No knowledge attached.
        </p>
      ) : (
        <div className="flex flex-col gap-5">
          {grants.map((grant) => (
            <GrantedRepository
              key={grant.repository_id}
              repositoryId={grant.repository_id}
            />
          ))}
        </div>
      )}
    </SectionCard>
  );
};
 
// ─── Web sources ──────────────────────────────────────────────────────────────
 
/**
 * The publishers the bot's web searches put first (`config.web_sources`) and
 * why each kind is there. Put first, never a limit — and the workspace's own
 * Tools rules replace them, which **Change it** starts: the builder on
 * built-in Tools rule #13 (the same list), pinned to the bot.
 */
const WebSourcesSection: React.FC<{ bot: Agent }> = ({ bot }) => {
  const web = platformWebSources(bot.config);
  if (!web) return null;
  const change = newRuleHref("tools", {
    scope: "agent",
    target: bot.id,
    from: web.rule_template_id ?? undefined,
  });
  return (
    <SectionCard
      icon={Globe}
      title="Where it looks things up"
      subtitle="Publishers its web searches put first: a starting point, never a limit."
      action={
        <Link
          to={change}
          className="text-xs font-medium text-gray-700 dark:text-gray-200 hover:underline"
        >
          Change it
        </Link>
      }
    >
      <div className="flex flex-col gap-4">
        {groupedByKind(web).map(({ kind, sources }) => (
          <section key={kind.kind} aria-label={kind.label}>
            <h4 className="text-xs font-semibold text-gray-800 dark:text-gray-100">
              {kind.label}
            </h4>
            {kind.criteria && (
              <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">
                {kind.criteria}
              </p>
            )}
            <ul className="mt-2 flex flex-wrap gap-1.5">
              {sources.map((source) => (
                <li
                  key={source.domain}
                  className="inline-flex items-baseline gap-1.5 rounded-md border border-gray-200 dark:border-gray-700 px-2 py-1 text-xs"
                >
                  <span className="text-gray-800 dark:text-gray-100">
                    {source.publisher || source.domain}
                  </span>
                  <span className="font-mono text-[11px] text-gray-500 dark:text-gray-400">
                    {source.domain}
                  </span>
                </li>
              ))}
            </ul>
          </section>
        ))}
        <p className="text-xs leading-relaxed text-gray-500 dark:text-gray-400">
          Every other source stays usable. Your workspace&apos;s Tools rules come
          first: a rule covering {bot.name} that puts sources first, or allows
          only some, replaces this list, and a site your rules block is never
          used.
        </p>
      </div>
    </SectionCard>
  );
};
 
// ─── Memory ───────────────────────────────────────────────────────────────────
 
/** How many memories show before "Show all": enough to see what it keeps,
 *  few enough that the sections below stay within reach. */
const MEMORY_PREVIEW = 5;
 
/**
 * The user's own memories with the bot. The API narrows every memory route
 * to the caller for a system agent, so this lists — and clears — only what
 * the bot remembers about the person looking at it.
 *
 * Memories accrue with every conversation, so the list shows the newest
 * {@link MEMORY_PREVIEW} and the rest on request — and even then scrolls
 * inside the card, so the page below never moves out of reach.
 */
const MemorySection: React.FC<{ agentId: string }> = ({ agentId }) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const [confirmClear, setConfirmClear] = useState(false);
  const [showAll, setShowAll] = useState(false);
  const memoryKey = [QUERY_KEYS.GET.AGENT_MEMORY, agentId];
 
  const { data, isLoading } = useQuery<AgentMemory[]>({
    queryKey: memoryKey,
    queryFn: () => getApiHandler().agent_router.listAgentMemory(agentId),
  });
  // Newest first. The API lists oldest first — the agent page's memory
  // graph draws them as a chain in that order — but a preview should be
  // what the bot noted most recently.
  const memories: AgentMemory[] = useMemo(
    () =>
      [...(data ?? [])].sort(
        (a, b) =>
          parseServerDate(b.created_at).getTime() -
          parseServerDate(a.created_at).getTime(),
      ),
    [data],
  );
  const shown = showAll ? memories : memories.slice(0, MEMORY_PREVIEW);
  const more = memories.length - MEMORY_PREVIEW;
 
  const refresh = () => queryClient.invalidateQueries({ queryKey: memoryKey });
  const deleteOne = useMutation({
    mutationFn: (memoryId: string) =>
      getApiHandler().agent_router.deleteAgentMemoryItem(agentId, memoryId),
    onSuccess: refresh,
  });
  const clearAll = useMutation({
    mutationFn: () => getApiHandler().agent_router.clearAgentMemory(agentId),
    onSuccess: () => {
      setConfirmClear(false);
      refresh();
    },
  });
 
  return (
    <SectionCard
      icon={Brain}
      title="What it remembers about you"
      subtitle="Private to you. Clearing it never affects anyone else."
      action={
        memories.length > 0 ? (
          <button
            type="button"
            onClick={() => setConfirmClear(true)}
            className="text-xs font-medium text-red-500 dark:text-red-400 hover:underline"
          >
            Clear all
          </button>
        ) : undefined
      }
    >
      {isLoading ? (
        <SkeletonLines count={2} />
      ) : memories.length === 0 ? (
        <p className="text-xs text-gray-400 dark:text-gray-500">
          Nothing yet. CHAINR Bot keeps short notes of your conversations, and
          what you tell it about yourself and how you like to be answered, so
          it can pick up where you left off.
        </p>
      ) : (
        <>
          <ul
            className={`flex flex-col divide-y divide-gray-100 dark:divide-gray-700/60 ${
              showAll ? "max-h-96 overflow-y-auto pr-1" : ""
            }`}
          >
            {shown.map((memory) => (
              <li key={memory.id} className="flex items-start gap-3 py-2">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-1 mb-0.5">
                    <span className="text-[10px] font-semibold uppercase tracking-wide text-violet-600 dark:text-violet-400">
                      {MEMORY_KIND_LABELS[memoryKind(memory)]}
                    </span>
                    {memoryStateLabel(memory) && (
                      <StatusBadge
                        status={memoryState(memory)}
                        scale={MEMORY_STATE}
                        label={memoryStateLabel(memory)}
                      />
                    )}
                  </div>
                  <p className="text-xs text-gray-700 dark:text-gray-300 leading-relaxed">
                    {memoryKind(memory) === "episode"
                      ? memory.content
                      : memoryHeadline(memory)}
                  </p>
                  {memory.evidence && (
                    <p className="text-[11px] text-gray-400 dark:text-gray-500 italic mt-0.5">
                      You said: “{memory.evidence}”
                    </p>
                  )}
                </div>
                <span className="shrink-0 text-[10px] text-gray-400 dark:text-gray-500 mt-0.5">
                  {parseServerDate(memory.created_at).toLocaleDateString()}
                </span>
                <button
                  type="button"
                  aria-label="Forget this"
                  title="Forget this"
                  onClick={() => deleteOne.mutate(memory.id)}
                  className="shrink-0 text-gray-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 transition-colors"
                >
                  <Trash2 className="size-3.5" />
                </button>
              </li>
            ))}
          </ul>
          {more > 0 && (
            <button
              type="button"
              onClick={() => setShowAll((all) => !all)}
              aria-expanded={showAll}
              className="mt-2 inline-flex items-center gap-1 p-0 border-0 bg-transparent text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 transition-colors"
            >
              {showAll ? (
                <>
                  <ChevronUp className="size-3.5" aria-hidden="true" />
                  Show fewer
                </>
              ) : (
                <>
                  <ChevronDown className="size-3.5" aria-hidden="true" />
                  Show all {memories.length}
                </>
              )}
            </button>
          )}
        </>
      )}
      {confirmClear && (
        <ConfirmDialog
          title="Clear your memories with CHAINR Bot?"
          body="It will forget what it has noted from your conversations. Your conversations themselves are kept."
          icon={Trash2}
          confirmLabel="Clear"
          loadingLabel="Clearing…"
          destructive
          loading={clearAll.isPending}
          onConfirm={() => clearAll.mutate()}
          onCancel={() => setConfirmClear(false)}
        />
      )}
    </SectionCard>
  );
};
 
// ─── Page ─────────────────────────────────────────────────────────────────────
 
export interface SystemAgentViewerProps {
  agent: Agent;
  /** `?version=` from a link stamped with the revision that answered. */
  initialVersion?: number | null;
}
 
const SystemAgentViewer: React.FC<SystemAgentViewerProps> = ({
  agent,
  initialVersion,
}) => {
  const { getApiHandler } = useApiHandler();
  const chatHref = APP_ROUTES.USER.INFERENCE.AGENTS.chat.replace(
    ROUTE_PARAMS.AGENT.id,
    encodeResourceId(agent.id),
  );
  const [evaluating, setEvaluating] = useState(false);
 
  return (
    <DetailPage<Agent>
      resource={agent}
      resourceId={agent.id}
      label="agent"
      back={APP_ROUTES.USER.INFERENCE.agents}
      title={
        <span className="inline-flex items-center gap-2 flex-wrap">
          {agent.name}
          <BuiltInBadge />
        </span>
      }
      icon={
        <AppearanceSwatch
          registry={AGENT_ICON_REGISTRY}
          icon={agent.icon}
          accent={agent.accent}
          size="xl"
        />
      }
      actions={[
        <Link
          key="chat"
          to={chatHref}
          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>,
        <button
          key="evaluate"
          type="button"
          onClick={() => setEvaluating(true)}
          className="flex items-center gap-2 px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
        >
          <FlaskConical className="size-4" />
          Evaluate
        </button>,
      ]}
      history={{
        source: getApiHandler().agent_router,
        queryKey: QUERY_KEYS.GET.AGENT_HISTORY,
        initialVersion,
        fieldLabels: HISTORY_FIELD_LABELS,
      }}
    >
      {(bot) => (
        <div className="flex flex-col gap-5">
          <div
            role="note"
            className="flex items-start gap-3 rounded-xl border border-indigo-200 dark:border-indigo-800/70 bg-indigo-50/70 dark:bg-indigo-950/30 px-4 py-3"
          >
            <ShieldCheck className="size-4 mt-0.5 shrink-0 text-indigo-500 dark:text-indigo-400" />
            <div className="text-xs leading-relaxed text-indigo-900 dark:text-indigo-200">
              <p className="font-semibold">Managed by CHAIN-R</p>
              <p className="mt-0.5">
                {bot.name} is available to every user and cannot be edited —
                it changes only with platform releases, each recorded in the
                history below. Your conversations and memories with it are
                private to you. For an agent that answers from your own
                documents and tools,{" "}
                <Link
                  to={APP_ROUTES.USER.INFERENCE.AGENTS.new}
                  className="font-medium underline underline-offset-2"
                >
                  build your own
                </Link>
                .
              </p>
            </div>
          </div>
 
          <SectionCard icon={BadgeCheck} title="About">
            {bot.description && (
              <p className="text-sm text-gray-600 dark:text-gray-300 mb-4">
                {bot.description}
              </p>
            )}
            <MetaGrid columns={3}>
              <MetaItem icon={Cpu} label="Model" value="Deployment default" />
              <MetaItem icon={Lock} label="Editable" value="No — built-in" />
              <MetaItem icon={ShieldCheck} label="Maintained by" value="CHAIN-R" />
            </MetaGrid>
          </SectionCard>
 
          <SectionCard
            icon={FileText}
            title="Instructions"
            subtitle="The system prompt it runs with."
            action={<CopyButton value={bot.system_prompt} label="Copy" />}
          >
            <pre className="whitespace-pre-wrap break-words font-mono text-xs leading-relaxed text-gray-600 dark:text-gray-300 max-h-80 overflow-y-auto">
              {bot.system_prompt}
            </pre>
          </SectionCard>
 
          <SectionCard
            icon={Gauge}
            title="Platform benchmark"
            subtitle="Scored by CHAIN-R on every gold dataset at most once a month, on the release then live, beside each maker's strongest model."
          >
            <BotBenchmark />
          </SectionCard>
 
          <KnowledgeSection agentId={bot.id} />
          <WebSourcesSection bot={bot} />
          <MemorySection agentId={bot.id} />
          {evaluating && (
            <EvaluateAgentModal
              agentId={bot.id}
              agentName={bot.name}
              onClose={() => setEvaluating(false)}
            />
          )}
        </div>
      )}
    </DetailPage>
  );
};
 
export default SystemAgentViewer;