All files / src/apps/user/pages/agents/skills/run SkillRunForm.tsx

34.78% Statements 24/69
37.5% Branches 24/64
23.52% Functions 4/17
35.38% Lines 23/65

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                                                                                        2x         3x 3x 3x   3x   1x   3x 3x   3x 3x 3x 3x 3x 3x     3x 2x 2x 2x 2x     3x                                   3x                               3x                                                         3x                                                                                                                                                                                                                                                                                                                              
import { SectionCard, Skeleton } from "@/components/detail";
import { RunSchema } from "@/objects/Skill";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, Braces, ListChecks, Loader2, Play } from "lucide-react";
import React, { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  FormValues,
  REQUIRED,
  initialValues,
  jsonToValues,
  toInputs,
  valuesToJson,
} from "@/util/runForm";
import {
  RunFieldControl,
  borderClass,
  inputClass,
} from "@/components/form/RunFields/RunFieldControl";
import { skillRunHref } from "@/routes/resourceHref";
 
/**
 * Run a skill as a structured workflow.
 *
 * The form is drawn from the skill's **run schema** (svc-core derives it from
 * the graph): its declared interface inputs, plus whatever its nodes read
 * that nothing in the graph supplies. Every field is drawn by its type — an
 * enum is a select, an array a list, an object a JSON editor — and a field
 * the author never declared says which node is asking for it, so the form
 * explains itself.
 *
 * Submitting starts the run and opens it; the run carries on in the
 * background while its page polls.
 */
 
export interface RunSeed {
  prompt?: string | null;
  inputs?: Record<string, unknown> | null;
}
 
type Mode = "form" | "json";
 
const SkillRunForm: React.FC<{
  skillId: string;
  seed?: RunSeed | null;
  className?: string;
}> = ({ skillId, seed, className }) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
 
  const { data, isLoading, error } = useQuery<RunSchema | null>({
    queryKey: [QUERY_KEYS.GET.SKILL_RUN_SCHEMA, skillId],
    queryFn: () => getApiHandler().skill_router.runSchema(skillId),
  });
  const schema: RunSchema | null = data ?? null;
  const fields = useMemo(() => schema?.fields ?? [], [schema]);
 
  const [values, setValues] = useState<FormValues>({});
  const [prompt, setPrompt] = useState(seed?.prompt ?? "");
  const [mode, setMode] = useState<Mode>("form");
  const [json, setJson] = useState("");
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [formError, setFormError] = useState<string | null>(null);
 
  // (Re)seed when the schema arrives or a "Run again" hands in a new seed.
  useEffect(() => {
    setValues(initialValues(fields, seed?.inputs));
    setPrompt(seed?.prompt ?? "");
    setFieldErrors({});
    setFormError(null);
  }, [fields, seed]);
 
  const start = useMutation({
    mutationFn: (body: { prompt: string; inputs: Record<string, unknown> }) =>
      getApiHandler().skill_router.startRun(skillId, body),
    onSuccess: (result) => {
      if ("refused" in result) {
        setFieldErrors(result.refused.fields);
        setFormError(result.refused.message);
        return;
      }
      void queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.SKILL_RUNS, skillId],
      });
      void navigate(skillRunHref(skillId, result.run.id));
    },
    onError: (e: unknown) =>
      setFormError((e as { message?: string })?.message ?? "Could not start the run."),
  });
 
  const switchMode = (next: Mode) => {
    if (next === mode) return;
    if (next === "json") {
      setJson(valuesToJson(fields, values));
    } else {
      const parsed = jsonToValues(fields, json);
      if ("error" in parsed) {
        setFormError(parsed.error);
        return;
      }
      setValues(parsed.values);
    }
    setFormError(null);
    setMode(next);
  };
 
  const submit = (e: React.FormEvent) => {
    e.preventDefault();
    setFormError(null);
    let current = values;
    if (mode === "json") {
      const parsed = jsonToValues(fields, json);
      if ("error" in parsed) {
        setFormError(parsed.error);
        return;
      }
      current = parsed.values;
      setValues(current);
    }
    const { inputs, errors } = toInputs(fields, current);
    if (schema?.requires_prompt && !prompt.trim()) errors.prompt = REQUIRED;
    setFieldErrors(errors);
    if (Object.keys(errors).length) {
      setFormError(
        mode === "json"
          ? Object.entries(errors)
              .map(([k, v]) => `${k}: ${v}`)
              .join(" · ")
          : "Some inputs need attention.",
      );
      return;
    }
    start.mutate({ prompt, inputs });
  };
 
  return (
    <SectionCard
      icon={Play}
      title="Run"
      subtitle={
        fields.length
          ? `${fields.length} input${fields.length === 1 ? "" : "s"}`
          : undefined
      }
      className={className}
      action={
        fields.length > 0 && (
          <div
            role="tablist"
            aria-label="Input mode"
            className="flex rounded-lg border border-gray-200 dark:border-gray-600 p-0.5"
          >
            {(
              [
                ["form", ListChecks, "Form"],
                ["json", Braces, "JSON"],
              ] as const
            ).map(([key, Icon, label]) => (
              <button
                key={key}
                type="button"
                role="tab"
                aria-selected={mode === key}
                onClick={() => switchMode(key)}
                className={`flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-colors ${
                  mode === key
                    ? "bg-gray-900 dark:bg-white text-white dark:text-gray-900"
                    : "text-gray-500 dark:text-gray-400 hover:text-gray-700"
                }`}
              >
                <Icon className="size-3" />
                {label}
              </button>
            ))}
          </div>
        )
      }
    >
      {isLoading ? (
        <div className="space-y-2">
          <Skeleton className="h-10 w-full" />
          <Skeleton className="h-10 w-full" />
        </div>
      ) : error || !schema ? (
        <p className="text-sm text-red-600 dark:text-red-400">
          Could not work out what this skill takes.
        </p>
      ) : (
        <form onSubmit={submit} className="space-y-4" noValidate>
          {!schema.complete && (
            <p className="flex items-start gap-1.5 text-[11px] px-3 py-2 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 text-amber-800 dark:text-amber-300">
              <AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
              Some workers' inputs could not be looked up, so this form may be
              missing fields.
            </p>
          )}
 
          {fields.length > 0 &&
            (mode === "form" ? (
              <div className="@container">
                <div className="grid @md:grid-cols-2 gap-x-4 gap-y-3">
                  {fields.map((f) => (
                    <RunFieldControl
                      key={f.name}
                      field={f}
                      value={values[f.name] ?? ""}
                      error={fieldErrors[f.name]}
                      onChange={(v) =>
                        setValues((prev) => ({ ...prev, [f.name]: v }))
                      }
                    />
                  ))}
                </div>
              </div>
            ) : (
              <div>
                <textarea
                  value={json}
                  onChange={(e) => setJson(e.target.value)}
                  rows={Math.min(16, Math.max(6, json.split("\n").length + 1))}
                  spellCheck={false}
                  aria-label="Inputs as JSON"
                  className={`${inputClass} ${borderClass(false)} font-mono text-xs resize-y`}
                />
                <p className="mt-1 text-[11px] text-gray-400 dark:text-gray-500">
                  One object, keyed by input name — the same body{" "}
                  <code className="font-mono">POST …/runs</code> takes as{" "}
                  <code className="font-mono">inputs</code>.
                </p>
              </div>
            ))}
 
          <div>
            <label
              htmlFor="run-prompt"
              className="flex items-center gap-1.5 mb-1 text-xs font-medium text-gray-700 dark:text-gray-300"
            >
              {schema.requires_prompt ? "Task" : "Additional instructions"}
              {schema.requires_prompt ? (
                <span className="text-red-500">*</span>
              ) : (
                <span className="text-[10px] text-gray-400">optional</span>
              )}
            </label>
            <textarea
              id="run-prompt"
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              rows={3}
              placeholder={
                schema.requires_prompt
                  ? "What should the skill work on?"
                  : "Anything the inputs above do not say…"
              }
              className={`${inputClass} ${borderClass(!!fieldErrors.prompt)} resize-y`}
            />
            {fieldErrors.prompt && (
              <p className="mt-1 text-[11px] text-red-600 dark:text-red-400">
                {fieldErrors.prompt}
              </p>
            )}
          </div>
 
          {formError && (
            <div className="text-xs px-3 py-2 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">
              {formError}
            </div>
          )}
 
          <div className="flex flex-col-reverse sm:flex-row sm:items-center justify-between gap-3">
            <p className="text-[11px] text-gray-400 dark:text-gray-500">
              Runs on its own — no agent persona or knowledge — under your
              governance rules, and is kept in your runs below.
            </p>
            <button
              type="submit"
              disabled={start.isPending}
              className="shrink-0 flex items-center justify-center gap-1.5 px-4 py-2 text-sm font-medium bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-lg hover:opacity-80 disabled:opacity-40 transition-opacity"
            >
              {start.isPending ? (
                <Loader2 className="size-3.5 animate-spin" />
              ) : (
                <Play className="size-3.5" />
              )}
              Run skill
            </button>
          </div>
        </form>
      )}
    </SectionCard>
  );
};
 
export default SkillRunForm;