diff --git a/Commands/SaveElementCommand.ts b/Commands/SaveElementCommand.ts index 00a6692..6eb7852 100644 --- a/Commands/SaveElementCommand.ts +++ b/Commands/SaveElementCommand.ts @@ -131,7 +131,7 @@ const staleShown = new Set(); const unguardedShown = new Set(); /** Per note path, the save running now: the next save of that note waits for it. */ -const saveChains = new Map>(); +const saveChains = new Map>(); // Element ids whose new name auto-sync saved without renaming the note live // in the plugin's data (settings.pendingRenames, per world folder), so the @@ -304,7 +304,8 @@ export class SaveElementCommand { // auto-sync's, or the next pause's) waits for it, then reads the // change_seq it recorded. Otherwise both read the same number and the // second is refused as stale over the person's own write. - const key = activeFile instanceof TFile ? activeFile.path : ''; + // The note is the file, not its path: Obsidian keeps the same TFile through a rename. + const key = activeFile instanceof TFile ? activeFile : null; const run = (saveChains.get(key) ?? Promise.resolve()).then(() => this.saveOne(activeFile, opts)); const tail = run.then(() => undefined, () => undefined); saveChains.set(key, tail); @@ -327,9 +328,18 @@ export class SaveElementCommand { // type and name come from those bytes, never the metadata cache: a cache // that still holds an id the note no longer carries would send the new // text under that id. + // ★ The change numbers are read BEFORE the text that is sent (as Upload does). This save sends the number as If-Match: read + // after the text, across the PIN prompt and the client, it could be the number a pull recorded meanwhile, paired with the + // text from before that pull, and the old text would go over what the pull brought. Read first, a pull in between leaves + // the number old and the save is refused as stale. + const placed = await this.extractPathInfo(activeFile.path, await this.app.vault.read(activeFile)); + if (!placed) { + return this.fail("The current file is not a valid OnlyWorlds element note."); + } + const seqIndex = await readChangeSeqIndex(this.app, placed.worldName); const content = await this.app.vault.read(activeFile); const pathInfo = await this.extractPathInfo(activeFile.path, content); - if (!pathInfo) { + if (!pathInfo || pathInfo.worldName !== placed.worldName) { return this.fail("The current file is not a valid OnlyWorlds element note."); } const { worldName, category } = pathInfo; @@ -469,7 +479,6 @@ export class SaveElementCommand { // change is refused (412) instead of reverting it. None recorded (a // vault from before 3.8.1, a note never saved): saved as before, once, // and the answer's change_seq is recorded for the next save. - const seqIndex = await readChangeSeqIndex(this.app, worldName); const knownSeq = seqIndex[elementUuid] ?? null; // Only a note marked as holding the world's group at this very number clears it by having none (an older plugin that renews the number leaves the mark behind). const groupHeld = knownSeq !== null && seqIndex[heldKey(elementUuid)] === knownSeq; diff --git a/sync/auto-sync.ts b/sync/auto-sync.ts index f89ce83..5c52057 100644 --- a/sync/auto-sync.ts +++ b/sync/auto-sync.ts @@ -11,7 +11,7 @@ import { isUnderElements, mayBeElementNote, typeOfPlace } from "../vault/categor * Watches vault modifications, debounces rapid edits per file, and triggers * per-element pushes via SaveElementCommand once typing stops. * - * Per-file debounce: a separate timer per file path means edits in file A don't + * Per-file debounce: a separate timer per file means edits in file A don't * delay syncing file B, and rapid typing in one file just keeps resetting that * file's own timer. * @@ -26,7 +26,8 @@ export class AutoSyncEngine { static readonly SELF_WRITE_TTL_MS = 30_000; private app: App; private plugin: OnlyWorldsPlugin; - private timers: Map> = new Map(); + /** File -> its pending timer. Keyed by the file itself, not its path: Obsidian keeps the same TFile through a rename, so a note renamed while its timer waits is still the one timer. */ + private timers: Map> = new Map(); /** Path -> when it was marked (now()); one mark swallows one modify event. */ private selfWritePaths: Map = new Map(); private now: () => number; @@ -78,17 +79,17 @@ export class AutoSyncEngine { * pending timer for this file's path, so rapid edits coalesce into one push. */ private scheduleSync(file: TFile): void { - const existing = this.timers.get(file.path); + const existing = this.timers.get(file); if (existing !== undefined) { clearTimeout(existing); } this.plugin.setSyncStatus("dirty"); const ms = this.plugin.settings.debounceMs; const timer = setTimeout(() => { - this.timers.delete(file.path); + this.timers.delete(file); void this.syncFile(file); }, ms); - this.timers.set(file.path, timer); + this.timers.set(file, timer); } /** diff --git a/test/auto-sync.test.ts b/test/auto-sync.test.ts index 395a927..f3d004b 100644 --- a/test/auto-sync.test.ts +++ b/test/auto-sync.test.ts @@ -31,7 +31,7 @@ interface FakeClientOpts { existing?: Set; } -async function harness(opts: FakeClientOpts & { worldKey?: string | null; pin?: boolean } = {}) { +async function harness(opts: FakeClientOpts & { worldKey?: string | null; pin?: boolean; debounceMs?: number } = {}) { const { app, vault } = makeApp(); const worldKey = opts.worldKey === undefined ? "ow_k_test" : opts.worldKey; await vault.seed(`${W}/World.md`, worldKey ? `- **API Key:** ${worldKey}\n` : "# W\n"); @@ -72,7 +72,7 @@ async function harness(opts: FakeClientOpts & { worldKey?: string | null; pin?: }; const statuses: string[] = []; const plugin = { - settings: { apiKey: "", debounceMs: 5, autoSync: true }, + settings: { apiKey: "", debounceMs: opts.debounceMs ?? 5, autoSync: true }, setSyncStatus: (s: string) => statuses.push(s), buildV2Client: async () => (opts.pin === false ? null : client), }; @@ -146,3 +146,14 @@ test("a save that lands, or finds nothing to change, ends on synced", async () = assert.equal(h.statuses.at(-1), "synced"); assert.ok(!h.statuses.includes("error")); }); + +test("★ a note renamed while its timer waits is saved once, not once under each path (#2443)", async () => { + const h = await harness({ debounceMs: 80 }); + schedule(h.engine, h.fileB); + h.vault.move(`${FOLDER}/Beta.md`, `${FOLDER}/Beta renamed.md`); + schedule(h.engine, h.fileB); // the person types again, under the new name + await settle(250); + const saves = h.calls.filter((c) => c === `create character ${ID_B}`); + assert.equal(saves.length, 1, "one note, one save: " + h.calls.join(" | ")); + assert.equal((h.engine as unknown as { timers: Map }).timers.size, 0, "no timer is left under a path the note no longer has"); +}); diff --git a/test/save-chain-rename.test.ts b/test/save-chain-rename.test.ts new file mode 100644 index 0000000..9407341 --- /dev/null +++ b/test/save-chain-rename.test.ts @@ -0,0 +1,50 @@ +/** + * #2443: saves of one note wait for each other (one reads the change number the one before recorded). Queued by path, a note + * renamed while its first save was in flight got a second save beside it, which read the old number and was refused as stale + * over the person's own write. Queued by the file, the second waits. + */ +import "./support/obsidian-shim"; // MUST stay first: routes `obsidian` to the mock +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { App } from "obsidian"; +import { makeApp } from "./support/obsidian-mock"; +import { SaveElementCommand } from "../Commands/SaveElementCommand"; + +const W = "OnlyWorlds/Worlds/W"; +const FOLDER = `${W}/Elements/Character`; +const ID = "019a0000-0000-7000-8000-0000000000e1"; +const settle = () => new Promise((r) => setTimeout(r, 40)); + +test("★ a note renamed while its save is in flight: the second save waits for the first (red on 3.23.1: it ran beside it)", async () => { + const { app, vault } = makeApp(); + await vault.seed(`${W}/World.md`, "- **API Key:** ow_k_test\n"); + const file = await vault.seed(`${FOLDER}/Beta.md`, `---\nname: Beta\nid: ${ID}\n---\n\n### Description\n\nText.\n`); + const calls: string[] = []; + let release: () => void = () => {}; + const held = new Promise((r) => (release = r)); + let updates = 0; + const client = { + getWorld: async () => ({ id: "019a0000-0000-7000-8000-0000000000ee" }), + changesWalk: async () => ({ changes: [], cursor: null, head: 0 }), + get: async () => { + calls.push("get"); + return { id: ID, name: "old" }; + }, + update: async () => { + calls.push("update"); + if (++updates === 1) await held; + return {}; + }, + }; + const plugin = { settings: { apiKey: "" }, saveSettings: async () => {}, buildV2Client: async () => client }; + const first = new SaveElementCommand(app as App, plugin as never).execute(file as never); + await settle(); + assert.deepEqual(calls, ["get", "update"], "the first save is in flight"); + vault.move(`${FOLDER}/Beta.md`, `${FOLDER}/Beta renamed.md`); + const second = new SaveElementCommand(app as App, plugin as never).execute(file as never); + await settle(); + assert.deepEqual(calls, ["get", "update"], "the second save read the server while the first was still in flight: " + calls.join(" | ")); + release(); + await Promise.all([first, second]); + assert.equal(calls.filter((c) => c === "get").length, 2, "the second ran after: " + calls.join(" | ")); +}); diff --git a/test/save-pairs-seq.test.ts b/test/save-pairs-seq.test.ts new file mode 100644 index 0000000..85c40c0 --- /dev/null +++ b/test/save-pairs-seq.test.ts @@ -0,0 +1,67 @@ +/** + * #2443: a Save read the note, then waited (the PIN, the client), then read the change number it sends as If-Match. A pull that + * writes the note in that wait records a newer number; the save would pair the text it read before the pull with the pull's number, + * pass the If-Match, and put the old text over what the pull brought. The numbers are now read before the text. + */ +import "./support/obsidian-shim"; // MUST stay first: routes `obsidian` to the mock +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { harnessSave } from "./support/save-harness"; + +const ID = "0199c000-0000-7000-8000-0000000000d1"; +const SEQ_FILE = "OnlyWorlds/Worlds/W/.ow-seq.json"; +const note = (text: string) => `---\nname: Ireena\nid: ${ID}\n---\n\n### Description\n\n${text}\n`; +const NOTE = "Character/Ireena.md"; +const pullLands = async ({ app, vault, files }: { app: never; vault: { dotfiles: Map }; files: Record }) => { + await (app as { vault: { modify(f: unknown, t: string): Promise } }).vault.modify(files[NOTE], note("new prose from the world")); + vault.dotfiles.set(SEQ_FILE, JSON.stringify({ [ID]: 6 })); +}; + +test("★ a pull that lands while the save waits for its client: the save is refused as stale and nothing is sent (red on 3.23.1: the old text went over the pull's)", async () => { + const r = await harnessSave({ + notes: { [NOTE]: note("old prose"), "~/.ow-seq.json": JSON.stringify({ [ID]: 5 }) }, + save: NOTE, + server: { [ID]: { name: "Ireena", description: "new prose from the world", change_seq: 6 } }, + beforeClient: pullLands as never, + }); + assert.equal(r.sent.length, 0, "the old text was sent: " + JSON.stringify(r.sent)); + assert.equal(r.result.ok, false, r.notices.join(" | ")); + assert.ok(!(r.result as { local?: boolean }).local, "a refusal the status shows, never idle"); + assert.ok((await r.vault.read(r.files[NOTE] as never)).includes("new prose from the world"), "the pull's text stays in the note"); +}); + +test("the same wait in auto-sync: nothing is sent and the result is an error the status shows, with its notice", async () => { + const r = await harnessSave({ + notes: { [NOTE]: note("old prose"), "~/.ow-seq.json": JSON.stringify({ [ID]: 5 }) }, + save: NOTE, + manual: false, + server: { [ID]: { name: "Ireena", description: "new prose from the world", change_seq: 6 } }, + beforeClient: pullLands as never, + }); + assert.equal(r.sent.length, 0); + assert.equal(r.result.ok, false); + assert.ok(!(r.result as { local?: boolean }).local); +}); + +test("★ the note typed into while the save waits for its client (Obsidian's own autosave): the save goes through with the newest text, never refused", async () => { + const r = await harnessSave({ + notes: { [NOTE]: note("my edit"), "~/.ow-seq.json": JSON.stringify({ [ID]: 5 }) }, + save: NOTE, + server: { [ID]: { name: "Ireena", description: "old prose", change_seq: 5 } }, + beforeClient: (async ({ app, files }: { app: { vault: { modify(f: unknown, t: string): Promise } }; files: Record }) => { + await app.vault.modify(files[NOTE], note("my edit, and more")); + }) as never, + }); + assert.equal(r.sent.length, 1, r.notices.join(" | ")); +}); + +test("the control: no pull in the wait, the edited note is saved", async () => { + const r = await harnessSave({ + notes: { [NOTE]: note("my edit"), "~/.ow-seq.json": JSON.stringify({ [ID]: 5 }) }, + save: NOTE, + server: { [ID]: { name: "Ireena", description: "old prose", change_seq: 5 } }, + beforeClient: async () => {}, + }); + assert.equal(r.sent.length, 1, r.notices.join(" | ")); + assert.equal(r.sent[0].description, "my edit"); +}); diff --git a/test/support/save-harness.ts b/test/support/save-harness.ts index 1c82567..c358b89 100644 --- a/test/support/save-harness.ts +++ b/test/support/save-harness.ts @@ -4,7 +4,7 @@ * Returns what was sent, the calls in order and the notices shown. */ import type { App, TFile } from "obsidian"; -import { makeApp, __notices, __modals } from "./obsidian-mock"; +import { makeApp, __notices, __modals, type MockVault } from "./obsidian-mock"; import { SaveElementCommand } from "../../Commands/SaveElementCommand"; import { V2ApiError } from "../../client-v2"; @@ -37,6 +37,8 @@ export interface HarnessOpts { answer?: Record>; /** Runs while an update is in flight (after the body is sent, before keel answers): a person typing into a note as the save runs. */ during?: (ctx: { app: App; files: Record }) => Promise; + /** Runs while the save waits for its client (the PIN prompt's place): a pull that writes the note and records its number meanwhile. */ + beforeClient?: (ctx: { app: App; vault: MockVault; files: Record }) => Promise; } export async function harnessSave(o: HarnessOpts) { @@ -100,7 +102,7 @@ export async function harnessSave(o: HarnessOpts) { lastKnown: (o.lastKnown ? { [HARNESS_WID]: o.lastKnown } : {}) as Record, syncCursors: (o.cursor ? { [HARNESS_WID]: o.cursor } : {}) as Record, }; - const plugin = { settings, saveSettings: async () => {}, buildV2Client: async () => client }; + const plugin = { settings, saveSettings: async () => {}, buildV2Client: async () => { await o.beforeClient?.({ app, vault: vault as MockVault, files }); return client; } }; __notices.length = 0; __modals.length = 0; let done = false;