Skip to content

Fix: Node type conversions persist as text nodes with truncated content #424

Closed

Description

@malibio

Overview

Node type conversions (via slash commands or pattern detection) display correctly in the UI but persist to the database as text nodes with incomplete content, causing data corruption and loss of user work.

Problem Statement

User Experience:

  1. User creates placeholder node (press Enter)
  2. User converts to task via slash command /task OR types task pattern [ ]
  3. UI immediately shows task node (blue dot icon) ✅
  4. User types content "Buy groceries"
  5. After 500ms debounce, node persists to database
  6. Database shows: node_type = "text", content = "[ ] " (truncated) ❌
  7. Page reload → Node appears as text, user work is lost

Database Evidence:

-- Node that should be a task
id: ab4b8104-db51-4e69-b2e4-9f0704bc71ae
node_type: "text"                    ❌ Should be "task"
content: "[ ] "                      ❌ Should be "[ ] Buy groceries"
properties: {"_schema_version":1}    ❌ Missing task.status, task.priority

Backend Logs:

UPDATE node: ab4b8104...
  node_type: None              ❌ Missing
  content: Some("[ ] ")        ❌ Truncated
  properties: None             ❌ Missing

Root Cause

Issue 1: NodeType Not Included in Content Updates

When updateNodeContent() is called, it only sends { content } without nodeType:

// reactive-node-service.svelte.ts:617
function updateNodeContent(nodeId: string, content: string): void {
  const node = sharedNodeStore.getNode(nodeId);
  if (!node) return;

  // ❌ BUG: Only sends content, missing nodeType
  sharedNodeStore.updateNode(nodeId, { content }, viewerSource);
}

Why this exists:
Comment on line 612 says "DON'T include nodeType - it prevents pattern-based conversions"

The conflict:

  • Pattern conversions: nodeType updates come via SEPARATE event → including it causes stale overwrites
  • Slash commands: nodeType updates happen FIRST → content updates LATER → nodeType must be preserved

Current code handles pattern conversions but breaks slash commands.

Issue 2: Content Truncation (Needs Investigation)

The content "[ ] Buy groceries" is being truncated to just "[ ] " when persisted. This suggests either:

  • Pattern detection is stripping the content after conversion
  • Debounce is firing too early (before full content is entered)
  • Multiple updates are racing and early one wins

Why Tests Didn't Catch This

Current Test Pattern (Doesn't Match Reality)

All existing tests call updateNode() with BOTH fields together:

// node-type-persistence.test.ts:104-112
store.updateNode(textNode.id, {
  content: '## Hello',     // ← Both together
  nodeType: 'header'       // ← Single call
}, viewerSource);

This is NOT how the real code works!

Actual User Flow (What Tests Should Do)

// Step 1: Slash command OR pattern detection
reactiveNodeService.updateNodeType(nodeId, 'task');  // ← Separate call

// Step 2: User types content (separate event)
reactiveNodeService.updateNodeContent(nodeId, 'Buy groceries');  // ← Separate call

// Step 3: Debounce fires (500ms later)
// ❌ BUG: Only { content } sent, nodeType lost!

Why This Keeps Regressing

Contributing factors:

  1. ❌ No integration test simulating separate updateNodeType/updateNodeContent calls
  2. ❌ Tests don't verify actual database persistence (use test mode)
  3. ❌ Two competing requirements (pattern vs slash) not clearly separated
  4. ❌ No documentation explaining the two conversion flows
  5. ❌ Complex async coordination (debounce + persistence) hard to test

Historical fixes (all regressed):

  • Commit ad7d804: "Apply schema defaults + prevent pattern reversion"
  • Commit c609ce1: "Include nodeType in content updates" → REVERTED in same PR

Solution

Proposal: Track Conversion Source

Add explicit tracking to distinguish pattern conversions from slash commands:

// ReactiveNodeService state
private nodeTypeConversionSource = new Map<string, 'pattern' | 'slash-command'>();

function updateNodeType(nodeId: string, nodeType: string): void {
  // Mark this as slash-command conversion
  this.nodeTypeConversionSource.set(nodeId, 'slash-command');

  sharedNodeStore.updateNode(nodeId, { nodeType, content: node.content }, viewerSource);
}

function updateNodeContent(nodeId: string, content: string): void {
  const node = sharedNodeStore.getNode(nodeId);
  if (!node) return;

  const conversionSource = this.nodeTypeConversionSource.get(nodeId);

  // Include nodeType if it was set via slash command
  const update = conversionSource === 'slash-command'
    ? { content, nodeType: node.nodeType }  // ← Preserve slash type
    : { content };                          // ← Pattern handles separately

  sharedNodeStore.updateNode(nodeId, update, viewerSource);

  // Clear tracking after persistence
  if (conversionSource === 'slash-command' && content.trim() !== '') {
    this.nodeTypeConversionSource.delete(nodeId);
  }
}

// Pattern conversion handler
function handlePatternConversion(nodeId: string, detectedType: string): void {
  this.nodeTypeConversionSource.set(nodeId, 'pattern');
  // Pattern system already handles nodeType separately
}

Benefits:

  • ✅ Fixes slash command persistence
  • ✅ Doesn't break pattern conversions
  • ✅ Clear separation of concerns
  • ✅ Self-documenting code

Implementation Tasks

Phase 1: Add Missing Test Coverage (Test-First)

Create file: packages/desktop-app/src/tests/integration/slash-command-type-persistence.test.ts

Required tests:

  • Placeholder → task via slash command → add content → persists as task
  • Placeholder → header via slash command → add content → persists as header
  • Pattern detection (type "[ ] ") → add content → persists as task
  • Pattern detection (type "## ") → add content → persists as header
  • Verify full content persists (not truncated to pattern only)
  • Verify schema defaults applied (task.status, task.priority, etc.)
  • Test with database mode (shouldUseDatabase())

Critical test requirements:

// ✅ MUST simulate real flow (separate calls)
reactiveNodeService.updateNodeType(nodeId, 'task');
await sleep(50);  // Simulate user thinking
reactiveNodeService.updateNodeContent(nodeId, 'Buy milk');
await sleep(600);  // Wait for debounce
const persisted = await backend.getNode(nodeId);
expect(persisted.nodeType).toBe('task');  // ← Currently fails
expect(persisted.content).toBe('Buy milk');  // ← Currently truncated

// ❌ WRONG (current tests)
store.updateNode(nodeId, { content: 'Buy milk', nodeType: 'task' });

Phase 2: Implement Conversion Source Tracking

File to modify: packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts

  • Add nodeTypeConversionSource Map to track conversion method
  • Update updateNodeType() to record 'slash-command' source (line ~630)
  • Update updateNodeContent() to conditionally include nodeType (line ~605)
  • Add pattern conversion handler to record 'pattern' source
  • Add cleanup logic when content is first persisted

Phase 3: Investigate Content Truncation

Debug why "[ ] Test task" becomes "[ ] ":

  • Check if pattern detection is stripping content
  • Verify debounce timing isn't catching partial input
  • Check if multiple updates are racing
  • Add logging to identify which update persists

Phase 4: Validation

  • All new tests pass
  • Existing node-type-persistence tests still pass
  • Manual test: Type "[ ] Buy groceries" → reload → shows as task
  • Manual test: Type /task, then "Buy groceries" → reload → shows as task
  • Database query confirms nodeType='task' and full content saved
  • Run full test suite (bun run test:all)

Acceptance Criteria

  • Slash command conversions persist nodeType correctly to database
  • Pattern detection conversions persist nodeType correctly to database
  • Full content persists (not truncated to pattern only)
  • Schema defaults applied when creating task nodes
  • Pattern conversions still work bidirectionally (header ↔ text)
  • Page reload shows correct node type from database
  • Integration tests cover separate updateNodeType/updateNodeContent calls
  • Tests run in database mode to verify actual persistence
  • No regressions in existing tests
  • Code passes bun run quality:fix

Evidence of Bug

Database State

sqlite3 nodespace-dev.db "SELECT id, node_type, content FROM nodes WHERE content LIKE '%[ ]%'"

Result: node_type = "text", content = "[ ] " (should be task with full content)

Backend Logs

UPDATE node: ab4b8104...
  node_type: None          ← Missing
  content: Some("[ ] ")    ← Truncated

UI vs Database Mismatch

  • UI shows: Task node with blue dot icon ✅
  • Database has: Text node with incomplete content ❌

Related Issues

Previous Fix Attempts (Regressed)

Related Architecture

Technical Specifications

Reference Files

Study these for context:

  • packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts:605-647 - updateNodeContent and updateNodeType
  • packages/desktop-app/src/lib/services/shared-node-store.ts:436-542 - Persistence logic
  • packages/desktop-app/src/lib/utils/placeholder-detection.ts - isPlaceholderNode logic
  • packages/desktop-app/src/tests/integration/node-type-persistence.test.ts - Existing tests (flawed)

Key Architecture Concepts

Placeholder Lifecycle:

  1. Created in-memory (not in persistedNodeIds)
  2. User converts type → Still placeholder (empty content)
  3. User adds content → No longer placeholder
  4. Debounce fires → Persist via CREATE (first time)

Two Conversion Flows:

  1. Pattern Detection: Type "## " → TextareaController detects → fires nodeTypeConversionDetected event
  2. Slash Commands: Type "/task" → SlashCommandService → calls updateNodeType()

Both must persist correctly!

Non-Goals

This issue does NOT include:

  • ❌ Refactoring placeholder system
  • ❌ Changing batching architecture
  • ❌ Modifying pattern detection logic
  • ❌ Adding new node types

Scope: Fix nodeType persistence for existing conversion mechanisms only.

Success Metrics

Before Fix:

  • Database: 0% of converted nodes have correct nodeType
  • Content: Truncated to pattern only ("[ ] " instead of "[ ] Buy groceries")

After Fix:

  • Database: 100% of converted nodes persist with correct nodeType
  • Content: Full content persists ("[ ] Buy groceries")
  • Tests: Integration tests catch this regression
  • Reliability: No regressions for 30+ days

Activity

  1. added
    bug
    on Nov 6, 2025
  2. self-assigned this
    on Nov 6, 2025
  3. malibio commented on Nov 6, 2025

    @malibio
    CollaboratorAuthor

    Test Baseline Recorded

    Before starting work on issue #424:

    • Total Tests: 1598 tests
    • Passing: 1549 passed
    • Skipped: 48 skipped
    • Failing: 1 failed (pre-existing)

    Pre-existing Failure:

    • HierarchyService > Node Depth Calculations > getNodeDepth caches results for performance - Performance timing flake (not related to this issue)

    All new tests must pass. No new failures will be accepted.

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

Metadata

Metadata

Assignees

Labels

bugcriticaldatabasefrontend

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions