Skip to content

Content-only edits forced immediate (non-debounced) persistence via redundant nodeType, and property-only updates never synced typed fields back from the backend - #1694

Merged
malibio merged 4 commits into
mainfrom
worktree-issue-1690-shared-node-store-sync
Jul 18, 2026
Merged

malibio merged 4 commits into
mainfrom
worktree-issue-1690-shared-node-store-sync

Conversation

@malibio

@malibio malibio commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator

Closes #1690

malibio and others added 2 commits July 18, 2026 09:36
… SharedNodeStore (closes #1690)

Two related bugs in updateNode()'s persistence path, found via live
interactive testing in the Tauri app and browser dev mode.

Bug 1: isNodeTypeChange was computed as 'nodeType' in changes (mere key
presence), not a value comparison. updateNodeContent() always bundles the
current, unchanged nodeType alongside content on every keystroke (a
deliberate prior fix protecting in-flight slash-command conversions from a
race). That combination forced mode: 'immediate' instead of 'debounce' on
every keystroke of every text edit, so each keystroke fired its own RPC
round-trip. An early keystroke's echo could land after later keystrokes
moved local content on, misclassifying it as a foreign write and firing a
spurious "conflicted with a remote change" toast — and under fast typing,
visibly corrupted persisted content (reproduced: "Testing conflict
reproduction now" persisted as "Tng conflict reproduction nowesti"). Fixed
by comparing changes.nodeType !== existingNode.nodeType.

Bug 2: after backendAdapter.updateNode() returns the backend's
authoritative, flattened response, only .version was copied into the local
node — every other field, including type-specific top-level fields
(ai-chat's provider/model, task's status/priority) that node_to_typed_value
promotes server-side, was discarded. A properties-only optimistic write
(e.g. AiChatModelSelector) sends the un-flattened nested shape client-side,
so the local node's top-level typed fields never got corrected. Reproduced
live: selecting a model in AI Chat left the UI stuck on "Choose a model to
get started" indefinitely, textarea never appearing, even though the
selection was genuinely persisted (confirmed via direct API read) — a page
reload didn't fix it either, ruling out a pure timing explanation. Fixed by
applying the full backend response over the local node, re-asserting
.content from the pre-update local node afterward so an in-flight newer
edit isn't clobbered by the response for an older send.

Added a regression test for bug 1 that simulates the exact real-world
payload shape updateNodeContent sends (content + redundant unchanged
nodeType together) — the existing tests in this file only ever sent
{ content } alone and so never exercised this path. Verified the new test
fails without the fix and passes with it.

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

malibio commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Review Type: Initial Review

Two-bug fix in SharedNodeStore.updateNode()'s persistence path, both diagnosed via live interactive reproduction rather than pure code reading. The diff is small (one method, plus one new test), the root-cause analysis in both the comments and commit message is precise and verifiable against the surrounding code, and I independently reproduced both the failure and the fix: reverting the isNodeTypeChange comparison to the old 'nodeType' in changes check makes the new regression test fail exactly as claimed (updateCallCount goes from 0 to 1), and restoring the fix passes it again. This is a net positive, low-risk, well-targeted change. One real gap (properties clobbering, same class as the content-clobbering bug 2 explicitly guards against) is worth flagging as an important follow-up, not a blocker.

Requirements Check (issue #1690)

  • Bug 1: isNodeTypeChange uses a value comparison, not presence — shared-node-store.svelte.ts:1102-1103, confirmed correct (changes.nodeType !== existingNode.nodeType).
  • Bug 1: regression test added to node-content-persistence-regression.test.ts, verified to fail without the fix and pass with it — independently reverted the fix and reran; test fails as claimed, passes with fix restored.
  • Bug 2: full backend response applied to the local node on update, with .content protected against in-flight local edits — shared-node-store.svelte.ts:1679-1683, confirmed.
  • Bug 2: live-verified in the Tauri app (per commit message/issue; not independently re-verified live by this review, but the fix mechanism is sound and directly addresses the described symptom).
  • No regression to bun run test:all — ran the full regression file (6/6 pass); tsc --noEmit and eslint clean on both touched files. (Full workspace test:all not re-run in this review pass; the issue's own AC box for it was unchecked at time of writing, and PR context states the full 4107-test suite passes with this branch's merge commit included.)
  • bun run quality:fix clean — eslint reports zero issues on both changed files.

All acceptance criteria are satisfied.

Code Review Findings

Critical Issues

None.

Important

  • packages/desktop-app/src/lib/services/shared-node-store.svelte.ts:1679-1683 — The bug 2 fix protects only .content from being clobbered by a stale backend response; .properties (and any other field a concurrent local updateNode() call might touch) has the identical exposure and is not protected. Concretely: AiChatNodeViewer.handleModelSelect (ai-chat-node-viewer.svelte:150-161) sends a properties-only optimistic update that reads current?.messages at call time and round-trips it through properties. Because RPC writes are serialized per-node by SimplePersistenceCoordinator, this can't race a second in-flight RPC, but it can absolutely race a newer local mutation the same way .content can: if a chat message arrives (mutating properties.messages locally) while an earlier model-selection RPC is still in flight, that RPC's response — built from the older properties.messages snapshot — will Object.assign over the newer local properties, silently reverting the new message. This is the same failure shape bug 2 fixes for .content, just left open for .properties. Given Object.assign's shallow merge, this is also not solvable by "spread everything except properties too" without a real merge strategy (nested properties.messages vs properties.model could each be independently stale). At minimum, this asymmetry should be called out explicitly in the comment (right now the comment explains why .content is protected but doesn't acknowledge that other fields have the same theoretical exposure and were consciously left unprotected) — "we know, and here's why it's out of scope" is a materially different comment than what's there now, which reads as if .content was the only field with this problem. Recommendation: either (a) add a one-line comment acknowledging the tradeoff and that it's deferred, or (b) if this is considered a live-enough risk (AI chat is an active feature), file a fast-follow issue for a proper per-field or timestamp-based merge and reference it in the comment. Not a blocker for this PR since it's a pre-existing exposure class this diff improves on net (previously nothing but .version was synced back — this fix is strictly better even with the properties gap), but it should not be quietly accepted as "solved."

Suggestions

  • packages/desktop-app/src/tests/services/node-content-persistence-regression.test.ts:150-213 — Good regression test: it drives the exact real-world payload shape ({ content, nodeType } bundled together, matching updateNodeContent()'s actual call site) rather than the simplified { content }-only shape the rest of the file used, and the assertion strategy (checking updateCallCount === 0 synchronously before any await, exploiting the fact that immediate-mode persist() calls executeOperation() synchronously while debounce schedules a setTimeout) is a precise, non-flaky way to distinguish immediate vs. debounced mode without depending on wall-clock timing. I verified by hand that this assertion fails without the fix and passes with it — it isn't a coincidental match. No issues with this test as written.

  • Bug 2 has no automated regression test — only bug 1 does. The issue's own acceptance criteria only required live verification for bug 2 ("live-verified in the Tauri app"), so this isn't a violation of what was scoped, and pragmatically, a full page-reload-survives-it live repro is reasonably strong manual evidence. But the risk profile is broader than the AI-chat trigger that surfaced it: this Object.assign sync point runs on every successful updateNode() call for every node type, not just ai-chat, so a regression here (e.g. someone "simplifying" it back to .version-only, or breaking the .content re-assertion) would silently reintroduce lost-field bugs across all type-specific top-level fields (task status/priority, etc.) with no test to catch it. Given bug 1 already has a precedent test in this exact file for "assert the RPC response shape gets correctly reflected in the local node," a companion test asserting that a mocked updateNode() response with extra top-level fields (e.g. provider/model) ends up on store.getNode(nodeId) afterward — and that .content specifically survives a same-tick local edit — would be cheap to add and would close this gap. Suggest as a fast-follow, not a blocker: the fix is simple, directly matches the diagnosed root cause, and the "protect .content from staleness" logic is straightforward enough that manual verification plus code review carries acceptable confidence for this PR, but I'd want this test to exist before this code sees much more churn.

Nitpicks

  • Nit: shared-node-store.svelte.ts:1657-1678 — this 16-line comment (plus the 10-line one for bug 1 at 1092-1101) is denser than the file's typical convention; a scan of the surrounding ~3500-line file found comment blocks are usually 1-5 lines, with the longest pre-existing block being 5 lines (line 504). Both new comments are justified here — they document a genuinely non-obvious cross-file interaction (the reactive-node-service.svelte.ts nodeType-bundling behavior, and the backend's node_to_typed_value flattening) that a future reader has no other way to discover, and they explain why, not what, consistent with the stated commenting principle. Not asking for a trim, just flagging it's on the long end relative to this file's norm — acceptable given the subtlety of both bugs.
  • Nit: shared-node-store.svelte.ts:1092-1101 references "issue Fix: Node type conversions persist as text nodes with truncated content #424 fix" and the test file references the same at line 154. Per this repo's own documentation standard (no embedded issue/ticket numbers in code comments — describe the behavior directly), this should describe what that prior fix protects against rather than citing its issue number, since the number is meaningless without external context and issue numbers aren't guaranteed stable references in comments. The surrounding prose already does describe the behavior in both places, so this is genuinely optional — the numeric reference is redundant with the prose, not load-bearing.
  • Nit: The merge commit 62143f76 pulling in unrelated origin/main changes (including PR Fix Pro-sync pill resolution, conflict-toast churn, collaboration roster, and add create-collection UI #1693's independent remote-update-policy.ts conflict-guard fix) is expected and appropriately explained by context, not a bundling problem — the net diff reviewed here (origin/main...HEAD) is clean and scoped to exactly the two files described. No action needed.

Cross-check with PR #1693 (context only, not reviewed here)

No logical inconsistency spotted between this PR's bug 1 fix (mode-selection correctness in SharedNodeStore) and #1693's version-comparison guard in remote-update-policy.ts's decideRemoteUpdate(). They operate at different layers — this PR prevents the spurious immediate-mode RPC storm from happening in the first place; #1693 guards against misclassifying an echo as a conflict if one still lands. Complementary, not overlapping in a way that could double-suppress a genuine conflict.

Overall Assessment

Net positive, well-diagnosed, low-risk fix with a solid regression test for bug 1 and clean type/lint checks. The one gap worth tracking (properties clobbering, same shape as the .content protection but unaddressed) is pre-existing risk this PR reduces rather than introduces, and is appropriately scoped as a fast-follow rather than a blocker for this change.

Recommendation: APPROVE

@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: APPROVE (recommendation — GitHub blocks self-approval on this account, so recording as a comment-type review instead). Full report posted above. Both bugs verified (reverted bug-1 fix locally, confirmed the new regression test fails without it and passes with it). One non-blocking Important finding: the bug-2 Object.assign fix protects .content from in-flight staleness but not .properties, which has the identical exposure (e.g. AiChatModelSelector). Flagged as a fast-follow, not a blocker — net improvement either way.

…), fix stale comment

The bug-2 fix only protected setNode()'s persistence closure, but the
real-world trigger for the "stuck on Choose a model" bug (AiChatModelSelector's
handleModelSelect) calls updateNode(), which has its own, separate persistence
closure with the identical .version-only sync gap. Apply the same fix there:
spread the backend's typed-field response over the local node, protecting
content and properties from being clobbered by a stale/racing response.

Also: properties must only be taken from the backend when it actually returned
some — TaskNode-shaped responses and task-updater responses for changes they
don't map back have no `properties` field, and undefined must never clobber a
defined local value (caught by two existing tests exercising exactly this).

Drop the stale "issue #424" code comment reference per this repo's convention
of describing behavior directly rather than citing ticket numbers.

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

malibio commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review feedback

🟡 Important — .properties not protected from in-flight staleness (fixed, and expanded in scope):

While implementing this, I found the fix needed to go further than the review anticipated. The reviewer's finding was framed against setNode()'s persistence closure (where the original bug-2 fix landed), but tracing the actual UI trigger (AiChatModelSelector/ai-chat-node-viewer.svelte's handleModelSelect) showed it calls sharedNodeStore.updateNode() — a separate, sibling persistence closure with the identical .version-only sync gap that bug 2 originally fixed in setNode(). The setNode() fix only helped indirectly, via a later daemon broadcast re-hydrating the node — not the direct optimistic-update path the button click exercises.

Applied the same fix to both closures:

  • updateNode()'s generic-path closure (packages/desktop-app/src/lib/services/shared-node-store.svelte.ts, ~line 1256): now spreads the backend's typed-field response over the local node instead of only .version/.title.
  • setNode()'s closure (~line 1683): extended the existing content-only protection to also cover .properties.

Both now protect content and properties from being clobbered by a stale/racing backend response, using the same precedence rule bug 2 established for content: keep the local value if it changed since the request was sent, otherwise take the backend's.

One correctness issue surfaced while writing tests for this: the backend doesn't always return a .properties field (e.g. TaskNode-shaped responses, or a task-updater response for a properties-only change it doesn't map). undefined must never clobber a defined local value — added an explicit guard for that, confirmed by two existing tests (multi-tab-reactivity.test.ts, shared-node-store-coverage.test.ts) that would otherwise fail.

🟢 Suggestion — missing regression test for bug 2 (addressed): Added 'a properties-only update syncs the backend's flattened top-level fields back into the local node' to node-content-persistence-regression.test.ts, simulating the ai-chat provider/model flattening scenario generically (avoided nodeType: 'ai-chat' specifically since normalizeNodeData's nodeToAiChatNode() strips .properties entirely, which would have made the test path unrepresentative of the generic-node case).

🟢 Suggestion — redundant "issue #424" reference (addressed): Removed from both the source comment and the test comment; described the behavior directly instead, per this repo's documentation convention of not citing ticket numbers in code.

🟢 Suggestion — inline comment length (skipped, as the reviewer anticipated): Left as-is; the reviewer's own framing called the length "justified here given the subtlety being documented."

All 166 test files / 4108 frontend tests pass, plus the full Rust test suite via the pre-push gate (including the real-model ai_chat_send_to_idle_test).

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: This wasn't a mechanical touch-up — tracing the actual bug trigger revealed the original fix needed to be duplicated into a second, previously-unpatched code path (updateNode()'s closure), which is a real architectural/behavioral change beyond what the initial review saw. It also uncovered and fixed a new correctness edge case (backend responses without a .properties field) that didn't exist in the original diff. Given the scope grew past "address feedback" into "fix an additional instance of the same class of bug," a fresh look is warranted before merge.

@malibio

malibio commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary — Re-Review

Review Type: Re-Review (reviewing only commit eca60631 against its parent 62143f76, per the prior review comment's "RE-REVIEW NEEDED" decision)

This commit does exactly what its message and the PR comment describe: it duplicates the bug-2 fix into updateNode()'s previously-unpatched persistence closure (the actual path AiChatModelSelector/handleModelSelect exercises), extends setNode()'s existing content-only staleness guard to also cover properties, and fixes a real correctness bug found along the way (backend responses without a properties field). I independently verified the logic, ran the three directly-relevant test files (63/63 passing, including the new regression test and the two previously-fragile ones), and confirmed lint is clean on both touched files. This is a solid, well-scoped fix that closes the gap the first review flagged.

Previous Review Follow-up

  • 🟡 Important — .properties not protected from staleness: Resolved, and correctly identified as needing to go further than the original finding — the real UI trigger path (updateNode()'s closure) had never been patched at all, not just under-patched. Both closures now use the same precedence rule already established for content.
  • 🟢 Suggestion — missing regression test for bug 2: Resolved. New test added, verified below to be non-tautological.
  • 🟢 Suggestion — "issue Fix: Node type conversions persist as text nodes with truncated content #424" reference: Resolved. Removed from both places it appeared; replaced with direct behavior description, consistent with this repo's documentation convention.
  • 🟢 Nit — inline comment length: Left as-is, as the prior review anticipated ("justified here").

Findings

Critical Issues

None.

Correctness Analysis (the core of this delta)

  • updateNode() closure fix (shared-node-store.svelte.ts ~1256-1298) — correct and consistent with setNode()'s version. Both closures now follow the identical shape: snapshot currentNode/latestNode synchronously right before the await backendAdapter.updateNode(...) call, then after the await, compare the current local value against that snapshot to detect "did local move on while the RPC was in flight," and only apply the backend's value if local didn't move on. I traced currentNode's lifecycle in both closures — it's captured once before the RPC fires (with one legitimate pre-RPC reassignment for the pendingMove refresh, which correctly updates the staleness baseline before, not after, the request is sent) and never mutated between capture and comparison. The two closures are structurally parallel; there's no asymmetry between them that would explain a "why does one path work and the other doesn't" bug going forward.

  • The undefined-guard (updatedNodeFromBackend.properties === undefined ? localNode.properties : updatedNodeFromBackend.properties) is correct. I checked the backend's node_to_typed_value (single flattening authority, packages/core/src/models/mod.rs / ops/node_ops.rs) — there is no backend code path that returns properties: null or an explicit "clear properties" signal; type-specific responses (e.g. TaskNode) simply omit the field entirely. JavaScript's === undefined check is true both when a key is absent and when it's present with an explicit undefined value, so there's no case here where the code needs to (and fails to) distinguish "absent" from "explicitly undefined" — both correctly fall through to "keep local." This isn't a latent gap; it's an accurate model of what the backend actually does.

  • Object.assign(localNode, updatedNodeFromBackend, { content: localContent, properties: localProperties }) — the override object always supplies an explicit properties key, so Object.assign's own last-key-wins semantics make the two-argument merge deterministic regardless of whether updatedNodeFromBackend.properties was present or absent on the source object. No edge case here.

  • The new regression test is meaningful, not tautological. It mocks backendAdapter.updateNode to return a response with top-level provider/model fields (simulating the real flattening behavior) and asserts those fields land on store.getNode(nodeId) afterward — this only passes if the Object.assign sync actually happens; a store that still only synced .version (the pre-fix behavior) would fail this assertion. I did not need to hand-revert to confirm this, since the commit message states two pre-existing tests (multi-tab-reactivity.test.ts's "should detect concurrent edits to same node", shared-node-store-coverage.test.ts's "should handle task property changes for nodes with updater") independently broke and were fixed by the undefined-guard — I read both and confirmed they drive updateNode()'s real optimistic-update path through reactiveNodeService/direct calls without a properties field on their mocked responses in the concurrent-edit case, which is exactly the scenario the guard protects. That two unrelated, pre-existing tests caught this bug independently is good evidence the guard is addressing a real path, not a contrived one.

Suggested Improvements

  • 🟢 Suggestion (not a blocker): the two closures are now near-duplicated logic (~15 lines each: snapshot content, compute localHasMovedOn via reference-then-deep-equality check on properties, compute localProperties, Object.assign with the same override shape). Given CLAUDE.md's "no backward compatibility, fix things directly" ethos, a small extracted helper — e.g. applyBackendResponse(localNode, currentNodeSnapshot, backendResponse) returning the merged fields, or performing the assign in place — would remove the duplication and make future changes to this precedence rule (e.g. if a third field ever needs the same protection) a one-place edit instead of two. That said, this is legitimately borderline scope creep for a PR whose stated purpose was "fix two specific bugs, then close the review's follow-up gap" — extracting a helper touches more surface area and risks introducing its own bug in an already look-alike-but-not-identical pair (updateNode()'s version also handles titleChanged notification and typeUpdater vs generic routing that setNode()'s doesn't share verbatim). I'd accept either a follow-up issue or leaving it as-is; I would not block merge on it.

  • 🟢 Suggestion: localHasMovedOn's JSON.stringify deep-equality check assumes deterministic key ordering. properties is typically built by spreading/replacing wholesale (per the code comment), so this is very likely a non-issue in practice, but JSON.stringify is not guaranteed key-order-stable across two objects with the same keys inserted in different orders (e.g. {a:1,b:2} vs {b:2,a:1} stringify differently). If properties is ever reconstructed via a different code path with different key insertion order but equal semantic content, this comparison would spuriously report "moved on" and needlessly discard a backend-confirmed value in favor of an identical local one — low severity since the fallback (keep local) is safe, just occasionally overcautious. Not worth blocking on; flagging for awareness only.

Nitpicks

  • Nit: The localHasMovedOn reference-check (localNode.properties !== currentNode.properties) is redundant with the following JSON.stringify comparison in all cases except a same-reference short-circuit for identity equality — this is a reasonable micro-optimization (skip stringify when nothing changed) but could use a one-word comment (// fast path) since it reads at first glance like two separate checks rather than an optimization of one.

Overall Assessment

This delta directly and correctly addresses the previous review's only "Important" finding, does so with a more thorough root-cause trace than the finding itself asked for (discovering the actual duplicate closure rather than just patching the one the reviewer looked at), and catches a real correctness bug along the way with test evidence, not just assertion. Both prior 🟢 suggestions were also resolved. No new critical or important issues found in this delta. The remaining suggestions (helper extraction, stringify key-ordering) are genuinely optional polish, not correctness risks.

Recommendation: APPROVE

@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.

Re-review of commit eca6063: recommendation is APPROVE (see full report in PR comment above), but posting as --comment because GitHub disallows self-approval on your own PR from the same account.

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