All files / src/apps/user/pages/rules GenerateRuleModal.tsx

84.14% Statements 69/82
82.14% Branches 46/56
74.19% Functions 23/31
84.61% Lines 66/78

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                                                                                    5x           5x 1x   1x             5x     5x     9x                             5x 15x 15x 9x   15x       9x                   5x           18x 18x   18x                                                                                                                                     9x               15x                               5x 383x 383x   383x 383x 383x 383x   383x     383x 383x 383x 383x   383x   7x   383x   383x 5x 5x 5x 5x       5x 5x 8x 5x                 383x 2x 2x 2x 2x 2x   4x 3x     1x     1x       1x       2x       383x                                                                     355x                                           1104x                                                                                                   5x                                                                             10x                                                       18x         1x 1x 1x   1x                                                                 2x                                              
import {
  FieldLabel,
  SectionCard,
  ToggleRow,
  inputBase,
} from "@/apps/user/pages/agents/setup/primitives";
import {
  LAYER_CLASSES,
  ruleLayerMeta,
} from "@/apps/user/pages/rules/ruleLayer";
import { Model, isSelectableModel, modelDisplayName } from "@/objects/Model";
import { RuleAction, RuleCondition } from "@/objects/Rule";
import { ProposedRule, RulesGenerationProposal } from "@/objects/RuleSetup";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertCircle,
  ChevronRight,
  Crosshair,
  Lightbulb,
  Loader2,
  ShieldCheck,
  Sparkles,
  X,
  Zap,
} from "lucide-react";
import React, { useState } from "react";
 
// A sibling of the skillset, toolkit and knowledge generative modals, scoped
// to governance rules.
//
// What makes this one different is that there is nothing to interpret on
// arrival. svc-core validates each proposed rule against the same registries
// the engine evaluates with, and drops — with a reason in `warnings` — any
// rule whose field, operator, action or scope it cannot honour. So the review
// step shows rules in exactly the shape they will be stored in, and the
// warnings panel is not a footnote: it is the list of governance the model
// asked for and this platform will not pretend to enforce.
 
type Step = "describe" | "generating" | "review";
 
const EXAMPLES: string[] = [
  "Stop anyone pasting credentials or customer PII into a prompt, and record it when they try",
  "Keep spend under control: cap what each project can run up in a day and fall back to a cheaper model when the prompt is short",
  "Everything our legal assistant produces should be logged and flagged for a human to read",
];
 
const errorDetail = (e: unknown, fallback: string): string => {
  const detail = (e as { response?: { data?: { detail?: unknown } } })?.response
    ?.data?.detail;
  Eif (typeof detail === "string") return detail;
  return (e as { message?: string })?.message ?? fallback;
};
 
// ─── Block summaries ──────────────────────────────────────────────────────────
 
const CODE =
  "px-1.5 py-0.5 rounded bg-white/70 dark:bg-gray-900/40 border border-black/5 dark:border-white/10 font-mono text-[11px] text-gray-700 dark:text-gray-300";
 
/** A condition in the order it reads: field, comparison, value. */
const ConditionLine: React.FC<{ condition: RuleCondition }> = ({
  condition,
}) => (
  <div className="flex flex-wrap items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
    <code className={CODE}>{condition.field}</code>
    <ChevronRight className="size-3 shrink-0 text-gray-300 dark:text-gray-600" />
    <span className="font-medium">{condition.operator}</span>
    {String(condition.value ?? "") !== "" && (
      <>
        <ChevronRight className="size-3 shrink-0 text-gray-300 dark:text-gray-600" />
        <code className={CODE}>{String(condition.value)}</code>
      </>
    )}
  </div>
);
 
/** An action and the parameters it was given — a quota with no limit never
 *  reaches here, but a reviewer still needs to see the numbers it did get. */
const ActionLine: React.FC<{ action: RuleAction }> = ({ action }) => {
  const { type, ...params } = action;
  const entries = Object.entries(params).filter(
    ([, value]) => value !== null && value !== undefined && value !== "",
  );
  return (
    <div className="flex flex-wrap items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
      <code className={CODE}>{String(type)}</code>
      {entries.map(([key, value]) => (
        <span key={key} className="text-[11px]">
          {key}: <span className="font-medium">{String(value)}</span>
        </span>
      ))}
    </div>
  );
};
 
// ─── Proposed rule ────────────────────────────────────────────────────────────
 
const ProposedRuleRow: React.FC<{
  rule: ProposedRule;
  included: boolean;
  onToggle: () => void;
  onChange: (rule: ProposedRule) => void;
}> = ({ rule, included, onToggle, onChange }) => {
  const meta = ruleLayerMeta(rule.layer);
  const Icon = meta.Icon;
 
  return (
    <ToggleRow
      title={rule.name}
      subtitle={rule.description}
      selected={included}
      accent="violet"
      onToggle={onToggle}
      icon={
        <div className={`p-1.5 rounded-lg ${LAYER_CLASSES.iconTile}`}>
          <Icon className="size-4" />
        </div>
      }
      meta={
        <span
          className={`text-[11px] font-medium px-2 py-0.5 rounded-full border ${LAYER_CLASSES.tag}`}
        >
          {meta.label}
        </span>
      }
    >
      {included && (
        <div className="mt-3 space-y-3">
          <div>
            <FieldLabel label="Name" />
            <input
              type="text"
              value={rule.name}
              aria-label={`Name for ${rule.name}`}
              onChange={(e) => onChange({ ...rule, name: e.target.value })}
              className={inputBase}
            />
          </div>
 
          <div className="flex flex-wrap items-center gap-3 text-xs text-gray-500 dark:text-gray-400">
            <span className="inline-flex items-center gap-1.5">
              {rule.scope_id && <Crosshair className="size-3" />}
              Applies to{" "}
              <span className="font-medium text-gray-700 dark:text-gray-300">
                {rule.scope_label || rule.scope_type}
              </span>
            </span>
            <span>Priority {rule.priority}</span>
            <label className="inline-flex items-center gap-1.5 cursor-pointer">
              <input
                type="checkbox"
                checked={rule.is_active}
                aria-label={`Activate ${rule.name} on creation`}
                onChange={(e) =>
                  onChange({ ...rule, is_active: e.target.checked })
                }
                className="size-3.5 accent-gray-800 dark:accent-gray-200"
              />
              <span className="inline-flex items-center gap-1">
                <Zap className="size-3" />
                Active on creation
              </span>
            </label>
          </div>
 
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div className="rounded-lg bg-gray-50 dark:bg-gray-800/60 px-3 py-2 space-y-1.5">
              <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500">
                {rule.conditions.length === 0
                  ? "Every invocation"
                  : `When (${rule.conditions.length})`}
              </div>
              {rule.conditions.map((condition, i) => (
                <ConditionLine key={i} condition={condition} />
              ))}
            </div>
            <div className="rounded-lg bg-gray-50 dark:bg-gray-800/60 px-3 py-2 space-y-1.5">
              <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500">
                Then ({rule.actions.length})
              </div>
              {rule.actions.map((action, i) => (
                <ActionLine key={i} action={action} />
              ))}
            </div>
          </div>
          <p className="text-[11px] text-gray-400 dark:text-gray-500">
            Everything here can be changed after creating: Edit on the rule's
            page opens it in the builder, with the whole vocabulary.
          </p>
        </div>
      )}
    </ToggleRow>
  );
};
 
// ─── GenerateRuleModal ────────────────────────────────────────────────────────
 
const GenerateRuleModal: 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<RulesGenerationProposal | null>(
    null,
  );
  const [rules, setRules] = useState<ProposedRule[]>([]);
  const [included, setIncluded] = useState<Set<number>>(new Set());
  const [createError, setCreateError] = useState<string | null>(null);
  const [creating, setCreating] = 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 handleGenerate = async () => {
    setGenerateError(null);
    setStep("generating");
    try {
      const result = await getApiHandler().rule_router.generateConfig({
        problem_description: description.trim(),
        ai_model_id: modelId || null,
      });
      setProposal(result);
      setRules(result.proposed_rules);
      setIncluded(new Set(result.proposed_rules.map((_, i) => i)));
      setStep("review");
    } catch (e) {
      setGenerateError(
        errorDetail(e, "Could not generate rules. Please try again."),
      );
      setStep("describe");
    }
  };
 
  const handleCreate = async () => {
    Iif (!proposal) return;
    setCreating(true);
    setCreateError(null);
    try {
      await getApiHandler().rule_router.createFromConfig({
        rules: rules
          .filter((_, i) => included.has(i))
          .map((rule) => ({ ...rule, name: rule.name.trim() })),
        generation_id: proposal.generation_id,
      });
      await queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.RULES],
      });
      onClose();
    } catch (e) {
      // The create path re-validates rather than trusting the proposal, so
      // its refusal names the rule and the reason — show it verbatim.
      setCreateError(
        errorDetail(e, "Could not create the rules. Please try again."),
      );
    } finally {
      setCreating(false);
    }
  };
 
  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 Rules
            </h2>
          </div>
          <button
            onClick={onClose}
            aria-label="Close"
            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 what you want governed"
                description="Explain what should be stopped, routed or recorded — the AI writes the rules, using only the conditions and actions this engine can enforce."
              >
                <div>
                  <FieldLabel
                    label="What should these rules do?"
                    description="Name the behaviour, not the mechanism. The more concrete, the better the rules."
                    required
                  />
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="e.g. Nobody should be able to paste customer credit-card numbers into a prompt, and every attempt should be flagged for our compliance reviewer."
                    rows={5}
                    className={inputBase + " resize-none"}
                  />
                </div>
                <div className="flex items-start gap-2 px-3 py-2.5 rounded-lg bg-gray-50 dark:bg-gray-800/60 border border-gray-100 dark:border-gray-700">
                  <AlertCircle className="size-3.5 shrink-0 mt-0.5 text-gray-400" />
                  <p className="text-xs text-gray-500 dark:text-gray-400 leading-relaxed">
                    Every proposed rule is checked against the same vocabulary
                    the engine evaluates. Anything it cannot enforce is dropped
                    and the reason shown — a rule that looks active and never
                    fires is worse than no rule at all.
                  </p>
                </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 write the rules."
                    />
                    <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 Rules
                </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">
                Writing your rules…
              </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 && (
            <>
              {proposal.reasoning && (
                <div className="px-4 py-3 rounded-lg bg-violet-50 dark:bg-violet-950/30 border border-violet-200 dark:border-violet-900 text-xs text-violet-900 dark:text-violet-200 leading-relaxed">
                  {proposal.reasoning}
                </div>
              )}
 
              {proposal.warnings.length > 0 && (
                <div className="px-4 py-3 rounded-lg bg-amber-50 dark:bg-amber-950/40 border border-amber-200 dark:border-amber-800 text-amber-800 dark:text-amber-300 text-xs space-y-1">
                  {proposal.warnings.map((warning) => (
                    <div key={warning} className="flex items-start gap-2">
                      <AlertCircle className="size-3.5 shrink-0 mt-0.5" />
                      {warning}
                    </div>
                  ))}
                </div>
              )}
 
              {rules.length === 0 ? (
                <div className="rounded-xl border border-dashed border-gray-200 dark:border-gray-700 px-6 py-12 flex flex-col items-center text-center">
                  <ShieldCheck className="size-7 text-gray-200 dark:text-gray-600 mb-3" />
                  <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
                    No rules could be written for that description.
                  </p>
                  <p className="text-xs text-gray-400 dark:text-gray-500 mt-1 max-w-sm">
                    Try naming the behaviour you want stopped, routed or
                    recorded, and what it applies to.
                  </p>
                </div>
              ) : (
                <SectionCard
                  icon={ShieldCheck}
                  title="Proposed Rules"
                  subtitle={`(${included.size}/${rules.length})`}
                  description="Uncheck anything you don't want. Everything here is created as an ordinary rule — versioned, editable, and tagged as AI generated."
                >
                  <div className="space-y-2">
                    {rules.map((rule, i) => (
                      <ProposedRuleRow
                        key={i}
                        rule={rule}
                        included={included.has(i)}
                        onToggle={() =>
                          setIncluded((current) => {
                            const next = new Set(current);
                            if (next.has(i)) next.delete(i);
                            else Enext.add(i);
                            return next;
                          })
                        }
                        onChange={(updated) =>
                          setRules((current) =>
                            current.map((r, index) =>
                              index === i ? updated : r,
                            ),
                          )
                        }
                      />
                    ))}
                  </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}
                  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 handleCreate()}
                  disabled={creating || included.size === 0}
                  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" />
                  ) : (
                    <ShieldCheck className="size-4" />
                  )}
                  {creating
                    ? "Creating…"
                    : `Create ${included.size} Rule${included.size === 1 ? "" : "s"}`}
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};
 
export default GenerateRuleModal;