All files / src/apps/user/pages/agents/setup/steps ReviewKnowledgeStep.tsx

65% Statements 26/40
81.57% Branches 31/38
56.66% Functions 17/30
62.16% Lines 23/37

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                                                                                                      2x                                                                   2x                                                                   13x       13x     13x       13x           13x 13x   13x       13x 13x   13x 13x     13x                                       2x                                                                                 13x                                                     1x                 39x                                                                           1x                   13x                                                                                                         65x                                   1x                                               13x                                                                                  
import { ProposedKnowledgeStub, ProposedRepository } from "@/objects/AgentSetup";
import DiscoveryProgress from "@/apps/user/pages/knowledge/DiscoveryProgress";
import {
  LinkDraft,
  PublisherTermsNote,
  SourceLinksEditor,
  takesLinks,
  toggledLink,
  withLink,
} from "@/apps/user/pages/knowledge/sourceLinks";
import { CategoryBadge } from "@/apps/user/pages/knowledge/cardParts";
import {
  CATEGORY_KEYS,
  KNOWLEDGE_CATEGORIES,
  KnowledgeCategoryKey,
  knowledgeCategory,
} from "@/apps/user/pages/knowledge/categories";
import { AppearanceSwatch } from "@/components/appearance/AppearancePicker";
import { REPOSITORY_ICON_REGISTRY } from "@/components/appearance/icons";
import { BuiltInBadge } from "@/components/badge/BuiltInBadge";
import { isSystemManaged } from "@/objects/Doc";
import {
  Knowledge,
  KnowledgeRepository,
  WebCrawlScope,
  WebRefreshCadence,
} from "@/objects/Knowledge";
import { GenerationProgress, GenerationStage } from "@/objects/KnowledgeSetup";
import {
  AlertCircle,
  AlertTriangle,
  BookOpen,
  FolderOpen,
  Search,
  Sparkles,
} from "lucide-react";
import React from "react";
import {
  SOURCE_TYPE_KEYS,
  sourceType,
} from "@/apps/user/pages/knowledge/sourceTypes";
import {
  FieldLabel,
  SectionCard,
  ToggleRow,
  inputBase,
} from "../primitives";
 
/** What keeping a built-in costs, by its kind: written methods fetch
 *  nothing; a publisher's pages are read weekly and its feeds hourly, at the
 *  platform's cost, only while an agent uses them. */
const BUILT_IN_UPKEEP: Record<KnowledgeCategoryKey, string> = {
  domain:
    "Kept by CHAIN-R: nothing to set up. Granting it starts its weekly reading of its publishers' pages, at the platform's cost, while an agent uses it.",
  temporal:
    "Kept by CHAIN-R: nothing to set up. Granting it starts its hourly reading of its publishers' feeds, at the platform's cost, while an agent uses it.",
  reasoning:
    "Written by CHAIN-R: nothing to set up, and nothing is fetched to keep it.",
};
 
/** A proposed source's links as the step edits them. */
export interface KnowledgeLinks {
  links: LinkDraft[];
  scope: WebCrawlScope;
  refresh: WebRefreshCadence;
}
 
/** Where the search for the proposed sources' links is. */
export interface LinkSearch {
  running: boolean;
  stage: GenerationStage;
  progress: GenerationProgress;
  error: string | null;
  warnings: string[];
}
 
// Agents only ever integrate whole repositories — never individual sources —
// so context stays grouped, deduplicated, and reusable across agents. This
// step therefore surfaces repositories as the primary attachable unit; any
// individual source (existing or newly proposed) is only ever created or
// granted as a member of one.
//
// A proposed website or file source comes with links: a search started when
// the proposal landed (svc-core `source_discovery`) finds pages to crawl and
// documents to import for it, each one a search found and svc-core checked.
const ReviewKnowledgeStep: React.FC<{
  existingKnowledge: Knowledge[];
  proposedKnowledge: ProposedKnowledgeStub[];
  existingRepositories: KnowledgeRepository[];
  proposedRepositories: ProposedRepository[];
  includedProposed: Set<number>;
  includedExistingRepositories: Set<string>;
  includedProposedRepositories: Set<number>;
  onToggleProposed: (index: number) => void;
  onToggleExistingRepository: (id: string) => void;
  onToggleProposedRepository: (index: number) => void;
  onEditProposedRepository: (index: number, repo: ProposedRepository) => void;
  onEditProposed: (index: number, stub: ProposedKnowledgeStub) => void;
  knowledgeLinks: (index: number) => KnowledgeLinks;
  search: LinkSearch;
  onEditLinks: (index: number, change: Partial<KnowledgeLinks>) => void;
}> = ({
  existingKnowledge,
  proposedKnowledge,
  existingRepositories,
  proposedRepositories,
  includedProposed,
  includedExistingRepositories,
  includedProposedRepositories,
  onToggleProposed,
  onToggleExistingRepository,
  onToggleProposedRepository,
  onEditProposedRepository,
  onEditProposed,
  knowledgeLinks,
  search,
  onEditLinks,
}) => {
  const nothingSelected =
    proposedKnowledge.length === 0 &&
    existingRepositories.length === 0 &&
    proposedRepositories.length === 0;
 
  const knowledgeNameById = new Map(
    existingKnowledge.map((kb) => [kb.id, kb.name]),
  );
  const repositoryMemberNames = (repo: ProposedRepository): string[] => [
    ...repo.member_knowledge_ids.map(
      (id) => knowledgeNameById.get(id) ?? `Unknown (${id})`,
    ),
    ...repo.member_proposed_knowledge_names.map((name) => `${name} (new)`),
  ];
 
  // Only a proposed knowledge base referenced as a member of at least one
  // proposed repository will actually be created and granted — a source
  // with no repository has nowhere to attach to.
  const repoMemberNames = new Set(
    proposedRepositories.flatMap((r) => r.member_proposed_knowledge_names),
  );
  const indexedProposed = proposedKnowledge.map((stub, index) => ({
    stub,
    index,
  }));
  const groupedProposed = indexedProposed.filter(({ stub }) =>
    repoMemberNames.has(stub.name),
  );
  const orphanProposed = indexedProposed.filter(
    ({ stub }) => !repoMemberNames.has(stub.name),
  );
 
  return (
    <div className="space-y-4">
      {nothingSelected && (
        <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 px-5 py-8 text-center">
          <BookOpen className="size-5 text-gray-400 dark:text-gray-500 mx-auto mb-2" />
          <p className="text-sm text-gray-500 dark:text-gray-400">
            The AI didn't select or propose any knowledge repositories for
            this use case. You can grant access after the agent is created.
          </p>
        </div>
      )}
 
      {existingRepositories.length > 0 && (
        <SectionCard
          icon={FolderOpen}
          title="Your existing knowledge repositories"
          description="Repositories from your workspace the AI recommends granting to this agent — each expands to its member knowledge bases."
        >
          <div className="space-y-2">
            {existingRepositories.map((repo) => (
              <ToggleRow
                key={repo.id}
                title={repo.name}
                subtitle={repo.description}
                icon={
                  <AppearanceSwatch
                    registry={REPOSITORY_ICON_REGISTRY}
                    icon={repo.icon}
                    accent={repo.accent}
                    size="sm"
                  />
                }
                meta={
                  <>
                    {isSystemManaged(repo) && <BuiltInBadge size="sm" />}
                    <CategoryBadge category={repo.category} />
                  </>
                }
                selected={includedExistingRepositories.has(repo.id)}
                accent="emerald"
                onToggle={() => onToggleExistingRepository(repo.id)}
              >
                {isSystemManaged(repo) && (
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    {BUILT_IN_UPKEEP[knowledgeCategory(repo.category).key]}
                  </p>
                )}
              </ToggleRow>
            ))}
          </div>
        </SectionCard>
      )}
 
      {proposedRepositories.length > 0 && (
        <SectionCard
          icon={Sparkles}
          title="New knowledge repositories to create"
          description="Named collections grouping the knowledge bases below — granted to the agent as a single unit."
        >
          <div className="space-y-2">
            {proposedRepositories.map((repo, index) => (
              <ToggleRow
                key={index}
                title={repo.name}
                subtitle={repo.description}
                icon={
                  <AppearanceSwatch
                    registry={REPOSITORY_ICON_REGISTRY}
                    icon={repo.icon}
                    accent={repo.accent}
                    size="sm"
                  />
                }
                meta={
                  <>
                    <FolderOpen className="size-3" />
                    {repositoryMemberNames(repo).join(", ")}
                  </>
                }
                selected={includedProposedRepositories.has(index)}
                accent="amber"
                onToggle={() => onToggleProposedRepository(index)}
              >
                <label className="mt-2 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
                  Kind
                  <select
                    value={knowledgeCategory(repo.category).key}
                    onChange={(e) =>
                      onEditProposedRepository(index, {
                        ...repo,
                        category: knowledgeCategory(e.target.value).key,
                      })
                    }
                    aria-label={`Kind of knowledge in ${repo.name}`}
                    className="rounded border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 px-1.5 py-0.5 text-xs text-gray-700 dark:text-gray-300"
                  >
                    {CATEGORY_KEYS.map((key) => (
                      <option key={key} value={key}>
                        {KNOWLEDGE_CATEGORIES[key].label}
                      </option>
                    ))}
                  </select>
                  <span className="truncate">
                    {knowledgeCategory(repo.category).use}
                  </span>
                </label>
              </ToggleRow>
            ))}
          </div>
        </SectionCard>
      )}
 
      {groupedProposed.length > 0 && (
        <SectionCard
          icon={Sparkles}
          title="New knowledge bases to create"
          description="Created as members of the repositories above. A website source starts crawling the pages you keep, and a file source imports the documents you keep; any other source is created empty for you to fill."
        >
          {search.running && (
            <div className="rounded-lg border border-gray-200 dark:border-gray-700 px-4 py-3">
              <p className="flex items-center gap-1.5 text-xs font-medium text-gray-600 dark:text-gray-300 mb-2">
                <Search className="size-3.5" />
                Finding pages and documents for these sources…
              </p>
              <DiscoveryProgress
                stage={search.stage}
                progress={search.progress}
                lastStep="Matching them to your sources"
              />
            </div>
          )}
          {!search.running && (search.error || search.warnings.length > 0) && (
            <div className="px-4 py-3 rounded-lg bg-amber-50 dark:bg-amber-950/40 border border-amber-200 dark:border-amber-800 text-amber-800 dark:text-amber-300 text-xs space-y-1">
              {[...(search.error ? [search.error] : []), ...search.warnings].map(
                (line) => (
                  <div key={line} className="flex items-start gap-2">
                    <AlertCircle className="size-3.5 shrink-0 mt-0.5" />
                    {line}
                  </div>
                ),
              )}
            </div>
          )}
          <div className="space-y-2">
            {groupedProposed.map(({ stub, index }) => (
              <ToggleRow
                key={index}
                title={stub.name}
                selected={includedProposed.has(index)}
                accent="amber"
                onToggle={() => onToggleProposed(index)}
              >
                {includedProposed.has(index) && (
                  <div className="mt-3 space-y-3">
                    <div>
                      <FieldLabel label="Name" required />
                      <input
                        type="text"
                        value={stub.name}
                        onChange={(e) =>
                          onEditProposed(index, {
                            ...stub,
                            name: e.target.value,
                          })
                        }
                        className={inputBase}
                      />
                    </div>
                    <div>
                      <FieldLabel
                        label="Description"
                        description="What content should live in this knowledge base."
                      />
                      <textarea
                        value={stub.description}
                        onChange={(e) =>
                          onEditProposed(index, {
                            ...stub,
                            description: e.target.value,
                          })
                        }
                        rows={2}
                        className={inputBase + " resize-none"}
                      />
                    </div>
                    <div>
                      <FieldLabel label="Source type" />
                      <select
                        value={stub.source_type}
                        onChange={(e) =>
                          onEditProposed(index, {
                            ...stub,
                            source_type: e.target.value,
                          })
                        }
                        className={inputBase}
                      >
                        {SOURCE_TYPE_KEYS.map((value) => (
                          <option key={value} value={value}>
                            {sourceType(value).label}
                          </option>
                        ))}
                      </select>
                    </div>
                    {takesLinks(stub.source_type) &&
                      (search.running ? (
                        <p className="text-xs text-gray-400 dark:text-gray-500">
                          Links are being found for this source…
                        </p>
                      ) : (
                        <SourceLinksEditor
                          sourceType={stub.source_type}
                          links={knowledgeLinks(index).links}
                          scope={knowledgeLinks(index).scope}
                          refresh={knowledgeLinks(index).refresh}
                          onToggle={(url) =>
                            onEditLinks(index, {
                              links: toggledLink(knowledgeLinks(index).links, url),
                            })
                          }
                          onAdd={(link) =>
                            onEditLinks(index, {
                              links: withLink(knowledgeLinks(index).links, link),
                            })
                          }
                          onScope={(scope) => onEditLinks(index, { scope })}
                          onRefresh={(refresh) => onEditLinks(index, { refresh })}
                          emptyNote={
                            search.error
                              ? "Add links by hand, or after creating."
                              : "Nothing the search found fitted this source."
                          }
                        />
                      ))}
                  </div>
                )}
              </ToggleRow>
            ))}
          </div>
          {groupedProposed.some(({ index }) =>
            knowledgeLinks(index).links.some((l) => l.included),
          ) && <PublisherTermsNote />}
        </SectionCard>
      )}
 
      {(orphanProposed.length > 0 || existingKnowledge.length > 0) && (
        <SectionCard
          icon={AlertTriangle}
          title="Not attachable directly"
          description="Agents only integrate repositories, not individual sources — these aren't included above. Group them into a repository first if you want this agent to have access."
        >
          <div className="space-y-1.5">
            {orphanProposed.map(({ stub }) => (
              <div
                key={stub.name}
                className="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400"
              >
                <Sparkles className="size-3 shrink-0 text-gray-400" />
                {stub.name} <span className="text-gray-400">(new, ungrouped)</span>
              </div>
            ))}
            {existingKnowledge.map((kb) => {
              const meta = sourceType(kb.source_type);
              return (
                <div
                  key={kb.id}
                  className="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400"
                >
                  <meta.Icon className="size-3 shrink-0 text-gray-400" />
                  {kb.name}
                </div>
              );
            })}
          </div>
        </SectionCard>
      )}
    </div>
  );
};
 
export default ReviewKnowledgeStep;