All files / src/apps/user/pages/agents/setup GenerativeSetup.tsx

70.18% Statements 186/265
62.8% Branches 152/242
63.41% Functions 78/123
72.65% Lines 178/245

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                                                                                                                                      2x                               2x                 14x   2x                                                                                                               2x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 91x 13x                                         2x     13x                               2x 27x 27x 27x           2x 63x               2x 10x 10x 10x 10x 10x 10x       10x           10x                 2x 1x       2x 2x       2x               2x                                                   2x 25x   25x 25x   25x   25x                     2x 25x   25x 25x   25x                                   2x 20x               2x             2x 865x 865x 865x       865x 865x 865x     865x     865x 865x 865x 865x 865x 865x   865x   865x   17x 864x         865x           865x 1x       865x 833x 88x               865x 1x 1x 1x 1x 1x 1x     865x 13x 13x 13x 13x 13x       13x 13x 13x 13x 13x                       865x 13x 13x 13x 12x           13x 12x 12x 12x 12x                       12x 12x 12x                       865x 865x     12x         921x               865x 52x 12x 10x 2x       1x 1x                             865x         865x 5x 5x 5x   5x 5x   5x 5x 5x   5x                                                     5x               5x       5x               5x 5x                     5x 5x               5x       5x         5x 5x                             5x 5x 5x 5x                   40x       5x                           5x       865x 865x                 6912x 865x   865x           6048x                                                                                                       2x                                                               13x   1x                                                                                                                                                                                                                                                     47x   1x   1x                     1x 1x                                                                                                                                                               20x 20x   20x     20x 20x         20x 20x   20x 20x             20x 20x     5x                   1x                   4x                   43x                                          
import { encodeResourceId } from "@/components/detail";
import { SectionErrorBoundary } from "@/components/ErrorBoundary";
import SubPage from "@/components/page/SubPage/SubPage";
import { useWorkspace } from "@/context/WorkspaceContext";
import {
  AgentGenerationProposal,
  CreateFromConfigRequest,
  GenerationModelInfo,
  NewSkillsetInput,
  NewToolkitInput,
  ProposalAgent,
  ProposedKnowledgeStub,
  ProposedRepository,
  ProposedRule,
  ProposedSkill,
  ProposedSkillsetInfo,
  ProposedToolkitInfo,
  ProposedWorker,
} from "@/objects/AgentSetup";
import {
  DEFAULT_SCOPE,
  draftLinks,
  keptLinks,
  linkError,
  refreshFor,
  runningSearch,
  takesLinks,
  withLink,
} from "@/apps/user/pages/knowledge/sourceLinks";
import {
  Knowledge,
  KnowledgeRepository,
} from "@/objects/Knowledge";
import { FindSourcesStatus } from "@/objects/KnowledgeSetup";
import { MCPServer } from "@/objects/MCPServer";
import { Model } from "@/objects/Model";
import { Skill } from "@/objects/Skill";
import { Skillset } from "@/objects/Skillset";
import { Toolkit } from "@/objects/Toolkit";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertTriangle,
  ArrowLeft,
  ArrowRight,
  History,
  RotateCcw,
} from "lucide-react";
import React, { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import ConfirmStep from "./steps/ConfirmStep";
import DescribeStep from "./steps/DescribeStep";
import GeneratingStep from "./steps/GeneratingStep";
import ReviewIdentityStep from "./steps/ReviewIdentityStep";
import ReviewKnowledgeStep from "./steps/ReviewKnowledgeStep";
import ReviewRulesStep from "./steps/ReviewRulesStep";
import ReviewSkillsStep from "./steps/ReviewSkillsStep";
import ReviewToolkitsStep from "./steps/ReviewToolkitsStep";
import ReviewWorkersStep from "./steps/ReviewWorkersStep";
import { MCP_AVAILABLE } from "@/util/mcp";
import { clearDraft, loadDraft, saveDraft } from "./draftStore";
import { KnowledgeLinks } from "./steps/ReviewKnowledgeStep";
 
/** How often the search for the proposed sources' links is asked where it
 *  is. */
const SEARCH_POLL_MS = 2000;
 
type WizardStep =
  | "describe"
  | "generating"
  | "review-identity"
  | "review-skills"
  | "review-toolkits"
  | "review-workers"
  | "review-knowledge"
  | "review-rules"
  | "confirm";
 
// Toolkits bundle MCP servers, which are not available in this release
// (util/mcp.ts): svc-core proposes none, so their step is not offered.
const REVIEW_STEPS: WizardStep[] = (
  [
    "review-identity",
    "review-skills",
    "review-toolkits",
    "review-workers",
    "review-knowledge",
    "review-rules",
    "confirm",
  ] as WizardStep[]
).filter((s) => MCP_AVAILABLE || s !== "review-toolkits");
 
const STEP_LABELS: Record<WizardStep, string> = {
  describe: "Describe",
  generating: "Describe",
  "review-identity": "Prompt",
  "review-skills": "Skills",
  "review-toolkits": "Toolkits",
  "review-workers": "Workers",
  "review-knowledge": "Knowledge",
  "review-rules": "Rules",
  confirm: "Confirm",
};
 
/** Editable working copy of a generation proposal. */
interface Draft {
  agent: ProposalAgent;
  /** The invocation that produced it, sent back on create. */
  generationId: string | null;
  reasoning: string;
  warnings: string[];
  model: GenerationModelInfo | null;
  existingSkills: Skill[];
  proposedSkills: ProposedSkill[];
  existingKnowledge: Knowledge[];
  proposedKnowledge: ProposedKnowledgeStub[];
  existingRepositories: KnowledgeRepository[];
  proposedRepositories: ProposedRepository[];
  existingSkillsets: Skillset[];
  proposedSkillsets: ProposedSkillsetInfo[];
  existingToolkits: Toolkit[];
  proposedToolkits: ProposedToolkitInfo[];
  proposedWorkers: ProposedWorker[];
  proposedRules: ProposedRule[];
  includedProposedSkills: Set<number>;
  includedProposedKnowledge: Set<number>;
  includedExistingRepositoryIds: Set<string>;
  includedProposedRepositories: Set<number>;
  includedExistingSkillsetIds: Set<string>;
  includedProposedSkillsets: Set<number>;
  includedExistingToolkitIds: Set<string>;
  includedProposedToolkits: Set<number>;
  includedProposedWorkers: Set<number>;
  includedProposedRules: Set<number>;
  /** The background search finding the proposed sources' links (POST
   *  /knowledge/discover), started when the proposal lands. */
  sourceSearchId: string | null;
  /** Its result has been taken into ``knowledgeLinks`` (or it failed). */
  sourceSearchDone: boolean;
  sourceSearchError: string | null;
  sourceSearchWarnings: string[];
  /** Each proposed source's links, by its index in ``proposedKnowledge``. */
  knowledgeLinks: Record<number, KnowledgeLinks>;
}
 
/** The proposal as the wizard edits it. Every list is read with a default:
 *  this is where a response from another release (or a stored copy) meets
 *  the steps, which then read plain arrays. */
const draftFromProposal = (proposal: AgentGenerationProposal): Draft => {
  const selectedRepositories = proposal.selected_repositories ?? [];
  const selectedSkillsets = proposal.selected_skillsets ?? [];
  const selectedToolkits = proposal.selected_toolkits ?? [];
  const proposedSkills = proposal.proposed_skills ?? [];
  const proposedKnowledge = proposal.proposed_knowledge ?? [];
  const proposedRepositories = proposal.proposed_repositories ?? [];
  const proposedSkillsets = proposal.proposed_skillsets ?? [];
  const proposedToolkits = proposal.proposed_toolkits ?? [];
  const proposedWorkers = proposal.proposed_workers ?? [];
  const proposedRules = proposal.proposed_rules ?? [];
  const indices = (items: unknown[]) => new Set(items.map((_, i) => i));
  return {
    agent: proposal.agent,
    generationId: proposal.generation_id ?? null,
    reasoning: proposal.reasoning ?? "",
    warnings: proposal.warnings ?? [],
    model: proposal.model,
    existingSkills: proposal.selected_skills ?? [],
    proposedSkills,
    existingKnowledge: proposal.selected_knowledge ?? [],
    proposedKnowledge,
    existingRepositories: selectedRepositories,
    proposedRepositories,
    existingSkillsets: selectedSkillsets,
    proposedSkillsets,
    existingToolkits: selectedToolkits,
    proposedToolkits,
    proposedWorkers,
    proposedRules,
    includedProposedSkills: indices(proposedSkills),
    includedProposedKnowledge: indices(proposedKnowledge),
    includedExistingRepositoryIds: new Set(
      selectedRepositories.map((r) => r.id),
    ),
    includedProposedRepositories: indices(proposedRepositories),
    includedExistingSkillsetIds: new Set(selectedSkillsets.map((s) => s.id)),
    includedProposedSkillsets: indices(proposedSkillsets),
    includedExistingToolkitIds: new Set(selectedToolkits.map((t) => t.id)),
    includedProposedToolkits: indices(proposedToolkits),
    includedProposedWorkers: indices(proposedWorkers),
    includedProposedRules: indices(proposedRules),
    sourceSearchId: null,
    sourceSearchDone: false,
    sourceSearchError: null,
    sourceSearchWarnings: [],
    knowledgeLinks: {},
  };
};
 
/** The kind of knowledge a proposed source is made for: the kind of the
 *  proposed repository holding it (the first, if several), else Domain. */
const kindOf = (draft: Draft, index: number): string | undefined => {
  const name = draft.proposedKnowledge[index]?.name;
  return draft.proposedRepositories.find((repo) =>
    repo.member_proposed_knowledge_names.includes(name),
  )?.category;
};
 
/** A proposed source's links, empty until the search fills them; a website
 *  source read as often as its kind needs. */
const linksOf = (draft: Draft, index: number): KnowledgeLinks =>
  draft.knowledgeLinks?.[index] ?? {
    links: [],
    scope: DEFAULT_SCOPE,
    refresh: refreshFor(kindOf(draft, index)),
  };
 
/** The search's result taken into the draft: each source's links by its key
 *  (its index), added to any the person typed meanwhile. */
const withFoundLinks = (draft: Draft, found: FindSourcesStatus): Draft => {
  const knowledgeLinks = { ...(draft.knowledgeLinks ?? {}) };
  for (const source of found.proposal?.sources ?? []) {
    const index = Number(source.key);
    Iif (!Number.isInteger(index)) continue;
    const current = linksOf(draft, index);
    const links = draftLinks([...source.pages, ...source.documents]).reduce(
      withLink,
      current.links,
    );
    knowledgeLinks[index] = {
      links,
      scope: source.scope ?? current.scope,
      refresh: refreshFor(kindOf(draft, index), source.refresh ?? current.refresh),
    };
  }
  return {
    ...draft,
    knowledgeLinks,
    sourceSearchDone: true,
    sourceSearchWarnings: found.proposal?.warnings ?? [],
  };
};
 
/** When a copy was saved (an epoch from this browser, not the server's). */
const clockTime = (t: number): string =>
  new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
 
/** Where a restored wizard opens: the step it was on, never mid-generation
 *  (that request is gone). */
const restoredStep = (step: string): WizardStep =>
  REVIEW_STEPS.includes(step as WizardStep) || step === "describe"
    ? (step as WizardStep)
    : "review-identity";
 
const toggled = <T,>(set: Set<T>, value: T): Set<T> => {
  const next = new Set(set);
  if (next.has(value)) next.delete(value);
  else next.add(value);
  return next;
};
 
/** Rewrite skill-graph agent_name references when a proposed worker is renamed. */
const renameWorkerInGraph = (
  graph: Record<string, unknown>,
  oldName: string,
  newName: string,
): Record<string, unknown> => {
  const nodes = graph.nodes;
  if (!nodes || typeof nodes !== "object") return graph;
  const rewritten = Object.fromEntries(
    Object.entries(nodes as Record<string, unknown>).map(([id, node]) => {
      if (
        node &&
        typeof node === "object" &&
        (node as Record<string, unknown>).agent_name === oldName
      ) {
        return [id, { ...(node as Record<string, unknown>), agent_name: newName }];
      }
      return [id, node];
    }),
  );
  return { ...graph, nodes: rewritten };
};
 
/** Proposed knowledge bases that will actually be created — those included
 *  and referenced as a member of at least one included proposed repository.
 *  Agents only ever integrate whole repositories, so a source with no
 *  repository has nothing to attach it to and is dropped. */
const groupedIncludedKnowledge = (draft: Draft): ProposedKnowledgeStub[] => {
  const includedRepoMemberNames = new Set(
    draft.proposedRepositories
      .filter((_, i) => draft.includedProposedRepositories.has(i))
      .flatMap((r) => r.member_proposed_knowledge_names),
  );
  return draft.proposedKnowledge.filter(
    (k, i) =>
      draft.includedProposedKnowledge.has(i) &&
      includedRepoMemberNames.has(k.name),
  );
};
 
/** New skillsets that will actually be created — those included, with their
 *  proposed-skill members filtered to skills actually being created this
 *  submission (a skill whose own checkbox was unticked is dropped from the
 *  membership, not the whole skillset — unlike knowledge, a skill is
 *  independently useful so its checkbox stays its own decision). A
 *  skillset left with no members after filtering is dropped entirely. */
const newSkillsetsPayload = (draft: Draft): NewSkillsetInput[] => {
  const includedSkillNames = new Set(
    draft.proposedSkills
      .filter((_, i) => draft.includedProposedSkills.has(i))
      .map((s) => s.name.trim()),
  );
  return draft.proposedSkillsets
    .filter((_, i) => draft.includedProposedSkillsets.has(i))
    .map((sk) => ({
      name: sk.name.trim(),
      description: sk.description,
      skill_ids: sk.member_skill_ids,
      new_skill_names: sk.member_proposed_skill_names.filter((n) =>
        includedSkillNames.has(n),
      ),
    }))
    .filter((sk) => sk.skill_ids.length > 0 || sk.new_skill_names.length > 0);
};
 
/** New toolkits that will actually be created — those included. Unlike
 *  newSkillsetsPayload, there is no member-name filtering here: a proposed
 *  toolkit's members are always existing tool/MCP-server ids (see
 *  ProposedToolkitInfo), never a name referencing something else in this
 *  request. */
const newToolkitsPayload = (draft: Draft): NewToolkitInput[] =>
  draft.proposedToolkits
    .filter((_, i) => draft.includedProposedToolkits.has(i))
    .map((tk) => ({
      name: tk.name.trim(),
      description: tk.description,
      mcp_server_ids: tk.member_mcp_server_ids,
    }));
 
const errorDetail = (e: unknown, fallback: string): string => {
  const detail = (e as { response?: { data?: { detail?: unknown } } })
    ?.response?.data?.detail;
  if (typeof detail === "string") return detail;
  return (e as { message?: string })?.message ?? fallback;
};
 
const GenerativeSetup: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
 
  // A generation already paid for survives a reload — and the app's error
  // page, which reloads — in this tab's storage (draftStore).
  const { key: workspaceKey } = useWorkspace();
  const [restored] = useState(() => loadDraft<Draft>(workspaceKey));
  const [restoredAt, setRestoredAt] = useState<number | null>(
    restored?.savedAt ?? null,
  );
  const [step, setStep] = useState<WizardStep>(
    restored ? restoredStep(restored.step) : "describe",
  );
  const [problem, setProblem] = useState(restored?.problem ?? "");
  const [modelId, setModelId] = useState(restored?.modelId ?? "");
  const [draft, setDraft] = useState<Draft | null>(restored?.draft ?? null);
  const [generateError, setGenerateError] = useState<string | null>(null);
  const [createError, setCreateError] = useState<string | null>(null);
  const [creating, setCreating] = useState(false);
  // Bumped on cancel so a stale in-flight generation can't clobber the wizard.
  const generationRun = useRef(0);
 
  const { data: models = [] } = useQuery<Model[]>({
    queryKey: [QUERY_KEYS.GET.MODELS],
    queryFn: async () => (await getApiHandler().model_router.list()) ?? [],
    select: (all) => all.filter((m) => m.is_available && m.is_chat),
  });
 
  // Fetched to resolve a proposed toolkit's member tool/MCP-server ids to
  // display names in ReviewToolkitsStep.
  const { data: allMcpServers = [] } = useQuery<MCPServer[]>({
    queryKey: [QUERY_KEYS.GET.USER_MCP_SERVERS],
    queryFn: () => getApiHandler().mcp_server_router.list(),
    enabled: MCP_AVAILABLE && step === "review-toolkits",
  });
 
  const setDraftField = <K extends keyof Draft>(key: K, value: Draft[K]) =>
    setDraft((prev) => (prev ? { ...prev, [key]: value } : prev));
 
  // Kept on every change once there is something to keep. A generation in
  // flight is kept as the step before it: that request is not resumable.
  useEffect(() => {
    if (!draft) return;
    saveDraft(workspaceKey, {
      problem,
      modelId,
      step: step === "generating" ? "describe" : step,
      draft,
    });
  }, [workspaceKey, problem, modelId, step, draft]);
 
  const handleStartOver = () => {
    generationRun.current += 1;
    clearDraft(workspaceKey);
    setDraft(null);
    setRestoredAt(null);
    setProblem("");
    setStep("describe");
  };
 
  const handleGenerate = async () => {
    const run = ++generationRun.current;
    setStep("generating");
    setGenerateError(null);
    try {
      const proposal = await getApiHandler().agent_router.generateConfig({
        problem_description: problem.trim(),
        ai_model_id: modelId || null,
      });
      Iif (generationRun.current !== run) return; // cancelled
      setDraft(draftFromProposal(proposal));
      setRestoredAt(null);
      setStep("review-identity");
      void findSources(proposal, run);
    } catch (e) {
      if (generationRun.current !== run) return;
      setGenerateError(
        errorDetail(e, "Generation failed. Please try again."),
      );
      setStep("describe");
    }
  };
 
  /** Start finding the proposed website and file sources' links, in the
   *  background, while the person reviews the other steps. */
  const findSources = async (proposal: AgentGenerationProposal, run: number) => {
    const sources = (proposal.proposed_knowledge ?? [])
      .map((stub, index) => ({ stub, index }))
      .filter(({ stub }) => takesLinks(stub.source_type))
      .map(({ stub, index }) => ({
        key: String(index),
        name: stub.name,
        description: stub.description,
        source_type: stub.source_type as "web" | "file",
      }));
    if (sources.length === 0) return;
    let id: string | null = null;
    let error: string | null = null;
    try {
      id = (
        await getApiHandler().knowledge_router.findSources({
          sources,
          for_generation_id: proposal.generation_id ?? null,
          ai_model_id: modelId || null,
        })
      ).generation_id;
    } catch (e) {
      // One already going for this proposal (another tab): follow it.
      id = runningSearch(e);
      if (!id) error = linkError(e, "Links for these sources could not be searched for.");
    }
    Iif (generationRun.current !== run) return; // regenerated or started over
    setDraft((prev) =>
      prev
        ? {
            ...prev,
            sourceSearchId: id,
            sourceSearchDone: !id,
            sourceSearchError: error,
          }
        : prev,
    );
  };
 
  const searching =
    !!draft?.sourceSearchId && !draft.sourceSearchDone;
  const { data: sourceSearch } = useQuery<FindSourcesStatus>({
    queryKey: [QUERY_KEYS.GET.KNOWLEDGE_SOURCE_SEARCH, draft?.sourceSearchId],
    queryFn: () =>
      getApiHandler().knowledge_router.sourcesStatus(
        draft?.sourceSearchId as string,
      ),
    enabled: searching,
    refetchInterval: (query) =>
      query.state.data?.status === "running" || !query.state.data
        ? SEARCH_POLL_MS
        : false,
    retry: false,
  });
 
  // Once the search lands (or fails), its links go into the draft — where a
  // reload finds them — and polling stops.
  useEffect(() => {
    if (!searching || !sourceSearch) return;
    if (sourceSearch.status === "proposed" && sourceSearch.proposal) {
      setDraft((prev) => (prev ? withFoundLinks(prev, sourceSearch) : prev));
    } else if (
      sourceSearch.status === "failed" ||
      sourceSearch.status === "applied"
    ) {
      setDraft((prev) =>
        prev
          ? {
              ...prev,
              sourceSearchDone: true,
              sourceSearchError:
                sourceSearch.status === "failed"
                  ? (sourceSearch.error ??
                    "Links for these sources could not be found.")
                  : null,
            }
          : prev,
      );
    }
  }, [searching, sourceSearch]);
 
  const handleCancelGeneration = () => {
    generationRun.current += 1;
    setStep("describe");
  };
 
  const handleCreate = async () => {
    Iif (!draft) return;
    setCreating(true);
    setCreateError(null);
 
    const includedProposed = draft.proposedSkills.filter((_, i) =>
      draft.includedProposedSkills.has(i),
    );
    const includedNewKnowledge = groupedIncludedKnowledge(draft);
    const includedNewKnowledgeNames = new Set(
      includedNewKnowledge.map((k) => k.name.trim()),
    );
    const body: CreateFromConfigRequest = {
      agent: {
        name: draft.agent.name.trim(),
        description: draft.agent.description.trim(),
        icon: draft.agent.icon,
        accent: draft.agent.accent,
        system_prompt: draft.agent.system_prompt.trim(),
      },
      // Assign the generation model as the agent's runtime model — leaving
      // this null silently drops the user's model choice and the agent falls
      // back to the workspace default on every invocation.
      ai_model_id: draft.model?.ai_model_id ?? null,
      // What links everything created here to the invocation behind it;
      // without it the agent was stamped as generated with nothing to show.
      generation_id: draft.generationId,
      // Agents only ever integrate skills through an attached skillset —
      // never individually — so there is no existing_skill_ids to send.
      // Individual existing sources are never attached directly — only via
      // an included repository (see existing_repository_ids below).
      existing_knowledge_ids: [],
      existing_repository_ids: [...draft.includedExistingRepositoryIds],
      existing_skillset_ids: [...draft.includedExistingSkillsetIds],
      // svc-core refuses toolkits while MCP servers are unavailable.
      existing_toolkit_ids: MCP_AVAILABLE
        ? [...draft.includedExistingToolkitIds]
        : [],
      new_skills: [
        ...includedProposed.map((s) => ({
          name: s.name.trim(),
          description: s.description,
          tags: s.tags,
          graph_definition: s.graph_definition,
        })),
      ],
      new_knowledge: includedNewKnowledge.map((k) => {
        const { links, scope, refresh } = linksOf(
          draft,
          draft.proposedKnowledge.indexOf(k),
        );
        return {
          name: k.name.trim(),
          description: k.description,
          source_type: k.source_type,
          ...keptLinks(k.source_type, links, scope, refresh),
        };
      }),
      new_workers: draft.proposedWorkers
        .filter((_, i) => draft.includedProposedWorkers.has(i))
        .map((w) => ({
          name: w.name.trim(),
          description: w.description,
          role: w.role || null,
          system_prompt: w.system_prompt,
          base_worker: w.base_worker || null,
          tags: w.tags,
        })),
      // Members referencing excluded new knowledge bases are dropped; a
      // repository left with no members is dropped entirely.
      new_repositories: draft.proposedRepositories
        .filter((_, i) => draft.includedProposedRepositories.has(i))
        .map((r) => ({
          name: r.name.trim(),
          description: r.description,
          icon: r.icon,
          accent: r.accent,
          category: r.category ?? "domain",
          knowledge_ids: r.member_knowledge_ids,
          new_knowledge_names: r.member_proposed_knowledge_names.filter(
            (name) => includedNewKnowledgeNames.has(name),
          ),
        }))
        .filter(
          (r) => r.knowledge_ids.length > 0 || r.new_knowledge_names.length > 0,
        ),
      new_skillsets: newSkillsetsPayload(draft),
      new_toolkits: MCP_AVAILABLE ? newToolkitsPayload(draft) : [],
      new_rules: draft.proposedRules
        .filter((_, i) => draft.includedProposedRules.has(i))
        .map((r) => ({
          name: r.name.trim(),
          description: r.description,
          layer: r.layer,
          conditions: r.conditions,
          actions: r.actions,
          priority: r.priority,
        })),
      // The search behind the links, applied to the agent with them.
      source_discovery_id:
        draft.sourceSearchDone && !draft.sourceSearchError
          ? draft.sourceSearchId
          : null,
    };
 
    try {
      const result = await getApiHandler().agent_router.createFromConfig(body);
      clearDraft(workspaceKey);
      await Promise.all(
        [
          QUERY_KEYS.GET.AGENTS,
          QUERY_KEYS.GET.SKILLS,
          QUERY_KEYS.GET.KNOWLEDGE,
          QUERY_KEYS.GET.REPOSITORIES,
          QUERY_KEYS.GET.SKILLSETS,
          QUERY_KEYS.GET.TOOLKITS,
          QUERY_KEYS.GET.USER_WORKERS,
          QUERY_KEYS.GET.RULES,
        ].map((key) => queryClient.invalidateQueries({ queryKey: [key] })),
      );
      // Agent route params are base64-encoded (see AgentsGrid/Agent.tsx atob) —
      // a raw UUID here throws in the viewer's atob() and blanks the page.
      void navigate(
        APP_ROUTES.USER.INFERENCE.AGENTS.id.replace(
          ROUTE_PARAMS.AGENT.id,
          encodeResourceId(result.agent.id),
        ),
      );
    } catch (e) {
      setCreateError(
        errorDetail(
          e,
          "Creation failed. Nothing was created — please try again.",
        ),
      );
    } finally {
      setCreating(false);
    }
  };
 
  const reviewIndex = REVIEW_STEPS.indexOf(step);
  const stepperItems = [
    "Describe",
    "Prompt",
    "Skills",
    "Toolkits",
    "Workers",
    "Knowledge",
    "Rules",
    "Confirm",
  ].filter((label) => MCP_AVAILABLE || label !== "Toolkits");
  const activeStepper = stepperItems.indexOf(STEP_LABELS[step]);
 
  return (
    <SubPage title="Generate New Agent">
      <div className="max-w-2xl space-y-5">
        {/* Stepper */}
        <div className="flex items-center gap-2">
          {stepperItems.map((label, index) => (
            <React.Fragment key={label}>
              {index > 0 && (
                <div
                  className={`h-px flex-1 ${
                    index <= activeStepper
                      ? "bg-gray-800 dark:bg-gray-200"
                      : "bg-gray-200 dark:bg-gray-700"
                  }`}
                />
              )}
              <div
                className={`text-xs font-medium ${
                  index === activeStepper
                    ? "text-gray-900 dark:text-white"
                    : index < activeStepper
                      ? "text-gray-500 dark:text-gray-400"
                      : "text-gray-300 dark:text-gray-600"
                }`}
              >
                {label}
              </div>
            </React.Fragment>
          ))}
        </div>
 
        {restoredAt !== null && draft && (
          <div className="flex items-start gap-2.5 rounded-xl border border-blue-200 dark:border-blue-800/60 bg-blue-50 dark:bg-blue-900/20 px-4 py-3 text-sm text-blue-800 dark:text-blue-200">
            <History className="size-4 mt-0.5 shrink-0" />
            <p className="flex-1">
              Restored the agent you generated at {clockTime(restoredAt)}.
            </p>
            <button
              type="button"
              onClick={handleStartOver}
              className="text-xs font-medium underline underline-offset-2"
            >
              Start over
            </button>
            <button
              type="button"
              onClick={() => setRestoredAt(null)}
              className="text-xs font-medium"
              aria-label="Dismiss"
            >
              Dismiss
            </button>
          </div>
        )}
 
        <SectionErrorBoundary
          resetKey={step}
          fallback={(error, reset) => (
            <div
              role="alert"
              className="rounded-xl border border-amber-200 dark:border-amber-800/60 bg-amber-50 dark:bg-amber-900/20 p-4 space-y-2"
            >
              <p className="flex items-center gap-2 text-sm font-medium text-amber-800 dark:text-amber-200">
                <AlertTriangle className="size-4" />
                This step couldn&apos;t be shown — your generated agent is kept.
              </p>
              <p className="text-xs text-amber-700 dark:text-amber-300">
                Use Back or Next to carry on, or try the step again.
              </p>
              <pre className="text-xs text-amber-700 dark:text-amber-300 whitespace-pre-wrap">
                {error.message}
              </pre>
              <button
                type="button"
                onClick={reset}
                className="text-xs font-medium text-amber-800 dark:text-amber-200 underline underline-offset-2"
              >
                Try again
              </button>
            </div>
          )}
        >
          {step === "describe" && (
            <DescribeStep
              value={problem}
              onChange={setProblem}
              models={models}
              modelId={modelId}
              onModelChange={setModelId}
              error={generateError}
              onGenerate={() => void handleGenerate()}
              resumeName={draft?.agent.name}
              onResume={draft ? () => setStep("review-identity") : undefined}
            />
          )}
 
          {step === "generating" && (
            <GeneratingStep onCancel={handleCancelGeneration} />
          )}
 
          {step === "review-identity" && draft && (
            <ReviewIdentityStep
              agent={draft.agent}
              reasoning={draft.reasoning}
              warnings={draft.warnings}
              onChange={(agent) => setDraftField("agent", agent)}
            />
          )}
 
          {step === "review-skills" && draft && (
            <ReviewSkillsStep
              existingSkills={draft.existingSkills}
              proposedSkills={draft.proposedSkills}
              existingSkillsets={draft.existingSkillsets}
              proposedSkillsets={draft.proposedSkillsets}
              includedProposed={draft.includedProposedSkills}
              includedExistingSkillsets={draft.includedExistingSkillsetIds}
              includedProposedSkillsets={draft.includedProposedSkillsets}
              onToggleProposed={(index) =>
                setDraftField(
                  "includedProposedSkills",
                  toggled(draft.includedProposedSkills, index),
                )
              }
              onToggleExistingSkillset={(id) =>
                setDraftField(
                  "includedExistingSkillsetIds",
                  toggled(draft.includedExistingSkillsetIds, id),
                )
              }
              onToggleProposedSkillset={(index) =>
                setDraftField(
                  "includedProposedSkillsets",
                  toggled(draft.includedProposedSkillsets, index),
                )
              }
              onEditProposed={(index, skill) =>
                setDraftField(
                  "proposedSkills",
                  draft.proposedSkills.map((s, i) => (i === index ? skill : s)),
                )
              }
            />
          )}
 
          {step === "review-toolkits" && draft && (
            <ReviewToolkitsStep
              existingToolkits={draft.existingToolkits}
              proposedToolkits={draft.proposedToolkits}
              allMcpServers={allMcpServers}
              includedExistingToolkits={draft.includedExistingToolkitIds}
              includedProposedToolkits={draft.includedProposedToolkits}
              onToggleExistingToolkit={(id) =>
                setDraftField(
                  "includedExistingToolkitIds",
                  toggled(draft.includedExistingToolkitIds, id),
                )
              }
              onToggleProposedToolkit={(index) =>
                setDraftField(
                  "includedProposedToolkits",
                  toggled(draft.includedProposedToolkits, index),
                )
              }
            />
          )}
 
          {step === "review-workers" && draft && (
            <ReviewWorkersStep
              proposedWorkers={draft.proposedWorkers}
              includedProposed={draft.includedProposedWorkers}
              onToggleProposed={(index) =>
                setDraftField(
                  "includedProposedWorkers",
                  toggled(draft.includedProposedWorkers, index),
                )
              }
              onEditProposed={(index, worker) => {
                const previous = draft.proposedWorkers[index];
                setDraft((prev) => {
                  if (!prev) return prev;
                  const proposedSkills =
                    previous && previous.name !== worker.name
                      ? // Keep skill-graph references pointing at the worker
                        // through a rename.
                        prev.proposedSkills.map((s) => ({
                          ...s,
                          graph_definition: renameWorkerInGraph(
                            s.graph_definition,
                            previous.name,
                            worker.name,
                          ),
                        }))
                      : prev.proposedSkills;
                  return {
                    ...prev,
                    proposedSkills,
                    proposedWorkers: prev.proposedWorkers.map((w, i) =>
                      i === index ? worker : w,
                    ),
                  };
                });
              }}
            />
          )}
 
          {step === "review-knowledge" && draft && (
            <ReviewKnowledgeStep
              existingKnowledge={draft.existingKnowledge}
              proposedKnowledge={draft.proposedKnowledge}
              existingRepositories={draft.existingRepositories}
              proposedRepositories={draft.proposedRepositories}
              includedProposed={draft.includedProposedKnowledge}
              includedExistingRepositories={draft.includedExistingRepositoryIds}
              includedProposedRepositories={draft.includedProposedRepositories}
              knowledgeLinks={(index) => linksOf(draft, index)}
              onEditProposedRepository={(index, repo) =>
                setDraftField(
                  "proposedRepositories",
                  draft.proposedRepositories.map((r, i) => (i === index ? repo : r)),
                )
              }
              search={{
                running: searching,
                stage: sourceSearch?.stage ?? "queued",
                progress: sourceSearch?.progress ?? {},
                error: draft.sourceSearchError,
                warnings: draft.sourceSearchWarnings ?? [],
              }}
              onEditLinks={(index, change) =>
                setDraft((prev) =>
                  prev
                    ? {
                        ...prev,
                        knowledgeLinks: {
                          ...(prev.knowledgeLinks ?? {}),
                          [index]: { ...linksOf(prev, index), ...change },
                        },
                      }
                    : prev,
                )
              }
              onToggleProposed={(index) =>
                setDraftField(
                  "includedProposedKnowledge",
                  toggled(draft.includedProposedKnowledge, index),
                )
              }
              onToggleExistingRepository={(id) =>
                setDraftField(
                  "includedExistingRepositoryIds",
                  toggled(draft.includedExistingRepositoryIds, id),
                )
              }
              onToggleProposedRepository={(index) =>
                setDraftField(
                  "includedProposedRepositories",
                  toggled(draft.includedProposedRepositories, index),
                )
              }
              onEditProposed={(index, stub) => {
                const previous = draft.proposedKnowledge[index];
                setDraft((prev) => {
                  if (!prev) return prev;
                  const proposedRepositories =
                    previous && previous.name !== stub.name
                      ? // Keep repository member references pointing at the
                        // knowledge base through a rename.
                        prev.proposedRepositories.map((r) => ({
                          ...r,
                          member_proposed_knowledge_names:
                            r.member_proposed_knowledge_names.map((name) =>
                              name === previous.name ? stub.name : name,
                            ),
                        }))
                      : prev.proposedRepositories;
                  return {
                    ...prev,
                    proposedRepositories,
                    proposedKnowledge: prev.proposedKnowledge.map((k, i) =>
                      i === index ? stub : k,
                    ),
                  };
                });
              }}
            />
          )}
 
          {step === "review-rules" && draft && (
            <ReviewRulesStep
              proposedRules={draft.proposedRules}
              includedProposed={draft.includedProposedRules}
              onToggleProposed={(index) =>
                setDraftField(
                  "includedProposedRules",
                  toggled(draft.includedProposedRules, index),
                )
              }
              onEditProposed={(index, rule) =>
                setDraftField(
                  "proposedRules",
                  draft.proposedRules.map((r, i) => (i === index ? rule : r)),
                )
              }
            />
          )}
 
          {step === "confirm" && draft && (
            <ConfirmStep
              agentName={draft.agent.name}
              newSkillNames={draft.proposedSkills
                .filter((_, i) => draft.includedProposedSkills.has(i))
                .map((s) => s.name)}
              newKnowledgeNames={groupedIncludedKnowledge(draft).map(
                (k) => k.name,
              )}
              newWorkerNames={draft.proposedWorkers
                .filter((_, i) => draft.includedProposedWorkers.has(i))
                .map((w) => w.name)}
              attachedRepositoryNames={draft.existingRepositories
                .filter((r) => draft.includedExistingRepositoryIds.has(r.id))
                .map((r) => r.name)}
              newRepositoryNames={draft.proposedRepositories
                .filter((_, i) => draft.includedProposedRepositories.has(i))
                .map((r) => r.name)}
              attachedSkillsetNames={draft.existingSkillsets
                .filter((s) => draft.includedExistingSkillsetIds.has(s.id))
                .map((s) => s.name)}
              newSkillsetNames={newSkillsetsPayload(draft).map((s) => s.name)}
              attachedToolkitNames={draft.existingToolkits
                .filter((t) => draft.includedExistingToolkitIds.has(t.id))
                .map((t) => t.name)}
              newToolkitNames={newToolkitsPayload(draft).map((t) => t.name)}
              newRuleNames={draft.proposedRules
                .filter((_, i) => draft.includedProposedRules.has(i))
                .map((r) => r.name)}
              error={createError}
              creating={creating}
              onCreate={() => void handleCreate()}
            />
          )}
        </SectionErrorBoundary>
 
        {/* Review navigation */}
        {reviewIndex >= 0 && (
          <div className="flex items-center justify-between pt-1 pb-6">
            <button
              type="button"
              onClick={() => setStep("describe")}
              className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
            >
              <RotateCcw className="size-3.5" />
              Regenerate
            </button>
            <div className="flex items-center gap-2">
              {reviewIndex > 0 && (
                <button
                  type="button"
                  onClick={() => setStep(REVIEW_STEPS[reviewIndex - 1])}
                  className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                >
                  <ArrowLeft className="size-4" />
                  Back
                </button>
              )}
              {reviewIndex < REVIEW_STEPS.length - 1 && (
                <button
                  type="button"
                  onClick={() => setStep(REVIEW_STEPS[reviewIndex + 1])}
                  disabled={
                    step === "review-identity" &&
                    (!draft?.agent.name.trim() ||
                      !draft?.agent.system_prompt.trim())
                  }
                  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"
                >
                  Next
                  <ArrowRight className="size-4" />
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </SubPage>
  );
};
 
export default GenerativeSetup;