Skip to content

Fix slash/type-conversion state_unsafe_mutation that wedges the flush (closes #1578) - #1581

Merged
malibio merged 3 commits into
mainfrom
issue-1578-slash-conversion-mutation
Jul 7, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-1578-slash-conversion-mutation

Conversation

@malibio

@malibio malibio commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

Summary

Fixes #1578 — typing / (or converting/creating a node type, e.g. Task) threw state_unsafe_mutation, wedged the Svelte flush, made the edited node disappear, and left node-type creation failing in the UI with the app going sluggish.

Two distinct reactive-safety violations on the date-viewer render path had to be fixed; the second is the one the issue's proposed fix didn't catch and was the actual flush-wedger.

Root cause & fix

1. Slash/type-conversion handlers wrote $state during the render flush (base-node-viewer.svelte)

handleSlashCommandSelected and handleNodeTypeChanged called focusManager.focusNodeFromTypeConversion() (and, on the non-placeholder path, sharedNodeStore.updateNode()) synchronously at the top of the handler — during the render flush a keystroke triggers. Svelte throws state_unsafe_mutation.

Fix: move these writes into the tick().then(...) blocks the placeholder-promotion paths already use (focus first, so the new component sees it on mount). The non-placeholder updateNode is now guarded with hasNode(), eliminating the Cannot update non-existent node warning when the id was promoted/removed since the event fired.

2. UI-state lazy-init wrote $state from inside a $derived (reactive-node-service.svelte.ts)

The visibleNodesFromStores $derived flattens nodes and reads each node's UI state via getUIState → ensureUIState, which lazily persisted a default into the _uiState $state map. Writing reactive state from inside a $derived throws state_unsafe_mutation at date-viewer render time — before any keystroke — and wedges the flush, so even with fix #1 the deferred writes never landed and Task creation silently did nothing.

Fix: replace the render-path read with a pure peekUIState() that computes a default without persisting. Genuine UI-state seeding still happens on the mutation/lifecycle paths (node load, create, expand/collapse, structure changes). Deleted the now-unused ensureUIState.

Both align with ADR-049: reactive state is written from event handlers / store methods, never inside a render/derived path.

Verification

Verified end-to-end in dev:browser driving the real app (not just tests):

  • On load: 0 console errors (was throwing state_unsafe_mutation at date-viewer render before fix Create design system foundation #2).
  • Type /: slash palette opens (14 commands), node does not disappear, focus retained, 0 new errors.
  • /task → Enter: node converts to a Task, keeps cursor/focus, and persists to the daemon (nodeType: "task"). No Cannot update non-existent node warning.
  • Reload: the persisted Task renders cleanly with 0 errors.
  • The / → Task path also confirmed working in dev:tauri.

Before/after comparison against unmodified main (via stash) confirmed the exact issue symptoms (Cannot update non-existent node + multiple state_unsafe_mutation) are eliminated.

bun run test → 150 files / 3940 tests pass. eslint + svelte-check clean. Pre-push gate (test:all + cargo build + test:e2e) passed.

Acceptance criteria

  • Typing / no longer makes the node disappear; slash palette opens normally.
  • Creating/converting to Task via / works in the UI and keeps cursor/focus.
  • No state_unsafe_mutation on the slash / node-type-conversion path.
  • No Cannot update non-existent node warning during slash-command node creation.
  • App remains responsive after these interactions (no flush wedge).
  • Verified in dev:browser; slash→Task path verified in dev:tauri.

🤖 Generated with Claude Code

malibio and others added 2 commits July 7, 2026 14:02
handleSlashCommandSelected and handleNodeTypeChanged wrote reactive $state
synchronously during the render flush a keystroke triggers: the top-level
focusManager.focusNodeFromTypeConversion() and, on the non-placeholder path,
sharedNodeStore.updateNode(). Svelte throws state_unsafe_mutation and wedges
the flush, so the edited node disappears and type conversion fails in the UI.

Move these writes into the tick().then(...) blocks the placeholder-promotion
paths already use (focus first, so the new component sees it on mount), and
guard the non-placeholder updateNode with hasNode() so it no longer logs
'Cannot update non-existent node' when the id was promoted/removed since the
event fired. Aligns with ADR-049 (reactive state written from event handlers,
never during a render/derived path).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The visibleNodesFromStores $derived flattens nodes and reads each node's UI
state via getUIState -> ensureUIState, which lazily persisted a default into
the _uiState $state map. Writing reactive state from inside a $derived throws
state_unsafe_mutation at date-viewer render time and wedges the flush, so the
slash/type-conversion deferred writes never land and Task creation silently
fails in the UI even after the handler fix.

Replace the render-path read with a pure peekUIState() that computes a default
without persisting; genuine UI-state seeding still happens on the mutation/
lifecycle paths. Delete the now-unused ensureUIState.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pragmatic Code Review — PR #1581 (closes #1578)

Review Type: Initial review

Verdict: APPROVE. Correct, minimal, root-cause fix that is a clear net positive to code health. It applies the file's own established tick()-deferral pattern to the two un-deferred reactive writes, and closes the deeper render-path $state write in peekUIState that the handler fix alone would not have resolved. The two behavior-change concerns (persistence side-effect removal; computeDepth per-render cost) were verified as non-issues. 144 tests across the three most-affected suites pass.

Requirements Check (acceptance criteria from #1578)

  • ✅ Typing / no longer makes the node disappear — the two synchronous render-flush $state writes (top-level focus + non-placeholder updateNode) are deferred to tick(); peekUIState removes the third write (_uiState lazy-persist) firing inside the visibleNodesFromStores $derived.
  • ✅ Convert to Task/other types works and keeps focus — focus is set first inside the deferred block (base-node-viewer.svelte:1040, :1061, :1208), mirroring the placeholder-promotion path.
  • ✅ No state_unsafe_mutation on the slash/type-conversion path — all reactive writes now event-handler/tick()-scoped (ADR-049 §1).
  • ✅ No Cannot update non-existent node warning — hasNode guard at base-node-viewer.svelte:1209.
  • ✅ App remains responsive (no flush wedge) — removing the render-path $state write un-wedges the flush.
  • ✅ Verified in both dev:tauri and dev:browser.

Findings

🔴 Critical

None.

🟡 Suggested Improvements

🟡 base-node-viewer.svelte:1208 — focus is set on a possibly-removed node (slash handler). The hasNode(node.id) guard wraps only updateNode, but focusManager.focusNodeFromTypeConversion(node.id, …) and handleCustomEntitySlashCommand(node.id, …) run unconditionally. If node.id was promoted/removed between the event and the tick — the exact scenario the guard exists for — focus/editing state (and a custom-entity flow) run against a node that no longer exists. Low blast radius (a stale id writes three $state scalars and self-corrects on next focus), but the intent reads as "if the node is gone, skip the whole conversion." Principle: least-surprise / guard-the-whole-operation. Consider hoisting the guard:

tick().then(() => {
  if (!sharedNodeStore.hasNode(node.id)) return;
  focusManager.focusNodeFromTypeConversion(node.id, cursorPosition, paneId);
  sharedNodeStore.updateNode(node.id, updatePayload, { type: 'viewer', viewerId });
  if (isCustomSchemaType(newNodeType)) { … }
});

🟢 Nitpicks

  • Guard asymmetry between the two handlers. handleNodeTypeChanged's non-placeholder branch (:1060) has no hasNode guard because it routes through nodeManager.updateNodeContent/updateNodeType, which internally if (!node) return. The slash handler needs the explicit guard because it calls sharedNodeStore.updateNode directly. Correct and intentional, but a half-line comment noting "type-changed path is guarded inside nodeManager.update*" would save a future reader the cross-file trace.
  • getUIState doc comment slightly stale (reactive-node-service.svelte.ts:1434-1437). Still opens "Lazily initializes state…" before the "PURE read" clarification. Leading with "Direct pure read of a node's UI state…" would be cleaner.

Focus-area analysis

  1. ADR-049 — CONFIRMED CORRECT. No reactive $state written from render/derived/template after the change. peekUIState is a pure read; deferred writes run inside tick().then(...) from event handlers.
  2. peekUIState behavior change — NO REGRESSION. Old ensureUIState and new peekUIState are return-value identical; differ only in persistence side-effect. Both node-expansion-coordinator.ts call sites (:192 reads .expanded over in-store nodes; :235 filters !== undefined governed by getUIState's own getNode ? … : _uiState[nodeId] branch) behave identically. No caller relied on a prior read seeding _uiState — mutators (setExpanded:1294, updateNodeContent:475) are self-sufficient. computeDepth-per-render is bounded: loadFromNodes seeds _uiState for loaded nodes, so steady-state hits the plain map lookup; the fallback fires only for the small transient set of in-store-but-not-yet-seeded nodes.
  3. tick() ordering/races — SOUND. await nodeLoader.load(...) completes before the tick; nothing between event and tick reads focus/updateNode results. Focus-first ordering matches the placeholder-promotion path. Double-fire mitigated by isPromoting + hasNode/internal !node guards.
  4. Testing. No new automated test; verified by driving the real app. Concur this is pragmatic — the state_unsafe_mutation throw needs a real render flush the Happy-DOM harness doesn't model. A unit test asserting "getUIState does not mutate _uiState" would cheaply lock in the ADR-049 invariant — worth a follow-up, not a blocker. Existing 144 tests in the affected suites pass unchanged.

Recommendation: APPROVE

The single 🟡 (hoist the hasNode guard) and two 🟢 nits are optional polish; none block merge.

🤖 Generated with Claude Code

…1578)

- 🟡 handleSlashCommandSelected non-placeholder branch: hoist the hasNode
  guard to the top of the tick block so a node promoted/removed between the
  event and the tick skips the whole conversion (focus + updateNode +
  custom-entity flow), not just the updateNode call.
- 🟢 handleNodeTypeChanged non-placeholder branch: comment why it needs no
  explicit hasNode guard (routes through nodeManager.update*, which guards
  internally with 'if (!node) return').
- 🟢 getUIState: replace the stale 'Lazily initializes' lead — it is now a
  pure non-persisting read.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@malibio

malibio commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed (commit ecb67119)

All three findings from the review applied:

  • 🟡 Hoist the hasNode guard (base-node-viewer.svelte, handleSlashCommandSelected non-placeholder branch) — the guard now sits at the top of the tick() block (if (!sharedNodeStore.hasNode(node.id)) return;), so a node promoted/removed between the event and the tick skips the whole conversion (focus + updateNode + custom-entity flow), not just updateNode.
  • 🟢 Guard-asymmetry comment (handleNodeTypeChanged non-placeholder branch) — added a note that no explicit hasNode guard is needed there because it routes through nodeManager.updateNodeContent/updateNodeType, which guard internally with if (!node) return.
  • 🟢 Stale doc comment (reactive-node-service.svelte.ts getUIState) — replaced the "Lazily initializes" lead with an accurate "pure non-persisting read" description.

Nothing skipped. eslint + svelte-check clean; bun run test → 150 files / 3940 tests pass; pre-push gate (test:all + cargo build + test:e2e) passed.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED.

Rationale: The reviewer's verdict was already APPROVE with no critical/architectural findings. These changes are a small defensive-guard hoist (behavior-narrowing, not new logic) plus two comment/doc edits — low-risk, no new functionality, fully covered by the existing green test suite and pre-push gate. The PR is ready for merge pending your call.

🤖 Generated with Claude Code

@malibio

malibio commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Re-Review — commit ecb67119 (delta 7e69cca1..ecb67119)

Delta re-review of the review-feedback commit (findings only — not a formal approval, since this PR was authored in-session).

All three prior findings addressed; one real behavior change (the 🟡 guard hoist), the rest comment/doc edits.

The 🟡 guard hoist — SAFE

Changed handleSlashCommandSelected's non-placeholder else branch from guarding only updateNode to an early return if (!sharedNodeStore.hasNode(node.id)) return; gating the whole tick block. Traced whether any real path leaves node.id legitimately absent at tick-time while still wanting focus / custom-entity work — none exists:

  • The else branch is the already-in-store path (the promotion if requires !nodeExistsInStore, so not-yet-in-store nodes take the other branch). Normal case: node is present, guard doesn't fire.
  • hasNode returns false at tick-time only on a genuine promoted/removed race. There: updateNode was already a no-op (Cannot update non-existent node warn) — skipping is strictly better; focusNodeFromTypeConversion on a dead id is meaningless and self-corrects; handleCustomEntitySlashCommand navigating to a removed entity is exactly the work to skip.
  • The optimistic-promotion case (node briefly absent but will exist) is handled entirely by the promotion branch, which sets the node into the store within the same tick and never consults this guard — so no real node mid-flight is starved.

Comment edits — accurate

Both the guard-asymmetry note and the reworded getUIState doc match the code.

New findings: none.

Assessment: the delta is minimal, self-consistent, and correct — the guard hoist is a strict improvement with no legitimate work dropped. A human approving review is still appropriate before merge.

🤖 Generated with Claude Code

@malibio
malibio merged commit 149508f into main Jul 7, 2026
2 checks passed
@malibio
malibio deleted the issue-1578-slash-conversion-mutation branch July 7, 2026 16:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant