Repository navigation
Fix slash/type-conversion state_unsafe_mutation that wedges the flush (closes #1578) - #1581
Conversation
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
left a comment
There was a problem hiding this comment.
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$statewrites (top-level focus + non-placeholderupdateNode) are deferred totick();peekUIStateremoves the third write (_uiStatelazy-persist) firing inside thevisibleNodesFromStores$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_mutationon the slash/type-conversion path — all reactive writes now event-handler/tick()-scoped (ADR-049 §1). - ✅ No
Cannot update non-existent nodewarning —hasNodeguard atbase-node-viewer.svelte:1209. - ✅ App remains responsive (no flush wedge) — removing the render-path
$statewrite un-wedges the flush. - ✅ Verified in both
dev:taurianddev: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 nohasNodeguard because it routes throughnodeManager.updateNodeContent/updateNodeType, which internallyif (!node) return. The slash handler needs the explicit guard because it callssharedNodeStore.updateNodedirectly. 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. getUIStatedoc 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
- ADR-049 — CONFIRMED CORRECT. No reactive
$statewritten from render/derived/template after the change.peekUIStateis a pure read; deferred writes run insidetick().then(...)from event handlers. peekUIStatebehavior change — NO REGRESSION. OldensureUIStateand newpeekUIStateare return-value identical; differ only in persistence side-effect. Bothnode-expansion-coordinator.tscall sites (:192reads.expandedover in-store nodes;:235filters!== undefinedgoverned bygetUIState's owngetNode ? … : _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:loadFromNodesseeds_uiStatefor 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.tick()ordering/races — SOUND.await nodeLoader.load(...)completes before the tick; nothing between event and tick reads focus/updateNoderesults. Focus-first ordering matches the placeholder-promotion path. Double-fire mitigated byisPromoting+hasNode/internal!nodeguards.- Testing. No new automated test; verified by driving the real app. Concur this is pragmatic — the
state_unsafe_mutationthrow needs a real render flush the Happy-DOM harness doesn't model. A unit test asserting "getUIStatedoes 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]>
Review feedback addressed (commit
|
Re-Review — commit
|
Summary
Fixes #1578 — typing
/(or converting/creating a node type, e.g. Task) threwstate_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
$stateduring the render flush (base-node-viewer.svelte)handleSlashCommandSelectedandhandleNodeTypeChangedcalledfocusManager.focusNodeFromTypeConversion()(and, on the non-placeholder path,sharedNodeStore.updateNode()) synchronously at the top of the handler — during the render flush a keystroke triggers. Svelte throwsstate_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-placeholderupdateNodeis now guarded withhasNode(), eliminating theCannot update non-existent nodewarning when the id was promoted/removed since the event fired.2. UI-state lazy-init wrote
$statefrom inside a$derived(reactive-node-service.svelte.ts)The
visibleNodesFromStores$derivedflattens nodes and reads each node's UI state viagetUIState → ensureUIState, which lazily persisted a default into the_uiState$statemap. Writing reactive state from inside a$derivedthrowsstate_unsafe_mutationat 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-unusedensureUIState.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:browserdriving the real app (not just tests):state_unsafe_mutationat date-viewer render before fix Create design system foundation #2)./: 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"). NoCannot update non-existent nodewarning./→ Task path also confirmed working indev:tauri.Before/after comparison against unmodified
main(via stash) confirmed the exact issue symptoms (Cannot update non-existent node+ multiplestate_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
/no longer makes the node disappear; slash palette opens normally./works in the UI and keeps cursor/focus.state_unsafe_mutationon the slash / node-type-conversion path.Cannot update non-existent nodewarning during slash-command node creation.dev:browser; slash→Task path verified indev:tauri.🤖 Generated with Claude Code