Repository navigation
Description
Problem Statement
The current node service architecture is single-viewer oriented, with ReactiveNodeService maintaining a single global view context via setViewParentId(). This prevents multiple tabs or panes from displaying different node collections simultaneously, which is essential for:
- Multi-tab navigation (e.g., Today's date + Project notes + Search results)
- Split-pane editing (e.g., Side-by-side project planning and task tracking)
- Cross-referencing workflows (e.g., Viewing multiple linked documents simultaneously)
Current Limitations
// BaseNodeViewer currently sets GLOBAL view context
nodeManager.setViewParentId(parentId); // ❌ Only ONE viewer can be activeConsequences:
- ❌ Multiple
BaseNodeViewerinstances conflict and override each other's view - ❌ Opening a new tab changes what's visible in existing tabs
- ❌ No way to have independent expand/collapse state per viewer
- ❌ Focus management becomes ambiguous with multiple viewers
Real-Time Synchronization Requirements
Multi-Source Updates:
- Cross-tab updates - Editing node in Tab 1 must reflect live in Tab 2/3 if viewing same node
- MCP server updates - External AI agents modifying nodes via MCP must sync to all open viewers
- Concurrent editing - Multiple viewers/sources editing same node simultaneously
Proposed Solution: Hybrid Shared Store Architecture
Refactor the service layer to support multiple independent viewer instances with real-time synchronization across all viewers and external sources (MCP server).
This issue focuses on the architectural foundation (Phases 1-3). UI components for tab/pane management are tracked in issue #198.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ Tab/Pane Manager │
│ (Implemented in #198) │
└─────────────────────────────────────────────────────────────┘
│
┌────────────────┼────────────────┐
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Tab 1 Viewer │ │ Tab 2 Viewer │ │ Tab 3 Viewer │
│ (UI State) │ │ (UI State) │ │ (UI State) │
└───────────────┘ └───────────────┘ └───────────────┘
│ │ │
└────────────────┼────────────────┘
▼
┌─────────────────────┐
│ Shared Node Store │◄────┐
│ (THIS ISSUE #197) │ │
│ Single Source of │ │
│ Truth for Data │ │
└─────────────────────┘ │
│ │
▼ │
┌─────────────────────┐ │
│ Database Service │ │
│ (Persistence) │ │
└─────────────────────┘ │
▲ │
│ │
┌──────────┴──────────┐ │
│ MCP Server │─────┘
│ (External Updates)│
└─────────────────────┘
Key Design Decisions
-
Shared Node Data Store (singleton)
- Single source of truth for all node data
- Reactive using Svelte 5
$state - Receives updates from: local edits, database, MCP server
- Broadcasts changes to all subscribed viewers
-
Per-Viewer UI State (instanced)
- Expand/collapse state
- Scroll position
- Focus management
- Selection state
-
Synchronization Layer
- Event bus for change notifications with source tracking
- Optimistic updates with conflict resolution
- Last-Write-Wins conflict resolution (simple, upgradable)
Benefits
✅ Clean isolation - Each viewer UI state is independent
✅ Real-time sync - Changes appear immediately across all viewers
✅ Multi-source support - Local edits, database, and MCP updates coordinated
✅ Memory efficient - Single data store, multiple lightweight UI states
✅ Consistency maintained - Database writes remain serialized and coordinated
✅ Extensible - Easy to add new viewer types (search results, graphs, etc.)
Implementation Tasks
Phase 1: Shared Node Store Foundation
- Create
SharedNodeStoreas singleton reactive store using Svelte 5$state - Migrate node data from
ReactiveNodeServiceinstances to shared store - Implement reactive subscriptions for viewers (observer pattern)
- Add change notification system with source tracking
- Remove any singleton patterns that prevent multiple viewer instances
Phase 2: Multi-Source Update Handling
- Design update protocol for local edits, database, and MCP sources
- Implement optimistic update strategy with rollback
- Add conflict detection for concurrent edits to same node
- Create update queue with source tracking and timestamps
- Implement Last-Write-Wins conflict resolution (Phase 1, simple)
Phase 3: MCP Server Integration (Architecture)
- Add MCP server event listener interface for node updates
- Route MCP updates through shared store to all viewers
- Implement update batching for performance (collect 50-100ms)
- Add validation and permission checks for external updates
- Handle offline/reconnection scenarios
- Note: Test with simulated MCP events until Add MCP stdio server for AI agent access #112 is complete
Acceptance Criteria
Architectural Foundation:
-
SharedNodeStorestores all node data reactively - Multiple
ReactiveNodeServiceinstances can read from shared store - Each viewer maintains independent UI state (expand/collapse, scroll, focus)
- All existing tests still pass (backward compatibility maintained)
Real-Time Synchronization:
- Editing node in viewer 1 updates immediately in viewer 2 (if viewing same node)
- Updates propagate across viewers within 50ms (local edits)
- MCP server updates routed through shared store (tested with simulated events)
- Conflicting concurrent edits are detected and resolved (Last-Write-Wins)
- No data loss during conflict resolution
- Visual feedback when node updates from external source
Database Coordination:
- Database writes from multiple viewers don't cause conflicts
- Optimistic UI updates with rollback on conflict
- Concurrent edits to same node handled gracefully
- Existing
queueDatabaseWrite()coordination preserved
Performance:
- Update propagation: <50ms (local edits)
- Multi-viewer sync: <100ms (cross-viewer)
- No memory leaks with 3+ viewer instances
- Performance remains smooth with high-frequency updates (10+ updates/sec)
Technical Notes
Current Service Architecture
// node-service-context.svelte (already supports instancing)
NodeServiceContext → {
ReactiveNodeService (node manager),
HierarchyService,
NodeOperationsService,
NodeReferenceService,
TauriNodeService (shared),
ContentProcessor
}Already instance-friendly:
- Services created per
NodeServiceContextmount - No global singletons except database service (intentionally shared)
Needs refactoring:
- Move node data from
ReactiveNodeServiceto sharedSharedNodeStore - Convert
ReactiveNodeServiceto UI-state-only (expand/collapse, scroll, focus) - Add source tracking to event bus
- Implement conflict detection and resolution
Database Write Coordination
// Already implemented in base-node-viewer.svelte
queueDatabaseWrite(() => databaseService.updateNode(...))✅ This existing pattern already handles serialization
✅ Multiple viewers can safely queue writes
Event Bus Enhancement
// Current: Simple pub/sub
eventBus.emit({ type: 'node:updated', nodeId, ... });
// Enhanced: Source tracking and update protocol
eventBus.emit({
type: 'node:updated',
nodeId,
source: 'mcp-server' | 'viewer-tab1' | 'database',
updateType: 'content' | 'metadata' | 'hierarchy',
timestamp: Date.now(),
conflictResolution: 'auto' | 'manual-required'
});Shared Store API Design
class SharedNodeStore {
// Reactive state (Svelte 5)
private nodes = $state(new Map<string, Node>());
// Subscribe to node changes
subscribe(nodeId: string, callback: (node: Node) => void): Unsubscribe;
// Update with source tracking
updateNode(nodeId: string, changes: Partial<Node>, source: UpdateSource);
// Conflict detection
detectConflicts(nodeId: string, incomingUpdate: Update): Conflict | null;
// Batch updates for performance
batchUpdate(updates: Array<{ nodeId: string; changes: Partial<Node> }>);
// Pluggable conflict resolution (upgradable to OT/CRDT later)
private conflictResolver: ConflictResolver = new LastWriteWinsResolver();
setConflictResolver(resolver: ConflictResolver);
}Conflict Resolution Strategy
Phase 1: Last-Write-Wins (Simple)
// Update always wins, notify user of overwrite
if (localEdit.timestamp < externalUpdate.timestamp) {
showNotification("Node updated by external source");
applyUpdate(externalUpdate);
}Future Upgrades (Issue #198 or beyond):
- Field-level merging for non-conflicting changes
- Operational Transformation (OT) for text merging
- CRDT (Conflict-free Replicated Data Types)
Migration Strategy
Gradual Migration (No Breaking Changes):
// Phase 1: Keep ReactiveNodeService working, add SharedNodeStore
class ReactiveNodeService {
constructor(private sharedStore: SharedNodeStore) {}
// Old API still works (adapter pattern)
setViewParentId(parentId: string | null) {
this.viewParentId = parentId;
}
get visibleNodes() {
// Read from shared store, filter by viewParentId
return this.sharedStore.getNodesForParent(this.viewParentId);
}
}Testing Strategy
Test-Driven Development:
tests/services/
shared-node-store.test.ts # Core store operations
multi-viewer-sync.test.ts # Cross-viewer updates
conflict-resolution.test.ts # Concurrent edit handling
mcp-integration.test.ts # Simulated MCP events
Priority test scenarios:
- ✅ SharedNodeStore basic CRUD operations
- ✅ Multi-viewer subscription (two viewers see same node update)
- ✅ Conflict detection (concurrent edits to same node)
- ✅ Last-Write-Wins resolution
- ✅ Database write coordination (no conflicts)
- ✅ MCP event handling (simulated events)
Technical Challenges
Challenge 1: Cursor Preservation
- External updates may change text length
- Need to track cursor position semantically (not by index)
- Solution for Refactor Node Service Architecture for Multi-Tab Support (Phases 1-3: Foundation) #197: Accept that cursor may jump; refined solution in Implement Topic Node Embeddings with Adaptive Chunking #198
Challenge 2: Update Frequency
- MCP server + multiple viewers = high update rate
- Solutions: Debounce (50-100ms), incremental DOM updates
Challenge 3: Memory Consistency
- Shared store must be source of truth
- Solutions: Immutable data structures, copy-on-write, clear ownership model
File Structure
packages/desktop-app/src/lib/services/
shared-node-store.svelte.ts # NEW - Core singleton store
reactive-node-service.svelte.ts # MODIFY - Adapt to use shared store
node-service-context.svelte # MODIFY - Initialize shared store
packages/desktop-app/src/tests/services/
shared-node-store.test.ts # NEW
multi-viewer-sync.test.ts # NEW
conflict-resolution.test.ts # NEW
mcp-integration.test.ts # NEW
Related Issues
- Add MCP stdio server for AI agent access #112 - Add MCP stdio server for AI agent access (MCP server implementation)
- Implement reactive state synchronization #111 - Implement reactive state synchronization (related to multi-viewer consistency)
- Implement Topic Node Embeddings with Adaptive Chunking #198 - Tab/Pane Management UI (Phases 4-8, depends on this issue)
Blocks
- Implement Topic Node Embeddings with Adaptive Chunking #198 - Tab/Pane Management UI (requires shared store foundation from this issue)
Priority
Foundation - Critical architectural change that enables:
- Multi-tab/pane navigation
- Real-time collaboration features
- AI agent integration via MCP
- Advanced UX patterns (split views, search results, etc.)
Estimated Complexity
Medium-High (Phases 1-3 only, scoped down from original)
- Services already support instancing (good foundation)
- Database coordination already in place
- Main work: Shared store, multi-source sync, conflict resolution
- Testing with simulated MCP events (no dependency on Add MCP stdio server for AI agent access #112)
Activity
Phase 1: Implement SharedNodeStore foundation with conflict resolution
Phase 1.2: Refactor ReactiveNodeService to adapter pattern
Complete Phase 3: MCP-Ready Integration with Simulated Tests
[-]Refactor Node Service Architecture for Multi-Tab/Pane Support[/-][+]Refactor Node Service Architecture for Multi-Tab Support (Phases 1-3: Foundation)[/+]Refactor Node Service Architecture for Multi-Tab/Pane Support (#205)
Refactor Node Service Architecture for Multi-Tab/Pane Support (#205)
Refactor Node Service Architecture for Multi-Tab/Pane Support (#205)
Refactor Node Service Architecture for Multi-Tab/Pane Support (#205)