Skip to content

Fix Enter Key & Node Creation Operations (17 test failures) - #244

Merged
malibio merged 7 commits into
mainfrom
feature/issue-232-enter-key-operations
Oct 12, 2025
Merged

malibio merged 7 commits into
mainfrom
feature/issue-232-enter-key-operations

Conversation

@malibio

@malibio malibio commented Oct 12, 2025

Copy link
Copy Markdown
Collaborator

Closes #232

malibio and others added 7 commits October 12, 2025 02:07
…ge (Issue #232)

## Problem
HTTP dev server used a single shared NodeService instance, preventing test
isolation. When tests called /api/database/init with unique database paths, the
endpoint created new services but didn't update AppState, causing:
- UNIQUE constraint errors from static node IDs across tests
- Test contamination (nodes from one test appearing in another)
- Inability to run comprehensive integration test suites

## Solution
Implemented RwLock pattern to enable atomic database swapping:

**Backend Changes:**
- AppState now uses Arc<RwLock<Arc<DatabaseService>>> and Arc<RwLock<Arc<NodeService>>>
- init_database() creates new services and swaps them atomically via RwLock
- All endpoints use .read().unwrap().clone() pattern for safe concurrent access
- Updated dev-server.rs to wrap initial services in RwLock

**Frontend Changes:**
- SharedNodeStore: Skip viewer-sourced persistence (temporary dual persistence fix)
- ReactiveNodeService: Fixed containerNodeId='root' for root-level nodes
- node-ordering tests: Added sharedNodeStore.__resetForTesting() for isolation

## Test Results
- ✅ node-ordering: 10/10 passing
- ✅ enter-key-operations: 7/10 passing (3 real bugs remain - Issue #232 continued)
- ⏳ shift-enter-operations: Skipped (HTTP 500 error - separate issue)

**Database isolation verified working:**
- Server logs show "🔄 Database SWAPPED to: <path>" for each test
- NO MORE UNIQUE constraint errors
- Each test gets isolated database with unique path

## Files Modified
- src-tauri/src/bin/dev-server.rs - RwLock initialization
- src-tauri/src/dev_server/mod.rs - AppState with RwLock
- src-tauri/src/dev_server/node_endpoints.rs - RwLock swap logic + access pattern
- src-tauri/src/dev_server/query_endpoints.rs - RwLock access pattern
- src-tauri/src/dev_server/embedding_endpoints.rs - RwLock access pattern
- src/lib/services/reactive-node-service.svelte.ts - containerNodeId fix
- src/lib/services/shared-node-store.ts - viewer-source persistence skip
- src/tests/integration/node-ordering.test.ts - test isolation reset

## Next Steps (Issue #232 continued)
1. Fix 3 remaining enter-key operation bugs (beforeSiblingId logic)
2. Investigate shift-enter HTTP 500 error
3. Run full test suite
4. Create PR

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
**Problem**:
- Nodes created via Enter key (createNode in ReactiveNodeService) were not persisting to database
- SharedNodeStore was skipping persistence for viewer-sourced operations
- Tests expected nodes to exist in database but they were only in memory

**Root Cause**:
- setNode() and updateNode() had logic: `source.type !== 'viewer'` which skipped ALL viewer operations
- This was intended to avoid duplicate persistence (BaseNodeViewer handles debounced content updates)
- But NEW node creation needs immediate persistence, regardless of source

**Solution**:
- setNode(): Persist NEW nodes from viewer immediately (`isNewNode` flag)
- updateNode(): Persist STRUCTURAL changes from viewer immediately (parentId/beforeSiblingId)
- Content updates from viewer still skipped (handled by BaseNodeViewer with debouncing)

**Changes**:
- Added `isNewNode` tracking in setNode() before adding to map
- Added `isStructuralChange` detection in updateNode() (parentId or beforeSiblingId in changes)
- Updated persistence logic: `shouldPersist = source.type !== 'viewer' || (isNewNode || isStructuralChange)`

**Remaining Issue**:
- Backend validation rejects empty content nodes (HTTP 500)
- Tests still failing due to backend constraints, not frontend logic
- Backend needs update to accept empty/placeholder nodes
- See Issue #232 for backend validation fix

**Testing**:
- enter-key-operations.test.ts: Nodes now attempt persistence correctly
- Structural changes (sibling chain updates) now persist properly
- Frontend logic is correct; backend validation needs adjustment

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Remove empty content validation to allow placeholder nodes from Enter key
- Convert 'root' container_node_id to None for database operations
- Add debug logging for UPDATE operations
- Apply fixes to both CREATE and UPDATE paths

Related to #232
- Add custom deserializer for Option<Option<T>> fields in NodeUpdate struct
  - Accepts plain JSON values from TypeScript (e.g., {"beforeSiblingId": "value"})
  - Maps to Rust double-Option pattern automatically
  - Fixes HTTP 500 errors on UPDATE operations

- Fix SharedNodeStore.isNewNode check
  - Use persistedNodeIds Set instead of nodes Map
  - Prevents incorrect CREATE vs UPDATE determination

- Fix SharedNodeStore.isStructuralChange definition
  - Include containerNodeId in structural change detection
  - Ensures container updates persist immediately from viewer

Related to #232
- Multi-line formatting for isStructuralChange check (readability)

Related to #232
CRITICAL FIXES (Production Safety):
- Replace all .unwrap() calls with proper error handling in dev_server endpoints
  * node_endpoints.rs: All RwLock operations now handle poisoned locks gracefully
  * query_endpoints.rs: Added error propagation for lock acquisition
  * embedding_endpoints.rs: Same error handling improvements
  * Prevents cascading failures from poisoned RwLocks

- Add security documentation to TextNodeBehavior validation
  * Explains why empty content is allowed (Enter key UX pattern)
  * Documents security considerations around placeholder nodes
  * Clarifies that empty nodes are intentional user actions

IMPORTANT IMPROVEMENTS:
- Fix Arc::clone() pattern for better lock contention
  * Release RwLock immediately after cloning Arc
  * Pattern: { let lock = ...; Arc::clone(&*lock) }
  * Applied to all node service access points

- Add comprehensive JSDoc for TypeScript ↔ Rust type mapping
  * Documents Option<Option<T>> pattern in NodeUpdate interface
  * Includes table showing undefined/null/value mappings
  * Example usage for each field type
  * References Rust custom deserializer location

NICE-TO-HAVE:
- Extract 'root' magic string to ROOT_CONTAINER_ID constant
  * Centralized in node_service.rs with documentation
  * Replaced all 3 occurrences of hardcoded "root" string
  * Improves maintainability and self-documentation

- Add test for containerNodeId 'root' → null conversion
  * Verifies frontend 'root' string converts to database NULL
  * Tests enter-key-operations.test.ts
  * Ensures ROOT_CONTAINER_ID constant behavior is correct

All fixes address code review feedback from comprehensive review.
Tests pass, quality checks pass, no regressions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Introduces SharedService<T> type alias to improve code readability:
- Reduces visual noise in AppState definition
- Makes the swappable service pattern more explicit
- Self-documenting with inline comments explaining each layer

Before:
  pub db: Arc<RwLock<Arc<DatabaseService>>>,

After:
  pub db: SharedService<DatabaseService>,

The type alias documents the pattern's purpose:
- Thread-safe shared ownership (outer Arc)
- Safe service replacement via write lock (RwLock)
- Multiple readers or single writer semantics (inner Arc)

No behavioral changes, purely a readability improvement.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio
malibio merged commit a0bcb60 into main Oct 12, 2025
@malibio
malibio deleted the feature/issue-232-enter-key-operations branch October 12, 2025 09:29
malibio added a commit that referenced this pull request Oct 12, 2025
Resolved conflicts by:
- Keeping PersistenceCoordinator delegation from our branch
- Incorporating shouldPersist logic from main (PR #244)
- Combining both isEmptyTextNode checks and viewer source filtering
- Maintaining ancestor chain dependency resolution

Changes from main (PR #244):
- Added shouldPersist check for viewer source filtering
- Added isNewNode tracking for setNode
- Better comments explaining viewer persistence behavior

Our changes preserved:
- PersistenceCoordinator delegation for all persistence
- Ancestor chain dependency resolution via lambda
- Structured error handling and test error tracking
malibio added a commit that referenced this pull request Feb 4, 2026
* Fix HTTP server database isolation & enable comprehensive test coverage (Issue #232)

## Problem
HTTP dev server used a single shared NodeService instance, preventing test
isolation. When tests called /api/database/init with unique database paths, the
endpoint created new services but didn't update AppState, causing:
- UNIQUE constraint errors from static node IDs across tests
- Test contamination (nodes from one test appearing in another)
- Inability to run comprehensive integration test suites

## Solution
Implemented RwLock pattern to enable atomic database swapping:

**Backend Changes:**
- AppState now uses Arc<RwLock<Arc<DatabaseService>>> and Arc<RwLock<Arc<NodeService>>>
- init_database() creates new services and swaps them atomically via RwLock
- All endpoints use .read().unwrap().clone() pattern for safe concurrent access
- Updated dev-server.rs to wrap initial services in RwLock

**Frontend Changes:**
- SharedNodeStore: Skip viewer-sourced persistence (temporary dual persistence fix)
- ReactiveNodeService: Fixed containerNodeId='root' for root-level nodes
- node-ordering tests: Added sharedNodeStore.__resetForTesting() for isolation

## Test Results
- ✅ node-ordering: 10/10 passing
- ✅ enter-key-operations: 7/10 passing (3 real bugs remain - Issue #232 continued)
- ⏳ shift-enter-operations: Skipped (HTTP 500 error - separate issue)

**Database isolation verified working:**
- Server logs show "🔄 Database SWAPPED to: <path>" for each test
- NO MORE UNIQUE constraint errors
- Each test gets isolated database with unique path

## Files Modified
- src-tauri/src/bin/dev-server.rs - RwLock initialization
- src-tauri/src/dev_server/mod.rs - AppState with RwLock
- src-tauri/src/dev_server/node_endpoints.rs - RwLock swap logic + access pattern
- src-tauri/src/dev_server/query_endpoints.rs - RwLock access pattern
- src-tauri/src/dev_server/embedding_endpoints.rs - RwLock access pattern
- src/lib/services/reactive-node-service.svelte.ts - containerNodeId fix
- src/lib/services/shared-node-store.ts - viewer-source persistence skip
- src/tests/integration/node-ordering.test.ts - test isolation reset

## Next Steps (Issue #232 continued)
1. Fix 3 remaining enter-key operation bugs (beforeSiblingId logic)
2. Investigate shift-enter HTTP 500 error
3. Run full test suite
4. Create PR

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix SharedNodeStore persistence for new nodes from viewer source

**Problem**:
- Nodes created via Enter key (createNode in ReactiveNodeService) were not persisting to database
- SharedNodeStore was skipping persistence for viewer-sourced operations
- Tests expected nodes to exist in database but they were only in memory

**Root Cause**:
- setNode() and updateNode() had logic: `source.type !== 'viewer'` which skipped ALL viewer operations
- This was intended to avoid duplicate persistence (BaseNodeViewer handles debounced content updates)
- But NEW node creation needs immediate persistence, regardless of source

**Solution**:
- setNode(): Persist NEW nodes from viewer immediately (`isNewNode` flag)
- updateNode(): Persist STRUCTURAL changes from viewer immediately (parentId/beforeSiblingId)
- Content updates from viewer still skipped (handled by BaseNodeViewer with debouncing)

**Changes**:
- Added `isNewNode` tracking in setNode() before adding to map
- Added `isStructuralChange` detection in updateNode() (parentId or beforeSiblingId in changes)
- Updated persistence logic: `shouldPersist = source.type !== 'viewer' || (isNewNode || isStructuralChange)`

**Remaining Issue**:
- Backend validation rejects empty content nodes (HTTP 500)
- Tests still failing due to backend constraints, not frontend logic
- Backend needs update to accept empty/placeholder nodes
- See Issue #232 for backend validation fix

**Testing**:
- enter-key-operations.test.ts: Nodes now attempt persistence correctly
- Structural changes (sibling chain updates) now persist properly
- Frontend logic is correct; backend validation needs adjustment

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix backend validation for empty content and 'root' container_node_id

- Remove empty content validation to allow placeholder nodes from Enter key
- Convert 'root' container_node_id to None for database operations
- Add debug logging for UPDATE operations
- Apply fixes to both CREATE and UPDATE paths

Related to #232

* Fix type system mismatch and SharedNodeStore persistence logic

- Add custom deserializer for Option<Option<T>> fields in NodeUpdate struct
  - Accepts plain JSON values from TypeScript (e.g., {"beforeSiblingId": "value"})
  - Maps to Rust double-Option pattern automatically
  - Fixes HTTP 500 errors on UPDATE operations

- Fix SharedNodeStore.isNewNode check
  - Use persistedNodeIds Set instead of nodes Map
  - Prevents incorrect CREATE vs UPDATE determination

- Fix SharedNodeStore.isStructuralChange definition
  - Include containerNodeId in structural change detection
  - Ensures container updates persist immediately from viewer

Related to #232

* Format: Apply Prettier formatting to shared-node-store.ts

- Multi-line formatting for isStructuralChange check (readability)

Related to #232

* Apply code review fixes for issue #232

CRITICAL FIXES (Production Safety):
- Replace all .unwrap() calls with proper error handling in dev_server endpoints
  * node_endpoints.rs: All RwLock operations now handle poisoned locks gracefully
  * query_endpoints.rs: Added error propagation for lock acquisition
  * embedding_endpoints.rs: Same error handling improvements
  * Prevents cascading failures from poisoned RwLocks

- Add security documentation to TextNodeBehavior validation
  * Explains why empty content is allowed (Enter key UX pattern)
  * Documents security considerations around placeholder nodes
  * Clarifies that empty nodes are intentional user actions

IMPORTANT IMPROVEMENTS:
- Fix Arc::clone() pattern for better lock contention
  * Release RwLock immediately after cloning Arc
  * Pattern: { let lock = ...; Arc::clone(&*lock) }
  * Applied to all node service access points

- Add comprehensive JSDoc for TypeScript ↔ Rust type mapping
  * Documents Option<Option<T>> pattern in NodeUpdate interface
  * Includes table showing undefined/null/value mappings
  * Example usage for each field type
  * References Rust custom deserializer location

NICE-TO-HAVE:
- Extract 'root' magic string to ROOT_CONTAINER_ID constant
  * Centralized in node_service.rs with documentation
  * Replaced all 3 occurrences of hardcoded "root" string
  * Improves maintainability and self-documentation

- Add test for containerNodeId 'root' → null conversion
  * Verifies frontend 'root' string converts to database NULL
  * Tests enter-key-operations.test.ts
  * Ensures ROOT_CONTAINER_ID constant behavior is correct

All fixes address code review feedback from comprehensive review.
Tests pass, quality checks pass, no regressions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Refactor: Add type alias for Arc<RwLock<Arc<T>>> pattern

Introduces SharedService<T> type alias to improve code readability:
- Reduces visual noise in AppState definition
- Makes the swappable service pattern more explicit
- Self-documenting with inline comments explaining each layer

Before:
  pub db: Arc<RwLock<Arc<DatabaseService>>>,

After:
  pub db: SharedService<DatabaseService>,

The type alias documents the pattern's purpose:
- Thread-safe shared ownership (outer Arc)
- Safe service replacement via write lock (RwLock)
- Multiple readers or single writer semantics (inner Arc)

No behavioral changes, purely a readability improvement.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 5, 2026
* Fix HTTP server database isolation & enable comprehensive test coverage (Issue #232)

## Problem
HTTP dev server used a single shared NodeService instance, preventing test
isolation. When tests called /api/database/init with unique database paths, the
endpoint created new services but didn't update AppState, causing:
- UNIQUE constraint errors from static node IDs across tests
- Test contamination (nodes from one test appearing in another)
- Inability to run comprehensive integration test suites

## Solution
Implemented RwLock pattern to enable atomic database swapping:

**Backend Changes:**
- AppState now uses Arc<RwLock<Arc<DatabaseService>>> and Arc<RwLock<Arc<NodeService>>>
- init_database() creates new services and swaps them atomically via RwLock
- All endpoints use .read().unwrap().clone() pattern for safe concurrent access
- Updated dev-server.rs to wrap initial services in RwLock

**Frontend Changes:**
- SharedNodeStore: Skip viewer-sourced persistence (temporary dual persistence fix)
- ReactiveNodeService: Fixed containerNodeId='root' for root-level nodes
- node-ordering tests: Added sharedNodeStore.__resetForTesting() for isolation

## Test Results
- ✅ node-ordering: 10/10 passing
- ✅ enter-key-operations: 7/10 passing (3 real bugs remain - Issue #232 continued)
- ⏳ shift-enter-operations: Skipped (HTTP 500 error - separate issue)

**Database isolation verified working:**
- Server logs show "🔄 Database SWAPPED to: <path>" for each test
- NO MORE UNIQUE constraint errors
- Each test gets isolated database with unique path

## Files Modified
- src-tauri/src/bin/dev-server.rs - RwLock initialization
- src-tauri/src/dev_server/mod.rs - AppState with RwLock
- src-tauri/src/dev_server/node_endpoints.rs - RwLock swap logic + access pattern
- src-tauri/src/dev_server/query_endpoints.rs - RwLock access pattern
- src-tauri/src/dev_server/embedding_endpoints.rs - RwLock access pattern
- src/lib/services/reactive-node-service.svelte.ts - containerNodeId fix
- src/lib/services/shared-node-store.ts - viewer-source persistence skip
- src/tests/integration/node-ordering.test.ts - test isolation reset

## Next Steps (Issue #232 continued)
1. Fix 3 remaining enter-key operation bugs (beforeSiblingId logic)
2. Investigate shift-enter HTTP 500 error
3. Run full test suite
4. Create PR

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix SharedNodeStore persistence for new nodes from viewer source

**Problem**:
- Nodes created via Enter key (createNode in ReactiveNodeService) were not persisting to database
- SharedNodeStore was skipping persistence for viewer-sourced operations
- Tests expected nodes to exist in database but they were only in memory

**Root Cause**:
- setNode() and updateNode() had logic: `source.type !== 'viewer'` which skipped ALL viewer operations
- This was intended to avoid duplicate persistence (BaseNodeViewer handles debounced content updates)
- But NEW node creation needs immediate persistence, regardless of source

**Solution**:
- setNode(): Persist NEW nodes from viewer immediately (`isNewNode` flag)
- updateNode(): Persist STRUCTURAL changes from viewer immediately (parentId/beforeSiblingId)
- Content updates from viewer still skipped (handled by BaseNodeViewer with debouncing)

**Changes**:
- Added `isNewNode` tracking in setNode() before adding to map
- Added `isStructuralChange` detection in updateNode() (parentId or beforeSiblingId in changes)
- Updated persistence logic: `shouldPersist = source.type !== 'viewer' || (isNewNode || isStructuralChange)`

**Remaining Issue**:
- Backend validation rejects empty content nodes (HTTP 500)
- Tests still failing due to backend constraints, not frontend logic
- Backend needs update to accept empty/placeholder nodes
- See Issue #232 for backend validation fix

**Testing**:
- enter-key-operations.test.ts: Nodes now attempt persistence correctly
- Structural changes (sibling chain updates) now persist properly
- Frontend logic is correct; backend validation needs adjustment

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix backend validation for empty content and 'root' container_node_id

- Remove empty content validation to allow placeholder nodes from Enter key
- Convert 'root' container_node_id to None for database operations
- Add debug logging for UPDATE operations
- Apply fixes to both CREATE and UPDATE paths

Related to #232

* Fix type system mismatch and SharedNodeStore persistence logic

- Add custom deserializer for Option<Option<T>> fields in NodeUpdate struct
  - Accepts plain JSON values from TypeScript (e.g., {"beforeSiblingId": "value"})
  - Maps to Rust double-Option pattern automatically
  - Fixes HTTP 500 errors on UPDATE operations

- Fix SharedNodeStore.isNewNode check
  - Use persistedNodeIds Set instead of nodes Map
  - Prevents incorrect CREATE vs UPDATE determination

- Fix SharedNodeStore.isStructuralChange definition
  - Include containerNodeId in structural change detection
  - Ensures container updates persist immediately from viewer

Related to #232

* Format: Apply Prettier formatting to shared-node-store.ts

- Multi-line formatting for isStructuralChange check (readability)

Related to #232

* Apply code review fixes for issue #232

CRITICAL FIXES (Production Safety):
- Replace all .unwrap() calls with proper error handling in dev_server endpoints
  * node_endpoints.rs: All RwLock operations now handle poisoned locks gracefully
  * query_endpoints.rs: Added error propagation for lock acquisition
  * embedding_endpoints.rs: Same error handling improvements
  * Prevents cascading failures from poisoned RwLocks

- Add security documentation to TextNodeBehavior validation
  * Explains why empty content is allowed (Enter key UX pattern)
  * Documents security considerations around placeholder nodes
  * Clarifies that empty nodes are intentional user actions

IMPORTANT IMPROVEMENTS:
- Fix Arc::clone() pattern for better lock contention
  * Release RwLock immediately after cloning Arc
  * Pattern: { let lock = ...; Arc::clone(&*lock) }
  * Applied to all node service access points

- Add comprehensive JSDoc for TypeScript ↔ Rust type mapping
  * Documents Option<Option<T>> pattern in NodeUpdate interface
  * Includes table showing undefined/null/value mappings
  * Example usage for each field type
  * References Rust custom deserializer location

NICE-TO-HAVE:
- Extract 'root' magic string to ROOT_CONTAINER_ID constant
  * Centralized in node_service.rs with documentation
  * Replaced all 3 occurrences of hardcoded "root" string
  * Improves maintainability and self-documentation

- Add test for containerNodeId 'root' → null conversion
  * Verifies frontend 'root' string converts to database NULL
  * Tests enter-key-operations.test.ts
  * Ensures ROOT_CONTAINER_ID constant behavior is correct

All fixes address code review feedback from comprehensive review.
Tests pass, quality checks pass, no regressions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Refactor: Add type alias for Arc<RwLock<Arc<T>>> pattern

Introduces SharedService<T> type alias to improve code readability:
- Reduces visual noise in AppState definition
- Makes the swappable service pattern more explicit
- Self-documenting with inline comments explaining each layer

Before:
  pub db: Arc<RwLock<Arc<DatabaseService>>>,

After:
  pub db: SharedService<DatabaseService>,

The type alias documents the pattern's purpose:
- Thread-safe shared ownership (outer Arc)
- Safe service replacement via write lock (RwLock)
- Multiple readers or single writer semantics (inner Arc)

No behavioral changes, purely a readability improvement.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 26, 2026
* Fix HTTP server database isolation & enable comprehensive test coverage (Issue #232)

## Problem
HTTP dev server used a single shared NodeService instance, preventing test
isolation. When tests called /api/database/init with unique database paths, the
endpoint created new services but didn't update AppState, causing:
- UNIQUE constraint errors from static node IDs across tests
- Test contamination (nodes from one test appearing in another)
- Inability to run comprehensive integration test suites

## Solution
Implemented RwLock pattern to enable atomic database swapping:

**Backend Changes:**
- AppState now uses Arc<RwLock<Arc<DatabaseService>>> and Arc<RwLock<Arc<NodeService>>>
- init_database() creates new services and swaps them atomically via RwLock
- All endpoints use .read().unwrap().clone() pattern for safe concurrent access
- Updated dev-server.rs to wrap initial services in RwLock

**Frontend Changes:**
- SharedNodeStore: Skip viewer-sourced persistence (temporary dual persistence fix)
- ReactiveNodeService: Fixed containerNodeId='root' for root-level nodes
- node-ordering tests: Added sharedNodeStore.__resetForTesting() for isolation

## Test Results
- ✅ node-ordering: 10/10 passing
- ✅ enter-key-operations: 7/10 passing (3 real bugs remain - Issue #232 continued)
- ⏳ shift-enter-operations: Skipped (HTTP 500 error - separate issue)

**Database isolation verified working:**
- Server logs show "🔄 Database SWAPPED to: <path>" for each test
- NO MORE UNIQUE constraint errors
- Each test gets isolated database with unique path

## Files Modified
- src-tauri/src/bin/dev-server.rs - RwLock initialization
- src-tauri/src/dev_server/mod.rs - AppState with RwLock
- src-tauri/src/dev_server/node_endpoints.rs - RwLock swap logic + access pattern
- src-tauri/src/dev_server/query_endpoints.rs - RwLock access pattern
- src-tauri/src/dev_server/embedding_endpoints.rs - RwLock access pattern
- src/lib/services/reactive-node-service.svelte.ts - containerNodeId fix
- src/lib/services/shared-node-store.ts - viewer-source persistence skip
- src/tests/integration/node-ordering.test.ts - test isolation reset

## Next Steps (Issue #232 continued)
1. Fix 3 remaining enter-key operation bugs (beforeSiblingId logic)
2. Investigate shift-enter HTTP 500 error
3. Run full test suite
4. Create PR

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix SharedNodeStore persistence for new nodes from viewer source

**Problem**:
- Nodes created via Enter key (createNode in ReactiveNodeService) were not persisting to database
- SharedNodeStore was skipping persistence for viewer-sourced operations
- Tests expected nodes to exist in database but they were only in memory

**Root Cause**:
- setNode() and updateNode() had logic: `source.type !== 'viewer'` which skipped ALL viewer operations
- This was intended to avoid duplicate persistence (BaseNodeViewer handles debounced content updates)
- But NEW node creation needs immediate persistence, regardless of source

**Solution**:
- setNode(): Persist NEW nodes from viewer immediately (`isNewNode` flag)
- updateNode(): Persist STRUCTURAL changes from viewer immediately (parentId/beforeSiblingId)
- Content updates from viewer still skipped (handled by BaseNodeViewer with debouncing)

**Changes**:
- Added `isNewNode` tracking in setNode() before adding to map
- Added `isStructuralChange` detection in updateNode() (parentId or beforeSiblingId in changes)
- Updated persistence logic: `shouldPersist = source.type !== 'viewer' || (isNewNode || isStructuralChange)`

**Remaining Issue**:
- Backend validation rejects empty content nodes (HTTP 500)
- Tests still failing due to backend constraints, not frontend logic
- Backend needs update to accept empty/placeholder nodes
- See Issue #232 for backend validation fix

**Testing**:
- enter-key-operations.test.ts: Nodes now attempt persistence correctly
- Structural changes (sibling chain updates) now persist properly
- Frontend logic is correct; backend validation needs adjustment

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix backend validation for empty content and 'root' container_node_id

- Remove empty content validation to allow placeholder nodes from Enter key
- Convert 'root' container_node_id to None for database operations
- Add debug logging for UPDATE operations
- Apply fixes to both CREATE and UPDATE paths

Related to #232

* Fix type system mismatch and SharedNodeStore persistence logic

- Add custom deserializer for Option<Option<T>> fields in NodeUpdate struct
  - Accepts plain JSON values from TypeScript (e.g., {"beforeSiblingId": "value"})
  - Maps to Rust double-Option pattern automatically
  - Fixes HTTP 500 errors on UPDATE operations

- Fix SharedNodeStore.isNewNode check
  - Use persistedNodeIds Set instead of nodes Map
  - Prevents incorrect CREATE vs UPDATE determination

- Fix SharedNodeStore.isStructuralChange definition
  - Include containerNodeId in structural change detection
  - Ensures container updates persist immediately from viewer

Related to #232

* Format: Apply Prettier formatting to shared-node-store.ts

- Multi-line formatting for isStructuralChange check (readability)

Related to #232

* Apply code review fixes for issue #232

CRITICAL FIXES (Production Safety):
- Replace all .unwrap() calls with proper error handling in dev_server endpoints
  * node_endpoints.rs: All RwLock operations now handle poisoned locks gracefully
  * query_endpoints.rs: Added error propagation for lock acquisition
  * embedding_endpoints.rs: Same error handling improvements
  * Prevents cascading failures from poisoned RwLocks

- Add security documentation to TextNodeBehavior validation
  * Explains why empty content is allowed (Enter key UX pattern)
  * Documents security considerations around placeholder nodes
  * Clarifies that empty nodes are intentional user actions

IMPORTANT IMPROVEMENTS:
- Fix Arc::clone() pattern for better lock contention
  * Release RwLock immediately after cloning Arc
  * Pattern: { let lock = ...; Arc::clone(&*lock) }
  * Applied to all node service access points

- Add comprehensive JSDoc for TypeScript ↔ Rust type mapping
  * Documents Option<Option<T>> pattern in NodeUpdate interface
  * Includes table showing undefined/null/value mappings
  * Example usage for each field type
  * References Rust custom deserializer location

NICE-TO-HAVE:
- Extract 'root' magic string to ROOT_CONTAINER_ID constant
  * Centralized in node_service.rs with documentation
  * Replaced all 3 occurrences of hardcoded "root" string
  * Improves maintainability and self-documentation

- Add test for containerNodeId 'root' → null conversion
  * Verifies frontend 'root' string converts to database NULL
  * Tests enter-key-operations.test.ts
  * Ensures ROOT_CONTAINER_ID constant behavior is correct

All fixes address code review feedback from comprehensive review.
Tests pass, quality checks pass, no regressions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Refactor: Add type alias for Arc<RwLock<Arc<T>>> pattern

Introduces SharedService<T> type alias to improve code readability:
- Reduces visual noise in AppState definition
- Makes the swappable service pattern more explicit
- Self-documenting with inline comments explaining each layer

Before:
  pub db: Arc<RwLock<Arc<DatabaseService>>>,

After:
  pub db: SharedService<DatabaseService>,

The type alias documents the pattern's purpose:
- Thread-safe shared ownership (outer Arc)
- Safe service replacement via write lock (RwLock)
- Multiple readers or single writer semantics (inner Arc)

No behavioral changes, purely a readability improvement.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix Enter Key & Node Creation Operations (17 test failures)

1 participant