import { Handle, Position, useReactFlow, type NodeProps } from "@xyflow/react"; import { useState } from "react"; import { AlertTriangle, ChevronDown, FileText, SlidersHorizontal, X, } from "lucide-react"; import { resolveNodeSpec, type NodeKind, type NodeParamSpec, type PluginNodeSpec, } from "../lib/nodeCatalog"; import { NodeParamEditor } from "./NodeParamEditor"; import { RunStatusChips } from "./RunStatusChips"; import { SignatureTile } from "./TransformationSignature"; import { ANON } from "../lib/anon"; import { TipIcon } from "./TipIcon"; import { useApp } from "../lib/store"; import { FAMILY_HINTS } from "../lib/familyHints"; import { durationTone, headlineFor } from "../lib/headlineMetric"; export interface QNodeData extends Record { kind: NodeKind; params?: Record; } /** * Visual representation of a pipeline step on the canvas. * * We deliberately keep each node simple (icon + label + 1-2 param hints) — the * full parameter editor / results viewer lives in the ResultsPane on the * right. Noisy per-node inline editors make the graph hard to read. * * A small × button (always rendered, dimmed until hover/focus) lets * users delete a node without knowing the Backspace shortcut. */ export function QNode({ id, data, selected }: NodeProps) { const d = data as QNodeData; const flow = useReactFlow(); const { deleteElements } = flow; // Subscribe to the active circuit so source/algorithm blocks can // surface circuit-relevant context (e.g. Input shows the loaded // sample's qubit count; Qshot warns if the circuit is outside its // 5–8 qubit training range). Hooks must run unconditionally, so we // pull these even when the node kind doesn't use them — Zustand's // shallow comparison keeps the cost cheap. const circuit = useApp((s) => s.circuit); const sampleKey = useApp((s) => s.sampleKey); const plugins = useApp((s) => s.plugins); // After-run state: subscribe to the latest run so each node can // surface its own headline metric + duration badge. Cheap because // run only changes once per Run click. const run = useApp((s) => s.run); // Authoring lock (audit S2): while a run streams, node deletion and // param edits are disabled — mutating the graph mid-run would leave // the canvas out of sync with what is actually executing/archiving. const running = useApp((s) => s.running); const step = run?.steps.find((s) => s.node_id === id); // Anytime evidence: while a run streams, sampled steps report each // shot batch here BEFORE their StepResult exists — the node face // renders a live-narrowing CI from these frames. const liveProgress = useApp((s) => s.liveProgress?.[id]); const stepDurationS = step && step.status === "ok" ? step.finished_at - step.started_at : null; // Spec resolution — built-in OR user plugin. Hook order requires // this stay above any early return. const spec = resolveNodeSpec(d.kind, plugins); // Per-instance disclosure state for the param editor. Default to // collapsed so the canvas stays scannable; users click the chevron // to reveal the controls. State lives in component-local React // state, not in node-data, because it's UI affordance only — we // don't want it serialised into share-links or auto-connect graphs. const [paramsOpen, setParamsOpen] = useState(false); if (!spec) { // Plugin was deleted (or never installed in this browser) while a // node referencing its kind is still on the canvas — show a // tombstone so the user knows what happened instead of an // invisible-but-runnable block. return (
?
{d.kind}
plugin not installed
This browser doesn't have the plugin installed — add it via the plugin API (see PLUGIN_SDK.md), or hover and click × to remove the block.
); } const Icon = spec.icon; /** Patch this node's `data.params` and propagate to React Flow state. */ const patchParams = (patch: Record) => { flow.updateNodeData(id, { ...d, params: { ...(d.params ?? {}), ...patch }, }); }; const hasInput = spec.family !== "source"; const hasOutput = spec.family !== "sink"; return (
{spec.paper && !ANON && ( e.stopPropagation()} title={`Paper: ${spec.paper.title} (${spec.paper.venue})`} aria-label={`Open paper: ${spec.paper.title}`} > )}
{"isPlugin" in spec && spec.isPlugin ? ( // Plugin badge: filled square in plugin's chosen color + // first-letter(s) so users can distinguish multiple plugins // at a glance. {(spec as PluginNodeSpec).initials} ) : ( )}
{spec.label} {"isPlugin" in spec && spec.isPlugin && ( plugin )}
{spec.family}
{spec.tagline}
{/* Circuit-aware context — only kinds that actually depend on the loaded circuit render anything here. */} {d.kind === "input_circuit" && circuit && (
Loaded {sampleKey ?? "uploaded"}
{circuit.num_qubits}q · depth {circuit.depth} {circuit.num_parameters > 0 && ( <> · {circuit.num_parameters} params )}
)} {d.kind === "qshot" && circuit && ( )} {/* Editable params (schema-driven) start collapsed so the block stays compact on a busy canvas. Header row is a chip-like button so it reads as obviously clickable: SlidersHorizontal icon + uppercase "PARAMS" label, current-value summary on the right, ChevronDown that rotates on toggle. The whole row gets a hover background + border so newcomers see the affordance without needing to hover over the chevron. Other node kinds fall back to the static read-out. */} {spec.params && spec.params.length > 0 ? (
{paramsOpen && ( )}
) : ( d.params && Object.keys(d.params).length > 0 && (
{Object.entries(d.params).map(([k, v]) => (
{k} {String(v)}
))}
) )} {!step && liveProgress && ( )} {step && step.status === "ok" && ( )} {step && step.status === "error" && (
{step.message ?? "Failed"}
)} {hasInput && ( )} {hasOutput && ( )}
); } /** Live evidence strip: rendered while a sampled step is still * accumulating shot batches (i.e. before its StepResult exists). * Same 0-1 fixed-scale encoding as the post-run micro CI bar so the * live band morphs seamlessly into the final one; the CSS * left/width transition is what makes the narrowing READ as motion * instead of flicker. The counter states the evidence honestly in * shots, not percent-done — the whole point of anytime steering is * that "done" is the user's call, not the progress bar's. */ function LiveEvidenceStrip({ progress, }: { progress: import("../lib/api").StepProgress; }) { const [lo, hi] = progress.ci95; return (
{(progress.point * 100).toFixed(1)}% {progress.shots_done} shots · batch {progress.batch_i}/ {progress.n_batches}
); } /** After-run strip at the bottom of the node tile: headline metric + * duration chip + cache indicator. None of these are interactive, * but they make the canvas itself a glanceable dashboard once a run * has happened. * * Layout contract (visual-calm audit, 2026-07-10): the strip is at * most the stretched glyph + TWO further rows — (1) headline+chips, * (2) the 3px micro-CI bar — at ANY tile width. The chips row cannot * wrap: it is flex-nowrap, the headline block is min-w-0 + truncate * (it gives way first), the chips are shrink-0, and at most three * small chips can coexist (⏹ shots · one cached/live chip — * RunStatusChips renders at most one — · duration). Worst case * ≈130px of chips against the 180px min tile width, so the headline * truncates rather than the row wrapping. If a chip is ever added * here, re-audit against that budget. */ function RunResultStrip({ kind, step, durationS, }: { kind: NodeKind; step: import("../lib/api").StepResult; durationS: number | null; }) { const headline = headlineFor(kind, step); const tone = durationS !== null ? durationTone(durationS) : null; const durBadgeClass = { fast: "border-edge/60 text-mute/80", medium: "border-accent/40 text-accent/90", slow: "border-warn/50 text-warn", "very-slow": "border-danger/50 text-danger", }[tone ?? "fast"]; const durFormatted = durationS === null ? "" : durationS < 1 ? `${Math.round(durationS * 1000)}ms` : `${durationS.toFixed(durationS < 10 ? 2 : 1)}s`; // Micro CI bar: the same 0-1-scale encoding as the results card's // uncertainty block (interval band + point tick), shrunk to 3px so // a stochastic node face answers "how sure are we" without opening // any panel. Only steps that emit a binomial distribution payload // (sampled fidelity today, plugins tomorrow) render it. const dist = step.distribution as | { kind?: string; point?: number; ci95?: [number, number]; shots?: number; shots_requested?: number; stopped_early?: boolean; precision_target?: number; } | null | undefined; const ci = dist?.kind === "binomial" && Array.isArray(dist.ci95) ? dist.ci95 : null; const rawPoint = typeof dist?.point === "number" ? dist.point : Number((step.summary as Record)["fidelity"]); const ciPoint = ci && Number.isFinite(rawPoint) ? rawPoint : null; return (
{headline ? (
{headline.label}
{headline.value}
) : (
✓ ran
)}
{dist?.stopped_early && ( ⏹ {dist.shots} )} {durationS !== null && ( {durFormatted} )}
{ci && ciPoint !== null && (
)}
); } /** Build a one-line "param₁ · param₂ · …" summary for the collapsed * state of the param editor. Selects use the raw value (short keys * like "pittsburgh_1") rather than the long display label so the * whole summary stays under ~30 characters; numbers respect the * spec's `displayPrecision`. Result is meant to be a glanceable * cue — not a full read-out — so order in the schema matters. */ function summariseParams( spec: NodeParamSpec[], values: Record, ): string { const parts: string[] = []; for (const p of spec) { const raw = values[p.key]; if (raw === undefined || raw === null || raw === "") continue; if (p.type === "select") { parts.push(String(raw)); } else { const n = Number(raw); if (!Number.isFinite(n)) continue; const precision = p.displayPrecision ?? (p.type === "int" ? 0 : 2); parts.push(n.toFixed(precision)); } } return parts.join(" · "); } /** Tiny in-block status pill for the Qshot node: shows whether the * loaded circuit's qubit count is inside the 5-8q training range or * will trip the GNN-fallback path. Saves the user from learning the * hard way after a 60-second pilot run that the recommendation came * from the extrapolation path. */ function QshotFitChip({ nq }: { nq: number }) { const inRange = nq >= 5 && nq <= 8; if (inRange) { return (
in training range · {nq}q
); } return (
{nq}q · outside 5–8q range
will trigger GNN fallback
); }