Skip to content

Extract an explicit remote-update policy from the skip-while-editing logic - #1608

Merged
malibio merged 1 commit into
mainfrom
worktree-issue-1512-remote-update-policy
Jul 10, 2026
Merged

malibio merged 1 commit into
mainfrom
worktree-issue-1512-remote-update-policy

Conversation

@malibio

@malibio malibio commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator

Closes #1512

…loses #1512)

The skip-while-editing conflict policy was inlined in both setNode and
batchSetNodes, branching on editing state, own-echo detection, and
ai-chat message-count heuristics duplicated across both call sites.
Extract decideRemoteUpdate / shouldSkipStaleAiChatUpdate into
remote-update-policy.ts as pure functions with their own unit tests;
setNode and batchSetNodes now call the shared unit instead of
inlining the policy. Behavior is unchanged (existing skip-while-editing
suite and full frontend suite pass).

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

malibio commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: Extract remote-update policy from skip-while-editing logic

Review Type: Initial Review
Issue: #1512 — "Extract an explicit remote-update policy from the skip-while-editing logic"

Requirements Check

  • Remote-update decision logic extracted into a tested unit — remote-update-policy.ts exposes decideRemoteUpdate, isPlausibleOwnEcho, shouldSkipStaleAiChatUpdate
  • setNode calls the unit rather than inlining the policy — confirmed
  • batchSetNodes also migrated (not explicitly required by the AC text but was duplicated inline before, and the issue's problem statement calls out both call sites)
  • Code passes bun run quality:fix; tests pass — CI green (test:all and test:e2e both pass, see below)

All acceptance criteria met. Single, atomic commit; correctly scoped to the extraction only.

Overall Assessment

This is a clean, well-executed pure extraction. I verified the two highest-risk behavior-parity items line-by-line against origin/main's prior inline implementation, and both are preserved exactly:

1. notifyConflict asymmetry — preserved correctly. decideRemoteUpdate() returns a notifyConflict field. setNode() (shared-node-store.svelte.ts:1511) reads it and raises the deduped conflictNotifications toast, matching the original inline behavior. batchSetNodes() (shared-node-store.svelte.ts:1830-1845) computes the same decision but never reads decision.notifyConflict — it only acts on decision.stashVersion, exactly mirroring the original's asymmetry where batch operations silently skip without notifying. The author even left an explicit comment calling this out as intentional pre-existing behavior, not an oversight. This is exactly right and was the highest-risk item in this PR — a silent unification in either direction would have been a real regression despite looking like harmless cleanup.

2. isPlausibleOwnEcho semantics — preserved verbatim. Old: lastSent === (incoming.content ?? '') (strict equality). New: lastSentContent === (incoming.content ?? '') (same strict equality, just parameterized instead of reading this.lastPersistedContent directly). The regression-guarding comment about the old startsWith false-positive bug was carried forward into both the module doc comment and a dedicated test case ('returns false for a prefix-compatible but different foreign write (not a startsWith heuristic)'). No semantic drift.

3. Test coverage delta — real, not redundant. shared-node-store-skip-while-editing.test.ts is byte-for-byte unchanged (confirmed via diff — zero changes). The new remote-update-policy.test.ts unit-tests the pure functions directly, including cases that are awkward to hit through the store-level integration test: the notifyConflict/stashVersion field values in isolation for both the own-echo and foreign-write branches, an explicit non-Node.version-as-number case, and the startsWith-regression guard as a pure-function assertion. This is incremental value, not restated coverage.

4. Extraction quality. remote-update-policy.ts imports only Node and UpdateSource as types — no Svelte reactivity, no focusManager, no PersistenceCoordinator leak in. Both call sites now share one code path with no leftover duplicated branching (the old private isPlausibleOwnEcho method and its startsWith comment block were fully deleted, not left dead). Function/field naming (decideRemoteUpdate, RemoteUpdateDecision.apply/stashVersion/notifyConflict, EditingState) is clear and reads naturally at both call sites.

5. CI. gh pr checks 1608: test:all (frontend + skill + Rust) — pass (2m41s); test:e2e (headless daemon) — pass (1m34s). PR is MERGEABLE.

Findings

Critical Issues

None.

Suggested Improvements

None — this PR does exactly what the issue asked, nothing more, nothing less.

Nitpicks

  • Nit: remote-update-policy.ts — the RemoteUpdateDecision discriminated union's apply: false branch always carries stashVersion/notifyConflict as mutually exclusive booleans (stashVersion === !notifyConflict in every observed path). Not a defect, just worth knowing there's an implicit invariant here if a third case is ever added later (e.g. "foreign write, don't notify") — the type doesn't currently prevent both being set independently even though today's logic never does that.
  • Nit: shared-node-store.svelte.ts:1839 comment says "Mirrors setNode's decision, but batchSetNodes does not raise conflict notifications (pre-existing behavior, unchanged here)" — good, this is exactly the kind of "why" comment that should exist given how easy it'd be for a future editor to "fix" this asymmetry by accident. Worth keeping as a permanent guardrail comment, not typical churn to trim later.

Triage Matrix

Severity Count
Critical 0
Improvement 0
Nit 2

Recommendation: APPROVE

Pure, atomic, behavior-preserving extraction that fully satisfies issue #1512's acceptance criteria. The two highest-risk correctness traps called out in review scope (notifyConflict asymmetry, own-echo equality semantics) were both verified preserved exactly against the pre-refactor code. New unit tests add genuine incremental coverage rather than restating the existing integration suite. CI is green.

@malibio

malibio commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1608 — Extract remote-update policy from skip-while-editing logic

Note on process: This is an independent second-party review. A prior review comment already exists on this PR, posted under the same account that authored the code — I did not take its claims (CI status, behavior-parity conclusions) at face value and re-verified everything below from the actual diff, actual file contents at both refs, and by actually running the test suite myself in an isolated worktree (/tmp/pr1608-review, cleaned up after).

Summary

This is a clean, behavior-preserving extraction. packages/desktop-app/src/lib/services/remote-update-policy.ts pulls the skip-while-editing conflict policy (previously inlined and duplicated across setNode and batchSetNodes) into three pure functions: decideRemoteUpdate, isPlausibleOwnEcho, shouldSkipStaleAiChatUpdate. Both call sites in shared-node-store.svelte.ts now delegate to the shared module; the old private isPlausibleOwnEcho method and inline branching were fully deleted, not left as dead code.

Verification of the four specific risk areas

1. conflictNotifications asymmetry — preserved correctly.
Confirmed by reading both refs' full source, not just the diff. decideRemoteUpdate() returns a notifyConflict field on the apply: false branch. setNode() (new shared-node-store.svelte.ts:1511) reads decision.notifyConflict and raises the deduped conflictNotifications.add(...) toast — matching old inline behavior exactly (old line ~1580-1589). batchSetNodes() (new shared-node-store.svelte.ts:1823-1845) computes the identical decision object but only reads decision.stashVersion; it never touches decision.notifyConflict, exactly mirroring the old batchSetNodes which never called conflictNotifications.add at all (confirmed old batchSetNodes source has zero occurrences of conflictNotifications). The author left an explicit comment at shared-node-store.svelte.ts:1838-1839 calling this out as intentional, pre-existing, unchanged behavior. No regression in either direction.

2. isPlausibleOwnEcho semantics — preserved verbatim.
Old (private method, shared-node-store.svelte.ts:733-736 on main):

private isPlausibleOwnEcho(_local: Node, incoming: Node): boolean {
  const lastSent = this.lastPersistedContent.get(incoming.id);
  if (lastSent === undefined) return false;
  return lastSent === (incoming.content ?? '');
}

New (pure function, remote-update-policy.ts:57-60):

export function isPlausibleOwnEcho(incoming: Node, lastSentContent: string | undefined): boolean {
  if (lastSentContent === undefined) return false;
  return lastSentContent === (incoming.content ?? '');
}

Identical strict-equality semantics — only the lookup was hoisted to the caller (this.lastPersistedContent.get(node.id) passed in as a parameter instead of read internally), which is a correct and desirable side effect of making the function pure/testable. Note the old inline comment at the setNode call site (old line 1563-1564: "if the existing optimistic content equals or starts with the incoming content...") was misleading relative to the actual implementation, which was always strict equality, never startsWith. The new code fixes this stale/incorrect comment and explicitly documents the historical startsWith false-positive bug (alice/bob example) in the module doc comment, and pins it with a dedicated regression test ('returns false for a prefix-compatible but different foreign write (not a startsWith heuristic)'). This is a genuine improvement, not just a lift-and-shift.

3. Tests actually run and passed by me.
I created an isolated worktree at /tmp/pr1608-review off origin/worktree-issue-1512-remote-update-policy (outside the repo's normal worktree directories, removed afterward), ran bun install, and executed:

  • Full frontend suite (bun run test): 157 test files, 4009 tests, all passed (46.52s).
  • Targeted run of the two files in scope (bun run test -- remote-update-policy shared-node-store-skip-while-editing): 2 files, 38 tests, all passed (20 in the skip-while-editing integration suite, 18 in the new pure-function suite).
  • shared-node-store-skip-while-editing.test.ts diff against origin/main: confirmed zero changes (byte-for-byte identical) — it's exercising the same behavior end-to-end through the store, post-refactor, and still passes.
  • quality:check (eslint + svelte-check) in packages/desktop-app: 0 errors, 0 warnings across 1753 files.
  • Also independently confirmed gh pr checks 1608: test:all pass (2m41s), test:e2e pass (1m34s) — matches what CI reports, verified via the gh CLI myself rather than trusting the prior comment's claim.

4. Test coverage delta — real, incremental value, not redundant.
remote-update-policy.test.ts (18 tests) exercises the pure functions directly with cases that are awkward or impossible to hit cleanly through the store-level integration test: the exact stashVersion/notifyConflict field values in isolation for both the own-echo and foreign-write branches, an explicit "incoming node with no numeric version" edge case, viewerSource/no-existing-node/not-actively-edited short-circuit paths, and the startsWith-regression guard as a direct pure-function assertion rather than an indirect store-behavior inference. shared-node-store-skip-while-editing.test.ts (unchanged, 20 tests) continues to validate the end-to-end wiring (focus manager, persistence coordinator, actual store mutations). These are complementary, not overlapping — verdict: genuine incremental coverage.

Findings

Critical Issues

None.

Suggested Improvements

None blocking. One observation below is a nit, not a blocker.

Nitpicks

  • Nit (remote-update-policy.ts:87-88 vs. shared-node-store.svelte.ts:1508 and :1840): decideRemoteUpdate already gates stashVersion internally on typeof incoming.version === 'number', but both call sites re-check typeof node.version === 'number' again before writing to serverConfirmedVersions. Harmless (the check is trivially true whenever stashVersion is true), but it's belt-and-suspenders duplication that slightly obscures that stashVersion is already a complete, sufficient guard. Could drop the redundant typeof check at the call sites in a future pass, but not worth doing now — it doesn't affect correctness and removing it purely for its own sake isn't warranted mid-review.
  • Nit: RemoteUpdateDecision's apply: false branch carries stashVersion/notifyConflict as two independent booleans that are always mutually exclusive in practice (stashVersion === !notifyConflict in every code path today). A discriminated union (e.g. { apply: false, reason: 'own-echo' } | { apply: false, reason: 'foreign-write' }) would make that invariant structurally enforced rather than implicit. Not a defect — today's two call sites can't violate it — just worth knowing if a third case is ever added (e.g. "foreign write, don't notify").
  • Nit: EditingState/module docstring calls out that the caller must compute isFocused/hasPending once and pass them in (to avoid double-reads racing against the coordinator's internal map transitions) — this is a real, subtle invariant carried over correctly from the original inline comment, but it's easy for a future caller of decideRemoteUpdate to violate silently since nothing in the type signature enforces "compute once." Not asking for a change, just flagging as a sharp edge inherent to the design (also present in the original code, not introduced by this PR).

Architecture/SRP Assessment

Clean extraction. The new module imports only Node and UpdateSource as types — no Svelte reactivity, no focusManager, no PersistenceCoordinator dependency leaked in, which is exactly what "pure and testable" should look like. Both call sites converge on one code path with no leftover duplicated branching logic. Naming (decideRemoteUpdate, RemoteUpdateDecision.apply/stashVersion/notifyConflict, EditingState) is clear and reads naturally at both call sites. The commit is single and atomic — scoped only to the extraction, no unrelated changes bundled in. Performance impact is negligible: the functions are cheap (a handful of comparisons, no allocations beyond the small returned object), called on the same hot paths as before.

Recommendation: APPROVE

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.

Extract an explicit remote-update policy from the skip-while-editing logic

1 participant