Repository navigation
Closed
Description
Overview
Current childrenCache and parentsCache in SharedNodeStore require manual synchronization and don't react to external changes from MCP server operations. We need a reactive structure store that subscribes to LIVE SELECT edge events and maintains ordered children using fractional ordering.
Self-Contained Scope
- Reactive Svelte 5 store using
$statefor automatic UI updates - LIVE SELECT subscription to edge:created, edge:updated, edge:deleted events
- Binary search insertion to maintain sorted children by order
- Snapshot/restore capability for optimistic operations with rollback
- Complete replacement for manual cache management
Implementation Approach
- Store Structure: Map of parentId → sorted ChildInfo[] array
- Event Subscriptions: Listen to Tauri events from LIVE SELECT
- Sorted Insertion: Binary search to keep children ordered
- Reactivity: Use Svelte 5 $state for automatic updates
- Testing: Verify reactivity and multi-client sync
Acceptance Criteria
- Create
src/lib/stores/reactive-structure-tree.svelte.ts - Implement
$stateMap:parentId → ChildInfo[](sorted by order) - Subscribe to Tauri events:
edge:created,edge:updated,edge:deleted - Implement
getChildren(parentId): string[](reactive, returns sorted IDs) - Implement binary search insertion to keep children sorted
- Implement
snapshot()andrestore()for optimistic rollback - Initialize with bulk load from backend on startup
- All hierarchy rendering tests pass with new store
- Memory: 45% reduction vs current implementation (110KB vs 200KB for 100 nodes)
Technical Implementation Notes
Complete Implementation
File: packages/desktop-app/src/lib/stores/reactive-structure-tree.svelte.ts
import { listen } from '@tauri-apps/api/event';
import type { UnlistenFn } from '@tauri-apps/api/event';
import type { HasChildEdge } from '$lib/types/events';
import { tauriNodeService } from '$lib/services/tauri-node-service';
interface ChildInfo {
nodeId: string;
order: number;
}
class ReactiveStructureTree {
// Reactive map using Svelte 5 $state
private children = $state(new Map<string, ChildInfo[]>());
private unlisteners: UnlistenFn[] = [];
private initialized = false;
async initialize() {
if (this.initialized) return;
console.log('[ReactiveStructureTree] Initializing...');
try {
// Step 1: Initial bulk load from backend
const initialEdges = await tauriNodeService.getAllEdges();
this.buildTree(initialEdges);
console.log(`[ReactiveStructureTree] Loaded ${initialEdges.length} edges`);
// Step 2: Subscribe to LIVE SELECT structure events
await this.subscribeToEvents();
this.initialized = true;
console.log('[ReactiveStructureTree] Initialization complete');
} catch (error) {
console.error('[ReactiveStructureTree] Initialization failed:', error);
throw error;
}
}
private async subscribeToEvents() {
// Edge created event
const unlistenCreated = await listen<HasChildEdge>('edge:created', (event) => {
console.log('[ReactiveStructureTree] Edge created:', event.payload);
this.addChild(event.payload);
});
this.unlisteners.push(unlistenCreated);
// Edge deleted event
const unlistenDeleted = await listen<HasChildEdge>('edge:deleted', (event) => {
console.log('[ReactiveStructureTree] Edge deleted:', event.payload);
this.removeChild(event.payload);
});
this.unlisteners.push(unlistenDeleted);
// Edge updated event (for order changes during rebalancing)
const unlistenUpdated = await listen<HasChildEdge>('edge:updated', (event) => {
console.log('[ReactiveStructureTree] Edge updated:', event.payload);
this.updateChildOrder(event.payload);
});
this.unlisteners.push(unlistenUpdated);
}
/**
* Get ordered child IDs for a parent (reactive)
* This is the main public API that components use
*/
getChildren(parentId: string): string[] {
const childInfos = this.children.get(parentId) || [];
// Children are already sorted on insertion
return childInfos.map(c => c.nodeId);
}
/**
* Get child info with order (for internal use)
*/
getChildrenWithOrder(parentId: string): ChildInfo[] {
return this.children.get(parentId) || [];
}
/**
* Check if a node has children (reactive)
*/
hasChildren(parentId: string): boolean {
const children = this.children.get(parentId);
return children ? children.length > 0 : false;
}
/**
* Get parent of a node by searching all edges
* Note: This is O(n) - consider adding reverse map if performance issue
*/
getParent(nodeId: string): string | null {
for (const [parentId, children] of this.children) {
if (children.some(c => c.nodeId === nodeId)) {
return parentId;
}
}
return null;
}
/**
* Build initial tree from bulk edge data
*/
private buildTree(edges: HasChildEdge[]) {
const tree = new Map<string, ChildInfo[]>();
for (const edge of edges) {
if (!tree.has(edge.in)) {
tree.set(edge.in, []);
}
tree.get(edge.in)!.push({
nodeId: edge.out,
order: edge.order
});
}
// Sort all children arrays by order
for (const [parentId, children] of tree) {
children.sort((a, b) => a.order - b.order);
tree.set(parentId, children);
}
this.children = tree;
}
/**
* Add a child with binary search insertion to maintain sort
*/
private addChild(edge: HasChildEdge) {
const children = this.children.get(edge.in) || [];
// Binary search to find insertion position
const insertIndex = this.findInsertPosition(children, edge.order);
// Insert at correct position to maintain sort
const newChild: ChildInfo = {
nodeId: edge.out,
order: edge.order
};
children.splice(insertIndex, 0, newChild);
this.children.set(edge.in, children);
}
/**
* Remove a child from parent's children
*/
private removeChild(edge: HasChildEdge) {
const children = this.children.get(edge.in) || [];
const filtered = children.filter(c => c.nodeId !== edge.out);
if (filtered.length === 0) {
this.children.delete(edge.in);
} else {
this.children.set(edge.in, filtered);
}
}
/**
* Update child order (rare - only during rebalancing)
*/
private updateChildOrder(edge: HasChildEdge) {
// Remove and re-add to update order
this.removeChild(edge);
this.addChild(edge);
}
/**
* Binary search to find insertion position
*/
private findInsertPosition(children: ChildInfo[], order: number): number {
let left = 0;
let right = children.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (children[mid].order < order) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
/**
* Take snapshot for optimistic rollback
*/
snapshot(): Map<string, ChildInfo[]> {
// Deep copy the map
const snapshot = new Map<string, ChildInfo[]>();
for (const [parentId, children] of this.children) {
snapshot.set(parentId, [...children]);
}
return snapshot;
}
/**
* Restore from snapshot (rollback on error)
*/
restore(snapshot: Map<string, ChildInfo[]>) {
this.children = snapshot;
}
/**
* Optimistically move a node (for instant UI update)
*/
moveNode(nodeId: string, newParentId: string, afterSiblingId?: string) {
// Remove from old parent
const oldParent = this.getParent(nodeId);
if (oldParent) {
const oldChildren = this.children.get(oldParent) || [];
const filtered = oldChildren.filter(c => c.nodeId !== nodeId);
this.children.set(oldParent, filtered);
}
// Add to new parent
const newChildren = this.children.get(newParentId) || [];
// Calculate order based on position
let order: number;
if (!afterSiblingId) {
// Insert at beginning
order = newChildren[0]?.order - 1 || 1.0;
} else {
// Insert after specific sibling
const siblingIndex = newChildren.findIndex(c => c.nodeId === afterSiblingId);
if (siblingIndex === -1) {
order = newChildren[newChildren.length - 1]?.order + 1 || 1.0;
} else {
const prev = newChildren[siblingIndex].order;
const next = newChildren[siblingIndex + 1]?.order;
order = next ? (prev + next) / 2 : prev + 1;
}
}
this.addChild({
id: `temp-edge-${nodeId}`,
in: newParentId,
out: nodeId,
order
});
}
/**
* Cleanup event listeners
*/
async destroy() {
for (const unlisten of this.unlisteners) {
unlisten();
}
this.unlisteners = [];
this.initialized = false;
}
}
// Export singleton instance
export const structureTree = new ReactiveStructureTree();
// Auto-initialize on module load
if (typeof window !== 'undefined') {
structureTree.initialize().catch(console.error);
}Testing the Store
File: packages/desktop-app/src/tests/unit/reactive-structure-tree.test.ts
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { structureTree } from '$lib/stores/reactive-structure-tree.svelte';
import { mockTauriEvent } from '../test-utils';
describe('ReactiveStructureTree', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(async () => {
await structureTree.destroy();
});
describe('getChildren', () => {
it('should return sorted child IDs', async () => {
// Simulate initial edges
await structureTree.initialize();
// Simulate edge:created events
await mockTauriEvent('edge:created', {
id: 'edge1',
in: 'parent1',
out: 'child1',
order: 2.0
});
await mockTauriEvent('edge:created', {
id: 'edge2',
in: 'parent1',
out: 'child2',
order: 1.0
});
await mockTauriEvent('edge:created', {
id: 'edge3',
in: 'parent1',
out: 'child3',
order: 3.0
});
// Children should be sorted by order
const children = structureTree.getChildren('parent1');
expect(children).toEqual(['child2', 'child1', 'child3']);
});
});
describe('snapshot and restore', () => {
it('should rollback on error', async () => {
await structureTree.initialize();
// Add some children
await mockTauriEvent('edge:created', {
id: 'edge1',
in: 'parent1',
out: 'child1',
order: 1.0
});
// Take snapshot
const snapshot = structureTree.snapshot();
// Make changes
await mockTauriEvent('edge:created', {
id: 'edge2',
in: 'parent1',
out: 'child2',
order: 2.0
});
expect(structureTree.getChildren('parent1')).toHaveLength(2);
// Rollback
structureTree.restore(snapshot);
expect(structureTree.getChildren('parent1')).toHaveLength(1);
expect(structureTree.getChildren('parent1')[0]).toBe('child1');
});
});
describe('binary search insertion', () => {
it('should maintain sorted order with rapid insertions', async () => {
await structureTree.initialize();
// Rapid insertions with random orders
const orders = [5.0, 1.0, 3.0, 7.0, 2.0, 6.0, 4.0];
for (let i = 0; i < orders.length; i++) {
await mockTauriEvent('edge:created', {
id: `edge${i}`,
in: 'parent1',
out: `child${i}`,
order: orders[i]
});
}
// Verify children are sorted
const children = structureTree.getChildrenWithOrder('parent1');
for (let i = 1; i < children.length; i++) {
expect(children[i].order).toBeGreaterThan(children[i - 1].order);
}
});
});
});Resources & References
- LIVE SELECT Events: Issue Implement SurrealDB LIVE SELECT for real-time node and edge updates #551 implementation
- Current Cache:
packages/desktop-app/src/lib/services/shared-node-store.tslines 101-106 - Svelte 5 Reactivity: Use
$statefor automatic updates - Binary Search: Standard algorithm for O(log n) insertion
Dependencies
- Implement SurrealDB LIVE SELECT for real-time node and edge updates #551 (LIVE SELECT must emit edge events)
- Migrate database schema to use fractional ordering instead of beforeSiblingId linked-list #550 (fractional ordering for edge.order field)
Related Issues
- Refactor BaseNodeViewer to use dual reactive stores #555 (ReactiveNodeData - companion data store)
- Simplify indent/outdent operations with atomic moveNode #556 (BaseNodeViewer will use this store)
- Create multi-client integration tests for LIVE SELECT #559 (Delete manual cache after this)
Definition of Done
- ReactiveStructureTree store created and working
- LIVE SELECT events update structure automatically
- Children always returned in sorted order
- Snapshot/restore working for rollback
- Memory usage reduced by 45%
- All hierarchy tests passing
- No manual cache synchronization needed
Activity
Implement ReactiveStructureTree store with LIVE SELECT integration (#553
Create ReactiveStructureTree store with LIVE SELECT integration (#566)
Implement ReactiveNodeData store with debounced content updates (#554)
Implement ReactiveNodeData store with debounced content updates (#554) (
Create comprehensive multi-client integration tests for LIVE SELECT s…
Create multi-client integration tests for LIVE SELECT (#590)
Remove dead workaround code from node-hierarchy.ts
Remove dead workaround code from node-hierarchy.ts (#617)
Remove dead workaround code from node-hierarchy.ts (#617)
Refactor tree loading to use efficient adjacency list strategy (#632)
Create ReactiveStructureTree store with LIVE SELECT integration (#566)
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)
Create ReactiveStructureTree store with LIVE SELECT integration (#566)
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)
Create ReactiveStructureTree store with LIVE SELECT integration (#566)
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)