Skip to content

Refactor UpdateSource type system for clarity and correctness #393

Closed

Description

@malibio

Problem

The UpdateSource type in packages/desktop-app/src/lib/types/update-protocol.ts conflates two orthogonal concerns:

  1. Data provenance - Where did this update originate? (viewer, backend, MCP)
  2. Persistence control - Should this update be written to the database?

Current type definition:

type UpdateSource =
  | { type: 'viewer'; viewerId: string }
  | { type: 'database'; reason: string }      // Dual meaning!
  | { type: 'mcp-server'; serverId?: string }
  | { type: 'external'; source: string; description?: string };

Critical Issues:

  1. Implicit side effects: source.type === 'database' marks nodes as persisted (line 556)
  2. Confusing control flow: source.type !== 'database' guards persistence operations (lines 341, 570, 728)
  3. Workarounds needed: Services use type: 'external' to force persistence (navigation-service:92, reactive-node-service:781)
  4. Poor discoverability: Developers don't understand persistence semantics from type names

Architecture Assessment

Root Cause: The type system is being misused for control flow instead of data classification. The actual persistence state is already tracked in the persistedNodeIds Set, but the type system creates a second, implicit mechanism.

Impact Analysis:

  • 18+ locations check source.type for persistence decisions
  • 2 known workarounds using type: 'external'
  • Future MCP integration (Phase 3) will compound confusion

Recommended Solution

Option C: Minimal Refactor with Explicit Persistence API

1. Clarify UpdateSource Semantics

/**
 * UpdateSource - Tracks the origin of node data for debugging and conflict resolution
 * 
 * CRITICAL: This type is ONLY for provenance tracking. It does NOT control persistence.
 * Persistence is managed separately via UpdateOptions.persist and persistedNodeIds Set.
 */
type UpdateSource =
  | { type: 'user-interaction'; viewerId: string; userId?: string }
  | { type: 'backend-load'; reason: 'initialization' | 'fetch' | 'sync' }
  | { type: 'mcp-sync'; serverId?: string; agentId?: string };

Changes from current:

  • 'viewer' → 'user-interaction' (clearer intent)
  • 'database' → 'backend-load' (no side effect implication)
  • 'mcp-server' → 'mcp-sync' (consistent naming)
  • 'external' → REMOVED (redundant, replaced by explicit options)

2. Add Explicit Persistence Control

interface UpdateOptions {
  // ... existing options ...
  
  /**
   * Explicit persistence control (replaces implicit source.type checks)
   * 
   * - undefined (default): Auto-decide based on source and content
   *   - backend-load: never persist (already in DB)
   *   - user-interaction: persist structural changes immediately, debounce content
   *   - mcp-sync: persist immediately
   * 
   * - true/'immediate': Force immediate persistence (replaces 'external' workaround)
   * - false: Skip persistence (temporary UI state, placeholders)
   * - 'debounced': Wait for typing pause before persisting
   */
  persist?: boolean | 'debounced' | 'immediate';
  
  /**
   * If true, mark node as persisted without writing to DB
   * Use when loading from backend to populate persistedNodeIds Set
   */
  markAsPersistedOnly?: boolean;
}

3. Refactor SharedNodeStore Persistence Logic

// Replace implicit checks:
// OLD: if (source.type !== 'database') { persist... }

// NEW: Explicit decision
private shouldAutoPersist(source: UpdateSource, changes: Partial<Node>): boolean {
  if (source.type === 'backend-load') return false; // Already in DB
  if (source.type === 'mcp-sync') return true; // External changes persist immediately
  
  // User interactions: structural changes immediate, content debounced via PersistenceCoordinator
  const isStructural = 'parentId' in changes || 'beforeSiblingId' in changes;
  return isStructural || 'nodeType' in changes || 'properties' in changes;
}

// In updateNode/setNode:
const shouldPersist = options.persist ?? this.shouldAutoPersist(source, changes);
if (shouldPersist && !isPlaceholder) {
  // Delegate to PersistenceCoordinator...
}

// Mark as persisted when loading from backend
if (options.markAsPersistedOnly || source.type === 'backend-load') {
  this.persistedNodeIds.add(nodeId);
}

Implementation Plan

Phase 1: Add Explicit API (Non-Breaking)

  • Add options.persist to UpdateOptions
  • Add shouldAutoPersist() helper method
  • Add markAsPersistedOnly option
  • Keep old behavior as fallback
  • Estimated effort: 2-4 hours

Phase 2: Migrate Internal Callers

  • Update SharedNodeStore to use explicit persistence
  • Fix navigation-service workaround (use persist: 'immediate')
  • Fix reactive-node-service workaround (use persist: 'immediate')
  • Estimated effort: 4-6 hours

Phase 3: Update Source Types

  • Rename source types ('database' → 'backend-load', etc.)
  • Update all call sites (grep shows ~20 locations)
  • Update tests to use new types
  • Estimated effort: 3-5 hours

Phase 4: Remove 'external' Type

  • Remove from type definition
  • Verify no usage remains (should be replaced by explicit options.persist)
  • Update documentation
  • Estimated effort: 1-2 hours

Phase 5: Documentation & Tests

  • Document new persistence semantics
  • Add tests for explicit persistence control
  • Update architecture docs
  • Estimated effort: 2-3 hours

Total estimated effort: 12-20 hours

Acceptance Criteria

  • UpdateSource types have clear, single-responsibility semantics
  • options.persist provides explicit persistence control
  • No more source.type checks for persistence decisions
  • All workarounds removed (navigation-service, reactive-node-service)
  • 'external' type removed from codebase
  • Existing functionality preserved (all tests pass)
  • New tests for explicit persistence API
  • Documentation updated with new patterns
  • Migration validated with integration tests

Files to Change

Core Implementation

  • packages/desktop-app/src/lib/types/update-protocol.ts - Type definitions
  • packages/desktop-app/src/lib/services/shared-node-store.ts - Persistence logic (lines 341, 556, 570, 728)

Workaround Fixes

  • packages/desktop-app/src/lib/services/navigation-service.ts - Line 92 (remove 'external' usage)
  • packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts - Line 781 (remove 'external' usage)

Test Updates

  • packages/desktop-app/src/tests/services/shared-node-store.test.ts
  • packages/desktop-app/src/tests/services/mcp-integration.test.ts
  • packages/desktop-app/src/tests/services/node-type-conflict-detection.test.ts
  • packages/desktop-app/src/tests/integration/node-type-persistence.test.ts

Related Issues

Priority

Medium-High - Current workarounds are fragile and will cause maintenance issues as MCP integration progresses. The implicit side effects make the codebase harder to reason about.

Activity

  1. self-assigned this
    on Nov 5, 2025
  2. malibio commented on Nov 5, 2025

    @malibio
    CollaboratorAuthor

    Test Baseline (Before Refactor)

    Frontend Tests: ✅ 1486 passed | 48 skipped (1534 total)
    Rust Tests: ✅ All passing

    Starting implementation of UpdateSource type system refactor (Option C: Explicit Persistence API).

    Test Command Used: bun run test:all
    Timestamp: 2025-11-05 11:49:08

    Will verify no new test failures when creating PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions