Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(web/playbooks): WS-F4 visual SOAR studio polish — undo/redo, edge validation, schema-driven forms, multi-select
Beenu Arora84feedfae0f8
diff --git a/apps/web/src/components/playbooks/PlaybookEditor.tsx b/apps/web/src/components/playbooks/PlaybookEditor.tsxindex a08886b29..81d13f8c2 100644--- a/apps/web/src/components/playbooks/PlaybookEditor.tsx+++ b/apps/web/src/components/playbooks/PlaybookEditor.tsx@@ -7,21 +7,37 @@* - Left: metadata panel (name, description, trigger)* - Centre: React Flow canvas* - Right: step inspector (when step selected)- * - Bottom toolbar: save, run, add step+ * - Bottom toolbar: save, run, add step, undo/redo+ *+ * WS-F4 polish: every mutation that flows through `setPlaybook` is now+ * captured in a `useHistoryState` undo/redo stack. Remote loads sync via+ * `controls.replace(...)` so they don't pollute history. Cmd/Ctrl-Z and+ * Cmd/Ctrl-Shift-Z (or Ctrl-Y on Windows-style keyboards) trigger undo/redo+ * globally while the editor is mounted, except when focus is in a text+ * input — that lets the browser's native input undo keep working.*/-import React, { useState, useCallback } from 'react';+import React, { useState, useCallback, useEffect, useMemo } from 'react';import { useRouter } from 'next/navigation';import useSWR, { mutate } from 'swr';import { PlaybookFlowCanvas } from './PlaybookFlowCanvas';import { StepInspector } from './StepInspector';import type { Playbook, PlaybookStep, StepType } from './types';import { STEP_TYPE_META } from './stepColors';+import { defaultParamsFor } from './stepSchemas';import { ContextualActions } from '@/components/copilot/ContextualActions';+import { useHistoryState } from '@/hooks/useHistoryState';const STEP_TYPES: StepType[] = [- 'enrich', 'investigate', 'notify', 'block_ip',- 'isolate_host', 'create_ticket', 'close_case', 'http', 'condition',+ 'enrich',+ 'investigate',+ 'notify',+ 'block_ip',+ 'isolate_host',+ 'create_ticket',+ 'close_case',+ 'http',+ 'condition',];function generateId(): string {@@ -33,7 +49,9 @@ function makeNewStep(type: StepType): PlaybookStep {id: generateId(),name: `New ${STEP_TYPE_META[type].label} step`,type,- params: {},+ // Honour each step kind's default param shape so the new step is+ // immediately valid for the schema-driven inspector form.+ params: defaultParamsFor(type),on_failure: 'abort',retry_max: 0,timeout_seconds: 30,@@ -79,37 +97,41 @@ interface PlaybookEditorProps {playbookId: string;}+const EMPTY_PLAYBOOK: Playbook = {+ id: '',+ name: 'Untitled Playbook',+ description: '',+ version: '1.0.0',+ tags: [],+ trigger: { on: 'manual' },+ steps: [],+ author: 'AiSOC',+ enabled: true,+ created_at: '',+ updated_at: '',+};+export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {const router = useRouter();const isNew = playbookId === 'new';const { data: remote, isLoading } = useSWR<Playbook>(!isNew ? `/api/v1/playbooks/${playbookId}` : null,- fetcher+ fetcher,);- const [playbook, setPlaybook] = useState<Playbook>(() => ({- id: '',- name: 'Untitled Playbook',- description: '',- version: '1.0.0',- tags: [],- trigger: { on: 'manual' },- steps: [],- author: 'AiSOC',- enabled: true,- created_at: '',- updated_at: '',- }));-- // Sync remote data once loaded+ const [playbook, history] = useHistoryState<Playbook>(EMPTY_PLAYBOOK);+ const setPlaybook = history.set;++ // Sync remote data once loaded — use replace() so the load doesn't push+ // an extra entry onto the history stack.const [synced, setSynced] = useState(false);- React.useEffect(() => {+ useEffect(() => {if (remote && !synced) {- setPlaybook(remote);+ history.reset(remote);setSynced(true);}- }, [remote, synced]);+ }, [remote, synced, history]);const [selectedStepId, setSelectedStepId] = useState<string | null>(null);const [saving, setSaving] = useState(false);@@ -118,37 +140,89 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {const [showAddStep, setShowAddStep] = useState(false);const [editMeta, setEditMeta] = useState(false);- const selectedStep = playbook.steps.find((s) => s.id === selectedStepId) ?? null;+ const selectedStep = useMemo(+ () => playbook.steps.find((s) => s.id === selectedStepId) ?? null,+ [playbook.steps, selectedStepId],+ );/* ── Callbacks ── */- const updateStep = useCallback((updated: PlaybookStep) => {- setPlaybook((pb) => ({- ...pb,- steps: pb.steps.map((s) => (s.id === updated.id ? updated : s)),- }));- }, []);-- const deleteStep = useCallback((id: string) => {- setPlaybook((pb) => ({- ...pb,- steps: pb.steps.filter((s) => s.id !== id),- }));- setSelectedStepId(null);- }, []);-- const addStep = useCallback((type: StepType) => {- const step = makeNewStep(type);- setPlaybook((pb) => ({ ...pb, steps: [...pb.steps, step] }));- setSelectedStepId(step.id);- setShowAddStep(false);- }, []);+ const updateStep = useCallback(+ (updated: PlaybookStep) => {+ setPlaybook((pb) => ({+ ...pb,+ steps: pb.steps.map((s) => (s.id === updated.id ? updated : s)),+ }));+ },+ [setPlaybook],+ );++ const deleteStep = useCallback(+ (id: string) => {+ setPlaybook((pb) => ({+ ...pb,+ steps: pb.steps.filter((s) => s.id !== id),+ }));+ setSelectedStepId(null);+ },+ [setPlaybook],+ );++ const addStep = useCallback(+ (type: StepType) => {+ const step = makeNewStep(type);+ setPlaybook((pb) => ({ ...pb, steps: [...pb.steps, step] }));+ setSelectedStepId(step.id);+ setShowAddStep(false);+ },+ [setPlaybook],+ );++ const handleStepsChange = useCallback(+ (steps: PlaybookStep[]) => {+ setPlaybook((p) => ({ ...p, steps }));+ },+ [setPlaybook],+ );++ /* ── Undo / redo keyboard shortcuts ── */++ useEffect(() => {+ function onKeyDown(e: KeyboardEvent) {+ const target = e.target as HTMLElement | null;+ if (target) {+ // Don't swallow native input undo while the user is typing.+ const tag = target.tagName;+ if (tag === 'INPUT' || tag === 'TEXTAREA' || target.isContentEditable) {+ return;+ }+ }+ const mod = e.metaKey || e.ctrlKey;+ if (!mod) return;+ const key = e.key.toLowerCase();+ // Cmd/Ctrl + Z = undo (no Shift)+ if (key === 'z' && !e.shiftKey) {+ e.preventDefault();+ history.undo();+ return;+ }+ // Cmd/Ctrl + Shift + Z = redo, or Cmd/Ctrl + Y = redo+ if ((key === 'z' && e.shiftKey) || key === 'y') {+ e.preventDefault();+ history.redo();+ }+ }+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [history]);const handleSave = async () => {setSaving(true);setRunResult(null);try {- const url = isNew ? '/api/v1/playbooks' : `/api/v1/playbooks/${playbook.id}`;+ const url = isNew+ ? '/api/v1/playbooks'+ : `/api/v1/playbooks/${playbook.id}`;const method = isNew ? 'POST' : 'PUT';const body = isNew ? playbook : { ...playbook };const res = await fetch(url, {@@ -158,13 +232,17 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {});if (!res.ok) throw new Error(await res.text());const saved: Playbook = await res.json();- setPlaybook(saved);+ // Save reset: post-save state is the new "clean" baseline, so wipe+ // any historical drafts that no longer match the persisted record.+ history.reset(saved);setSynced(true);await mutate('/api/v1/playbooks');if (isNew) router.replace(`/playbooks/${saved.id}`);setRunResult('Saved');} catch (err) {- setRunResult(`Save failed: ${err instanceof Error ? err.message : String(err)}`);+ setRunResult(+ `Save failed: ${err instanceof Error ? err.message : String(err)}`,+ );} finally {setSaving(false);}@@ -187,7 +265,9 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {const data = await res.json();setRunResult(`Dry run started — run_id: ${data.run_id}`);} catch (err) {- setRunResult(`Run failed: ${err instanceof Error ? err.message : String(err)}`);+ setRunResult(+ `Run failed: ${err instanceof Error ? err.message : String(err)}`,+ );} finally {setRunning(false);}@@ -217,7 +297,9 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {<inputautoFocusvalue={playbook.name}- onChange={(e) => setPlaybook((p) => ({ ...p, name: e.target.value }))}+ onChange={(e) =>+ setPlaybook((p) => ({ ...p, name: e.target.value }))+ }onBlur={() => setEditMeta(false)}className="bg-transparent border-b border-blue-500 text-white text-lg font-semibold focus:outline-none w-64"/>@@ -230,14 +312,39 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {{playbook.name}</button>)}- <TriggerBadge on={playbook.trigger.on} severity={playbook.trigger.severity} />+ <TriggerBadge+ on={playbook.trigger.on}+ severity={playbook.trigger.severity}+ /><span className="text-xs text-gray-600">v{playbook.version}</span>- <span className={`text-xs px-2 py-0.5 rounded-full border ${playbook.enabled ? 'border-green-800 text-green-400 bg-green-950/50' : 'border-gray-700 text-gray-500'}`}>+ <span+ className={`text-xs px-2 py-0.5 rounded-full border ${playbook.enabled ? 'border-green-800 text-green-400 bg-green-950/50' : 'border-gray-700 text-gray-500'}`}+ >{playbook.enabled ? 'enabled' : 'disabled'}</span></div><div className="flex items-center gap-2">+ {/* Undo / redo buttons */}+ <button+ onClick={() => history.undo()}+ disabled={!history.canUndo}+ title="Undo (⌘Z)"+ aria-label="Undo"+ className="text-xs px-2.5 py-1.5 rounded border border-gray-700 text-gray-400 hover:bg-gray-800 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"+ >+ ↶+ </button>+ <button+ onClick={() => history.redo()}+ disabled={!history.canRedo}+ title="Redo (⌘⇧Z)"+ aria-label="Redo"+ className="text-xs px-2.5 py-1.5 rounded border border-gray-700 text-gray-400 hover:bg-gray-800 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"+ >+ ↷+ </button>+ <div className="h-5 w-px bg-gray-800" /><buttononClick={() => setShowAddStep(true)}className="text-xs px-3 py-1.5 rounded border border-blue-700 text-blue-400 hover:bg-blue-900/30 transition-colors"@@ -266,7 +373,10 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {{runResult && (<div className="px-5 py-2 bg-gray-900/60 text-sm border-b border-gray-800/60 flex items-center justify-between"><span className="text-gray-300">{runResult}</span>- <button onClick={() => setRunResult(null)} className="text-gray-600 hover:text-gray-400 text-xs">+ <button+ onClick={() => setRunResult(null)}+ className="text-gray-600 hover:text-gray-400 text-xs"+ >Dismiss</button></div>@@ -310,25 +420,40 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {{/* Left meta panel */}<div className="w-56 flex-shrink-0 border-r border-gray-800/60 bg-gray-900/40 p-4 overflow-y-auto space-y-4 text-sm"><div>- <div className="text-gray-500 text-xs font-medium uppercase tracking-wider mb-2">Metadata</div>+ <div className="text-gray-500 text-xs font-medium uppercase tracking-wider mb-2">+ Metadata+ </div><div className="space-y-2"><div>- <label className="text-gray-600 text-xs block mb-1">Description</label>+ <label className="text-gray-600 text-xs block mb-1">+ Description+ </label><textarearows={3}value={playbook.description}- onChange={(e) => setPlaybook((p) => ({ ...p, description: e.target.value }))}+ onChange={(e) =>+ setPlaybook((p) => ({ ...p, description: e.target.value }))+ }className="w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-300 focus:outline-none focus:border-blue-500 resize-none"/></div><div>- <label className="text-gray-600 text-xs block mb-1">Trigger</label>+ <label className="text-gray-600 text-xs block mb-1">+ Trigger+ </label><selectvalue={playbook.trigger.on}onChange={(e) =>setPlaybook((p) => ({...p,- trigger: { ...p.trigger, on: e.target.value as 'alert' | 'case' | 'manual' | 'schedule' },+ trigger: {+ ...p.trigger,+ on: e.target.value as+ | 'alert'+ | 'case'+ | 'manual'+ | 'schedule',+ },}))}className="w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-300 focus:outline-none focus:border-blue-500"@@ -340,13 +465,18 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {</select></div><div>- <label className="text-gray-600 text-xs block mb-1">Tags (comma sep)</label>+ <label className="text-gray-600 text-xs block mb-1">+ Tags (comma sep)+ </label><inputvalue={playbook.tags.join(', ')}onChange={(e) =>setPlaybook((p) => ({...p,- tags: e.target.value.split(',').map((t) => t.trim()).filter(Boolean),+ tags: e.target.value+ .split(',')+ .map((t) => t.trim())+ .filter(Boolean),}))}className="w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-300 focus:outline-none focus:border-blue-500"@@ -357,7 +487,9 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {<inputtype="checkbox"checked={playbook.enabled}- onChange={(e) => setPlaybook((p) => ({ ...p, enabled: e.target.checked }))}+ onChange={(e) =>+ setPlaybook((p) => ({ ...p, enabled: e.target.checked }))+ }className="accent-blue-500"/></div>@@ -375,14 +507,20 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {return (<buttonkey={step.id}- onClick={() => setSelectedStepId(step.id === selectedStepId ? null : step.id)}+ onClick={() =>+ setSelectedStepId(+ step.id === selectedStepId ? null : step.id,+ )+ }className={`w-full text-left px-2 py-1.5 rounded text-xs flex items-center gap-2 transition-colors ${step.id === selectedStepId? 'bg-blue-900/40 text-blue-300': 'text-gray-400 hover:bg-gray-800'}`}>- <span className="text-gray-600 w-4 text-right flex-shrink-0">{idx + 1}.</span>+ <span className="text-gray-600 w-4 text-right flex-shrink-0">+ {idx + 1}.+ </span><span>{m.icon}</span><span className="truncate">{step.name}</span></button>@@ -399,8 +537,12 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {<div className="flex-1 min-w-0 relative">{playbook.steps.length === 0 ? (<div className="absolute inset-0 flex flex-col items-center justify-center text-gray-700">- <div className="text-lg font-medium text-gray-500">Empty playbook</div>- <div className="text-sm mt-1 mb-6">Add your first step to get started</div>+ <div className="text-lg font-medium text-gray-500">+ Empty playbook+ </div>+ <div className="text-sm mt-1 mb-6">+ Add your first step to get started+ </div><buttononClick={() => setShowAddStep(true)}className="px-4 py-2 rounded bg-blue-600 hover:bg-blue-500 text-white text-sm transition-colors"@@ -413,7 +555,7 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {steps={playbook.steps}selectedId={selectedStepId}onSelectStep={setSelectedStepId}- onStepsChange={(steps) => setPlaybook((p) => ({ ...p, steps }))}+ onStepsChange={handleStepsChange}/>)}</div>@@ -422,7 +564,9 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {{selectedStep && (<div className="w-72 flex-shrink-0 border-l border-gray-800/60 bg-gray-900/40"><div className="px-4 py-3 border-b border-gray-800/60 flex items-center justify-between">- <span className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Step Inspector</span>+ <span className="text-xs font-semibold text-gray-400 uppercase tracking-wider">+ Step Inspector+ </span><buttononClick={() => setSelectedStepId(null)}className="text-gray-600 hover:text-gray-400 text-sm"@@ -449,7 +593,9 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {className="bg-gray-900 border border-gray-700 rounded-xl p-5 w-80 shadow-2xl"onClick={(e) => e.stopPropagation()}>- <div className="text-sm font-semibold text-white mb-4">Choose Step Type</div>+ <div className="text-sm font-semibold text-white mb-4">+ Choose Step Type+ </div><div className="grid grid-cols-3 gap-2">{STEP_TYPES.map((type) => {const m = STEP_TYPE_META[type];@@ -459,8 +605,12 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {onClick={() => addStep(type)}className="flex flex-col items-center gap-1 p-3 rounded-lg border border-gray-700 hover:border-gray-500 bg-gray-800 hover:bg-gray-750 transition-colors">- <span style={{ color: m.color, fontSize: 20 }}>{m.icon}</span>- <span className="text-xs text-gray-400 text-center leading-tight">{m.label}</span>+ <span style={{ color: m.color, fontSize: 20 }}>+ {m.icon}+ </span>+ <span className="text-xs text-gray-400 text-center leading-tight">+ {m.label}+ </span></button>);})}diff --git a/apps/web/src/components/playbooks/PlaybookFlowCanvas.tsx b/apps/web/src/components/playbooks/PlaybookFlowCanvas.tsxindex 9e04db3fa..69f2cf912 100644--- a/apps/web/src/components/playbooks/PlaybookFlowCanvas.tsx+++ b/apps/web/src/components/playbooks/PlaybookFlowCanvas.tsx@@ -6,32 +6,59 @@* React Flow canvas that renders a playbook's steps as an interactive* directed graph. Steps are laid out top-to-bottom automatically.*+ * WS-F4 polish:+ * - User-drawn connections are validated against `connectionValidation`+ * before being persisted into the underlying step's+ * `next_true` / `next_false` field. Rejections surface as a transient+ * banner above the canvas (so users see *why* a connection was refused+ * instead of having it silently disappear).+ * - Multi-select via Shift-click and Shift-drag (box select) is wired to+ * a Delete/Backspace handler that bulk-deletes selected nodes and edges+ * with proper reference cleanup (`pruneReferences` / `removeConnection`).+ * - The previous behaviour silently dropped any user-drawn edge: React+ * Flow's `addEdge` mutated only the local `edges` array, never the+ * playbook steps, so reload erased the work. That bug is fixed here.+ ** Props:* steps – array of PlaybookStep (read from Playbook.steps)* onSelectStep – called when user clicks a node (for the sidebar panel)- * selectedId – currently selected step id- * readOnly – disables drag/add when true+ * selectedId – currently selected step id (single-select sidebar focus)+ * readOnly – disables drag, connect, delete when true+ * onStepsChange – propagate edits back to the parent. Required for the+ * canvas to actually persist user actions.*/-import React, { useCallback, useEffect, useMemo } from 'react';+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import {ReactFlow,Background,Controls,MiniMap,- addEdge,useNodesState,useEdgesState,type Node,type Edge,type Connection,type NodeTypes,+ type OnSelectionChangeParams,BackgroundVariant,MarkerType,} from '@xyflow/react';import '@xyflow/react/dist/style.css';import type { PlaybookStep } from './types';import { STEP_TYPE_META } from './stepColors';+import {+ validateConnection,+ applyConnection,+ removeConnection,+ pruneReferences,+} from './connectionValidation';/* ─────────────────────────── Custom Node ─────────────────────────── */@@ -133,7 +160,7 @@ const V_GAP = 60;function buildGraphElements(steps: PlaybookStep[],selectedId: string | null,- onClickNode: (id: string) => void+ onClickNode: (id: string) => void,): { nodes: Node[]; edges: Edge[] } {// Build adjacency from explicit next_true / next_false; fall back to sequentialconst nodes: Node[] = steps.map((step, idx) => ({@@ -143,7 +170,11 @@ function buildGraphElements(x: step.type === 'condition' ? (idx % 2 === 0 ? 0 : NODE_W + H_GAP) : 0,y: idx * (NODE_H + V_GAP),},- data: { step, selected: step.id === selectedId, onClick: onClickNode } as StepNodeData,+ data: {+ step,+ selected: step.id === selectedId,+ onClick: onClickNode,+ } as StepNodeData,draggable: true,}));@@ -158,7 +189,7 @@ function buildGraphElements(id: `${step.id}-true`,source: step.id,target: step.next_true,- label: 'true',+ label: step.type === 'condition' ? 'true' : undefined,style: { stroke: '#34d399' },labelStyle: { fill: '#34d399', fontWeight: 600, fontSize: 11 },markerEnd: { type: MarkerType.ArrowClosed, color: '#34d399' },@@ -175,7 +206,10 @@ function buildGraphElements(markerEnd: { type: MarkerType.ArrowClosed, color: '#f87171' },});} else if (!step.next_true && !step.next_false && idx < steps.length - 1) {- // Sequential fallback+ // Sequential fallback for unconfigured steps. Note this is a *visual*+ // hint only — it is not persisted into next_true unless the user+ // explicitly draws the edge. That keeps the playbook's declared graph+ // honest about which connections were intentional vs. defaulted.edges.push({id: `${step.id}-seq`,source: step.id,@@ -190,6 +224,22 @@ function buildGraphElements(return { nodes, edges };}+/**+ * Decode the source step id and which slot (`next_true` / `next_false`)+ * a synthetic edge id refers to. Edge ids minted by `buildGraphElements`+ * are of the form `${stepId}-(true|false|seq)`. We split on the LAST dash+ * so step ids that happen to contain dashes still resolve correctly.+ */+function parseEdgeId(+ id: string,+): { sourceId: string; branch: 'true' | 'false' | 'seq' } | null {+ const last = id.lastIndexOf('-');+ if (last === -1) return null;+ const branch = id.slice(last + 1) as 'true' | 'false' | 'seq';+ if (branch !== 'true' && branch !== 'false' && branch !== 'seq') return null;+ return { sourceId: id.slice(0, last), branch };+}+/* ─────────────────────────── Main Component ─────────────────────────── */interface PlaybookFlowCanvasProps {@@ -211,50 +261,235 @@ export function PlaybookFlowCanvas({(id: string) => {onSelectStep(id === selectedId ? null : id);},- [onSelectStep, selectedId]+ [onSelectStep, selectedId],);const { nodes: initialNodes, edges: initialEdges } = useMemo(() => buildGraphElements(steps, selectedId, handleNodeClick),// eslint-disable-next-line react-hooks/exhaustive-deps- [steps, selectedId]+ [steps, selectedId],);const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);- // Sync when steps prop changes+ // Sync when steps prop changes (e.g. add step, undo, redo)useEffect(() => {const { nodes: n, edges: e } = buildGraphElements(steps,selectedId,- handleNodeClick+ handleNodeClick,);setNodes(n);setEdges(e);}, [steps, selectedId, handleNodeClick, setNodes, setEdges]);+ /* ── Validation banner ── */++ const [validationError, setValidationError] = useState<string | null>(null);+ const errorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const flashError = useCallback((reason: string) => {+ setValidationError(reason);+ if (errorTimerRef.current) {+ clearTimeout(errorTimerRef.current);+ }+ errorTimerRef.current = setTimeout(() => {+ setValidationError(null);+ errorTimerRef.current = null;+ }, 4000);+ }, []);++ useEffect(+ () => () => {+ if (errorTimerRef.current) clearTimeout(errorTimerRef.current);+ },+ [],+ );++ /* ── Connection persistence ── */+const onConnect = useCallback((params: Connection) => {- if (!readOnly) setEdges((eds) => addEdge(params, eds));+ if (readOnly || !onStepsChange) return;+ if (!params.source || !params.target) return;+ const result = validateConnection(+ steps,+ params.source,+ params.target,+ params.sourceHandle,+ );+ if (!result.ok) {+ flashError(result.reason);+ return;+ }+ onStepsChange(+ applyConnection(steps, params.source, params.target, result.branch),+ );},- [setEdges, readOnly]+ [readOnly, onStepsChange, steps, flashError],+ );++ /* ── Multi-select tracking ── */++ const [selectedNodeIds, setSelectedNodeIds] = useState<string[]>([]);+ const [selectedEdgeIds, setSelectedEdgeIds] = useState<string[]>([]);++ const onSelectionChange = useCallback(+ (params: OnSelectionChangeParams) => {+ setSelectedNodeIds(params.nodes.map((n) => n.id));+ setSelectedEdgeIds(params.edges.map((e) => e.id));+ },+ [],+ );++ /* ── Bulk delete via Delete / Backspace ── */++ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLDivElement>) => {+ if (readOnly || !onStepsChange) return;+ if (e.key !== 'Delete' && e.key !== 'Backspace') return;+ // Don't hijack typing in form inputs.+ const target = e.target as HTMLElement;+ const tag = target.tagName;+ if (tag === 'INPUT' || tag === 'TEXTAREA' || target.isContentEditable) {+ return;+ }+ if (selectedNodeIds.length === 0 && selectedEdgeIds.length === 0) return;+ e.preventDefault();++ let next = steps;++ // Delete edges first so any next_true/next_false slots that were the+ // target of a selected edge are cleared even if the source node also+ // gets deleted in the same batch.+ if (selectedEdgeIds.length > 0) {+ for (const edgeId of selectedEdgeIds) {+ const parsed = parseEdgeId(edgeId);+ if (!parsed) continue;+ const source = next.find((s) => s.id === parsed.sourceId);+ if (!source) continue;+ let targetId: string | undefined;+ if (parsed.branch === 'true' || parsed.branch === 'seq') {+ targetId = source.next_true;+ } else if (parsed.branch === 'false') {+ targetId = source.next_false;+ }+ if (!targetId) continue;+ next = removeConnection(next, parsed.sourceId, targetId);+ }+ }++ if (selectedNodeIds.length > 0) {+ next = pruneReferences(next, selectedNodeIds);+ if (selectedId && selectedNodeIds.includes(selectedId)) {+ onSelectStep(null);+ }+ }++ onStepsChange(next);+ },+ [+ readOnly,+ onStepsChange,+ steps,+ selectedNodeIds,+ selectedEdgeIds,+ selectedId,+ onSelectStep,+ ],);return (- <div style={{ width: '100%', height: '100%', background: '#0d1117' }}>+ <div+ style={{+ width: '100%',+ height: '100%',+ background: '#0d1117',+ position: 'relative',+ outline: 'none',+ }}+ tabIndex={0}+ onKeyDown={handleKeyDown}+ >+ {validationError && (+ <div+ role="status"+ aria-live="polite"+ style={{+ position: 'absolute',+ top: 12,+ left: '50%',+ transform: 'translateX(-50%)',+ zIndex: 10,+ padding: '8px 14px',+ borderRadius: 8,+ border: '1px solid #b91c1c',+ background: '#450a0a',+ color: '#fecaca',+ fontSize: 12,+ maxWidth: 480,+ boxShadow: '0 4px 12px rgba(0,0,0,0.4)',+ }}+ >+ ⚠ {validationError}+ </div>+ )}+ {(selectedNodeIds.length > 0 || selectedEdgeIds.length > 0) &&+ !readOnly && (+ <div+ style={{+ position: 'absolute',+ bottom: 12,+ left: 12,+ zIndex: 10,+ padding: '6px 10px',+ borderRadius: 6,+ border: '1px solid #374151',+ background: '#111827',+ color: '#9ca3af',+ fontSize: 11,+ boxShadow: '0 2px 6px rgba(0,0,0,0.4)',+ }}+ >+ {selectedNodeIds.length > 0 && (+ <span>+ {selectedNodeIds.length} step+ {selectedNodeIds.length === 1 ? '' : 's'}+ </span>+ )}+ {selectedNodeIds.length > 0 && selectedEdgeIds.length > 0 && (+ <span> · </span>+ )}+ {selectedEdgeIds.length > 0 && (+ <span>+ {selectedEdgeIds.length} edge+ {selectedEdgeIds.length === 1 ? '' : 's'}+ </span>+ )}+ <span style={{ color: '#6b7280', marginLeft: 8 }}>+ press Delete to remove+ </span>+ </div>+ )}<ReactFlownodes={nodes}edges={edges}onNodesChange={onNodesChange}onEdgesChange={onEdgesChange}onConnect={onConnect}+ onSelectionChange={onSelectionChange}nodeTypes={nodeTypes}fitViewfitViewOptions={{ padding: 0.3 }}nodesDraggable={!readOnly}nodesConnectable={!readOnly}elementsSelectable={true}+ multiSelectionKeyCode="Shift"+ selectionKeyCode="Shift"+ // We handle Delete/Backspace ourselves so we can prune+ // next_true/next_false references and propagate via onStepsChange.+ deleteKeyCode={null}onPaneClick={() => onSelectStep(null)}proOptions={{ hideAttribution: true }}>diff --git a/apps/web/src/components/playbooks/SchemaForm.test.tsx b/apps/web/src/components/playbooks/SchemaForm.test.tsxnew file mode 100644index 000000000..ee95846c4--- /dev/null+++ b/apps/web/src/components/playbooks/SchemaForm.test.tsx@@ -0,0 +1,371 @@+/**+ * SchemaForm + stepSchemas — component & validator tests+ * ======================================================+ *+ * Locks in the user-visible behaviour of the JSON-schema-driven form that+ * replaced the old free-text params textarea (WS-F4). The two surfaces+ * exercised here:+ *+ * 1. The form renders the right control for each field kind, lifts edits+ * via `onChange`, surfaces validation errors, exposes the raw-JSON+ * escape hatch, and warns about extra params not modelled by the+ * schema. It must also remain editable in non-readOnly mode and lock+ * down inputs when readOnly is set.+ *+ * 2. The companion `validateStepParams` helper returns the human+ * messages the inspector renders. Notify is the trickiest case+ * because it has channel-conditional required fields.+ */++import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { useState } from 'react';+import { SchemaForm } from './SchemaForm';++/**+ * Tiny harness that round-trips `value`/`onChange` so the controlled inputs+ * can actually accumulate characters. Without this the parent never updates+ * `value`, React snaps the input back to '' after each keystroke, and+ * "type 900" reduces to "type 0".+ */+function ControlledForm(props: {+ schema: import('./stepSchemas').StepSchema;+ initial?: Record<string, unknown>;+ onChange?: (next: Record<string, unknown>) => void;+}) {+ const [v, setV] = useState<Record<string, unknown>>(props.initial ?? {});+ return (+ <SchemaForm+ schema={props.schema}+ value={v}+ onChange={(next) => {+ setV(next);+ props.onChange?.(next);+ }}+ />+ );+}+import {+ STEP_SCHEMAS,+ defaultParamsFor,+ validateStepParams,+} from './stepSchemas';++describe('SchemaForm — rendering', () => {+ it('renders all required fields with required asterisks', () => {+ const onChange = vi.fn();+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.block_ip}+ value={{}}+ onChange={onChange}+ />,+ );++ // Both fields on block_ip are required.+ expect(screen.getByText(/IP address field/i)).toBeInTheDocument();+ expect(screen.getByText(/Duration \(seconds\)/i)).toBeInTheDocument();+ // Two asterisks for two required fields.+ const asterisks = screen.getAllByText('*');+ expect(asterisks).toHaveLength(2);+ });++ it('renders a select with the configured options', () => {+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.notify}+ value={{}}+ onChange={vi.fn()}+ />,+ );++ expect(+ screen.getByRole('option', { name: /Slack/i }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('option', { name: /PagerDuty/i }),+ ).toBeInTheDocument();+ });++ it('renders a placeholder prompt for an empty short-help block when no params', () => {+ // Use condition (zero-field schema) and no extra keys — should fall+ // through to the short helper string.+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.condition}+ value={{}}+ onChange={vi.fn()}+ />,+ );+ expect(+ screen.getByText(/configure the predicate via the Condition section/i),+ ).toBeInTheDocument();+ });++ it('shows validation errors when supplied', () => {+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.block_ip}+ value={{}}+ onChange={vi.fn()}+ validationErrors={['IP address field is required.']}+ />,+ );+ expect(+ screen.getByRole('alert'),+ ).toHaveTextContent(/IP address field is required/i);+ });++ it('warns about extra params not modelled by the schema', () => {+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.enrich}+ value={{ indicator_field: 'alert.src_ip', mystery_param: 'kept' }}+ onChange={vi.fn()}+ />,+ );+ expect(+ screen.getByText(/Extra params present that the schema does not model/i),+ ).toBeInTheDocument();+ expect(screen.getByText(/mystery_param/)).toBeInTheDocument();+ });+});++describe('SchemaForm — interaction', () => {+ it('lifts a string field edit through onChange', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.enrich}+ value={{}}+ onChange={onChange}+ />,+ );++ const input = screen.getByPlaceholderText('alert.src_ip');+ await user.type(input, 'a');++ expect(onChange).toHaveBeenLastCalledWith({ indicator_field: 'a' });+ });++ it('lifts a select change through onChange with the option value', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.notify}+ value={{}}+ onChange={onChange}+ />,+ );++ // The first select on notify is `channel`.+ const channel = screen.getAllByRole('combobox')[0];+ await user.selectOptions(channel, 'pagerduty');++ expect(onChange).toHaveBeenLastCalledWith({ channel: 'pagerduty' });+ });++ it('drops a key entirely when its value clears to empty string', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.create_ticket}+ value={{ queue: 'soc' }}+ onChange={onChange}+ />,+ );++ const queueInput = screen.getByPlaceholderText('soc');+ await user.clear(queueInput);++ // Last call should have stripped `queue` entirely.+ const lastCall = onChange.mock.calls.at(-1)![0] as Record<string, unknown>;+ expect('queue' in lastCall).toBe(false);+ });++ it('coerces number fields to numeric values', () => {+ const onChange = vi.fn();+ render(+ <ControlledForm schema={STEP_SCHEMAS.block_ip} onChange={onChange} />,+ );++ const dur = screen.getByRole('spinbutton');+ // Use fireEvent.change so we set the controlled value in one shot rather+ // than relying on character-by-character input synthesis (which fights+ // with the controlled input round-trip).+ fireEvent.change(dur, { target: { value: '900' } });++ const last = onChange.mock.calls.at(-1)![0] as Record<string, unknown>;+ expect(typeof last.duration).toBe('number');+ expect(last.duration).toBe(900);+ });++ it('clears a number field back to undefined when emptied', () => {+ const onChange = vi.fn();+ render(+ <ControlledForm+ schema={STEP_SCHEMAS.block_ip}+ initial={{ duration: 60 }}+ onChange={onChange}+ />,+ );++ const dur = screen.getByRole('spinbutton');+ fireEvent.change(dur, { target: { value: '' } });++ const last = onChange.mock.calls.at(-1)![0] as Record<string, unknown>;+ // The field is dropped from the params object entirely.+ expect('duration' in last).toBe(false);+ });++ it('disables every control when readOnly is true', () => {+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.block_ip}+ value={{ ip_field: 'alert.src_ip', duration: 60 }}+ onChange={vi.fn()}+ readOnly+ />,+ );++ const inputs = [+ ...screen.getAllByRole('textbox', { hidden: true }),+ ...screen.getAllByRole('spinbutton', { hidden: true }),+ ];+ inputs.forEach((el) => {+ expect(el).toBeDisabled();+ });+ });++ it('opens the raw JSON escape hatch on click', async () => {+ const user = userEvent.setup();+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.enrich}+ value={{ indicator_field: 'alert.src_ip' }}+ onChange={vi.fn()}+ />,+ );++ const toggle = screen.getByRole('button', { name: /Advanced \(raw JSON\)/i });+ expect(screen.queryByText(/"indicator_field"/)).not.toBeInTheDocument();++ await user.click(toggle);++ // Now the textarea is visible with the JSON.+ const textarea = screen.getByDisplayValue(/"indicator_field"/);+ expect(textarea).toBeInTheDocument();+ });++ it('flags malformed JSON in the raw escape hatch without firing onChange', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <SchemaForm+ schema={STEP_SCHEMAS.enrich}+ value={{ indicator_field: 'alert.src_ip' }}+ onChange={onChange}+ />,+ );++ await user.click(+ screen.getByRole('button', { name: /Advanced \(raw JSON\)/i }),+ );+ const textarea = screen.getByDisplayValue(/"indicator_field"/);+ onChange.mockClear();+ // fireEvent.change avoids userEvent's curly-brace key-descriptor syntax,+ // which would mis-parse "{not json" as a key combo.+ fireEvent.change(textarea, { target: { value: '{not json' } });++ // No onChange because the parse failed.+ expect(onChange).not.toHaveBeenCalled();+ // And an inline error message surfaces. Browsers/Node phrase JSON parse+ // errors slightly differently across versions, so accept any of the+ // common shapes.+ expect(+ screen.getByText(/Unexpected token|Invalid JSON|in JSON|JSON\.parse/i),+ ).toBeInTheDocument();+ });+});++describe('defaultParamsFor', () => {+ it('seeds defaults for fields that declare them', () => {+ const params = defaultParamsFor('create_ticket');+ expect(params).toEqual({+ priority: 'P2',+ queue: 'soc',+ });+ });++ it('returns an empty object when the schema declares no defaults', () => {+ expect(defaultParamsFor('enrich')).toEqual({});+ // condition has no fields → also empty.+ expect(defaultParamsFor('condition')).toEqual({});+ });+});++describe('validateStepParams', () => {+ it('flags missing required fields', () => {+ const errors = validateStepParams('block_ip', {});+ expect(errors).toEqual(+ expect.arrayContaining([+ 'IP address field is required.',+ 'Duration (seconds) is required.',+ ]),+ );+ });++ it('returns no errors for a fully-populated valid step', () => {+ const errors = validateStepParams('block_ip', {+ ip_field: 'alert.src_ip',+ duration: 3600,+ });+ expect(errors).toEqual([]);+ });++ it('coerces a non-numeric duration into a type error', () => {+ const errors = validateStepParams('block_ip', {+ ip_field: 'alert.src_ip',+ duration: '3600',+ });+ expect(errors).toEqual(+ expect.arrayContaining(['Duration (seconds) must be a number.']),+ );+ });++ it('requires service_key_env when the notify channel is pagerduty', () => {+ const errors = validateStepParams('notify', {+ channel: 'pagerduty',+ message_template: 'hi',+ });+ expect(errors).toEqual(+ expect.arrayContaining([+ 'PagerDuty channel requires a service-key env var.',+ ]),+ );+ });++ it('requires webhook_env when the notify channel is webhook', () => {+ const errors = validateStepParams('notify', {+ channel: 'webhook',+ message_template: 'hi',+ });+ expect(errors).toEqual(+ expect.arrayContaining([+ 'Webhook channel requires a webhook env var.',+ ]),+ );+ });++ it('does not require pagerduty/webhook envs for slack notify', () => {+ const errors = validateStepParams('notify', {+ channel: 'slack',+ message_template: 'hi',+ });+ expect(errors).toEqual([]);+ });+});diff --git a/apps/web/src/components/playbooks/SchemaForm.tsx b/apps/web/src/components/playbooks/SchemaForm.tsxnew file mode 100644index 000000000..4f452dbec--- /dev/null+++ b/apps/web/src/components/playbooks/SchemaForm.tsx@@ -0,0 +1,268 @@+'use client';++/**+ * SchemaForm+ * ==========+ *+ * Renders a typed form for a step's `params` object based on a `StepSchema`+ * descriptor. Replaces the old free-form JSON textarea so users can no+ * longer ship malformed playbooks (the canonical failure mode pre-WS-F4).+ *+ * Each field knows its kind (string, number, boolean, select, env-ref,+ * jsonpath, textarea) and renders the matching control. Unknown keys+ * already present in `params` are surfaced under an "Advanced (raw JSON)"+ * disclosure so power-users can still edit anything the schema does not+ * model.+ */++import React, { useMemo, useState } from 'react';+import type { FieldDescriptor, StepSchema } from './stepSchemas';++interface SchemaFormProps {+ schema: StepSchema;+ value: Record<string, unknown>;+ onChange: (next: Record<string, unknown>) => void;+ readOnly?: boolean;+ validationErrors?: readonly string[];+}++function renderControl(+ field: FieldDescriptor,+ value: unknown,+ onChange: (v: unknown) => void,+ readOnly: boolean,+): React.ReactNode {+ const baseClass =+ 'w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-white text-sm focus:outline-none focus:border-blue-500 disabled:opacity-60';++ switch (field.kind) {+ case 'textarea':+ return (+ <textarea+ rows={4}+ placeholder={field.placeholder}+ value={typeof value === 'string' ? value : ''}+ onChange={(e) => onChange(e.target.value)}+ disabled={readOnly}+ className={`${baseClass} font-mono text-xs`}+ />+ );+ case 'number':+ return (+ <input+ type="number"+ placeholder={field.placeholder}+ value={value === undefined || value === null ? '' : String(value)}+ onChange={(e) => {+ const raw = e.target.value;+ if (raw === '') {+ onChange(undefined);+ } else {+ const n = Number(raw);+ onChange(Number.isFinite(n) ? n : raw);+ }+ }}+ disabled={readOnly}+ className={baseClass}+ />+ );+ case 'boolean':+ return (+ <label className="inline-flex items-center gap-2 text-gray-300">+ <input+ type="checkbox"+ checked={Boolean(value)}+ onChange={(e) => onChange(e.target.checked)}+ disabled={readOnly}+ />+ <span className="text-xs">Enabled</span>+ </label>+ );+ case 'select':+ return (+ <select+ value={typeof value === 'string' ? value : ''}+ onChange={(e) => onChange(e.target.value || undefined)}+ disabled={readOnly}+ className={baseClass}+ >+ <option value="">— select —</option>+ {field.options?.map((opt) => (+ <option key={opt.value} value={opt.value}>+ {opt.label}+ </option>+ ))}+ </select>+ );+ case 'env_ref':+ return (+ <input+ type="text"+ placeholder={field.placeholder}+ value={typeof value === 'string' ? value : ''}+ onChange={(e) => onChange(e.target.value || undefined)}+ disabled={readOnly}+ className={`${baseClass} font-mono`}+ />+ );+ case 'jsonpath':+ return (+ <input+ type="text"+ placeholder={field.placeholder}+ value={typeof value === 'string' ? value : ''}+ onChange={(e) => onChange(e.target.value || undefined)}+ disabled={readOnly}+ className={`${baseClass} font-mono`}+ />+ );+ case 'string':+ default:+ return (+ <input+ type="text"+ placeholder={field.placeholder}+ value={typeof value === 'string' ? value : ''}+ onChange={(e) => onChange(e.target.value || undefined)}+ disabled={readOnly}+ className={baseClass}+ />+ );+ }+}++export function SchemaForm({+ schema,+ value,+ onChange,+ readOnly = false,+ validationErrors,+}: SchemaFormProps) {+ const knownKeys = useMemo(+ () => new Set(schema.fields.map((f) => f.key)),+ [schema],+ );+ const extraKeys = useMemo(+ () => Object.keys(value).filter((k) => !knownKeys.has(k)),+ [value, knownKeys],+ );++ const [showRaw, setShowRaw] = useState(false);+ const [rawDraft, setRawDraft] = useState<string>(() =>+ JSON.stringify(value, null, 2),+ );+ const [rawError, setRawError] = useState<string | null>(null);++ function setField(key: string, next: unknown) {+ if (next === undefined) {+ // Drop the key entirely so we don't persist `undefined`s into JSON.+ const { [key]: _drop, ...rest } = value;+ onChange(rest);+ } else {+ onChange({ ...value, [key]: next });+ }+ }++ if (schema.fields.length === 0 && extraKeys.length === 0) {+ return (+ <div className="text-xs text-gray-500 italic">+ {schema.type === 'condition'+ ? 'Conditions have no params — configure the predicate via the Condition section above.'+ : 'No parameters for this step type.'}+ </div>+ );+ }++ return (+ <div className="space-y-3">+ {schema.fields.map((field) => (+ <div key={field.key}>+ <label className="block text-gray-400 text-xs mb-1">+ {field.label}+ {field.required && (+ <span className="text-red-400 ml-1" aria-hidden>+ *+ </span>+ )}+ </label>+ {renderControl(+ field,+ value[field.key],+ (v) => setField(field.key, v),+ readOnly,+ )}+ {field.help && (+ <div className="text-[11px] text-gray-500 mt-1">{field.help}</div>+ )}+ </div>+ ))}++ {validationErrors && validationErrors.length > 0 && (+ <ul+ role="alert"+ className="text-xs text-red-400 bg-red-950/30 border border-red-900 rounded p-2 space-y-1"+ >+ {validationErrors.map((msg) => (+ <li key={msg}>• {msg}</li>+ ))}+ </ul>+ )}++ {extraKeys.length > 0 && (+ <div className="text-xs text-amber-400 bg-amber-950/20 border border-amber-900/60 rounded p-2">+ Extra params present that the schema does not model:{' '}+ <code className="font-mono">{extraKeys.join(', ')}</code>. They will+ be preserved on save.+ </div>+ )}++ {/* Raw JSON escape hatch */}+ <div className="border-t border-gray-800 pt-3">+ <button+ type="button"+ onClick={() => {+ setRawDraft(JSON.stringify(value, null, 2));+ setRawError(null);+ setShowRaw((v) => !v);+ }}+ className="text-xs text-gray-500 hover:text-gray-300 transition-colors"+ >+ {showRaw ? '▾' : '▸'} Advanced (raw JSON)+ </button>+ {showRaw && (+ <div className="mt-2">+ <textarea+ rows={6}+ value={rawDraft}+ onChange={(e) => {+ setRawDraft(e.target.value);+ try {+ const parsed = JSON.parse(e.target.value);+ if (+ typeof parsed !== 'object' ||+ parsed === null ||+ Array.isArray(parsed)+ ) {+ setRawError('Params must be a JSON object.');+ return;+ }+ setRawError(null);+ onChange(parsed as Record<string, unknown>);+ } catch (err) {+ setRawError(+ err instanceof Error ? err.message : 'Invalid JSON',+ );+ }+ }}+ disabled={readOnly}+ className="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-green-400 font-mono text-xs focus:outline-none focus:border-blue-500 disabled:opacity-60"+ />+ {rawError && (+ <div className="text-xs text-red-400 mt-1">{rawError}</div>+ )}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/playbooks/StepInspector.tsx b/apps/web/src/components/playbooks/StepInspector.tsxindex a6d5e9d00..169d74846 100644--- a/apps/web/src/components/playbooks/StepInspector.tsx+++ b/apps/web/src/components/playbooks/StepInspector.tsx@@ -2,13 +2,29 @@/*** StepInspector- * Right-side panel showing details for the selected step.- * Allows editing name, type, params, on_failure, condition.+ * =============+ *+ * Right-side panel for the selected playbook step. Now schema-driven:+ * each step type renders a typed form (string, number, select, env-ref,+ * jsonpath, textarea) sourced from `stepSchemas`. The previous free-form+ * JSON textarea is preserved as an "Advanced (raw JSON)" escape hatch+ * inside `SchemaForm` so power users keep parity.+ *+ * Behaviour notes:+ * - When the step kind changes, params are reset to the schema's+ * defaults (mixing kinds would otherwise leave orphaned keys).+ * - The `condition` editor still applies to every step kind; it+ * gates whether the step runs (and, for `condition` steps, drives+ * true/false branching on the canvas).+ * - `validateStepParams` is run on every change and surfaced in the+ * form so users see required-field issues before saving.*/-import React, { useState, useEffect } from 'react';+import React, { useEffect, useMemo, useState } from 'react';import type { PlaybookStep, StepType, OnFailure } from './types';import { STEP_TYPE_META } from './stepColors';+import { STEP_SCHEMAS, defaultParamsFor, validateStepParams } from './stepSchemas';+import { SchemaForm } from './SchemaForm';const ALL_TYPES: StepType[] = ['enrich',@@ -47,7 +63,22 @@ export function StepInspector({onUpdate(next);}+ function changeType(nextType: StepType) {+ if (nextType === local.type) return;+ // Reset params to the new schema's defaults so the form doesn't render+ // a sea of "extra params present" warnings.+ update({+ type: nextType,+ params: defaultParamsFor(nextType),+ });+ }+const meta = STEP_TYPE_META[local.type];+ const schema = STEP_SCHEMAS[local.type];+ const validationErrors = useMemo(+ () => validateStepParams(local.type, local.params ?? {}),+ [local.type, local.params],+ );return (<div className="h-full overflow-y-auto p-4 space-y-4 text-sm">@@ -55,7 +86,14 @@ export function StepInspector({<div className="flex items-center justify-between"><div className="flex items-center gap-2"><span style={{ color: meta.color, fontSize: 18 }}>{meta.icon}</span>- <span style={{ color: meta.color, fontWeight: 700, fontSize: 12, textTransform: 'uppercase' }}>+ <span+ style={{+ color: meta.color,+ fontWeight: 700,+ fontSize: 12,+ textTransform: 'uppercase',+ }}+ >{meta.label}</span></div>@@ -69,6 +107,12 @@ export function StepInspector({)}</div>+ {schema.description && (+ <div className="text-xs text-gray-500 leading-relaxed">+ {schema.description}+ </div>+ )}+{/* Name */}<div><label className="block text-gray-400 text-xs mb-1">Step Name</label>@@ -85,7 +129,7 @@ export function StepInspector({<label className="block text-gray-400 text-xs mb-1">Step Type</label><selectvalue={local.type}- onChange={(e) => update({ type: e.target.value as StepType })}+ onChange={(e) => changeType(e.target.value as StepType)}disabled={readOnly}className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-white text-sm focus:outline-none focus:border-blue-500 disabled:opacity-60">@@ -133,7 +177,9 @@ export function StepInspector({min={1}max={600}value={local.timeout_seconds}- onChange={(e) => update({ timeout_seconds: Number(e.target.value) })}+ onChange={(e) =>+ update({ timeout_seconds: Number(e.target.value) })+ }disabled={readOnly}className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-white text-sm focus:outline-none focus:border-blue-500 disabled:opacity-60"/>@@ -142,7 +188,9 @@ export function StepInspector({{/* Condition */}<div>- <label className="block text-gray-400 text-xs mb-1">Condition (optional)</label>+ <label className="block text-gray-400 text-xs mb-1">+ Condition (optional)+ </label><div className="space-y-2 border border-gray-700 rounded p-3"><div><input@@ -168,7 +216,13 @@ export function StepInspector({update({condition: {field: local.condition?.field ?? '',- operator: e.target.value as 'eq' | 'ne' | 'gt' | 'lt' | 'contains' | 'exists',+ operator: e.target.value as+ | 'eq'+ | 'ne'+ | 'gt'+ | 'lt'+ | 'contains'+ | 'exists',value: local.condition?.value,},})@@ -211,22 +265,15 @@ export function StepInspector({</div></div>- {/* Params (JSON editor) */}+ {/* Params — schema-driven */}<div>- <label className="block text-gray-400 text-xs mb-1">Params (JSON)</label>- <textarea- rows={5}- value={JSON.stringify(local.params, null, 2)}- onChange={(e) => {- try {- const parsed = JSON.parse(e.target.value);- update({ params: parsed });- } catch {- /* ignore parse errors while typing */- }- }}- disabled={readOnly}- className="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-green-400 font-mono text-xs focus:outline-none focus:border-blue-500 disabled:opacity-60"+ <label className="block text-gray-400 text-xs mb-1">Params</label>+ <SchemaForm+ schema={schema}+ value={(local.params ?? {}) as Record<string, unknown>}+ onChange={(next) => update({ params: next })}+ readOnly={readOnly}+ validationErrors={validationErrors}/></div>diff --git a/apps/web/src/components/playbooks/connectionValidation.test.ts b/apps/web/src/components/playbooks/connectionValidation.test.tsnew file mode 100644index 000000000..6ade359ef--- /dev/null+++ b/apps/web/src/components/playbooks/connectionValidation.test.ts@@ -0,0 +1,263 @@+/**+ * connectionValidation — unit tests+ * =================================+ *+ * The visual canvas leans on these helpers to keep the playbook DAG+ * coherent. If any of these rules silently regress, the editor will+ * "lose" edges on save (a frustrating, hard-to-debug class of bug).+ *+ * Coverage map:+ * - validateConnection: self-loop, missing nodes, terminal sources,+ * cycles, condition true/false branches, duplicate edges, linear+ * overflow.+ * - applyConnection: writes into next_true / next_false correctly.+ * - removeConnection: clears both branches if they match.+ * - pruneReferences: drops nodes and dangling pointers.+ * - hasPath: BFS-style reachability used by the cycle detector.+ */++import { describe, expect, it } from 'vitest';+import {+ applyConnection,+ hasPath,+ pruneReferences,+ removeConnection,+ validateConnection,+} from './connectionValidation';+import type { PlaybookStep, StepType } from './types';++function step(+ id: string,+ type: StepType = 'enrich',+ overrides: Partial<PlaybookStep> = {},+): PlaybookStep {+ return {+ id,+ name: id,+ type,+ params: {},+ on_failure: 'abort',+ retry_max: 0,+ timeout_seconds: 30,+ ...overrides,+ };+}++describe('validateConnection', () => {+ it('rejects self-loops', () => {+ const steps = [step('a')];+ const r = validateConnection(steps, 'a', 'a');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/itself/i);+ });++ it('rejects when source step is missing', () => {+ const steps = [step('a')];+ const r = validateConnection(steps, 'ghost', 'a');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/Source.*ghost/);+ });++ it('rejects when target step is missing', () => {+ const steps = [step('a')];+ const r = validateConnection(steps, 'a', 'ghost');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/Target.*ghost/);+ });++ it('rejects outgoing edges from a terminal step (close_case)', () => {+ const steps = [step('a', 'close_case'), step('b')];+ const r = validateConnection(steps, 'a', 'b');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/terminal/i);+ });++ it('rejects edges that would create a cycle', () => {+ // a -> b -> c, then proposing c -> a would close the loop.+ const steps = [+ step('a', 'enrich', { next_true: 'b' }),+ step('b', 'enrich', { next_true: 'c' }),+ step('c'),+ ];+ const r = validateConnection(steps, 'c', 'a');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/cycle/i);+ });++ it('accepts a fresh linear edge and labels it "next"', () => {+ const steps = [step('a'), step('b')];+ const r = validateConnection(steps, 'a', 'b');+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.branch).toBe('next');+ });++ it('rejects a second outgoing edge from a non-condition source', () => {+ const steps = [+ step('a', 'enrich', { next_true: 'b' }),+ step('b'),+ step('c'),+ ];+ const r = validateConnection(steps, 'a', 'c');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/already has an outgoing/i);+ });++ it('rejects an exact-duplicate linear edge', () => {+ const steps = [step('a', 'enrich', { next_true: 'b' }), step('b')];+ const r = validateConnection(steps, 'a', 'b');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/already exists/i);+ });++ it('routes a condition source to the true branch by default', () => {+ const steps = [step('a', 'condition'), step('b')];+ const r = validateConnection(steps, 'a', 'b');+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.branch).toBe('true');+ });++ it('routes a condition source to the false branch when handle is "false"', () => {+ const steps = [step('a', 'condition'), step('b')];+ const r = validateConnection(steps, 'a', 'b', 'false');+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.branch).toBe('false');+ });++ it('lets a condition fan out to true AND false to different targets', () => {+ // condition already wired to true=b; we now ask to wire false=c.+ const steps = [+ step('a', 'condition', { next_true: 'b' }),+ step('b'),+ step('c'),+ ];+ const r = validateConnection(steps, 'a', 'c', 'false');+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.branch).toBe('false');+ });++ it('rejects re-wiring the same branch on a condition to the same target', () => {+ const steps = [+ step('a', 'condition', { next_true: 'b' }),+ step('b'),+ ];+ const r = validateConnection(steps, 'a', 'b', 'true');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/true branch/i);+ });+});++describe('applyConnection', () => {+ it('writes into next_true on a "next" branch', () => {+ const steps = [step('a'), step('b')];+ const out = applyConnection(steps, 'a', 'b', 'next');+ expect(out[0].next_true).toBe('b');+ expect(out[0].next_false).toBeUndefined();+ });++ it('writes into next_true on a "true" branch', () => {+ const steps = [step('a', 'condition'), step('b')];+ const out = applyConnection(steps, 'a', 'b', 'true');+ expect(out[0].next_true).toBe('b');+ });++ it('writes into next_false on a "false" branch', () => {+ const steps = [step('a', 'condition'), step('b')];+ const out = applyConnection(steps, 'a', 'b', 'false');+ expect(out[0].next_false).toBe('b');+ expect(out[0].next_true).toBeUndefined();+ });++ it('returns a new array — pure / immutable', () => {+ const steps = [step('a'), step('b')];+ const out = applyConnection(steps, 'a', 'b', 'next');+ expect(out).not.toBe(steps);+ expect(out[0]).not.toBe(steps[0]);+ expect(steps[0].next_true).toBeUndefined();+ });+});++describe('removeConnection', () => {+ it('clears next_true when it matches', () => {+ const steps = [step('a', 'enrich', { next_true: 'b' }), step('b')];+ const out = removeConnection(steps, 'a', 'b');+ expect(out[0].next_true).toBeUndefined();+ });++ it('clears next_false when it matches', () => {+ const steps = [+ step('a', 'condition', { next_false: 'b' }),+ step('b'),+ ];+ const out = removeConnection(steps, 'a', 'b');+ expect(out[0].next_false).toBeUndefined();+ });++ it('returns the source object unchanged when no slot matches', () => {+ const steps = [step('a', 'enrich', { next_true: 'c' }), step('b'), step('c')];+ const out = removeConnection(steps, 'a', 'b');+ // Same reference for the unaffected source step (no churn for memoized renderers).+ expect(out[0]).toBe(steps[0]);+ });+});++describe('pruneReferences', () => {+ it('drops removed nodes and clears dangling pointers', () => {+ // a -> b (will delete) -> c, plus a condition d with false=b.+ const steps = [+ step('a', 'enrich', { next_true: 'b' }),+ step('b', 'enrich', { next_true: 'c' }),+ step('c'),+ step('d', 'condition', { next_true: 'c', next_false: 'b' }),+ ];+ const out = pruneReferences(steps, ['b']);+ const ids = out.map((s) => s.id).sort();+ expect(ids).toEqual(['a', 'c', 'd']);++ const a = out.find((s) => s.id === 'a')!;+ const d = out.find((s) => s.id === 'd')!;+ expect(a.next_true).toBeUndefined();+ expect(d.next_false).toBeUndefined();+ // Untouched pointer is still intact.+ expect(d.next_true).toBe('c');+ });++ it('returns the same step ref when no pointers changed', () => {+ const steps = [step('a', 'enrich', { next_true: 'b' }), step('b')];+ const out = pruneReferences(steps, ['c']);+ expect(out[0]).toBe(steps[0]);+ expect(out[1]).toBe(steps[1]);+ });+});++describe('hasPath', () => {+ it('returns true for the trivial start === goal case', () => {+ expect(hasPath([step('a')], 'a', 'a')).toBe(true);+ });++ it('walks both true and false branches', () => {+ const steps = [+ step('a', 'condition', { next_true: 'b', next_false: 'c' }),+ step('b'),+ step('c', 'enrich', { next_true: 'd' }),+ step('d'),+ ];+ expect(hasPath(steps, 'a', 'd')).toBe(true);+ expect(hasPath(steps, 'a', 'b')).toBe(true);+ });++ it('returns false for unreachable goals', () => {+ const steps = [step('a', 'enrich', { next_true: 'b' }), step('b'), step('c')];+ expect(hasPath(steps, 'a', 'c')).toBe(false);+ });++ it('does not loop forever on a malformed cyclic graph', () => {+ // The validator prevents these from being created via the UI but the+ // function itself should still terminate on bad input that arrived+ // via a JSON paste or a buggy backend.+ const steps = [+ step('a', 'enrich', { next_true: 'b' }),+ step('b', 'enrich', { next_true: 'a' }),+ ];+ expect(hasPath(steps, 'a', 'c')).toBe(false);+ });+});diff --git a/apps/web/src/components/playbooks/connectionValidation.ts b/apps/web/src/components/playbooks/connectionValidation.tsnew file mode 100644index 000000000..e37f78cff--- /dev/null+++ b/apps/web/src/components/playbooks/connectionValidation.ts@@ -0,0 +1,211 @@+/**+ * connectionValidation+ * ====================+ *+ * Pure helpers that decide whether a proposed edge between two playbook+ * steps is structurally valid, and write user-drawn edges back into the+ * `PlaybookStep.next_true` / `next_false` fields the backend stores.+ *+ * The visual canvas previously let users freely drop arbitrary edges that+ * never persisted (silent data loss on save). This module makes the+ * editor honest:+ *+ * 1. Disallow self-loops.+ * 2. Disallow duplicate edges between the same source/target pair.+ * 3. Disallow edges that introduce a cycle (DAG invariant).+ * 4. Only `condition` steps support a true/false branch fork. Linear+ * steps may have at most ONE outgoing edge (sequential next).+ * 5. `close_case` is a terminal step — it has no outgoing edge.+ * 6. Everything else is rejected with a structured reason that the UI+ * can surface as a toast.+ */++import type { PlaybookStep, StepType } from './types';++export type EdgeBranch = 'true' | 'false' | 'next';++export interface ValidationFailure {+ ok: false;+ reason: string;+}++export interface ValidationSuccess {+ ok: true;+ branch: EdgeBranch;+}++export type ValidationResult = ValidationFailure | ValidationSuccess;++const TERMINAL_TYPES: ReadonlySet<StepType> = new Set<StepType>(['close_case']);++/**+ * Returns true iff there is already a path from `start` to `goal` via the+ * declared `next_true` / `next_false` edges (visiting each node once). This+ * is the basis of the cycle check: the proposed edge would create a cycle+ * iff the *target* already has a path back to the *source*.+ */+export function hasPath(+ steps: PlaybookStep[],+ start: string,+ goal: string,+): boolean {+ if (start === goal) return true;+ const byId = new Map(steps.map((s) => [s.id, s]));+ const stack: string[] = [start];+ const seen = new Set<string>();+ while (stack.length) {+ const id = stack.pop()!;+ if (seen.has(id)) continue;+ seen.add(id);+ const node = byId.get(id);+ if (!node) continue;+ if (node.next_true) {+ if (node.next_true === goal) return true;+ stack.push(node.next_true);+ }+ if (node.next_false) {+ if (node.next_false === goal) return true;+ stack.push(node.next_false);+ }+ }+ return false;+}++/**+ * Validates a proposed edge from `sourceId` to `targetId`.+ *+ * The optional `sourceHandle` is the React Flow handle id, which we use to+ * decide whether the edge should land on the true or false branch of a+ * `condition` step. For non-condition sources the value is ignored.+ */+export function validateConnection(+ steps: PlaybookStep[],+ sourceId: string,+ targetId: string,+ sourceHandle?: string | null,+): ValidationResult {+ if (sourceId === targetId) {+ return { ok: false, reason: 'A step cannot connect to itself.' };+ }+ const byId = new Map(steps.map((s) => [s.id, s]));+ const source = byId.get(sourceId);+ const target = byId.get(targetId);+ if (!source) {+ return { ok: false, reason: `Source step ${sourceId} no longer exists.` };+ }+ if (!target) {+ return { ok: false, reason: `Target step ${targetId} no longer exists.` };+ }+ if (TERMINAL_TYPES.has(source.type)) {+ return {+ ok: false,+ reason: `${source.type} is terminal — it cannot have outgoing edges.`,+ };+ }++ // Cycle check — would an edge source→target close a loop back to source?+ if (hasPath(steps, targetId, sourceId)) {+ return {+ ok: false,+ reason: 'That connection would create a cycle. Playbooks must be acyclic.',+ };+ }++ if (source.type === 'condition') {+ const branch: EdgeBranch =+ sourceHandle === 'false' ? 'false' : 'true';+ const slot = branch === 'true' ? source.next_true : source.next_false;+ if (slot === targetId) {+ return {+ ok: false,+ reason: `Condition already has a ${branch} branch to that step.`,+ };+ }+ return { ok: true, branch };+ }++ // Linear step: a single outbound edge stored in next_true.+ if (source.next_true && source.next_true !== targetId) {+ return {+ ok: false,+ reason:+ 'This step already has an outgoing connection. Remove it before adding a new one, or convert to a condition.',+ };+ }+ if (source.next_true === targetId) {+ return {+ ok: false,+ reason: 'That connection already exists.',+ };+ }+ return { ok: true, branch: 'next' };+}++/**+ * Apply a validated connection to the steps array. Pure, returns a new+ * array. Caller is expected to have already invoked `validateConnection`+ * and confirmed `ok: true`.+ */+export function applyConnection(+ steps: PlaybookStep[],+ sourceId: string,+ targetId: string,+ branch: EdgeBranch,+): PlaybookStep[] {+ return steps.map((s) => {+ if (s.id !== sourceId) return s;+ if (branch === 'true') return { ...s, next_true: targetId };+ if (branch === 'false') return { ...s, next_false: targetId };+ return { ...s, next_true: targetId };+ });+}++/**+ * Remove an edge by clearing the matching next_true / next_false slot on+ * the source. Pure, returns a new array. If the source has neither slot+ * pointing at the target the steps array is returned unchanged.+ */+export function removeConnection(+ steps: PlaybookStep[],+ sourceId: string,+ targetId: string,+): PlaybookStep[] {+ return steps.map((s) => {+ if (s.id !== sourceId) return s;+ let changed = false;+ let nextTrue = s.next_true;+ let nextFalse = s.next_false;+ if (nextTrue === targetId) {+ nextTrue = undefined;+ changed = true;+ }+ if (nextFalse === targetId) {+ nextFalse = undefined;+ changed = true;+ }+ if (!changed) return s;+ return { ...s, next_true: nextTrue, next_false: nextFalse };+ });+}++/**+ * Strip every reference (incoming and outgoing) to `removedIds` from the+ * surviving steps. Used after bulk delete so dangling next_true/next_false+ * pointers don't render as broken edges on next layout.+ */+export function pruneReferences(+ steps: PlaybookStep[],+ removedIds: Iterable<string>,+): PlaybookStep[] {+ const drop = new Set(removedIds);+ return steps+ .filter((s) => !drop.has(s.id))+ .map((s) => {+ let nt = s.next_true;+ let nf = s.next_false;+ if (nt && drop.has(nt)) nt = undefined;+ if (nf && drop.has(nf)) nf = undefined;+ if (nt === s.next_true && nf === s.next_false) return s;+ return { ...s, next_true: nt, next_false: nf };+ });+}diff --git a/apps/web/src/components/playbooks/stepSchemas.ts b/apps/web/src/components/playbooks/stepSchemas.tsnew file mode 100644index 000000000..abc0a4a04--- /dev/null+++ b/apps/web/src/components/playbooks/stepSchemas.ts@@ -0,0 +1,388 @@+/**+ * stepSchemas+ * ===========+ *+ * Lightweight schema registry for playbook step parameters. Drives the+ * StepInspector form so each step kind gets a typed editor instead of a+ * raw JSON textarea.+ *+ * The shape is *deliberately* simpler than full JSON Schema: only the+ * features the SOAR canvas actually needs (string, textarea, number,+ * boolean, select, env-ref, jsonpath). Extending later is straightforward.+ *+ * Empirical canonical shapes (from `playbooks/packs/v1/`):+ * block_ip : { duration, ip_field }+ * close_case : { resolution }+ * condition : { (no params; the condition lives on the step itself) }+ * create_ticket : { priority, queue, title_template }+ * enrich : { indicator_field }+ * http : { body_template?, headers_env?, method, url }+ * investigate : { case_id_field, focus? }+ * isolate_host : { host_field }+ * notify : { channel, message_template, service_key_env? | webhook_env? }+ */++import type { StepType } from './types';++export type FieldKind =+ | 'string'+ | 'textarea'+ | 'number'+ | 'boolean'+ | 'select'+ | 'env_ref'+ | 'jsonpath';++export interface FieldOption {+ value: string;+ label: string;+}++export interface FieldDescriptor {+ /** Param key (object key inside step.params). */+ key: string;+ /** Human label rendered as the form label. */+ label: string;+ kind: FieldKind;+ /** True if leaving the field empty should fail validation on save. */+ required?: boolean;+ /** Placeholder for string-y inputs. */+ placeholder?: string;+ /** Subtle help text rendered under the field. */+ help?: string;+ /** For select kinds. */+ options?: readonly FieldOption[];+ /** Optional default applied when a step is created. */+ defaultValue?: unknown;+}++export interface StepSchema {+ type: StepType;+ label: string;+ description: string;+ /** Pretty colour token used in the canvas / palette. */+ accent: string;+ /** Single-emoji icon used in the palette. */+ icon: string;+ fields: readonly FieldDescriptor[];+}++const NOTIFY_CHANNELS: readonly FieldOption[] = [+ { value: 'slack', label: 'Slack' },+ { value: 'pagerduty', label: 'PagerDuty' },+ { value: 'email', label: 'Email' },+ { value: 'webhook', label: 'Generic webhook' },+];++const TICKET_PRIORITIES: readonly FieldOption[] = [+ { value: 'P1', label: 'P1 — Critical' },+ { value: 'P2', label: 'P2 — High' },+ { value: 'P3', label: 'P3 — Medium' },+ { value: 'P4', label: 'P4 — Low' },+];++const HTTP_METHODS: readonly FieldOption[] = [+ { value: 'GET', label: 'GET' },+ { value: 'POST', label: 'POST' },+ { value: 'PUT', label: 'PUT' },+ { value: 'PATCH', label: 'PATCH' },+ { value: 'DELETE', label: 'DELETE' },+];++const INVESTIGATE_FOCUS: readonly FieldOption[] = [+ { value: 'forensics', label: 'Forensics' },+ { value: 'identity', label: 'Identity' },+ { value: 'network', label: 'Network' },+ { value: 'cloud', label: 'Cloud' },+ { value: 'malware', label: 'Malware' },+];++export const STEP_SCHEMAS: Record<StepType, StepSchema> = {+ enrich: {+ type: 'enrich',+ label: 'Enrich',+ description: 'Look up additional context for an indicator (IP, hash, user, asset).',+ accent: '#38bdf8',+ icon: '🔍',+ fields: [+ {+ key: 'indicator_field',+ label: 'Indicator field',+ kind: 'jsonpath',+ required: true,+ placeholder: 'alert.src_ip',+ help: 'JSON path on the alert/case context to enrich.',+ },+ ],+ },+ investigate: {+ type: 'investigate',+ label: 'Investigate',+ description: 'Run the investigator agent against a case to gather artefacts and timeline.',+ accent: '#a78bfa',+ icon: '🕵️',+ fields: [+ {+ key: 'case_id_field',+ label: 'Case ID field',+ kind: 'jsonpath',+ required: true,+ placeholder: 'alert.case_id',+ },+ {+ key: 'focus',+ label: 'Focus',+ kind: 'select',+ options: INVESTIGATE_FOCUS,+ help: 'Optional bias for what artefacts to pull first.',+ },+ ],+ },+ notify: {+ type: 'notify',+ label: 'Notify',+ description: 'Send a notification to Slack, PagerDuty, email, or a generic webhook.',+ accent: '#facc15',+ icon: '🔔',+ fields: [+ {+ key: 'channel',+ label: 'Channel',+ kind: 'select',+ required: true,+ options: NOTIFY_CHANNELS,+ defaultValue: 'slack',+ },+ {+ key: 'message_template',+ label: 'Message template',+ kind: 'textarea',+ required: true,+ placeholder: 'Lateral movement detected on {{alert.host}}',+ help: 'Mustache-style template; fields from alert/case are interpolated at runtime.',+ },+ {+ key: 'service_key_env',+ label: 'PagerDuty service key env',+ kind: 'env_ref',+ placeholder: 'PD_SOC_KEY',+ help: 'Required only for the PagerDuty channel.',+ },+ {+ key: 'webhook_env',+ label: 'Webhook URL env',+ kind: 'env_ref',+ placeholder: 'SOC_WEBHOOK_URL',+ help: 'Required only for the generic webhook channel.',+ },+ ],+ },+ block_ip: {+ type: 'block_ip',+ label: 'Block IP',+ description: 'Push a blocklist rule into the network executor (firewall / WAF / cloud SG).',+ accent: '#f87171',+ icon: '🚫',+ fields: [+ {+ key: 'ip_field',+ label: 'IP address field',+ kind: 'jsonpath',+ required: true,+ placeholder: 'alert.src_ip',+ },+ {+ key: 'duration',+ label: 'Duration (seconds)',+ kind: 'number',+ required: true,+ defaultValue: 3600,+ help: 'How long the block should remain in place. Use 0 for permanent.',+ },+ ],+ },+ isolate_host: {+ type: 'isolate_host',+ label: 'Isolate host',+ description: 'Quarantine an endpoint via the EDR (CrowdStrike, Defender, etc.).',+ accent: '#fb7185',+ icon: '🛡️',+ fields: [+ {+ key: 'host_field',+ label: 'Host field',+ kind: 'jsonpath',+ required: true,+ placeholder: 'alert.host',+ },+ ],+ },+ create_ticket: {+ type: 'create_ticket',+ label: 'Create ticket',+ description: 'Open a Jira / ServiceNow ticket for SOC follow-up.',+ accent: '#34d399',+ icon: '📝',+ fields: [+ {+ key: 'priority',+ label: 'Priority',+ kind: 'select',+ required: true,+ options: TICKET_PRIORITIES,+ defaultValue: 'P2',+ },+ {+ key: 'queue',+ label: 'Queue',+ kind: 'string',+ required: true,+ placeholder: 'soc',+ defaultValue: 'soc',+ },+ {+ key: 'title_template',+ label: 'Title template',+ kind: 'string',+ required: true,+ placeholder: 'Lateral movement: {{alert.src_host}} -> {{alert.dst_host}}',+ },+ ],+ },+ close_case: {+ type: 'close_case',+ label: 'Close case',+ description: 'Mark the case resolved. Terminal step — no outgoing edges allowed.',+ accent: '#94a3b8',+ icon: '✅',+ fields: [+ {+ key: 'resolution',+ label: 'Resolution',+ kind: 'select',+ required: true,+ options: [+ { value: 'true_positive_contained', label: 'True positive — contained' },+ { value: 'true_positive_remediated', label: 'True positive — remediated' },+ { value: 'false_positive', label: 'False positive' },+ { value: 'benign', label: 'Benign / expected' },+ { value: 'duplicate', label: 'Duplicate' },+ ],+ defaultValue: 'true_positive_contained',+ },+ ],+ },+ http: {+ type: 'http',+ label: 'HTTP request',+ description: 'Generic outbound HTTP — useful for arbitrary integrations.',+ accent: '#60a5fa',+ icon: '🌐',+ fields: [+ {+ key: 'method',+ label: 'Method',+ kind: 'select',+ required: true,+ options: HTTP_METHODS,+ defaultValue: 'POST',+ },+ {+ key: 'url',+ label: 'URL',+ kind: 'string',+ required: true,+ placeholder: 'https://example.com/api/notify',+ },+ {+ key: 'headers_env',+ label: 'Headers env',+ kind: 'env_ref',+ placeholder: 'INTEGRATION_HEADERS',+ help: 'Optional. Env var holding a JSON-encoded headers object.',+ },+ {+ key: 'body_template',+ label: 'Body template',+ kind: 'textarea',+ placeholder: '{"text": "Alert {{alert.id}}"}',+ help: 'Optional. Mustache-style template for the request body.',+ },+ ],+ },+ condition: {+ type: 'condition',+ label: 'Condition',+ description:+ 'Branch the playbook on a field check. Configure the predicate via the Condition section above.',+ accent: '#fbbf24',+ icon: '❓',+ // condition has no params — its predicate lives on `step.condition`.+ fields: [],+ },+};++/**+ * Default `params` object for a freshly added step. Honours `defaultValue`+ * on each field descriptor so the inspector form is never blank for known+ * required keys.+ */+export function defaultParamsFor(type: StepType): Record<string, unknown> {+ const schema = STEP_SCHEMAS[type];+ const params: Record<string, unknown> = {};+ for (const field of schema.fields) {+ if (field.defaultValue !== undefined) {+ params[field.key] = field.defaultValue;+ }+ }+ return params;+}++/**+ * Returns a list of human-readable validation problems for the given+ * params object against the schema for `type`. An empty array means the+ * step is valid.+ */+export function validateStepParams(+ type: StepType,+ params: Record<string, unknown>,+): string[] {+ const schema = STEP_SCHEMAS[type];+ const errors: string[] = [];+ for (const field of schema.fields) {+ const value = params[field.key];+ if (+ field.required &&+ (value === undefined || value === null || value === '')+ ) {+ errors.push(`${field.label} is required.`);+ }+ if (+ field.kind === 'number' &&+ value !== undefined &&+ value !== null &&+ value !== '' &&+ typeof value !== 'number'+ ) {+ errors.push(`${field.label} must be a number.`);+ }+ if (+ field.kind === 'boolean' &&+ value !== undefined &&+ typeof value !== 'boolean'+ ) {+ errors.push(`${field.label} must be true/false.`);+ }+ }+ // Notify channel-specific cross-field check.+ if (type === 'notify') {+ const channel = params.channel;+ if (channel === 'pagerduty' && !params.service_key_env) {+ errors.push('PagerDuty channel requires a service-key env var.');+ }+ if (channel === 'webhook' && !params.webhook_env) {+ errors.push('Webhook channel requires a webhook env var.');+ }+ }+ return errors;+}diff --git a/apps/web/src/hooks/useHistoryState.test.ts b/apps/web/src/hooks/useHistoryState.test.tsnew file mode 100644index 000000000..759387cbc--- /dev/null+++ b/apps/web/src/hooks/useHistoryState.test.ts@@ -0,0 +1,197 @@+/**+ * useHistoryState — unit tests+ * ============================+ *+ * Locks in the time-travel semantics the playbook editor relies on for+ * WS-F4 (Visual SOAR studio polish). Every behaviour exercised here maps+ * to a real editor flow:+ *+ * - set / undo / redo round-trip → keyboard shortcut handler+ * - `set` clears the redo branch → "edit after undo" rule+ * - `replace` skips history → remote SWR sync on first load+ * - `reset` wipes everything → post-save baseline+ * - bounded history → long sessions don't leak memory+ * - functional updaters → setState((p) => …) form+ * - no-op set is a no-op → Object.is short-circuit+ */++import { describe, expect, it } from 'vitest';+import { act, renderHook } from '@testing-library/react';+import { useHistoryState } from './useHistoryState';++describe('useHistoryState', () => {+ it('starts with the initial value and no history', () => {+ const { result } = renderHook(() => useHistoryState({ count: 0 }));+ const [state, controls] = result.current;+ expect(state).toEqual({ count: 0 });+ expect(controls.canUndo).toBe(false);+ expect(controls.canRedo).toBe(false);+ expect(controls.pastSize).toBe(0);+ expect(controls.futureSize).toBe(0);+ });++ it('pushes prior values onto the past stack on set()', () => {+ const { result } = renderHook(() => useHistoryState(0));++ act(() => {+ result.current[1].set(1);+ });+ expect(result.current[0]).toBe(1);+ expect(result.current[1].canUndo).toBe(true);+ expect(result.current[1].pastSize).toBe(1);++ act(() => {+ result.current[1].set(2);+ });+ expect(result.current[0]).toBe(2);+ expect(result.current[1].pastSize).toBe(2);+ });++ it('undo pops past back to present and pushes the old present onto future', () => {+ const { result } = renderHook(() => useHistoryState('a'));++ act(() => result.current[1].set('b'));+ act(() => result.current[1].set('c'));+ expect(result.current[0]).toBe('c');++ act(() => {+ const ok = result.current[1].undo();+ expect(ok).toBe(true);+ });+ expect(result.current[0]).toBe('b');+ expect(result.current[1].canRedo).toBe(true);++ act(() => {+ const ok = result.current[1].undo();+ expect(ok).toBe(true);+ });+ expect(result.current[0]).toBe('a');+ expect(result.current[1].canUndo).toBe(false);++ // undo past the bottom is a no-op and reports false.+ act(() => {+ const ok = result.current[1].undo();+ expect(ok).toBe(false);+ });+ expect(result.current[0]).toBe('a');+ });++ it('redo replays an undone change', () => {+ const { result } = renderHook(() => useHistoryState('a'));++ act(() => result.current[1].set('b'));+ act(() => result.current[1].undo());+ expect(result.current[0]).toBe('a');+ expect(result.current[1].canRedo).toBe(true);++ act(() => {+ const ok = result.current[1].redo();+ expect(ok).toBe(true);+ });+ expect(result.current[0]).toBe('b');+ expect(result.current[1].canRedo).toBe(false);++ // No redo to do; reports false.+ act(() => {+ const ok = result.current[1].redo();+ expect(ok).toBe(false);+ });+ });++ it('a fresh set() after undo discards the redo branch', () => {+ const { result } = renderHook(() => useHistoryState('a'));++ act(() => result.current[1].set('b'));+ act(() => result.current[1].set('c'));+ act(() => result.current[1].undo()); // back to 'b'+ expect(result.current[1].canRedo).toBe(true);++ act(() => result.current[1].set('d'));+ expect(result.current[0]).toBe('d');+ // Redo branch ('c') should be gone now — this is the core "edit after+ // undo" rule. Without it the user would see ghost history entries.+ expect(result.current[1].canRedo).toBe(false);+ expect(result.current[1].futureSize).toBe(0);+ });++ it('replace() updates state without touching history', () => {+ const { result } = renderHook(() => useHistoryState({ v: 0 }));++ act(() => result.current[1].set({ v: 1 }));+ act(() => result.current[1].set({ v: 2 }));+ const beforePast = result.current[1].pastSize;++ act(() => result.current[1].replace({ v: 99 }));+ expect(result.current[0]).toEqual({ v: 99 });+ // History stayed intact because replace() is the "remote sync" path.+ expect(result.current[1].pastSize).toBe(beforePast);+ expect(result.current[1].futureSize).toBe(0);+ });++ it('reset() clears past and future', () => {+ const { result } = renderHook(() => useHistoryState('a'));++ act(() => result.current[1].set('b'));+ act(() => result.current[1].set('c'));+ act(() => result.current[1].undo());+ expect(result.current[1].canUndo).toBe(true);+ expect(result.current[1].canRedo).toBe(true);++ act(() => result.current[1].reset('z'));+ expect(result.current[0]).toBe('z');+ expect(result.current[1].canUndo).toBe(false);+ expect(result.current[1].canRedo).toBe(false);+ expect(result.current[1].pastSize).toBe(0);+ expect(result.current[1].futureSize).toBe(0);+ });++ it('respects historyLimit and drops the oldest entry', () => {+ const { result } = renderHook(() =>+ useHistoryState(0, { historyLimit: 3 }),+ );++ // 5 sets → past stack should clamp at 3.+ act(() => result.current[1].set(1));+ act(() => result.current[1].set(2));+ act(() => result.current[1].set(3));+ act(() => result.current[1].set(4));+ act(() => result.current[1].set(5));++ expect(result.current[0]).toBe(5);+ expect(result.current[1].pastSize).toBe(3);++ // Three undos take us back as far as the bounded stack allows.+ act(() => result.current[1].undo()); // 4+ act(() => result.current[1].undo()); // 3+ act(() => result.current[1].undo()); // 2 (oldest preserved entry)+ expect(result.current[0]).toBe(2);+ expect(result.current[1].canUndo).toBe(false);+ });++ it('supports functional updaters in set()', () => {+ const { result } = renderHook(() => useHistoryState({ count: 0 }));++ act(() => {+ result.current[1].set((prev) => ({ count: prev.count + 1 }));+ });+ expect(result.current[0]).toEqual({ count: 1 });++ act(() => {+ result.current[1].set((prev) => ({ count: prev.count + 5 }));+ });+ expect(result.current[0]).toEqual({ count: 6 });+ expect(result.current[1].pastSize).toBe(2);+ });++ it('skips the history push when set() returns the identical value', () => {+ const obj = { v: 1 };+ const { result } = renderHook(() => useHistoryState(obj));++ act(() => {+ // Same reference → Object.is short-circuit, no history bump.+ result.current[1].set(obj);+ });+ expect(result.current[1].pastSize).toBe(0);+ expect(result.current[1].canUndo).toBe(false);+ });+});diff --git a/apps/web/src/hooks/useHistoryState.ts b/apps/web/src/hooks/useHistoryState.tsnew file mode 100644index 000000000..47e75f3d6--- /dev/null+++ b/apps/web/src/hooks/useHistoryState.ts@@ -0,0 +1,147 @@+'use client';++/**+ * useHistoryState+ * ===============+ *+ * Generic time-travel state hook. Wraps `useState` with an explicit history+ * stack so callers can undo / redo arbitrary mutations.+ *+ * Design notes (WS-F4 — Visual SOAR studio polish):+ * - History is bounded to `historyLimit` entries (default 50) to keep+ * memory bounded for long editing sessions on big playbooks.+ * - Calling `set` collapses the future stack — i.e. once the user makes+ * a new change after undoing, the redo branch is discarded. This is+ * the same model browsers and most IDEs use.+ * - `replace(next)` updates `present` *without* pushing to history. Useful+ * for "syncing" with remote data on first load: we do not want the load+ * to count as an undoable action.+ * - Equality is by reference. Callers should already produce a fresh+ * object when they intend a real change (which is standard React state+ * practice anyway).+ *+ * Returned tuple shape mimics `[state, setState]` from `useState` so the+ * hook is a near drop-in replacement.+ */++import { useCallback, useRef, useState } from 'react';++export interface HistoryControls<T> {+ set: (next: T | ((prev: T) => T)) => void;+ replace: (next: T) => void;+ undo: () => boolean;+ redo: () => boolean;+ reset: (next: T) => void;+ canUndo: boolean;+ canRedo: boolean;+ pastSize: number;+ futureSize: number;+}++export interface HistoryStateOptions {+ /**+ * Maximum number of entries to keep on the past stack. When exceeded the+ * oldest entry is dropped. Defaults to 50.+ */+ historyLimit?: number;+}++export function useHistoryState<T>(+ initial: T | (() => T),+ options: HistoryStateOptions = {},+): [T, HistoryControls<T>] {+ const limit = options.historyLimit ?? 50;++ const [present, setPresent] = useState<T>(initial);+ // Stacks live in refs to keep referential stability for the controls+ // object across renders. We bump `version` to force re-render when stack+ // sizes change so `canUndo` / `canRedo` flip correctly.+ const past = useRef<T[]>([]);+ const future = useRef<T[]>([]);+ const [, bump] = useState(0);++ const forceRerender = useCallback(() => bump((v) => v + 1), []);++ const set = useCallback(+ (next: T | ((prev: T) => T)) => {+ setPresent((prev) => {+ const resolved =+ typeof next === 'function' ? (next as (p: T) => T)(prev) : next;+ if (Object.is(resolved, prev)) {+ return prev;+ }+ past.current = [...past.current, prev];+ if (past.current.length > limit) {+ past.current = past.current.slice(past.current.length - limit);+ }+ future.current = [];+ forceRerender();+ return resolved;+ });+ },+ [forceRerender, limit],+ );++ const replace = useCallback(+ (next: T) => {+ setPresent(next);+ // History stays intact; this is meant for non-undoable syncs.+ },+ [],+ );++ const undo = useCallback((): boolean => {+ if (past.current.length === 0) {+ return false;+ }+ const previous = past.current[past.current.length - 1];+ past.current = past.current.slice(0, past.current.length - 1);+ setPresent((curr) => {+ future.current = [curr, ...future.current];+ return previous;+ });+ forceRerender();+ return true;+ }, [forceRerender]);++ const redo = useCallback((): boolean => {+ if (future.current.length === 0) {+ return false;+ }+ const next = future.current[0];+ future.current = future.current.slice(1);+ setPresent((curr) => {+ past.current = [...past.current, curr];+ if (past.current.length > limit) {+ past.current = past.current.slice(past.current.length - limit);+ }+ return next;+ });+ forceRerender();+ return true;+ }, [forceRerender, limit]);++ const reset = useCallback(+ (next: T) => {+ past.current = [];+ future.current = [];+ setPresent(next);+ forceRerender();+ },+ [forceRerender],+ );++ const controls: HistoryControls<T> = {+ set,+ replace,+ undo,+ redo,+ reset,+ canUndo: past.current.length > 0,+ canRedo: future.current.length > 0,+ pastSize: past.current.length,+ futureSize: future.current.length,+ };++ return [present, controls];+}