All files / src/apps/user/pages Skillsets.tsx

61.4% Statements 70/114
45.31% Branches 29/64
48.27% Functions 28/58
63.8% Lines 67/105

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                                                                              3x                                                                                                                                                 3x         3x 3x   3x 3x                 3x                                                                     3x                   6x                         3x                                                 3x                                 6x 3x 3x   6x   6x   6x         6x                                                                                     6x                                                                                               3x           3x           3x 9x 9x 9x 9x 9x     9x             9x         9x   4x   9x 9x 9x   6x       9x   4x   9x 9x 9x       9x       6x       3x 3x         9x 9x       9x 9x   3x       3x     9x 9x                   9x         9x                                   9x           9x         9x             9x     9x 6x                                   9x     9x                                           3x         3x                                   3x                                           3x                   3x                                                        
import {
  OriginBadge,
} from "@/components/owner";
import { encodeResourceId } from "@/components/detail";
import BuiltInBadge from "@/components/badge/BuiltInBadge";
import GeneratedMark from "@/components/badge/GeneratedMark";
import {
  collectionSection,
  CreateButton,
  FilterSelect,
  GenerateButton,
  ResourceCollection,
  SortSelect,
  useCollectionFilters,
} from "@/components/collection";
import { isSystemManaged } from "@/objects/Doc";
import { Skillset } from "@/objects/Skillset";
import { Skill } from "@/objects/Skill";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  ChevronDown,
  ChevronRight,
  Layers3,
  Loader2,
  Plus,
  Trash2,
  X,
  Zap,
} from "lucide-react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Link } from "react-router-dom";
import GenerateSkillsetModal from "./skillsets/GenerateSkillsetModal";
import { parseServerDate } from "@/util/time";
 
// ─── Create modal ─────────────────────────────────────────────────────────────
 
const CreateSkillsetModal: React.FC<{
  onClose: () => void;
  onCreate: (name: string, description: string) => void;
  loading: boolean;
}> = ({ onClose, onCreate, loading }) => {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const inputCls =
    "w-full rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 px-3 py-2 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-500";
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-md p-6">
        <div className="flex items-center justify-between mb-5">
          <h3 className="text-sm font-semibold text-gray-900 dark:text-gray-100">
            New Skillset
          </h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
          >
            <X className="size-4" />
          </button>
        </div>
        <div className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
              Name
            </label>
            <input
              autoFocus
              className={inputCls}
              placeholder="e.g. Support Bundle"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
              Description <span className="text-gray-400">(optional)</span>
            </label>
            <textarea
              rows={3}
              className={inputCls + " resize-none"}
              placeholder="What capability does this bundle group?"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>
        </div>
        <div className="flex justify-end gap-2 mt-5">
          <button
            onClick={onClose}
            className="px-3 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
            disabled={!name.trim() || loading}
            onClick={() => onCreate(name.trim(), description.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 transition-opacity disabled:opacity-40"
          >
            {loading ? "Creating…" : "Create"}
          </button>
        </div>
      </div>
    </div>
  );
};
 
// ─── Add member dropdown ───────────────────────────────────────────────────────
 
type MemberOption = { id: string; name: string };
 
const AddMemberMenu: React.FC<{
  label: string;
  available: MemberOption[];
  onAdd: (id: string) => void;
}> = ({ label, available, onAdd }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
 
  useEffect(() => {
    Eif (!open) return;
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node))
        setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);
 
  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen((v) => !v)}
        disabled={available.length === 0}
        className="flex items-center gap-1 text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors disabled:opacity-40"
      >
        <Plus className="size-3.5" />
        {label}
        <ChevronDown
          className={`size-3 transition-transform ${open ? "rotate-180" : ""}`}
        />
      </button>
      {open && (
        <div className="absolute left-0 top-full mt-1.5 z-50 min-w-56 max-h-56 overflow-y-auto rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-lg py-1">
          {available.map((item) => (
            <button
              key={item.id}
              onClick={() => {
                onAdd(item.id);
                setOpen(false);
              }}
              className="flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/60 transition-colors"
            >
              <span className="truncate">{item.name}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
};
 
// ─── Member chip group ─────────────────────────────────────────────────────────
 
const MemberGroup: React.FC<{
  icon: React.ElementType;
  label: string;
  members: MemberOption[];
  available: MemberOption[];
  onAdd: (id: string) => void;
  onRemove: (id: string) => void;
  /** A built-in skillset: members are listed, never added or removed. */
  readOnly?: boolean;
}> = ({ icon: Icon, label, members, available, onAdd, onRemove, readOnly }) => (
  <div className="space-y-1.5">
    <div className="flex items-center justify-between">
      <div className="flex items-center gap-1.5 text-[10px] font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wide">
        <Icon className="size-3" />
        {label}
      </div>
      {!readOnly && (
        <AddMemberMenu label="Add" available={available} onAdd={onAdd} />
      )}
    </div>
    {members.length > 0 ? (
      <div className="flex flex-wrap gap-1.5">
        {members.map((m) => (
          <span
            key={m.id}
            className="group/chip inline-flex items-center gap-1.5 pl-2 pr-1.5 py-1 rounded-lg bg-gray-50 dark:bg-gray-700/50 border border-gray-100 dark:border-gray-600 text-xs text-gray-600 dark:text-gray-300"
          >
            <span className="truncate max-w-36">{m.name}</span>
            {!readOnly && (
              <button
                onClick={() => onRemove(m.id)}
                className="text-gray-300 dark:text-gray-500 hover:text-red-500 dark:hover:text-red-400 transition-colors"
                title={`Remove from skillset`}
              >
                <X className="size-3" />
              </button>
            )}
          </span>
        ))}
      </div>
    ) : (
      <p className="text-xs text-gray-300 dark:text-gray-600 italic">None.</p>
    )}
  </div>
);
 
// ─── Skillset card ──────────────────────────────────────────────────────────
 
const SkillsetCard: React.FC<{
  skillset: Skillset;
  skillById: Map<string, Skill>;
  allSkills: Skill[];
  onDelete: () => void;
  deleting: boolean;
  onAddSkill: (id: string) => void;
  onRemoveSkill: (id: string) => void;
}> = ({
  skillset,
  skillById,
  allSkills,
  onDelete,
  deleting,
  onAddSkill,
  onRemoveSkill,
}) => {
  const skillMembers = skillset.skill_ids
    .map((id) => skillById.get(id))
    .filter((s): s is Skill => !!s);
 
  const skillMemberIds = new Set(skillset.skill_ids);
  // Built-in: the API refuses every write, so none is offered.
  const readOnly = isSystemManaged(skillset);
 
  const href = APP_ROUTES.USER.INFERENCE.SKILLSETS.id.replace(
    ROUTE_PARAMS.SKILLSET.id,
    encodeResourceId(skillset.id),
  );
 
  return (
    <div className="group flex flex-col rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm hover:shadow-md hover:border-gray-300 dark:hover:border-gray-500 transition-all overflow-hidden">
      <Link to={href} className="flex-1 p-5 flex flex-col gap-4">
        <div className="flex items-center gap-3 min-w-0">
          <GeneratedMark
            generated={skillset.is_ai_generated}
            label="AI generated skillset"
          >
            <div className="p-2.5 rounded-lg bg-amber-100 dark:bg-amber-900/30 shrink-0">
              <Layers3 className="size-5 text-amber-600 dark:text-amber-400" />
            </div>
          </GeneratedMark>
          <div className="min-w-0">
            <div className="flex items-center gap-1.5 min-w-0">
              <div className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
                {skillset.name}
              </div>
              {readOnly && <BuiltInBadge size="sm" />}
              <OriginBadge resource={skillset} />
            </div>
            <div className="text-[10px] text-gray-400 dark:text-gray-500 mt-0.5">
              {skillMembers.length} member
              {skillMembers.length !== 1 ? "s" : ""}
            </div>
          </div>
        </div>
 
        {skillset.description ? (
          <p className="text-xs text-gray-500 dark:text-gray-400 line-clamp-2 leading-relaxed">
            {skillset.description}
          </p>
        ) : (
          <p className="text-xs text-gray-300 dark:text-gray-600 italic">
            No description.
          </p>
        )}
      </Link>
 
      <div className="px-5 pb-4">
        <MemberGroup
          icon={Zap}
          label="Skills"
          members={skillMembers}
          available={allSkills.filter((s) => !skillMemberIds.has(s.id))}
          onAdd={onAddSkill}
          onRemove={onRemoveSkill}
          readOnly={readOnly}
        />
      </div>
 
      <div className="flex items-center justify-between px-5 py-3 border-t border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
        <span className="text-[10px] text-gray-400 dark:text-gray-500">
          {skillset.created_at
            ? parseServerDate(skillset.created_at).toLocaleDateString(undefined, {
                year: "numeric",
                month: "short",
                day: "numeric",
              })
            : "—"}
        </span>
        <div className="flex items-center gap-3">
          {!readOnly && (
            <button
              onClick={onDelete}
              disabled={deleting}
              className="shrink-0 text-gray-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 transition-colors disabled:opacity-40"
            >
              {deleting ? (
                <Loader2 className="size-4 animate-spin" />
              ) : (
                <Trash2 className="size-4" />
              )}
            </button>
          )}
          <Link
            to={href}
            className="flex items-center gap-1 text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
          >
            View
            <ChevronRight className="size-3.5" />
          </Link>
        </div>
      </div>
    </div>
  );
};
 
// ─── SkillsetsContent ─────────────────────────────────────────────────────────
 
type SortKey = "recent" | "name" | "members";
 
const SORT_OPTIONS: { value: SortKey; label: string }[] = [
  { value: "recent", label: "Newest first" },
  { value: "name", label: "Name (A-Z)" },
  { value: "members", label: "Most skills" },
];
 
const ORIGIN_OPTIONS = [
  { value: "all", label: "Any origin" },
  { value: "generated", label: "AI generated" },
  { value: "manual", label: "Hand-built" },
];
 
export const SkillsetsContent: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const [showModal, setShowModal] = useState(false);
  const [showGenerateModal, setShowGenerateModal] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
 
  // Sort is excluded from the active-filter count: reordering hides nothing.
  const collection = useCollectionFilters<{
    sort: SortKey;
    origin: string;
  }>({
    defaults: { sort: "recent", origin: "all" },
    unfiltered: ["sort"],
  });
  const { filters, setFilter, matches } = collection;
 
  // Built-in skillsets come with the user's own, and are split out below:
  // this page is where they are found, but the counts are what the user
  // built. Their skills are built-in too, so the skill list asks for those.
  const { data: skillsetData, isLoading } = useQuery<Skillset[]>({
    queryKey: [QUERY_KEYS.GET.SKILLSETS, "include_system"],
    queryFn: () => getApiHandler().skillset_router.list({ includeSystem: true }),
  });
  const { builtIn, skillsets } = useMemo(() => {
    const rows: Skillset[] = skillsetData ?? [];
    return {
      builtIn: rows.filter(isSystemManaged),
      skillsets: rows.filter((s) => !isSystemManaged(s)),
    };
  }, [skillsetData]);
 
  const { data: skillsData } = useQuery<Skill[]>({
    queryKey: [QUERY_KEYS.GET.SKILLS, "include_system"],
    queryFn: () => getApiHandler().skill_router.list({ include_system: true }),
  });
  const allSkills: Skill[] = useMemo(() => skillsData ?? [], [skillsData]);
  const skillById = useMemo(
    () => new Map(allSkills.map((s) => [s.id, s])),
    [allSkills],
  );
 
  const matchesSearch = React.useCallback(
    (skillset: Skillset) =>
      // Member names are searchable too: users look for the bundle holding a
      // skill more often than they recall what they named the bundle.
      matches(
        skillset.name,
        skillset.description,
        ...skillset.skill_ids
          .map((id) => skillById.get(id)?.name)
          .filter((n): n is string => !!n),
      ),
    [matches, skillById],
  );
 
  const visibleBuiltIn = useMemo(
    () => builtIn.filter(matchesSearch),
    [builtIn, matchesSearch],
  );
 
  const visible = useMemo(() => {
    const filtered = skillsets.filter((skillset) => {
      const matchesOrigin =
        filters.origin === "all" ||
        (filters.origin === "generated"
          ? !!skillset.is_ai_generated
          : !skillset.is_ai_generated);
      return matchesOrigin && matchesSearch(skillset);
    });
 
    const byName = (a: Skillset, b: Skillset) => a.name.localeCompare(b.name);
    return [...filtered].sort((a, b) => {
      if (filters.sort === "name") return byName(a, b);
      if (filters.sort === "members")
        return b.skill_ids.length - a.skill_ids.length || byName(a, b);
      return (
        (b.created_at ?? "").localeCompare(a.created_at ?? "") || byName(a, b)
      );
    });
  }, [skillsets, filters, matchesSearch]);
 
  const invalidate = () =>
    void queryClient.invalidateQueries({
      queryKey: [QUERY_KEYS.GET.SKILLSETS],
    });
 
  const createMutation = useMutation({
    mutationFn: ({
      name,
      description,
    }: {
      name: string;
      description: string;
    }) =>
      getApiHandler().skillset_router.create({
        name,
        description: description || undefined,
      }),
    onSuccess: () => {
      invalidate();
      setShowModal(false);
    },
  });
 
  const deleteMutation = useMutation({
    mutationFn: (id: string) => getApiHandler().skillset_router.delete(id),
    onSuccess: invalidate,
    onSettled: () => setDeletingId(null),
  });
 
  const addSkillMutation = useMutation({
    mutationFn: ({ id, skillId }: { id: string; skillId: string }) =>
      getApiHandler().skillset_router.addSkill(id, skillId),
    onSuccess: invalidate,
  });
  const removeSkillMutation = useMutation({
    mutationFn: ({ id, skillId }: { id: string; skillId: string }) =>
      getApiHandler().skillset_router.removeSkill(id, skillId),
    onSuccess: invalidate,
  });
 
  const createButton = (
    <CreateButton label="New Skillset" onClick={() => setShowModal(true)} />
  );
 
  const renderCard = (skillset: Skillset) => (
    <SkillsetCard
      skillset={skillset}
      skillById={skillById}
      allSkills={allSkills}
      onDelete={() => {
        setDeletingId(skillset.id);
        deleteMutation.mutate(skillset.id);
      }}
      deleting={deletingId === skillset.id}
      onAddSkill={(skillId) =>
        addSkillMutation.mutate({ id: skillset.id, skillId })
      }
      onRemoveSkill={(skillId) =>
        removeSkillMutation.mutate({ id: skillset.id, skillId })
      }
    />
  );
  const generateButton = (
    <GenerateButton onClick={() => setShowGenerateModal(true)} />
  );
 
  return (
    <>
      {showModal && (
        <CreateSkillsetModal
          onClose={() => setShowModal(false)}
          onCreate={(name, description) =>
            createMutation.mutate({ name, description })
          }
          loading={createMutation.isPending}
        />
      )}
 
      {showGenerateModal && (
        <GenerateSkillsetModal onClose={() => setShowGenerateModal(false)} />
      )}
 
      <ResourceCollection<Skillset>
        description="Bundle skills into named, reusable collections. Attach a skillset to an agent to grant its whole bundle in one step — the only way to give an agent a skill."
        stats={[
          { label: "Skillsets", value: skillsets.length, loading: isLoading },
          {
            label: "Skills bundled",
            value: new Set(skillsets.flatMap((s) => s.skill_ids)).size,
            loading: isLoading,
          },
          {
            label: "AI generated",
            value: skillsets.filter((s) => s.is_ai_generated).length,
            loading: isLoading,
          },
        ]}
        shown={visible.length + visibleBuiltIn.length}
        search={{
          value: collection.search,
          onChange: collection.setSearch,
          placeholder: "Search skillsets or their skills…",
        }}
        filters={
          <>
            <SortSelect
              value={filters.sort}
              onChange={(value) => setFilter("sort", value)}
              options={SORT_OPTIONS}
              defaultValue="recent"
            />
            {skillsets.some((s) => s.is_ai_generated) && (
              <FilterSelect
                value={filters.origin}
                onValueChange={(value) => setFilter("origin", value)}
                placeholder="Any origin"
                options={ORIGIN_OPTIONS}
                active={filters.origin !== "all"}
              />
            )}
          </>
        }
        {...collection.toolbarProps}
        actions={
          <>
            {generateButton}
            {createButton}
          </>
        }
        sections={[
          collectionSection<Skillset>({
            label: "Built-in",
            items: visibleBuiltIn,
            itemKey: (skillset) => skillset.id,
            renderCard,
            loading: isLoading,
            skeletonCount: 2,
            hideWhenEmpty: true,
            empty: { Icon: Layers3, title: "No built-in skillsets." },
          }),
          collectionSection<Skillset>({
            label: "Your skillsets",
            items: visible,
            itemKey: (skillset) => skillset.id,
            renderCard,
            loading: isLoading,
            skeletonCount: 3,
            empty: {
              Icon: Layers3,
              title: "No skillsets of your own yet.",
              hint:
                builtIn.length > 0
                  ? "The built-in skillsets are ready to grant to an agent now. Create your own to bundle skills you build — or describe the capability you want and let the AI design one."
                  : "Create a skillset to group skills into a bundle — or describe the capability you want and let the AI design one.",
              dashed: true,
              action: (
                <div className="flex items-center gap-2">
                  {generateButton}
                  {createButton}
                </div>
              ),
            },
            emptyFilteredTitle: "No skillsets match your filters.",
          }),
        ]}
      />
    </>
  );
};
 
export default SkillsetsContent;