19 Commits

Author SHA1 Message Date
b89e520479 Consistent label offsets across all schematic layout engines
Add ofst=0.15 to all component labels for uniform clearance between
label text and component bodies. Previously, loop layout had no offsets,
grid layout was missing offsets on multi-terminal devices (BJT/FET), and
connected layout was missing offsets on transistor and horizontal labels.
2026-02-23 14:25:50 -07:00
6f239c185e Chat widget: markdown styling, KaTeX math rendering, SSE streaming fix
- Add comprehensive CSS for markdown elements in chat bubbles (headers,
  lists, tables, blockquotes, links, code blocks, horizontal rules)
- Integrate KaTeX via marked-katex-extension for inline ($) and display
  ($$) math rendering with DOMPurify whitelist for MathML/SVG elements
- Add normalizeDisplayMath() pre-processor to handle LLM output where $$
  delimiters appear inline rather than on their own lines
- Add dark theme KaTeX styles matching the SpiceBook color palette
- Fix asyncio.to_thread usage in chat SSE endpoint for streaming
2026-02-23 14:25:42 -07:00
99d1ca28d2 Add MCP server and chat assistant
- Mount FastMCP at /mcp with tools for notebook CRUD, simulation,
  and cell execution. Includes status resource and circuit_assistant
  prompt.
- Add SSE streaming chat endpoint at /api/chat/stream backed by
  GPU LLM gateway (qwen3). Chat widget sends notebook context
  (SPICE cells, markdown notes) so the assistant can reference the
  user's circuit.
- React floating chat panel with zustand-persisted conversation
  history, streaming token display, reasoning collapse, and
  keyboard shortcuts.
- Refactor main.py from deprecated on_event("startup") to lifespan
  context manager with combine_lifespans for MCP integration.
- Add notebook_id path traversal validation, decouple get_engine()
  from HTTPException for MCP compatibility, fix HTTP client init
  race condition with asyncio.Lock.
- Update Caddy labels for /mcp/* routing and SSE streaming on
  backend reverse proxy.
2026-02-22 16:49:15 -07:00
2ddc08cd3a Add schematic thumbnails, descriptions to notebook cards and resistor color guide
Notebook cards now show schematic SVG thumbnails (on Mims green background)
and description snippets extracted from the first markdown cell. The backend
extracts both from already-loaded notebook data at zero additional I/O cost.

New ResistorColorGuide section between the pipeline strip and featured
notebooks explains the 4-band color code with an annotated zigzag diagram
and reference table using the same BAND_HEX colors from the schematic renderer.

Also switches docker-compose.dev.yml from direct port mapping to Caddy labels,
matching the production routing pattern and avoiding port conflicts.
2026-02-21 08:56:48 -07:00
fe6d20afbd Add schematic pipeline step and fix vertical label spacing
Add ofst=0.15 to vertical resistor label calls preventing overlap with
color-coded zigzag bands. Add Schematic step 03 to homepage pipeline
with inline SVG voltage divider on Mims graph paper. Pipeline now
4-step with responsive 1col/2x2/4col layout.
2026-02-20 20:34:41 -07:00
7e10b87a13 Color-code resistor zigzag symbols with standard 4-band colors
Map physical resistor color bands onto the IEEE zigzag schematic symbol.
Each sub-segment is colored to match its band (digit, multiplier, tolerance),
with wire-colored entry/exit and a gap before tolerance mimicking real spacing.
Parseable values 0.01–1GΩ get color; parametric/out-of-range fall back to mono.
2026-02-20 17:36:50 -07:00
b497d57890 Auto-generate schematics on mount, wire routing for grid layout
SPICE cells now auto-trigger schematic generation when they mount
without an existing diagram, so the schematic leads the UI. Template
and empty cells are skipped.

Grid fallback layout replaced with wire-connected rendering: BFS-based
node tier classification places components vertically between supply
and ground rails, then routes wires by node type (power/ground bus
rails, L-shaped signal wires, star topology for 3+ connections).
2026-02-15 14:40:25 -07:00
1e08be4409 Add /llms.txt API reference and POST /api/notebooks/compose endpoint
Machine-readable API docs at /llms.txt for LLM collaboration on circuit
design notebooks linked from Mims Electronics Reference Library.

Compose endpoint creates fully-populated notebooks in one call with
optional SPICE simulation. Per-cell try/except ensures partial simulation
failures don't lose the notebook.

Also extracts get_engine to spicebook.engine and makes
generate_notebook_id a public API.
2026-02-14 15:43:26 -07:00
3f3ca58521 Add embeddable notebook viewer for Mims library integration
New /embed/[id] route renders notebooks in a read-only, chromeless
layout for iframe embedding. Supports light/dark themes via URL
param and postMessage from the parent window.

- EmbedLayout: minimal HTML shell, no navbar/footer
- EmbedViewer: fetches notebook, runs simulations, syncs theme
- EmbedCell: read-only markdown + SPICE cell renderer
- SpiceEditor: added readOnly prop (EditorState.readOnly + editable.of)
- embed-theme.css: light mode CSS variable overrides
- Astro middleware: CSP frame-ancestors on /embed/* routes
- Backend: env-configurable CORS origins, CSP header middleware

Security hardening from review:
- postMessage origin validation (ALLOWED_MESSAGE_ORIGINS)
- markdown XSS fix: isSafeUrl() blocks javascript: URIs in links
- escapeHtml now covers single quotes
- Notebook ID validated against /^[a-zA-Z0-9_-]+$/
- Theme param normalized at Astro boundary
- classList.remove/add instead of className stomping
2026-02-13 15:46:37 -07:00
a8c53f34f4 Add click-to-edit schematic values and DOMPurify sanitization
SchematicViewer now supports inline editing of component values
directly on the SVG. Clicking an editable value opens an overlay
input that updates the SPICE netlist on commit, triggering an
auto-redraw after 800ms debounce.

Added DOMPurify for SVG sanitization, netlist-utils for safe
value substitution in netlists, and wired schematic generation
through the notebook store with generation counters to discard
stale responses.
2026-02-13 15:46:14 -07:00
4f174e9d0f Add Mims-style graph paper background to schematics
Sage-green grid (minor 10pt, major 50pt) on warm off-white canvas,
injected as nested SVG patterns behind all schematic content.
Works across all three renderers (loop, connected, grid).
2026-02-13 09:14:52 -07:00
c120a179c8 Improve connected schematic label placement (Mims-style)
- Add lead stub wires (0.75 unit) from collector and emitter pins
  for clearance between transistor and first component
- Transistor label placed right of body, all chain labels on left
- Offset parallel paths (RE/CE) label on right, facing outward
- Wider parallel path spacing (2.5 units) for label breathing room
- Down-turning components label outward based on path direction
- Parameterized label_loc in _draw_vert_chain for context-aware placement
2026-02-13 08:43:11 -07:00
4bc68a58bd Add connected schematic layout for single-active-device circuits
Replace the disconnected grid fallback with a topology-aware renderer
that places BJTs/MOSFETs at center and draws connected wire paths using
SchemDraw push/pop for branching at junction points.

Layout pipeline: trace component chains from each device terminal,
classify paths by direction (supply/ground/input/output), draw with
proper Vdd/Ground terminators and junction dots at branch points.

Fallback cascade: loop → connected → grid. Supply sources shown as Vdd
rail symbols; signal sources drawn inline as SourceV in input paths.
2026-02-13 07:18:50 -07:00
de7a29c69e Add auto-schematic generation from SPICE netlists
Parse netlists into component graphs and render circuit diagrams via
SchemDraw. Two layout strategies: loop layout for simple 2-terminal
circuits (RC, RL, voltage divider) and labeled grid for complex
circuits with active devices (BJT amplifiers, MOSFET).

Backend: netlist parser, schematic engine, POST API endpoint.
Frontend: SchematicViewer with zoom/download, stacked cell layout
showing schematic + SPICE editor + waveform simultaneously.
2026-02-13 06:07:30 -07:00
7ffd3f1bd3 Fix notebook directory permissions for non-root user
Pre-create /app/notebooks/{user,examples} with correct ownership
before switching to the spicebook user. Without this, the app crashes
with PermissionError when it tries to create these directories at
runtime.
2026-02-13 03:41:42 -07:00
a24375accb Fix Docker build: remove missing readme ref, disable astro telemetry 2026-02-13 03:39:00 -07:00
5aa36b252a Remove unsupported --no-editable flag from backend Dockerfile 2026-02-13 03:38:08 -07:00
72eb073787 Clean URLs and waveform rendering fixes
Switch from query-param routing (/notebook/?id=X) to Astro dynamic
routes (/notebook/rc-lowpass-filter). Add @astrojs/node adapter with
output: 'server' for on-demand route handling.

Fix formatEng/formatAxisValue crash on null values passed by uPlot
axis tick formatters. Add CORS origin for port 4322.
2026-02-13 02:16:11 -07:00
8abd7719bf Initial SpiceBook MVP: notebook interface for circuit simulation
Phase 1 implementation with ngspice backend and Astro/React frontend:

Backend (FastAPI):
- ngspice subprocess engine with custom .raw file parser
- Notebook CRUD with .spicebook JSON format (filesystem storage)
- Simulation endpoints (standalone + cell-in-notebook)
- SVG waveform export endpoint
- 18 REST API routes, 5 passing tests

Frontend (Astro 5 + React 19):
- Notebook editor as React island with Zustand state management
- CodeMirror 6 with custom SPICE language mode (syntax highlighting
  for dot commands, components, engineering notation, comments)
- uPlot waveform viewer with transient and AC/Bode plot modes
- Markdown cells with edit/preview toggle
- Notebook list with card grid UI
- Dark theme, Tailwind CSS 4, Lucide icons

Infrastructure:
- Docker Compose with dev/prod targets
- Caddy-based frontend prod serving
- 3 example notebooks (RC filter, voltage divider, CE amplifier)
2026-02-13 01:44:38 -07:00