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

60% Statements 45/75
76.38% Branches 55/72
43.24% Functions 16/37
60.86% Lines 42/69

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                                                                                  2x         3x 3x   3x 3x                 3x                                                                     2x                                     4x                         1x                                                   2x 8x 8x 8x 8x 8x   8x           8x     4x 4x             8x   4x   8x 8x 8x       8x         8x           8x         8x           8x                   8x   8x     8x 1x 1x 8x   8x   8x                                                   8x                                                                                                   12x                                                                                                                                               1x   1x                         1x                                                                                                                                      
import { MoveToShared, WorkspaceGuard } from "@/components/owner";
import BuiltInBadge from "@/components/badge/BuiltInBadge";
import GeneratedMark from "@/components/badge/GeneratedMark";
import AIProvenance from "@/components/badge/AIProvenance";
import ResourceHistorySection from "@/components/diff/ResourceHistorySection/ResourceHistorySection";
import InlineEdit from "@/components/field/InlineEdit/InlineEdit";
import SubPage from "@/components/page/SubPage/SubPage";
import { isSystemManaged } from "@/objects/Doc";
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 {
  Calendar,
  ChevronDown,
  Copy,
  Info,
  Layers3,
  Plus,
  Trash2,
  X,
  Zap,
} from "lucide-react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import {
  CopyButton,
  MetaItem,
  SectionCard,
  Skeleton,
  encodeResourceId,
} from "@/components/detail";
import { parseServerDate } from "@/util/time";
 
// ─── Primitives (mirrors Skill.tsx / ToolViewer.tsx) ───────────────────────────
 
// ─── Member management (mirrors Skillsets.tsx) ─────────────────────────────────
 
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
        type="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}
              type="button"
              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>
  );
};
 
const MemberGroup: React.FC<{
  icon: React.ElementType;
  label: string;
  members: MemberOption[];
  available: MemberOption[];
  onAdd: (id: string) => void;
  onRemove: (id: string) => void;
  saving?: boolean;
  readOnly?: boolean;
}> = ({
  icon: Icon,
  label,
  members,
  available,
  onAdd,
  onRemove,
  saving,
  readOnly,
}) => (
  <div className="space-y-2">
    <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-56">{m.name}</span>
            {!readOnly && (
              <button
                type="button"
                onClick={() => onRemove(m.id)}
                disabled={saving}
                className="text-gray-300 dark:text-gray-500 hover:text-red-500 dark:hover:text-red-400 transition-colors disabled:opacity-40"
              >
                <X className="size-3" />
              </button>
            )}
          </span>
        ))}
      </div>
    ) : (
      <p className="text-xs text-gray-300 dark:text-gray-600 italic">None.</p>
    )}
  </div>
);
 
// ─── SkillsetViewer ─────────────────────────────────────────────────────────
 
const SkillsetViewer: React.FC = () => {
  const { skillsetId } = useParams();
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const [confirmDelete, setConfirmDelete] = useState(false);
 
  const decodedId = skillsetId ? atob(skillsetId) : null;
 
  const {
    data: skillset,
    error,
    isLoading,
  } = useQuery({
    queryKey: [QUERY_KEYS.GET.SKILLSET_BY_ID, decodedId],
    queryFn: async () => {
      Iif (!decodedId) return null;
      return getApiHandler().skillset_router.getById(decodedId);
    },
    enabled: !!decodedId,
  });
 
  // A built-in skillset's members are built-in skills, and the user's own
  // skillsets may bundle them — so the skill list includes them.
  const { data: skillsData } = useQuery({
    queryKey: [QUERY_KEYS.GET.SKILLS, "include_system"],
    queryFn: () => getApiHandler().skill_router.list({ include_system: true }),
  });
  const allSkills = useMemo(() => skillsData ?? [], [skillsData]);
  const skillById = useMemo(
    () => new Map(allSkills.map((s: Skill) => [s.id, s])),
    [allSkills],
  );
 
  const invalidate = () =>
    void queryClient.invalidateQueries({
      queryKey: [QUERY_KEYS.GET.SKILLSET_BY_ID, decodedId],
    });
 
  const updateMutation = useMutation({
    mutationFn: (body: { name?: string; description?: string }) =>
      getApiHandler().skillset_router.update(decodedId!, body),
    onSuccess: invalidate,
  });
 
  const addSkillMutation = useMutation({
    mutationFn: (skillId: string) =>
      getApiHandler().skillset_router.addSkill(decodedId!, skillId),
    onSuccess: invalidate,
  });
  const removeSkillMutation = useMutation({
    mutationFn: (skillId: string) =>
      getApiHandler().skillset_router.removeSkill(decodedId!, skillId),
    onSuccess: invalidate,
  });
 
  const deleteMutation = useMutation({
    mutationFn: () => getApiHandler().skillset_router.delete(decodedId!),
    onSuccess: () => {
      void queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.SKILLSETS],
      });
      void navigate(APP_ROUTES.USER.INFERENCE.skillsets);
    },
  });
 
  Iif (!skillsetId)
    return <div className="p-4 text-red-500">Invalid skillset ID.</div>;
  Iif (error)
    return <div className="p-4 text-red-500">Error: {error.toString()}</div>;
 
  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 actionLinks = isLoading
    ? []
    : [
        <CopyButton
          key="copy"
          value={skillset?.name ?? ""}
          label="Copy Name"
        />,
        !readOnly && skillset && (
          <MoveToShared key="move" kind="skillset" resource={skillset} />
        ),
        readOnly ? (
          <BuiltInBadge key="built-in" />
        ) : (
          <button
            key="del"
            type="button"
            onClick={() => setConfirmDelete(true)}
            className="flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg border border-red-200 dark:border-red-800 text-red-500 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/30 transition-colors"
          >
            <Trash2 className="size-3" />
            Delete
          </button>
        ),
      ];
 
  return (
    <>
      <SubPage
        title={
          isLoading ? (
            <Skeleton className="h-7 w-48" />
          ) : (
            (skillset?.name ?? "—")
          )
        }
        title_icon={
          <GeneratedMark
            generated={skillset?.is_ai_generated}
            size="lg"
            label="AI generated skillset"
          >
            <div className="p-2.5 rounded-xl bg-amber-100 dark:bg-amber-900/30 shrink-0">
              <Layers3 className="size-7 text-amber-600 dark:text-amber-400" />
            </div>
          </GeneratedMark>
        }
        links={actionLinks}
        back={APP_ROUTES.USER.INFERENCE.skillsets}
      >
        <WorkspaceGuard resource={skillset} noun="skillset" copyKind="skillset" />
        {skillset?.is_ai_generated && (
          <AIProvenance
            resourceLabel="skillset"
            generationId={skillset.generation_id}
            generatedByAgentId={skillset.generated_by_agent_id}
            resourceId={skillset.id}
            className="mb-4"
          />
        )}
 
        {readOnly && (
          <p
            role="note"
            className="mb-4 text-xs leading-relaxed text-indigo-900 dark:text-indigo-200 rounded-xl border border-indigo-200 dark:border-indigo-800/70 bg-indigo-50/70 dark:bg-indigo-950/30 px-4 py-3"
          >
            Maintained by CHAIN-R and updated with platform releases. Grant it
            to your own agents from an agent's Skillsets tab, or open a skill below
            to run it on its own. It cannot be edited.
          </p>
        )}
 
        {/* Metadata strip */}
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-5 p-5 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm mb-4">
          {isLoading ? (
            Array.from({ length: 3 }).map((_, i) => (
              <div key={i} className="flex flex-col gap-1.5">
                <Skeleton className="h-3 w-16" />
                <Skeleton className="h-4 w-24" />
              </div>
            ))
          ) : (
            <>
              <MetaItem
                icon={Layers3}
                label="Name"
                value={
                  readOnly ? (
                    skillset?.name
                  ) : (
                    <InlineEdit
                      value={skillset?.name ?? ""}
                      placeholder="Unnamed skillset"
                      saving={updateMutation.isPending}
                      onSave={(v) => updateMutation.mutate({ name: v })}
                    />
                  )
                }
              />
              <MetaItem
                icon={Info}
                label="Description"
                value={
                  readOnly ? (
                    skillset?.description
                  ) : (
                    <InlineEdit
                      value={skillset?.description ?? ""}
                      placeholder="No description"
                      multiline
                      saving={updateMutation.isPending}
                      onSave={(v) => updateMutation.mutate({ description: v })}
                    />
                  )
                }
              />
              <MetaItem
                icon={Calendar}
                label="Created"
                value={
                  skillset?.created_at
                    ? parseServerDate(skillset.created_at).toLocaleDateString(
                        undefined,
                        { year: "numeric", month: "short", day: "numeric" },
                      )
                    : "—"
                }
              />
            </>
          )}
        </div>
 
        {/* Skills */}
        <SectionCard
          icon={Zap}
          title="Skills"
          subtitle={`${skillMembers.length} member${skillMembers.length !== 1 ? "s" : ""}`}
          className="mb-4"
        >
          {isLoading ? (
            <div className="flex gap-1.5">
              <Skeleton className="h-6 w-24 rounded-lg" />
              <Skeleton className="h-6 w-24 rounded-lg" />
            </div>
          ) : (
            <MemberGroup
              icon={Zap}
              label="Bundled skills"
              members={skillMembers.map((s) => ({ id: s.id, name: s.name }))}
              available={allSkills
                .filter((s: Skill) => !skillMemberIds.has(s.id))
                .map((s: Skill) => ({ id: s.id, name: s.name }))}
              onAdd={(id) => addSkillMutation.mutate(id)}
              onRemove={(id) => removeSkillMutation.mutate(id)}
              saving={
                addSkillMutation.isPending || removeSkillMutation.isPending
              }
              readOnly={readOnly}
            />
          )}
          {!isLoading && skillMembers.length > 0 && (
            <div className="flex flex-wrap gap-2 mt-4">
              {skillMembers.map((s) => (
                <Link
                  key={s.id}
                  to={APP_ROUTES.USER.INFERENCE.SKILLS.id.replace(
                    ROUTE_PARAMS.SKILL.id,
                    encodeResourceId(s.id),
                  )}
                  className="text-xs font-medium text-violet-600 dark:text-violet-400 hover:underline"
                >
                  View “{s.name}” →
                </Link>
              ))}
            </div>
          )}
        </SectionCard>
 
        {/* Edit history */}
        <ResourceHistorySection
          className="mb-4"
          source={getApiHandler().skillset_router}
          resourceId={decodedId}
          queryKey={QUERY_KEYS.GET.SKILLSET_HISTORY}
          fieldLabels={{ name: "Name", description: "Description" }}
        />
      </SubPage>
 
      {/* Delete modal */}
      {confirmDelete && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40">
          <div className="w-full max-w-sm rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 shadow-xl p-6 space-y-4">
            <div className="flex items-center gap-2">
              <Trash2 className="size-5 text-red-500" />
              <h2 className="text-sm font-semibold text-gray-800 dark:text-gray-200">
                Delete Skillset
              </h2>
            </div>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Are you sure you want to delete{" "}
              <span className="font-medium text-gray-800 dark:text-gray-200">
                {skillset?.name}
              </span>
              ? Agents using this skillset will lose access to its skills.
            </p>
            <div className="flex items-center justify-end gap-3">
              <button
                type="button"
                onClick={() => setConfirmDelete(false)}
                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={() => deleteMutation.mutate()}
                disabled={deleteMutation.isPending}
                className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-red-600 text-white text-sm font-medium hover:opacity-80 disabled:opacity-50 transition-opacity"
              >
                {deleteMutation.isPending ? "Deleting…" : "Delete"}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
};
 
export default SkillsetViewer;