All files / src/apps/user/pages/toolkits GenerateToolkitModal.tsx

4.28% Statements 3/70
0% Branches 0/43
0% Functions 0/22
4.54% Lines 3/66

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                                                                        2x           2x             2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
import {
  FieldLabel,
  SectionCard,
  ToggleRow,
  inputBase,
} from "@/apps/user/pages/agents/setup/primitives";
import DiffViewer from "@/components/diff/DiffViewer/DiffViewer";
import { FieldDiff } from "@/objects/History";
import { Model, isSelectableModel, modelDisplayName } from "@/objects/Model";
import { ToolkitGenerationProposal } from "@/objects/ToolkitSetup";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertCircle,
  Check,
  GitCompare,
  Hammer,
  Lightbulb,
  Loader2,
  Server,
  Sparkles,
  X,
} 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 toolkit. Existing-resources-only by construction — svc-ai's
// schema for this flow has no proposed-new-resource field at all, so a
// generated toolkit can only ever select/bundle MCP servers that already
// exist (they carry live credentials only a human can safely configure).
// Built-in tools are not members: every agent has them already.
 
type Step = "describe" | "generating" | "review";
 
const EXAMPLES = [
  "Tools for triaging and resolving customer support tickets",
  "Tools for researching and summarising web content",
  "Tools for querying internal databases and dashboards",
];
 
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 GenerateToolkitModal: 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<ToolkitGenerationProposal | null>(
    null,
  );
  const [name, setName] = useState("");
  const [bundleDescription, setBundleDescription] = useState("");
  const [includedMcpServers, setIncludedMcpServers] = useState<Set<string>>(
    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().toolkit_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 tool/MCP server here
      // genuinely becomes a member if included — this flow creates the
      // toolkit itself, so default every AI selection to included.
      setIncludedMcpServers(
        new Set(result.selected_mcp_servers.map((m) => m.id)),
      );
      setStep("review");
    } catch (e) {
      setGenerateError(
        errorDetail(e, "Could not generate a toolkit. Please try again."),
      );
      setStep("describe");
    }
  };
 
  const handleCreate = async () => {
    if (!proposal) return;
    setCreating(true);
    setCreateError(null);
    try {
      await getApiHandler().toolkit_router.createFromConfig({
        name: name.trim(),
        description: bundleDescription.trim(),
        generation_id: proposal.generation_id,
        existing_mcp_server_ids: [...includedMcpServers],
      });
      await Promise.all(
        [QUERY_KEYS.GET.TOOLKITS].map((key) =>
          queryClient.invalidateQueries({ queryKey: [key] }),
        ),
      );
      onClose();
    } catch (e) {
      setCreateError(
        errorDetail(e, "Could not create the toolkit. Please try again."),
      );
    } finally {
      setCreating(false);
    }
  };
 
  const nothingToInclude =
    (proposal?.selected_mcp_servers.length ?? 0) === 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 Toolkit
            </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 servers should let an agent do — the AI recommends a bundle of your existing MCP servers around it. Never invents a new server; they carry live credentials only a human can safely configure."
              >
                <div>
                  <FieldLabel
                    label="Capability description"
                    description="The more context you give, the better the recommended bundle."
                    required
                  />
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="e.g. Tools for triaging incoming support tickets, looking up customer records, and posting updates to our helpdesk."
                    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 recommend the bundle."
                    />
                    <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 Toolkit
                </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">
                Choosing your servers…
              </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 Toolkit"
                  description="A preview of what will be created, in the same git-style diff used to view a toolkit'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">
                      +{includedMcpServers.size} MCP server
                      {includedMcpServers.size === 1 ? "" : "s"} added
                    </p>
                  </div>
                </SectionCard>
              ) : (
                <SectionCard icon={Sparkles} title="Name your toolkit">
                  <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">
                  <Hammer 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 any MCP servers. You can
                    still create an empty toolkit and add members to it
                    afterward.
                  </p>
                </div>
              )}
 
              {proposal.selected_mcp_servers.length > 0 && (
                <SectionCard
                  icon={Server}
                  title="Existing MCP servers"
                  description="MCP servers from your workspace the AI recommends including. Untick any you don't want."
                >
                  <div className="space-y-2">
                    {proposal.selected_mcp_servers.map((server) => (
                      <ToggleRow
                        key={server.id}
                        title={server.name}
                        subtitle={server.description}
                        selected={includedMcpServers.has(server.id)}
                        accent="violet"
                        onToggle={() =>
                          setIncludedMcpServers((prev) =>
                            toggled(prev, server.id),
                          )
                        }
                      />
                    ))}
                  </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 Toolkit
                    </>
                  )}
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};
 
export default GenerateToolkitModal;