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

33.05% Statements 40/121
21.9% Branches 23/105
20.4% Functions 10/49
35.71% Lines 40/112

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                                                                                                      1x             1x         24x                           1x     1x           1x       6x                     1x                                                                                                               1x                                                                                                   1x                                                                                                 1x 6x 6x   6x           6x 6x     6x     6x     6x     6x 6x                   6x     3x   6x       6x   6x         3x   6x       6x   6x                 6x           6x                 6x                 6x                 6x                         6x                                                                                                                                 6x                                                                                                                                                                                                                     24x                                         6x                                                                                               6x                                                                                                                                                                                                                                                                
import {
  Appearance,
  AppearanceFields,
  AppearanceSwatch,
} from "@/components/appearance/AppearancePicker";
import {
  AGENT_ICON_REGISTRY,
  REPOSITORY_ICON_REGISTRY,
} from "@/components/appearance/icons";
import BuiltInBadge from "@/components/badge/BuiltInBadge";
import SubPage from "@/components/page/SubPage/SubPage";
import { isSystemManaged } from "@/objects/Doc";
import { Agent } from "@/objects/Agent";
import { KnowledgeRepository } from "@/objects/Knowledge";
import { CategoryBadge } from "@/apps/user/pages/knowledge/cardParts";
import { Skillset } from "@/objects/Skillset";
import { Toolkit } from "@/objects/Toolkit";
import { APP_ROUTES } from "@/routes/const";
import { INCLUDE_SYSTEM, QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import {
  AlertCircle,
  Bot,
  Check,
  CheckSquare,
  FileText,
  FolderGit2,
  Hammer,
  Info,
  Layers3,
  Loader2,
  Square,
} from "lucide-react";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { MCP_AVAILABLE } from "@/util/mcp";
import {
  SectionCard,
} from "@/components/detail";
 
// ─── FormData ─────────────────────────────────────────────────────────────────
 
interface FormData {
  name: string;
  description: string;
  system_prompt: string;
}
 
/** How a brand-new agent presents itself until the user picks otherwise —
 *  the registry's own default glyph on the neutral tone. */
const DEFAULT_APPEARANCE: Appearance = {
  icon: AGENT_ICON_REGISTRY.fallback,
  accent: "slate",
};
 
// ─── Primitives ───────────────────────────────────────────────────────────────
 
const FieldLabel: React.FC<{
  label: string;
  description?: string;
  required?: boolean;
}> = ({ label, description, required }) => (
  <div className="mb-1.5">
    <div className="text-sm font-medium text-gray-700 dark:text-gray-300">
      {label}
      {required && <span className="ml-0.5 text-red-500">*</span>}
    </div>
    {description && (
      <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">
        {description}
      </p>
    )}
  </div>
);
 
const inputBase =
  "w-full px-3 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300 dark:focus:ring-gray-500 transition-colors";
 
const errorBase =
  "w-full px-3 py-2 text-sm rounded-lg border border-red-300 dark:border-red-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-red-200 dark:focus:ring-red-900 transition-colors";
 
// ─── Section card ─────────────────────────────────────────────────────────────
 
// ─── Character count ──────────────────────────────────────────────────────────
 
const CharCount: React.FC<{ value: string; max: number }> = ({
  value,
  max,
}) => (
  <div
    className={`text-right text-xs mt-1 ${
      value.length > max ? "text-red-500" : "text-gray-400 dark:text-gray-500"
    }`}
  >
    {value.length} / {max}
  </div>
);
 
// ─── RepositoryToggle ─────────────────────────────────────────────────────────
 
const RepositoryToggle: React.FC<{
  repository: KnowledgeRepository;
  selected: boolean;
  onToggle: () => void;
}> = ({ repository, selected, onToggle }) => (
  <button
    type="button"
    onClick={onToggle}
    className={`w-full flex items-start gap-3 px-4 py-3 rounded-lg border text-left transition-all ${
      selected
        ? "border-emerald-400 dark:border-emerald-500 bg-emerald-50 dark:bg-emerald-900/20 shadow-sm"
        : "border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 bg-white dark:bg-gray-800"
    }`}
  >
    <div className="mt-0.5 shrink-0">
      {selected ? (
        <CheckSquare className="size-4 text-emerald-600 dark:text-emerald-400" />
      ) : (
        <Square className="size-4 text-gray-400 dark:text-gray-500" />
      )}
    </div>
    <AppearanceSwatch
      registry={REPOSITORY_ICON_REGISTRY}
      icon={repository.icon}
      accent={repository.accent}
      size="sm"
      className="mt-0.5"
    />
    <div className="min-w-0 flex-1">
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-1.5 min-w-0">
          <div className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate">
            {repository.name}
          </div>
          {isSystemManaged(repository) && <BuiltInBadge size="sm" />}
          <CategoryBadge category={repository.category} />
        </div>
        <div className="flex items-center gap-1 shrink-0">
          <FolderGit2 className="size-3 text-gray-400 dark:text-gray-500" />
          <span className="text-xs text-gray-400 dark:text-gray-500">
            {repository.knowledge_ids.length} source
            {repository.knowledge_ids.length !== 1 ? "s" : ""}
          </span>
        </div>
      </div>
      {repository.description && (
        <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 line-clamp-2">
          {repository.description}
        </div>
      )}
    </div>
  </button>
);
 
// ─── SkillsetToggle ───────────────────────────────────────────────────────────
 
const SkillsetToggle: React.FC<{
  skillset: Skillset;
  selected: boolean;
  onToggle: () => void;
}> = ({ skillset, selected, onToggle }) => {
  const memberCount = skillset.skill_ids.length;
  return (
    <button
      type="button"
      onClick={onToggle}
      className={`w-full flex items-start gap-3 px-4 py-3 rounded-lg border text-left transition-all ${
        selected
          ? "border-amber-400 dark:border-amber-500 bg-amber-50 dark:bg-amber-900/20 shadow-sm"
          : "border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 bg-white dark:bg-gray-800"
      }`}
    >
      <div className="mt-0.5 shrink-0">
        {selected ? (
          <CheckSquare className="size-4 text-amber-600 dark:text-amber-400" />
        ) : (
          <Square className="size-4 text-gray-400 dark:text-gray-500" />
        )}
      </div>
      <div className="min-w-0 flex-1">
        <div className="flex items-center justify-between gap-2">
          <div className="flex items-center gap-1.5 min-w-0">
            <span className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate">
              {skillset.name}
            </span>
            {isSystemManaged(skillset) && <BuiltInBadge size="sm" />}
          </div>
          <div className="flex items-center gap-1 shrink-0">
            <Layers3 className="size-3 text-gray-400 dark:text-gray-500" />
            <span className="text-xs text-gray-400 dark:text-gray-500">
              {memberCount} member{memberCount !== 1 ? "s" : ""}
            </span>
          </div>
        </div>
        {skillset.description && (
          <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 line-clamp-2">
            {skillset.description}
          </div>
        )}
      </div>
    </button>
  );
};
 
// ─── ToolkitToggle ────────────────────────────────────────────────────────────
 
const ToolkitToggle: React.FC<{
  toolkit: Toolkit;
  selected: boolean;
  onToggle: () => void;
}> = ({ toolkit, selected, onToggle }) => {
  const memberCount = toolkit.mcp_server_ids.length;
  return (
    <button
      type="button"
      onClick={onToggle}
      className={`w-full flex items-start gap-3 px-4 py-3 rounded-lg border text-left transition-all ${
        selected
          ? "border-teal-400 dark:border-teal-500 bg-teal-50 dark:bg-teal-900/20 shadow-sm"
          : "border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 bg-white dark:bg-gray-800"
      }`}
    >
      <div className="mt-0.5 shrink-0">
        {selected ? (
          <CheckSquare className="size-4 text-teal-600 dark:text-teal-400" />
        ) : (
          <Square className="size-4 text-gray-400 dark:text-gray-500" />
        )}
      </div>
      <div className="min-w-0 flex-1">
        <div className="flex items-center justify-between gap-2">
          <div className="text-sm font-medium text-gray-800 dark:text-gray-200">
            {toolkit.name}
          </div>
          <div className="flex items-center gap-1 shrink-0">
            <Hammer className="size-3 text-gray-400 dark:text-gray-500" />
            <span className="text-xs text-gray-400 dark:text-gray-500">
              {memberCount} member{memberCount !== 1 ? "s" : ""}
            </span>
          </div>
        </div>
        {toolkit.description && (
          <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 line-clamp-2">
            {toolkit.description}
          </div>
        )}
      </div>
    </button>
  );
};
 
// ─── NewAgent ─────────────────────────────────────────────────────────────────
 
export type FormValues = Partial<FormData>;
 
const NewAgent: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const navigate = useNavigate();
 
  const [data, setData] = useState<FormData>({
    name: "",
    description: "",
    system_prompt: "",
  });
  const [appearance, setAppearance] =
    useState<Appearance>(DEFAULT_APPEARANCE);
  const [selectedRepositories, setSelectedRepositories] = useState<
    Set<string>
  >(new Set());
  const [selectedSkillsets, setSelectedSkillsets] = useState<Set<string>>(
    new Set(),
  );
  const [selectedToolkits, setSelectedToolkits] = useState<Set<string>>(
    new Set(),
  );
  const [errors, setErrors] = useState<Partial<Record<keyof FormData, string>>>(
    {},
  );
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
 
  // Created in the workspace this page shows (svc-core puts it there), and
  // granted only what that workspace has: the lists below are its own —
  // what it owns, inherits and the built-ins — which is all an agent here
  // may reach (svc-core refuses anything else).
 
  // Built-in repositories (the CHAIN-R User Guide, News) may be granted like
  // the user's own; listed after them.
  const { data: repositoryRows = [], isLoading: repositoriesLoading } =
    useQuery<KnowledgeRepository[]>({
      queryKey: [QUERY_KEYS.GET.REPOSITORIES, INCLUDE_SYSTEM],
      queryFn: () =>
        getApiHandler().repository_router.list({ includeSystem: true }),
      select: (rows) =>
        [...rows].sort(
          (a, b) => Number(isSystemManaged(a)) - Number(isSystemManaged(b)),
        ),
    });
  const allRepositories = repositoryRows as KnowledgeRepository[];
 
  const { data: skillsetRows = [], isLoading: skillsetsLoading } = useQuery<
    Skillset[]
  >({
    // Built-in skillsets may be granted like the user's own; listed after them.
    queryKey: [QUERY_KEYS.GET.SKILLSETS, "include_system"],
    queryFn: () => getApiHandler().skillset_router.list({ includeSystem: true }),
    select: (rows) =>
      [...rows].sort(
        (a, b) => Number(isSystemManaged(a)) - Number(isSystemManaged(b)),
      ),
  });
  const allSkillsets = skillsetRows as Skillset[];
 
  const { data: allToolkits = [], isLoading: toolkitsLoading } = useQuery<
    Toolkit[]
  >({
    queryKey: [QUERY_KEYS.GET.TOOLKITS],
    queryFn: () => getApiHandler().toolkit_router.list(),
    // Toolkits bundle MCP servers, not available in this release.
    enabled: MCP_AVAILABLE,
  });
 
  const set = <K extends keyof FormData>(key: K, value: string) => {
    setData((prev) => ({ ...prev, [key]: value }));
    setErrors((prev) => ({ ...prev, [key]: undefined }));
    setSubmitError(null);
  };
 
  const toggleRepository = (id: string) => {
    setSelectedRepositories((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };
 
  const toggleSkillset = (id: string) => {
    setSelectedSkillsets((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };
 
  const toggleToolkit = (id: string) => {
    setSelectedToolkits((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };
 
  const validate = (): boolean => {
    const next: Partial<Record<keyof FormData, string>> = {};
    if (!data.name.trim()) next.name = "Name is required.";
    else if (data.name.trim().length < 2)
      next.name = "Name must be at least 2 characters.";
    else if (data.name.trim().length > 50)
      next.name = "Name must be 50 characters or fewer.";
    if (!data.system_prompt.trim())
      next.system_prompt = "System prompt is required.";
    setErrors(next);
    return Object.keys(next).length === 0;
  };
 
  const handleSubmit = async () => {
    if (!validate()) return;
    setSubmitting(true);
    setSubmitError(null);
    try {
      const api = getApiHandler();
 
      const res = await api.agent_router.new({
        name: data.name.trim(),
        description: data.description.trim(),
        icon: appearance.icon,
        accent: appearance.accent,
        system_prompt: data.system_prompt.trim(),
      } as Agent);
 
      const agentId: string | undefined = (res as { data?: { id?: string } })
        ?.data?.id;
 
      if (agentId && selectedRepositories.size > 0) {
        await Promise.all(
          // Only what the chosen owner can use: a pick made before the owner
          // changed is dropped rather than granted.
          [...selectedRepositories]
            .filter((id) => allRepositories.some((r) => r.id === id))
            .map((repoId) =>
            api.agent_router
              .addAgentRepository(agentId, repoId)
              .catch(() => null),
          ),
        );
      }
 
      if (agentId && selectedSkillsets.size > 0) {
        await Promise.all(
          [...selectedSkillsets]
            .filter((id) => allSkillsets.some((s) => s.id === id))
            .map((skillsetId) =>
            api.agent_router
              .addAgentSkillset(agentId, skillsetId)
              .catch(() => null),
          ),
        );
      }
 
      if (agentId && selectedToolkits.size > 0) {
        await Promise.all(
          [...selectedToolkits].map((toolkitId) =>
            api.agent_router
              .addAgentToolkit(agentId, toolkitId)
              .catch(() => null),
          ),
        );
      }
 
      void navigate(APP_ROUTES.USER.INFERENCE.agents);
    } catch (e: any) {
      setSubmitError(
        (e as { message?: string })?.message ??
          "Something went wrong. Please try again.",
      );
    } finally {
      setSubmitting(false);
    }
  };
 
  return (
    <SubPage title="New Agent">
      <div className="max-w-2xl space-y-4">
        {/* Identity */}
        <SectionCard variant="form"
          icon={Bot}
          title="Identity"
          description="Name and describe your agent so it's easy to find and understand at a glance."
        >
          <div>
            <FieldLabel
              label="Name"
              description="A short, memorable name for this agent."
              required
            />
            <input
              type="text"
              value={data.name}
              onChange={(e) => set("name", e.target.value)}
              placeholder="e.g. Support Bot"
              className={errors.name ? errorBase : inputBase}
            />
            <CharCount value={data.name} max={50} />
            {errors.name && (
              <p className="text-xs text-red-500 mt-1">{errors.name}</p>
            )}
          </div>
 
          <div>
            <FieldLabel
              label="Description"
              description="What this agent does and who it is designed for."
            />
            <textarea
              value={data.description}
              onChange={(e) => set("description", e.target.value)}
              placeholder="e.g. Assists employees with HR queries using internal policy documents."
              rows={3}
              className={inputBase + " resize-none"}
            />
          </div>
 
          <div>
            <FieldLabel
              label="Appearance"
              description="An icon and accent so this agent is recognisable at a glance in a list of many."
            />
            <div className="flex items-start gap-4">
              <AppearanceSwatch
                registry={AGENT_ICON_REGISTRY}
                icon={appearance.icon}
                accent={appearance.accent}
                size="lg"
              />
              <div className="flex-1 min-w-0">
                <AppearanceFields
                  registry={AGENT_ICON_REGISTRY}
                  value={appearance}
                  onChange={setAppearance}
                  labels={false}
                />
              </div>
            </div>
          </div>
        </SectionCard>
 
        {/* System prompt */}
        <SectionCard variant="form"
          icon={FileText}
          title="System Prompt"
          description="The core instructions sent at the start of every conversation."
        >
          <div>
            <FieldLabel
              label="Prompt"
              description="Define this agent's behaviour, tone, and scope."
              required
            />
            <textarea
              value={data.system_prompt}
              onChange={(e) => set("system_prompt", e.target.value)}
              placeholder={`e.g. You are a helpful HR assistant at Acme Corp. You answer questions based on company policy documents only. Always be professional and concise.`}
              rows={8}
              className={
                (errors.system_prompt ? errorBase : inputBase) +
                " resize-none font-mono text-xs leading-relaxed"
              }
            />
            {errors.system_prompt && (
              <p className="text-xs text-red-500 mt-1">
                {errors.system_prompt}
              </p>
            )}
          </div>
 
          <div className="rounded-lg bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 px-4 py-3 space-y-1.5">
            <div className="flex items-center gap-1.5 text-xs font-medium text-blue-700 dark:text-blue-300">
              <Info className="size-3.5" />
              Prompt tips
            </div>
            <ul className="space-y-1">
              {[
                "Define the agent's role and expertise clearly.",
                "Specify tone: professional, friendly, concise, etc.",
                "Set boundaries on what topics the agent should avoid.",
                "Include context about who the agent is interacting with.",
              ].map((tip) => (
                <li
                  key={tip}
                  className="flex items-start gap-1.5 text-xs text-blue-600 dark:text-blue-400"
                >
                  <span className="mt-1.5 size-1 rounded-full bg-blue-400 dark:bg-blue-500 shrink-0" />
                  {tip}
                </li>
              ))}
            </ul>
          </div>
        </SectionCard>
 
        {/* Knowledge repositories */}
        <SectionCard variant="form"
          icon={FolderGit2}
          title="Knowledge Repositories"
          description="Grant this agent access to repositories — named collections of sources — for retrieval and context. Agents integrate whole repositories rather than individual sources, keeping retrieval focused and reusable across agents."
        >
          {repositoriesLoading ? (
            <div className="space-y-2">
              {[1, 2].map((i) => (
                <div
                  key={i}
                  className="h-14 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 animate-pulse"
                />
              ))}
            </div>
          ) : allRepositories.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <div className="p-3 rounded-full bg-gray-100 dark:bg-gray-700 mb-3">
                <FolderGit2 className="size-5 text-gray-400 dark:text-gray-500" />
              </div>
              <p className="text-sm text-gray-500 dark:text-gray-400 font-medium">
                No repositories found
              </p>
              <p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
                Group your sources into a repository first to grant access
                here.
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {allRepositories.map((repo) => (
                <RepositoryToggle
                  key={repo.id}
                  repository={repo}
                  selected={selectedRepositories.has(repo.id)}
                  onToggle={() => toggleRepository(repo.id)}
                />
              ))}
            </div>
          )}
          {selectedRepositories.size > 0 && (
            <p className="text-xs text-emerald-600 dark:text-emerald-400 font-medium">
              {selectedRepositories.size} repositor
              {selectedRepositories.size !== 1 ? "ies" : "y"} selected
            </p>
          )}
        </SectionCard>
 
        {/* Skillsets */}
        <SectionCard variant="form"
          icon={Layers3}
          title="Skillsets"
          description="Grant bundles of skills in one step — the only way to give this agent skills."
        >
          {skillsetsLoading ? (
            <div className="space-y-2">
              {[1, 2].map((i) => (
                <div
                  key={i}
                  className="h-14 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 animate-pulse"
                />
              ))}
            </div>
          ) : allSkillsets.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <div className="p-3 rounded-full bg-gray-100 dark:bg-gray-700 mb-3">
                <Layers3 className="size-5 text-gray-400 dark:text-gray-500" />
              </div>
              <p className="text-sm text-gray-500 dark:text-gray-400 font-medium">
                No skillsets found
              </p>
              <p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
                Create a skillset first to attach a bundle to an agent.
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {allSkillsets.map((skillset) => (
                <SkillsetToggle
                  key={skillset.id}
                  skillset={skillset}
                  selected={selectedSkillsets.has(skillset.id)}
                  onToggle={() => toggleSkillset(skillset.id)}
                />
              ))}
            </div>
          )}
          {selectedSkillsets.size > 0 && (
            <p className="text-xs text-amber-600 dark:text-amber-400 font-medium">
              {selectedSkillsets.size} skillset
              {selectedSkillsets.size !== 1 ? "s" : ""} selected
            </p>
          )}
        </SectionCard>
 
        {/* Toolkits — MCP servers are not available in this release
            (util/mcp.ts), so there is nothing to grant. */}
        {MCP_AVAILABLE && (
          <SectionCard variant="form"
            icon={Hammer}
            title="Toolkits"
            description="Grant bundles of tools and MCP servers in one step — the only way to give this agent tool or MCP server access."
          >
            {toolkitsLoading ? (
              <div className="space-y-2">
                {[1, 2].map((i) => (
                  <div
                    key={i}
                    className="h-14 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 animate-pulse"
                  />
                ))}
              </div>
            ) : allToolkits.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-8 text-center">
                <div className="p-3 rounded-full bg-gray-100 dark:bg-gray-700 mb-3">
                  <Hammer className="size-5 text-gray-400 dark:text-gray-500" />
                </div>
                <p className="text-sm text-gray-500 dark:text-gray-400 font-medium">
                  No toolkits found
                </p>
                <p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
                  Create a toolkit first to attach a bundle to an agent.
                </p>
              </div>
            ) : (
              <div className="space-y-2">
                {allToolkits.map((toolkit) => (
                  <ToolkitToggle
                    key={toolkit.id}
                    toolkit={toolkit}
                    selected={selectedToolkits.has(toolkit.id)}
                    onToggle={() => toggleToolkit(toolkit.id)}
                  />
                ))}
              </div>
            )}
            {selectedToolkits.size > 0 && (
              <p className="text-xs text-teal-600 dark:text-teal-400 font-medium">
                {selectedToolkits.size} toolkit
                {selectedToolkits.size !== 1 ? "s" : ""} selected
              </p>
            )}
          </SectionCard>
        )}
 
        {submitError && (
          <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" />
            {submitError}
          </div>
        )}
 
        <div className="flex items-center justify-end gap-3 pt-2 pb-6">
          <button
            type="button"
            onClick={() => void navigate(APP_ROUTES.USER.INFERENCE.agents)}
            className="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"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={() => void handleSubmit()}
            disabled={submitting}
            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"
          >
            {submitting ? (
              <>
                <Loader2 className="size-4 animate-spin" />
                Creating…
              </>
            ) : (
              <>
                <Check className="size-4" />
                Create Agent
              </>
            )}
          </button>
        </div>
      </div>
    </SubPage>
  );
};
 
export default NewAgent;