From 23a713fd8bcf7d02a386fe21e7d90da0f2dcb7f9 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sat, 28 Nov 2026 19:44:12 +1100 Subject: [PATCH] Keep Writer collection metadata across ordinary chapter saves --- apps/writer/scripts/perf/README.md | 22 +++ apps/writer/scripts/perf/docx-profile.mjs | 155 ++++++++++++++++++ apps/writer/scripts/perf/generator.ts | 4 +- .../scripts/perf/large-collection.bench.ts | 28 ++-- apps/writer/src/backend/native.test.ts | 62 +++++++ apps/writer/src/backend/native.ts | 55 ++++++- apps/writer/src/ui/WorkspaceView.tsx | 7 +- apps/writer/src/workspace/workspace.ts | 2 +- 8 files changed, 315 insertions(+), 20 deletions(-) create mode 100644 apps/writer/scripts/perf/docx-profile.mjs diff --git a/apps/writer/scripts/perf/README.md b/apps/writer/scripts/perf/README.md index 103a890d..10ad27f4 100644 --- a/apps/writer/scripts/perf/README.md +++ b/apps/writer/scripts/perf/README.md @@ -129,6 +129,28 @@ Both runs used `PROFILE_EDITOR_ONLY=1` on an AMD Ryzen 9 7940HS with Node 22.22. Both exports produced a 27,086-byte DOCX containing the Word document part. The two browser runs had long tasks above 20 seconds around export and source interactions. The browser measurements are single observations. The repeated Vitest runs establish the outline comparison. +### Word export during a chapter save + +With `pnpm dev` running, use the dedicated Chromium benchmark to time a chapter +save overlapping a Word download. Each run opens a fresh browser context, edits +the first chapter with Outline and Comments open, starts a save, and uses the +Word export menu. The browser fixture has 60 chapters, 300 manuscript comment +records, and 5,000 sources. + +```sh +PROFILE_OUTPUT=/tmp/writer-docx-before pnpm -C apps/writer exec node scripts/perf/docx-profile.mjs +PROFILE_OUTPUT=/tmp/writer-docx-after PROFILE_REFERENCE=/tmp/writer-docx-before/run-1.docx \ + pnpm -C apps/writer exec node scripts/perf/docx-profile.mjs +``` + +Run the first command with the benchmark and fixture on the baseline revision. +The script takes three samples by default. It reports save-to-download time, +time before the export handler starts, time inside the handler, and main-thread +long-task time. Python checks the ZIP, all 480 chapter passages, the edit, the +bibliography and the cited footnote. Every uncompressed package part is +compared, with creation and modification timestamps normalized. Writer review +threads stay in the collection. + ### Earlier browser measurements On the fixture-corrected product comparison, cold preview went from 3,426 to diff --git a/apps/writer/scripts/perf/docx-profile.mjs b/apps/writer/scripts/perf/docx-profile.mjs new file mode 100644 index 00000000..9d5c4eca --- /dev/null +++ b/apps/writer/scripts/perf/docx-profile.mjs @@ -0,0 +1,155 @@ +// Use the DEV-only large manuscript and the real Word download controls. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir } from "node:fs/promises"; +import { resolve } from "node:path"; +import { chromium } from "playwright"; + +const base = process.env.BASE ?? "http://127.0.0.1:5320/"; +const output = resolve(process.env.PROFILE_OUTPUT ?? "out/perf/docx"); +const referencePath = process.env.PROFILE_REFERENCE; +const runs = Number(process.env.PROFILE_RUNS ?? 3); +assert.ok(Number.isInteger(runs) && runs > 0, "PROFILE_RUNS must be a positive integer"); +const manuscript = "manuscripts/main.md"; +const chapter = "chapters/chapter-00000.md"; +const typed = " ordinary typing"; +await mkdir(output, { recursive: true }); + +// Validate every ZIP entry and fingerprint the uncompressed package. Pandoc +// records the export time in core.xml and in the ZIP container. +const inspect = String.raw` +import hashlib, json, sys, zipfile +from xml.etree import ElementTree as ET + +w = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}" +terms = "{http://purl.org/dc/terms/}" +def text(root): + return "".join(n.text or "" for n in root.iter(w + "t")) + +with zipfile.ZipFile(sys.argv[1]) as package: + assert package.testzip() is None + doc = ET.fromstring(package.read("word/document.xml")) + paragraphs = [text(p) for p in doc.iter(w + "p")] + for chapter in range(1, 61): + for section in range(1, 9): + expected = (f"Evidence in chapter {chapter}, section {section}, supports the manuscript’s " + "argument. Further analysis puts the result in context.") + assert any(p.startswith(expected) for p in paragraphs), expected + assert text(doc).count(" ordinary typing" * 24) == 1 + assert "Bibliography" in paragraphs + assert "Synthetic research 00099" in text(doc) + assert "Author00099, 2024" in text(doc) + assert list(doc.iter(w + "footnoteReference")) + footnotes = ET.fromstring(package.read("word/footnotes.xml")) + assert "Footnote text with a citation (Author00000, 2000)." in text(footnotes) + # Writer review threads stay in the collection, outside the Word document. + assert not list(doc.iter(w + "commentReference")) + if "word/comments.xml" in package.namelist(): + comments = ET.fromstring(package.read("word/comments.xml")) + assert not list(comments.iter(w + "comment")) + parts = {} + for name in sorted(package.namelist()): + content = package.read(name) + if name == "docProps/core.xml": + root = ET.fromstring(content) + for node in root: + if node.tag in (terms + "created", terms + "modified"): + node.text = "" + content = ET.tostring(root) + parts[name] = hashlib.sha256(content).hexdigest() + print(json.dumps(parts)) +`; + +const browser = await chromium.launch({ executablePath: process.env.CHROME }); +const inspectDocx = (path) => JSON.parse(execFileSync("python3", ["-c", inspect, path], { encoding: "utf8" })); +try { + const fixture = new URL(base); + fixture.search = new URLSearchParams({ demo: "large", largeManuscript: "1", manuscript }).toString(); + let reference = referencePath ? inspectDocx(resolve(referencePath)) : undefined; + for (let run = 1; run <= runs; run++) { + const page = await browser.newPage({ viewport: { width: 1500, height: 950 }, serviceWorkers: "block" }); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + page.setDefaultTimeout(120_000); + const cdp = await page.context().newCDPSession(page); + await cdp.send("Network.enable"); + await cdp.send("Network.setCacheDisabled", { cacheDisabled: true }); + await page.addInitScript(() => { + localStorage.setItem("mdbase-writer:layout", JSON.stringify({ view: "write" })); + window.tasks = []; + new PerformanceObserver((list) => window.tasks.push(...list.getEntries().map(e => [e.startTime, e.duration]))) + .observe({ type: "longtask" }); + }); + await page.goto(fixture.href); + await page.waitForFunction(() => { + const workspace = window.writer?.workspace; + if (!workspace) return false; + const snap = workspace.getSnapshot(); + const order = workspace.readingOrder(); + return order.length === 61 && order.every(path => snap.records.has(path)) + && ["indexLoad", "libraryLoad", "annotationsLoad", "commentsLoad"].every(key => snap[key].phase === "ready"); + }); + assert.deepEqual(await page.evaluate(() => { + const snap = window.writer.workspace.getSnapshot(); + return { comments: snap.comments.length, sources: snap.library.length }; + }), { comments: 300, sources: 5_000 }); + await page.getByRole("tab", { name: "Outline", exact: true }).click(); + await page.locator(`.record-row[data-path="${chapter}"]`).click(); + const editor = page.locator(".cm-content"); + const type = async () => { + await editor.focus(); + await page.keyboard.press("ControlOrMeta+End"); + for (let i = 0; i < 12; i++) await page.keyboard.insertText(typed); + }; + await type(); + await page.getByRole("tab", { name: /Comments/ }).click(); + await page.locator(".mdbase-threads > .mdbase-thread").first().waitFor(); + await type(); + await page.waitForFunction(({ chapter, suffix }) => window.writer.workspace.getSnapshot().records.get(chapter).snapshot.body.endsWith(suffix), + { chapter, suffix: typed.repeat(24) }); + + // Save at the export boundary to reproduce the autosave refresh on demand. + // Both paths use the ordinary SDK record session and collection watch. + const start = await page.evaluate(chapter => { + const workspace = window.writer.workspace; + const exportDocx = workspace.exportDocx.bind(workspace); + workspace.exportDocx = async (...args) => { + performance.mark("export:start"); + try { return await exportDocx(...args); } + finally { performance.mark("export:end"); } + }; + const start = performance.now(); + window.save = workspace.retrySave(chapter); + return start; + }, chapter); + + const download = page.waitForEvent("download"); + await page.getByRole("button", { name: "Export formats" }).click(); + await page.getByRole("menuitem").filter({ has: page.getByText("Word (DOCX)", { exact: true }) }).click(); + await page.waitForFunction(() => performance.getEntriesByName("export:end").length === 1); + const review = page.getByRole("button", { name: "Export anyway", exact: true }); + if (await review.isVisible()) await review.click(); + const file = await download; + const timing = await page.evaluate(start => { + const exportStart = performance.getEntriesByName("export:start")[0].startTime; + const exportEnd = performance.getEntriesByName("export:end")[0].startTime; + return { + saveToDownloadMs: Math.round(performance.now() - start), + beforeExportMs: Math.round(exportStart - start), + exportMs: Math.round(exportEnd - exportStart), + mainLongTaskMs: Math.round(window.tasks.filter(([at]) => at >= start).reduce((sum, [, duration]) => sum + duration, 0)), + }; + }, start); + assert.equal((await page.evaluate(() => window.save)).ok, true); + assert.deepEqual(errors, []); + const path = resolve(output, `run-${run}.docx`); + await file.saveAs(path); + const parts = inspectDocx(path); + if (reference) assert.deepEqual(parts, reference); + reference = parts; + console.log(JSON.stringify({ run, ...timing, parts })); + await page.context().close(); + } +} finally { + await browser.close(); +} diff --git a/apps/writer/scripts/perf/generator.ts b/apps/writer/scripts/perf/generator.ts index 98d0cf13..69186585 100644 --- a/apps/writer/scripts/perf/generator.ts +++ b/apps/writer/scripts/perf/generator.ts @@ -14,7 +14,9 @@ export function generateCollection(seed: (path: string, type: string, fm: JsonOb const noteBody = "Ordinary collection note.\n".repeat(80); const commentBody = "A comment discussing the passage. ".repeat(16); const abstract = "Source metadata. ".repeat(40); - const mainBody = browserChapters.length ? `${body}${browserChapters.map(path => `![[${path}]]`).join("\n\n")}\n` : body; + const mainBody = browserChapters.length + ? `${body}The manuscript includes a footnote.[^fixture]\n\n[^fixture]: Footnote text with a citation [@source00000].\n\n${browserChapters.map(path => `![[${path}]]`).join("\n\n")}\n` + : body; for (let i = 0; i < counts.manuscripts; i++) seed(i === 0 ? main : `manuscripts/paper-${pad(i)}.md`, "writer-manuscript", { title: `Paper ${pad(i)}`, csl: "apa", template: "article" }, i === 0 ? mainBody : body); for (const [i, path] of browserChapters.entries()) { const sections = Array.from({ length: 8 }, (_, section) => `### Section ${section + 1}\n\nEvidence in chapter ${i + 1}, section ${section + 1}, supports the manuscript's argument. Further analysis puts the result in context.`); diff --git a/apps/writer/scripts/perf/large-collection.bench.ts b/apps/writer/scripts/perf/large-collection.bench.ts index e29e5e8b..1e91f343 100644 --- a/apps/writer/scripts/perf/large-collection.bench.ts +++ b/apps/writer/scripts/perf/large-collection.bench.ts @@ -233,16 +233,24 @@ it("large collection baseline (opt-in)", async () => { cloneLibrary5000: measure(() => structuredClone({ type: "library", library: library.map((e) => e.item) })), }; const previousRecords = workspace.getSnapshot().recordPaths; - const refreshMessagesStart = compiler.messages.length; - const refreshStart = performance.now(); - f.replica.editElsewhere("notes/note-00000.md", { body: "Changed in another app" }); - await until(workspace, () => { - const current = workspace!.getSnapshot(); - return current.indexLoad.phase === "ready" && current.libraryLoad.phase === "ready" && current.annotationsLoad.phase === "ready" && (current.recordPaths !== previousRecords || f.transfers.some((t) => t.operation === "query:changed-paths" || t.operation === "read:note")); + const note = "notes/note-00000.md"; + const noteMessagesStart = compiler.messages.length; + const noteChanged = new Promise(resolve => { + const stop = f.backend.onCollectionChange(delta => { + if (!delta.paths.includes(note)) return; + stop(); + resolve(); + }); }); - const externalRefreshMs = performance.now() - refreshStart; - const externalTransfers = totals(f.transfers.splice(0)); - const noteWorkerMessages = compiler.messages.slice(refreshMessagesStart); + const noteStart = performance.now(); + f.replica.editElsewhere(note, { body: "Changed in another app" }); + await noteChanged; + expect(await f.backend.readBody(note)).toEqual({ ok: true, value: "Changed in another app" }); + const noteChangeAndReadMs = performance.now() - noteStart; + const noteTransfers = totals(f.transfers.splice(0)); + const noteWorkerMessages = compiler.messages.slice(noteMessagesStart); + expect(noteTransfers.byOperation).toEqual({ "read:note": 1 }); + expect(workspace.getSnapshot().recordPaths).toBe(previousRecords); f.seed("sources/new-source.md", "reader-source", { csl: { id: "newsource", type: "book", title: "A newly imported source" } }, "New source"); const sourceChangeStart = performance.now(); const sourceMessagesStart = compiler.messages.length; @@ -251,7 +259,7 @@ it("large collection baseline (opt-in)", async () => { const newSourceMs = performance.now() - sourceChangeStart; const newSourceTransfers = totals(f.transfers.splice(0)); const sourceWorkerMessages = compiler.messages.slice(sourceMessagesStart); - output.push({ run: run + 1, seedMs, homeListMs, homeBackgroundMs, readyMs, sourcesUsableMs, sourcesFirstSearchMs, commentsUsableMs, annotationIndexMs, sourceAnnotationsMs, annotationsUsableMs, previewInitializedMs, externalRefreshMs, newSourceMs, newSourceTransfers, commentTransfers, annotationIdentityTransfers, returnHomeMs, returnHomeTransfers, navigationTransfers, noteWorkerMessages, sourceWorkerMessages, homeTransfers, readyTransfers, workspaceTransfers, externalTransfers, computations, workerMessages: [...compiler.messages] }); + output.push({ run: run + 1, seedMs, homeListMs, homeBackgroundMs, readyMs, sourcesUsableMs, sourcesFirstSearchMs, commentsUsableMs, annotationIndexMs, sourceAnnotationsMs, annotationsUsableMs, previewInitializedMs, noteChangeAndReadMs, noteTransfers, newSourceMs, newSourceTransfers, commentTransfers, annotationIdentityTransfers, returnHomeMs, returnHomeTransfers, navigationTransfers, noteWorkerMessages, sourceWorkerMessages, homeTransfers, readyTransfers, workspaceTransfers, computations, workerMessages: [...compiler.messages] }); } finally { await workspace?.dispose(); await f.close(); } // Same collection size, redistributed highlights: one book has 300, not six. // Only its no-body annotation discovery pages are 6x slower, exposing preview gating. diff --git a/apps/writer/src/backend/native.test.ts b/apps/writer/src/backend/native.test.ts index ea9c1dcd..3832c99a 100644 --- a/apps/writer/src/backend/native.test.ts +++ b/apps/writer/src/backend/native.test.ts @@ -158,6 +158,68 @@ describe("native Writer domain backend", () => { expect(pages).not.toHaveBeenCalled(); opened.value.release(); }); + it("keeps collection metadata after a chapter edit and reads its latest confirmed body", async () => { + const h = await fixture(); + const path = "chapters/typed.md"; + const chapter = h.replica.seed({path, types: ["note"], body: "Original chapter"}); + const pages = vi.spyOn(h.client, "pages"); + const index = await h.backend.index(); + const library = await h.backend.library(); + if (!index.ok || !library.ok) throw new Error("Missing fixture metadata"); + const changed = vi.fn(); h.backend.onCollectionChange(changed); + + h.replica.editElsewhere(chapter.id, {body: "Edited chapter"}); + await vi.waitFor(() => expect(changed).toHaveBeenCalledWith({paths: [path]})); + expect(await h.backend.readBody(path)).toEqual({ok: true, value: "Edited chapter"}); + const currentIndex = await h.backend.index(); + const currentLibrary = await h.backend.library(); + expect(currentIndex.ok && currentIndex.value).toBe(index.value); + expect(currentLibrary.ok && currentLibrary.value).toBe(library.value); + expect(pages).toHaveBeenCalledOnce(); + + const get = h.client.get.bind(h.client); + const getSpy = vi.spyOn(h.client, "get"); + getSpy.mockImplementationOnce(async (...args) => { + const record = await get(...args); + return {...record, state: {...record.state, unresolved: 1}}; + }); + expect((await h.backend.readBody(path)).ok).toBe(false); + getSpy.mockImplementationOnce(async (...args) => { + const record = await get(...args); + changed.mockClear(); + h.replica.editElsewhere(chapter.id, {body: "Newer chapter"}); + await vi.waitFor(() => expect(changed).toHaveBeenCalledWith({paths: [path]})); + return record; + }); + expect((await h.backend.readBody(path)).ok).toBe(false); + getSpy.mockRestore(); + expect(await h.backend.readBody(path)).toEqual({ok: true, value: "Newer chapter"}); + + h.replica.renameElsewhere(chapter.id, "chapters/renamed.md"); + await vi.waitFor(() => expect(changed).toHaveBeenCalledWith({paths: [path], reset: true})); + const moved = await h.backend.index(); + expect(moved.ok && moved.value.recordPaths).toContain("chapters/renamed.md"); + expect(moved.ok && moved.value.recordPaths).not.toContain(path); + expect(pages).toHaveBeenCalledTimes(2); + }); + it("reloads metadata when a watch batch has an unknown type, changed type or different identity", async () => { + const watch = controlledWatch(); + const h = await fixture(client => {vi.spyOn(client, "watchChanges").mockReturnValue(watch.watch);}); + const chapter = h.replica.seed({path: "chapters/typed.md", types: ["note"]}); + const onChange = vi.mocked(h.client.watchChanges).mock.calls[0]?.[0]; + if (!onChange) throw new Error("Missing watch callback"); + const changed = vi.fn(); h.backend.onCollectionChange(changed); + const pages = vi.spyOn(h.client, "pages"); + const put = {id: chapter.id, path: chapter.path, kind: "put", entity: "record", version: 1} as const; + await h.backend.index(); + + for (const uncertain of [put, {...put, types: ["native-source"]}, {...put, types: ["note"], id: crypto.randomUUID()}]) { + onChange({changes: [{...put, types: ["note"]}, uncertain], cursor: "change", reset: false}); + expect(changed).toHaveBeenLastCalledWith({paths: [chapter.path, chapter.path], reset: true}); + expect((await h.backend.index()).ok).toBe(true); + } + expect(pages).toHaveBeenCalledTimes(4); + }); it("unrelated invalid definitions do not hide Writer records or untyped notes", async () => { const h = await fixture(); h.description.issues.push({code: "type_invalid", severity: "error", message: "An unrelated custom type is invalid", details: {path: "_types/unrelated.md"}}); diff --git a/apps/writer/src/backend/native.ts b/apps/writer/src/backend/native.ts index 3f69e759..0c4afae1 100644 --- a/apps/writer/src/backend/native.ts +++ b/apps/writer/src/backend/native.ts @@ -1,6 +1,6 @@ // Writer's domain repository over one borrowed public SDK connection. No // legacy backend facade, SDK runtime/setup engine, copied client or app journal. -import { isMdbaseError, type JsonObject, type MdbaseApplicationConnection, type MdbaseClient, type ContractRecordView, type ContractSelector, type DescribeResult, type FileView, type Receipt, type RecordView, type Write } from "@mdbase-dev/sdk"; +import { isMdbaseError, type Change, type JsonObject, type MdbaseApplicationConnection, type MdbaseClient, type ContractRecordView, type ContractSelector, type DescribeResult, type FileView, type Receipt, type RecordView, type Write } from "@mdbase-dev/sdk"; import { t } from "@lingui/core/macro"; import { changeFields, commentFromRecord, commentPath, newCommentFields, type CommentChange, type CommentRecord } from "@mdbase-dev/ui/comments"; import { CollectionBodies, type WriterBodyRow } from "./bodies.js"; @@ -27,12 +27,19 @@ interface NativeManuscripts { readonly manuscripts: ManuscriptSummary[]; readonly generation: number; } +interface RecordIdentity { + readonly id: string; + readonly revision: string; + /** Ordinary Markdown whose types contribute no Writer contract metadata. */ + readonly noteTypes?: readonly string[]; +} interface NativeMetadata { readonly schema: CollectionSchema; readonly store: CollectionStore; - readonly identities: ReadonlyMap; + readonly identities: ReadonlyMap; readonly files: ReadonlyMap; readonly generation: number; + readonly noteChanges: Map; } interface DomainScope { readonly asOf: number; @@ -67,6 +74,9 @@ function unprotected(record: RecordView): boolean { function readable(record: RecordView): boolean { return !record.state.hold && !(record.state.unresolved ?? 0); } +function sameTypes(a: readonly string[], b: readonly string[]): boolean { + return a.length === b.length && a.every((type, i) => type === b[i]); +} export class NativeWriterBackend implements WriterBackend { readonly kind: WriterBackend["kind"] = "connect"; @@ -137,7 +147,9 @@ export class NativeWriterBackend implements WriterBackend { let notifyFailure = !reconnecting; const current = () => !this.disposed && epoch === this.watchEpoch; const watch = this.client.watchChanges(batch => { - if (current()) this.invalidate(batch.reset ? [] : batch.changes.map(change => change.path)); + if (!current()) return; + if (batch.reset) this.invalidate([]); + else this.onChanges(batch.changes); }); const ended = () => { if (notifyFailure) this.invalidate([]); @@ -199,6 +211,25 @@ export class NativeWriterBackend implements WriterBackend { const result = await this.safely(operation, "index"); return result.ok ? result.value : result; } + private onChanges(changes: readonly Change[]): void { + const paths = changes.map(change => change.path); + const cached = this.cached; + // An ordinary note edit leaves discovery intact. Require an explicit + // identity and type witness for every change in the batch. The record + // sessions follow content independently of this collection watch. + if (!cached || !changes.length || !changes.every(change => { + const known = cached.identities.get(change.path); + return change.kind === "put" && change.entity === "record" && change.types !== undefined + && known?.id === change.id && known.noteTypes !== undefined && sameTypes(known.noteTypes, change.types); + })) { + this.invalidate(paths); + return; + } + for (const change of changes) cached.noteChanges.set(change.path, change.version); + for (const listener of this.external) listener(paths); + for (const listener of this.collection) listener({paths}); + } + private invalidate(paths: readonly string[]): void { if (this.disposed) return; ++this.generation; @@ -318,7 +349,7 @@ export class NativeWriterBackend implements WriterBackend { const {catalog, schema} = await this.loadSchemaAt(watch, generation); const store = new CollectionStore(schema); const rows = new Map(); - const identities = new Map(); + const identities = new Map(); const ids = new Set(); const recordCursors = new Set(); let asOf: number | undefined; @@ -333,7 +364,10 @@ export class NativeWriterBackend implements WriterBackend { } for (const record of page.records) { if (identities.has(record.path) || ids.has(record.id)) throw new IndexDiagnostic("Writer's native query repeated a record identity."); - identities.set(record.path, {id: record.id, revision: record.revision}); ids.add(record.id); + const note = /\.md$/i.test(record.path) && schema.roles(record.types).size === 0 + && !record.types.some(type => schema.isUnavailableType(type)); + identities.set(record.path, {id: record.id, revision: record.revision, ...(note ? {noteTypes: record.types} : {})}); + ids.add(record.id); rows.set(record.id, {path: record.path, types: record.types, ...(record.mtime !== undefined ? {modified: new Date(record.mtime).toISOString()} : {})}); } @@ -362,7 +396,7 @@ export class NativeWriterBackend implements WriterBackend { store.files([...files.keys()]); this.check(generation); if (watch !== this.watch || watch.state !== "active") throw new Error("Writer's collection watch needs reconnection."); - return this.cached = {schema, store, identities, files, generation}; + return this.cached = {schema, store, identities, files, generation, noteChanges: new Map()}; } private async projectMetadata(catalog: DescribeResult, schema: CollectionSchema, rows: Map, identities: ReadonlyMap, asOf: number, generation: number): Promise { for (const domain of COLLECTION_DOMAINS) { @@ -513,8 +547,15 @@ export class NativeWriterBackend implements WriterBackend { return this.safely(async () => { const metadata = await this.metadata(); const original = metadata.identities.get(path); if (!original) throw new Error("Writer cannot find this record in its native index."); + const change = metadata.noteChanges.get(path); const record = await this.client.get(original.id, {include: {body: true}, signal: this.signal}); this.check(metadata.generation); - if (record.id !== original.id || record.path !== path || record.revision !== original.revision || !unprotected(record)) throw new Error("Writer's record changed or is protected."); + // A note with a delivered edit has a newer revision than the index. + // Read its confirmed bytes by ID, and reject if another change arrived + // during the read or the record's path or types no longer match. + const matches = change === undefined + ? record.revision === original.revision && !metadata.noteChanges.has(path) + : original.noteTypes !== undefined && sameTypes(original.noteTypes, record.types) && metadata.noteChanges.get(path) === change; + if (record.id !== original.id || record.path !== path || !matches || !unprotected(record)) throw new Error("Writer's record changed or is protected."); return record.body ?? ""; }); } diff --git a/apps/writer/src/ui/WorkspaceView.tsx b/apps/writer/src/ui/WorkspaceView.tsx index cb632959..459f9335 100644 --- a/apps/writer/src/ui/WorkspaceView.tsx +++ b/apps/writer/src/ui/WorkspaceView.tsx @@ -415,7 +415,12 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc // Where each record's open threads are anchored, for the outline's quiet counts. const commentOffsets = useMemo(() => { const map = new Map(); - for (const p of placed) if (p.thread.root.status === "open" && p.at && p.at !== "whole") map.set(p.record, [...(map.get(p.record) ?? []), p.at.from]); + for (const p of placed) { + if (p.thread.root.status !== "open" || !p.at || p.at === "whole") continue; + const offsets = map.get(p.record); + if (offsets) offsets.push(p.at.from); + else map.set(p.record, [p.at.from]); + } return map; }, [placed]); const openThreads = useMemo(() => placed.filter((p) => p.thread.root.status === "open"), [placed]); diff --git a/apps/writer/src/workspace/workspace.ts b/apps/writer/src/workspace/workspace.ts index 55eecf39..092c108e 100644 --- a/apps/writer/src/workspace/workspace.ts +++ b/apps/writer/src/workspace/workspace.ts @@ -691,7 +691,7 @@ export class ManuscriptWorkspace { void this.refreshCollection(); return; } const indexChanged = delta.index && (delta.index.recordPaths !== this.current.recordPaths || delta.index.filePaths !== this.current.filePaths); - this.update({ ...(delta.index ? { ...(indexChanged ? { recordPaths: delta.index.recordPaths, filePaths: delta.index.filePaths } : {}), indexLoad: READY } : {}), ...(delta.library ? { library: delta.library, libraryLoad: READY } : {}) }); + if (delta.index || delta.library) this.update({ ...(delta.index ? { ...(indexChanged ? { recordPaths: delta.index.recordPaths, filePaths: delta.index.filePaths } : {}), indexLoad: READY } : {}), ...(delta.library ? { library: delta.library, libraryLoad: READY } : {}) }); if (indexChanged) { this.sendCollection(); for (const [path, view] of this.current.records) this.openEmbeds(path, view.snapshot.body);