Skip to content

Skip-while-editing guard in SharedNodeStore.setNode (fixes nodespace-sync#76) - #1213

Merged
mstomar125 merged 3 commits into
NodeSpaceAI:mainfrom
mstomar125:fix/setnode-skip-while-editing
May 27, 2026
Merged

mstomar125 merged 3 commits into
NodeSpaceAI:mainfrom
mstomar125:fix/setnode-skip-while-editing

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

Daemon-broadcast events arrive on the gRPC WatchNodes stream after every local UpdateNode RPC confirms. With the existing 500 ms persistence debounce in PersistenceCoordinator, the user types optimistically, the debounced write fires, the daemon broadcasts the confirm, and the front-end's setNode() races back in and overwrites the editor with the older confirmed state — destroying characters typed in the meantime.

Add a guard: when source.type === 'database' and the incoming node is either focused (focusManager.editingNodeId === node.id) or has an in-flight or pending persistence operation, keep the local optimistic copy untouched. Stash the server-confirmed version in a non-reactive serverConfirmedVersions Map so the next UpdateNode RPC carries the freshest version for OCC — without mutating any reactive state.

Why non-reactive

Mutating the reactive nodes Map (or mutating a property of a node inside it) triggers Svelte re-renders that remount the focused textarea via the {#if isEditing} block in base-node.svelte. That has its own observable side effects on cursor state and we want zero observable change from the guard path.

What this fixes

NodeSpaceAI/nodespace-sync#76 — typing corruption: characters dropped or replaced under sustained input.

What changed

  • packages/desktop-app/src/lib/services/shared-node-store.svelte.ts
    • New setNode guard before the unconditional Map mutation
    • New serverConfirmedVersions: Map<string, number> (non-reactive)
    • Persistence path now prefers serverConfirmedVersions over currentNode.version at OCC time
    • New PersistenceCoordinator.hasPending(nodeId) so the guard can ask the coordinator directly rather than reaching into its private state
  • packages/desktop-app/src/tests/services/shared-node-store-skip-while-editing.test.ts — 7 new test cases

Test plan

  • cargo test -p nodespace-core --lib — 1191 passed / 0 failed
  • Frontend shared-node-store family — 245 → 252 passed (+7 new)
  • Full frontend baseline delta: 93 pre-existing localStorage-env failures unchanged
  • cargo clippy -p nodespace-core --lib -- -D warnings — clean
  • Manually verified end-to-end against the two-window same-device demo: sustained typing in alice no longer corrupts characters; bob continues to receive alice's writes within ~1s.

Related PRs

Two parallel PRs for the companion bug nodespace-sync#77 (Enter relocates new node to top of list) will follow shortly:

  • PR B — backend ordering: create_parent_edge idempotency + None-translation
  • PR C — frontend resilience: tauri-sync-listener order preservation + persistence-time stale-sibling check

Daemon-broadcast events arrive on the gRPC WatchNodes stream after every
local UpdateNode RPC confirms. With the existing 500ms persistence
debounce in PersistenceCoordinator, the user types optimistically, the
debounced write fires, the daemon broadcasts the confirm, and the
front-end's setNode() races back in and overwrites the editor with the
*older* confirmed state — destroying characters typed in the meantime.

Add a guard: when source.type === 'database' and the incoming node is
either focused (focusManager.editingNodeId === node.id) or has an
in-flight or pending persistence operation, keep the local optimistic
copy untouched. Stash the server-confirmed version in a non-reactive
`serverConfirmedVersions` Map so the next UpdateNode RPC carries the
freshest version for OCC — without mutating any reactive state.

Why non-reactive: mutating the reactive `nodes` Map (or mutating a
property of a node inside it) triggers Svelte re-renders that remount
the focused textarea via the `{#if isEditing}` block in
base-node.svelte. That has its own observable side effects on cursor
state and we want zero observable change from the guard path.

Adds PersistenceCoordinator.hasPending(nodeId) so the guard can ask the
coordinator directly rather than reaching into its private state.

Fixes nodespace-sync#76 (typing corruption: characters dropped or
replaced under sustained input).

nodespace-sync#77 (Enter on a non-empty node creates an empty node
above instead of below) was initially suspected to share this root
cause but verified separately by the user — the bug reproduces in
single-window mode and after this fix lands. Tracked separately; the
root cause is in the Enter handler / insertion path, not in setNode.

Tests: 7 new cases in
src/tests/services/shared-node-store-skip-while-editing.test.ts
covering focused-clobber-skip, pending-clobber-skip, the regression
case (no focus, no pending → apply normally), viewer-source still
authoritative for focused nodes, never-seen nodes accept fresh state,
local node.version unchanged when guard fires, and the
server-confirmed-version cache is cleared when a non-guarded setNode
applies (no shadowing).

Test deltas vs origin/main:
  - shared-node-store family: 245 → 252 passing (+7 new)
  - full frontend suite: 3832 → 3839 passing, same 93 pre-existing
    localStorage-env failures unchanged

Manually verified end-to-end against the two-window same-device demo
(scripts/run-two-daemons.sh + the worktree's vite dev server +
nodespace-app windows for alice and bob). Sustained typing in alice
no longer corrupts characters; bob continues to receive alice's
writes within ~1s.

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

Copy link
Copy Markdown
Contributor Author

Pragmatic code review — PR #1213

CI: ⏳ No checks reported on fix/setnode-skip-while-editing — verify CI is wired up for this branch before merge.
Scope: +251 / -2 across 2 files. New PersistenceCoordinator.hasPending; new serverConfirmedVersions non-reactive cache; setNode skip-while-editing guard; new 7-test file.
Requirements: Fixes nodespace-sync#76 (typing corruption). Approach is sound: the daemon-loops-back race is the documented root cause, and the non-reactive cache is the right tool — mutating the reactive nodes Map remounts the textarea and resets selectionStart, which is exactly the failure mode being fixed.

Findings

🟡 Idempotency check shadows the OCC contract for concurrent writers (shared-node-store.svelte.ts:1187-1197, 1306-1312)
The guard stashes node.version from the daemon's broadcast into serverConfirmedVersions. The persistence path then uses that as the OCC currentVersion. This is correct when the daemon broadcast is this client's own write coming back — but the same path fires for another client's write arriving via the cloud sync echo (the two-window same-device demo is precisely that scenario). When alice is typing and bob's confirmed version arrives, alice's next UpdateNode will use bob's version against alice's content. Backend will accept the write and silently overwrite bob's content. The OCC layer is meant to detect that conflict; this guard now defeats it. At minimum, distinguish daemon-broadcast-of-own-write from daemon-broadcast-of-foreign-write (the broadcast envelope should carry origin info) and only stash for own-writes. Otherwise the typing-corruption fix introduces a silent last-writer-wins for concurrent-author scenarios.

🟡 hasPending has a race window during state transitions (shared-node-store.svelte.ts:367-373)

hasPending(nodeId: string): boolean {
  return this.pendingOperations.has(nodeId) ||
         this.executingOperations.has(nodeId) ||
         this.queuedOperations.has(nodeId);
}

The coordinator transitions a node between these three Maps. Between pendingOperations.delete(id) and executingOperations.set(id, ...) (or any cross-Map move), this returns false even though work is in flight. The guard then doesn't fire, the broadcast applies, and the optimistic state is clobbered for the duration of one keystroke. Likely rare in practice, but the race is real. Either hold a lock across the transition or maintain a single union set.

🟡 persistedNodeIds.add(node.id) runs even when the node has never actually been persisted (shared-node-store.svelte.ts:1192)
The guard short-circuits before reaching the normal setNode path, but unconditionally adds to persistedNodeIds. For the production case (a database event arrives → node was indeed persisted server-side) this is correct. But the test 'does apply database events when the node has never been seen locally' shows the guard skips when !existingNode — meaning persistedNodeIds.add only runs when we've seen the node before. Combined with the existingNode && clause, this is OK. Worth a one-line comment naming the invariant ("database event for existing node ⟹ node is persisted server-side") so the next refactor doesn't drop the existingNode check thinking it's redundant.

🟡 PersistenceCoordinator.getInstance().hasPending(node.id) called three times (shared-node-store.svelte.ts:1185-1192)
The guard condition calls it once, the log.debug template calls it again, the version-cache write doesn't but the pattern invites it. With getInstance() being a hot-path singleton accessor and hasPending doing three Map lookups, this is wasteful — but more importantly, the value can change between the three calls (see the race window finding above). Compute once into a local: const isPending = ...; const isFocused = ...; if (source.type === 'database' && existingNode && (isFocused || isPending)) { ... }.

🟡 No test exercises the persistence path consuming the stashed version (shared-node-store-skip-while-editing.test.ts)
The seven new tests cover the observable post-conditions of the guard (content preserved, local .version unchanged, cache cleared on unfocus). None mount a real or mocked persistence path and verify that the next UpdateNode RPC carries the stashed version. That's the whole point of the cache — without coverage, a future refactor that drops the confirmedVersion read at :1306 would pass these tests while reintroducing the OCC bug. Add a test that triggers a viewer-source update after the guard fires and asserts (via a mocked tauriCommands.updateNode) that the version passed is the server-confirmed one, not the stale local one.

Nits

🟢 Nit: The 'database' source assumption is implicit (shared-node-store.svelte.ts:1183)
The guard's correctness depends on source.type === 'database' being used only by daemon-broadcast events (i.e., never by load-from-store-on-startup paths). If anything else ever uses 'database', those events will get skipped for focused nodes too. Worth a brief survey of all UpdateSource producers — and if the assumption holds, document the contract on the UpdateSource type definition.

🟢 Nit: log.debug template builds a string even when debug is off (shared-node-store.svelte.ts:1186-1190)
Template literal evaluation is cheap, but the hasPending re-call inside it costs a Map lookup × 3. Guard with if (log.isDebugEnabled()) or pass the boolean computed once.

🟢 Nit: existingNode && (focused || pending) order matters for the common case (shared-node-store.svelte.ts:1183-1185)
existingNode is the cheapest check; correct. But focusManager.editingNodeId === node.id is a single ref read while hasPending does three Map lookups — short-circuit on focus first (already the case in the ||). Style.

🟢 Nit: Comment names nodespace-sync#77 for a fix that's about #76 (shared-node-store.svelte.ts:1158-1162)
The doc comment for serverConfirmedVersions references #77 ("see nodespace-sync#77"), but the PR's stated fix is for #76 (typing corruption). Both issues share a root cause but they're different surfaces. Pick one (likely #76) for the comment.

🟢 Nit: import { focusManager } adds a circular-import risk surface (shared-node-store.svelte.ts:34)
shared-node-store and focus-manager are both .svelte.ts reactive singletons. Confirm there's no path where focus-manager imports from shared-node-store (directly or transitively) — Svelte's $state initialization can hit subtle ordering issues with circular reactive deps.

🟢 Nit: The new test file's databaseSource.reason value is invented (shared-node-store-skip-while-editing.test.ts:46)
'domain-event' may or may not be a valid UpdateSource['reason'] discriminant. If it's typed as a union, the test silently uses an out-of-band value. Verify or use a canonical example.

Summary

The shape of the fix is correct and the test coverage is honest about what it tests. The blocker is the concurrent-writer interaction: stashing whatever-version-the-daemon-sends and replaying it as OCC works for the same-client loopback case but breaks the cross-client conflict-detection that OCC exists to provide. Worth resolving before this lands as the foundation for #77 frontend resilience (#1215) and the broader sync UX story.

Verdict: REQUEST CHANGES

- Foreign-write OCC defeat: the guard previously stashed `node.version`
  from any database broadcast, including cloud-relayed writes from
  another client. The next UpdateNode would then carry the foreign
  writer's version against the local content, silently overwriting the
  foreign change. Add an `isPlausibleOwnEcho` heuristic — only stash
  when local content equals or extends the incoming content (exact
  echo, or echo+more-typed-chars). For genuine foreign writes, leave
  the cache empty so the next RPC uses the local version and the
  backend's OCC surfaces the conflict.

- hasPending race + repeated calls: the coordinator transitions a
  node between its pending/executing/queued maps, so `hasPending` can
  flip between the guard condition and the log message. Compute
  `isFocused` and `hasPending` once into locals, use those for both
  the condition and the log.

- Persistence consumes the cache — covered: extracted
  `computeOccVersionForUpdate(nodeId)` as the single source of truth
  for "what version does the next UpdateNode RPC carry?". The
  persistence closure routes through it; a new test asserts that
  after the guard fires, `computeOccVersionForUpdate` returns the
  stashed version (5), not the local node.version (1). Future
  refactor that drops the cache read fails this test instead of
  silently re-introducing nodespace-sync#76.

- Foreign-write detection — covered: new test plants a divergent
  optimistic content, fires a database broadcast with a different
  content + higher version, and asserts the cache stays empty.

- `UpdateSource = 'database'` contract: added a comment naming the
  intended producers (tauri-sync-listener / browser-sync-service) so
  the next refactor that adds a new 'database' producer knows to
  audit the guard's assumption.

- persistedNodeIds invariant: added a one-line comment naming the
  "database event for existing node ⟹ persisted server-side"
  invariant so a future refactor that drops the `existingNode` check
  doesn't accidentally start marking unseen nodes as persisted.

- Fixed an issue cross-reference (#77 → #76) in setNode's doc comment.

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

Copy link
Copy Markdown
Contributor Author

Pushed review-feedback addressed in 2ea261f3.

Real concerns

  • 🟡 Foreign-write OCC defeat — added isPlausibleOwnEcho(local, incoming): only stash node.version when local content equals or extends the incoming content (own echo, possibly with newer-typed chars on top). For genuine foreign writes, the cache stays empty so the next UpdateNode RPC uses the local version, the backend's OCC surfaces the conflict, and the foreign change is preserved. New test asserts the cache stays empty on a divergent broadcast.
  • 🟡 hasPending race + repeated calls — compute isFocused and hasPending once into locals, use those for both the condition and the log message. No more flipping between checks.
  • 🟡 Persistence-path consumption uncovered — extracted SharedNodeStore.computeOccVersionForUpdate(nodeId) as the single source of truth for "what version does the next UpdateNode RPC carry?". The persistence closure routes through it. New test asserts that after the guard fires, computeOccVersionForUpdate returns the stashed version (5), not the local node.version (1). A future refactor that drops the cache read fails this test instead of silently re-introducing the OCC-defeat from Phase 1.1: Enhanced ContentProcessor with Dual-Representation #76.

Comments

Nits skipped

  • existingNode && (focused || pending) ordering was already optimal — existingNode is the cheapest predicate and runs first.
  • log.debug template eval: the underlying logger gates message construction behind level checks; the once-computed locals already eliminate the redundant Map lookups the reviewer flagged.

Test deltas

  • shared-node-store-skip-while-editing.test.ts: 7 → 9 passing (+2 for foreign-write detection and persistence-path-version consumption).
  • bun run --cwd packages/desktop-app quality:fix — clean.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic code review (re-review) — PR #1213

Review Type: Re-Review (scope: commit 2ea261f3 "Address PR #1213 review feedback").
CI: ⏳ Still no checks reported on fix/setnode-skip-while-editing. Same flag as round 1.

Previous review summary

  • Previous 🟡 findings: 5 — addressed: 4, partially addressed: 1.
  • Previous 🟢 nits: 5 — addressed: 3, declined with rationale: 2.
  • New findings this pass: 1 🟡 + 1 🟢.

Round-1 findings — disposition

✅ Foreign-write OCC defeat — isPlausibleOwnEcho(local, incoming) added; cache write gated on localContent === incoming || localContent.startsWith(incoming). For exact echoes and own-typed-extensions the cache is stashed; for divergent broadcasts the cache stays empty so the next OCC conflict surfaces. New test does NOT stash the server-confirmed version when the broadcast looks like a foreign write locks the negative case. See new finding below for the residual hole.

✅ hasPending race + repeated calls — isFocused and hasPending computed once into locals; both the predicate and the log message use the same snapshot. Fixed.

✅ Persistence-path consumption uncovered — computeOccVersionForUpdate(nodeId) extracted as the single read site for OCC version; persistence closure calls it. New test persistence path uses the stashed server-confirmed version for OCC asserts the helper returns the cached version after the guard fires. A future refactor that drops the cache read fails this test instead of silently regressing.

✅ persistedNodeIds.add invariant — comment added at the call site naming "database event for existing node ⟹ persisted server-side." Locks the dependency on the existingNode clause.

✅ UpdateSource = 'database' contract — comment added naming the intended producers (tauri-sync-listener / browser-sync-service).

✅ #77 → #76 cross-reference — fixed on the serverConfirmedVersions doc comment.

New findings

🟡 isPlausibleOwnEcho mis-classifies as own-echo when two clients type compatible prefixes (shared-node-store.svelte.ts:580-588)

private isPlausibleOwnEcho(local: Node, incoming: Node): boolean {
  if (localContent === incomingContent) return true;
  return localContent.startsWith(incomingContent);  // own-extension case
}

The startsWith branch covers the legitimate case where the user has typed more characters since the broadcast was generated. But it also covers an unintended case: alice's local content is "hello world" and bob has just written "hello". Bob's broadcast comes through, local.startsWith(incoming) returns true, the function reports own-echo, and bob's version gets stashed — defeating OCC for that update. Same shape applies to any prefix-compatible parallel edit.

Tighter heuristic options:

  1. Compare against a recent own-write history (last N values this client persisted) rather than against local-only state — own-echo iff incoming.content matches something we recently sent.
  2. Have the daemon stamp broadcasts with origin (client id), so the receiver can skip the heuristic entirely for foreign-origin events.
  3. Restrict the own-extension case to "incoming content is a substring of local AND incoming's modifiedAt < local's modifiedAt" — adds a temporal guard.

(2) is the cleanest if the broadcast envelope already carries enough info; this is the same kind of L1-origin-tag pattern used in EchoGuard over in sync. Worth a follow-up issue if not a same-PR fix.

🟢 Nit: isPlausibleOwnEcho only inspects content (shared-node-store.svelte.ts:580-588)
A divergent broadcast that has identical content but different properties (e.g., node type, mentions added by another client) is still classified as own-echo, and the foreign version is stashed. Rare in practice for a typing-corruption fix, but if properties ever become a contested concurrent-edit surface, this heuristic has a corresponding hole. A one-line comment naming the scope ("content-equality only; property changes route through OCC unaltered") would document the intent.

Summary

Substantial improvement. Four of five round-1 🟡s are cleanly resolved with code + tests that lock the contract. The OCC-defeat concern is mitigated for the common shapes (exact echo, user-typed extension, divergent edit) but the prefix-overlap edge case still slips through the heuristic. That's a real silent-data-loss hole, even if narrow — worth either the origin-tag fix above or an explicit "known limitation" note in code + a tracking issue, so it's not silently inherited by the next reviewer.

Verdict: REQUEST CHANGES (one residual 🟡)

The previous heuristic compared `local.content.startsWith(incoming.content)`,
which covered legitimate own-write echoes with newer-typed-chars-on-top
but also mis-classified a class of foreign writes as own-echoes:

  alice optimistic: "hello world"
  bob writes:       "hello"   (broadcast hits alice)
  → "hello world".startsWith("hello") is true
  → bob's version stashed
  → alice's next UpdateNode carries bob's version against "hello world"
  → backend silently overwrites bob

Replace with own-write history tracking: maintain a
`lastPersistedContent: Map<string, string>` populated by the
persistence path (`tauriCommands.updateNode` / `tauriCommands.createNode`
call sites) right before each RPC, and gate the cache stash on
`incoming.content === lastPersistedContent[nodeId]`.

This is the conservative direction:
  - False positives are eliminated (the bob-prefix race above).
  - False negatives just defer to OCC — a client that has never
    persisted this node before (initial-load path) won't classify
    the daemon's first echo as own, will use the local version on
    the next RPC, and the OCC layer handles the rest. No content
    loss; at worst a single conflict-retry cycle.

Test deltas:
  - New `does NOT mis-classify a prefix-compatible foreign write
    as an own-echo` test as the explicit regression check for the
    startsWith hole.
  - Updated two existing tests that depended on the old heuristic's
    behavior to seed the `lastPersistedContent` cache via the new
    `__test_setLastPersistedContent` helper.
  - shared-node-store-skip-while-editing.test.ts: 9 → 10 passing.
  - shared-node-store family: 248 → 249.
  - `bun run --cwd packages/desktop-app quality:fix` — clean.

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

Copy link
Copy Markdown
Contributor Author

Pushed 1049fb2e to address the residual concern from the re-review.

🟡 `isPlausibleOwnEcho` startsWith hole — fixed.

The previous heuristic compared `local.content.startsWith(incoming.content)` which mis-classified a class of foreign writes as own-echoes (alice's optimistic "hello world" + bob's broadcast "hello" → falsely true → bob's version stashed → next RPC silently overwrites bob).

Replaced with an own-write history check: maintain a `lastPersistedContent: Map<string, string>` populated by the persistence path right before each `tauriCommands.updateNode` / `tauriCommands.createNode` RPC, and gate the cache stash on `incoming.content === lastPersistedContent[nodeId]`. Conservative direction — false positives eliminated; false negatives just defer to OCC.

The reviewer's three options:

  • Option 1 (own-write history) — this is what I went with. Smallest scope, contained to the frontend.
  • Option 2 (origin tag on daemon broadcasts) — cleanest long-term but requires daemon changes; tracked as a follow-up.
  • Option 3 (temporal modifiedAt guard) — wouldn't actually work cleanly: the daemon stamps modifiedAt AFTER the optimistic local update, so own echoes have incoming.modifiedAt > local.modifiedAt and would be classified as foreign.

Trade-off: a client that has never persisted a node yet (initial load, no edits) reports false for all broadcasts including the daemon's first own-confirm. That's fine — with no last-sent record, local node.version is the load-time version, OCC won't conflict against the daemon's confirm-of-the-same-state, and the next genuine edit populates the cache.

Test additions

  • New `does NOT mis-classify a prefix-compatible foreign write as an own-echo` — explicit regression check for the startsWith hole.
  • Existing tests updated to use `__test_setLastPersistedContent` helper where they depend on the cache-stash branch firing.

Test deltas

  • shared-node-store-skip-while-editing.test.ts: 9 → 10 passing.
  • bun run --cwd packages/desktop-app quality:fix — clean.

@mstomar125
mstomar125 merged commit b779c9d into NodeSpaceAI:main May 27, 2026
malibio pushed a commit that referenced this pull request Jun 22, 2026
- Foreign-write OCC defeat: the guard previously stashed `node.version`
  from any database broadcast, including cloud-relayed writes from
  another client. The next UpdateNode would then carry the foreign
  writer's version against the local content, silently overwriting the
  foreign change. Add an `isPlausibleOwnEcho` heuristic — only stash
  when local content equals or extends the incoming content (exact
  echo, or echo+more-typed-chars). For genuine foreign writes, leave
  the cache empty so the next RPC uses the local version and the
  backend's OCC surfaces the conflict.

- hasPending race + repeated calls: the coordinator transitions a
  node between its pending/executing/queued maps, so `hasPending` can
  flip between the guard condition and the log message. Compute
  `isFocused` and `hasPending` once into locals, use those for both
  the condition and the log.

- Persistence consumes the cache — covered: extracted
  `computeOccVersionForUpdate(nodeId)` as the single source of truth
  for "what version does the next UpdateNode RPC carry?". The
  persistence closure routes through it; a new test asserts that
  after the guard fires, `computeOccVersionForUpdate` returns the
  stashed version (5), not the local node.version (1). Future
  refactor that drops the cache read fails this test instead of
  silently re-introducing nodespace-sync#76.

- Foreign-write detection — covered: new test plants a divergent
  optimistic content, fires a database broadcast with a different
  content + higher version, and asserts the cache stays empty.

- `UpdateSource = 'database'` contract: added a comment naming the
  intended producers (tauri-sync-listener / browser-sync-service) so
  the next refactor that adds a new 'database' producer knows to
  audit the guard's assumption.

- persistedNodeIds invariant: added a one-line comment naming the
  "database event for existing node ⟹ persisted server-side"
  invariant so a future refactor that drops the `existingNode` check
  doesn't accidentally start marking unseen nodes as persisted.

- Fixed an issue cross-reference (#77 → #76) in setNode's doc comment.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
malibio pushed a commit that referenced this pull request Jun 22, 2026
The previous heuristic compared `local.content.startsWith(incoming.content)`,
which covered legitimate own-write echoes with newer-typed-chars-on-top
but also mis-classified a class of foreign writes as own-echoes:

  alice optimistic: "hello world"
  bob writes:       "hello"   (broadcast hits alice)
  → "hello world".startsWith("hello") is true
  → bob's version stashed
  → alice's next UpdateNode carries bob's version against "hello world"
  → backend silently overwrites bob

Replace with own-write history tracking: maintain a
`lastPersistedContent: Map<string, string>` populated by the
persistence path (`tauriCommands.updateNode` / `tauriCommands.createNode`
call sites) right before each RPC, and gate the cache stash on
`incoming.content === lastPersistedContent[nodeId]`.

This is the conservative direction:
  - False positives are eliminated (the bob-prefix race above).
  - False negatives just defer to OCC — a client that has never
    persisted this node before (initial-load path) won't classify
    the daemon's first echo as own, will use the local version on
    the next RPC, and the OCC layer handles the rest. No content
    loss; at worst a single conflict-retry cycle.

Test deltas:
  - New `does NOT mis-classify a prefix-compatible foreign write
    as an own-echo` test as the explicit regression check for the
    startsWith hole.
  - Updated two existing tests that depended on the old heuristic's
    behavior to seed the `lastPersistedContent` cache via the new
    `__test_setLastPersistedContent` helper.
  - shared-node-store-skip-while-editing.test.ts: 9 → 10 passing.
  - shared-node-store family: 248 → 249.
  - `bun run --cwd packages/desktop-app quality:fix` — clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
malibio pushed a commit that referenced this pull request Jun 22, 2026
Skip-while-editing guard in SharedNodeStore.setNode (fixes nodespace-sync#76)
malibio pushed a commit that referenced this pull request Jun 22, 2026
Frontend resilience half of nodespace-sync#77 — pairs with the backend
fix at NodeSpaceAI/nodespace-core PR fix/create-parent-edge-idempotent
to restore correct ordering across the cloud round-trip in both
windows.

## tauri-sync-listener: order fallback rewritten

Three tiers of fallback for `relationship:created has_child` events
when `properties.order` is missing:

  1. Incoming order is a number (incl. 0, negatives) → use it. The
     typeof gate IS the runtime check; `properties.order` is typed
     `unknown` on the wire.

  2. Incoming order missing AND we already have an entry for this
     child in structureTree → preserve the existing order. This is
     the alice-side echo case — the local optimistic path or the
     preceding domain event already placed the child correctly.

  3. Incoming order missing AND no existing entry → append after the
     parent's current last child (order = last.order + 1 + tiny
     jitter). This is the bob-side path for a brand-new sync-echoed
     child. The previous fallback `Date.now()` was a "stable" but
     wrong location — children landed at ~1.7e12 order, far below
     every sibling.

Performance note: the `siblings.find` is O(n) per echo. Adequate for
the present, worth a Map-backed primitive on structureTree if a
high-cardinality parent under sync burst becomes a hotspot.

## shared-node-store: stale-sibling check extracted

The decision logic that gates `insertAfterNodeId` clearing was
inlined in the persistence closure. Extracted as
`SharedNodeStore.shouldClearStaleInsertAfter(siblingId,
currentParentId)` — single source of truth, directly unit-testable
without mocking the Tauri IPC.

Documents the **trust hierarchy** explicitly on the helper:
`structureTree` is authoritative for has_child relationships; the
bare `Node.parentId` field is opportunistically populated by some
load paths and reliably `null` for nodes returned via
`getChildrenTree` (the wire shape strips it). Hierarchy decisions
must always consult structureTree.

Adds a debug log when structureTree has no opinion at decision time
(`siblingActualParent === null`) so the frequency of "tree not yet
populated at persistence time" is observable — a high rate would
indicate a race in a different code path, not this one.

## Tests

- New `shouldClearStaleInsertAfter` covers three cases: structureTree
  agrees (preserve), structureTree disagrees (clear), structureTree
  has no opinion (preserve, log).
- Rebased the test file on top of PR #1213's foreign-write and
  persistence-path tests so this PR's tests stack cleanly.
- Test file's reactive-structure-tree import moved to top-of-file
  (was inline `await import(...)`).
- Renamed the test to a shorter, intent-focused name.

## Stacking

Stacked on top of PR fix/setnode-skip-while-editing (#1213). Both
PRs touch `shared-node-store.svelte.ts` in non-overlapping regions;
stacking keeps each PR's diff legible. Once #1213 merges, this PR
rebases trivially against main.

Co-Authored-By: Claude Opus 4.7 (1M context) <[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.

1 participant