diff --git a/.kiln/work/20261121-stop-app-s-own-overlapping-saves/brief.md b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/brief.md new file mode 100644 index 0000000..8afa294 --- /dev/null +++ b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/brief.md @@ -0,0 +1,26 @@ +# Brief — the app's own overlapping saves no longer show a false conflict + +Follows spike 20261121-review-each-items-above-one-one, findings F1 and F2 (audit item 1). + +## What is asked +- Who: the owner, who sees "This note was also edited in another window…" when no other window exists. +- What: a change event from this window's own save must never be merged as another window's edit. +- Why now: the spike reproduced it; fast note moves (holding Alt+Down) trigger it. +- Success: a save that finishes after a newer save of the same note started is recognised as this window's own; no merge, no toast, no duplicated paragraph. +- Constraint: the user's answer to "Will Notelet ever run a second window?" was "Yes, maybe later" — keep the cross-window merge (`merge.js`, `acceptRemote`) and fix the own-save check in place. + +## What I found +- `extension/app.js:365-367` `persist` records only the latest JSON per note in `written` (`Map`). +- `extension/app.js:540` `acceptRemote` treats an event as own only when it equals that latest JSON. +- `extension/desktop.js:24-28`: each write fires its change event after its own save finishes and before its promise resolves. A first save still in flight when a second persist runs has its event compared against the second's JSON, so it reads as foreign. +- Every save path goes through `persist` (app.js:360, 389, 413, 462, 495, 710), so one fix covers all of them. +- `app.js` cannot be imported in Node (it reads `window.__TAURI__` at load), so the own-save tracking needs to live in a module the tests can import. + +## Still unknown +- None blocking. + +## Past learnings +- None: no learnings store (`.kiln/learnings/` does not exist), recall not run. + +## Design (bounded: two sentences) +Track every version of a note this window has in flight, not only the latest, and release each one when its save settles; the change event for any in-flight version is this window's own. The tracker is a small export beside the merge code in `extension/merge.js`, used by `persist` and `acceptRemote` in `app.js`. diff --git a/.kiln/work/20261121-stop-app-s-own-overlapping-saves/ledger.md b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/ledger.md new file mode 100644 index 0000000..65f70c5 --- /dev/null +++ b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/ledger.md @@ -0,0 +1,6 @@ +Pre-flight: no shared interfaces +Task 1: Step 2 matched (does not provide an export named createOwnSaves). +Task 1: regression proved: isOwn reduced to the latest version -> 2 fail; restored -> 13/13. +Task 1: complete (tests: node --test "tests/*.test.js" -> exit 0, 217 pass) +Ruling: recorded with --phase full, since the project has no fast phase - cost if wrong: none. +Ruling: the race test also covers the failed-save row in the same test rather than a fourth test - cost if wrong: one less-specific test name. diff --git a/.kiln/work/20261121-stop-app-s-own-overlapping-saves/plan.md b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/plan.md new file mode 100644 index 0000000..30db690 --- /dev/null +++ b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/plan.md @@ -0,0 +1,107 @@ +# Own overlapping saves — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: use kiln-implement to work this plan task by task. Steps use checkbox (`- [ ]`) syntax, and a checked box is a claim kiln re-checks rather than believes. + +**Goal:** A change event from any save this window still has in flight is recognised as its own, so it is never merged as another window's edit. + +**Architecture:** Replace `written` (latest JSON per note) with a tracker that holds every in-flight version per note and drops each when its save settles. The change event fires before the save's promise settles (`desktop.js:24-28`), so the version is still held when its event arrives. + +**Tech Stack:** plain ES modules, `node:test`. + +**Spec:** `.kiln/work/20261121-stop-app-s-own-overlapping-saves/brief.md` + +## Global Constraints + +- Keep `merge.js`'s merge functions and `acceptRemote`; the user may add a second window later. +- No new file, no new dependency. + +## Risk flags + +- none + +## I/O & Edge-Case Matrix + +| Scenario | Input / State | Expected Output / Behavior | Error Handling | +|----------|---------------|----------------------------|----------------| +| Overlap | save v1 in flight, save v2 starts, v1's event arrives | v1's event is own | n/a | +| Last save | v2's event arrives | own | n/a | +| Settled | both saves settled | neither version is held | n/a | +| Failed save | the save rejects | its version is released, nothing held | the caller's `.catch` still runs | +| Same JSON twice | the same note version saved twice | still own until both settle | n/a | +| Foreign | a version never saved here | not own | n/a | + +## Review Focus + +- A save that never settles (Rust hangs) keeps its version held; harmless, since only an identical foreign version would be misread. No test. +- `importNotes` awaits `persist`; its rejection must still reach `reportImportError` after the release. Covered by the failed-save row. + +--- + +### Task 1: In-flight own-save tracker, wired into the app + +**Files:** +- Modify: `extension/merge.js` (add `createOwnSaves`) +- Modify: `extension/app.js:48`, `:365-367`, `:540` +- Test: `tests/merge.test.js` + +**Acceptance:** +- Every matrix row passes as a test. +- `app.js` has no `written` map; `persist` and `acceptRemote` use the tracker. + +**Verification:** `node --test "tests/*.test.js"` → `# fail 0`. +**Depends on:** none · **Size:** S + +**Interfaces:** +- Produces: `createOwnSaves(): { track(notes: Note[]): () => void, isOwn(note: Note): boolean }` in `extension/merge.js`. `track` holds one copy of each note's `JSON.stringify` and returns a function that releases exactly those copies. + +- [ ] **Step 1: Write the failing tests in `tests/merge.test.js`** + +```js +test("an older save that finishes after a newer one started is still this window's own", async () => { + const saves = createOwnSaves(); + const v1 = { id: "n", position: 90 }; + const v2 = { id: "n", position: 80 }; + const release1 = saves.track([v1]); + const release2 = saves.track([v2]); + assert.equal(saves.isOwn(v1), true); + release1(); + assert.equal(saves.isOwn(v2), true); + release2(); + assert.equal(saves.isOwn(v1), false); + assert.equal(saves.isOwn(v2), false); +}); + +test("the same version saved twice stays own until both saves settle; a version never saved is not own", () => { + const saves = createOwnSaves(); + const v = { id: "n", position: 1 }; + const first = saves.track([v]); + const second = saves.track([v]); + first(); + assert.equal(saves.isOwn(v), true); + second(); + assert.equal(saves.isOwn(v), false); + assert.equal(saves.isOwn({ id: "n", position: 2 }), false); +}); + +test("with the real file area, an overlapping older save's change event is recognised as own", async () => { + // createFileArea + createStore with a 30 ms save; persist v1, then v2 after 10 ms; + // record isOwn(remote) for every event; expect [true, true]. + // A save that rejects releases its version: invoke rejects, isOwn(v) false after the catch. +}); +``` + +The third test fills in the comments as code, using `createFileArea` (`../extension/desktop.js`) and `createStore` (`../extension/store.js`), with persist written as `const release = saves.track(notes); return store.saveNotes(notes).finally(release);`. + +- [ ] **Step 2: Run them to see them fail** + +Run: `node --test tests/merge.test.js` +Expected: FAIL with `SyntaxError` / `createOwnSaves` not exported + +- [ ] **Step 3: Implement `createOwnSaves()` in `extension/merge.js`; in `app.js` replace `written` with `const ownSaves = createOwnSaves();`, make `persist` `const release = ownSaves.track(changed); return store.saveNotes(changed).finally(release);`, and make `acceptRemote`'s check `if (ownSaves.isOwn(remote)) return null;`** + +The per-note store is `Map`; release removes one matching copy per note and deletes the key when its list is empty. + +- [ ] **Step 4: Run the tests to see them pass** + +Run: `node --test "tests/*.test.js"` +Expected: `# fail 0`, three more tests than the 214 baseline (217) diff --git a/.kiln/work/20261121-stop-app-s-own-overlapping-saves/release.md b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/release.md new file mode 100644 index 0000000..14e30c2 --- /dev/null +++ b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/release.md @@ -0,0 +1,22 @@ +# 20261121-stop-app-s-own-overlapping-saves — no false conflict from the app's own saves + +## Change +- Fixed: moving or editing a note quickly no longer shows "This note was also edited in another window", and no longer duplicates a paragraph, when no other window exists. + +## Before release +- [x] The change carries no migration and reads no new configuration value. (checked) +- [x] `kiln verify` ran the full unit suite: exit 0, 217 of 217 pass on Node 22.17.1. (checked) +- [x] The regression test fails with the fix undone (2 fail) and passes with it. (checked) +- [ ] In the desktop app, holding Alt+Down on a note in the list shows no conflict message. (confirm) + +## Release steps +1. Merge the pull request once CI is green. +2. Ship it in the next release as usual. + +## After release +- [ ] After updating, fast note moves and edits show no "edited in another window" message. (confirm) + +## Rollback +- Trigger: notes edited in Notelet stop saving, or the conflict message appears more often than before. +- Steps: `git revert` the merge commit, then open and merge that pull request, then release. +- Time: one revert pull request and one release. diff --git a/.kiln/work/20261121-stop-app-s-own-overlapping-saves/review.md b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/review.md new file mode 100644 index 0000000..dff93a5 --- /dev/null +++ b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/review.md @@ -0,0 +1,45 @@ +# Review — 20261121-stop-app-s-own-overlapping-saves + +lenses: reviewer reported, blind-hunter reported, edge-case-hunter reported, verification-gap reported, intent-alignment reported, code-review-specialist reported, security-auditor reported, test-engineer reported + +Scope — predicted 3 · actual 3 + +Rules: no rule is routed to this change, so there is no checklist. + +Bar: nothing lowers the bar. + +## Triage log + +| # | Reader(s) | Location | Finding | Verdict | Grade | Route | +|---|---|---|---|---|---|---| +| 1 | verification-gap, reviewer, code-review, intent, blind, test-engineer | tests/merge.test.js (third test), extension/app.js persist / acceptRemote | the integration test uses its own copy of `persist`; a regression in app.js's two wiring lines would pass the suite | real: no test imports app.js (it reads `window.__TAURI__` at load) | Important · Unlikely | note | +| 2 | edge-case, reviewer, code-review, blind, test-engineer | extension/merge.js `release` | `splice(indexOf(...), 1)` removes the last version when `indexOf` is -1 | real but unreachable: each release closure runs once, from `.finally` | Minor · Unlikely | drop | +| 3 | security, intent, blind, code-review, edge-case, test-engineer | extension/merge.js comment; extension/desktop.js:24-28 | correctness depends on the change event firing before the save settles; a future storage area that fires later would misread own saves | real dependency; holds for the only area the app uses; the third test fails if desktop.js changes that order | Minor · Unlikely | note | +| 4 | reviewer, blind, test-engineer | extension/app.js acceptRemote | an event matching an already-settled own save is now classed as foreign | unreachable today: the file area never fires after settle; with local equal to remote the merge reports no conflict | Minor · Unlikely | drop | +| 5 | blind, test-engineer | tests/merge.test.js third test | overlap forced by 10 ms vs 30 ms timers; a late timer would still pass without overlapping | real: the assertions would hold without overlap | Minor · Possible | note | +| 6 | blind, test-engineer | tests/merge.test.js | untested: failure mid-overlap, multi-note partial overlap, an id never tracked, double release | real gaps in edge cases of a 15-line helper | Minor · Unlikely | drop | +| 7 | blind | extension/store.js saveMigration | migration note writes are not tracked as own | false: the migration runs inside `store.load()` (app.js:76), before `store.onChange` is registered (app.js:95) | false | drop | +| 8 | reviewer, code-review, blind | extension/merge.js placement | own-save tracking is bookkeeping, not merging | plan's decision, beside the code that reads it | — | drop | +| 9 | blind | extension/app.js `const ownSaves` | the call site lost its comment | the name says what it is; the why is on the helper | — | drop | +| 10 | blind, intent | .gitignore | kiln line not in the diff | kiln setup, not this change | — | declined to judge | +| 11 | test-engineer | end to end | no test asserts "no toast, no merge" in the app | same root as 1 | — | note (with 1) | + +## Fixed + +None: no finding landed in a fix-now cell. + +## Rulings + +- Ruling: finding 1 is not fixed here — app.js cannot be imported in Node, and moving the save sequence into merge.js (`ownSaves.save(store, notes)`) adds surface the plan did not name; the two wiring lines were read by six readers and match the tested copy — cost if wrong: a later edit to persist could bring the false conflict back unnoticed. + +## Deferred + +- Move the track-save-release sequence into one exported helper so the test exercises the shipped code (finding 1, 11). +- Replace the timer-forced overlap with deferred promises the test resolves itself (finding 5). +- If a second window or another storage area arrives, revisit the event-before-settle dependency (finding 3). + +## Declined to judge + +- The `.gitignore` kiln line and `.kiln/`: kiln setup, not this change. +- Empty read-only dotfiles at the repo root: sandbox placeholders. +- e2e tests and the real Tauri app: not run in this session. diff --git a/.kiln/work/20261121-stop-app-s-own-overlapping-saves/state.json b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/state.json new file mode 100644 index 0000000..a8eb3b3 --- /dev/null +++ b/.kiln/work/20261121-stop-app-s-own-overlapping-saves/state.json @@ -0,0 +1,144 @@ +{ + "schema_version": 1, + "id": "20261121-stop-app-s-own-overlapping-saves", + "follows": "20261121-review-each-items-above-one-one", + "status": "shipped", + "session_id": "0b73138a-cf32-4ba7-ac23-30a61cd6d8d6", + "path": "bounded", + "type": "fix", + "auto": false, + "stage": "VERIFY", + "step": null, + "gates": { + "plan": { + "decision": "approved", + "artifact_sha": "7d9fe55fcf334df55d33ce17b4db3be96ada5d86c25582b5b728c0b8afa942d5", + "answer": "ruled by auto mode, not by the user", + "by": "auto", + "at": "2026-11-21T06:51:50.294Z" + }, + "review": { + "decision": "approved", + "artifact_sha": "25d3e6ec852d66e7728f6d4d04c60568fa4beaf44ae3d90ec7eb31dc8957c579", + "answer": "ruled by auto mode, not by the user", + "by": "auto", + "at": "2026-11-21T06:55:37.756Z" + } + }, + "predicted": [ + { + "path": "extension/merge.js" + }, + { + "path": "extension/app.js" + }, + { + "path": "tests/merge.test.js" + } + ], + "base": "10da06c82d4f1920b2252dcdac2559cc86786f8f", + "last_verified": "10da06c82d4f1920b2252dcdac2559cc86786f8f", + "dirty_at_open": [ + ".gitignore" + ], + "verify": [ + { + "id": "unit", + "cmd": "node --test \"tests/*.test.js\"", + "exit": 0, + "ms": 5433, + "range": "10da06c82d4f1920b2252dcdac2559cc86786f8f..10da06c82d4f1920b2252dcdac2559cc86786f8f", + "phase": "full", + "tree": "dfd84b0caf6f2e8dc57092c59b0489487d5042ef" + }, + { + "id": "unit", + "cmd": "node --test \"tests/*.test.js\"", + "exit": 0, + "ms": 5474, + "range": "10da06c82d4f1920b2252dcdac2559cc86786f8f..10da06c82d4f1920b2252dcdac2559cc86786f8f", + "phase": "full", + "tree": "1e6758a296afee43e620ed1fedb1b2f870ed462c" + }, + { + "id": "unit", + "cmd": "node --test \"tests/*.test.js\"", + "exit": 0, + "ms": 3504, + "range": "10da06c82d4f1920b2252dcdac2559cc86786f8f..10da06c82d4f1920b2252dcdac2559cc86786f8f", + "phase": "full", + "tree": "1e6758a296afee43e620ed1fedb1b2f870ed462c" + } + ], + "pass": 1, + "carry_over": [], + "displaced": [], + "rules": [ + { + "stage": "plan", + "files": [] + }, + { + "stage": "review", + "files": [] + } + ], + "knowledge": [], + "practices": [ + { + "stage": "investigate", + "ids": [] + }, + { + "stage": "plan", + "ids": [ + "planning-and-task-breakdown" + ] + }, + { + "stage": "implement", + "ids": [ + "incremental-implementation", + "test-driven-development", + "source-driven-development" + ] + }, + { + "stage": "review", + "ids": [ + "reviewer", + "blind-hunter", + "edge-case-hunter", + "verification-gap", + "intent-alignment", + "code-review-specialist", + "security-auditor", + "test-engineer" + ] + } + ], + "snapshots": [ + { + "name": "task/0", + "commits": { + ".": "d33df44be979450af2a7798e545b8f5a403765d8" + }, + "at": "2026-11-21T06:51:50.325Z" + }, + { + "name": "task/1", + "commits": { + ".": "199b485d772b1cd8e190bc70ae71150b17199460" + }, + "at": "2026-11-21T06:52:52.304Z" + } + ], + "baseline": null, + "checklist": [], + "opened": [ + "https://github.com/ttncode/notelet/pull/104" + ], + "branches": { + ".": "fix/20261121-stop-app-s-own-overlapping-saves" + } +} diff --git a/extension/app.js b/extension/app.js index 9d5f189..cad7c0d 100644 --- a/extension/app.js +++ b/extension/app.js @@ -10,7 +10,7 @@ import { formatEditedDate } from "./format.js"; import { applyShortcutTitles, matchHotkey, setCustomKeys } from "./hotkeys.js"; import { setupLayout } from "./layout.js"; import { EMPTY_BODY_HTML, EMPTY_NOTE_HTML, isBlankNote, isEmptyNote, isExpired, newNote, noteText, noteTitleOf, orderedGroups, placeNote, stepNote } from "./model.js"; -import { mergeNote } from "./merge.js"; +import { createOwnSaves, mergeNote } from "./merge.js"; import { legacySections, normalizeSettings, sameSettings, upgradeNote } from "./sprint.js"; import { openSprintSettings } from "./sprint-settings.js"; import { sanitizeHtml } from "./sanitize.js"; @@ -44,8 +44,7 @@ const notes = new Map(); // What storage last held for each note, as told by its change events: the base for merging // another window's save with edits this window has not saved yet. const synced = new Map(); -// What this window last wrote for each note, to recognise its own change events. -const written = new Map(); +const ownSaves = createOwnSaves(); const saves = createSaveScheduler({ delayMs: SAVE_DELAY_MS, maxWaitMs: SAVE_MAX_WAIT_MS, save: saveNow }); const state = { currentId: null, mode: "notes", query: "", ui: null, settings: null }; let editor; @@ -363,8 +362,8 @@ function saveNow(id) { const flushSaves = () => saves.flush(); function persist(changed) { - changed.forEach((note) => written.set(note.id, JSON.stringify(note))); - return store.saveNotes(changed); + const release = ownSaves.track(changed); + return store.saveNotes(changed).finally(release); } function reportSaveError(error) { @@ -537,7 +536,7 @@ function applyRemoteChanges({ updated, removedIds, settings, theme }) { function acceptRemote(remote) { const base = synced.get(remote.id); synced.set(remote.id, remote); - if (written.get(remote.id) === JSON.stringify(remote)) return null; + if (ownSaves.isOwn(remote)) return null; const local = notes.get(remote.id); if (!local || !base || sameNote(local, base)) { notes.set(remote.id, remote); diff --git a/extension/merge.js b/extension/merge.js index 8f5feed..c0f96ea 100644 --- a/extension/merge.js +++ b/extension/merge.js @@ -7,6 +7,26 @@ import { parseHtml } from "./model.js"; const NO_CONFLICT = { conflict: false }; +// Every version of a note this window is still saving. A save's change event arrives before the +// save settles, and an older save can finish after a newer one has started, so remembering only +// the latest version would mistake this window's own older save for another window's. +export function createOwnSaves() { + const inFlight = new Map(); + const release = ([id, version]) => { + const versions = inFlight.get(id) ?? []; + versions.splice(versions.indexOf(version), 1); + if (versions.length === 0) inFlight.delete(id); + }; + return { + track(notes) { + const entries = notes.map((note) => [note.id, JSON.stringify(note)]); + entries.forEach(([id, version]) => inFlight.set(id, [...(inFlight.get(id) ?? []), version])); + return () => entries.forEach(release); + }, + isOwn: (note) => inFlight.get(note.id)?.includes(JSON.stringify(note)) ?? false, + }; +} + function same(a, b) { if (a === b) return true; if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false; diff --git a/tests/merge.test.js b/tests/merge.test.js index 603278d..0b79ce5 100644 --- a/tests/merge.test.js +++ b/tests/merge.test.js @@ -1,7 +1,62 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { mergeBoard, mergeHtml, mergeNote, mergeSequence, mergeValue } from "../extension/merge.js"; +import { createOwnSaves, mergeBoard, mergeHtml, mergeNote, mergeSequence, mergeValue } from "../extension/merge.js"; +import { createFileArea } from "../extension/desktop.js"; +import { SCHEMA_VERSION, createStore } from "../extension/store.js"; + +test("an older save that finishes after a newer one started is still this window's own", () => { + const saves = createOwnSaves(); + const v1 = { id: "n", position: 90 }; + const v2 = { id: "n", position: 80 }; + const release1 = saves.track([v1]); + const release2 = saves.track([v2]); + assert.equal(saves.isOwn(v1), true); + release1(); + assert.equal(saves.isOwn(v2), true); + release2(); + assert.equal(saves.isOwn(v1), false); + assert.equal(saves.isOwn(v2), false); +}); + +test("the same version saved twice stays own until both saves settle; a version never saved is not own", () => { + const saves = createOwnSaves(); + const v = { id: "n", position: 1 }; + const first = saves.track([v]); + const second = saves.track([v]); + first(); + assert.equal(saves.isOwn(v), true); + second(); + assert.equal(saves.isOwn(v), false); + assert.equal(saves.isOwn({ id: "n", position: 2 }), false); +}); + +test("with the real file area, an overlapping older save's change event is recognised as own, and a failed save is released", async () => { + const base = { id: "n", html: "

A

", pinned: false, updatedAt: 1, deletedAt: null, position: 100 }; + let failNext = false; + const invoke = (command) => { + if (command === "storage_load") return Promise.resolve({ data: { "note:n": base, schemaVersion: SCHEMA_VERSION }, recovered: null, damagedPath: null }); + const fail = failNext; + return new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error("disk full")) : resolve()), 30)); + }; + const store = createStore(createFileArea(invoke)); + await store.load(); + const saves = createOwnSaves(); + const persist = (notes) => { + const release = saves.track(notes); + return store.saveNotes(notes).finally(release); + }; + const seen = []; + store.onChange(({ updated }) => updated.forEach((remote) => seen.push(saves.isOwn(remote)))); + const first = persist([{ ...base, position: 90, updatedAt: 2 }]); + await new Promise((resolve) => setTimeout(resolve, 10)); + await Promise.all([first, persist([{ ...base, position: 80, updatedAt: 3 }])]); + assert.deepEqual(seen, [true, true]); + failNext = true; + const failed = { ...base, position: 70, updatedAt: 4 }; + await assert.rejects(persist([failed]), /disk full/); + assert.equal(saves.isOwn(failed), false); +}); test("a value changed on one side only takes that change; both changed keeps this window's", () => { assert.deepEqual(mergeValue(1, 1, 2), { value: 2, conflict: false });