Spaces:
Sleeping
Sleeping
Commit History
-
Polish pass: dedupe pipeline runners, shared chip component, emitter map
Yuchen YuanThree concrete refactors that reduce surface area for future bugs and make the codebase easier to maintain by hand or by LLM. 1. backend/app/services/workflow_service.py — run_pipeline and run_pipeline_stream used to be two 100+ line copies of the same dispatch loop. Extract a single _execute_pipeline generator and make both functions thin wrappers (one collects into a list, the other yields). Per-node dispatch (input / built-in / plugin / skipped) and the post-step circuit_shape stamping are factored into _dispatch_one_node. Plugin hydration becomes a named helper instead of an inline block duplicated on both paths. Also pulled out _clamp_shots and _set_backend_ctx so the two backend handlers share their shots-clamping and ctx-writing patterns; _cache_put's prefix_types argument becomes required (all call sites pass it; the dead 'None means skip sidecar' branch is gone); the run_cache.qpy_dump_bytes import moves to the top of the file with the …4ee621f -
Code quality cleanup + first unit-test seed
Yuchen YuanPost-audit polish on the bug-fix wave from the last 9 commits: * Hoist function-level constants to module top so they're discoverable and reusable: _FAKE_BACKENDS_AVAILABLE, _FIDELITY_METHODS, _FIDELITY_UNBOUND_POLICIES, _COMPVQC_MAX_QP_VARS, _COMPVQC_ROTATION_GATES. * Move 'import re' from inside _format_exception_for_user to the file's top-level imports. * Standardise validation error phrasing on 'Choose one of: ...' (was a mix of 'Allowed values:' and 'Choose one of:'). * Add the same name-validation rigour to _handle_ibm_backend that _handle_fake_backend has — refuse empty / non-string names with a clear message, and surface IBM's resolution failure through _format_exception_for_user instead of letting it bubble as a 500. * Drop the now-unused '_qpy_bytes' alias from run_cache.py; the one remaining call site uses the canonical name directly. * Drop the trivial _is_known_fake_backend wrapper; inline the membership test at the one …6962cb3 -
Invalidate step cache when a plugin is (re-)installed
Yuchen YuanIf a user re-uploads a plugin with the same kind + params, every in-memory step-cache entry whose prefix covered that kind would otherwise stay valid — the next run hit-served a result computed by the OLD plugin code. Confirmed by code review: install_plugin_zip overwrote the on-disk handler but never touched _step_cache. Fix is a sidecar map of prefix_key → set of node types covered by that prefix. _cache_put populates it; install_plugin_zip calls a new invalidate_step_cache_for_node_type(kind) helper to evict any entry that includes the affected kind. LRU eviction was updated to drop both the cache entry and the sidecar entry in sync. Unit-tested locally (4 scenarios: plugin invalidate, builtin invalidate, no-match, LRU sync) — all green.0894ed2 -
Surface graph-cycle errors as 422 instead of 500
Yuchen YuanA8 degenerate-graph probing: a cyclic node graph (A→B→A) made topological_order raise ValueError, which propagated as an HTTP 500. The user saw 'Internal Server Error' with no diagnosis. Catch ValueError in both /workflow/run and /workflow/run-stream and return 422 with the actual cycle/malformed-graph message. For the stream route, pre-flight the topological sort BEFORE opening the stream — otherwise the error would happen mid-stream with an empty SSE response and no status code surface. Other A8 cases (empty graph, output-only, two inputs, disconnected nodes) all returned reasonable results without crashes.fa31bfd -
Validate fidelity method + fake-backend name; refuse unknown strings
Yuchen YuanA4 fuzzing found three silent-coerce UX cracks: * backend_name='FakeBollywood' silently fell back to FakeFez * backend_name='' (empty) silently fell back to FakeFez * method='banana' on Fidelity silently picked statevector In all three the run reported ok and produced a number — but the number was for inputs the user didn't ask for. That's worse than erroring: it pretends to have done what was requested. Replace the silent coerce with explicit validation. Allowed values are enumerated in the error message so the user knows what to type. Also surface the same hardening on unbound_param_policy (same enum trap pattern).8a2d350 -
Stop the chain when a handler returns status='error'
Yuchen YuanHandlers signal failure two ways: by raising (caught + converted to status='error' in the loop) or by returning a StepResult with status='error' directly (e.g. QuCAD's 'needs a backend upstream'). Only the raise path was breaking the loop. A direct-return error let downstream steps execute on whatever ctx['circuit'] the failed upstream had left alone, silently producing misleading metrics (e.g. Fidelity reporting the input circuit's fidelity rather than the algorithm-transformed one). Live repro before fix: efficient_su2_4q → QuCAD (no backend) → Fidelity → Output ran all four steps; Fidelity returned the input-circuit fidelity even though the chain logically failed. Now: status='error' is honoured in both run_pipeline and run_pipeline_stream the same way as an exception. status='skipped' (e.g. CompVQC scale-guard) still continues — ctx is still valid.102bda8 -
QuBound: stop mutating caller's QuantumCircuit + handler defensive copy
Yuchen YuanQuBound's get_labels_fromNoise called qc.measure_all() in place to attach measurements for the Aer shots that train the LSTM. The comment said 'caller doesn't reuse qc after this point' — but the pipeline runner does: ctx['circuit'] points to the same object, so the measurement register leaked into every downstream step. Reproduction on the live server (ry_chain_6q → QuCAD → QuBound → Qshot → Fidelity → Output): Qshot crashed with 'ValueError: invalid literal for int() with base 2: "110100…"' because the counts string suddenly had a 'classical_register meas' delimiter splitting it. Two-layer fix: 1. qbound.get_labels_fromNoise now copies qc before measure_all. 2. _handle_qubound also copies ctx['circuit'] defensively when num_parameters == 0 (when >0, assign_parameters already returns a fresh circuit). Belt + suspenders so any future in-place mutation deeper inside QuBound still can't leak. Audited sampledFidelityEstimator and qshot recommender — both already copy…1c02f7a -
CompVQC scale-guard: count actual rotation instances, not unique Params
Yuchen Yuan524cb79 -
Surface real exception detail + add CompVQC scale guard
Yuchen YuanTwo ergonomics fixes triggered by trying to chain all algorithms on a parametric circuit: 1. Built-in handler crashes used to say 'see the run log for details' — but HF Spaces don't expose log surfaces to end users. Now bubble the exception class + first line of str(exc) (path-sanitised, 240-char cap) into the user-facing message. Server-side traceback logging is unchanged. 2. CompressVQC silently exploded on any non-trivial parametric input (ValueError: Maximum allowed dimension exceeded — QAOA tried to allocate 2^120 statevector for a 24-rotation EfficientSU2). Add an explicit pre-flight guard: skip with an actionable message if the QUBO would have > 22 binary variables. Locally reproduced the 512 GiB allocation attempt that confirmed the limit. Tested locally: ValueError formatter strips paths, leaves message intact. qaoa_maxcut_4 → 35 vars → would have crashed; now skips cleanly. vqc_2q_small (10 vars) still passes through to the solver.9f61265 -
Tighten nondeterministic guard: set flag before put + evict stale entries
Yuchen YuanV1 of this fix wrote the nondeterministic step itself to the cache because the flag was set after _cache_put. Subsequent runs lookup-hit and served the frozen draw — same bug we were trying to fix. V2: set the sticky flag BEFORE _cache_put, mirror the same change on the plugin path, and refuse to lookup-hit any cached entry whose own nondeterministic flag is True (defense against legacy entries from the v1 deploy that already populated the cache before this commit).146c829 -
Fix sampled fidelity being frozen by the per-node step cache
Yuchen YuanThe SSE run path caches each step's StepResult+ctx snapshot keyed on the pipeline prefix. For deterministic blocks (statevector fidelity, QuCAD output, etc.) that's a feature: re-runs reuse the trained model or computed metric. For sampled fidelity it was a silent scientific bug — the first shot draw got frozen and replayed forever. Reproduced live: 5 SSE runs of bell + FakeFez + fidelity(method=sampled) returned identical 0.5938 with from_step_cache=true after the first run. Fix: handlers can mark a StepResult as nondeterministic. The stream loop carries a sticky flag — once a nondeterministic step is emitted, both cache lookups AND cache puts are disabled for the rest of that run, including all downstream steps (their ctx depends on the fresh draw, so a lookup hit would restore a contradictory state). Frontend renders a 'live' chip on those steps so users know the cache is intentionally bypassed. Statevector fidelity is unchanged (still cacheable). QuBound / Qshot / QuCAD are als…b3ebd47 -
Fix exported script header URL: point to jqub21-quaim space
Yuchen YuanThe exportPython header was still referencing the qudastudio-app mirror. Since we now only maintain jqub21/quaim, point users at the canonical URL.50e62eb
-
Second-order checks: export gaps, pre-flight rule, backward compat
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Audit pass after Fidelity/QuBound/Backend changes to catch the downstream code that wasn't updated. exportPython.ts — 4 gaps fixed - fake_backend + ibm_backend export: now writes the user-set shots into the generated script. - qubound export: now writes the threshold + pass/fail check + margin printout so the exported script matches the canvas's behaviour. - fidelity export: the call signature changed (returns tuple, takes unbound_param_policy). Previously called the old signature, which would have crashed on every exported pipeline. Now branches on method: * statevector: calls simpleFidelityEstimator(qc, unbound_param_policy=...) * sampled: calls sampledFidelityEstimator(qc, backend, shots=shots, unbound_param_policy=...) Tuple unpacking captured both fidelity + meta. Print line identifies which method is in use. Pre-flight rule added Fidelity in `sampled` mode needs a backend upstream — that's where the noise model and shots come from. Without a backen…adb5d6a -
Fix Fidelity on parameterized circuits + QuBound threshold + Backend shots
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Three user-reported issues, all addressed with proper logging and actionable error surfaces. Issue 1 — Fidelity crashed on parameterized circuits simpleFidelityEstimator used Statevector.from_instruction(qc), which refuses circuits with unbound parameters. ry_chain_6q has 12 such parameters; Fidelity throw "TypeError: Parameter expression with unbound parameters … is not numeric" which surfaced as a generic "unexpected error" in the result card. The estimator now takes an `unbound_param_policy` argument: * "bind_zero" (default) — auto-binds free params to 0, matching the convention QuBound already uses internally, and reports `bound_unbound_to_zero: N` in the summary so the user sees what we did. * "error" — refuses and raises UnboundParametersError with the actionable message naming the offending param count and suggesting the upstream fix. _handle_fidelity catches UnboundParametersError specifically and maps it to a clean error step (the message is shown v…286193c
-
Self-explanatory edge labels + un-clip toolbar dropdowns
Yuchen Yuan +1: Claude Opus 4.7 (1M context)User feedback: "2q · d2 · 2g" was cryptic for anyone not steeped in quantum vocabulary, and the Load preset dropdown was being clipped behind the canvas. Edge labels: spell it out Was: "2q · d2 · 2g" Now: "2 qubits · depth 2 · 2 ops" The chip is a few characters wider but no longer needs a legend. "ops" instead of "gates" because Qiskit's circuit.size() counts all operations (gates + barriers + measurements), so "ops" is also slightly more accurate. Toolbar overflow no longer clips dropdowns Canvas toolbar previously had `overflow-x-auto` so narrow viewports could scroll the row instead of pushing items off-screen. CSS spec gotcha: when one axis is auto/scroll/hidden, the other axis can't be `visible` — it's coerced to auto. That meant the PresetPicker and MoreMenu dropdowns (which anchor below the trigger via `absolute top-full`) got CLIPPED by the toolbar's height. Removed overflow-x-auto. To still fit on mobile, the toolbar Run button is now `hidden md:flex` — the bottom-rig…89b1792 -
Canvas becomes data-aware: shapes, headline metrics, perf tint, pre-flight
Yuchen Yuan +1: Claude Opus 4.7 (1M context)After a Run, the canvas itself shows what's happening at every node and every edge — instead of just being a connection diagram with the real numbers banished to a sidebar. circuit_shape on every StepResult (backend) StepResult schema gains a CircuitShape sidecar field ({num_qubits, depth, size, num_parameters}). workflow_service snapshots ctx["circuit"] AFTER every successful handler and attaches it to the step. Built-in handlers and plugin steps both populate; ctx-less steps (source plugins with no upstream, errored steps) leave it as None. Edge data-flow labels (frontend) styledEdges memo in FlowCanvas reads the SOURCE node's circuit_shape and attaches a tiny monospace label to the React Flow edge: "5q · d8 · 17g". Falls back to no label when the source step doesn't have a shape (no run yet, or source errored). Drop-target highlight during drag-to-insert composes on top. Per-node headline metric + duration chip + tone (frontend) New lib/headlineMetric.ts table picks the most r…33e7bee -
Global code-quality polish: DRY + named constants + leak cleanup
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Targeted refactor pass based on a structured audit. Pure maintainability wins; no behaviour changes. Frontend: collapse 8 popovers into one hook 8 components (AuthButton, ThemeSwitcher, MoreMenu, PapersPopover, SupportPopover, DevelopersPopover, BlockPicker, PresetPicker) each carried an identical 16-line "close on mousedown + Escape" effect block. Extracted to lib/useDismissOn.ts; ~150 lines deleted, one hook to audit instead of eight. useDismissOn(open, rootRef, useCallback(() => setOpen(false), [])) Behaviour is intentionally identical to the inlined block so older git-blame on the call sites stays coherent. Backend: consolidate effective-user-id resolution routes/plugins.py and routes/workflow.py each carried a subtly different implementation of "session cookie wins over query_user_id, anon hf_ prefix is reserved". Pulled into auth_service.resolve_effective_user_id(request, query, *, required). - required=True path raises ValueError → routes/plugins maps to 400 - required=…57f0b3e -
Hide IBM live-mode chip entirely when server can't go live
Yuchen Yuan +1: Claude Opus 4.7 (1M context)User feedback: "live ibm: unavailable" / "ibm: n/a" chip adds noise without value on a deployment that has no IBM token configured — it's a permanent dead chip the user can't act on. Now the chip only renders when the server actually supports live mode (token configured AND ALLOW_LIVE_IBM=true). The 3-branch state-machine collapses to 2 (on / off-using-cache); the dead "unavailable" branch is gone. setUseLiveIbm + the useLiveIbm store state are kept untouched since the run code still reads them when the server IS live-capable. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>89aa5b4 -
Fix popover clipping + IBM-chip transparency bleed-through
Yuchen Yuan +1: Claude Opus 4.7 (1M context)User report: two visible glitches on the screenshots — (1) on a desktop browser, the icons in the TopBar's right cluster appeared to be visually stacked behind/inside the "ibm: n/a" chip on the left cluster; (2) on iPhone Safari, opening the Theme dropdown made the menu slide off the left edge of the screen. Root cause (1) — opacity-70 on the IBM chip When the server has no IBM token, the chip was rendered with class `opacity-70`. That made the WHOLE element 70% translucent, including its background. At narrower viewports where the right- cluster icons (Lab/Papers/Developers/Theme/Tour/Support/Auth) flex- squeeze closer to the chip, anything sitting under or behind it became visible through the alpha. Fixed by replacing opacity-70 with `!bg-canvas` (solid surface color) + the existing `text-mute` for the dimmed-disabled look. Identical visual intent, no alpha transparency. Root cause (2) — 3 popovers lacked the mobile-safe anchor pattern PapersPopover, Support…db325d1 -
Mobile + large-touchscreen UX overhaul
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Addresses a 15-finding audit covering viewport handling, safe areas, touch behavior, hit-target sizing, and iOS Safari quirks. Viewport + PWA chrome - viewport meta gains viewport-fit=cover + interactive-widget= resizes-content so safe-area-inset(*) applies and the iOS keyboard triggers layout reflow instead of just overlaying content. - theme-color set for light + dark via prefers-color-scheme media queries — browser chrome now blends with our surface instead of flashing white. apple-mobile-web-app-* meta + apple-touch-icon let the app feel native if added to home screen. - New /public/manifest.webmanifest registered, minimal but sufficient for installable-PWA detection. Dynamic viewport (100dvh) - App.tsx root: h-screen → 100dvh inline (with fallback). Was clipping ~80px under iOS Safari's collapsing address bar on first paint. - UploadPluginModal max-h moved from calc(100vh-2rem) to calc(100dvh-1rem) + safe-area-inset-bottom padding so the modal fits even whe…5c7eb51 -
Display fix + focus trap + mobile touch drag-to-edge-insert
Yuchen Yuan +1: Claude Opus 4.7 (1M context)DevelopersPopover layout fix When Yuchen Yuan's row gained a second link chip (LinkedIn), the single-row "icon + truncated name + chip + chip" layout squeezed the name down to its first letter ("Y") inside the 320px popover. Restructured to two rows per person: name on top (full width, no truncation), link chips below with flex-wrap. Single-link entries still look natural — the chip row simply contains one chip. Focus trap for modals + drawers New lib/focusTrap.ts useFocusTrap hook implements WAI-ARIA Authoring Practices for dialog focus management: - On open, focus moves into the container (prefers the container itself if tabIndex=-1, else first focusable child). - Tab from the last focusable wraps to first; Shift+Tab from first wraps to last. - Defensively re-routes focus into the container if something else steals it (e.g. async overlay). - Caller restores focus on close — we already do this for the upload modal and auth dropdown via their existing openerRef pattern. App…defa0ba -
Mobile + a11y + defense-in-depth fixes from broader audit
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Mobile + keyboard access to palette tiles (CRITICAL) Previously the only way to add a block to the canvas was HTML5 drag- and-drop, which doesn't fire on touch devices and has no keyboard analogue. Tiles were <div draggable> with no role, no tabIndex, and no click handler — so mobile users could only use the BlockPicker dropdown, and keyboard users had no path at all. - PaletteTile is now a <button type="button"> with onClick → addBlocksToCanvas([kind]) plus a Space override (Enter is handled by the native button semantics). - Drag-and-drop still works for mouse users on top of this — the button element preserves draggable + onDragStart so drag-to- insert keeps working. - focus-visible:ring-2 ring-accent makes the focused tile obvious to keyboard users. - aria-label per tile now reads "Add Gate Counter block to canvas. Tally gate types in the current circuit." (label + tagline) rather than relying on title-attr-only. Touch-friendly delete X (IMPORTANT) Both the palett…524287c -
Plugin output: typed figures (markdown / table / bar / svg / png)
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Plugins can now emit a list of typed visual outputs beyond the flat summary dict. Each figure is a small JSON object with a `type` field; the result card renders them inline below the summary table. Five types ship today - markdown — headings, lists, bold/italic/code, fenced code blocks. Raw HTML is rejected by the backend; the frontend renderer never reaches for dangerouslySetInnerHTML on this path. - table — headers (≤ 12 cols) + rows (≤ 100 rows), primitives only. - bar — inline SVG bar chart, up to 50 bars, zero JS deps. - svg — escape hatch with sanitisation: rejects <script>, javascript:, <foreignObject>, <iframe>, <object>, <embed>, and any on*= event-handler attribute. Up to 256 KB. - image_png_b64 — base64-encoded PNG, ≤ 1 MB decoded, must have the PNG magic bytes (JPEG/GIF/other formats rejected). Each figure also accepts an optional `title` (≤ 120 chars) rendered as the panel header. Total `figures` list capped at 10 entries. Backend - New plugin_run…725a720 -
Engineering hardening: PKCE + HF Datasets 412 retry
Yuchen Yuan +1: Claude Opus 4.7 (1M context)PKCE (RFC 7636) on OAuth flow The state cookie alone wasn't browser-bound — an attacker who could plant cookies on the Space's domain (e.g. via HTTPS-stripping proxy) could forge a matching state value. PKCE closes this: - /login mints a 64-byte code_verifier alongside the random state, computes code_challenge = base64url(sha256(verifier)), and stores state + verifier together in the signed cookie. - The /authorize URL passed to HF includes code_challenge=...& code_challenge_method=S256. - /callback retrieves the verifier from the signed cookie and POSTs it along with the code to /oauth/token. HF re-hashes it server-side and rejects the exchange if it doesn't match the original challenge. - A forged state cookie now needs the matching verifier to even attempt the exchange — and since the cookie binds them together, forging both requires the original itsdangerous secret. decode_state now returns (state, verifier) — both must validate; if either is missing or the cookie …ad3c861
-
Drag-to-insert + plugin lifecycle UX fixes
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Drag-to-insert (new feature) When the user drags a block from the palette and the cursor passes within ~60 flow-units of an existing edge, that edge lights up with an accent-coloured dashed animation. Dropping the block onto a lit edge splices it in: the old edge is removed and replaced by two new edges (upstream → new node, new node → downstream). Implementation: - New _findClosestEdge_ helper does line-segment-distance hit testing against every edge's source-right-center → target-left-center approximation. Threshold is in flow coordinates so it scales with zoom. Falls back to default 200x56 node footprint when React Flow hasn't measured yet. - _onDragOver_ checks for the palette's `application/reactflow` data type and computes the closest edge each frame, setting dropTargetEdgeId. - _onDragLeave_ clears the target so the dashed highlight doesn't linger if the user abandons the drag outside the canvas. - _onDrop_ captures dropTargetEdgeId, clears it, then either splices…dca3016 -
Full audit pass: leak fixes, sign-in clarity, functional bugs
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Triggered by user request "全方位的检查、测试" covering visualization, user comprehension, page logic, ease-of-use, science, info leakage, and security. Three parallel audits ran (info-leak, sign-in clarity, visual/a11y, functional/scientific); fixes batched below. Critical functional bugs - workflow_service.run_pipeline + run_pipeline_stream now call plugin_service.hydrate_from_dataset_if_needed before dispatch. Without this, a logged-in user running a pipeline on a fresh container (or on the mirror Space) would see "plugin not found" even though it sits safely in their HF Datasets backing store. - plugin_runner._scrub_scalars / _scrub_value drop NaN and ±Inf instead of passing them through. Standard JSON has no representation for either; model_dump_json emits NaN/Infinity which the browser's JSON.parse refuses, so any plugin returning a numerically degenerate scalar used to make the entire /run response fail to parse client- side. NaN → dropped from scalars dict; Inf → nul…4c566b4 -
Multi-user: HF OAuth login + per-user plugin persistence
Yuchen Yuan +1: Claude Opus 4.7 (1M context)What this lets users do - Anyone can click "Sign in" in the top bar and authenticate with their Hugging Face account (OpenID Connect via the HF OAuth flow). No account creation, no password management on our side. - Each signed-in user gets their own private namespace for uploaded plugins. Other users (and other browsers from the same person) cannot see them. - Plugins uploaded while signed in are mirrored to a private HF Dataset repo (qudastudio/quda-user-data) so they survive container restarts and follow the user across devices. - Guest (anonymous) mode is fully preserved: visitors can still drop a .zip without signing in; those plugins continue to live in /tmp and are per-browser, exactly as before. Architecture Browser ──cookie──▶ FastAPI ──HfApi──▶ HF Dataset (private) │ └──▶ /tmp (volatile cache) Identity = session cookie's hf_<username> (when signed in) ∥ anon UUID query par…b6faf15 -
Polish pass on plugin Upload modal
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Detail review surfaced four small but meaningful items. Storage listener over-fires (App.tsx) - Was triggered by any quda.* key — included pane widths, theme, live-IBM toggle. Tightened to e.key === "quda.pluginsRev" so only actual plugin upload/delete events refetch. bumpPluginsRev() already writes that exact key. Duplicate-install regex collision (UploadPluginModal) - /already have a plugin/i matched both the per-kind duplicate AND the 5-plugin cap message, so a user at cap who clicked Install on a sample saw a green success banner. Tightened to /already have a plugin with kind=/i so only the idempotent case surfaces as a friendly hint; the cap is now an honest error. - Added a Content-Type guard after the example zip fetch so a captive portal serving an HTML 200 surfaces "got <type>, not a .zip" instead of the confusing manifest-parse error from the backend. Modal UX restructure - Examples-first ordering when installedPlugins.length === 0 — a first-time visito…4d0158a -
Bundled example plugins + UX polish from second audit pass
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Lets users try the plugin upload flow end-to-end without writing one from scratch: the Upload modal now shows a "Try with a sample" section that fetches /api/plugins/examples and offers per-example Install + .zip download buttons. Backend: - New read-only GET /api/plugins/examples returns minimal metadata parsed from each bundled zip's manifest.json (label, family, tagline, color, size). Catalog is empty if the examples dir is missing. - New read-only GET /api/plugins/examples/{name}.zip returns the raw zip bytes. Name is constrained to `^[a-z][a-z0-9_]{0,30}$`; resolved path must stay inside the examples dir (defence in depth against symlink shenanigans). 400 on bad name, 404 on missing or escaped path. - manifest.json read inside the zip capped at 64 KB so a malformed bundled example can't allocate unboundedly. - Defensive comment about route ordering vs the path-param DELETE. - Dockerfile COPYs example_plugins/ into the runtime image so the endpoints have content to s…ef8bb5f -
Plugin protocol Phase 5: final audit fixes + polish
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Defence-in-depth fixes from the security/UX/scientific audits: Backend safety: - Reject `\` and absolute paths in zip entry names (defensive even on Linux containers). - Cap stdin payload at 50 MB in the subprocess wrapper before parsing. - Drop the full `/tmp/quda_plugins/<user>/<kind>/` path from the "handler.py missing" error message — user already knows their kind. Frontend UX: - QNode now renders a red-bordered tombstone card with a "?" badge and a "plugin not installed" hint when a referenced plugin has been deleted, instead of silently disappearing. - App.tsx listens for `storage` events on `quda.*` keys to refresh the plugin list across tabs. - UploadPluginModal title now reads "Upload your own block" with a one-line explanation of what plugins do. - TrySlide adds a "Upload your own block" tip alongside the Export .py one so new users discover the plugin workflow. Docs: - README.md gains a User plugins section pointing to PLUGIN_SDK.md. - PLUGIN_SDK.md adds a "…d06bf19 -
Plugin protocol Phase 5: SDK docs + two example plugins
Yuchen Yuan* PLUGIN_SDK.md — complete plugin developer guide: - .zip layout (manifest.json + handler.py at top level) - Full manifest schema with each field's constraints - run(inputs, params) signature + every recognised return key - Minimum working example (h_counter metric) - Execution environment table (10-min timeout, 1 GB RAM, env strip) - Per-family conventions for source/backend/algorithm/metric/sink - Where plugins live + lifecycle (per-browser, /tmp scoped) - Safety notes (no IBM token leakage, subprocess isolation) - Troubleshooting table * example_plugins/count_gates/ — minimal metric plugin: counts gate types in the upstream circuit, returns summary + scalars. * example_plugins/prefix_x/ — minimal algorithm plugin: prepends an X gate on a chosen qubit, returns new circuit + summary. * example_plugins/*.zip — pre-zipped versions for users who want to download + upload directly without re-zipping. End-to-end verified on live HF Space: both example plugins up…e66189d -
Plugin protocol Phase 4: full UI integration
Yuchen Yuan* lib/nodeCatalog.ts — `synthesizePluginSpec(manifest)` builds a NodeSpec on the fly from a backend-served PluginManifest. `resolveNodeSpec(kind, plugins)` is the new single source of truth for spec lookups: returns the built-in spec if available, otherwise the synthesized plugin spec, otherwise undefined. Adds PluginNodeSpec (NodeSpec + isPlugin/initials/pluginColor). * UploadPluginModal.tsx — drag-drop or click-to-pick .zip, posts to /api/plugins/upload with the browser's anonymous user_id, surfaces backend validation errors verbatim, refreshes the in- store plugin list on success. Inline docs spell out the manifest + handler.py contract. * NodePalette — new "Upload" button next to "Add blocks"; merges plugin specs with NODE_CATALOG before filtering by search / family chips. Plugin tiles render with the manifest's color + first-letter badge instead of a Lucide icon, and grow an X delete affordance on hover (with confirm dialog). * BlockPicker — same merge…74b7708 -
Plugin protocol Phase 3: frontend foundation
Yuchen Yuan* lib/userId.ts — anonymous browser ID stored in localStorage. Uses crypto.getRandomValues for a 16-byte hex string; falls back to Math.random if Web Crypto is unavailable. Matches the backend regex [a-zA-Z0-9_-]{8,64}. * lib/api.ts — three new endpoints (listPlugins / uploadPlugin / deletePlugin) and a PluginManifest type. RunRequest gains an optional user_id field so workflow runs can address the right user's plugins. * lib/store.ts — Zustand state for the current user's plugin list (refreshed on App boot, after upload, and after delete). * App.tsx — on boot, fetch this browser's plugin manifests in parallel with the health probe. Silent failure (just no plugins shown if /api/plugins is unreachable). * FlowCanvas.tsx — include getUserId() in the run-stream request payload so the backend can dispatch unknown node types to this user's plugins. No UI for upload yet — that's Phase 4. After this commit, refresh the live Space and a plugin uploaded directly via curl …10b580f -
Plugin protocol Phase 2: workflow runner dispatches to plugins
Yuchen Yuan* schemas.py: relax NodeType from a Literal of 9 built-in kinds to a free-form str. Plugin kinds are validated separately in plugin_service so they don't pollute the schema. Add optional user_id to RunRequest so the runner can find the right user's plugins. * workflow_service.py: new _handle_plugin() that converts in-process ctx (QuantumCircuit + Backend object + scalars) into the JSON- friendly inputs the plugin subprocess expects, invokes the subprocess via plugin_runner.run_plugin, then translates the result back: circuit replacement via QPY round-trip, backend selection limited to known fake backends, scalar writes folded into ctx for downstream blocks. run_pipeline + run_pipeline_stream both take a new user_id param and fall through to _handle_plugin for any node type not in the built-in _HANDLERS table. Plugin steps participate in the intermediate cache: the prefix hash includes the plugin's kind + params, so re-running with the same plugin setting…8d471b9 -
Plugin protocol Phase 1: backend service + subprocess runner
Yuchen YuanThree new backend modules to support user-uploaded plugin blocks: * plugin_service.py — manifest schema (Pydantic), per-user storage under /tmp/quda_plugins/<user_id>/, zip upload + validation: - max 1 MB zip, ≤ 50 entries, ≤ 512 KB per file - allowlist: .py / .json / .txt / .md only - rejects path traversal (.., leading /) - rejects reserved kinds (collisions with built-in block types) - rejects > 5 plugins per user (count cap) - validates manifest.json against PluginManifest schema (kind format, family enum, hex color, unique param keys, …) * plugin_runner.py — subprocess execution with safety measures: - 10-minute hard timeout (subprocess.run(timeout=600)) - 1 GB virtual memory cap via RLIMIT_AS in preexec_fn - 11-minute CPU time cap via RLIMIT_CPU - os.nice(10) so a busy plugin doesn't starve FastAPI - env stripped to allowlist (PATH, PYTHONPATH, HOME, TMPDIR, …) — drops IBM_QUANTUM_TOKEN and any other Space secrets - cwd set to plugin's own dire…34125c4 -
Remove Parameter Sweep feature
Yuchen YuanReverts all 8 files involved in the sweep feature (per user request): - Delete SweepDialog.tsx - Remove Sweep button + state + dialog mount in FlowCanvas - Remove Sweep entry + props from MoreMenu (mobile) - Drop Sweep mention from TrySlide power-features strip - Drop Sweep mention from NextStepsHint in ResultsPane - Remove SweepConfig/SweepRequest/SweepRunResult types + sweepStream method from api.ts - Remove /api/workflow/sweep endpoint from backend routes - Remove SweepConfig/SweepRequest/SweepRunResult/SweepResponse from backend schemas The per-node intermediate cache stays — it was originally built as groundwork for sweep but is independently useful for re-running modified pipelines.44acddd -
Polish: unified value prop, error-message location hints, next-steps guidance
Yuchen YuanFour UX-audit follow-ups: 1. **Value-prop consistency**: WelcomeSlide's opening paragraph replaced. Was "A visual playground for research algorithms" — conflicted with README's "Interactive workflows for quantum system deployment" and TopBar's "Quantum Design Automation Studio" subtitle. Now leads with the QuDA acronym expansion + the canonical "interactive workflows" tagline, then explains the lab context underneath. All three surfaces (TopBar / WelcomeSlide / README) now agree. 2. **Error messages point at UI**: "Pick a circuit first" now also bumps a Zustand counter that App.tsx watches; the left CircuitPicker pane auto-expands (desktop) or its drawer slides open (mobile) so the user can SEE where to act. The message itself names the pane explicitly. "Canvas is empty" now mentions all three ways to add blocks (drag / Add blocks dropdown / preset). 3. **Cross-feature guidance**: After a successful run, ResultsPane shows a subtle "Where to …974ac89 -
Tour + mobile parity: address UX audit findings
Yuchen YuanUX audit found: 1. Tour didn't mention Export .py, Sweep, or BlockPicker (all shipped after the tour was last updated). 2. Sweep & Export were hidden on mobile (toolbar md+ only, not in MoreMenu). 3. TrySlide "What to try first" list was static text — users had to manually find samples + presets. Fixes: - MoreMenu: add Sweep entry alongside Auto-connect / Share / Export / Clear so mobile users can reach the parameter-sweep feature. - TrySlide: the 4 "What to try first" lines are now clickable buttons. Each loads its (preset, sample) combination via a new Zustand quickStart bridge and closes the tour. The bridge mirrors the existing pendingBlockKinds pattern. - TrySlide: new "Once you've got results" strip explicitly introduces Sweep and Export .py as the power-user features — these were completely undocumented before this commit. - TrySlide: "Build your own" now mentions Add blocks (multi-select dropdown) alongside drag interaction. - FlowCanvas.loadPreset: acce…82f6435 -
Feature: parameter sweep with comparison chart
Yuchen YuanBackend: - New POST /api/workflow/sweep SSE endpoint. Accepts a base pipeline + SweepConfig (target node_id, param_key, list of values up to 50). For each value, patches the target node's data and runs the full pipeline. Yields one SweepRunResult per value. - Schemas: SweepConfig, SweepRequest, SweepRunResult, SweepResponse. - Leverages the existing per-node intermediate cache: prefix steps upstream of the swept block are reused across all sweep iterations. An N-value sweep of the last block's parameter costs roughly N * (last-block runtime) instead of N * (full-pipeline runtime). Frontend: - New SweepDialog modal. UI flow: 1. Picks the target: auto-discovers all numeric NodeParamSpec entries on the canvas (QuCAD iters/lam/rho, Qshot alpha, etc.) 2. User sets start, end, steps (2-20) → preview of computed values 3. Click "Run sweep" → streams results from /workflow/sweep 4. Renders a line chart (param value on X, output metric on Y) plus a data table. Met…fead27e -
Fix 3 audit findings: export signatures, cache safety, accessibility
Yuchen Yuan1. CRITICAL — exportPython.ts CompressVQC template had 3 wrong function calls: - quadraticProgram_luttoqp(lut) → (qc, lut) - admmOptimizedCompVQC(qp, lut) → (qp) - resultsCompressVQC(qc, result, lut) → (result, qc) All verified against backend/qlib/compvqc.py actual signatures. Users who exported and ran pipeline.py would have hit TypeError. 2. MEDIUM — Step cache _cache_put now deep-copies QuantumCircuit objects via qc.copy() instead of storing references. Prevents a future handler that mutates circuit in-place from silently corrupting cached snapshots. Current handlers all reassign, so this is defensive, but the cost (one .copy() per step) is cheap. 3. MEDIUM — BlockPicker button now has aria-haspopup, aria-expanded, aria-label. Dropdown div has role="menu" and aria-label. Screen reader users can now navigate the block catalog.51365eb -
Feature: per-node intermediate result cache
Yuchen YuanBackend: - In-memory LRU cache (200 entries) keyed by pipeline-prefix hash. The prefix hash covers (circuit QPY + all node types & params up to the current step). If the user changes only the last block, all preceding steps return instantly from cache (~0ms) instead of re-running (saves minutes for QuBound LSTM / Qshot HDBSCAN). - After each step, a shallow copy of the ctx dict is cached alongside the StepResult. On cache hit, ctx is restored so subsequent steps can pick up where the cached prefix left off. - Cached steps are flagged with from_step_cache=True (new optional field on StepResult) so the frontend can distinguish them. - Cache is process-scoped and resets on container restart. LRU eviction at 200 entries prevents unbounded memory growth. Frontend: - StepResult type extended with optional from_step_cache. - Results pane shows a small "cached" chip on steps served from the intermediate cache, so users can see which steps were instant. Works with the SSE st…1e3019d -
TopBar: remove backdrop-blur that trapped tooltip in compositing layer
Yuchen Yuana84a94a -
Fix build: remove unused vars in exportPython; fix setRun functional updater
Yuchen Yuan22b441d -
Feature: SSE streaming for real-time pipeline progress
Yuchen YuanBackend: - Add run_pipeline_stream() generator in workflow_service.py that yields each StepResult as it completes instead of collecting all. - Add POST /api/workflow/run-stream SSE endpoint in workflow.py. Cache hits emit the full RunResponse as one event + [CACHED] sentinel. Cache misses stream individual step events + [DONE]. Frontend: - Add api.runStream() in api.ts: uses fetch + ReadableStream to parse SSE events incrementally. - FlowCanvas.runPipeline() now uses the streaming endpoint. Each step appears in the Results pane as soon as it finishes, so the user sees "Step 1: Input circuit... done" while Step 2 is still running, instead of staring at a blank spinner for 2+ minutes. - On cache hit, the full response arrives instantly (same UX as before). On stream error, falls back gracefully with an error toast. The old POST /api/workflow/run endpoint is unchanged for backwards compatibility and the precompute script.02d0eb5 -
Feature: Export pipeline as runnable Python script
Yuchen YuanNew "Export .py" button in the canvas toolbar (Code2 icon). Generates a flat, readable Python script that reproduces the current pipeline: - Topologically sorts the canvas nodes using the edge list - For each block, emits the corresponding Python code with the actual parameter values from the canvas (iterations, lambda, rho, noise_snapshot, alpha, backend_name, etc.) - Includes import statements, parameter binding for parameterized circuits, and print statements for each step's output - Downloads as pipeline.py with a browser file-save dialog Supports all 9 block types: input_circuit, fake_backend, ibm_backend, qucad, qubound, compvqc, qshot, fidelity, output. IBM live backend generates commented-out code with instructions + a fake backend fallback. Also added to the mobile MoreMenu so the feature works on phones.90bf6ec -
Polish pass: brand cleanup, popover consistency, mobile safety
Yuchen YuanAudit-driven fixes: 1. Branding: - Dockerfile comment: QuAIM → QuDA Studio - package.json name: jqub-quantum-flow-ui → quda-studio-ui - All localStorage keys: jqub.* → quda.* (theme, pane widths, collapsed state, IBM toggle, tour flag). Existing users will see fresh defaults on first visit (acceptable — the old Space URL is gone anyway so there's no continuity to preserve). 2. Popover consistency: - All 4 popovers (Papers, Developers, Support, BlockPicker) now share z-40 instead of a mix of z-30 and z-50. - BlockPicker gets the same mobile-safe positioning as the other three: fixed left-3 top-14 on narrow screens, absolute on ≥sm. - BlockPicker width clamped with min() so it can't overflow on narrow viewports. 3. Pre-hydration script in index.html updated to read quda.theme instead of jqub.theme.95967ab -
Family chips: click to filter tile strip to one category, click again to show all
Yuchen Yuan38f03db -
TipIcon: force opaque background via inline style + bump z to 100
Yuchen Yuanb788eb2
-
BlockPicker: pre-check required blocks + per-family guidance hints
Yuchen Yuan7a9f56e -
Add dropdown BlockPicker for browse-and-select workflow
Yuchen YuanNew "Add blocks" button in the NodePalette header opens a dropdown list showing ALL blocks organised by family (Source / Backend / Algorithm / Metric / Sink). Users can: - Search/filter by name or tagline - Check multiple blocks via checkboxes - See "on canvas" badges for blocks already placed - Hit "Add to canvas" to batch-create all checked blocks (auto- connected via the existing Zustand pendingBlockKinds bridge) The tile strip stays for drag-and-drop (quick access). The dropdown is the structured alternative for building a pipeline from scratch or when there are many blocks to browse. Tile checkboxes from the previous commit are removed — tiles go back to drag-only, keeping them clean. The dropdown handles the multi-select workflow instead.f152600