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

7.2% Statements 8/111
0% Branches 0/59
0% Functions 0/55
8% Lines 8/100

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                                                                  2x                                                                                                                                                 2x                                                                                                         2x                                                                                   2x                                                                                                                                                                                                                                     2x           2x               2x           2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
import { encodeResourceId } from "@/components/detail";
import GeneratedMark from "@/components/badge/GeneratedMark";
import {
  CreateButton,
  FilterSelect,
  GenerateButton,
  ResourceCollection,
  SortSelect,
  useCollectionFilters,
} from "@/components/collection";
import { Toolkit } from "@/objects/Toolkit";
import { MCPServer } from "@/objects/MCPServer";
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,
  Hammer,
  Loader2,
  Plus,
  Server,
  Trash2,
  X,
} from "lucide-react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Link } from "react-router-dom";
import GenerateToolkitModal from "./toolkits/GenerateToolkitModal";
import { parseServerDate } from "@/util/time";
 
// ─── Create modal ─────────────────────────────────────────────────────────────
 
const CreateToolkitModal: 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 Toolkit
          </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 Toolkit"
              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 (generic over tools/MCP servers) ─────────────────────
 
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(() => {
    if (!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;
}> = ({ icon: Icon, label, members, available, onAdd, onRemove }) => (
  <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>
      <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>
            <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 toolkit`}
            >
              <X className="size-3" />
            </button>
          </span>
        ))}
      </div>
    ) : (
      <p className="text-xs text-gray-300 dark:text-gray-600 italic">None.</p>
    )}
  </div>
);
 
// ─── Toolkit card ───────────────────────────────────────────────────────────
 
const ToolkitCard: React.FC<{
  toolkit: Toolkit;
  mcpServerById: Map<string, MCPServer>;
  allMCPServers: MCPServer[];
  onDelete: () => void;
  deleting: boolean;
  onAddMCPServer: (id: string) => void;
  onRemoveMCPServer: (id: string) => void;
}> = ({
  toolkit,
  mcpServerById,
  allMCPServers,
  onDelete,
  deleting,
  onAddMCPServer,
  onRemoveMCPServer,
}) => {
  const mcpMembers = toolkit.mcp_server_ids
    .map((id) => mcpServerById.get(id))
    .filter((s): s is MCPServer => !!s);
 
  const mcpMemberIds = new Set(toolkit.mcp_server_ids);
 
  const totalMembers = mcpMembers.length;
 
  const href = APP_ROUTES.USER.INFERENCE.TOOLKITS.id.replace(
    ROUTE_PARAMS.TOOLKIT.id,
    encodeResourceId(toolkit.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={toolkit.is_ai_generated}
            label="AI generated toolkit"
          >
            <div className="p-2.5 rounded-lg bg-teal-100 dark:bg-teal-900/30 shrink-0">
              <Hammer className="size-5 text-teal-600 dark:text-teal-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">
                {toolkit.name}
              </div>
            </div>
            <div className="text-[10px] text-gray-400 dark:text-gray-500 mt-0.5">
              {totalMembers} member{totalMembers !== 1 ? "s" : ""}
            </div>
          </div>
        </div>
 
        {toolkit.description ? (
          <p className="text-xs text-gray-500 dark:text-gray-400 line-clamp-2 leading-relaxed">
            {toolkit.description}
          </p>
        ) : (
          <p className="text-xs text-gray-300 dark:text-gray-600 italic">
            No description.
          </p>
        )}
      </Link>
 
      <div className="px-5 pb-4 space-y-3">
        <MemberGroup
          icon={Server}
          label="MCP Servers"
          members={mcpMembers}
          available={allMCPServers.filter((s) => !mcpMemberIds.has(s.id))}
          onAdd={onAddMCPServer}
          onRemove={onRemoveMCPServer}
        />
      </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">
          {toolkit.created_at
            ? parseServerDate(toolkit.created_at).toLocaleDateString(undefined, {
                year: "numeric",
                month: "short",
                day: "numeric",
              })
            : "—"}
        </span>
        <div className="flex items-center gap-3">
          <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>
  );
};
 
// ─── ToolkitsContent ──────────────────────────────────────────────────────────
 
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 members" },
];
 
const ORIGIN_OPTIONS = [
  { value: "all", label: "Any origin" },
  { value: "generated", label: "AI generated" },
  { value: "manual", label: "Hand-built" },
];
 
// A toolkit holds MCP servers only, so "has tools" is gone. Empty replaces it:
// an empty toolkit grants an agent nothing, which is worth being able to find.
const CONTENT_OPTIONS = [
  { value: "all", label: "Any contents" },
  { value: "mcp", label: "Has MCP servers" },
  { value: "empty", label: "Empty" },
];
 
export const ToolkitsContent: 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;
    contents: string;
  }>({
    defaults: { sort: "recent", origin: "all", contents: "all" },
    unfiltered: ["sort"],
  });
  const { filters, setFilter, matches } = collection;
 
  const { data: toolkitData, isLoading } = useQuery<Toolkit[]>({
    queryKey: [QUERY_KEYS.GET.TOOLKITS],
    queryFn: () => getApiHandler().toolkit_router.list(),
  });
  const toolkits: Toolkit[] = useMemo(() => toolkitData ?? [], [toolkitData]);
 
  const { data: mcpServersData } = useQuery<MCPServer[]>({
    queryKey: [QUERY_KEYS.GET.USER_MCP_SERVERS],
    queryFn: () => getApiHandler().mcp_server_router.list(),
  });
  const allMCPServers: MCPServer[] = useMemo(
    () => mcpServersData ?? [],
    [mcpServersData],
  );
  const mcpServerById = useMemo(
    () => new Map(allMCPServers.map((s) => [s.id, s])),
    [allMCPServers],
  );
 
  const visible = useMemo(() => {
    const filtered = toolkits.filter((toolkit) => {
      // Member names are searchable too: users look for the bundle holding a
      // server more often than they recall what they named the bundle.
      const memberNames = toolkit.mcp_server_ids
        .map((id) => mcpServerById.get(id)?.name)
        .filter((n): n is string => !!n);
      const matchesOrigin =
        filters.origin === "all" ||
        (filters.origin === "generated"
          ? !!toolkit.is_ai_generated
          : !toolkit.is_ai_generated);
      const matchesContents =
        filters.contents === "all" ||
        (filters.contents === "empty"
          ? toolkit.mcp_server_ids.length === 0
          : toolkit.mcp_server_ids.length > 0);
      return (
        matchesOrigin &&
        matchesContents &&
        matches(toolkit.name, toolkit.description, ...memberNames)
      );
    });
 
    const size = (t: Toolkit) => t.mcp_server_ids.length;
    const byName = (a: Toolkit, b: Toolkit) => a.name.localeCompare(b.name);
    return [...filtered].sort((a, b) => {
      if (filters.sort === "name") return byName(a, b);
      if (filters.sort === "members") return size(b) - size(a) || byName(a, b);
      return (
        (b.created_at ?? "").localeCompare(a.created_at ?? "") || byName(a, b)
      );
    });
  }, [toolkits, mcpServerById, filters, matches]);
 
  const invalidate = () =>
    void queryClient.invalidateQueries({
      queryKey: [QUERY_KEYS.GET.TOOLKITS],
    });
 
  const createMutation = useMutation({
    mutationFn: ({
      name,
      description,
    }: {
      name: string;
      description: string;
    }) =>
      getApiHandler().toolkit_router.create({
        name,
        description: description || undefined,
      }),
    onSuccess: () => {
      invalidate();
      setShowModal(false);
    },
  });
 
  const deleteMutation = useMutation({
    mutationFn: (id: string) => getApiHandler().toolkit_router.delete(id),
    onSuccess: invalidate,
    onSettled: () => setDeletingId(null),
  });
 
  const addMCPServerMutation = useMutation({
    mutationFn: ({ id, mcpServerId }: { id: string; mcpServerId: string }) =>
      getApiHandler().toolkit_router.addMCPServer(id, mcpServerId),
    onSuccess: invalidate,
  });
  const removeMCPServerMutation = useMutation({
    mutationFn: ({ id, mcpServerId }: { id: string; mcpServerId: string }) =>
      getApiHandler().toolkit_router.removeMCPServer(id, mcpServerId),
    onSuccess: invalidate,
  });
 
  const createButton = (
    <CreateButton label="New Toolkit" onClick={() => setShowModal(true)} />
  );
  const generateButton = (
    <GenerateButton onClick={() => setShowGenerateModal(true)} />
  );
 
  return (
    <>
      {showModal && (
        <CreateToolkitModal
          onClose={() => setShowModal(false)}
          onCreate={(name, description) =>
            createMutation.mutate({ name, description })
          }
          loading={createMutation.isPending}
        />
      )}
 
      {showGenerateModal && (
        <GenerateToolkitModal onClose={() => setShowGenerateModal(false)} />
      )}
 
      <ResourceCollection<Toolkit>
        description="Bundle MCP servers into named, reusable collections. Attach a toolkit to an agent to grant its whole bundle in one step — the only way to give an agent MCP server access. Built-in tools need no grant: every agent has them. Skills are bundled the same way via a Skillset instead."
        stats={[
          { label: "Toolkits", value: toolkits.length, loading: isLoading },
          {
            label: "MCP servers bundled",
            value: new Set(toolkits.flatMap((t) => t.mcp_server_ids)).size,
            loading: isLoading,
          },
        ]}
        shown={visible.length}
        search={{
          value: collection.search,
          onChange: collection.setSearch,
          placeholder: "Search toolkits or their members…",
        }}
        filters={
          <>
            <SortSelect
              value={filters.sort}
              onChange={(value) => setFilter("sort", value)}
              options={SORT_OPTIONS}
              defaultValue="recent"
            />
            <FilterSelect
              value={filters.contents}
              onValueChange={(value) => setFilter("contents", value)}
              placeholder="Any contents"
              options={CONTENT_OPTIONS}
              active={filters.contents !== "all"}
            />
            {toolkits.some((t) => t.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}
          </>
        }
        items={visible}
        itemKey={(toolkit) => toolkit.id}
        loading={isLoading}
        skeletonCount={3}
        renderCard={(toolkit) => (
          <ToolkitCard
            toolkit={toolkit}
            mcpServerById={mcpServerById}
            allMCPServers={allMCPServers}
            onDelete={() => {
              setDeletingId(toolkit.id);
              deleteMutation.mutate(toolkit.id);
            }}
            deleting={deletingId === toolkit.id}
            onAddMCPServer={(mcpServerId) =>
              addMCPServerMutation.mutate({ id: toolkit.id, mcpServerId })
            }
            onRemoveMCPServer={(mcpServerId) =>
              removeMCPServerMutation.mutate({ id: toolkit.id, mcpServerId })
            }
          />
        )}
        empty={{
          Icon: Hammer,
          title: "No toolkits yet.",
          hint: "Create a toolkit to group tools and MCP servers into a bundle — or describe the use case and let the AI recommend one.",
          dashed: true,
          action: (
            <div className="flex items-center gap-2">
              {generateButton}
              {createButton}
            </div>
          ),
        }}
        emptyFilteredTitle="No toolkits match your filters."
        emptyFilteredHint="Try adjusting your search or filters."
      />
    </>
  );
};
 
export default ToolkitsContent;