All files / src/apps/user/pages/skillsets GenerateSkillsetModal.tsx

63.04% Statements 58/92
54.68% Branches 35/64
37.83% Functions 14/37
67.85% Lines 57/84

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                                                                              4x           4x             4x     3x 3x                                             4x     59x 59x   59x 59x 59x 59x   59x     59x 59x 59x     59x 59x     59x 59x 59x   59x   1x   59x   59x             59x 1x 1x 1x 1x       1x 1x 1x       1x 1x 1x 1x                 59x 1x 1x 1x 1x 1x   1x 1x               1x               1x   2x     1x           1x       59x       59x                                                                   54x                         165x                                                                                                   1x                                                                                                                                                                                                                                                                                                                                   3x                                                                                                                                                     1x                                                    
import {
  FieldLabel,
  SectionCard,
  ToggleRow,
  inputBase,
} from "@/apps/user/pages/agents/setup/primitives";
import BuiltInBadge from "@/components/badge/BuiltInBadge";
import { ProposedSkill } from "@/objects/AgentSetup";
import { isSystemManaged } from "@/objects/Doc";
import DiffViewer from "@/components/diff/DiffViewer/DiffViewer";
import { FieldDiff } from "@/objects/History";
import { Model, isSelectableModel, modelDisplayName } from "@/objects/Model";
import { SkillsetGenerationProposal } from "@/objects/SkillsetSetup";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertCircle,
  Check,
  ChevronDown,
  ChevronRight,
  GitCompare,
  Lightbulb,
  Loader2,
  Sparkles,
  Tag,
  X,
  Zap,
} from "lucide-react";
import React, { useState } from "react";
 
// A narrower sibling of the agent generative wizard (see
// apps/user/pages/agents/setup/GenerativeSetup.tsx), scoped to creating a
// standalone skillset. Skills-only by construction — svc-ai's schema for
// this flow has no tool/MCP-server field at all, so a generated skillset
// can never bundle either.
 
type Step = "describe" | "generating" | "review";
 
const EXAMPLES = [
  "Skills for triaging and resolving customer support tickets",
  "Skills for summarising and cross-referencing legal contracts",
  "Skills for onboarding new employees through HR policy Q&A",
];
 
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 GraphPreview: React.FC<{ graph: Record<string, unknown> }> = ({
  graph,
}) => {
  const [open, setOpen] = useState(false);
  return (
    <div className="mt-2">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
      >
        {open ? (
          <ChevronDown className="size-3.5" />
        ) : (
          <ChevronRight className="size-3.5" />
        )}
        Workflow graph
      </button>
      {open && (
        <pre className="mt-2 p-3 rounded-lg bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 text-[11px] leading-relaxed text-gray-600 dark:text-gray-300 overflow-x-auto max-h-64">
          {JSON.stringify(graph, null, 2)}
        </pre>
      )}
    </div>
  );
};
 
const GenerateSkillsetModal: React.FC<{ onClose: () => void }> = ({
  onClose,
}) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
 
  const [step, setStep] = useState<Step>("describe");
  const [description, setDescription] = useState("");
  const [modelId, setModelId] = useState("");
  const [generateError, setGenerateError] = useState<string | null>(null);
 
  const [proposal, setProposal] = useState<SkillsetGenerationProposal | null>(
    null,
  );
  const [name, setName] = useState("");
  const [bundleDescription, setBundleDescription] = useState("");
  const [includedExisting, setIncludedExisting] = useState<Set<string>>(
    new Set(),
  );
  const [proposedSkills, setProposedSkills] = useState<ProposedSkill[]>([]);
  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 { data: modelsData } = useQuery<Model[]>({
    queryKey: [QUERY_KEYS.GET.MODELS],
    queryFn: () => getApiHandler().model_router.list() as Promise<Model[]>,
  });
  const models: Model[] = (modelsData ?? []).filter(isSelectableModel);
 
  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;
  };
 
  const handleGenerate = async () => {
    setGenerateError(null);
    setStep("generating");
    try {
      const result = await getApiHandler().skillset_router.generateConfig({
        problem_description: description.trim(),
        ai_model_id: modelId || null,
      });
      setProposal(result);
      setName(result.name);
      setBundleDescription(result.description);
      // Unlike the agent wizard, a selected existing skill here genuinely
      // becomes a member if included — this flow creates the skillset
      // itself, so default every AI selection to included.
      setIncludedExisting(new Set(result.selected_skills.map((s) => s.id)));
      setProposedSkills(result.proposed_skills);
      setIncludedProposed(new Set(result.proposed_skills.map((_, i) => i)));
      setStep("review");
    } catch (e) {
      setGenerateError(
        errorDetail(e, "Could not generate a skillset. Please try again."),
      );
      setStep("describe");
    }
  };
 
  const handleCreate = async () => {
    Iif (!proposal) return;
    setCreating(true);
    setCreateError(null);
    const includedProposedSkills = proposedSkills.filter((_, i) =>
      includedProposed.has(i),
    );
    try {
      await getApiHandler().skillset_router.createFromConfig({
        name: name.trim(),
        description: bundleDescription.trim(),
        // Without it the skillset and its skills were stamped as generated
        // with no invocation to resolve to.
        generation_id: proposal.generation_id,
        existing_skill_ids: [...includedExisting],
        new_skills: [
          ...includedProposedSkills.map((s) => ({
            name: s.name.trim(),
            description: s.description,
            tags: s.tags,
            graph_definition: s.graph_definition,
          })),
        ],
      });
      await Promise.all(
        [QUERY_KEYS.GET.SKILLSETS, QUERY_KEYS.GET.SKILLS].map((key) =>
          queryClient.invalidateQueries({ queryKey: [key] }),
        ),
      );
      onClose();
    } catch (e) {
      setCreateError(
        errorDetail(e, "Could not create the skillset. Please try again."),
      );
    } finally {
      setCreating(false);
    }
  };
 
  const nothingToInclude =
    (proposal?.selected_skills.length ?? 0) === 0 &&
    proposedSkills.length === 0;
 
  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">
              Generate a Skillset
            </h2>
          </div>
          <button
            onClick={onClose}
            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 capability"
                description="Explain what these skills should let an agent do — the AI designs a cohesive, reusable set of skills around it. Never bundles tools or MCP servers; a human curates those on an existing skillset."
              >
                <div>
                  <FieldLabel
                    label="Capability description"
                    description="The more context you give, the better the generated skills."
                    required
                  />
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="e.g. Skills for triaging incoming support tickets, drafting responses from our documentation, and escalating billing issues."
                    rows={5}
                    className={inputBase + " resize-none"}
                  />
                </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">
                    {EXAMPLES.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 design the skills."
                    />
                    <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={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"
                >
                  <Sparkles className="size-4" />
                  Generate Skills
                </button>
              </div>
            </>
          )}
 
          {step === "generating" && (
            <div className="rounded-xl border border-gray-200 dark:border-gray-700 px-6 py-16 flex flex-col items-center text-center">
              <div className="relative mb-6">
                <div className="p-4 rounded-full bg-violet-100 dark:bg-violet-900/40">
                  <Sparkles className="size-7 text-violet-600 dark:text-violet-400" />
                </div>
                <Loader2 className="absolute -bottom-1 -right-1 size-5 animate-spin text-gray-400 dark:text-gray-500" />
              </div>
              <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Designing your skills…
              </p>
              <p className="text-xs text-gray-400 dark:text-gray-500 mt-2 max-w-sm">
                This usually takes under a minute.
              </p>
            </div>
          )}
 
          {step === "review" && proposal && (
            <>
              <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>
 
              {showDiff ? (
                <SectionCard
                  icon={GitCompare}
                  title="Proposed Skillset"
                  description="A preview of what will be created, in the same git-style diff used to view a skillset'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: bundleDescription,
                        },
                      ] as FieldDiff[]
                    }
                    fieldLabels={{ name: "Name", description: "Description" }}
                  />
                  <div className="mt-3 space-y-1 text-xs">
                    <p className="text-green-600 dark:text-green-400">
                      +{includedExisting.size + includedProposed.size} skill
                      {includedExisting.size + includedProposed.size === 1
                        ? ""
                        : "s"}{" "}
                      added
                    </p>
                  </div>
                </SectionCard>
              ) : (
                <SectionCard icon={Sparkles} title="Name your skillset">
                  <div>
                    <FieldLabel label="Name" required />
                    <input
                      type="text"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className={inputBase}
                    />
                  </div>
                  <div>
                    <FieldLabel label="Description" />
                    <textarea
                      value={bundleDescription}
                      onChange={(e) => setBundleDescription(e.target.value)}
                      rows={2}
                      className={inputBase + " resize-none"}
                    />
                  </div>
                  {proposal.reasoning && (
                    <p className="text-xs text-gray-400 dark:text-gray-500">
                      {proposal.reasoning}
                    </p>
                  )}
                </SectionCard>
              )}
 
              {nothingToInclude && (
                <div className="rounded-xl border border-gray-200 dark:border-gray-700 px-5 py-8 text-center">
                  <Zap className="size-5 text-gray-400 dark:text-gray-500 mx-auto mb-2" />
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    The AI didn't select or propose any skills. You can still
                    create an empty skillset and add skills to it afterward.
                  </p>
                </div>
              )}
 
              {proposal.selected_skills.length > 0 && (
                <SectionCard
                  icon={Zap}
                  title="Existing skills"
                  description="Skills the AI recommends bundling — yours, or built into the platform, which are included by reference rather than copied. Untick any you don't want."
                >
                  <div className="space-y-2">
                    {proposal.selected_skills.map((skill) => (
                      <ToggleRow
                        key={skill.id}
                        title={skill.name}
                        subtitle={skill.description}
                        meta={
                          (isSystemManaged(skill) || skill.tags.length > 0) && (
                            <>
                              {isSystemManaged(skill) && (
                                <BuiltInBadge size="sm" />
                              )}
                              {skill.tags.length > 0 && (
                                <>
                                  <Tag className="size-3" />
                                  {skill.tags.slice(0, 2).join(", ")}
                                </>
                              )}
                            </>
                          )
                        }
                        selected={includedExisting.has(skill.id)}
                        accent="violet"
                        onToggle={() =>
                          setIncludedExisting((prev) =>
                            toggled(prev, skill.id),
                          )
                        }
                      />
                    ))}
                  </div>
                </SectionCard>
              )}
 
              {proposedSkills.length > 0 && (
                <SectionCard
                  icon={Sparkles}
                  title="New skills designed for you"
                  description="Multi-step workflows the AI designed for this capability. Rename or exclude them; advanced graph editing is available after creation."
                >
                  <div className="space-y-2">
                    {proposedSkills.map((skill, index) => (
                      <ToggleRow
                        key={index}
                        title={skill.name}
                        selected={includedProposed.has(index)}
                        accent="amber"
                        onToggle={() =>
                          setIncludedProposed((prev) => toggled(prev, index))
                        }
                      >
                        {includedProposed.has(index) && (
                          <div className="mt-3 space-y-3">
                            <div>
                              <FieldLabel label="Name" required />
                              <input
                                type="text"
                                value={skill.name}
                                onChange={(e) =>
                                  setProposedSkills((prev) =>
                                    prev.map((s, i) =>
                                      i === index
                                        ? { ...s, name: e.target.value }
                                        : s,
                                    ),
                                  )
                                }
                                className={inputBase}
                              />
                            </div>
                            <div>
                              <FieldLabel label="Description" />
                              <textarea
                                value={skill.description}
                                onChange={(e) =>
                                  setProposedSkills((prev) =>
                                    prev.map((s, i) =>
                                      i === index
                                        ? {
                                            ...s,
                                            description: e.target.value,
                                          }
                                        : s,
                                    ),
                                  )
                                }
                                rows={2}
                                className={inputBase + " resize-none"}
                              />
                            </div>
                            <GraphPreview graph={skill.graph_definition} />
                          </div>
                        )}
                      </ToggleRow>
                    ))}
                  </div>
                </SectionCard>
              )}
 
              {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={onClose}
                  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"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={() => void handleCreate()}
                  disabled={creating || !name.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"
                >
                  {creating ? (
                    <>
                      <Loader2 className="size-4 animate-spin" />
                      Creating…
                    </>
                  ) : (
                    <>
                      <Check className="size-4" />
                      Create Skillset
                    </>
                  )}
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};
 
export default GenerateSkillsetModal;