Repository navigation
Description
Context
NodeSpace currently has no multi-client synchronization. When the MCP server creates or modifies nodes, the Tauri frontend doesn't see these changes until a manual refresh. This architecture review document identified LIVE SELECT as the solution for real-time reactivity.
Current Problems:
- No multi-client sync: MCP server changes invisible to Tauri frontend
- Manual cache management: Frontend maintains
childrenCacheandparentsCachethat get stale - Race conditions: Frontend cache can be out of sync with database
- Manual event propagation: Custom EventBus needs manual emit/subscribe everywhere
Proposed Solution: SurrealDB LIVE SELECT
LIVE SELECT provides real-time notifications when database records change. We'll use it to stream node and edge changes directly to the frontend via Tauri events.
Step-by-Step Implementation Guide
Step 1: Create the Live Query Service in Rust
File: packages/desktop-app/src-tauri/src/services/live_query_service.rs (create new)
use futures::StreamExt;
use surrealdb::engine::local::Db;
use surrealdb::opt::auth::Root;
use surrealdb::{Notification, Surreal};
use tauri::Manager;
use serde::{Deserialize, Serialize};
use anyhow::Result;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Node {
pub id: String,
pub content: String,
#[serde(rename = "nodeType")]
pub node_type: String,
pub properties: serde_json::Value,
pub version: i32,
#[serde(rename = "createdAt")]
pub created_at: String,
#[serde(rename = "modifiedAt")]
pub modified_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HasChildEdge {
pub id: String,
#[serde(rename = "in")]
pub parent_id: String,
#[serde(rename = "out")]
pub child_id: String,
pub order: f64, // Fractional ordering from Issue #550
}
pub struct LiveQueryService {
db: Surreal<Db>,
app_handle: tauri::AppHandle,
}
impl LiveQueryService {
pub fn new(db: Surreal<Db>, app_handle: tauri::AppHandle) -> Self {
Self { db, app_handle }
}
/// Start listening to database changes and emit Tauri events
pub async fn start_live_queries(&self) -> Result<()> {
println!("Starting LIVE SELECT subscriptions...");
// Subscribe to node changes
self.subscribe_to_nodes().await?;
// Subscribe to edge changes
self.subscribe_to_edges().await?;
println!("LIVE SELECT subscriptions active");
Ok(())
}
async fn subscribe_to_nodes(&self) -> Result<()> {
// Create LIVE SELECT query for nodes
let mut response = self.db
.query("LIVE SELECT * FROM node")
.await?;
// Get the UUID for this live query
let live_id: String = response.take(0)?;
println!("Node LIVE query ID: {}", live_id);
// Stream notifications
let mut stream = self.db
.query(&format!("SHOW CHANGES FOR TABLE node SINCE 0 LIVE"))
.await?
.stream::<Notification<Node>>(0)?;
let app_handle = self.app_handle.clone();
// Spawn task to handle node notifications
tokio::spawn(async move {
println!("Node stream handler started");
while let Some(notification) = stream.next().await {
match notification.action {
surrealdb::Action::Create => {
println!("Node created: {:?}", notification.data.id);
app_handle.emit_all("node:created", ¬ification.data)
.unwrap_or_else(|e| eprintln!("Failed to emit node:created: {}", e));
}
surrealdb::Action::Update => {
println!("Node updated: {:?}", notification.data.id);
app_handle.emit_all("node:updated", ¬ification.data)
.unwrap_or_else(|e| eprintln!("Failed to emit node:updated: {}", e));
}
surrealdb::Action::Delete => {
println!("Node deleted: {:?}", notification.data.id);
app_handle.emit_all("node:deleted", ¬ification.data.id)
.unwrap_or_else(|e| eprintln!("Failed to emit node:deleted: {}", e));
}
_ => {}
}
}
eprintln!("Node stream ended unexpectedly");
});
Ok(())
}
async fn subscribe_to_edges(&self) -> Result<()> {
// Create LIVE SELECT query for edges
let mut response = self.db
.query("LIVE SELECT * FROM has_child")
.await?;
let live_id: String = response.take(0)?;
println!("Edge LIVE query ID: {}", live_id);
// Stream notifications
let mut stream = self.db
.query(&format!("SHOW CHANGES FOR TABLE has_child SINCE 0 LIVE"))
.await?
.stream::<Notification<HasChildEdge>>(0)?;
let app_handle = self.app_handle.clone();
// Spawn task to handle edge notifications
tokio::spawn(async move {
println!("Edge stream handler started");
while let Some(notification) = stream.next().await {
match notification.action {
surrealdb::Action::Create => {
println!("Edge created: {} -> {}",
notification.data.parent_id,
notification.data.child_id);
app_handle.emit_all("edge:created", ¬ification.data)
.unwrap_or_else(|e| eprintln!("Failed to emit edge:created: {}", e));
}
surrealdb::Action::Update => {
println!("Edge updated: {} -> {}",
notification.data.parent_id,
notification.data.child_id);
app_handle.emit_all("edge:updated", ¬ification.data)
.unwrap_or_else(|e| eprintln!("Failed to emit edge:updated: {}", e));
}
surrealdb::Action::Delete => {
println!("Edge deleted: {}", notification.data.id);
app_handle.emit_all("edge:deleted", ¬ification.data)
.unwrap_or_else(|e| eprintln!("Failed to emit edge:deleted: {}", e));
}
_ => {}
}
}
eprintln!("Edge stream ended unexpectedly");
});
Ok(())
}
/// Handle reconnection if stream disconnects
pub async fn handle_reconnection(&self) -> Result<()> {
loop {
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
// Check if streams are still alive
// If not, restart them
if !self.check_streams_alive().await {
println!("Streams disconnected, reconnecting...");
self.start_live_queries().await?;
}
}
}
async fn check_streams_alive(&self) -> bool {
// Implementation to check if streams are still active
// This could ping the database or check stream status
true // Placeholder
}
}Step 2: Register Live Query Service in main.rs
File: packages/desktop-app/src-tauri/src/main.rs
Add the LiveQueryService to your app initialization:
mod services;
use services::live_query_service::LiveQueryService;
#[tokio::main]
async fn main() {
// ... existing code ...
tauri::Builder::default()
.setup(|app| {
// Get database connection
let db = app.state::<Surreal<Db>>();
let app_handle = app.handle();
// Create and start live query service
let live_service = LiveQueryService::new(db.clone(), app_handle);
// Start live queries in background
tauri::async_runtime::spawn(async move {
if let Err(e) = live_service.start_live_queries().await {
eprintln!("Failed to start live queries: {}", e);
}
// Keep service alive with reconnection handling
if let Err(e) = live_service.handle_reconnection().await {
eprintln!("Live query reconnection failed: {}", e);
}
});
Ok(())
})
// ... rest of your app config ...
.run(tauri::generate_context!())
.expect("error while running tauri application");
}Step 3: Add Service Module
File: packages/desktop-app/src-tauri/src/services/mod.rs
pub mod live_query_service;
// ... other services ...Step 4: Update Cargo.toml Dependencies
File: packages/desktop-app/src-tauri/Cargo.toml
Ensure you have the required dependencies:
[dependencies]
surrealdb = { version = "1.0", features = ["kv-mem", "kv-rocksdb"] }
futures = "0.3"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
anyhow = "1.0"
tauri = { version = "2.0", features = [] }Step 5: Create TypeScript Types for Events
File: packages/desktop-app/src/lib/types/events.ts (create new)
// Event types that match Rust structures
export interface NodeEvent {
id: string;
content: string;
nodeType: string;
properties: Record<string, unknown>;
version: number;
createdAt: string;
modifiedAt: string;
}
export interface EdgeEvent {
id: string;
in: string; // parent_id in Rust
out: string; // child_id in Rust
order: number;
}
// Event payload types
export type NodeCreatedEvent = NodeEvent;
export type NodeUpdatedEvent = NodeEvent;
export type NodeDeletedEvent = string; // Just the ID
export type EdgeCreatedEvent = EdgeEvent;
export type EdgeUpdatedEvent = EdgeEvent;
export type EdgeDeletedEvent = EdgeEvent;Step 6: Test LIVE SELECT with Frontend Listener
File: packages/desktop-app/src/lib/stores/test-live-select.svelte.ts (create for testing)
import { listen } from '@tauri-apps/api/event';
import type { NodeEvent, EdgeEvent } from '$lib/types/events';
// Test listener to verify events are coming through
export async function testLiveSelect() {
console.log('Setting up LIVE SELECT test listeners...');
// Node events
await listen<NodeEvent>('node:created', (event) => {
console.log('📗 Node created:', event.payload);
});
await listen<NodeEvent>('node:updated', (event) => {
console.log('📘 Node updated:', event.payload);
});
await listen<string>('node:deleted', (event) => {
console.log('📕 Node deleted:', event.payload);
});
// Edge events
await listen<EdgeEvent>('edge:created', (event) => {
console.log('🔗 Edge created:', event.payload);
});
await listen<EdgeEvent>('edge:updated', (event) => {
console.log('🔄 Edge updated:', event.payload);
});
await listen<EdgeEvent>('edge:deleted', (event) => {
console.log('❌ Edge deleted:', event.payload);
});
console.log('LIVE SELECT listeners ready!');
}
// Call this in your app initialization to test
// testLiveSelect();Step 7: Integration Test for Multi-Client Sync
File: packages/desktop-app/src/tests/integration/live-select-multi-client.test.ts (create new)
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { listen } from '@tauri-apps/api/event';
import type { NodeEvent } from '$lib/types/events';
describe('LIVE SELECT Multi-Client Synchronization', () => {
let unsubscribe: () => void;
let nodeCreatedPromise: Promise<NodeEvent>;
beforeAll(async () => {
// Set up listener before MCP creates node
nodeCreatedPromise = new Promise((resolve) => {
listen<NodeEvent>('node:created', (event) => {
resolve(event.payload);
}).then(unsub => {
unsubscribe = unsub;
});
});
});
afterAll(() => {
if (unsubscribe) unsubscribe();
});
it('should receive node:created event when MCP server creates node', async () => {
// Simulate MCP server creating a node
// In real test, this would be actual MCP server call
await simulateMCPCreateNode({
id: 'test-node-1',
content: 'Test content',
nodeType: 'text'
});
// Wait for event with timeout
const event = await Promise.race([
nodeCreatedPromise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), 100)
)
]) as NodeEvent;
expect(event.id).toBe('test-node-1');
expect(event.content).toBe('Test content');
});
it('should sync hierarchy changes within 100ms', async () => {
const startTime = Date.now();
const edgePromise = new Promise((resolve) => {
listen('edge:created', (event) => {
resolve(event.payload);
});
});
// MCP server indents a node
await simulateMCPIndentNode('node-1', 'parent-1');
const edge = await edgePromise;
const elapsed = Date.now() - startTime;
expect(elapsed).toBeLessThan(100);
expect(edge).toHaveProperty('in', 'parent-1');
expect(edge).toHaveProperty('out', 'node-1');
});
});
// Helper function to simulate MCP operations
async function simulateMCPCreateNode(node: any) {
// This would call your actual MCP API
// For now, directly insert to database to trigger LIVE SELECT
}
async function simulateMCPIndentNode(nodeId: string, parentId: string) {
// Simulate MCP server moving a node
}Testing Checklist
Manual Testing
- Start Tauri app with
bun run tauri:dev - Open browser console
- Run
testLiveSelect()in console - Create a node via MCP server or database CLI
- Verify "📗 Node created" appears in console within 100ms
- Update a node via database
- Verify "📘 Node updated" appears in console
- Delete a node
- Verify "📕 Node deleted" appears in console
Automated Tests
- Test node creation events arrive within 100ms
- Test node update events arrive with correct data
- Test edge creation/deletion for hierarchy changes
- Test reconnection after database restart
- Test handling of malformed events
- Test memory usage with 1000+ rapid events
Performance Tests
- Measure latency: database commit → Tauri event
- Should be <10ms for local database
- Should be <100ms even under load
Acceptance Criteria
- Create
LiveQueryServicein Rust that subscribes to LIVE SELECT - Subscribe to
LIVE SELECT * FROM nodewith notification stream - Subscribe to
LIVE SELECT * FROM has_childwith notification stream - Emit Tauri events:
node:created,node:updated,node:deleted - Emit Tauri events:
edge:created,edge:updated,edge:deleted - Handle stream reconnection on disconnect
- Latency: <10ms from database commit to Tauri event
- Integration test: MCP server creates node → Tauri receives event within 100ms
- Console logging shows all events arriving correctly
Common Pitfalls to Avoid
- Don't forget error handling - Streams can disconnect, handle gracefully
- Watch memory usage - Long-running streams can leak if not managed
- Test reconnection - Database restarts shouldn't break the app
- Verify event structure - TypeScript types must match Rust exactly
- Check Tauri event limits - Very large payloads might need chunking
Dependencies
- Issue Migrate database schema to use fractional ordering instead of beforeSiblingId linked-list #550 (Fractional ordering) - The
orderfield must exist on edges
Files to Create/Modify
- CREATE:
packages/desktop-app/src-tauri/src/services/live_query_service.rs - CREATE:
packages/desktop-app/src-tauri/src/services/mod.rs - CREATE:
packages/desktop-app/src/lib/types/events.ts - CREATE:
packages/desktop-app/src/lib/stores/test-live-select.svelte.ts - CREATE:
packages/desktop-app/src/tests/integration/live-select-multi-client.test.ts - MODIFY:
packages/desktop-app/src-tauri/src/main.rs- Initialize service - MODIFY:
packages/desktop-app/src-tauri/Cargo.toml- Add dependencies
Questions During Implementation
- Should we batch rapid events to avoid overwhelming frontend?
- How should we handle events for nodes user doesn't have loaded?
- Should we filter LIVE SELECT by workspace/document?
Success Metrics
After implementation:
- Zero manual cache invalidation calls
- MCP changes visible in Tauri within 100ms
- Memory stable even after 10,000 events
- Automatic reconnection works after database restart
Activity
Implement SurrealDB LIVE SELECT for real-time synchronization (Issue #…
WIP: Foundation for SurrealDB LIVE SELECT real-time sync (Issue #551)
malibio commentedon Nov 20, 2025
Test Baseline - Issue #551
Test Run Date: 2025-11-20 12:12 PM
Status: Foundation code compiles cleanly with no new test failures introduced
Test Results:
Test Categories:
Foundation Work Completed (from commit de403a5):
LiveQueryServiceRust structureKnown Limitations (To Be Implemented):
sync:*instead ofnode:*/edge:*(spec mismatch)Next Steps:
Will implement actual polling-based change detection as recommended in commit message (SurrealDB Rust driver doesn't fully support streaming LIVE SELECT yet).
Implement polling-based real-time sync with proper event types (Issue #…
WIP: Implement polling-based real-time sync - Core implementation com…
malibio commentedon Nov 20, 2025
WIP Update: Core Polling Implementation Complete ✅
Summary
The core polling-based real-time synchronization implementation is complete and ready for testing. All Rust and TypeScript code compiles cleanly with no linting errors.
Completed Phases (1-5)
Phase 1: Polling-based change detection ✅
LiveQueryServicein Rust with full change trackingparent_id,child_id,order)Phase 2: Event naming ✅
sync:*to specificnode:*andedge:*eventsnode:created,node:updated,node:deleted,edge:created,edge:updated,edge:deletedPhase 3: Reconnection logic ✅
sync:statusevents:connected,reconnecting,disconnectedPhase 4: Type-safe payloads ✅
NodeEventDataandEdgeEventDatainterfaces in both Rust and TypeScriptRecord<string, unknown>Phase 5: Code quality ✅
asynckeyword from non-async emit functions (Tauriemitis synchronous)bun run quality:fixRemaining Phases (6-8)
Phase 6: Integration tests ⏳
Phase 7: Manual testing ⏳
Phase 8: Performance testing ⏳
Technical Implementation Details
Files Modified:
packages/desktop-app/src-tauri/src/services/live_query_service.rs- Complete implementationpackages/desktop-app/src-tauri/src/services/mod.rs- Module exportspackages/desktop-app/src/lib/services/event-types.ts- Event type definitionspackages/desktop-app/src/lib/services/tauri-sync-listener.ts- Event handlersArchitecture:
Event Flow:
tauri-sync-listener.tsbridges to EventBusNext Session Focus
The next agent should focus on Phase 6: Integration Tests. The core implementation is solid and ready for comprehensive testing. Start with:
packages/desktop-app/src/tests/integration/live-select-polling.test.tsAcceptance Criteria Status
LiveQueryServicein Rust that subscribes to database changesnode:created,node:updated,node:deletededge:created,edge:updated,edge:deletedOverall Progress: 6/9 criteria complete (67%)
Branch:
feature/issue-551-surrealdb-live-selectCommit:
af79bd4Add comprehensive integration tests for polling-based real-time sync …
Implement SurrealDB LIVE SELECT for real-time node and edge updates (#…
WIP: Phase 1 Complete - Remove all before_sibling_id references
9 remaining items
Implement SurrealDB LIVE SELECT for real-time node and edge updates (#…
Implement ReactiveNodeData store with debounced content updates (#554) (
Create multi-client integration tests for LIVE SELECT (#590)
Remove dead workaround code from node-hierarchy.ts (#617)
Refactor tree loading to use efficient adjacency list strategy (#632)
Implement SurrealDB LIVE SELECT for real-time node and edge updates (#…
Implement ReactiveNodeData store with debounced content updates (#554) (
Create multi-client integration tests for LIVE SELECT (#590)
Remove dead workaround code from node-hierarchy.ts (#617)
Refactor tree loading to use efficient adjacency list strategy (#632)
Implement SurrealDB LIVE SELECT for real-time node and edge updates (#…
Implement ReactiveNodeData store with debounced content updates (#554) (
Create multi-client integration tests for LIVE SELECT (#590)
Remove dead workaround code from node-hierarchy.ts (#617)
Refactor tree loading to use efficient adjacency list strategy (#632)