All files / src/apps/user/pages/knowledge GenerateKnowledgeModal.tsx

83.09% Statements 177/213
81.08% Branches 180/222
70.37% Functions 57/81
83.76% Lines 160/191

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 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184                                                                                                                                                                                                          9x           9x 85x 85x   29x       29x           27x               9x                                     9x       13x   39x         39x                   9x                                   932x 932x 932x 932x     932x 932x 932x     932x     932x     932x 932x 932x   932x     932x 932x 932x 932x     932x 932x     932x 932x 932x   932x 932x   932x   20x   932x   932x     18x     1008x             932x 1x 1x   1x     932x   932x 1x 1x 1x 1x     932x 13x 13x 13x     13x         13x         13x 13x 13x 13x 39x 13x     932x 80x 36x           36x 18x 13x 5x   5x 1x               932x 17x           17x 17x     932x 17x 17x 17x 17x             16x     1x 1x           17x       932x         932x 2x 2x 6x       932x 1x 1x 3x       932x             932x 11x 11x 11x 33x 11x 11x                       10x 10x   20x     10x 29x 10x   1x       11x       932x             932x 1x 1x 1x 1x 1x 1x 1x     932x     932x       932x 932x   932x                                                                                               3x                                       816x                                             2571x                                                                                                   17x                                                             1x                                                                                                                                                                                                                                                                                                                                                                                                                       87x 87x 87x                                                       1x             1x 1x             29x                         1x 1x                                             11x                                                                 1x                             9x           36x                                                                       9x           85x                                                                             9x         27x             27x 81x 81x     27x 27x                                           1x 1x             27x                                       9x             10x 10x 10x                                                                                                                                                              
import {
  FieldLabel,
  SectionCard,
  ToggleRow,
  inputBase,
} from "@/apps/user/pages/agents/setup/primitives";
import {
  clearGeneration,
  loadGeneration,
  saveGeneration,
} from "@/apps/user/pages/knowledge/generationStore";
import {
  formatBytes,
  knowledgeHref,
  repositoryHref,
  sourceIcon,
} from "@/apps/user/pages/knowledge/util";
import DiscoveryProgress from "@/apps/user/pages/knowledge/DiscoveryProgress";
import { sourceType } from "@/apps/user/pages/knowledge/sourceTypes";
import {
  ACCEPTS,
  DEFAULT_SCOPE,
  LinkDraft,
  PublisherTermsNote,
  SourceLinksEditor,
  draftLinks,
  hostOf,
  keptLinks,
  kindLabel,
  linkError,
  refreshFor,
  runningSearch,
  toggledLink,
  withLink,
} from "@/apps/user/pages/knowledge/sourceLinks";
import CategoryPicker from "@/apps/user/pages/knowledge/CategoryPicker";
import {
  DEFAULT_CATEGORY,
  KNOWLEDGE_CATEGORIES,
  KnowledgeCategoryKey,
  knowledgeCategory,
} from "@/apps/user/pages/knowledge/categories";
import {
  Appearance,
  AppearanceFields,
  AppearanceSwatch,
  appearanceOf,
} from "@/components/appearance/AppearancePicker";
import { REPOSITORY_ICON_REGISTRY } from "@/components/appearance/icons";
import DiffViewer from "@/components/diff/DiffViewer/DiffViewer";
import { useWorkspace } from "@/context/WorkspaceContext";
import { FieldDiff } from "@/objects/History";
import { WebCrawlScope, WebRefreshCadence } from "@/objects/Knowledge";
import {
  Candidate,
  CreateKnowledgeFromConfigResponse,
  GenerationProgress,
  GenerationStage,
  KnowledgeGenerationProposal,
  KnowledgeGenerationStatus,
  NewKnowledgeInput,
} from "@/objects/KnowledgeSetup";
import { Model, isSelectableModel, modelDisplayName } from "@/objects/Model";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertCircle,
  BookCopy,
  Check,
  FolderGit2,
  GitCompare,
  Lightbulb,
  Loader2,
  Search,
  Sparkles,
  X,
} from "lucide-react";
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
 
// A sibling of the skillset and toolkit generative modals (see
// apps/user/pages/skillsets/GenerateSkillsetModal.tsx), scoped to knowledge.
//
// Three things make this one different. It runs in the background: svc-core
// searches the web, checks what it found and designs the sources on it,
// which takes longer than a request may, so the wizard starts a run and
// polls it — and remembers it (generationStore), so closing the modal or
// reloading comes back to it. A website source arrives with the pages it
// would crawl and a file source with the documents it would import, each
// one an address a search found and svc-core checked; the person keeps,
// drops or adds to them. And the repository is optional, so the same wizard
// serves both entry points: from Repositories it groups its output into a
// shelf; from Sources it produces loose sources.
 
type Step = "describe" | "generating" | "review" | "done";
 
/** Which entry point opened the wizard. Only the repository differs. */
export type GenerateKnowledgeMode = "repository" | "sources";
 
/** How often a running generation is asked where it is. */
export const POLL_MS = 2000;
 
 
 
/** What happens to each kind of source once created, or what the person
 *  has to do to make it useful. */
const nextStep = (source: SourceDraft): string => {
  const kept = source.links.filter((l) => l.included).length;
  switch (source.source_type) {
    case "web":
      return kept
        ? "Crawled as soon as it is created, then kept current."
        : "Add the URLs to crawl, here or after creating.";
    case "file":
      return kept
        ? "Its documents are downloaded and indexed once it is created."
        : "Add document links here, or upload documents after creating.";
    case "graph":
      return "Build out its entities and relationships after creating.";
    case "db":
      return "Add the database connection after creating.";
    case "api":
      return "Add the API endpoint after creating.";
    default:
      return "Add its content after creating.";
  }
};
 
const DEFAULT_APPEARANCE: Appearance = {
  icon: REPOSITORY_ICON_REGISTRY.fallback,
  accent: "slate",
};
 
/** A proposed source as the review edits it. */
interface SourceDraft {
  name: string;
  description: string;
  source_type: string;
  /** A website source's pages and feeds, or a file source's documents. */
  links: LinkDraft[];
  scope: WebCrawlScope;
  refresh: WebRefreshCadence;
}
 
/** The proposal's sources as the review edits them. A website source is read
 *  as often as its kind of knowledge needs (`refreshFor`), as svc-core will
 *  hold it to. */
const draftsOf = (
  proposal: KnowledgeGenerationProposal,
  category: KnowledgeCategoryKey,
): SourceDraft[] =>
  proposal.proposed_knowledge.map((source) => {
    const links =
      source.source_type === "web"
        ? (source.pages ?? [])
        : source.source_type === "file"
          ? (source.documents ?? [])
          : [];
    return {
      name: source.name,
      description: source.description,
      source_type: source.source_type,
      links: draftLinks(links),
      scope: source.scope ?? DEFAULT_SCOPE,
      refresh: refreshFor(category, source.refresh),
    };
  });
 
const GenerateKnowledgeModal: React.FC<{
  mode?: GenerateKnowledgeMode;
  /** The kind of knowledge it opens on (an empty section's own button). */
  initialCategory?: KnowledgeCategoryKey;
  /** The caller's own answers whose questions the knowledge is for: a
   *  recommendation's. svc-core describes the knowledge from them, and
   *  anything written here is added. */
  fromTurns?: string[];
  /** Those questions, as the recommendation showed them. */
  fromQuestions?: string[];
  onClose: () => void;
}> = ({
  mode = "repository",
  initialCategory = DEFAULT_CATEGORY,
  fromTurns = [],
  fromQuestions = [],
  onClose,
}) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const { key: workspaceKey } = useWorkspace();
  const wantRepository = mode === "repository";
 
  // A run this tab started and has not finished with is picked up again.
  const [restored] = useState(() => loadGeneration(workspaceKey, mode));
  const [step, setStep] = useState<Step>(restored ? "generating" : "describe");
  const [generationId, setGenerationId] = useState<string | null>(
    restored?.generationId ?? null,
  );
  const [description, setDescription] = useState(restored?.description ?? "");
  // What kind of knowledge it is for: what the search looks for, how its
  // website sources are read, and the repository's kind.
  const [category, setCategory] = useState<KnowledgeCategoryKey>(
    restored?.category ?? initialCategory,
  );
  const [modelId, setModelId] = useState(restored?.modelId ?? "");
  const [generateError, setGenerateError] = useState<string | null>(null);
  const [starting, setStarting] = useState(false);
 
  const [proposal, setProposal] = useState<KnowledgeGenerationProposal | null>(
    null,
  );
  const [name, setName] = useState("");
  const [repositoryDescription, setRepositoryDescription] = useState("");
  const [appearance, setAppearance] = useState<Appearance>(DEFAULT_APPEARANCE);
  const [includedExisting, setIncludedExisting] = useState<Set<string>>(
    new Set(),
  );
  const [sources, setSources] = useState<SourceDraft[]>([]);
  const [includedProposed, setIncludedProposed] = useState<Set<number>>(
    new Set(),
  );
  const [createError, setCreateError] = useState<string | null>(null);
  const [creating, setCreating] = useState(false);
  const [showDiff, setShowDiff] = useState(false);
  const [created, setCreated] =
    useState<CreateKnowledgeFromConfigResponse | null>(null);
  const [createdNames, setCreatedNames] = useState<string[]>([]);
 
  const { data: modelsData } = useQuery<Model[]>({
    queryKey: [QUERY_KEYS.GET.MODELS],
    queryFn: () => getApiHandler().model_router.list() as Promise<Model[]>,
  });
  const models: Model[] = (modelsData ?? []).filter(isSelectableModel);
 
  const { data: run, error: runError } = useQuery<KnowledgeGenerationStatus>({
    queryKey: [QUERY_KEYS.GET.KNOWLEDGE_GENERATION, generationId],
    queryFn: () =>
      getApiHandler().knowledge_router.generationStatus(generationId as string),
    enabled: !!generationId && step === "generating",
    refetchInterval: (query) =>
      query.state.data?.status === "running" || !query.state.data
        ? POLL_MS
        : false,
    retry: false,
    gcTime: 0,
  });
 
  const toggled = <T,>(set: Set<T>, value: T): Set<T> => {
    const next = new Set(set);
    if (next.has(value)) next.delete(value);
    else Enext.add(value);
    return next;
  };
 
  const forget = () => clearGeneration(workspaceKey, mode);
 
  const backToDescribe = (message: string) => {
    forget();
    setGenerationId(null);
    setGenerateError(message);
    setStep("describe");
  };
 
  const review = (result: KnowledgeGenerationProposal) => {
    setProposal(result);
    setName(result.repository_name);
    setRepositoryDescription(result.repository_description);
    // The model's choices are clamped server-side already; `appearanceOf`
    // is the same client-side fallback every stored value goes through.
    setAppearance(
      appearanceOf(REPOSITORY_ICON_REGISTRY, result.icon, result.accent),
    );
    // An existing source only becomes a member if a repository groups it,
    // so default the selection on only where that is possible.
    setIncludedExisting(
      wantRepository
        ? new Set(result.selected_knowledge.map((k) => k.id))
        : new Set(),
    );
    const kind = knowledgeCategory(result.category ?? category).key;
    setCategory(kind);
    const drafts = draftsOf(result, kind);
    setSources(drafts);
    setIncludedProposed(new Set(drafts.map((_, i) => i)));
    setStep("review");
  };
 
  useEffect(() => {
    if (step !== "generating") return;
    Iif (runError) {
      backToDescribe(
        linkError(runError, "The generation could not be found. Try again."),
      );
      return;
    }
    if (!run) return;
    if (run.status === "proposed" && run.proposal) {
      review(run.proposal);
    } else Iif (run.status === "applied") {
      backToDescribe("This generation has already been created.");
    } else if (run.status === "failed") {
      backToDescribe(
        run.error ?? "Could not generate knowledge. Please try again.",
      );
    }
    // `review` and `backToDescribe` only set state.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [run, runError, step]);
 
  const follow = (id: string) => {
    saveGeneration(workspaceKey, mode, {
      generationId: id,
      description: description.trim(),
      modelId,
      category,
    });
    setGenerationId(id);
    setStep("generating");
  };
 
  const handleGenerate = async () => {
    setGenerateError(null);
    setStarting(true);
    try {
      const started = await getApiHandler().knowledge_router.startGeneration({
        problem_description: description.trim(),
        ...(fromTurns.length ? { from_turns: fromTurns } : {}),
        ai_model_id: modelId || null,
        want_repository: wantRepository,
        category,
      });
      follow(started.generation_id);
    } catch (e) {
      // One is already going for this person here: follow that one.
      const running = runningSearch(e);
      if (running) follow(running);
      else
        EsetGenerateError(
          linkError(e, "Could not generate knowledge. Please try again."),
        );
    } finally {
      setStarting(false);
    }
  };
 
  const updateSource = (index: number, change: Partial<SourceDraft>) =>
    setSources((prev) =>
      prev.map((s, i) => (i === index ? { ...s, ...change } : s)),
    );
 
  const addLink = (index: number, link: Candidate) =>
    setSources((prev) =>
      prev.map((s, i) =>
        i === index ? { ...s, links: withLink(s.links, link) } : s,
      ),
    );
 
  const toggleLink = (index: number, url: string) =>
    setSources((prev) =>
      prev.map((s, i) =>
        i === index ? { ...s, links: toggledLink(s.links, url) } : s,
      ),
    );
 
  const inputFor = (source: SourceDraft): NewKnowledgeInput => ({
    name: source.name.trim(),
    description: source.description,
    source_type: source.source_type,
    ...keptLinks(source.source_type, source.links, source.scope, source.refresh),
  });
 
  const handleCreate = async () => {
    Iif (!proposal) return;
    setCreating(true);
    setCreateError(null);
    const included = sources.filter((_, i) => includedProposed.has(i));
    try {
      const result = await getApiHandler().knowledge_router.createFromConfig({
        repository_name: wantRepository ? name.trim() : "",
        repository_description: wantRepository
          ? repositoryDescription.trim()
          : "",
        icon: appearance.icon,
        accent: appearance.accent,
        repository_category: category,
        existing_knowledge_ids: wantRepository ? [...includedExisting] : [],
        new_knowledge: included.map(inputFor),
        generation_id: proposal.generation_id,
      });
      forget();
      await Promise.all(
        [QUERY_KEYS.GET.KNOWLEDGE, QUERY_KEYS.GET.REPOSITORIES].map((key) =>
          queryClient.invalidateQueries({ queryKey: [key] }),
        ),
      );
      setCreated(result);
      setCreatedNames(included.map((s) => s.name.trim()));
      setStep("done");
    } catch (e) {
      setCreateError(
        linkError(e, "Could not create the knowledge. Please try again."),
      );
    } finally {
      setCreating(false);
    }
  };
 
  const discard = () => {
    forget();
    onClose();
  };
 
  /** After creating one kind on a topic, start another on it: the same
   *  description, as a fresh run. */
  const startAgain = (kind: KnowledgeCategoryKey) => {
    forget();
    setCategory(kind);
    setProposal(null);
    setCreated(null);
    setGenerationId(null);
    setGenerateError(null);
    setStep("describe");
  };
 
  const nothingToInclude =
    (proposal?.selected_knowledge.length ?? 0) === 0 && sources.length === 0;
 
  const canCreate = wantRepository
    ? !!name.trim()
    : includedProposed.size > 0;
 
  const used = new Set(sources.flatMap((s) => s.links.map((l) => l.url)));
  const alsoFound = (proposal?.candidates ?? []).filter((c) => !used.has(c.url));
 
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40">
      <div className="w-full max-w-2xl max-h-[90vh] overflow-y-auto rounded-2xl bg-white dark:bg-gray-900 shadow-xl">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 dark:border-gray-700 sticky top-0 bg-white dark:bg-gray-900 z-10">
          <div className="flex items-center gap-2">
            <Sparkles className="size-4 text-violet-500 dark:text-violet-400" />
            <h2 className="text-sm font-semibold text-gray-800 dark:text-gray-200">
              {wantRepository
                ? "Generate a Repository"
                : "Generate Knowledge Sources"}
            </h2>
          </div>
          <button
            onClick={onClose}
            aria-label="Close"
            className="p-1 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
          >
            <X className="size-4" />
          </button>
        </div>
 
        <div className="p-6 space-y-4">
          {step === "describe" && (
            <>
              <SectionCard
                icon={Sparkles}
                title="Describe the knowledge"
                description={
                  wantRepository
                    ? "Explain what your agents need to know — the AI searches for the material, then designs a repository around it, reusing sources you already have and proposing the ones you're missing."
                    : "Explain what your agents need to know — the AI searches for the material and proposes the sources to hold it. Group them into a repository later, or generate from the Repositories tab to do both at once."
                }
              >
                <div>
                  <FieldLabel
                    label="What kind of knowledge?"
                    description="It decides what the search looks for, how often its websites are read, and how agents use it."
                  />
                  <CategoryPicker value={category} onChange={setCategory} compact />
                </div>
                {fromTurns.length > 0 && (
                  <div>
                    <FieldLabel
                      label={`From ${fromTurns.length === 1 ? "your question" : `your ${fromTurns.length} questions`}`}
                      description="The knowledge is described from the questions your agent could not answer, in your words as they were kept."
                    />
                    <ul className="space-y-1 rounded-lg border border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/60 px-3 py-2">
                      {fromQuestions.map((question, n) => (
                        <li key={n} className="text-xs text-gray-700 dark:text-gray-300 line-clamp-1">
                          “{question}”
                        </li>
                      ))}
                      {fromTurns.length > fromQuestions.length && (
                        <li className="text-xs text-gray-400 dark:text-gray-500">
                          and {fromTurns.length - fromQuestions.length} more
                        </li>
                      )}
                    </ul>
                  </div>
                )}
                <div>
                  <FieldLabel
                    label={fromTurns.length ? "Anything else it should cover" : "Knowledge description"}
                    description="The more context you give — the subject, the jurisdiction, the kind of material — the better the sources."
                    required={!fromTurns.length}
                  />
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="e.g. UK and EU AI regulation: the AI Act, the UK's regulator guidance, and the ISO standards for AI management."
                    rows={fromTurns.length ? 3 : 5}
                    className={inputBase + " resize-none"}
                  />
                </div>
                <div className="flex items-start gap-2 px-3 py-2.5 rounded-lg bg-gray-50 dark:bg-gray-800/60 border border-gray-100 dark:border-gray-700">
                  <Search className="size-3.5 shrink-0 mt-0.5 text-gray-400" />
                  <p className="text-xs text-gray-500 dark:text-gray-400 leading-relaxed">
                    The AI searches the web for official pages and documents,
                    and every link it proposes is one the search found and
                    CHAIN-R checked — never an address it made up. You review
                    each link before anything is created. Database and API
                    sources stay empty for you to connect.
                  </p>
                </div>
                <div>
                  <div className="flex items-center gap-1.5 text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">
                    <Lightbulb className="size-3.5" />
                    Need inspiration?
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {KNOWLEDGE_CATEGORIES[category].starters.map((example) => (
                      <button
                        key={example}
                        type="button"
                        onClick={() => setDescription(example)}
                        className="px-3 py-1.5 rounded-full border border-gray-200 dark:border-gray-600 text-xs text-gray-600 dark:text-gray-300 hover:border-gray-300 dark:hover:border-gray-500 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors text-left"
                      >
                        {example}
                      </button>
                    ))}
                  </div>
                </div>
                {models.length > 0 && (
                  <div>
                    <FieldLabel
                      label="Generation model"
                      description="The model used to plan the searches and design the knowledge."
                    />
                    <select
                      value={modelId}
                      onChange={(e) => setModelId(e.target.value)}
                      className={inputBase}
                    >
                      <option value="">Default model</option>
                      {models.map((model) => (
                        <option key={model.id} value={model.id}>
                          {modelDisplayName(model)}
                        </option>
                      ))}
                    </select>
                  </div>
                )}
              </SectionCard>
 
              {generateError && (
                <div className="flex items-center gap-2 px-4 py-3 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 text-sm">
                  <AlertCircle className="size-4 shrink-0" />
                  {generateError}
                </div>
              )}
 
              <div className="flex justify-end gap-2">
                <button
                  type="button"
                  onClick={onClose}
                  className="px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={() => void handleGenerate()}
                  disabled={
                    starting || (!fromTurns.length && description.trim().length < 20)
                  }
                  className="flex items-center gap-1.5 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 disabled:opacity-50 transition-opacity"
                >
                  {starting ? (
                    <Loader2 className="size-4 animate-spin" />
                  ) : (
                    <Sparkles className="size-4" />
                  )}
                  {wantRepository ? "Generate Repository" : "Generate Sources"}
                </button>
              </div>
            </>
          )}
 
          {step === "generating" && (
            <GenerationProgressView
              stage={run?.stage ?? "queued"}
              progress={run?.progress ?? {}}
              description={description}
              onClose={onClose}
            />
          )}
 
          {step === "review" && proposal && (
            <>
              {proposal.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">
                  {proposal.warnings.map((warning) => (
                    <div key={warning} className="flex items-start gap-2">
                      <AlertCircle className="size-3.5 shrink-0 mt-0.5" />
                      {warning}
                    </div>
                  ))}
                </div>
              )}
 
              {wantRepository && (
                <div className="flex justify-end">
                  <button
                    type="button"
                    onClick={() => setShowDiff((v) => !v)}
                    className="flex items-center gap-1.5 text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 transition-colors"
                  >
                    <GitCompare className="size-3.5" />
                    {showDiff ? "Edit fields" : "View as diff"}
                  </button>
                </div>
              )}
 
              {wantRepository &&
                (showDiff ? (
                  <SectionCard
                    icon={GitCompare}
                    title="Proposed Repository"
                    description="A preview of what will be created, in the same git-style diff used to view a repository's later edit history."
                  >
                    <DiffViewer
                      fields={
                        [
                          {
                            field: "name",
                            change_type: "added",
                            old_value: null,
                            new_value: name,
                          },
                          {
                            field: "description",
                            change_type: "added",
                            old_value: null,
                            new_value: repositoryDescription,
                          },
                          {
                            field: "icon",
                            change_type: "added",
                            old_value: null,
                            new_value: appearance.icon,
                          },
                          {
                            field: "accent",
                            change_type: "added",
                            old_value: null,
                            new_value: appearance.accent,
                          },
                        ] as FieldDiff[]
                      }
                      fieldLabels={{
                        name: "Name",
                        description: "Description",
                        icon: "Icon",
                        accent: "Accent",
                      }}
                    />
                    <div className="mt-3 space-y-1 text-xs">
                      <p className="text-green-600 dark:text-green-400">
                        +{includedExisting.size + includedProposed.size} source
                        {includedExisting.size + includedProposed.size === 1
                          ? ""
                          : "s"}{" "}
                        added
                      </p>
                    </div>
                  </SectionCard>
                ) : (
                  <SectionCard icon={FolderGit2} title="Name your repository">
                    <div>
                      <FieldLabel label="Name" required />
                      <input
                        type="text"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        className={inputBase}
                      />
                    </div>
                    <div>
                      <FieldLabel
                        label="Kind of knowledge"
                        description="What you asked for. Its website sources are set up for it."
                      />
                      <CategoryPicker
                        value={category}
                        onChange={(kind) => {
                          setCategory(kind);
                          // A kind's sources are read as often as it needs.
                          setSources((prev) =>
                            prev.map((source) => ({
                              ...source,
                              refresh: refreshFor(kind, source.refresh),
                            })),
                          );
                        }}
                        compact
                        label="Kind of knowledge"
                      />
                    </div>
                    <div>
                      <FieldLabel label="Description" />
                      <textarea
                        value={repositoryDescription}
                        onChange={(e) =>
                          setRepositoryDescription(e.target.value)
                        }
                        rows={2}
                        className={inputBase + " resize-none"}
                      />
                    </div>
                    <div>
                      <FieldLabel
                        label="Appearance"
                        description="Proposed by the AI — change it to anything you prefer."
                      />
                      <div className="flex items-start gap-3">
                        <AppearanceSwatch
                          registry={REPOSITORY_ICON_REGISTRY}
                          icon={appearance.icon}
                          accent={appearance.accent}
                          size="lg"
                        />
                        <div className="flex-1 min-w-0">
                          <AppearanceFields
                            registry={REPOSITORY_ICON_REGISTRY}
                            value={appearance}
                            onChange={setAppearance}
                            labels={false}
                          />
                        </div>
                      </div>
                    </div>
                    {proposal.reasoning && (
                      <p className="text-xs text-gray-400 dark:text-gray-500">
                        {proposal.reasoning}
                      </p>
                    )}
                  </SectionCard>
                ))}
 
              {!wantRepository && proposal.reasoning && (
                <SectionCard icon={Sparkles} title="What the AI designed">
                  <p className="text-xs text-gray-500 dark:text-gray-400 leading-relaxed">
                    {proposal.reasoning}
                  </p>
                </SectionCard>
              )}
 
              {nothingToInclude && (
                <div className="rounded-xl border border-gray-200 dark:border-gray-700 px-5 py-8 text-center">
                  <BookCopy 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">
                    {wantRepository
                      ? "The AI didn't select or propose any sources. You can still create an empty repository and add sources to it afterward."
                      : "The AI didn't propose any sources. Try describing the knowledge in more detail."}
                  </p>
                </div>
              )}
 
              {wantRepository && proposal.selected_knowledge.length > 0 && (
                <SectionCard
                  icon={BookCopy}
                  title="Existing sources"
                  description="Sources already in your workspace the AI recommends grouping here. Untick any you don't want."
                >
                  <div className="space-y-2">
                    {proposal.selected_knowledge.map((kb) => {
                      const Icon = sourceIcon(kb.source_type);
                      return (
                        <ToggleRow
                          key={kb.id}
                          title={kb.name}
                          subtitle={kb.description}
                          icon={
                            <Icon className="size-3.5 shrink-0 text-gray-400" />
                          }
                          meta={sourceType(kb.source_type).label}
                          selected={includedExisting.has(kb.id)}
                          accent="violet"
                          onToggle={() =>
                            setIncludedExisting((prev) => toggled(prev, kb.id))
                          }
                        />
                      );
                    })}
                  </div>
                </SectionCard>
              )}
 
              {sources.length > 0 && (
                <SectionCard
                  icon={Sparkles}
                  title="New sources designed for you"
                  description="Each website source comes with the pages it will crawl and each file source with the documents it will import. Untick a link or a source you don't want, or add your own."
                >
                  <div className="space-y-2">
                    {sources.map((source, index) => {
                      const Icon = sourceIcon(source.source_type);
                      const kept = source.links.filter((l) => l.included);
                      return (
                        <ToggleRow
                          key={index}
                          title={source.name}
                          icon={
                            <Icon className="size-3.5 shrink-0 text-gray-400" />
                          }
                          meta={
                            <>
                              {kept.length > 0 && (
                                <span>
                                  {kept.length}{" "}
                                  {source.source_type === "file"
                                    ? kept.length === 1
                                      ? "document"
                                      : "documents"
                                    : kept.length === 1
                                      ? "page"
                                      : "pages"}{" "}
                                  ·{" "}
                                </span>
                              )}
                              {sourceType(source.source_type).label}
                            </>
                          }
                          selected={includedProposed.has(index)}
                          accent="amber"
                          onToggle={() =>
                            setIncludedProposed((prev) => toggled(prev, index))
                          }
                        >
                          {includedProposed.has(index) && (
                            <SourceFields
                              source={source}
                              onChange={(change) => updateSource(index, change)}
                              onToggleLink={(url) => toggleLink(index, url)}
                              onAddLink={(link) => addLink(index, link)}
                            />
                          )}
                        </ToggleRow>
                      );
                    })}
                  </div>
                  {sources.some((s) => s.links.length > 0) && (
                    <div className="mt-3">
                      <PublisherTermsNote />
                    </div>
                  )}
                </SectionCard>
              )}
 
              {alsoFound.length > 0 && (
                <AlsoFound
                  candidates={alsoFound}
                  sources={sources}
                  onAdd={(index, candidate) => {
                    addLink(index, candidate);
                    setIncludedProposed((prev) => new Set(prev).add(index));
                  }}
                />
              )}
 
              {createError && (
                <div className="flex items-center gap-2 px-4 py-3 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 text-sm">
                  <AlertCircle className="size-4 shrink-0" />
                  {createError}
                </div>
              )}
 
              <div className="flex justify-end gap-2">
                <button
                  type="button"
                  onClick={discard}
                  disabled={creating}
                  className="px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors disabled:opacity-50"
                >
                  Discard
                </button>
                <button
                  type="button"
                  onClick={() => void handleCreate()}
                  disabled={creating || !canCreate}
                  className="flex items-center gap-1.5 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 disabled:opacity-50 transition-opacity"
                >
                  {creating ? (
                    <>
                      <Loader2 className="size-4 animate-spin" />
                      Creating…
                    </>
                  ) : (
                    <>
                      <Check className="size-4" />
                      {wantRepository
                        ? "Create Repository"
                        : `Create ${includedProposed.size} Source${
                            includedProposed.size === 1 ? "" : "s"
                          }`}
                    </>
                  )}
                </button>
              </div>
            </>
          )}
 
          {step === "done" && created && (
            <CreatedPanel
              created={created}
              names={createdNames}
              onClose={onClose}
              // Reference knowledge on a topic is kept current by a temporal
              // repository on the same topic: offered in one step.
              onKeepCurrent={
                category !== "temporal" && created.repository
                  ? () => startAgain("temporal")
                  : undefined
              }
            />
          )}
        </div>
      </div>
    </div>
  );
};
 
// ─── Pieces ──────────────────────────────────────────────────────────────────
 
/** Where a running generation has got to. Closing leaves it running; the
 *  wizard comes back to it when it is opened again. */
const GenerationProgressView: React.FC<{
  stage: GenerationStage;
  progress: GenerationProgress;
  description: string;
  onClose: () => void;
}> = ({ stage, progress, description, onClose }) => {
  return (
    <div className="rounded-xl border border-gray-200 dark:border-gray-700 px-6 py-8">
      <div className="flex items-center gap-3 mb-5">
        <div className="p-2.5 rounded-full bg-violet-100 dark:bg-violet-900/40">
          <Sparkles className="size-5 text-violet-600 dark:text-violet-400" />
        </div>
        <div className="min-w-0">
          <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
            Finding and designing your knowledge…
          </p>
          {description && (
            <p className="text-xs text-gray-400 dark:text-gray-500 truncate">
              {description}
            </p>
          )}
        </div>
      </div>
      <DiscoveryProgress stage={stage} progress={progress} />
      <div className="mt-6 flex items-center justify-between gap-4">
        <p className="text-xs text-gray-400 dark:text-gray-500">
          Usually a minute or two. You can close this — it carries on, and
          opening Generate again comes back to it.
        </p>
        <button
          type="button"
          onClick={onClose}
          className="shrink-0 px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
        >
          Close
        </button>
      </div>
    </div>
  );
};
 
/** A proposed source's editable fields, its links among them. */
const SourceFields: React.FC<{
  source: SourceDraft;
  onChange: (change: Partial<SourceDraft>) => void;
  onToggleLink: (url: string) => void;
  onAddLink: (link: Candidate) => void;
}> = ({ source, onChange, onToggleLink, onAddLink }) => {
  return (
    <div className="mt-3 space-y-3">
      <div>
        <FieldLabel label="Name" required />
        <input
          type="text"
          value={source.name}
          onChange={(e) => onChange({ name: e.target.value })}
          className={inputBase}
        />
      </div>
      <div>
        <FieldLabel label="Description" />
        <textarea
          value={source.description}
          onChange={(e) => onChange({ description: e.target.value })}
          rows={2}
          className={inputBase + " resize-none"}
        />
      </div>
      <SourceLinksEditor
        sourceType={source.source_type}
        links={source.links}
        scope={source.scope}
        refresh={source.refresh}
        onToggle={onToggleLink}
        onAdd={onAddLink}
        onScope={(scope) => onChange({ scope })}
        onRefresh={(refresh) => onChange({ refresh })}
      />
      <p className="text-xs text-gray-400 dark:text-gray-500">
        {nextStep(source)}
      </p>
    </div>
  );
};
 
/** What the search found and checked that no source took — each one can be
 *  added to a source of a type that holds it. */
const AlsoFound: React.FC<{
  candidates: Candidate[];
  sources: SourceDraft[];
  onAdd: (sourceIndex: number, candidate: Candidate) => void;
}> = ({ candidates, sources, onAdd }) => (
  <SectionCard
    icon={Search}
    title="Also found"
    description="Checked by the search but not chosen for a source. Add any that belong."
  >
    <div className="divide-y divide-gray-100 dark:divide-gray-700">
      {candidates.map((candidate) => {
        const targets = sources
          .map((s, i) => ({ s, i }))
          .filter(({ s }) =>
            (ACCEPTS[s.source_type] ?? []).includes(candidate.kind),
          );
        const label = candidate.title || candidate.url;
        return (
          <div key={candidate.url} className="flex items-center gap-3 py-2">
            <div className="min-w-0 flex-1">
              <a
                href={candidate.url}
                target="_blank"
                rel="noopener noreferrer"
                className="block text-xs text-gray-700 dark:text-gray-300 truncate hover:underline"
              >
                {label}
              </a>
              <div className="text-[11px] text-gray-400 dark:text-gray-500 truncate">
                {candidate.host || hostOf(candidate.url)} ·{" "}
                {kindLabel(candidate)}
                {candidate.size_bytes != null &&
                  ` · ${formatBytes(candidate.size_bytes)}`}
              </div>
            </div>
            {targets.length > 0 ? (
              <select
                value=""
                onChange={(e) => {
                  Eif (e.target.value !== "")
                    onAdd(Number(e.target.value), candidate);
                }}
                aria-label={`Add ${label} to a source`}
                className="shrink-0 max-w-[10rem] rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 px-2 py-1 text-xs text-gray-600 dark:text-gray-300"
              >
                <option value="">Add to…</option>
                {targets.map(({ s, i }) => (
                  <option key={i} value={i}>
                    {s.name}
                  </option>
                ))}
              </select>
            ) : (
              <span className="shrink-0 text-[11px] text-gray-400 dark:text-gray-500">
                {candidate.kind === "document"
                  ? "No file source"
                  : "No website source"}
              </span>
            )}
          </div>
        );
      })}
    </div>
  </SectionCard>
);
 
/** What was created, and what is happening to it now. */
const CreatedPanel: React.FC<{
  created: CreateKnowledgeFromConfigResponse;
  names: string[];
  onClose: () => void;
  /** Start a temporal repository on the same topic. */
  onKeepCurrent?: () => void;
}> = ({ created, names, onClose, onKeepCurrent }) => {
  const crawling = created.crawls_started.length;
  const importing = created.imports_queued;
  return (
    <div className="rounded-xl border border-gray-200 dark:border-gray-700 px-6 py-8 space-y-4">
      <div className="flex items-center gap-3">
        <div className="p-2.5 rounded-full bg-emerald-100 dark:bg-emerald-900/40">
          <Check className="size-5 text-emerald-600 dark:text-emerald-400" />
        </div>
        <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
          {created.repository
            ? `Created ${created.repository.name}`
            : `Created ${created.created_knowledge_ids.length} source${
                created.created_knowledge_ids.length === 1 ? "" : "s"
              }`}
        </p>
      </div>
      {(crawling > 0 || importing > 0) && (
        <ul className="space-y-1 text-xs text-gray-500 dark:text-gray-400">
          {crawling > 0 && (
            <li>
              {crawling} website source{crawling === 1 ? " is" : "s are"} being
              crawled.
            </li>
          )}
          {importing > 0 && (
            <li>
              {importing} document{importing === 1 ? " is" : "s are"} being
              imported — each shows as importing until it is indexed.
            </li>
          )}
        </ul>
      )}
      {onKeepCurrent && (
        <div className="flex items-start justify-between gap-3 rounded-lg border border-gray-200 dark:border-gray-700 px-4 py-3">
          <p className="text-xs text-gray-500 dark:text-gray-400">
            Keep it current: a Temporal repository on the same topic holds the
            news and updates, read newest first.
          </p>
          <button
            type="button"
            onClick={onKeepCurrent}
            className="shrink-0 px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            Generate its updates
          </button>
        </div>
      )}
      <div className="flex flex-wrap gap-2">
        {created.repository ? (
          <Link
            to={repositoryHref(created.repository.id)}
            onClick={onClose}
            className="px-3 py-1.5 rounded-lg bg-gray-900 dark:bg-white text-white dark:text-gray-900 text-xs font-medium hover:opacity-80"
          >
            Open the repository
          </Link>
        ) : (
          created.created_knowledge_ids.map((id, i) => (
            <Link
              key={id}
              to={knowledgeHref(id)}
              onClick={onClose}
              className="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"
            >
              {names[i] ?? "Open source"}
            </Link>
          ))
        )}
        <button
          type="button"
          onClick={onClose}
          className="px-3 py-1.5 text-xs text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
        >
          Done
        </button>
      </div>
    </div>
  );
};
 
export default GenerateKnowledgeModal;