Skip to content

CLI serve mode - #6

Merged
melonamin merged 20 commits into
masterfrom
cli-serve-mode
Jan 23, 2026
Merged

melonamin merged 20 commits into
masterfrom
cli-serve-mode

Conversation

@melonamin

@melonamin melonamin commented Jan 22, 2026 •

Copy link
Copy Markdown
Member

CLI Serve Mode - Embedded Web UI

This PR adds a new --serve mode to the FlowScope CLI that runs a local HTTP server with the full web UI embedded. This enables single-binary deployment where all SQL lineage analysis happens locally without requiring external services.

Features

Embedded Web UI Server

  • Start a local HTTP server with flowscope --serve
  • Web UI is embedded at compile time using rust-embed - no external files needed
  • Same full-featured UI as the web app (lineage graph, matrix view, schema editor, etc.)

Multiple Input Modes

# Watch directories for changes (hot reload)
flowscope --serve --watch ./sql --watch ./queries

# Serve specific files (static, no watching)
flowscope --serve file1.sql file2.sql

# Serve from stdin
cat query.sql | flowscope --serve

REST API

All analysis runs locally via REST endpoints:

Endpoint Method Description
/api/health GET Health check with version
/api/analyze POST Run lineage analysis
/api/completion POST Get code completion items
/api/split POST Split SQL into statements
/api/files GET List files with content
/api/schema GET Get schema metadata
/api/export/:format POST Export to json/mermaid/html/csv/xlsx
/api/config GET Server configuration

File Watching

  • Automatic detection of .sql file changes with 100ms debouncing
  • Mtime-based change detection to avoid unnecessary reloads
  • Support for multiple watch directories with path prefixing to avoid collisions

Architecture

Backend (Rust)

  • server/mod.rs - Axum HTTP server with CORS and request limits
  • server/api.rs - REST API handlers using flowscope-core
  • server/state.rs - Shared application state with RwLock-protected files
  • server/watcher.rs - File system watcher using notify-debouncer-mini
  • server/assets.rs - Embedded static assets served via rust-embed

Frontend (TypeScript)

  • BackendAdapter pattern to abstract REST vs WASM backends
  • useBackendFiles hook for polling /api/files with delta detection
  • BackendContext provider for mode detection and file sync
  • Files from serve mode are read-only in the UI

CLI Options

--serve              Start HTTP server with embedded web UI
--port <PORT>        Server port (default: 3000)
--watch <DIR>        Directory to watch for SQL files (repeatable)
--open               Open browser automatically on startup

All existing options work in serve mode:

  • -d/--dialect - SQL dialect for analysis
  • --metadata-url - Live database schema introspection
  • -s/--schema - DDL schema file
  • --template - Jinja/dbt template preprocessing

Build System

New justfile targets:

  • just build-cli-serve - Build CLI with serve feature (release)
  • just build-cli-serve-debug - Debug build for development
  • just test-cli-serve - Run serve mode tests

The serve feature requires building the frontend first (handled automatically by justfile):

cd app && yarn build
cargo build -p flowscope-cli --features serve --release

Testing

  • Unit tests (serve_api.rs) - API handler tests with mock state
  • Integration tests (serve_integration.rs) - Full HTTP request/response testing
  • Tests cover: health check, analysis, file listing, exports, file watcher, multi-directory support

Security Considerations

  • CORS restricted to same-origin (localhost only)
  • Request body limited to 10MB
  • File paths validated to prevent directory traversal
  • Symlinks not followed to prevent accessing files outside watched dirs
  • Large files (>10MB) skipped with warning
  • File count limited to 10,000 to prevent memory exhaustion

UI Behavior

The UI in serve mode shows:

  • "Static Files" indicator when serving files without watching
  • Watch directory path(s) when using --watch
  • "READ ONLY" badge on the editor (files cannot be modified in serve mode)

Test Plan

  • just test-cli-serve passes
  • Watch mode: flowscope --serve --watch ./sql
  • Static files: flowscope --serve file.sql
  • Stdin: echo "SELECT 1" | flowscope --serve
  • Combined options: flowscope --serve --watch ./sql -d postgres --open
  • Error handling: flowscope --serve with no input shows error

Add optional serve mode dependencies gated by the "serve" feature flag:
- axum 0.8 for HTTP server
- tower-http 0.6 for CORS and static file serving
- rust-embed 8 for embedding static assets
- notify-debouncer-mini 0.5 for file watching
- mime_guess 2 for content-type detection
- open 5 for browser opening
Add --serve, --port, --watch, and --open flags for serve mode.
All arguments are gated behind the serve feature flag.
Create the foundational server module with:
- mod.rs: main server loop and file scanning
- assets.rs: rust-embed static file serving with SPA fallback
- state.rs: AppState with RwLock for files and schema
- api.rs: REST API handlers for all endpoints
- watcher.rs: file system watcher with debouncing

Also adds walkdir and chrono dependencies for serve feature.
Task 4 completed - WebAssets struct with rust-embed for static files:
- Embeds app/dist/ with include patterns for html, js, css, wasm, svg, png, ico, json
- static_handler serves embedded assets with MIME type detection
- SPA fallback routes non-asset paths to index.html
Task 5 was already implemented in a previous iteration. Verified that:
- AppState has RwLock<Vec<FileSource>> for files
- AppState has RwLock<Option<SchemaMetadata>> for schema
- ServerConfig struct has dialect, watch_dirs, metadata_url, port
- AppState::new() loads initial files and schema
Task 6 API handlers were already implemented in a previous commit.
All endpoints are working:
- GET /api/health - health check with version
- POST /api/analyze - lineage analysis
- POST /api/completion - code completion items
- POST /api/split - statement splitting
- GET /api/files - list watched files
- GET /api/schema - schema metadata
- POST /api/export/:format - export to json/mermaid/html/csv/xlsx
- GET /api/config - server configuration
Add logging of specific file paths when SQL files change, improving
debugging experience in serve mode.
Add run_serve_mode() function that:
- Checks args.serve flag at CLI entry point
- Builds ServerConfig from parsed CLI arguments
- Creates tokio runtime and calls server::run_server()

The server URL printing and browser opening are handled by
run_server() which was implemented in Task 4.
Add abstraction layer for analysis backends:
- BackendAdapter interface with REST and WASM implementations
- createBackendAdapter() factory with health check fallback
- Update useAnalysis to support optional adapter injection
- Add BackendProvider context for app-wide backend state
- Add useBackendFiles() hook to fetch /api/files and /api/schema
- Integrate BackendProvider with ProjectProvider for serve mode
- Create virtual backend project from server files
- Make files read-only in backend mode (editor, file tree)
- Show backend schema in read-only mode via SchemaEditor
- Add schemaMetadataToSQL utility for displaying backend schema
- Add build-cli-serve and build-cli-serve-debug justfile targets
- Add test-cli-serve target for testing with serve feature
- Add cli-serve CI job that builds app then CLI with embedded UI
- Document CLI serve mode build order in AGENTS.md
- Add unit tests for all API endpoints with mock state
- Add integration tests for server startup and health endpoint
- Add integration tests for analyze endpoint with sample SQL
- Add integration tests for file watcher functionality
- Create lib.rs to expose server module for testing
- Add tower and reqwest dev dependencies for test infrastructure
- Add --serve usage examples to CLI README with server options table
- Document REST API endpoints available in serve mode
- Add build instructions for serve feature
- Add troubleshooting section for common issues (port conflicts, permissions)
- Document serve mode in main README for discoverability
- Format generated code files
- Wire backend adapter into useAnalysis in EditorArea
  (CRITICAL: without this, REST mode fell back to WASM)
- Add missing fields to server AnalyzeRequest (hide_ctes,
  enable_column_lineage, template_mode) and use them in handler
- Log watcher blocking_send failures instead of silently ignoring
- Add CHANGELOG entry for serve mode feature
- Bind to port before opening browser to prevent broken page if port unavailable
- Fetch dialect from /api/config for backend project instead of hardcoding 'generic'
- Remove unused dialect/schema_sql fields from REST analyze request
- Remove unused backendType prop from Workspace component
Add ability to serve specific files or stdin input without file watching:
- flowscope --serve file1.sql file2.sql (static files)
- cat query.sql | flowscope --serve (stdin input)

Changes:
- Add static_files field to ServerConfig for non-watched files
- Update run_serve_mode to read from positional args or stdin
- Skip file watcher and reload for static files mode
- Name stdin files as <stdin>.sql to pass frontend .sql filter
- Show "Static Files" indicator in UI when watch_dirs is empty
- Fix READ ONLY badge overlapping scrollbar (right-2 -> right-5)
- Update tests with new ServerConfig fields
When switching projects, nodes were stacking at position (0,0) because
the Stage 1 layout logic tried to preserve positions from the old
project's nodes. Since new projects have different node IDs, position
lookup failed and nodes kept their default (0,0) position.

The fix detects project switches by checking node ID overlap:
- If <50% of nodes have existing positions, treat as new graph
- For incremental updates, use fast layout positions as fallback
- Optimizes case where all nodes already have positions
@melonamin
melonamin merged commit 89c5941 into master Jan 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant