Repository navigation
Description
Problem
PR #497 successfully migrated browser dev mode to use SurrealDB HTTP API (port 8000), but in doing so, we bypassed the entire Rust business logic layer (NodeService). This means browser dev mode is now a "raw database mode" that skips critical application logic.
What We Lost
Current Architecture (Post-Migration)
Frontend → HttpAdapter → SurrealDB HTTP API (port 8000) → Raw Database
Missing Business Logic:
- Virtual date nodes - YYYY-MM-DD format auto-creation
populate_mentions()- Backlinks computationbackfill_schema_version()- Schema version managementapply_lazy_migration()- Automatic schema migrations- Node validation - Type-specific validation rules
- Behavior system - All NodeBehavior implementations
- Computed fields - Any derived data
- Business rules - All NodeService logic
Reference: Old Dev-Server Implementation
IMPORTANT: The old dev-server code was deleted in PR #497, but you can reference it from git history.
View Old Implementation:
# View complete old dev-server code
git show dd07b4e:packages/desktop-app/src-tauri/src/dev_server/node_endpoints.rs
git show dd07b4e:packages/desktop-app/src-tauri/src/dev_server/schema_endpoints.rs
git show dd07b4e:packages/desktop-app/src-tauri/src/dev_server/mod.rs
# Save to temp files for reference
git show dd07b4e:packages/desktop-app/src-tauri/src/dev_server/node_endpoints.rs > /tmp/old-node-endpoints.rs
git show dd07b4e:packages/desktop-app/src-tauri/src/dev_server/schema_endpoints.rs > /tmp/old-schema-endpoints.rs
git show dd07b4e:packages/desktop-app/src-tauri/src/dev_server/mod.rs > /tmp/old-server-setup.rs
# Open in editor
code /tmp/old-node-endpoints.rsKey files to reference:
- node_endpoints.rs - All node CRUD operations (create, get, update, delete, query)
- schema_endpoints.rs - Schema management (get, add field, remove field, etc.)
- mod.rs - Server setup, CORS, state management
Use these as templates - they show exactly how to wrap NodeService calls in HTTP handlers.
Proposed Solution: Restore Business Logic Proxy
Target Architecture
Frontend (Svelte) → HttpAdapter → HTTP Proxy (port 3001)
↓
NodeService (Rust business logic)
↓
SurrealStore (HTTP client) → SurrealDB Server (port 8000)
↓
Surrealist Inspector ──────────────────────────────────────→ SurrealDB (port 8000) ✅
Key Points:
- Frontend connects to port 3001 (HTTP proxy)
- Proxy uses NodeService for all business logic
- SurrealStore uses HTTP client mode to connect to SurrealDB on port 8000
- Surrealist connects directly to port 8000 for inspection
Benefits
✅ All NodeService business logic preserved
✅ Surrealist can connect to SurrealDB for live inspection
✅ Consistent behavior between browser and desktop modes
✅ Minimal code (~300 lines total)
✅ No business logic duplication
Implementation Plan
Phase 0: Add HTTP Constructor to SurrealStore (~1 hour) ⏱️
CRITICAL: SurrealStore currently only supports embedded RocksDB. We need to add HTTP client support.
File: packages/core/src/db/surreal_store.rs
Step 0.1: Add HTTP Engine Import
// At top of file (around line 52)
use surrealdb::engine::local::{Db, RocksDb};
use surrealdb::engine::remote::http::{Client, Http}; // ← ADD THIS
use surrealdb::opt::auth::Root; // ← ADD THIS
use surrealdb::sql::{Id, Thing};
use surrealdb::Surreal;Step 0.2: Add new_http() Constructor
Find the impl SurrealStore { block (around line 127) and add this new method:
impl SurrealStore {
/// Create embedded RocksDB store for desktop mode
///
/// This is the production mode - database is stored in a local file.
pub async fn new(db_path: PathBuf) -> Result<Self> {
// Existing code - DON'T CHANGE THIS
let db = Surreal::new::<RocksDb>(db_path).await?;
// ... rest of existing code
}
/// Create HTTP client store for dev-proxy mode
///
/// This connects to a remote SurrealDB server via HTTP API.
/// Used by dev-proxy to enable Surrealist inspection while preserving business logic.
///
/// # Arguments
///
/// * `endpoint` - SurrealDB server URL (e.g., "http://127.0.0.1:8000")
/// * `namespace` - Database namespace (e.g., "nodespace")
/// * `database` - Database name (e.g., "nodes")
/// * `username` - Auth username (e.g., "root")
/// * `password` - Auth password (e.g., "root")
///
/// # Example
///
/// ```rust,no_run
/// use nodespace_core::db::SurrealStore;
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
/// let store = SurrealStore::new_http(
/// "http://127.0.0.1:8000",
/// "nodespace",
/// "nodes",
/// "root",
/// "root"
/// ).await?;
///
/// // Use store normally - same API as embedded mode
/// let node = store.get_node("some-id").await?;
///
/// Ok(())
/// }
/// ```
pub async fn new_http(
endpoint: &str,
namespace: &str,
database: &str,
username: &str,
password: &str,
) -> Result<Self> {
tracing::info!("Connecting to SurrealDB HTTP server at {}", endpoint);
// Create HTTP client connection to remote SurrealDB server
let db = Surreal::new::<Http>(endpoint)
.await
.context("Failed to connect to SurrealDB HTTP server")?;
// Authenticate with root credentials
db.signin(Root {
username,
password,
})
.await
.context("Failed to authenticate with SurrealDB")?;
// Set namespace and database
db.use_ns(namespace)
.use_db(database)
.await
.context("Failed to set namespace/database")?;
let db = Arc::new(db);
// IMPORTANT: Do NOT call initialize_schema() or seed_core_schemas()
// In HTTP mode, the server should already be initialized.
// Calling these would try to recreate tables/schemas.
tracing::info!("✅ Connected to SurrealDB HTTP server");
Ok(Self { db })
}
// ... rest of existing methods (get_node, create_node, etc.)
}Step 0.3: Update Cargo.toml Dependencies
# In packages/core/Cargo.toml
[dependencies]
# Existing dependencies
surrealdb = { version = "2.3", features = [
"kv-rocksdb", # Embedded RocksDB for desktop mode
"protocol-http", # ← ADD THIS: HTTP client for dev-proxy mode
] }Step 0.4: Test HTTP Constructor
# Create a test file to verify HTTP connection works
cat > /tmp/test-http-surreal.rs << 'EOF'
use nodespace_core::db::SurrealStore;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Make sure SurrealDB server is running first
println!("Testing HTTP connection to SurrealDB...");
let store = SurrealStore::new_http(
"http://127.0.0.1:8000",
"nodespace",
"nodes",
"root",
"root"
).await?;
println!("✅ Connection successful!");
// Test a simple query
let nodes = store.query_nodes(/* some filter */).await?;
println!("Found {} nodes", nodes.len());
Ok(())
}
EOF
# Run test (make sure dev:db is running first!)
bun run dev:db # In another terminal
cd packages/core
cargo run --example test-http-surreal # Or add to examples/Phase 1: Create Minimal HTTP Proxy Binary (~3-4 hours) ⏱️
File: packages/desktop-app/src-tauri/src/bin/dev-proxy.rs (NEW)
Step 1.1: Basic Server Structure
//! Development HTTP Proxy for Browser Mode
//!
//! This is a minimal HTTP server that forwards requests to NodeService,
//! preserving all Rust business logic while enabling SurrealDB inspection.
//!
//! Architecture:
//! Frontend → HTTP (port 3001) → NodeService → SurrealStore (HTTP) → SurrealDB (port 8000)
//! ↓
//! Surrealist ──────────────────────────────────────────────────────────→ SurrealDB
use axum::{
extract::{Path, State},
http::StatusCode,
response::Json,
routing::{delete, get, patch, post},
Router,
};
use nodespace_core::{
db::SurrealStore,
models::{Node, NodeUpdate},
services::NodeService,
};
use std::sync::Arc;
use tokio::sync::RwLock;
use tower_http::cors::CorsLayer;
/// Application state shared across handlers
#[derive(Clone)]
struct AppState {
node_service: Arc<RwLock<Arc<NodeService>>>,
}
/// Standard error response format
type ApiResult<T> = Result<Json<T>, (StatusCode, String)>;
type ApiStatusResult = Result<StatusCode, (StatusCode, String)>;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Initialize logging (shows debug output in terminal)
tracing_subscriber::fmt()
.with_env_filter("dev_proxy=debug,nodespace_core=debug")
.init();
println!("🔧 Initializing dev-proxy...");
// Connect to SurrealDB HTTP server (must be running on port 8000)
// IMPORTANT: Uses HTTP client mode, NOT embedded RocksDB
println!("📡 Connecting to SurrealDB HTTP server on port 8000...");
let store = match SurrealStore::new_http( // ← Uses new HTTP constructor from Phase 0
"http://127.0.0.1:8000",
"nodespace",
"nodes",
"root",
"root",
)
.await
{
Ok(s) => {
println!("✅ Connected to SurrealDB");
Arc::new(s)
}
Err(e) => {
eprintln!("❌ Failed to connect to SurrealDB: {}", e);
eprintln!(" Make sure SurrealDB server is running:");
eprintln!(" bun run dev:db");
eprintln!("\n Or check if port 8000 is available:");
eprintln!(" lsof -i :8000");
return Err(e);
}
};
// Initialize NodeService with all business logic
// NodeService has ALL the logic (virtual dates, schema backfill, etc.)
println!("🧠 Initializing NodeService...");
let node_service = match NodeService::new(store) {
Ok(s) => {
println!("✅ NodeService initialized");
Arc::new(s)
}
Err(e) => {
eprintln!("❌ Failed to initialize NodeService: {}", e);
return Err(e.into());
}
};
let state = AppState {
node_service: Arc::new(RwLock::new(node_service)),
};
// Build HTTP router
let app = Router::new()
// Health check (useful for testing)
.route("/health", get(health_check))
// Node CRUD endpoints
.route("/api/nodes", post(create_node))
.route("/api/nodes/:id", get(get_node))
.route("/api/nodes/:id", patch(update_node))
.route("/api/nodes/:id", delete(delete_node))
// Query endpoints
.route("/api/nodes/:id/children", get(get_children))
.route("/api/query", post(query_nodes))
.route("/api/nodes/by-container/:container_id", get(get_nodes_by_container))
// Mention endpoints
.route("/api/mentions", post(create_mention))
.route("/api/mentions", delete(delete_mention))
.route("/api/nodes/:id/mentions/outgoing", get(get_outgoing_mentions))
.route("/api/nodes/:id/mentions/incoming", get(get_incoming_mentions))
.route("/api/nodes/:id/mentions/containers", get(get_mentioning_containers))
// Schema endpoints
.route("/api/schemas/:id", get(get_schema))
.route("/api/mention-autocomplete", post(mention_autocomplete))
.with_state(state)
.layer(CorsLayer::permissive()); // Allow CORS from frontend (localhost:5173)
// Start HTTP server on port 3001
let listener = tokio::net::TcpListener::bind("127.0.0.1:3001")
.await
.map_err(|e| {
eprintln!("❌ Failed to bind to port 3001: {}", e);
eprintln!(" Another process may be using this port.");
eprintln!(" Check with: lsof -i :3001");
eprintln!(" Kill with: kill -9 <PID>");
e
})?;
println!("\n🚀 Dev proxy server started\!");
println!(" Listening on: http://127.0.0.1:3001");
println!(" NodeService → SurrealDB (port 8000)");
println!(" Surrealist can connect to port 8000\n");
axum::serve(listener, app).await?;
Ok(())
}
// === Handler Functions (implement all of these) ===
async fn health_check() -> &'static str {
"OK"
}
async fn create_node(
State(state): State<AppState>,
Json(node): Json<Node>,
) -> ApiResult<String> {
let service = state.node_service.read().await;
let id = service
.create_node(node)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
Ok(Json(id))
}
async fn get_node(
State(state): State<AppState>,
Path(id): Path<String>,
) -> ApiResult<Option<Node>> {
let service = state.node_service.read().await;
// ⭐ This call includes ALL business logic:
// - Virtual date node creation (YYYY-MM-DD format)
// - populate_mentions() (backlinks)
// - backfill_schema_version() (adds _schema_version to properties)
// - apply_lazy_migration() (upgrades nodes to latest schema)
let node = service
.get_node(&id)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
Ok(Json(node))
}
async fn update_node(
State(state): State<AppState>,
Path(id): Path<String>,
Json(update): Json<NodeUpdate>,
) -> ApiStatusResult {
let service = state.node_service.read().await;
service
.update_node(&id, update)
.await
.map_err(|e| {
let error_str = e.to_string();
// Map NodeService errors to HTTP status codes
// This helps frontend handle errors correctly
if error_str.contains("version") || error_str.contains("Version conflict") {
(StatusCode::CONFLICT, error_str) // 409 Conflict
} else if error_str.contains("not found") {
(StatusCode::NOT_FOUND, error_str) // 404 Not Found
} else if error_str.contains("validation") {
(StatusCode::BAD_REQUEST, error_str) // 400 Bad Request
} else {
(StatusCode::INTERNAL_SERVER_ERROR, error_str) // 500 Internal Error
}
})?;
Ok(StatusCode::NO_CONTENT) // 204 No Content (success)
}
async fn delete_node(
State(state): State<AppState>,
Path(id): Path<String>,
) -> ApiStatusResult {
let service = state.node_service.read().await;
service
.delete_node(&id, None)
.await
.map_err(|e| {
let error_str = e.to_string();
if error_str.contains("not found") {
(StatusCode::NOT_FOUND, error_str)
} else {
(StatusCode::INTERNAL_SERVER_ERROR, error_str)
}
})?;
Ok(StatusCode::NO_CONTENT)
}
async fn get_children(
State(state): State<AppState>,
Path(parent_id): Path<String>,
) -> ApiResult<Vec<Node>> {
let service = state.node_service.read().await;
let children = service
.get_children(&parent_id)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
Ok(Json(children))
}
// ⚠️ TODO: Implement remaining 12+ endpoints (see Step 1.2 below)
// Reference old dev-server code for exact patternsStep 1.2: Implement ALL Remaining Endpoints
Copy patterns from old dev-server (use git show commands above to view):
Endpoints still needed:
POST /api/query→query_nodes(body: NodeFilter JSON)GET /api/nodes/by-container/:id→get_nodes_by_container_idPOST /api/mentions→create_mention(body: {sourceId, targetId})DELETE /api/mentions→delete_mention(body: {sourceId, targetId})GET /api/nodes/:id/mentions/outgoing→get_outgoing_mentionsGET /api/nodes/:id/mentions/incoming→get_incoming_mentionsGET /api/nodes/:id/mentions/containers→get_mentioning_containersGET /api/schemas/:id→get_schemaPOST /api/mention-autocomplete→mention_autocomplete(body: {query, limit})
Pattern to follow for each endpoint:
async fn endpoint_name(
State(state): State<AppState>,
// Add Path/Json extractors as needed
) -> ApiResult<ReturnType> {
let service = state.node_service.read().await;
let result = service
.method_name(/* params */)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
Ok(Json(result))
}Step 1.3: Update Cargo.toml
# In packages/desktop-app/src-tauri/Cargo.toml
[[bin]]
name = "dev-proxy"
path = "src/bin/dev-proxy.rs"
[dependencies]
# Existing dependencies (already there)
nodespace-core = { path = "../../../packages/core" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.35", features = ["full"] }
anyhow = "1.0"
tracing = "0.1"
# Add these for HTTP server
axum = "0.7"
tower-http = { version = "0.6", features = ["cors"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }Step 1.4: Test Dev Proxy Compiles and Runs
# Make sure SurrealDB is running first
bun run dev:db
# In another terminal, compile and run dev-proxy
cd packages/desktop-app/src-tauri
cargo build --bin dev-proxy
# If successful, run it
cargo run --bin dev-proxy
# Expected output:
# 🔧 Initializing dev-proxy...
# 📡 Connecting to SurrealDB HTTP server on port 8000...
# ✅ Connected to SurrealDB
# 🧠 Initializing NodeService...
# ✅ NodeService initialized
# 🚀 Dev proxy server started!
# Listening on: http://127.0.0.1:3001Step 1.5: Test Endpoints with curl
# Terminal 1: SurrealDB
bun run dev:db
# Terminal 2: Dev proxy
cargo run --bin dev-proxy
# Terminal 3: Test with curl
# 1. Health check
curl http://127.0.0.1:3001/health
# Expected: OK
# 2. Get non-existent node
curl http://127.0.0.1:3001/api/nodes/test-123
# Expected: null
# 3. Get virtual date node (⭐ THIS TESTS BUSINESS LOGIC!)
curl http://127.0.0.1:3001/api/nodes/2025-01-15
# Expected: JSON with virtual date node (not null!)
# 4. Create a node
curl -X POST http://127.0.0.1:3001/api/nodes \\
-H "Content-Type: application/json" \\
-d '{
"id": "test-node-1",
"nodeType": "text",
"content": "Hello from dev-proxy",
"parentId": null,
"containerNodeId": null,
"beforeSiblingId": null,
"version": 1,
"createdAt": "2025-01-14T00:00:00Z",
"modifiedAt": "2025-01-14T00:00:00Z",
"properties": {},
"mentions": []
}'
# Expected: "test-node-1"
# 5. Verify node was created in SurrealDB
curl -X POST http://127.0.0.1:8000/sql \\
-H "Authorization: Basic cm9vdDpyb290" \\
-H "NS: nodespace" \\
-H "DB: nodes" \\
-d "SELECT * FROM nodes;"
# Expected: See test-node-1 in responsePhase 2: Restore HttpAdapter to REST (~2-3 hours) ⏱️
File: packages/desktop-app/src/lib/services/backend-adapter.ts
Step 2.1: View Old HttpAdapter Implementation
# Get the OLD HttpAdapter code (before SurrealQL migration)
git show 1f510e3^:packages/desktop-app/src/lib/services/backend-adapter.ts > /tmp/old-http-adapter.ts
# Open it in editor to see original REST implementation
code /tmp/old-http-adapter.ts
# You'll use this as reference for ALL the methodsStep 2.2: Change Constructor to Use Port 3001
export class HttpAdapter implements BackendAdapter {
private readonly baseUrl: string;
constructor(baseUrl: string = 'http://localhost:3001') { // ← Changed from 8000 to 3001
this.baseUrl = baseUrl;
// ❌ Remove this.auth - no longer needed (proxy doesn't need auth)
}
}Step 2.3: Remove ALL SurrealQL-Specific Code
Delete these methods (they're not needed with REST approach):
// ❌ DELETE THESE:
private async surrealQuery<T>(sql: string): Promise<T> { /* ... */ }
private escapeSurrealString(str: string): string { /* ... */ }
private toSurrealValue(value: unknown): string { /* ... */ }
private mapSurrealNodeToTypescript(surrealNode: Record<string, unknown>): Node { /* ... */ }Step 2.4: Restore getNode() to REST
Reference: /tmp/old-http-adapter.ts (from Step 2.1)
async getNode(id: string): Promise<Node | null> {
try {
// Simple REST call - proxy handles all business logic
const response = await this.fetchWithTimeout(
\`${this.baseUrl}/api/nodes/${encodeURIComponent(id)}\`
);
// 404 = node not found (or virtual node not created by NodeService)
if (response.status === 404) {
return null;
}
if (!response.ok) {
throw new Error(\`Failed to get node: ${response.statusText}\`);
}
const node = await response.json();
// ⭐ Node returned by proxy includes ALL computed fields:
// - Virtual date nodes (if ID is YYYY-MM-DD)
// - _schema_version in properties (backfilled by NodeService)
// - mentioned_by populated (computed from mentions table)
return node;
} catch (error) {
const err = toError(error);
throw new NodeOperationError(err.message, id, 'get');
}
}Step 2.5: Restore createNode() to REST
async createNode(node: Omit<Node, 'createdAt' | 'modifiedAt' | 'version'>): Promise<string> {
return await this.retryOnTransientError(async () => {
const response = await globalThis.fetch(\`${this.baseUrl}/api/nodes\`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(node),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(\`Failed to create node: ${errorText}\`);
}
const nodeId = await response.json();
// ✅ KEEP event emissions - these are still needed!
eventBus.emit<NodeCreatedEvent>({
type: 'node:created',
namespace: 'lifecycle',
source: 'HttpAdapter',
nodeId: nodeId,
parentId: node.parentId ?? undefined,
nodeType: node.nodeType,
});
return nodeId;
});
}Step 2.6: Restore updateNode() to REST
async updateNode(id: string, version: number, update: NodeUpdate): Promise<Node> {
return await this.retryOnTransientError(async () => {
const response = await globalThis.fetch(\`${this.baseUrl}/api/nodes/${encodeURIComponent(id)}\`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ version, ...update }),
});
// 409 Conflict = version mismatch (OCC)
if (response.status === 409) {
throw new Error(\`Version conflict: expected version ${version} but node has been modified\`);
}
if (!response.ok) {
const errorText = await response.text();
throw new Error(\`Failed to update node: ${errorText}\`);
}
const updatedNode = await response.json();
// ✅ KEEP event emissions
let updateType: 'content' | 'hierarchy' | 'status' | 'metadata' | 'nodeType' = 'content';
if (update.parentId !== undefined || update.containerNodeId !== undefined) {
updateType = 'hierarchy';
} else if (update.nodeType !== undefined) {
updateType = 'nodeType';
}
eventBus.emit<NodeUpdatedEvent>({
type: 'node:updated',
namespace: 'lifecycle',
source: 'HttpAdapter',
nodeId: id,
updateType,
});
return updatedNode;
});
}Step 2.7: Restore ALL Other Methods
Reference: Use /tmp/old-http-adapter.ts as your guide.
For EACH of these 14 methods, copy the REST implementation from old code:
- ✅
getNode()- Done above - ✅
createNode()- Done above - ✅
updateNode()- Done above deleteNode()- Copy from old codegetChildren()- Copy from old codequeryNodes()- Copy from old codegetNodesByContainerId()- Copy from old codecreateNodeMention()- Copy from old codedeleteNodeMention()- Copy from old codegetOutgoingMentions()- Copy from old codegetIncomingMentions()- Copy from old codegetMentioningContainers()- Copy from old codementionAutocomplete()- Copy from old codegetSchema()- Copy from old codeaddSchemaField()- Copy from old coderemoveSchemaField()- Copy from old codeupdateSchemaField()- Copy from old code
What to keep:
- ✅ All
eventBus.emit()calls - ✅ All
retryOnTransientError()wrappers - ✅ All error handling with
NodeOperationError - ✅ All
fetchWithTimeout()calls
What to remove:
- ❌ Any
surrealQuery()calls - ❌ Any
escapeSurrealString()calls - ❌ Any SQL building logic
- ❌ Any
mapSurrealNodeToTypescript()calls
Step 2.8: Test Each Method in Browser Console
After restoring each method, test it:
// Open http://localhost:5173 in browser
// Open DevTools console
import { getBackendAdapter } from '/services/backend-adapter';
const adapter = getBackendAdapter();
// Test the method you just restored
await adapter.getNode('2025-01-15'); // Should return virtual date node now!Phase 3: Update Dev Scripts (~30 min) ⏱️
File: packages/desktop-app/package.json
Replace the scripts section:
{
"scripts": {
"preinstall": "node ../../enforce-bun.js",
"postinstall": "bun run scripts/check-dev-deps.ts || true",
"dev:check": "bun run scripts/check-dev-deps.ts",
"dev:db": "surreal start --bind 127.0.0.1:8000 --user root --pass root --log info memory",
"dev:db:persist": "surreal start --bind 127.0.0.1:8000 --user root --pass root --log info file://.nodespace/dev.db",
"dev:proxy": "cd src-tauri && cargo run --bin dev-proxy",
"dev:db:init": "bun run scripts/init-schemas-via-proxy.ts",
"dev:frontend": "bunx vite dev",
"dev": "bun run dev:check && bunx concurrently --kill-others --names 'DB,Proxy,Init,UI' --prefix-colors 'blue,yellow,magenta,green' 'bun run dev:db' 'sleep 2 && bun run dev:proxy' 'sleep 4 && bun run dev:db:init' 'sleep 6 && bun run dev:frontend'",
"dev:web": "bunx vite dev --port 1421",
"build": "bunx vite build",
"test": "bunx vitest run",
"test:watch": "bunx vitest",
"test:all": "bun run test && cd src-tauri && cargo test",
"tauri": "bunx tauri",
"tauri:dev": "bunx tauri dev -- --bin nodespace-app",
"tauri:build": "bunx tauri build"
}
}Startup sequence explained:
Time Service What Happens
------ -------------- ------------------------------------------
0s dev:check Verify SurrealDB installed
0s dev:db Start SurrealDB on port 8000 (in-memory)
2s dev:proxy Start dev-proxy on port 3001
→ Connects to SurrealDB (port 8000)
→ Initializes NodeService (business logic)
4s dev:db:init Initialize schemas via proxy
→ Creates 7 core schemas through NodeService
6s dev:frontend Start Vite dev server
→ Opens browser at localhost:5173
→ HttpAdapter connects to proxy (port 3001)
Why the delays:
- 2s: SurrealDB needs time to start and become ready
- 4s: Dev-proxy needs to connect to DB and init NodeService
- 6s: Schema init needs proxy to be ready
Test:
bun run dev
# Watch terminal output - should see all 4 services start:
# [DB] Started database server on 127.0.0.1:8000
# [Proxy] 🚀 Dev proxy listening on http://127.0.0.1:3001
# [Init] ✅ All core schemas initialized successfully!
# [UI] ➜ Local: http://localhost:5173/Phase 4: Schema Initialization via Proxy (~1 hour) ⏱️
Step 4.1: Create init-schemas-via-proxy.ts
File: packages/desktop-app/scripts/init-schemas-via-proxy.ts (NEW)
Full implementation provided in issue (see above) - 200+ lines with all 7 core schemas.
Step 4.2: Delete Old init-surrealdb.ts
# Remove old script that bypasses NodeService
git rm packages/desktop-app/scripts/init-surrealdb.ts
# Verify it's staged for deletion
git statusStep 4.3: Test Schema Initialization
# Start DB and proxy first
bun run dev:db # Terminal 1
bun run dev:proxy # Terminal 2
# Run schema init
bun run dev:db:init # Terminal 3
# Expected output:
# ⏳ Waiting for dev-proxy to be ready...
# ✅ Dev-proxy is ready
# 🌱 Initializing core schemas via NodeService...
# ✅ Created schema: task
# ✅ Created schema: text
# ✅ Created schema: date
# ✅ Created schema: header
# ✅ Created schema: code-block
# ✅ Created schema: quote-block
# ✅ Created schema: ordered-list
# ✅ All core schemas initialized successfully!
# Verify schemas in browser console
const adapter = getBackendAdapter();
const taskSchema = await adapter.getNode('task');
console.log(taskSchema); // Should show schema node with properties._schema_versionPhase 5: Testing (~2 hours) ⏱️
Run all 5 test scenarios documented above (Test 1-5).
Critical Test: Virtual date nodes must work!
# In browser console (http://localhost:5173)
const adapter = getBackendAdapter();
const dateNode = await adapter.getNode('2025-01-15');
// ⭐ This should NOT be null - it should return virtual date node!
console.log(dateNode);
// Expected:
// {
// id: "2025-01-15",
// nodeType: "date",
// content: "2025-01-15",
// parentId: null,
// ...
// }Phase 6: Documentation (~1 hour) ⏱️
Update docs/architecture/development/browser-dev-mode.md:
Changes needed:
- Add dev-proxy to architecture diagram
- Update "How It Works" section to explain port 3001 vs 8000
- Add troubleshooting for dev-proxy issues
- Document that business logic is now preserved
Acceptance Criteria
Functionality Restored ✅
- Virtual date nodes work:
getNode('2025-01-15')returns virtual node (NOT null) - Schema version backfill works: New nodes have
properties._schema_version - Lazy schema migrations work: Nodes auto-upgraded when schema version changes
- Mention backlinks work:
mentioned_byfield populated by NodeService - All NodeService business logic runs in browser mode
- Browser mode behavior matches desktop mode (100% parity)
Surrealist Integration ✅
- Surrealist connects to port 8000
- Can query:
SELECT * FROM nodes; - Can see all nodes created via frontend
- Real-time inspection works
Developer Experience ✅
-
bun run devstarts all services automatically (DB, proxy, init, frontend) - Startup sequence is reliable (no race conditions)
- Clear error messages if any service fails
- Hot reload works for frontend code
- Logs clearly show which service is logging
Code Quality ✅
- Dev proxy is minimal (~300 lines including all endpoints)
- No business logic duplication (all logic in NodeService)
- HttpAdapter is simple REST calls (no SurrealQL)
- All 460+ frontend tests pass
- Rust tests pass:
cargo test - Quality checks pass:
bun run quality:fix
Documentation ✅
- Updated
browser-dev-mode.mdwith dev-proxy architecture - Explains port 3001 (proxy) vs 8000 (SurrealDB)
- Troubleshooting section for proxy issues
- README reflects new setup
Implementation Checklist
Phase 0: Add HTTP Constructor to SurrealStore (1 hour) ⏱️
File: packages/core/src/db/surreal_store.rs
-
Add imports at top of file (line ~52):
use surrealdb::engine::remote::http::{Client, Http}; use surrealdb::opt::auth::Root;
-
Add
new_http()method after existingnew()method (around line 180):- Copy complete implementation from issue (provided above)
- Test compilation:
cargo build
-
Update
packages/core/Cargo.toml:[dependencies] surrealdb = { version = "2.3", features = [ "kv-rocksdb", # Embedded mode (existing) "protocol-http", # ← ADD THIS: HTTP client mode ] }
-
Test HTTP constructor works:
# Start SurrealDB first bun run dev:db # Test connection in Rust cd packages/core cargo test test_http_connection --lib -- --nocapture
Phase 1: Create Dev Proxy (3-4 hours) ⏱️
-
Create file:
packages/desktop-app/src-tauri/src/bin/dev-proxy.rs -
Copy main() function from issue (complete implementation provided)
-
Implement all handler functions:
-
health_check() -
create_node() -
get_node() -
update_node() -
delete_node() -
get_children() -
query_nodes() -
get_nodes_by_container() -
create_mention() -
delete_mention() -
get_outgoing_mentions() -
get_incoming_mentions() -
get_mentioning_containers() -
get_schema() -
mention_autocomplete()
-
-
Update
packages/desktop-app/src-tauri/Cargo.toml:- Add
[[bin]]section for dev-proxy - Add axum, tower-http, tracing-subscriber dependencies
- Add
-
Test compilation:
cargo build --bin dev-proxy -
Test server starts:
cargo run --bin dev-proxy -
Test with curl (all 5 curl examples from Step 1.5)
Phase 2: Restore HttpAdapter to REST (2-3 hours) ⏱️
- Save old implementation:
git show 1f510e3^:packages/desktop-app/src/lib/services/backend-adapter.ts > /tmp/old-http-adapter.ts - Open
packages/desktop-app/src/lib/services/backend-adapter.ts - Change constructor baseUrl:
http://localhost:3001 - Delete SurrealQL methods (4 methods)
- Restore all 17 REST methods:
- Use
/tmp/old-http-adapter.tsas reference - Copy method by method
- Keep event emissions!
- Keep retry logic!
- Use
- Test each method in browser console as you restore it
Phase 3: Update Dev Scripts (30 min) ⏱️
- Update
packages/desktop-app/package.jsonscripts - Add
dev:proxyscript - Update
devscript with concurrently - Test
bun run devstarts all services - Verify correct startup order
Phase 4: Schema Init via Proxy (1 hour) ⏱️
- Create
packages/desktop-app/scripts/init-schemas-via-proxy.ts - Copy complete implementation from issue (200+ lines provided)
- Test:
bun run dev:db:init - Delete old script:
git rm packages/desktop-app/scripts/init-surrealdb.ts
Phase 5: Testing (2 hours) ⏱️
- Run Test 1: Virtual date nodes (console test)
- Run Test 2: Schema version backfill (console test)
- Run Test 3: Mention backlinks (console test)
- Run Test 4: Surrealist connection
- Run Test 5: Full CRUD workflow (console test)
- Run frontend tests:
bun run test:all - Verify no test regressions
- Manual QA in UI: create tasks, dates, mentions
Phase 6: Documentation (1 hour) ⏱️
- Update
docs/architecture/development/browser-dev-mode.md - Add dev-proxy to architecture diagram
- Explain port 3001 (proxy) vs 8000 (SurrealDB)
- Add troubleshooting section
- Update README.md if needed
- Run
bun run quality:fix - Create PR:
bun run gh:pr 500
Detailed Implementation Guide
Understanding the Architecture
Key Concept: SurrealDB Rust SDK supports two modes:
Mode 1: Embedded (Desktop):
use surrealdb::engine::local::RocksDb;
let db = Surreal::new::<RocksDb>(PathBuf::from("./data.db")).await?;
// Database is a LOCAL FILE - no server neededMode 2: HTTP Client (Dev-Proxy):
use surrealdb::engine::remote::http::Http;
use surrealdb::opt::auth::Root;
let db = Surreal::new::<Http>("http://127.0.0.1:8000").await?;
db.signin(Root { username: "root", password: "root" }).await?;
// Database is a REMOTE SERVER - connects via HTTPYour dev-proxy uses Mode 2 (HTTP client) to connect to the standalone SurrealDB server.
Common Mistakes to Avoid
❌ DON'T:
- Try to use
SurrealStore::new(PathBuf)in dev-proxy - it won't work (embedded only) - Skip Phase 0 (HTTP constructor) - dev-proxy won't compile without it
- Remove event emissions from HttpAdapter - frontend depends on them
- Connect HttpAdapter directly to port 8000 - bypasses business logic again!
- Run schema init BEFORE dev-proxy is ready - will fail with connection refused
✅ DO:
- Complete Phase 0 FIRST (add HTTP constructor to SurrealStore)
- Use
SurrealStore::new_http()in dev-proxy - Reference old dev-server code for endpoint patterns
- Test each phase before moving to next
- Verify virtual date nodes work in browser console
Troubleshooting Guide
Phase 0 Issues
Error: cannot find \Http` in `engine::remote::http``
Solution: Add protocol-http feature to packages/core/Cargo.toml:
surrealdb = { version = "2.3", features = ["kv-rocksdb", "protocol-http"] }Error: cannot find \Root` in `opt::auth``
Solution: Add import:
use surrealdb::opt::auth::Root;Phase 1 Issues
Error: Dev-proxy can't connect to SurrealDB
Check:
# Is SurrealDB running?
curl http://127.0.0.1:8000/health
# Expected: {"status":"ok"}
# If not, start it
bun run dev:dbError: Address already in use (port 3001)
Solution:
lsof -i :3001
kill -9 <PID>Phase 2 Issues
Error: Virtual date nodes still return null
Possible causes:
- HttpAdapter still using port 8000 (check constructor baseUrl)
- Dev-proxy not calling NodeService.get_node() correctly
- HTTP constructor not working (Phase 0 incomplete)
Debug:
# Test proxy directly
curl http://127.0.0.1:3001/api/nodes/2025-01-15
# Should return virtual date node JSON, not nullTime Estimate
Junior Engineer: 12-14 hours total
- Phase 0: 1 hour (new HTTP constructor)
- Phase 1: 3-4 hours (dev-proxy implementation)
- Phase 2: 2-3 hours (HttpAdapter restoration)
- Phase 3: 30 min (dev scripts)
- Phase 4: 1 hour (schema init)
- Phase 5: 2 hours (testing)
- Phase 6: 1 hour (documentation)
- Buffer: 2 hours (debugging)
Senior Engineer: 7-9 hours (faster due to codebase familiarity)
Success Metrics
- Virtual Nodes Work:
getNode('2025-01-15')returns node (not null) - Business Logic 100%: All NodeService features work in browser
- Code Reduction: Net ~1,500 lines removed vs original dev-server
- Surrealist Works: Live database inspection on port 8000
- Tests Pass: All 460+ frontend tests + Rust tests passing
Related Issues & PRs
- Simplify Browser Dev Mode: Use SurrealDB HTTP Server Instead of Custom REST Layer #490: Original SurrealDB migration (unclear intent)
- Simplify Browser Dev Mode: Use SurrealDB HTTP Server Instead of Custom REST Layer #497: Direct SurrealDB migration PR (introduced regression)
- Migrate schema operations to SurrealQL #499: Schema operations SurrealQL migration (no longer needed with proxy)
Priority
High - Browser dev mode currently unusable for feature development (missing critical business logic).
Activity
malibio commentedon Nov 14, 2025
Path Standardization Update
Updated all database paths to use standardized structure:
Desktop Mode (Tauri):
~/.nodespace/database/nodespaceBrowser Dev Mode (SurrealDB Server):
~/.nodespace/database/nodespace-devBenefits:
~/.nodespace/database/)nodespacefor production,nodespace-devfor dev.dbextension (SurrealDB RocksDB creates directories, not single files)Updated in commit f5fed57:
packages/desktop-app/package.json:dev:dbscript uses correct pathdocs/architecture/development/browser-dev-mode.md: Documents correct pathAll code examples in this issue should use these standardized paths.
Restore Business Logic Layer to Browser Dev Mode
Restore Business Logic Layer to Browser Dev Mode (#501)
Restore Business Logic Layer to Browser Dev Mode (#501)
Restore Business Logic Layer to Browser Dev Mode (#501)