Skip to content

Add Server-Sent Events (SSE) for Real-Time Sync in Browser Dev Mode #621

Closed

Description

@malibio

Overview

In browser dev mode (bun run dev:browser), external database changes (e.g., edits made via Surrealist GUI) are not reflected in the frontend UI. This is because LIVE SELECT events only work via Tauri IPC in desktop mode. Browser mode needs an alternative mechanism for real-time synchronization.

Problem Statement

Current Behavior:

  1. User types "Parent" in browser → Node saved to database ✅
  2. User edits content to "Parent A" via Surrealist GUI → Database updated ✅
  3. Frontend UI still shows "Parent" ❌ (no real-time update)

Root Cause:

  • ReactiveNodeData and ReactiveStructureTree subscribe to Tauri events (@tauri-apps/api/event)
  • In browser mode, there's no Tauri IPC - only HTTP calls to dev-proxy
  • External changes to the database don't trigger any frontend updates

Expected Behavior:

  • External database changes should trigger UI updates in browser mode
  • Same real-time sync experience as desktop mode (via different transport)

Proposed Solution

Implement Server-Sent Events (SSE) in the dev-proxy to broadcast database changes to browser clients.

Implementation Approach

Phase 1: Backend SSE Infrastructure

File to modify: packages/desktop-app/src-tauri/src/bin/dev-proxy.rs

  1. Add SSE endpoint /api/events:

    // Add to imports
    use axum::response::sse::{Event, Sse};
    use futures::stream::Stream;
    use tokio::sync::broadcast;
    
    // Add to AppState
    struct AppState {
        service: Arc<NodeService>,
        event_tx: broadcast::Sender<SseEvent>,
    }
    
    // SSE event types
    #[derive(Clone, Serialize)]
    #[serde(tag = "type", rename_all = "camelCase")]
    enum SseEvent {
        NodeCreated { node_id: String, node_data: Node },
        NodeUpdated { node_id: String, node_data: Node },
        NodeDeleted { node_id: String },
        EdgeCreated { parent_id: String, child_id: String },
        EdgeDeleted { parent_id: String, child_id: String },
    }
  2. Add SSE handler:

    async fn sse_handler(
        State(state): State<Arc<AppState>>,
    ) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
        let rx = state.event_tx.subscribe();
        let stream = BroadcastStream::new(rx)
            .filter_map(|result| async move {
                result.ok().map(|event| {
                    Ok(Event::default()
                        .json_data(event)
                        .unwrap())
                })
            });
        Sse::new(stream)
    }
  3. Broadcast events after each operation:

    • In create_node_handler: state.event_tx.send(SseEvent::NodeCreated { ... })
    • In update_node_handler: state.event_tx.send(SseEvent::NodeUpdated { ... })
    • In delete_node_handler: state.event_tx.send(SseEvent::NodeDeleted { ... })
    • In set_parent_handler: state.event_tx.send(SseEvent::EdgeCreated/Deleted { ... })

Phase 2: Frontend SSE Client

File to create: packages/desktop-app/src/lib/services/browser-sync-service.ts

/**
 * Browser Sync Service - SSE client for browser dev mode
 * 
 * Provides real-time sync via Server-Sent Events when running in browser mode.
 * Mirrors the Tauri event subscription pattern used by ReactiveNodeData.
 */

import { sharedNodeStore } from './shared-node-store';
import { structureTree } from '$lib/stores/reactive-structure-tree.svelte';

class BrowserSyncService {
  private eventSource: EventSource | null = null;
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectDelay = 1000;

  /**
   * Initialize SSE connection (browser mode only)
   */
  async initialize(): Promise<void> {
    // Only run in browser mode (not Tauri)
    if (typeof window !== 'undefined' && !window.__TAURI__) {
      this.connect();
    }
  }

  private connect(): void {
    const baseUrl = 'http://localhost:3001';
    this.eventSource = new EventSource(`${baseUrl}/api/events`);

    this.eventSource.onopen = () => {
      console.log('[BrowserSyncService] SSE connection established');
      this.reconnectAttempts = 0;
    };

    this.eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        this.handleEvent(data);
      } catch (error) {
        console.error('[BrowserSyncService] Failed to parse event:', error);
      }
    };

    this.eventSource.onerror = () => {
      console.warn('[BrowserSyncService] SSE connection error');
      this.eventSource?.close();
      this.scheduleReconnect();
    };
  }

  private handleEvent(event: SseEvent): void {
    console.log('[BrowserSyncService] Received event:', event.type);
    
    switch (event.type) {
      case 'nodeCreated':
        // Update shared store with new node
        sharedNodeStore.setNode(event.nodeData, { type: 'external' });
        break;
      case 'nodeUpdated':
        // Update existing node in store
        sharedNodeStore.updateNode(
          event.nodeId,
          event.nodeData,
          { type: 'external' }
        );
        break;
      case 'nodeDeleted':
        // Remove node from store
        sharedNodeStore.deleteNode(event.nodeId, { type: 'external' }, true);
        break;
      case 'edgeCreated':
        // Update structure tree
        structureTree.addChild(event.parentId, event.childId);
        break;
      case 'edgeDeleted':
        // Update structure tree
        structureTree.removeChild(event.parentId, event.childId);
        break;
    }
  }

  private scheduleReconnect(): void {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      const delay = this.reconnectDelay * this.reconnectAttempts;
      console.log(`[BrowserSyncService] Reconnecting in ${delay}ms...`);
      setTimeout(() => this.connect(), delay);
    } else {
      console.error('[BrowserSyncService] Max reconnect attempts reached');
    }
  }

  destroy(): void {
    this.eventSource?.close();
    this.eventSource = null;
  }
}

export const browserSyncService = new BrowserSyncService();

Phase 3: Integration

File to modify: packages/desktop-app/src/lib/components/layout/app-shell.svelte

Initialize the browser sync service on mount:

import { browserSyncService } from '$lib/services/browser-sync-service';
import { onMount, onDestroy } from 'svelte';

onMount(async () => {
  await browserSyncService.initialize();
});

onDestroy(() => {
  browserSyncService.destroy();
});

Acceptance Criteria

  • SSE endpoint /api/events added to dev-proxy
  • Events broadcast after create/update/delete node operations
  • Events broadcast after edge (parent-child) changes
  • Frontend EventSource client connects in browser mode only
  • External database changes (via Surrealist) reflected in UI within 1 second
  • Graceful reconnection on connection loss (up to 5 attempts)
  • No impact on Tauri desktop mode (conditional initialization)
  • Console logging for debugging sync events
  • Code passes bun run quality:fix
  • Tests pass (bun run test:all)

Technical Specifications

Reference Files

  • dev-proxy.rs: packages/desktop-app/src-tauri/src/bin/dev-proxy.rs - Add SSE endpoint and event broadcasting
  • ReactiveNodeData: packages/desktop-app/src/lib/stores/reactive-node-data.svelte.ts - Reference for event handling pattern
  • ReactiveStructureTree: packages/desktop-app/src/lib/stores/reactive-structure-tree.svelte.ts - Reference for structure updates
  • SharedNodeStore: packages/desktop-app/src/lib/services/shared-node-store.ts - Target for node updates
  • BackendAdapter: packages/desktop-app/src/lib/services/backend-adapter.ts - Reference for browser mode detection

Rust Dependencies to Add

# In Cargo.toml for dev-proxy
tokio-stream = "0.1"
futures = "0.3"

Event Type Definitions

// packages/desktop-app/src/lib/types/sse-events.ts
export interface SseEventBase {
  type: string;
}

export interface NodeCreatedEvent extends SseEventBase {
  type: 'nodeCreated';
  nodeId: string;
  nodeData: Node;
}

export interface NodeUpdatedEvent extends SseEventBase {
  type: 'nodeUpdated';
  nodeId: string;
  nodeData: Node;
}

export interface NodeDeletedEvent extends SseEventBase {
  type: 'nodeDeleted';
  nodeId: string;
}

export interface EdgeCreatedEvent extends SseEventBase {
  type: 'edgeCreated';
  parentId: string;
  childId: string;
}

export interface EdgeDeletedEvent extends SseEventBase {
  type: 'edgeDeleted';
  parentId: string;
  childId: string;
}

export type SseEvent = 
  | NodeCreatedEvent 
  | NodeUpdatedEvent 
  | NodeDeletedEvent 
  | EdgeCreatedEvent 
  | EdgeDeletedEvent;

Browser Mode Detection

// Check if running in Tauri (desktop) or browser mode
const isTauriMode = typeof window !== 'undefined' && !!window.__TAURI__;
const isBrowserMode = typeof window !== 'undefined' && !window.__TAURI__;

Testing Strategy

Manual Testing

  1. Start dev server: bun run dev:browser
  2. Open browser to http://localhost:5173
  3. Type some text in a node
  4. Open Surrealist and connect to ws://localhost:8000
  5. Modify the node content directly in database
  6. Verify UI updates automatically

Unit Tests

  • Test SSE event parsing
  • Test reconnection logic
  • Test event handler routing

Non-Goals

  • This issue does NOT implement SSE for Tauri desktop mode (Tauri IPC is already working)
  • This issue does NOT implement WebSocket (SSE is simpler for one-way server→client)
  • This issue does NOT implement LIVE SELECT in browser (requires SurrealDB WebSocket which is complex)

Related Issues

Metadata

Metadata

Assignees

Labels

backendenhancementfrontend

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions