Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
Sync deliberate note clears and preserve later Undo edits (#2604)
Joshua654bf42c828a
diff --git a/agent-skills/openwhispr-api/SKILL.md b/agent-skills/openwhispr-api/SKILL.mdindex 89037698d..91dea9ad0 100644--- a/agent-skills/openwhispr-api/SKILL.md+++ b/agent-skills/openwhispr-api/SKILL.md@@ -91,16 +91,17 @@ Wrap all responses in a consistent envelope.### Error Codes-| HTTP Status | Code | Meaning |-| ----------- | -------------------- | -------------------------------------------------- |-| 400 | `validation_error` | Invalid request body or query params |-| 401 | `invalid_api_key` | Missing, malformed, expired, or revoked key |-| 403 | `forbidden` | Key lacks required scope |-| 404 | `not_found` | Resource does not exist or belongs to another user |-| 405 | `method_not_allowed` | Wrong HTTP method |-| 409 | `conflict` | Duplicate resource (e.g. folder name) |-| 429 | `rate_limited` | Rate limit exceeded — check `Retry-After` header |-| 500 | `internal_error` | Server error |+| HTTP Status | Code | Meaning |+| ----------- | ----------------------- | --------------------------------------------------------------------- |+| 400 | `validation_error` | Invalid request body or query params |+| 401 | `invalid_api_key` | Missing, malformed, expired, or revoked key |+| 403 | `forbidden` | Key lacks required scope |+| 404 | `not_found` | Resource does not exist or belongs to another user |+| 405 | `method_not_allowed` | Wrong HTTP method |+| 409 | `conflict` | Duplicate resource (e.g. folder name) |+| 409 | `note_version_conflict` | Note changed since `base_revision`; body's `data` is the current note |+| 429 | `rate_limited` | Rate limit exceeded — check `Retry-After` header |+| 500 | `internal_error` | Server error |## Rate Limits@@ -150,6 +151,8 @@ Scope: `notes:read` (personal) / `workspace:notes:read` (workspace)**Get Note** — `GET /notes/{id}`Scope: `notes:read` / `workspace:notes:read`. Returns 404 if the note does not exist or is deleted. A workspace key may fetch any note in its workspace's spaces.+Note responses include `revision` (integer, advances on every change), `content_state` and `enhanced_content_state` (`set`, `clear`, or `null` for a field never written with an intent), and `enhancement_template_id` (the template the summary was built from).+**Create Note** — `POST /notes/create`| Field | Type | Required | Description ||-------|------|----------|-------------|@@ -168,8 +171,15 @@ Scope: `notes:write` / `workspace:notes:write`. Returns `201` with the created n| `content` | string | No | New content || `enhanced_content` | string | No | New enhanced content || `folder_id` | UUID | No | Move to folder |+| `base_revision` | integer | No | The note's `revision` you last read; the write applies only at that revision |+| `field_updates` | object | No | `{ "content"?: "set" \| "clear", "enhanced_content"?: "set" \| "clear" }`. Requires `base_revision` |Scope: `notes:write` / `workspace:notes:write`. All fields optional — only provided fields are updated. Cannot change a note's space.+- Without `base_revision`, a provided blank `content` or `enhanced_content` clears that field.+- With `base_revision`, state each change in `field_updates`: `set` needs nonblank text, `clear` takes an omitted, null or blank value (`400 validation_error` otherwise). A stale `base_revision` answers `409 note_version_conflict` with `{ "error": { "code", "message" }, "data": <current note> }`; rebase on `data` and retry.+- Clearing `enhanced_content` also removes its prompt and content hash but keeps `enhancement_template_id`.+- A nonblank legacy v1 write restores the field even when it matches text removed by a clear. Exact stale resends are suppressed only for released desktop sync endpoints; mobile and v1 restores remain edits.+**Delete Note** — `DELETE /notes/{id}`Scope: `notes:write` / `workspace:notes:write`. Soft-deletes the note. Returns `204 No Content`.diff --git a/preload.js b/preload.jsindex c475970cc..38c9b4f74 100644--- a/preload.js+++ b/preload.js@@ -1167,7 +1167,7 @@ contextBridge.exposeInMainWorld("electronAPI", {getNoteByClientId: (clientNoteId) => ipcRenderer.invoke("db-get-note-by-client-id", clientNoteId),upsertNoteFromCloud: (cloudNote, localFolderId, localSpaceId) =>ipcRenderer.invoke("db-upsert-note-from-cloud", cloudNote, localFolderId, localSpaceId),- acknowledgeNoteCreate: (id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged) =>+ acknowledgeNoteCreate: (id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, options) =>ipcRenderer.invoke("db-acknowledge-note-create",id,@@ -1175,22 +1175,34 @@ contextBridge.exposeInMainWorld("electronAPI", {cloudId,cloudUpdatedAt,ownerUserId,- settleIfUnchanged+ options),- markNoteSyncedIfUnchanged: (id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId) =>+ markNoteSyncedIfUnchanged: (+ id,+ snapshot,+ expectedCloudId,+ cloudUpdatedAt,+ ownerUserId,+ cloudRevision,+ cloudNote+ ) =>ipcRenderer.invoke("db-mark-note-synced-if-unchanged",id,snapshot,expectedCloudId,cloudUpdatedAt,- ownerUserId+ ownerUserId,+ cloudRevision,+ cloudNote),- setNoteCloudBase: (id, cloudUpdatedAt) =>- ipcRenderer.invoke("db-set-note-cloud-base", id, cloudUpdatedAt),+ setNoteCloudBase: (id, cloudUpdatedAt, cloudRevision, options) =>+ ipcRenderer.invoke("db-set-note-cloud-base", id, cloudUpdatedAt, cloudRevision, options),setNoteOwnerFromCloud: (id, ownerUserId) =>ipcRenderer.invoke("db-set-note-owner-from-cloud", id, ownerUserId),countTeamNotesMissingOwner: () => ipcRenderer.invoke("db-count-team-notes-missing-owner"),+ countNotesMissingRevision: (spaceKind) =>+ ipcRenderer.invoke("db-count-notes-missing-revision", spaceKind),markNoteSyncError: (id) => ipcRenderer.invoke("db-mark-note-sync-error", id),restoreNoteAfterDeniedDelete: (id) =>ipcRenderer.invoke("db-restore-note-after-denied-delete", id),diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex 2834b63ee..8d98e3a71 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -233,6 +233,8 @@ interface NoteEditorProps {onCreateFolderAndMove?: (noteId: number, folderName: string) => void;/** Cancels the owner's debounced autosaves before an external copy is applied. */onCancelPendingSaves?: (noteId: number) => void;+ /** Saves the owner's debounced autosaves now; rejects when a save fails. */+ onFlushPendingSaves?: (noteId: number) => Promise<void>;}export default function NoteEditor({@@ -267,6 +269,7 @@ export default function NoteEditor({onMoveToFolder,onCreateFolderAndMove,onCancelPendingSaves,+ onFlushPendingSaves,}: NoteEditorProps) {const { t } = useTranslation();const locale = useUiLocale();@@ -959,11 +962,30 @@ export default function NoteEditor({// Keep the local edits, overwriting the cloud revision the user just saw.// Advancing the base first is what lets the next push succeed instead of- // 409ing against the same conflict and re-raising the banner.- const handleConflictKeep = useCallback(() => {- if (conflict) void window.electronAPI.setNoteCloudBase?.(note.id, conflict.updated_at);- clearNoteConflict(note.client_note_id);- }, [conflict, note.id, note.client_note_id]);+ // 409ing against the same conflict and re-raising the banner. A field this+ // device never edited takes the cloud copy's value, a clear included, rather+ // than resurrecting the old text.+ const handleConflictKeep = useCallback(async () => {+ try {+ if (conflict) {+ // Unsaved edits are part of what the user keeps. Saving them first also+ // means no debounced save lands after Keep, writing the draft back over+ // a clear Keep took; with none pending, the store copy resyncs the editor.+ await onFlushPendingSaves?.(note.id);+ const result = await window.electronAPI.setNoteCloudBase?.(+ note.id,+ conflict.updated_at,+ conflict.revision,+ { keepLocal: true, cloudNote: conflict }+ );+ if (result?.note) updateNoteInStore(result.note);+ }+ clearNoteConflict(note.client_note_id);+ } catch (err) {+ // The banner stays, so Keep can be retried.+ console.error("Failed to keep local note edits:", err);+ }+ }, [conflict, note.id, note.client_note_id, onFlushPendingSaves]);const noteDate = formatNoteDate(note.created_at, locale);const shortDate = formatShortDate(note.created_at, locale);@@ -1382,7 +1404,9 @@ export default function NoteEditor({/>)) : viewMode === "transcript" && hasMeetingTranscript ? (- <RichTextEditor value={note.transcript || ""} disabled />+ // Each tab keys its own editor, so undo never crosses tabs: an+ // undo step from one tab would replay over the other and save it.+ <RichTextEditor key="transcript" value={note.transcript || ""} disabled />) : viewMode === "transcript" ? (<divclassName={cn(@@ -1414,6 +1438,7 @@ export default function NoteEditor({</div>) : viewMode === "enhanced" && enhancement ? (<RichTextEditor+ key="enhanced"value={enhancement.content}onChange={handleEnhancedChange}disabled={!canEditNote}@@ -1421,6 +1446,7 @@ export default function NoteEditor({/>) : (<RichTextEditor+ key="raw"value={note.content}onChange={handleContentChange}editorRef={editorRef}diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex e44233cfb..46565157c 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -75,6 +75,8 @@ import { markIntroSeen, NOTES_STRUCTURE_INTRO, shouldShowIntro } from "../../libimport {applyNoteDraftMutation,collectPendingNoteWrites,+ documentSaveUpdates,+ enhancedSaveUpdates,planNoteTransition,shouldCancelPendingSavesForDelete,type NoteEditorDraft,@@ -185,6 +187,29 @@ export default function PersonalNotesView({}}, []);+ // Conflict-banner Keep saves the note's pending edits before advancing the+ // base. They stay pending until written, so a failed save is retried by its+ // own timer and the draft is never replaced by the store copy meanwhile.+ const savePendingNow = useCallback(async (noteId: number) => {+ const document =+ pendingDocumentRef.current?.noteId === noteId ? pendingDocumentRef.current : null;+ const enhanced =+ pendingEnhancedRef.current?.noteId === noteId ? pendingEnhancedRef.current : null;+ for (const write of collectPendingNoteWrites(document, enhanced)) {+ const result = await window.electronAPI.updateNote(write.noteId, write.updates);+ if (!result?.success) throw new Error(result?.error ?? "Note save failed");+ }+ // Retire only the saves just written; an edit made meanwhile stays pending.+ if (document && pendingDocumentRef.current === document) {+ clearTimeout(document.timer);+ pendingDocumentRef.current = null;+ }+ if (enhanced && pendingEnhancedRef.current === enhanced) {+ clearTimeout(enhanced.timer);+ pendingEnhancedRef.current = null;+ }+ }, []);+const takePendingSnapshots = useCallback((): {document: PendingDocumentSnapshot | null;enhanced: PendingEnhancedSnapshot | null;@@ -406,63 +431,94 @@ export default function PersonalNotesView({}}, [activeNote, commitDraft, transitionToNote]);- const scheduleDocumentSave = useCallback((snapshot: NoteEditorDraft) => {- void window.electronAPI.discardNoteUndo?.(snapshot.noteId);- const current = pendingDocumentRef.current;- if (current) clearTimeout(current.timer);-- const pending: PendingDocumentSave = {- noteId: snapshot.noteId,- title: snapshot.title,- content: snapshot.content,- timer: setTimeout(async () => {- if (pendingDocumentRef.current !== pending) return;- pendingDocumentRef.current = null;- setIsSaving(true);- try {- await window.electronAPI.updateNote(pending.noteId, {- title: pending.title,- content: pending.content,- });- } catch (err) {- logger.warn("Failed to save note", { error: (err as Error).message }, "notes");- } finally {- setIsSaving(false);- }- }, 1000),- };- pendingDocumentRef.current = pending;- }, []);+ // A save leaves the draft behind any store update it held off (see the+ // effect above). Once nothing is pending for the note, the draft takes the+ // saved row: fields the save did not write carry what a pull or ack applied.+ const resyncDraftAfterSave = useCallback(+ (noteId: number, saved: NoteItem | undefined) => {+ if (+ !saved ||+ saved.id !== noteId ||+ draftRef.current?.noteId !== noteId ||+ pendingDocumentRef.current?.noteId === noteId ||+ pendingEnhancedRef.current?.noteId === noteId+ )+ return;+ commitDraft(draftFromNote(saved));+ },+ [commitDraft]+ );- const scheduleEnhancedSave = useCallback((snapshot: NoteEditorDraft) => {- void window.electronAPI.discardNoteUndo?.(snapshot.noteId);- const current = pendingEnhancedRef.current;- if (current) clearTimeout(current.timer);-- const pending: PendingEnhancedSave = {- noteId: snapshot.noteId,- enhancedContent: snapshot.enhancedContent,- timer: setTimeout(async () => {- if (pendingEnhancedRef.current !== pending) return;- pendingEnhancedRef.current = null;- setIsSaving(true);- try {- await window.electronAPI.updateNote(pending.noteId, {- enhanced_content: pending.enhancedContent,- });- } catch (err) {- logger.warn(- "Failed to save enhanced note content",- { error: (err as Error).message },- "notes"- );- } finally {- setIsSaving(false);- }- }, 1000),- };- pendingEnhancedRef.current = pending;- }, []);+ const scheduleDocumentSave = useCallback(+ (+ snapshot: NoteEditorDraft,+ edits: Pick<PendingDocumentSnapshot, "contentEdited" | "clearContent">+ ) => {+ void window.electronAPI.discardNoteUndo?.(snapshot.noteId);+ const current = pendingDocumentRef.current;+ if (current) clearTimeout(current.timer);++ const pending: PendingDocumentSave = {+ noteId: snapshot.noteId,+ title: snapshot.title,+ content: snapshot.content,+ ...edits,+ timer: setTimeout(async () => {+ if (pendingDocumentRef.current !== pending) return;+ pendingDocumentRef.current = null;+ setIsSaving(true);+ try {+ const result = await window.electronAPI.updateNote(+ pending.noteId,+ documentSaveUpdates(pending)+ );+ if (result?.success) resyncDraftAfterSave(pending.noteId, result.note);+ } catch (err) {+ logger.warn("Failed to save note", { error: (err as Error).message }, "notes");+ } finally {+ setIsSaving(false);+ }+ }, 1000),+ };+ pendingDocumentRef.current = pending;+ },+ [resyncDraftAfterSave]+ );++ const scheduleEnhancedSave = useCallback(+ (snapshot: NoteEditorDraft) => {+ void window.electronAPI.discardNoteUndo?.(snapshot.noteId);+ const current = pendingEnhancedRef.current;+ if (current) clearTimeout(current.timer);++ const pending: PendingEnhancedSave = {+ noteId: snapshot.noteId,+ enhancedContent: snapshot.enhancedContent,+ timer: setTimeout(async () => {+ if (pendingEnhancedRef.current !== pending) return;+ pendingEnhancedRef.current = null;+ setIsSaving(true);+ try {+ const result = await window.electronAPI.updateNote(+ pending.noteId,+ enhancedSaveUpdates(pending)+ );+ if (result?.success) resyncDraftAfterSave(pending.noteId, result.note);+ } catch (err) {+ logger.warn(+ "Failed to save enhanced note content",+ { error: (err as Error).message },+ "notes"+ );+ } finally {+ setIsSaving(false);+ }+ }, 1000),+ };+ pendingEnhancedRef.current = pending;+ },+ [resyncDraftAfterSave]+ );const handleTitleChange = useCallback((sourceNoteId: number, title: string) => {@@ -473,7 +529,14 @@ export default function PersonalNotesView({});if (!next) return;commitDraft(next);- scheduleDocumentSave(next);+ // A title edit before the save fires shares that save, so it keeps an+ // edit or a clear of the notes; on its own it writes only the title.+ const pending =+ pendingDocumentRef.current?.noteId === next.noteId ? pendingDocumentRef.current : null;+ scheduleDocumentSave(next, {+ contentEdited: pending?.contentEdited ?? false,+ clearContent: pending?.clearContent ?? false,+ });},[commitDraft, scheduleDocumentSave]);@@ -487,7 +550,7 @@ export default function PersonalNotesView({});if (!next) return;commitDraft(next);- scheduleDocumentSave(next);+ scheduleDocumentSave(next, { contentEdited: true, clearContent: !content.trim() });},[commitDraft, scheduleDocumentSave]);@@ -815,6 +878,7 @@ export default function PersonalNotesView({onMoveToFolder={handleMoveToFolder}onCreateFolderAndMove={handleCreateFolderAndMove}onCancelPendingSaves={cancelPendingSaves}+ onFlushPendingSaves={savePendingNow}actionProcessingState={actionProcessingState}actionName={actionName}actionProgress={actionProgress}diff --git a/src/components/ui/RichTextEditor.tsx b/src/components/ui/RichTextEditor.tsxindex d1da713d1..ad526d98d 100644--- a/src/components/ui/RichTextEditor.tsx+++ b/src/components/ui/RichTextEditor.tsx@@ -18,6 +18,19 @@ interface RichTextEditorProps {mentionPeople?: MentionPerson[];}+/**+ * Starts a new undo history. Earlier steps would otherwise be mapped onto a+ * value set from outside: one that spanned the whole document (select all,+ * then type or delete) maps onto the whole new value, so Ctrl+Z would put the+ * user's older text back over it and save that.+ */+function resetUndoHistory(editor: Editor): void {+ const { plugins } = editor.state;+ editor.unregisterPlugin("history");+ // Reconfiguring keeps every other plugin's state; the history starts empty.+ editor.view.updateState(editor.state.reconfigure({ plugins }));+}+export function RichTextEditor({value,onChange,@@ -73,7 +86,9 @@ export function RichTextEditor({// Sync external value changes (e.g. dictation, programmatic updates)useEffect(() => {if (!editor || editor.isDestroyed) return;- if (value === internalValueRef.current) return;+ // A whitespace-only note is saved empty; that echo is not a new value, and+ // applying it would move the caret.+ if (value === internalValueRef.current || (!value && !internalValueRef.current.trim())) return;internalValueRef.current = value;suppressUpdateRef.current = true;@@ -86,6 +101,7 @@ export function RichTextEditor({const safeFrom = Math.min(from, docSize);const safeTo = Math.min(to, docSize);editor.commands.setTextSelection({ from: safeFrom, to: safeTo });+ resetUndoHistory(editor);suppressUpdateRef.current = false;}, [value, editor]);diff --git a/src/helpers/cliBridge.js b/src/helpers/cliBridge.jsindex b43ca99ff..13b057fb2 100644--- a/src/helpers/cliBridge.js+++ b/src/helpers/cliBridge.js@@ -6,6 +6,7 @@ const crypto = require("crypto");const debugLogger = require("./debugLogger");const { isPortAvailable } = require("../utils/serverUtils");const { broadcastToWindows } = require("./windowBroadcast");+const { NOTE_TEXT_FIELDS } = require("./noteFieldSync");const PORT_RANGE_START = 8200;const PORT_RANGE_END = 8219;@@ -103,6 +104,20 @@ function unwrapMutationResult(result, label) {return result[label];}+// The public v1 contract: a provided blank content or enhanced_content clears+// that field. updateNote treats a bare blank as unconfirmed (never synced as a+// clear), so the bridge states the intent; updateNote still validates it.+function withProvidedBlanksCleared(body) {+ const blanks = NOTE_TEXT_FIELDS.filter(+ (field) =>+ field in body &&+ (body[field] == null || (typeof body[field] === "string" && !body[field].trim()))+ );+ if (blanks.length === 0 || (body.clear_fields !== undefined && !Array.isArray(body.clear_fields)))+ return body;+ return { ...body, clear_fields: [...new Set([...(body.clear_fields ?? []), ...blanks])] };+}+class CliBridge {constructor(ipcHandlers) {this.ipcHandlers = ipcHandlers;@@ -438,7 +453,7 @@ class CliBridge {err.code = "NOT_FOUND";throw err;}- const result = db.updateNote(id, body || {});+ const result = db.updateNote(id, withProvidedBlanksCleared(body || {}));// The note exists, so a remaining error names a folder or space that doesn't.if (result.error) {const err = new Error(result.error);diff --git a/src/helpers/cloudSyncGuards.js b/src/helpers/cloudSyncGuards.jsindex cebbd27f7..d53c06807 100644--- a/src/helpers/cloudSyncGuards.js+++ b/src/helpers/cloudSyncGuards.js@@ -1,3 +1,5 @@+import { hasNoteRevision, noteFieldUpdates } from "./noteFieldSync.js";+// Sync guards shared by SyncService and the node --test suite (#1290).// SQLite `datetime('now')` yields "YYYY-MM-DD HH:MM:SS" (no T, no millis, no Z);@@ -25,14 +27,28 @@ export function isCloudEntryNewer(cloudUpdatedAt, localUpdatedAt) {// every push would fork duplicate notes; only the one-shot migration branch// sends it. `cloudFolderId` is the note's folder already mapped to its cloud// id (null when folderless or unmapped).+//+// A revision-aware write sends a text field only with its operation. Text+// without one must be unchanged since the last ack, and locally it need not+// be: a pull keeps local text over a blank the cloud never marked as a clear,+// and resending that text would overwrite newer text written elsewhere. So it+// stays out, and the summary metadata with the summary.export function buildNoteUpdatePayload(note, cloudFolderId) {+ const revisioned = hasNoteRevision(note.cloud_revision);+ const fieldUpdates = noteFieldUpdates(note);+ const sends = (field) => !revisioned || field in fieldUpdates;return {+ ...(revisioned ? { base_revision: note.cloud_revision, field_updates: fieldUpdates } : {}),title: note.title,- content: note.content,- enhanced_content: note.enhanced_content,- enhancement_prompt: note.enhancement_prompt,- enhancement_template_id: note.enhancement_template_id,- enhanced_at_content_hash: note.enhanced_at_content_hash,+ content: sends("content") ? pushedText(note, "content") : undefined,+ enhanced_content: sends("enhanced_content") ? pushedText(note, "enhanced_content") : undefined,+ ...(sends("enhanced_content")+ ? {+ enhancement_prompt: note.enhancement_prompt,+ enhancement_template_id: note.enhancement_template_id,+ enhanced_at_content_hash: note.enhanced_at_content_hash,+ }+ : {}),note_type: note.note_type,source_file: note.source_file,audio_duration_seconds: note.audio_duration_seconds,@@ -50,6 +66,15 @@ export function buildNoteUpdatePayload(note, cloudFolderId) {};}+// A blank is sent only as a deliberate clear, as "" (the server reads a null+// summary as omitted). The server also reads a blank that carries a timestamp+// base as a clear, so an unconfirmed local blank is omitted (undefined drops+// out of the JSON body) and the stored text stays.+function pushedText(note, field) {+ if (note[field]?.trim()) return note[field];+ return note[`${field}_sync_operation`] === "clear" ? "" : undefined;+}+// POST creates a new cloud identity and therefore has no prior server// revision to compare. Forks from older databases can retain a stale base, so// derive create payloads explicitly rather than forwarding base_updated_at.@@ -59,8 +84,32 @@ export function buildNoteUpdatePayload(note, cloudFolderId) {// the server stores it as-is — mobile's delta cursor (the newest updated_at// it has seen) would then skip the row forever. PATCHes are server-stamped.export function buildNoteCreatePayload(note, cloudFolderId) {- const payload = buildNoteUpdatePayload(note, cloudFolderId);+ const payload = {+ ...buildNoteUpdatePayload(+ {+ ...note,+ cloud_revision: null,+ content_sync_operation: null,+ enhanced_content_sync_operation: null,+ },+ cloudFolderId+ ),+ // Create requires content, and a blank there never clears existing text.+ content: note.content ?? "",+ enhanced_content: note.enhanced_content,+ };delete payload.base_updated_at;+ delete payload.base_revision;+ delete payload.field_updates;delete payload.updated_at;return payload;}++// A server revision orders same-millisecond edits and survives local clock+// skew. A copy without one (an API that predates revisions) compares timestamps.+export function isCloudNoteNewer(cloud, local) {+ if (hasNoteRevision(cloud.revision) && hasNoteRevision(local.cloud_revision)) {+ return cloud.revision > local.cloud_revision;+ }+ return isCloudEntryNewer(cloud.updated_at, local.updated_at);+}diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 37aba8de8..32f9e3439 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -1,4 +1,13 @@const Database = require("better-sqlite3");+const {+ NOTE_TEXT_FIELDS,+ SUMMARY_CLEARED_METADATA,+ SUMMARY_METADATA,+ clearedNoteFields,+ cloudTextUpdates,+ hasNoteRevision,+ hasPendingNoteClear,+} = require("./noteFieldSync");const path = require("path");const fs = require("fs");const { randomUUID } = require("crypto");@@ -29,6 +38,13 @@ const { app } = require("electron");// trigger can't 400 the whole sync batch.const MAX_SNIPPET_TRIGGER_LENGTH = 100;+// Text a local writer creates is the user's: recording it as a set lets+// conflict Keep tell it from text this device merely pulled. A blank stays+// unmarked, as it never clears anything.+function typedTextOperation(text) {+ return typeof text === "string" && text.trim() ? "set" : null;+}+// Every local field a note create (POST) carries; the acknowledgement compares// these atomically against the pushed snapshot. Must mirror NotePushSnapshot// in src/types/electron.ts.@@ -37,6 +53,10 @@ const NOTE_CREATE_ACK_FIELDS = ["title","content","enhanced_content",+ "content_sync_operation",+ "enhanced_content_sync_operation",+ "content_edit_generation",+ "enhanced_content_edit_generation","enhancement_prompt","enhancement_template_id","enhanced_at_content_hash",@@ -56,7 +76,12 @@ const NOTE_CREATE_ACK_FIELDS = ["deleted_at",];// A PATCH additionally pins the server base and any pending scope retraction.-const NOTE_PATCH_ACK_FIELDS = [...NOTE_CREATE_ACK_FIELDS, "cloud_updated_at", "left_team"];+const NOTE_PATCH_ACK_FIELDS = [+ ...NOTE_CREATE_ACK_FIELDS,+ "cloud_updated_at",+ "cloud_revision",+ "left_team",+];// Must mirror FolderPushSnapshot in src/types/electron.ts.const FOLDER_ACK_FIELDS = ["client_folder_id",@@ -125,11 +150,35 @@ function toActionItem(row) {function rowMatchesSnapshot(row, snapshot, fields) {return fields.every((field) => {- const expected = snapshot[field] === undefined ? null : snapshot[field];+ const fallback = field.endsWith("_edit_generation") ? 0 : null;+ const expected = snapshot[field] === undefined ? fallback : snapshot[field];return row[field] === expected;});}+function noteTextMatchesSnapshot(row, snapshot, field) {+ return rowMatchesSnapshot(row, snapshot, [+ field,+ `${field}_sync_operation`,+ `${field}_edit_generation`,+ ...(field === "enhanced_content" ? SUMMARY_METADATA : []),+ ]);+}++// An applied create acknowledges the submitted sets, even if the server kept+// a clear instead. Later edits and undelivered clears still belong to this device.+function acknowledgedCreateTextUpdates(current, snapshot, cloudNote) {+ const fields = NOTE_TEXT_FIELDS.filter(+ (field) =>+ snapshot[`${field}_sync_operation`] !== "clear" &&+ noteTextMatchesSnapshot(current, snapshot, field)+ );+ return {+ ...cloudTextUpdates(current, cloudNote, fields),+ ...Object.fromEntries(fields.map((field) => [`${field}_sync_operation`, null])),+ };+}+// An optimistically deleted folder still holds its server-side name until the// DELETE is confirmed, so it must keep blocking reuse of that name.const FOLDER_NAME_TAKEN_FILTER = `(deleted_at IS NULL OR EXISTS (@@ -400,6 +449,24 @@ class DatabaseManager {} catch (err) {if (!err.message.includes("duplicate column")) throw err;}+ let addedSyncOperations = false;+ for (const definition of [+ "cloud_revision INTEGER",+ "cloud_create_rejected INTEGER NOT NULL DEFAULT 0",+ "cloud_create_pending TEXT",+ "content_sync_operation TEXT",+ "enhanced_content_sync_operation TEXT",+ "content_edit_generation INTEGER NOT NULL DEFAULT 0",+ "enhanced_content_edit_generation INTEGER NOT NULL DEFAULT 0",+ ]) {+ try {+ this.db.exec(`ALTER TABLE notes ADD COLUMN ${definition}`);+ if (definition.startsWith("content_sync_operation")) addedSyncOperations = true;+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ }+ if (addedSyncOperations) this._markUnsyncedNoteTextAsSet();try {this.db.exec("ALTER TABLE notes ADD COLUMN cloud_id TEXT");} catch (err) {@@ -3042,11 +3109,12 @@ class DatabaseManager {const clientNoteId = randomUUID();const accountId = this._accountIdForSpace(spaceId);const stmt = this.db.prepare(- "INSERT INTO notes (title, content, note_type, source_file, audio_duration_seconds, folder_id, space_id, client_note_id, account_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"+ "INSERT INTO notes (title, content, content_sync_operation, note_type, source_file, audio_duration_seconds, folder_id, space_id, client_note_id, account_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");const result = stmt.run(title,content,+ typedTextOperation(content),noteType,sourceFile,audioDuration,@@ -3097,9 +3165,9 @@ class DatabaseManager {}const insert = this.db.prepare(`- INSERT INTO notes (client_note_id, title, content, note_type, source_file,+ INSERT INTO notes (client_note_id, title, content, content_sync_operation, note_type, source_file,folder_id, space_id, account_id, transcript, participants, sync_status, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending',+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending',COALESCE(?, datetime('now')), COALESCE(?, datetime('now')))ON CONFLICT(client_note_id) DO NOTHING`);@@ -3115,6 +3183,7 @@ class DatabaseManager {row.clientNoteId,row.title,row.content,+ typedTextOperation(row.content),noteType,row.sourceFile,folderId,@@ -3310,9 +3379,64 @@ class DatabaseManager {}try {if (!this.db) throw new Error("Database not initialized");- if (!this.getNote(id)) return { success: false, error: "Note not found" };+ const previous = this.getNote(id);+ if (!previous) return { success: false, error: "Note not found" };updates = { ...updates };+ const clears = updates.clear_fields ?? [];+ if (!Array.isArray(clears) || clears.some((field) => !NOTE_TEXT_FIELDS.includes(field))) {+ return { success: false, error: "Invalid note clear fields" };+ }+ for (const field of NOTE_TEXT_FIELDS) {+ delete updates[`${field}_sync_operation`];+ delete updates[`${field}_edit_generation`];+ if (clears.includes(field)) {+ if (+ updates[field] != null &&+ (typeof updates[field] !== "string" || updates[field].trim())+ ) {+ return { success: false, error: "A clear cannot include nonempty text" };+ }+ updates[field] = field === "content" ? "" : null;+ updates[`${field}_sync_operation`] = "clear";+ if (field === "enhanced_content") {+ for (const key of SUMMARY_CLEARED_METADATA) updates[key] = null;+ }+ } else if (+ typeof updates[field] === "string" &&+ updates[field].trim() &&+ updates[field] !== previous[field]+ ) {+ updates[`${field}_sync_operation`] = "set";+ } else if (updates[field] !== undefined && !updates[field]?.trim()) {+ // Preserve the existing local save contract, but never turn an+ // untrusted blank into a sync operation.+ updates[`${field}_sync_operation`] =+ !previous[field]?.trim() && previous[`${field}_sync_operation`] === "clear"+ ? "clear"+ : null;+ }+ }+ if (+ !clears.includes("enhanced_content") &&+ (updates.enhanced_content === undefined || updates.enhanced_content?.trim()) &&+ (updates.enhanced_content ?? previous.enhanced_content)?.trim() &&+ SUMMARY_METADATA.some((key) => updates[key] !== undefined && updates[key] !== previous[key])+ ) {+ updates.enhanced_content_sync_operation = "set";+ }+ delete updates.clear_fields;delete updates.account_id;+ delete updates.cloud_revision;+ delete updates.cloud_create_rejected;+ delete updates.cloud_create_pending;+ if (+ updates.cloud_id === null ||+ (updates.client_note_id && updates.client_note_id !== previous.client_note_id)+ ) {+ updates.cloud_revision = null;+ updates.cloud_create_rejected = 0;+ updates.cloud_create_pending = null;+ }if (updates.folder_id != null) {// D2: a note's space always follows its folder's space.const folder = this._getFolderInAccountScope(updates.folder_id);@@ -3347,6 +3471,11 @@ class DatabaseManager {}}const allowedFields = [+ "content_sync_operation",+ "enhanced_content_sync_operation",+ "cloud_revision",+ "cloud_create_rejected",+ "cloud_create_pending","title","content","enhanced_content",@@ -3379,6 +3508,21 @@ class DatabaseManager {}}if (fields.length === 0) return { success: false };+ // Undo can return to the submitted text within the same SQLite second.+ // Keep that newer intent distinct from the in-flight request snapshot.+ for (const field of NOTE_TEXT_FIELDS) {+ const keys = [+ field,+ `${field}_sync_operation`,+ ...(field === "enhanced_content" ? SUMMARY_METADATA : []),+ ];+ if (+ clears.includes(field) ||+ keys.some((key) => updates[key] !== undefined && updates[key] !== previous[key])+ ) {+ fields.push(`${field}_edit_generation = ${field}_edit_generation + 1`);+ }+ }// Re-queue for cloud sync on any local edit, so post-sync field changes aren't// left local-only and overwritten by a later pull.if (!("sync_status" in updates)) {@@ -4110,7 +4254,7 @@ class DatabaseManager {.map((row) => row.id);if (preservedIds.length > 0) {const relocateNote = this.db.prepare(- "UPDATE notes SET space_id = ?, folder_id = NULL, client_note_id = ?, cloud_id = NULL, cloud_updated_at = NULL, owner_user_id = NULL, updated_by_user_id = NULL, sync_status = 'pending', left_team = 0, is_shared = 0, share_token = NULL, updated_at = datetime('now') WHERE id = ?"+ "UPDATE notes SET space_id = ?, folder_id = NULL, client_note_id = ?, cloud_id = NULL, cloud_updated_at = NULL, cloud_revision = NULL, cloud_create_rejected = 0, cloud_create_pending = NULL, owner_user_id = NULL, updated_by_user_id = NULL, sync_status = 'pending', left_team = 0, is_shared = 0, share_token = NULL, updated_at = datetime('now') WHERE id = ?");const detachNoteConversation = this.db.prepare("UPDATE agent_conversations SET space_id = NULL, folder_id = NULL WHERE note_id = ?"@@ -6221,6 +6365,43 @@ class DatabaseManager {if (!this.db) throw new Error("Database not initialized");const spaceId = localSpaceId ?? this.getPrivateSpaceId();const accountId = this._accountIdForSpace(spaceId);+ const existing = this.db+ .prepare("SELECT * FROM notes WHERE client_note_id = ?")+ .get(cloudNote.client_note_id);+ // Rows without an account (created signed out or before attribution) and+ // personal<->team moves are adopted as before; only another account's+ // row or another cloud row is left alone. Never throw: one bad row would+ // abort the whole pull and stall its cursor.+ const otherAccount = existing?.account_id && accountId && existing.account_id !== accountId;+ const otherCloudRow = existing?.cloud_id && existing.cloud_id !== cloudNote.id;+ if (otherAccount || otherCloudRow) {+ debugLogger.warn(+ "Skipping cloud note that belongs to another local row",+ { otherAccount: Boolean(otherAccount), otherCloudRow: Boolean(otherCloudRow) },+ "database"+ );+ // IPC broadcasts every returned note, so a skipped row must stay private.+ return null;+ }+ const versioned = hasNoteRevision(cloudNote.revision);+ // A copy older than the revision this device acknowledged is stale. One+ // without a revision (an API that predates them) applies as before and+ // drops the local revision.+ if (+ versioned &&+ hasNoteRevision(existing?.cloud_revision) &&+ cloudNote.revision < existing.cloud_revision+ )+ return existing;+ const cleared = versioned ? clearedNoteFields(cloudNote) : [];+ const clearsContent = cleared.includes("content");+ const clearsSummary = cleared.includes("enhanced_content");+ cloudNote = { ...cloudNote };+ if (!cloudNote.content?.trim()) cloudNote.content = "";+ if (!cloudNote.enhanced_content?.trim()) cloudNote.enhanced_content = null;+ if (clearsSummary) {+ for (const key of SUMMARY_CLEARED_METADATA) cloudNote[key] = null;+ }const hasExplicitCreator = Object.prototype.hasOwnProperty.call(cloudNote,"created_by_user_id"@@ -6238,40 +6419,42 @@ class DatabaseManager {const updaterUpdate = hasExplicitUpdater? "excluded.updated_by_user_id": "updated_by_user_id";+ // Sync must never replace non-empty local content/enhanced_content/+ // transcript with an empty cloud value (#1290, the #938 invariant),+ // unless the cloud recorded that empty value as a deliberate clear.+ // The enhancement prompt/hash/template travel with enhanced_content.+ const keepsLocalContent = clearsContent+ ? "0"+ : "COALESCE(excluded.content, '') = '' AND COALESCE(content, '') <> ''";+ const keepsLocalSummary = clearsSummary+ ? "0"+ : "COALESCE(excluded.enhanced_content, '') = '' AND COALESCE(enhanced_content, '') <> ''";// An API that predates template ids omits the key; keep the local one.const templateIdUpdate = Object.prototype.hasOwnProperty.call(cloudNote,"enhancement_template_id")- ? `CASE- WHEN COALESCE(excluded.enhanced_content, '') = '' AND COALESCE(enhanced_content, '') <> ''+ ? `CASE WHEN ${keepsLocalSummary}THEN enhancement_template_id ELSE excluded.enhancement_template_id END`: "enhancement_template_id";- // Sync must never replace non-empty local content/enhanced_content/- // transcript with an empty cloud value (#1290, the #938 invariant).- // The enhancement prompt/hash/template travel with enhanced_content.const stmt = this.db.prepare(`INSERT INTO notes (client_note_id, cloud_id, title, content, enhanced_content,enhancement_prompt, enhancement_template_id, enhanced_at_content_hash, note_type, source_file,audio_duration_seconds, transcript, folder_id, space_id, participants, calendar_event_id,diarization_enabled, expected_speaker_count, updated_by_user_id, owner_user_id, created_by_user_id, sync_status, created_at, updated_at,- cloud_updated_at, account_id)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?, ?, ?)+ cloud_updated_at, account_id, cloud_revision)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?, ?, ?, ?)ON CONFLICT(client_note_id) DO UPDATE SETcloud_id = excluded.cloud_id,title = excluded.title,- content = CASE- WHEN COALESCE(excluded.content, '') = '' AND COALESCE(content, '') <> ''+ content = CASE WHEN ${keepsLocalContent}THEN content ELSE excluded.content END,- enhanced_content = CASE- WHEN COALESCE(excluded.enhanced_content, '') = '' AND COALESCE(enhanced_content, '') <> ''+ enhanced_content = CASE WHEN ${keepsLocalSummary}THEN enhanced_content ELSE excluded.enhanced_content END,- enhancement_prompt = CASE- WHEN COALESCE(excluded.enhanced_content, '') = '' AND COALESCE(enhanced_content, '') <> ''+ enhancement_prompt = CASE WHEN ${keepsLocalSummary}THEN enhancement_prompt ELSE excluded.enhancement_prompt END,enhancement_template_id = ${templateIdUpdate},- enhanced_at_content_hash = CASE- WHEN COALESCE(excluded.enhanced_content, '') = '' AND COALESCE(enhanced_content, '') <> ''+ enhanced_at_content_hash = CASE WHEN ${keepsLocalSummary}THEN enhanced_at_content_hash ELSE excluded.enhanced_at_content_hash END,transcript = CASEWHEN COALESCE(excluded.transcript, '') = '' AND COALESCE(transcript, '') <> ''@@ -6289,7 +6472,12 @@ class DatabaseManager {sync_status = 'synced',left_team = 0,updated_at = excluded.updated_at,- cloud_updated_at = excluded.cloud_updated_at+ cloud_updated_at = excluded.cloud_updated_at,+ cloud_revision = excluded.cloud_revision,+ cloud_create_rejected = 0,+ cloud_create_pending = NULL,+ content_sync_operation = NULL,+ enhanced_content_sync_operation = NULL`);stmt.run(cloudNote.client_note_id,@@ -6316,7 +6504,8 @@ class DatabaseManager {cloudNote.created_at,cloudNote.updated_at,cloudNote.updated_at,- accountId+ accountId,+ versioned ? cloudNote.revision : null);return this.db.prepare("SELECT * FROM notes WHERE client_note_id = ?")@@ -6365,14 +6554,24 @@ class DatabaseManager {// base/owner. A purge forks the client_note_id, so the relocated Personal// row is never mutated. Partial migration creates explicitly opt out of// settling so a later full PATCH still delivers fields the POST omitted.+ // writeRejected links a create the server refused without writing it, so+ // the row stays parked until a pull resolves it (cloud_create_rejected).acknowledgeNoteCreate(id,snapshot,cloudId,cloudUpdatedAt = null,ownerUserId = null,- settleIfUnchanged = true+ options = {}) {+ let { settleIfUnchanged = true } = options;+ const {+ cloudRevision = null,+ writeRejected = false,+ cloudNote = null,+ requiresReconciliation = false,+ reconcilePending = false,+ } = options;try {if (!this.db) throw new Error("Database not initialized");if (!this.getNote(id)) {@@ -6397,7 +6596,10 @@ class DatabaseManager {};}- if (current.cloud_id) {+ if (+ current.cloud_id &&+ !(reconcilePending && current.cloud_create_pending && current.cloud_id === cloudId)+ ) {// Concurrent creates should be idempotent and return the same id.// A different id is ambiguous, though, so never replace the adopted// identity or authorize destructive cleanup in that case.@@ -6407,38 +6609,142 @@ class DatabaseManager {};}+ if (reconcilePending && current.cloud_create_pending) {+ const pending = JSON.parse(current.cloud_create_pending);+ snapshot = pending.snapshot;+ settleIfUnchanged = pending.settleIfUnchanged;+ if (!cloudNote) return { success: true, outcome: "awaiting-cloud" };+ if (+ hasNoteRevision(pending.revision) &&+ hasNoteRevision(cloudRevision) &&+ cloudRevision < pending.revision+ )+ return { success: true, outcome: "awaiting-cloud" };+ if (+ !hasNoteRevision(pending.revision) &&+ pending.updatedAt &&+ Date.parse(cloudUpdatedAt) < Date.parse(pending.updatedAt)+ )+ return { success: true, outcome: "awaiting-cloud" };+ const sameReceipt = hasNoteRevision(pending.revision)+ ? cloudRevision === pending.revision+ : Boolean(+ pending.updatedAt && Date.parse(pending.updatedAt) === Date.parse(cloudUpdatedAt)+ );+ if (!sameReceipt) {+ // A pull can already contain another device's newer write. Only+ // an unchanged full create can take it without a conflict choice.+ if (+ !settleIfUnchanged ||+ hasPendingNoteClear(snapshot) ||+ !rowMatchesSnapshot(current, snapshot, NOTE_CREATE_ACK_FIELDS) ||+ options.localSpaceId === undefined+ )+ return { success: true, outcome: "conflict" };+ const note = this.upsertNoteFromCloud(+ {+ ...cloudNote,+ id: cloudId,+ client_note_id: expectedClientNoteId,+ updated_at: cloudUpdatedAt,+ revision: cloudRevision,+ },+ options.localFolderId ?? null,+ options.localSpaceId+ );+ return { success: true, outcome: "synced", note };+ }+ }const unchanged = rowMatchesSnapshot(current, snapshot, NOTE_CREATE_ACK_FIELDS);-- // If a team note was moved to Personal while POST was in flight, the- // returned cloud row still lives in the old team. Mark the attached- // identity as owing a scope retraction even when backup is disabled.const leftTeam = this._leftTeamDuringPush(snapshot.space_id, current.space_id);- if (unchanged && settleIfUnchanged) {+ // A metadata-only receipt proves identity, not which text survived+ // the upsert. Save its request and keep every push gated until a pull+ // reconciles that exact receipt (including after restart).+ if (requiresReconciliation) {+ this.db+ .prepare(+ `UPDATE notes SET cloud_id = ?, owner_user_id = ?,+ sync_status = CASE WHEN sync_status = 'synced' THEN 'pending' ELSE sync_status END,+ cloud_create_pending = ?,+ left_team = CASE WHEN ? = 1 THEN 1 ELSE left_team END+ WHERE id = ? AND client_note_id = ?`+ )+ .run(+ cloudId,+ ownerUserId,+ JSON.stringify({+ snapshot: {+ ...snapshot,+ sync_status: snapshot.sync_status === "synced" ? "pending" : snapshot.sync_status,+ },+ settleIfUnchanged,+ revision: cloudRevision,+ updatedAt: cloudUpdatedAt,+ }),+ leftTeam,+ id,+ expectedClientNoteId+ );+ return { success: true, outcome: "awaiting-cloud" };+ }++ // A create's submitted set may have been ignored by the server. Take+ // the returned copy only for bundles still equal to that submission,+ // and retire those sets even when another field was edited in flight.+ // POST never delivers a deliberate clear; it still owes a PATCH.+ if (cloudNote && !writeRejected) {+ const adopted = acknowledgedCreateTextUpdates(current, snapshot, cloudNote);+ noteUndo.preserveUnchangedUndo(this, id, Object.keys(adopted), () => {+ this._setNoteColumns(id, adopted);+ });+ }++ // A clear still follows as a revisioned PATCH. A team-to-Personal+ // move stays pending for its scope retraction, even with backup off.+ if (unchanged && settleIfUnchanged && !hasPendingNoteClear(snapshot) && !writeRejected) {this.db.prepare(`UPDATE notesSET sync_status = 'synced', cloud_id = ?, left_team = 0,- cloud_updated_at = ?,- owner_user_id = ?- WHERE id = ? AND client_note_id = ? AND cloud_id IS NULL`+ cloud_updated_at = ?, cloud_revision = ?,+ owner_user_id = ?,+ content_sync_operation = NULL, enhanced_content_sync_operation = NULL,+ cloud_create_pending = NULL+ WHERE id = ? AND client_note_id = ?`)- .run(cloudId, cloudUpdatedAt, ownerUserId, id, expectedClientNoteId);- return { success: true, outcome: "synced" };+ .run(+ cloudId,+ cloudUpdatedAt,+ hasNoteRevision(cloudRevision) ? cloudRevision : null,+ ownerUserId,+ id,+ expectedClientNoteId+ );+ return { success: true, outcome: "synced", ...(cloudNote && { note: this.getNote(id) }) };}this.db.prepare(`UPDATE notesSET cloud_id = ?,- cloud_updated_at = ?,+ cloud_updated_at = ?, cloud_revision = ?,owner_user_id = ?,- sync_status = 'pending',+ sync_status = 'pending', cloud_create_rejected = ?, cloud_create_pending = NULL,left_team = CASE WHEN ? = 1 THEN 1 ELSE left_team END- WHERE id = ? AND client_note_id = ? AND cloud_id IS NULL`+ WHERE id = ? AND client_note_id = ?`)- .run(cloudId, cloudUpdatedAt, ownerUserId, leftTeam, id, expectedClientNoteId);- return { success: true, outcome: "pending" };+ .run(+ cloudId,+ cloudUpdatedAt,+ hasNoteRevision(cloudRevision) ? cloudRevision : null,+ ownerUserId,+ writeRejected ? 1 : 0,+ leftTeam,+ id,+ expectedClientNoteId+ );+ return { success: true, outcome: "pending", ...(cloudNote && { note: this.getNote(id) }) };})();} catch (error) {debugLogger.error("Error acknowledging note create", { error: error.message }, "database");@@ -6450,12 +6756,18 @@ class DatabaseManager {// identity that issued it. Purge/revocation forks in place, so numeric id// alone is never sufficient. An exact pushed snapshot settles; newer work// on the same identity remains pending while advancing its server base.+ // cloudNote is the response row: a text field this device pushed without+ // an edit and has not touched since takes the server's copy (see+ // cloudTextUpdates), so the ack never pins a revision over text the server+ // no longer holds (a clear this device missed, or a blank it left out).markNoteSyncedIfUnchanged(id,snapshot,expectedCloudId,cloudUpdatedAt = null,- ownerUserId = null+ ownerUserId = null,+ cloudRevision = null,+ cloudNote = null) {try {if (!this.db) throw new Error("Database not initialized");@@ -6476,7 +6788,33 @@ class DatabaseManager {return { success: true, outcome: "identity-changed", changes: 0 };}+ if (current.cloud_create_rejected || current.cloud_create_pending)+ return { success: true, outcome: "pending", changes: 0 };+ // An older response arriving out of order must not regress the+ // revision. A response without one (an API that predates revisions)+ // drops it, so pushes fall back to the timestamp base.+ const incomingRevision = hasNoteRevision(cloudRevision) ? cloudRevision : null;+ if (+ incomingRevision !== null &&+ hasNoteRevision(current.cloud_revision) &&+ incomingRevision < current.cloud_revision+ ) {+ return { success: true, outcome: "pending", changes: 0 };+ }const unchanged = rowMatchesSnapshot(current, snapshot, NOTE_PATCH_ACK_FIELDS);+ const adopted = cloudNote+ ? cloudTextUpdates(+ current,+ cloudNote,+ NOTE_TEXT_FIELDS.filter(+ (field) =>+ !current[`${field}_sync_operation`] &&+ noteTextMatchesSnapshot(current, snapshot, field)+ )+ )+ : {};+ this._setNoteColumns(id, adopted);+ const note = Object.keys(adopted).length > 0 ? this.getNote(id) : undefined;const nextCloudUpdatedAt = (() => {if (!cloudUpdatedAt) return current.cloud_updated_at;if (!current.cloud_updated_at) return cloudUpdatedAt;@@ -6494,13 +6832,20 @@ class DatabaseManager {const result = this.db.prepare(`UPDATE notes- SET sync_status = 'synced', left_team = 0,- cloud_updated_at = ?,+ SET sync_status = 'synced', left_team = 0, content_sync_operation = NULL, enhanced_content_sync_operation = NULL,+ cloud_updated_at = ?, cloud_revision = ?,owner_user_id = COALESCE(?, owner_user_id)WHERE id = ? AND client_note_id = ? AND cloud_id = ?`)- .run(nextCloudUpdatedAt, ownerUserId, id, snapshot.client_note_id, expectedCloudId);- return { success: true, outcome: "synced", changes: result.changes };+ .run(+ nextCloudUpdatedAt,+ incomingRevision,+ ownerUserId,+ id,+ snapshot.client_note_id,+ expectedCloudId+ );+ return { success: true, outcome: "synced", changes: result.changes, note };}// The delivered PATCH still advances this identity's base; otherwise@@ -6510,12 +6855,19 @@ class DatabaseManager {this.db.prepare(`UPDATE notes- SET cloud_updated_at = ?,+ SET cloud_updated_at = ?, cloud_revision = ?,owner_user_id = COALESCE(?, owner_user_id)WHERE id = ? AND client_note_id = ? AND cloud_id = ?`)- .run(nextCloudUpdatedAt, ownerUserId, id, snapshot.client_note_id, expectedCloudId);- return { success: true, outcome: "pending", changes: 0 };+ .run(+ nextCloudUpdatedAt,+ incomingRevision,+ ownerUserId,+ id,+ snapshot.client_note_id,+ expectedCloudId+ );+ return { success: true, outcome: "pending", changes: 0, note };})();} catch (error) {debugLogger.error(@@ -6572,21 +6924,136 @@ class DatabaseManager {}}+ // Clean cloud-backed notes synced before the server kept revisions. Their+ // server rows may never re-enter a delta pull, so a snapshot pull applies+ // them while any remain. spaceKind narrows like getPendingNotes.+ countNotesMissingRevision(spaceKind = null) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const accountScope = this._accountScopeCondition("n");+ const row = this.db+ .prepare(+ `SELECT COUNT(*) AS count FROM notes n+ JOIN spaces s ON s.id = n.space_id+ WHERE n.sync_status = 'synced' AND n.deleted_at IS NULL+ AND n.cloud_id IS NOT NULL AND n.cloud_revision IS NULL+ AND (? IS NULL OR s.kind = ?)+ AND ${accountScope.sql}`+ )+ .get(spaceKind, spaceKind, ...accountScope.params);+ return row?.count ?? 0;+ } catch (error) {+ debugLogger.error(+ "Error counting notes missing a revision",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }+// Records the server revision the user knowingly overwrites ("Keep editing"- // on the conflict banner). Deliberately leaves updated_at and sync_status- // alone — the local edit stays pending and pushes with the advanced base.- setNoteCloudBase(id, cloudUpdatedAt) {+ // on the conflict banner, keepLocal) or that a pull found equal to this+ // device's base. Deliberately leaves updated_at and sync_status alone — a+ // local edit stays pending and pushes with the advanced base. Keep merges+ // per field against the conflicting cloud copy: a field this device edited+ // (it has a sync operation) keeps the local value, and one it never edited+ // takes the cloud's, set or clear, so Keep never pushes a stale copy over+ // another device's edit.+ setNoteCloudBase(id, cloudUpdatedAt, cloudRevision = null, options = {}) {+ const { keepLocal = false, cloudNote = null } = options;try {if (!this.db) throw new Error("Database not initialized");- if (!this.getNote(id)) return { success: false };- this.db.prepare("UPDATE notes SET cloud_updated_at = ? WHERE id = ?").run(cloudUpdatedAt, id);- return { success: true };+ return this.db.transaction(() => {+ const current = this.getNote(id);+ if (!current) return { success: false };+ const revision = hasNoteRevision(cloudRevision) ? cloudRevision : null;+ if (+ hasNoteRevision(current.cloud_revision) &&+ revision !== null &&+ revision < current.cloud_revision+ )+ return { success: false };+ if (keepLocal && cloudNote) {+ // A deferred create may already have delivered (or had the server+ // discard) these sets. Keep preserves edits made after that POST,+ // not the unchanged submitted text a newer cloud copy cleared.+ const acknowledged = current.cloud_create_pending+ ? acknowledgedCreateTextUpdates(+ current,+ JSON.parse(current.cloud_create_pending).snapshot,+ cloudNote+ )+ : {};+ const merged = { ...current, ...acknowledged };+ const adopted = {+ ...acknowledged,+ ...cloudTextUpdates(+ merged,+ cloudNote,+ NOTE_TEXT_FIELDS.filter((field) => !merged[`${field}_sync_operation`])+ ),+ };+ noteUndo.preserveUnchangedUndo(this, id, Object.keys(adopted), () => {+ this._setNoteColumns(id, adopted);+ });+ }+ this.db+ .prepare(+ `UPDATE notes SET cloud_updated_at = ?, cloud_revision = ?,+ cloud_create_rejected = CASE WHEN ? THEN 0 ELSE cloud_create_rejected END,+ cloud_create_pending = CASE WHEN ? THEN NULL ELSE cloud_create_pending END+ WHERE id = ?`+ )+ .run(cloudUpdatedAt, revision, keepLocal ? 1 : 0, keepLocal ? 1 : 0, id);+ return { success: true, note: this.getNote(id) };+ })();} catch (error) {debugLogger.error("Error setting note cloud base", { error: error.message }, "database");throw error;}}+ // Runs once, when the sync operation columns are added. Unsynced text from+ // a build without them is the user's own edit, so it is marked as a set:+ // Keep then keeps it rather than taking the cloud's copy, and a+ // revision-aware push sends it. A blank stays unmarked, since a released+ // build's blank is no deliberate clear. A database that predates sync+ // status has never synced any of its notes.+ _markUnsyncedNoteTextAsSet() {+ const hasSyncStatus = this.db+ .prepare("PRAGMA table_info(notes)")+ .all()+ .some((column) => column.name === "sync_status");+ const rows = this.db+ .prepare(+ `SELECT id, content, enhanced_content FROM notes+ ${hasSyncStatus ? "WHERE sync_status IS NOT 'synced'" : ""}`+ )+ .all();+ const mark = this.db.prepare(+ `UPDATE notes SET content_sync_operation = ?, enhanced_content_sync_operation = ?+ WHERE id = ?`+ );+ this.db.transaction(() => {+ for (const row of rows) {+ const content = typedTextOperation(row.content);+ const summary = typedTextOperation(row.enhanced_content);+ if (content || summary) mark.run(content, summary, row.id);+ }+ })();+ }++ // Writes sync-owned columns (from cloudTextUpdates) without touching+ // updated_at or sync_status. Keys come from that fixed set, never input.+ _setNoteColumns(id, columns) {+ const keys = Object.keys(columns);+ if (keys.length === 0) return;+ this.db+ .prepare(`UPDATE notes SET ${keys.map((key) => `${key} = ?`).join(", ")} WHERE id = ?`)+ .run(...Object.values(columns), id);+ }+markNoteSyncError(id) {try {if (!this.db) throw new Error("Database not initialized");@@ -6941,7 +7408,7 @@ class DatabaseManager {this._deleteSpeakerRowsForNotes(serverOwnedChildren, id);this.db.prepare(`DELETE FROM notes WHERE id IN (${serverOwnedChildren})`).run(id);const relocateNote = this.db.prepare(- "UPDATE notes SET space_id = ?, folder_id = ?, client_note_id = ?, cloud_id = NULL, cloud_updated_at = NULL, owner_user_id = NULL, updated_by_user_id = NULL, sync_status = 'pending', left_team = 0, is_shared = 0, share_token = NULL, updated_at = datetime('now') WHERE id = ?"+ "UPDATE notes SET space_id = ?, folder_id = ?, client_note_id = ?, cloud_id = NULL, cloud_updated_at = NULL, cloud_revision = NULL, cloud_create_rejected = 0, cloud_create_pending = NULL, owner_user_id = NULL, updated_by_user_id = NULL, sync_status = 'pending', left_team = 0, is_shared = 0, share_token = NULL, updated_at = datetime('now') WHERE id = ?");const detachNoteConversation = this.db.prepare("UPDATE agent_conversations SET space_id = NULL, folder_id = NULL WHERE note_id = ?"diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 9e70c47de..d9d50f75a 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -2711,33 +2711,51 @@ class IPCHandlers {});ipcMain.handle("db-acknowledge-note-create",- (_, id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged) =>- this.databaseManager.acknowledgeNoteCreate(+ (_, id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, options) => {+ const result = this.databaseManager.acknowledgeNoteCreate(id,snapshot,cloudId,cloudUpdatedAt,ownerUserId,- settleIfUnchanged- )+ options+ );+ if (result.note) {+ setImmediate(() => broadcastToWindows("note-synced", result.note));+ this.notifyVectorChanges();+ }+ return result;+ });ipcMain.handle("db-mark-note-synced-if-unchanged",- (_, id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId) =>- this.databaseManager.markNoteSyncedIfUnchanged(+ (_, id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId, cloudRevision, cloudNote) => {+ const result = this.databaseManager.markNoteSyncedIfUnchanged(id,snapshot,expectedCloudId,cloudUpdatedAt,- ownerUserId- )+ ownerUserId,+ cloudRevision,+ cloudNote+ );+ // The ack took the server's copy of a field: refresh open editors.+ if (result.note) {+ setImmediate(() => broadcastToWindows("note-synced", result.note));+ this.notifyVectorChanges();+ }+ return result;+ });- ipcMain.handle("db-set-note-cloud-base", (_, id, cloudUpdatedAt) =>- this.databaseManager.setNoteCloudBase(id, cloudUpdatedAt)+ ipcMain.handle("db-set-note-cloud-base", (_, id, cloudUpdatedAt, cloudRevision, options) =>+ this.databaseManager.setNoteCloudBase(id, cloudUpdatedAt, cloudRevision, options));ipcMain.handle("db-set-note-owner-from-cloud", (_, id, ownerUserId) =>this.databaseManager.setNoteOwnerFromCloud(id, ownerUserId));+ ipcMain.handle("db-count-notes-missing-revision", (_, spaceKind) =>+ this.databaseManager.countNotesMissingRevision(spaceKind)+ );ipcMain.handle("db-count-team-notes-missing-owner", () =>this.databaseManager.countTeamNotesMissingOwner());diff --git a/src/helpers/noteFieldSync.js b/src/helpers/noteFieldSync.jsnew file mode 100644index 000000000..c0df6571a--- /dev/null+++ b/src/helpers/noteFieldSync.js@@ -0,0 +1,82 @@+export const NOTE_TEXT_FIELDS = ["content", "enhanced_content"];++// What a summary clear removes along with the text. The template stays: it is+// the note's choice, so "Generate AI Summary" reruns the same one.+export const SUMMARY_CLEARED_METADATA = ["enhancement_prompt", "enhanced_at_content_hash"];+// Everything that travels with the summary text.+export const SUMMARY_METADATA = [...SUMMARY_CLEARED_METADATA, "enhancement_template_id"];++export function hasNoteRevision(value) {+ return Number.isSafeInteger(value) && value >= 0;+}++export function hasPendingNoteClear(note) {+ return NOTE_TEXT_FIELDS.some((field) => note[`${field}_sync_operation`] === "clear");+}++// Only local edit intent is sent. A pulled snapshot must never become a set+// operation merely because another field (for example the title) was edited.+export function noteFieldUpdates(note) {+ return Object.fromEntries(+ NOTE_TEXT_FIELDS.flatMap((field) => {+ const operation = note[`${field}_sync_operation`];+ return operation === "set" || operation === "clear" ? [[field, operation]] : [];+ })+ );+}++// Fields a cloud copy deliberately cleared (not merely blank).+/** @returns {Array<"content" | "enhanced_content">} */+export function clearedNoteFields(cloudNote) {+ return NOTE_TEXT_FIELDS.filter(+ (field) => cloudNote[`${field}_state`] === "clear" && !cloudNote[field]?.trim()+ );+}++// Column values that bring local text fields to the cloud's copy: its text, or+// a clear it recorded, with the summary metadata that travels with it. Only+// columns that differ are returned. A blank the cloud never marked as a clear+// is no evidence of deletion (an older API, or a released desktop's blank), so+// it keeps the local text, as a pull does.+/** @returns {Record<string, string | null>} */+export function cloudTextUpdates(local, cloudNote, fields) {+ const cleared = clearedNoteFields(cloudNote);+ const updates = {};+ for (const field of fields) {+ const text = cloudNote[field]?.trim() ? cloudNote[field] : null;+ if (!text && !cleared.includes(field)) continue;+ const next = { [field]: text ?? (field === "content" ? "" : null) };+ if (field === "enhanced_content") {+ for (const key of SUMMARY_METADATA) {+ if (!text && SUMMARY_CLEARED_METADATA.includes(key)) next[key] = null;+ else if (cloudNote[key] !== undefined) next[key] = cloudNote[key];+ }+ }+ for (const [key, value] of Object.entries(next)) {+ if ((local[key] ?? null) !== value) updates[key] = value;+ }+ }+ return updates;+}++// A clear on a cloud row this device holds no revision for. Without a+// revision the push is legacy-shaped, and the server stores a desktop's+// legacy blank as unknown intent rather than a clear, so other devices would+// keep the text. The pull supplies a revision first.+export function hasUnrevisionedNoteClear(note) {+ return Boolean(+ note.cloud_id && hasPendingNoteClear(note) && !hasNoteRevision(note.cloud_revision)+ );+}++// A push must wait for a pull to resolve these first: a rejected create until+// Keep/Refresh links it to the actual cloud row, and a clear without a+// revision while the server keeps revisions (the pull supplies one). Against+// an API without revisions such a clear pushes as it always has.+export function noteAwaitsCloudResolution(note, serverKeepsRevisions) {+ return Boolean(+ note.cloud_create_rejected ||+ note.cloud_create_pending ||+ (serverKeepsRevisions && hasUnrevisionedNoteClear(note))+ );+}diff --git a/src/helpers/noteUndo.js b/src/helpers/noteUndo.jsindex ee8d581db..55dfbacc6 100644--- a/src/helpers/noteUndo.js+++ b/src/helpers/noteUndo.js@@ -1,4 +1,5 @@const { randomUUID } = require("crypto");+const { NOTE_TEXT_FIELDS, SUMMARY_CLEARED_METADATA } = require("./noteFieldSync");// Sync acknowledgements are not edits. All semantic changes (including SQL// writers outside updateNote) retire the previous assistant's recovery token.@@ -100,6 +101,10 @@ function updateNoteWithUndo(manager, id, updates, expected, turn) {const live = liveUndo(manager, "note_id", id);const result = manager.updateNote(id, updates);if (!result.success) return result;+ // A summary clear also resets its prompt and hash; Undo restores them too.+ for (const key of SUMMARY_CLEARED_METADATA) {+ if (!(key in previous) && before[key] !== result.note[key]) previous[key] = before[key];+ }// Edits of one note in the same turn (e.g. a summary rewrite and a rename)// share one Undo that restores each field's oldest value.const sameTurn = turn != null && live && undoTurns.get(live.token) === turn;@@ -125,6 +130,24 @@ function liveUndo(manager, column, value) {.get(value, manager.activeAccountId, Date.now() - UNDO_TTL_MS);}+// Reconciliation of an untouched field is not a later edit to the fields a+// live Undo restores. The normal trigger still retires overlapping recoveries.+function preserveUnchangedUndo(manager, id, changedFields, write) {+ if (!changedFields.length || !manager.noteUndoReady) return write();+ const saved = liveUndo(manager, "note_id", id);+ const preserves =+ saved && !Object.keys(JSON.parse(saved.previous)).some((key) => changedFields.includes(key));+ const result = write();+ if (preserves) {+ manager.db+ .prepare(+ "INSERT OR REPLACE INTO assistant_note_undo (note_id, token, account_id, previous, created_at) VALUES (?, ?, ?, ?, ?)"+ )+ .run(saved.note_id, saved.token, saved.account_id, saved.previous, saved.created_at);+ }+ return result;+}+function getNoteUndos(manager) {const scope = manager._accountScopeCondition("notes");return manager.db@@ -150,7 +173,13 @@ function undoNoteUpdate(manager, token) {return { success: false, error: "note_changed" };}}- const result = manager.updateNote(note.id, previous);+ // Restoring an empty field is a deliberate clear, so it syncs; a bare blank+ // would stay on this device while the edit came back from the cloud.+ const clearFields = NOTE_TEXT_FIELDS.filter((key) => key in previous && !previous[key]?.trim());+ const result = manager.updateNote(note.id, {+ ...previous,+ ...(clearFields.length > 0 && { clear_fields: clearFields }),+ });if (result.success)manager.db.prepare("DELETE FROM assistant_note_undo WHERE token = ?").run(token);return result;@@ -184,4 +213,5 @@ module.exports = {claimNoteUndo,undoNoteUpdate,discardNoteUndo,+ preserveUnchangedUndo,};diff --git a/src/lib/noteEditorPendingSave.ts b/src/lib/noteEditorPendingSave.tsindex a0c12212a..294f3880a 100644--- a/src/lib/noteEditorPendingSave.ts+++ b/src/lib/noteEditorPendingSave.ts@@ -13,6 +13,15 @@ export interface PendingDocumentSnapshot {readonly noteId: number;readonly title: string;readonly content: string;+ /**+ * The user edited the notes before this save. Otherwise the save writes only+ * the title: the draft's notes may predate a pull or ack the store applied+ * meanwhile, and writing them back would undo it (a cleared field would+ * return as an edit).+ */+ readonly contentEdited: boolean;+ /** The user emptied the notes, so the save is a deliberate clear that syncs. */+ readonly clearContent: boolean;}export interface PendingEnhancedSnapshot {@@ -24,6 +33,7 @@ export type PendingNoteUpdates = {readonly title?: string;readonly content?: string;readonly enhanced_content?: string | null;+ readonly clear_fields?: Array<"content" | "enhanced_content">;};export interface PendingNoteWrite {@@ -63,36 +73,48 @@ export function applyNoteDraftMutation(return { ...draft, [mutation.field]: mutation.value };}+export function documentSaveUpdates(document: PendingDocumentSnapshot): PendingNoteUpdates {+ if (!document.contentEdited && !document.clearContent) return { title: document.title };+ return {+ title: document.title,+ content: document.content,+ ...(document.clearContent && { clear_fields: ["content"] }),+ };+}++export function enhancedSaveUpdates(enhanced: PendingEnhancedSnapshot): PendingNoteUpdates {+ return {+ enhanced_content: enhanced.enhancedContent,+ ...(!enhanced.enhancedContent?.trim() && { clear_fields: ["enhanced_content"] }),+ };+}+export function collectPendingNoteWrites(document: PendingDocumentSnapshot | null,enhanced: PendingEnhancedSnapshot | null): PendingNoteWrite[] {if (document && enhanced && document.noteId === enhanced.noteId) {+ const documentUpdates = documentSaveUpdates(document);+ const enhancedUpdates = enhancedSaveUpdates(enhanced);+ const clearFields = [+ ...(documentUpdates.clear_fields ?? []),+ ...(enhancedUpdates.clear_fields ?? []),+ ];return [{noteId: document.noteId,updates: {- title: document.title,- content: document.content,- enhanced_content: enhanced.enhancedContent,+ ...documentUpdates,+ ...enhancedUpdates,+ ...(clearFields.length > 0 && { clear_fields: clearFields }),},},];}const writes: PendingNoteWrite[] = [];- if (document) {- writes.push({- noteId: document.noteId,- updates: { title: document.title, content: document.content },- });- }- if (enhanced) {- writes.push({- noteId: enhanced.noteId,- updates: { enhanced_content: enhanced.enhancedContent },- });- }+ if (document) writes.push({ noteId: document.noteId, updates: documentSaveUpdates(document) });+ if (enhanced) writes.push({ noteId: enhanced.noteId, updates: enhancedSaveUpdates(enhanced) });return writes;}diff --git a/src/services/NotesService.ts b/src/services/NotesService.tsindex 98e3bb098..632284dcf 100644--- a/src/services/NotesService.ts+++ b/src/services/NotesService.ts@@ -1,5 +1,6 @@import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";import { buildNotesListPath } from "./noteListQuery";+import type { CloudNoteCreateResult } from "./noteCreateAck";interface NoteInput {client_note_id?: string;@@ -26,9 +27,16 @@ interface NoteInput {// last acked. The server 409s (note_version_conflict) when a newer write// landed; omitted = legacy last-write-wins.base_updated_at?: string;+ base_revision?: number;+ field_updates?: { content?: "set" | "clear"; enhanced_content?: "set" | "clear" };}export interface CloudNote {+ revision?: number;+ content_state?: "set" | "clear" | null;+ enhanced_content_state?: "set" | "clear" | null;+ write_applied?: boolean;+ row_created?: boolean;id: string;client_note_id: string | null;title: string | null;@@ -73,13 +81,12 @@ async function create(note: NoteInput): Promise<CloudNote> {return cloudPost<CloudNote>("/api/notes/create", note);}-async function batchCreate(- notes: NoteInput[]-): Promise<{ created: { client_note_id: string; id: string; updated_at?: string }[] }> {- return cloudPost<{ created: { client_note_id: string; id: string; updated_at?: string }[] }>(- "/api/notes/batch-create",- { notes }- );+interface NoteBatchCreateResult {+ created: CloudNoteCreateResult[];+}++async function batchCreate(notes: NoteInput[]): Promise<NoteBatchCreateResult> {+ return cloudPost<NoteBatchCreateResult>("/api/notes/batch-create", { notes });}async function update(id: string, updates: Partial<NoteInput>): Promise<CloudNote> {diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex 1d1a68648..a1333dd26 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -1,3 +1,8 @@+import {+ hasUnrevisionedNoteClear,+ hasNoteRevision,+ noteAwaitsCloudResolution,+} from "../helpers/noteFieldSync.js";import type {NoteItem,FolderItem,@@ -41,6 +46,7 @@ import {buildNoteCreatePayload,buildNoteUpdatePayload,isCloudEntryNewer,+ isCloudNoteNewer,normalizeTimestamp,} from "../helpers/cloudSyncGuards.js";import { resolveRendererCloudNoteCreate, type CloudNoteCreateResult } from "./noteCreateAck";@@ -251,6 +257,14 @@ export class SyncService {private snippetsDirty = false;// One owner_user_id backfill probe per session (see backfillNoteOwners).private ownerBackfillChecked = false;+ // Whether the API keeps note revisions; null until a pulled row or the+ // probe (noteRevisionsSupported) shows it.+ private noteRevisionsKnown: boolean | null = null;+ // One successful snapshot per session each for clears without a revision+ // (pushPendingNotes) and rows synced before revisions (backfillNoteRevisions).+ // Incomplete pulls retry on a later ordinary pass.+ private unrevisionedClearPullDone = false;+ private revisionBackfillChecked = false;private pushTimers = new Map<string, ReturnType<typeof setTimeout>>();private teamSpacesRetryTimer: ReturnType<typeof setTimeout> | null = null;private teamSpacesRetryAttempt = 0;@@ -799,6 +813,14 @@ export class SyncService {// it as local-wins (or 409-spam) before the user chose Keep or Refresh.return;}+ // Until a pass shows the server has no revisions, a clear on a row without+ // a revision waits for the full pass that resolves it.+ if (noteAwaitsCloudResolution(note, this.noteRevisionsKnown !== false)) {+ // Only a full pass resolves it; stay throttled so typing in the note+ // doesn't start one per debounced push.+ this.requestSyncAll("interval");+ return;+ }const { localToCloud, blockedFolderIds } = await this.buildLocalToCloudFolderMap();if (note.folder_id && blockedFolderIds.has(note.folder_id)) {@@ -827,7 +849,9 @@ export class SyncService {note,note.cloud_id,cloud.updated_at,- cloud.user_id ?? null+ cloud.user_id ?? null,+ cloud.revision ?? null,+ cloud);} else {await this.createCloudNote(note, cloudFolderId, scope);@@ -871,7 +895,10 @@ export class SyncService {note: NoteItem,cloud: CloudNoteCreateResult): Promise<void> {- await resolveRendererCloudNoteCreate(note, cloud, (cloudId) => NotesService.delete(cloudId));+ const outcome = await resolveRendererCloudNoteCreate(note, cloud, (cloudId) =>+ NotesService.delete(cloudId)+ );+ if (outcome === "write-rejected" || outcome === "awaiting-cloud") this.requestSyncAll("retry");}private async createCloudNote(@@ -1732,6 +1759,9 @@ export class SyncService {// A parked pull left its cursors in place, so the next pass re-sees the// parked rows — typically after syncSpaces has mirrored the missing team.await this.pullNotes(teamOnly);+ // After the delta pull, which usually shows whether the server keeps+ // revisions without a probe.+ await this.backfillNoteRevisions(teamOnly);}// Team notes mirrored before owner_user_id existed have a NULL owner, and@@ -1752,21 +1782,77 @@ export class SyncService {}}+ // Rows synced before revisions carry none, and an unchanged server row never+ // re-enters a delta pull, so a clear made elsewhere while this device ran a+ // release that kept the text would never arrive. One successful snapshot per+ // session applies them (pullNotes takes a clean pre-revision row whole),+ // and only against a server that keeps revisions: an older API would+ // otherwise repeat it every session for nothing.+ private async backfillNoteRevisions(teamOnly: boolean): Promise<void> {+ if (this.revisionBackfillChecked) return;+ try {+ const missing =+ (await window.electronAPI.countNotesMissingRevision?.(teamOnly ? "team" : undefined)) ?? 0;+ // An unanswered probe retries on the next pass.+ const supported = missing > 0 ? await this.noteRevisionsSupported() : false;+ if (supported === null) return;+ this.revisionBackfillChecked = !supported || (await this.pullNotes(teamOnly, true));+ } catch (err) {+ console.error("Note revision backfill failed:", err);+ }+ }++ // A pull usually answers this already; otherwise one row is enough to tell.+ private async noteRevisionsSupported(): Promise<boolean | null> {+ if (this.noteRevisionsKnown === null) {+ try {+ const { notes } = await NotesService.list(1);+ const row = notes.find((note) => !note.access_removed);+ if (row) this.noteRevisionsKnown = hasNoteRevision(row.revision);+ } catch (err) {+ console.error("Note revision probe failed:", err);+ }+ }+ return this.noteRevisionsKnown;+ }+private async pushPendingNotes(teamOnly = false): Promise<void> {- const pending =- (await window.electronAPI.getPendingNotes?.(teamOnly ? "team" : undefined)) ?? [];+ let pending = (await window.electronAPI.getPendingNotes?.(teamOnly ? "team" : undefined)) ?? [];+ const conflicted = readNoteConflictIds();+ // A surfaced conflict already holds its cloud copy; only rows still+ // awaiting one need the snapshot pull, as an unchanged cloud row may be+ // absent from the delta feed. A rejected create pulls until its conflict+ // surfaces; a clear on a row without a revision gets one successful+ // snapshot per session when the server keeps revisions (the pull adopts+ // one or surfaces a conflict, see pullNotes).+ const unresolved = pending.filter((note) => !conflicted.has(note.client_note_id));+ const pullsForUnrevisionedClear =+ !this.unrevisionedClearPullDone &&+ unresolved.some(hasUnrevisionedNoteClear) &&+ (await this.noteRevisionsSupported()) === true;+ if (+ pullsForUnrevisionedClear ||+ unresolved.some((note) => note.cloud_create_rejected || note.cloud_create_pending)+ ) {+ const pulled = await this.pullNotes(teamOnly, true);+ if (pullsForUnrevisionedClear && pulled) this.unrevisionedClearPullDone = true;+ pending = (await window.electronAPI.getPendingNotes?.(teamOnly ? "team" : undefined)) ?? [];+ }if (pending.length === 0) return;this.teamPassMovedWork = true;const { localToCloud, blockedFolderIds } = await this.buildLocalToCloudFolderMap();const ctx = await this.buildSpaceContext();- const conflicted = readNoteConflictIds();const pushable: Array<{ note: NoteItem; scope: PushScopeFields }> = [];for (const note of pending) {- if (conflicted.has(note.client_note_id)) {- // An unresolved pull conflict: pushing now would auto-resolve it as- // local-wins before the user chose Keep or Refresh (which clear the- // registry entry and unblock the row).+ if (+ conflicted.has(note.client_note_id) ||+ noteAwaitsCloudResolution(note, this.noteRevisionsKnown !== false)+ ) {+ // An unresolved pull conflict or rejected create: pushing now would+ // auto-resolve it as local-wins before the user chose Keep or Refresh+ // (which clear the registry entry and unblock the row). A clear with+ // no revision waits for a pull to supply one.continue;}if (note.folder_id && blockedFolderIds.has(note.folder_id)) {@@ -1803,7 +1889,9 @@ export class SyncService {note,note.cloud_id!,cloud.updated_at,- cloud.user_id ?? null+ cloud.user_id ?? null,+ cloud.revision ?? null,+ cloud);this.clear404(NOTE_UPDATE_404_KEY, note.client_note_id);} catch (err) {@@ -1845,15 +1933,9 @@ export class SyncService {...scope,})));- for (const { client_note_id, id: cloudId, updated_at } of created) {- const local = chunk.find(({ note }) => note.client_note_id === client_note_id);- if (local) {- await this.acknowledgeCloudNoteCreate(local.note, {- id: cloudId,- client_note_id,- updated_at: updated_at ?? null,- });- }+ for (const cloud of created) {+ const local = chunk.find(({ note }) => note.client_note_id === cloud.client_note_id);+ if (local) await this.acknowledgeCloudNoteCreate(local.note, cloud);}} catch (err) {if (isAuthContextError(err)) throw err;@@ -1941,6 +2023,9 @@ export class SyncService {// per-note tombstone; denial restores the journaled row in place,// while confirmation removes it with the folder cascade.if (local?.folder_delete_pending) continue;+ if (!cloudNote.access_removed) {+ this.noteRevisionsKnown = hasNoteRevision(cloudNote.revision);+ }// Copy the cloud owner before any last-write-wins decision: an// unchanged note skips the upsert but must still gain its owner@@ -1975,7 +2060,14 @@ export class SyncService {continue;}- if (teamOnly && !cloudNote.space_id) {+ // Rejected create retries must be resolved against the actual row,+ // even when its timestamp predates the local offline snapshot.+ if (local?.cloud_create_rejected && !cloudNote.deleted_at) {+ await this.surfaceNoteConflict(local.client_note_id, cloudNote);+ continue;+ }++ if (teamOnly && !cloudNote.space_id && !local?.cloud_create_pending) {// A personal row whose local copy still sits in a team space// announces a team→personal transition — apply it, or a later// edit's push would re-team the privatized note.@@ -1983,7 +2075,7 @@ export class SyncService {if (cloudNote.deleted_at) {await window.electronAPI.hardDeleteNote?.(local.id);await this.settleNoteConflict(local.client_note_id);- } else if (isCloudEntryNewer(cloudNote.updated_at, local.updated_at)) {+ } else if (isCloudNoteNewer(cloudNote, local)) {// 'error' rows carry unpushed work just like 'pending' ones.if (local.sync_status !== "synced") {await this.surfaceNoteConflict(local.client_note_id, cloudNote);@@ -2032,7 +2124,68 @@ export class SyncService {}if (local?.deleted_at) continue;- if (!local || isCloudEntryNewer(cloudNote.updated_at, local.updated_at)) {+ if (local?.cloud_create_pending) {+ if (cloudNote.folder_id && !cloudToLocal.has(cloudNote.folder_id)) {+ parkedRows++;+ continue;+ }+ const result = await window.electronAPI.acknowledgeNoteCreate?.(+ local.id,+ local,+ cloudNote.id,+ cloudNote.updated_at,+ cloudNote.user_id ?? null,+ {+ reconcilePending: true,+ cloudNote,+ cloudRevision: cloudNote.revision ?? null,+ localFolderId: resolvePulledNoteFolderId(+ cloudNote,+ space.id,+ cloudToLocal,+ defaultFolderId+ ),+ localSpaceId: space.id,+ }+ );+ if (result?.outcome === "conflict") {+ await this.surfaceNoteConflict(local.client_note_id, cloudNote);+ } else if (result?.outcome === "synced" || result?.outcome === "pending") {+ await this.settleNoteConflict(local.client_note_id);+ } else {+ parkedRows++;+ }+ continue;+ }+ const preRevision =+ local &&+ !hasNoteRevision(local.cloud_revision) &&+ hasNoteRevision(cloudNote.revision) &&+ local.cloud_id === cloudNote.id;+ if (preRevision && local.sync_status !== "synced") {+ // Adopt the revision when this device's base is the server's+ // current row. An unpushed edit on a row acked before timestamp+ // bases existed pushed last-write-wins until now; it still does.+ const sameBase =+ normalizeTimestamp(local.cloud_updated_at) ===+ normalizeTimestamp(cloudNote.updated_at);+ if (!sameBase && local.cloud_updated_at) {+ await this.surfaceNoteConflict(local.client_note_id, cloudNote);+ continue;+ }+ await window.electronAPI.setNoteCloudBase?.(+ local.id,+ cloudNote.updated_at,+ cloudNote.revision+ );+ local.cloud_revision = cloudNote.revision;+ }+ // A clean row synced before revisions takes the cloud copy whole:+ // adopting only the revision would mark the copies equal from now+ // on, so a clear made elsewhere while this device ran a release that+ // kept the text would never arrive.+ const cleanPreRevision = preRevision && local.sync_status === "synced";+ if (!local || cleanPreRevision || isCloudNoteNewer(cloudNote, local)) {if (local && local.sync_status !== "synced") {// A newer cloud copy over unpushed local edits ('pending' or// 'error'): surface the conflict to the editor banner insteaddiff --git a/src/services/noteCreateAck.ts b/src/services/noteCreateAck.tsindex a098a94ac..0fb03191f 100644--- a/src/services/noteCreateAck.ts+++ b/src/services/noteCreateAck.ts@@ -1,10 +1,22 @@-import type { NoteCreateAckResult, NoteCreateSnapshot, NoteItem } from "../types/electron";+import type {+ NoteCreateAckResult,+ NoteCreateAckWriteOptions,+ NoteCreateSnapshot,+ NoteCloudText,+ NoteItem,+} from "../types/electron";+import { getValidatedAuthGeneration } from "../lib/authRequestContext";-export interface CloudNoteCreateResult {+export interface CloudNoteCreateResult extends NoteCloudText {id: string;client_note_id: string | null;updated_at?: string | null;user_id?: string | null;+ revision?: number;+ write_applied?: boolean;+ row_created?: boolean;+ deleted_at?: string | null;+ access_removed?: boolean;}export interface NoteCreateAckDependencies {@@ -14,7 +26,7 @@ export interface NoteCreateAckDependencies {cloudId: string,cloudUpdatedAt: string | null,ownerUserId: string | null,- settleIfUnchanged: boolean+ options: NoteCreateAckWriteOptions) => Promise<NoteCreateAckResult | undefined>;deleteCloud: (cloudId: string) => Promise<void>;onInvalidResponse?: (expectedClientNoteId: string, receivedClientNoteId: string | null) => void;@@ -24,10 +36,12 @@ export interface NoteCreateAckDependencies {export type NoteCreateResolution =| NoteCreateAckResult["outcome"]+ | "write-rejected"| "bridge-unavailable"| "invalid-response"| "unmatched-response"| "orphan-cleaned"+ | "orphan-unproven"| "orphan-cleanup-failed";export interface NoteCreateAckOptions {@@ -45,6 +59,9 @@ async function cleanupOrphanedCreate(cloud: CloudNoteCreateResult,dependencies: NoteCreateAckDependencies): Promise<NoteCreateResolution> {+ // Applied upserts can target an existing row. Only an atomic insertion+ // receipt gives this request authority to clean up its cloud orphan.+ if (cloud.row_created !== true) return "orphan-unproven";try {await dependencies.deleteCloud(cloud.id);return "orphan-cleaned";@@ -68,18 +85,37 @@ export async function resolveCloudNoteCreate(return "invalid-response";}if (options.requestStillCurrent && !options.requestStillCurrent()) {- return cleanupOrphanedCreate(cloud, dependencies);+ return cloud.write_applied === false+ ? "write-rejected"+ : cleanupOrphanedCreate(cloud, dependencies);}+ if (cloud.deleted_at || cloud.access_removed) return "unresolved";+ const writeRejected = cloud.write_applied === false;+ const hasCloudText =+ typeof cloud.content === "string" &&+ (typeof cloud.enhanced_content === "string" || cloud.enhanced_content === null);const result = await dependencies.acknowledge(note.id,note,cloud.id,- cloud.updated_at ?? null,+ writeRejected ? (note.cloud_updated_at ?? null) : (cloud.updated_at ?? null),cloud.user_id ?? null,- options.settleIfUnchanged ?? true+ {+ settleIfUnchanged: (options.settleIfUnchanged ?? true) && !writeRejected,+ cloudRevision: writeRejected ? (note.cloud_revision ?? null) : (cloud.revision ?? null),+ writeRejected,+ ...(!writeRejected && {+ cloudNote: hasCloudText ? cloud : undefined,+ requiresReconciliation: !hasCloudText,+ }),+ });if (!result) return "bridge-unavailable";+ // A rejected idempotent POST did not create or update this server row.+ // Link its identity for pull/conflict resolution, but grant neither a new+ // write base nor authority to delete it as an orphan of this request.+ if (writeRejected) return "write-rejected";if (result.outcome !== "orphaned") return result.outcome;return cleanupOrphanedCreate(cloud, dependencies);@@ -108,14 +144,14 @@ function rendererDependencies(deleteCloud: (cloudId: string) => Promise<void>): NoteCreateAckDependencies {return {- acknowledge: async (id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged) =>+ acknowledge: async (id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, options) =>window.electronAPI.acknowledgeNoteCreate?.(id,snapshot,cloudId,cloudUpdatedAt,ownerUserId,- settleIfUnchanged+ options),deleteCloud,onInvalidResponse: (expected, received) =>@@ -143,7 +179,21 @@ export function resolveRendererCloudNoteCreate(deleteCloud: (cloudId: string) => Promise<void>,options: NoteCreateAckOptions = {}): Promise<NoteCreateResolution> {- return resolveCloudNoteCreate(note, cloud, rendererDependencies(deleteCloud), options);+ return resolveCloudNoteCreate(+ note,+ cloud,+ rendererDependencies(deleteCloud),+ rendererOptions(options)+ );+}++function rendererOptions(options: NoteCreateAckOptions): NoteCreateAckOptions {+ const generation = getValidatedAuthGeneration();+ return {+ ...options,+ requestStillCurrent: () =>+ getValidatedAuthGeneration() === generation && (options.requestStillCurrent?.() ?? true),+ };}export function resolveRendererCloudNoteCreateBatch(@@ -152,5 +202,10 @@ export function resolveRendererCloudNoteCreateBatch(deleteCloud: (cloudId: string) => Promise<void>,options: NoteCreateAckOptions = {}): Promise<NoteCreateResolution[]> {- return resolveCloudNoteCreateBatch(notes, created, rendererDependencies(deleteCloud), options);+ return resolveCloudNoteCreateBatch(+ notes,+ created,+ rendererDependencies(deleteCloud),+ rendererOptions(options)+ );}diff --git a/src/stores/actionProcessingStore.ts b/src/stores/actionProcessingStore.tsindex 8c63fe074..63d04207e 100644--- a/src/stores/actionProcessingStore.ts+++ b/src/stores/actionProcessingStore.ts@@ -76,7 +76,7 @@ export interface NoteMaterial {export type NoteSummarySnapshot = Pick<NoteItem,"enhanced_content" | "enhancement_prompt" | "enhancement_template_id" | "enhanced_at_content_hash"-> & { title?: string };+> & { title?: string; clear_fields?: Array<"enhanced_content"> };export interface ActionAppliedEvent {noteId: number;@@ -563,16 +563,19 @@ export function runBackgroundAction(if (title) updates.title = title;const result = await window.electronAPI.updateNote(noteId, updates);if (!result?.success) throw new Error(labels.actionFailed);+ const previousSummary = before?.enhanced_content ?? null;pushAppliedEvent({noteId,action,previous: {- // "" as deleting a summary does: sync keeps the cloud copy over a null.- enhanced_content: before?.enhanced_content ?? "",+ enhanced_content: previousSummary,enhancement_prompt: before?.enhancement_prompt ?? null,enhancement_template_id: before?.enhancement_template_id ?? null,enhanced_at_content_hash: before?.enhanced_at_content_hash ?? null,...(title && before && { title: before.title }),+ // Undoing a first summary is a deliberate clear, so it syncs to every+ // device; a bare blank stays local and the summary would come back.+ ...(!previousSummary?.trim() && { clear_fields: ["enhanced_content"] }),},});diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.tsindex 473d7c19b..58e6432af 100644--- a/src/stores/noteStore.ts+++ b/src/stores/noteStore.ts@@ -937,6 +937,7 @@ export async function startMigration(): Promise<void> {enhanced_content: n.enhanced_content,enhancement_prompt: n.enhancement_prompt,enhancement_template_id: n.enhancement_template_id,+ enhanced_at_content_hash: n.enhanced_at_content_hash,note_type: n.note_type,source_file: n.source_file,audio_duration_seconds: n.audio_duration_seconds,diff --git a/src/types/electron.ts b/src/types/electron.tsindex 1aea28645..f09f0220f 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -431,6 +431,14 @@ export interface NoteItem {// Server updated_at this device last acked (push response or pull); echoed// as base_updated_at on the next PATCH. Null = pre-guard row, pushes LWW.cloud_updated_at?: string | null;+ cloud_revision?: number | null;+ cloud_create_rejected?: number;+ cloud_create_pending?: string | null;+ content_sync_operation?: "set" | "clear" | null;+ enhanced_content_sync_operation?: "set" | "clear" | null;+ // Local-only counters distinguish later edits/Undo from an in-flight snapshot.+ content_edit_generation?: number;+ enhanced_content_edit_generation?: number;created_at: string;updated_at: string;client_note_id: string;@@ -471,6 +479,11 @@ export type NotePushSnapshot = Pick<| "sync_status"| "deleted_at"| "cloud_updated_at"+ | "cloud_revision"+ | "content_sync_operation"+ | "enhanced_content_sync_operation"+ | "content_edit_generation"+ | "enhanced_content_edit_generation"| "left_team">;@@ -479,13 +492,54 @@ export type NoteUpdateSnapshot = NotePushSnapshot;export interface NoteCreateAckResult {success: boolean;- outcome: "synced" | "pending" | "already-linked" | "orphaned" | "unresolved";+ outcome:+ | "synced"+ | "pending"+ | "already-linked"+ | "orphaned"+ | "unresolved"+ | "awaiting-cloud"+ | "conflict";+ note?: NoteItem;+}++export interface NoteCreateAckWriteOptions {+ settleIfUnchanged?: boolean;+ cloudRevision?: number | null;+ // The server refused the create without writing it (write_applied: false).+ writeRejected?: boolean;+ cloudNote?: NoteCloudText;+ requiresReconciliation?: boolean;+ reconcilePending?: boolean;+ localFolderId?: number | null;+ localSpaceId?: number;+}++// A cloud note row's text fields, as a pull or a write response carries them.+export interface NoteCloudText {+ content?: string | null;+ enhanced_content?: string | null;+ enhancement_prompt?: string | null;+ enhanced_at_content_hash?: string | null;+ enhancement_template_id?: string | null;+ content_state?: "set" | "clear" | null;+ enhanced_content_state?: "set" | "clear" | null;+}++export interface NoteCloudBaseOptions {+ // The user chose Keep on the conflict banner.+ keepLocal?: boolean;+ // The conflicting cloud copy Keep merges against: fields this device never+ // edited take its values.+ cloudNote?: NoteCloudText;}export interface NoteUpdateAckResult {success: boolean;outcome: "synced" | "pending" | "identity-changed";changes: number;+ // Present when the ack took the server's copy of a text field.+ note?: NoteItem;}export type ShareVisibility = "private" | "link" | "domain" | "invited";@@ -1597,6 +1651,7 @@ declare global {updateNote: (id: number,updates: {+ clear_fields?: Array<"content" | "enhanced_content">;title?: string;content?: string;enhanced_content?: string | null;@@ -3488,25 +3543,33 @@ declare global {cloudNote: Record<string, unknown>,localFolderId: number | null,localSpaceId?: number | null- ) => Promise<NoteItem>;+ ) => Promise<NoteItem | null>;acknowledgeNoteCreate?: (id: number,snapshot: NoteCreateSnapshot,cloudId: string,cloudUpdatedAt?: string | null,ownerUserId?: string | null,- settleIfUnchanged?: boolean+ options?: NoteCreateAckWriteOptions) => Promise<NoteCreateAckResult>;markNoteSyncedIfUnchanged?: (id: number,snapshot: NoteUpdateSnapshot,expectedCloudId: string,cloudUpdatedAt?: string | null,- ownerUserId?: string | null+ ownerUserId?: string | null,+ cloudRevision?: number | null,+ cloudNote?: NoteCloudText | null) => Promise<NoteUpdateAckResult>;- setNoteCloudBase?: (id: number, cloudUpdatedAt: string | null) => Promise<void>;+ setNoteCloudBase?: (+ id: number,+ cloudUpdatedAt: string | null,+ cloudRevision?: number | null,+ options?: NoteCloudBaseOptions+ ) => Promise<{ success: boolean; note?: NoteItem }>;setNoteOwnerFromCloud?: (id: number, ownerUserId: string) => Promise<void>;countTeamNotesMissingOwner?: () => Promise<number>;+ countNotesMissingRevision?: (spaceKind?: "private" | "team") => Promise<number>;markNoteSyncError?: (id: number) => Promise<void>;restoreNoteAfterDeniedDelete?: (id: number) => Promise<{ success: boolean; id: number }>;hardDeleteNote?: (id: number) => Promise<void>;diff --git a/test/components/backgroundActionToastListener.test.js b/test/components/backgroundActionToastListener.test.jsindex 9640f3af6..e6a2f9a26 100644--- a/test/components/backgroundActionToastListener.test.js+++ b/test/components/backgroundActionToastListener.test.js@@ -61,11 +61,14 @@ async function mountListener(return { store, writes, focusListeners };}+// A first summary's Undo: clear_fields has to reach the database, or the+// restore is a local blank and the summary syncs back.const PREVIOUS = {enhanced_content: null,enhancement_prompt: null,enhancement_template_id: null,enhanced_at_content_hash: null,+ clear_fields: ["enhanced_content"],};const APPLIED = {noteId: 4,diff --git a/test/components/noteEditorSummaryDeletion.test.js b/test/components/noteEditorSummaryDeletion.test.jsindex 93db93ce8..ac2f1d6e7 100644--- a/test/components/noteEditorSummaryDeletion.test.js+++ b/test/components/noteEditorSummaryDeletion.test.js@@ -252,7 +252,7 @@ async function loadNoteEditor(t, permission) {});const latest = () => renders.at(-1);const unmount = () => React.act(async () => root.unmount());- return { render, click, latest, unmount, resizeCallbacks };+ return { render, click, latest, unmount, resizeCallbacks, vite };}test("deleting the AI summary moves the selection to Your notes", async (t) => {@@ -753,3 +753,103 @@ test("a read-only shared note offers no action picker, chips, slash menu or summawait unmount();}});++// The body editor (RichTextEditor, mocked) in the tree the component returned.+function bodyEditor(tree) {+ let editor = null;+ walk(tree, (node) => {+ if (!editor && node.type?.name === "RichTextEditor") editor = node;+ });+ return editor;+}++test("each tab has its own body editor, so undo never carries over between tabs", async (t) => {+ // An undo step from one tab, replayed over the other, would save there.+ const { render, click, latest, unmount } = await loadNoteEditor(t);+ await render(ENHANCEMENT, { note: { ...NOTE, transcript: "Plain transcript" } });+ const keys = [bodyEditor(latest()).key];+ for (const tab of ["raw", "transcript"]) {+ await click(tab);+ assert.equal(bodyEditor(latest()).props.disabled === true, tab === "transcript");+ keys.push(bodyEditor(latest()).key);+ }+ assert.ok(keys.every((key) => key != null));+ assert.equal(new Set(keys).size, 3, `distinct keys, got ${keys}`);+ await unmount();+});++const CONFLICT = {+ id: "cloud-1",+ client_note_id: NOTE.client_note_id,+ title: "Kickoff",+ content: "",+ content_state: "clear",+ enhanced_content: NOTE.enhanced_content,+ updated_at: "2026-09-02T00:00:00.000Z",+ revision: 4,+ updated_by_user_id: null,+};++async function loadWithConflict(t, overrides) {+ const loaded = await loadNoteEditor(t);+ const store = await loaded.vite.ssrLoadModule("/stores/noteStore.ts");+ t.after(() => store.clearNoteConflict(NOTE.client_note_id));+ await loaded.render(ENHANCEMENT, overrides);+ await React.act(async () => store.setNoteConflict(NOTE.client_note_id, CONFLICT));+ const keepButton = () => {+ let button = null;+ walk(loaded.latest(), (node) => {+ if (!button && node.props.children === "notes.spaces.conflictKeep") button = node;+ });+ return button;+ };+ return { ...loaded, keepButton };+}++test("Keep saves the pending edits before it advances the base", async (t) => {+ // A debounced save landing after Keep would write the draft's old notes back+ // over the clear Keep accepted from the other device.+ const calls = [];+ const { keepButton, unmount } = await loadWithConflict(t, {+ onFlushPendingSaves: async (noteId) => calls.push(["flush", noteId]),+ });+ globalThis.window.electronAPI.setNoteCloudBase = async (...args) => {+ calls.push(["base", ...args]);+ return { success: true, note: { ...NOTE, content: "" } };+ };+ await React.act(async () => keepButton().props.onClick());+ assert.deepEqual(calls, [+ ["flush", NOTE.id],+ [+ "base",+ NOTE.id,+ CONFLICT.updated_at,+ CONFLICT.revision,+ { keepLocal: true, cloudNote: CONFLICT },+ ],+ ]);+ assert.equal(keepButton(), null, "the banner is gone");+ await unmount();+});++for (const failing of ["flush", "base"]) {+ test(`Keep leaves the banner up for a retry when the ${failing} step fails`, async (t) => {+ const errors = t.mock.method(console, "error", () => {});+ const calls = [];+ const { keepButton, unmount } = await loadWithConflict(t, {+ onFlushPendingSaves: async () => {+ calls.push("flush");+ if (failing === "flush") throw new Error("disk full");+ },+ });+ globalThis.window.electronAPI.setNoteCloudBase = async () => {+ calls.push("base");+ throw new Error("database locked");+ };+ await React.act(async () => keepButton().props.onClick());+ assert.deepEqual(calls, failing === "flush" ? ["flush"] : ["flush", "base"]);+ assert.ok(keepButton(), "the banner stays");+ assert.equal(errors.mock.callCount(), 1);+ await unmount();+ });+}diff --git a/test/components/personalNotesUndoDiscard.test.js b/test/components/personalNotesUndoDiscard.test.jsindex 0b62183f2..c312b6711 100644--- a/test/components/personalNotesUndoDiscard.test.js+++ b/test/components/personalNotesUndoDiscard.test.js@@ -8,10 +8,8 @@ const {installHostDom,} = require("../lib/rendererTestHarness");-// Typing in the open note retires the assistant's Undo at once, before the-// editor's delayed save: an Undo clicked in that second would restore the-// assistant's previous text over what the user just typed. PersonalNotesView-// is real; NoteEditor is a stub that exposes its props.+// PersonalNotesView's delayed saves, seen through the props it hands the+// editor. PersonalNotesView is real; NoteEditor is a stub that exposes them.const NOTE = {id: 11,@@ -71,7 +69,7 @@ const MOCKS = {`,};-test("editing either document retires the assistant's Undo before the delayed save", async (t) => {+async function mountView(t, updateNote) {const calls = [];let root;t.after(async () => {@@ -86,7 +84,7 @@ test("editing either document retires the assistant's Undo before the delayed sagetNote: async () => NOTE,updateNote: async (...args) => {calls.push(["save", ...args]);- return { success: true };+ return updateNote ? updateNote(...args) : { success: true };},discardNoteUndo: async (...args) => calls.push(["discard", ...args]),},@@ -102,7 +100,21 @@ test("editing either document retires the assistant's Undo before the delayed sa"/components/notes/PersonalNotesView.tsx");root = createRoot(container);- await React.act(async () => root.render(React.createElement(PersonalNotesView)));+ const render = () => React.act(async () => root.render(React.createElement(PersonalNotesView)));+ await render();+ // Re-renders with the store's current note (globalThis.__note).+ Object.defineProperty(calls, "rerender", { value: render });+ return calls;+}++const settle = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+const saves = (calls) => calls.filter(([kind]) => kind === "save");++// Typing in the open note retires the assistant's Undo at once, before the+// editor's delayed save: an Undo clicked in that second would restore the+// assistant's previous text over what the user just typed.+test("editing either document retires the assistant's Undo before the delayed save", async (t) => {+ const calls = await mountView(t);await React.act(async () => globalThis.__editorProps.onContentChange(NOTE.id, "Typed"));assert.deepEqual(calls, [["discard", NOTE.id]], "retired before the save");@@ -110,5 +122,63 @@ test("editing either document retires the assistant's Undo before the delayed saglobalThis.__editorProps.enhancement.onChange(NOTE.id, "Typed summary"));assert.deepEqual(calls.at(-1), ["discard", NOTE.id]);- assert.equal(calls.filter(([kind]) => kind === "save").length, 0);+ assert.equal(saves(calls).length, 0);+});++// Keep on the conflict banner saves the draft first: a delayed save landing+// after Keep would write it back over a clear Keep accepted.+test("a flush before Keep saves the pending edits at once, and nothing lands later", async (t) => {+ const calls = await mountView(t);++ await React.act(async () => globalThis.__editorProps.onTitleChange(NOTE.id, "Retitled"));+ await React.act(async () => globalThis.__editorProps.onFlushPendingSaves(NOTE.id));+ assert.deepEqual(saves(calls), [["save", NOTE.id, { title: "Retitled" }]]);+ await React.act(() => settle(1100));+ assert.equal(saves(calls).length, 1, "the delayed save was retired");+});++test("a flush that fails rejects and leaves the edits pending", async (t) => {+ const calls = await mountView(t, () => ({ success: false, error: "Note not found" }));++ await React.act(async () => globalThis.__editorProps.onTitleChange(NOTE.id, "Retitled"));+ await assert.rejects(globalThis.__editorProps.onFlushPendingSaves(NOTE.id), /Note not found/);+ await React.act(() => settle(1100));+ assert.equal(saves(calls).length, 2, "the delayed save still runs");+});++// A pull or ack can apply a clear made elsewhere while a title save waits.+// The editor's notes are then stale: the save writes only the title, and the+// editor then shows the stored notes instead of bringing the cleared text back.+test("a title save after a pull or ack writes only the title, then shows the stored notes", async (t) => {+ const calls = await mountView(t, (id, updates) => ({+ success: true,+ note: { ...globalThis.__note, ...updates },+ }));++ await React.act(async () => globalThis.__editorProps.onTitleChange(NOTE.id, "Retitled"));+ globalThis.__note = { ...NOTE, content: "" };+ await calls.rerender();+ assert.equal(globalThis.__editorProps.note.content, "Notes", "a pending save keeps the draft");+ await React.act(() => settle(1100));+ assert.deepEqual(saves(calls), [["save", NOTE.id, { title: "Retitled" }]]);+ assert.equal(globalThis.__editorProps.note.content, "");+ assert.equal(globalThis.__editorProps.note.title, "Retitled");+});++test("a title edit after a notes edit still saves the notes", async (t) => {+ const calls = await mountView(t);++ await React.act(async () => globalThis.__editorProps.onContentChange(NOTE.id, "Typed"));+ await React.act(async () => globalThis.__editorProps.onTitleChange(NOTE.id, "Retitled"));+ await React.act(() => settle(1100));+ assert.deepEqual(saves(calls), [["save", NOTE.id, { title: "Retitled", content: "Typed" }]]);++ await React.act(async () => globalThis.__editorProps.onContentChange(NOTE.id, ""));+ await React.act(async () => globalThis.__editorProps.onTitleChange(NOTE.id, "Again"));+ await React.act(() => settle(1100));+ assert.deepEqual(saves(calls).at(-1), [+ "save",+ NOTE.id,+ { title: "Again", content: "", clear_fields: ["content"] },+ ]);});diff --git a/test/components/richTextEditor.test.js b/test/components/richTextEditor.test.jsindex c8edbb453..2a41ab038 100644--- a/test/components/richTextEditor.test.js+++ b/test/components/richTextEditor.test.js@@ -669,16 +669,18 @@ async function mountNotes(t, markdown = `Intro\n\n${TABLE}\n\nAfter`) {const editorRef = { current: null };let showOtherNote;let setDisabled;- let saved;+ let setNoteValue;+ const changes = [];function Note({ initial }) {const [value, setValue] = React.useState(initial);const [disabled, updateDisabled] = React.useState(false);setDisabled = updateDisabled;+ setNoteValue = setValue;return React.createElement(RichTextEditor, {value,disabled,onChange: (markdown) => {- saved = markdown;+ changes.push(markdown);setValue(markdown);},editorRef,@@ -723,9 +725,13 @@ async function mountNotes(t, markdown = `Intro\n\n${TABLE}\n\nAfter`) {editor: () => editorRef.current,errors,host,+ /** Every Markdown the note saved through onChange, in order. */+ changes,/** The Markdown the note last saved through onChange. */- saved: () => saved,+ saved: () => changes.at(-1),setDisabled: (disabled) => setDisabled(disabled),+ /** Replaces the note's value from outside the editor, as a summary arriving does. */+ setValue: (markdown) => setNoteValue(markdown),showOtherNote: () => showOtherNote(),};}@@ -782,6 +788,91 @@ test("Delete table from the menu works in a note that re-renders on every changeassert.equal(notes.saved().trim(), "Intro\n\nAfter");});+test("undo never reverts a value set from outside the editor", async (t) => {+ // A sync pull or an assistant edit replaces the note: undoing that would save+ // the text it replaced, often empty, over it.+ const notes = await mountNotes(t, "Transcript tab");+ await notes.act(() => notes.setValue("Summary tab"));+ await notes.act(() => notes.editor().commands.undo());+ assert.equal(markdownOf(notes.editor()), "Summary tab");+ assert.deepEqual(notes.changes, [], "nothing saved over the summary");+});++test("undo still reverts typing after a value set from outside the editor", async (t) => {+ const notes = await mountNotes(t, "Transcript tab");+ await notes.act(() => notes.setValue("Summary tab"));+ await notes.act(() => {+ notes.editor().commands.setTextSelection(notes.editor().state.doc.content.size - 1);+ type(notes.editor(), " edited");+ });+ assert.equal(notes.saved().trim(), "Summary tab edited");+ await notes.act(() => notes.editor().commands.undo());+ assert.equal(markdownOf(notes.editor()), "Summary tab");+ assert.equal(notes.saved().trim(), "Summary tab");+});++// Undo maps earlier steps onto a value set from outside, and a step that+// spanned the whole document maps onto the whole new value.+for (const [when, wait] of [+ ["at once", 30],+ ["after the undo group closed", 600],+]) {+ test(`undo of a select-all delete never brings its text back over a value set from outside, ${when}`, async (t) => {+ // The cleared summary's text would be saved over the notes, or the notes'+ // over the summary, and sync to every device.+ const notes = await mountNotes(t, "Summary paragraph one\n\nSummary two");+ await notes.act(() => {+ notes.editor().commands.selectAll();+ pressKey(notes.editor(), "Backspace");+ }, wait);+ assert.equal(notes.saved(), "");+ await notes.act(() => notes.setValue("Personal notes body\n\nMore notes"));+ notes.changes.length = 0;+ await notes.act(() => notes.editor().commands.undo());+ assert.equal(markdownOf(notes.editor()), "Personal notes body\n\nMore notes");+ assert.deepEqual(notes.changes, [], "nothing saved over the new value");+ });+}++test("undo of typing over a select-all never replaces a value set from outside", async (t) => {+ const notes = await mountNotes(t, "Summary paragraph one\n\nSummary two");+ await notes.act(() => {+ notes.editor().commands.selectAll();+ type(notes.editor(), "x");+ });+ assert.equal(notes.saved(), "x");+ await notes.act(() => notes.setValue("Pulled from another device"));+ notes.changes.length = 0;+ await notes.act(() => notes.editor().commands.undo());+ assert.equal(markdownOf(notes.editor()), "Pulled from another device");+ assert.deepEqual(notes.changes, []);+});++test("the echo of the user's own save keeps typing undoable", async (t) => {+ const notes = await mountNotes(t, "Notes body");+ await notes.act(() => {+ notes.editor().commands.setTextSelection(notes.editor().state.doc.content.size - 1);+ type(notes.editor(), " typed");+ });+ await notes.act(() => notes.setValue(notes.saved()));+ await notes.act(() => notes.editor().commands.undo());+ assert.equal(markdownOf(notes.editor()), "Notes body");+ assert.equal(notes.saved().trim(), "Notes body");+});++test("a whitespace-only note saved empty keeps its caret and its undo", async (t) => {+ const notes = await mountNotes(t, "");+ await notes.act(() => type(notes.editor(), " "));+ assert.equal(notes.saved(), " ");+ const caret = notes.editor().state.selection.from;+ // The store saves a blank note as empty and echoes that back.+ await notes.act(() => notes.setValue(""));+ assert.equal(notes.editor().state.selection.from, caret);+ assert.equal(notes.editor().state.doc.textContent, " ");+ await notes.act(() => notes.editor().commands.undo());+ assert.equal(notes.editor().state.doc.textContent, "");+});+test("the table menu disables actions that would break or empty the table", async (t) => {const isDisabled = (key) => menuItem(`notes.editor.table.${key}`).hasAttribute("data-disabled");const notes = await mountNotes(t, "Intro\n\n| A | B |\n| --- | --- |\n\nAfter");diff --git a/test/helpers/accountOwnershipDatabase.test.js b/test/helpers/accountOwnershipDatabase.test.jsindex 362900818..b8c09b866 100644--- a/test/helpers/accountOwnershipDatabase.test.js+++ b/test/helpers/accountOwnershipDatabase.test.js@@ -46,6 +46,7 @@ function createDatabaseManager() {id INTEGER PRIMARY KEY,title TEXT NOT NULL,content TEXT NOT NULL,+ content_sync_operation TEXT,note_type TEXT NOT NULL DEFAULT 'personal',source_file TEXT,audio_duration_seconds REAL,diff --git a/test/helpers/cliBridgeNotes.test.js b/test/helpers/cliBridgeNotes.test.jsindex 4c0c52c3c..a1b915347 100644--- a/test/helpers/cliBridgeNotes.test.js+++ b/test/helpers/cliBridgeNotes.test.js@@ -86,3 +86,28 @@ test("PATCH /v1/notes/:id returns the updated note", (t) => {assert.equal(result.data.title, "Updated Title");assert.equal(result.data.content, "Existing content");});++test("PATCH /v1/notes/:id clears a provided blank text field so the clear syncs", (t) => {+ const ctx = createBridge(t);+ if (!ctx) return;++ const { id } = ctx.db.saveNote("Original", "Existing content").note;+ ctx.db.updateNote(id, { enhanced_content: "Summary", transcript: "Spoken words" });++ const result = call(ctx.bridge, "PATCH", `/v1/notes/${id}`, {+ content: "",+ enhanced_content: null,+ transcript: "",+ });++ assert.equal(result.data.content, "");+ assert.equal(result.data.content_sync_operation, "clear");+ assert.equal(result.data.enhanced_content, null);+ assert.equal(result.data.enhanced_content_sync_operation, "clear");+ // Transcript is never a clear target; the bridge stores it as before.+ assert.equal(result.data.transcript, "");+ assert.throws(+ () => call(ctx.bridge, "PATCH", `/v1/notes/${id}`, { content: "", clear_fields: "content" }),+ { code: "VALIDATION" }+ );+});diff --git a/test/helpers/harness/electronApiBridge.js b/test/helpers/harness/electronApiBridge.jsindex 6c94050cc..33319133b 100644--- a/test/helpers/harness/electronApiBridge.js+++ b/test/helpers/harness/electronApiBridge.js@@ -84,27 +84,32 @@ function createElectronApi(db, options = {}) {getNoteByClientId: async (clientNoteId) => db.getNoteByClientId(clientNoteId),upsertNoteFromCloud: async (cloudNote, localFolderId, localSpaceId) =>db.upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId),- acknowledgeNoteCreate: async (+ acknowledgeNoteCreate: async (id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, options) =>+ db.acknowledgeNoteCreate(id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, options),+ markNoteSyncedIfUnchanged: async (id,snapshot,- cloudId,+ expectedCloudId,cloudUpdatedAt,ownerUserId,- settleIfUnchanged+ cloudRevision,+ cloudNote) =>- db.acknowledgeNoteCreate(+ db.markNoteSyncedIfUnchanged(id,snapshot,- cloudId,+ expectedCloudId,cloudUpdatedAt,ownerUserId,- settleIfUnchanged+ cloudRevision,+ cloudNote),- markNoteSyncedIfUnchanged: async (id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId) =>- db.markNoteSyncedIfUnchanged(id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId),+ setNoteCloudBase: async (id, cloudUpdatedAt, cloudRevision, options) =>+ db.setNoteCloudBase(id, cloudUpdatedAt, cloudRevision, options),markNoteSyncError: async (id) => db.markNoteSyncError(id),setNoteOwnerFromCloud: async (id, ownerUserId) => db.setNoteOwnerFromCloud(id, ownerUserId),countTeamNotesMissingOwner: async () => db.countTeamNotesMissingOwner(),+ countNotesMissingRevision: async (spaceKind) => db.countNotesMissingRevision(spaceKind),restoreNoteAfterDeniedDelete: async (id) => db.restoreNoteAfterDeniedDelete(id),hardDeleteNote: async (id) => db.hardDeleteNote(id),diff --git a/test/helpers/harness/fakeCloud.js b/test/helpers/harness/fakeCloud.jsindex 93d139530..5cd6fc3d6 100644--- a/test/helpers/harness/fakeCloud.js+++ b/test/helpers/harness/fakeCloud.js@@ -265,14 +265,25 @@ function createFakeCloud(config = {}) {function handle(method, pathname, query, body) {const route = `${method} ${pathname}`;switch (route) {- case "POST /api/notes/create":- return upsertRow(noteCollection, body ?? {});+ case "POST /api/notes/create": {+ const rowCreated = ![...notes.values()].some(+ (row) => row.client_note_id === body?.client_note_id+ );+ return {+ ...upsertRow(noteCollection, body ?? {}),+ row_created: rowCreated,+ write_applied: true,+ };+ }case "POST /api/notes/batch-create": {const inputs = Array.isArray(body?.notes) ? body.notes : [];return {created: inputs.map((input) => {+ const rowCreated = ![...notes.values()].some(+ (row) => row.client_note_id === input.client_note_id+ );const row = upsertRow(noteCollection, input);- return { client_note_id: row.client_note_id, id: row.id };+ return { ...row, row_created: rowCreated, write_applied: true };}),};}diff --git a/test/helpers/noteCloudCollision.test.js b/test/helpers/noteCloudCollision.test.jsnew file mode 100644index 000000000..707c0d989--- /dev/null+++ b/test/helpers/noteCloudCollision.test.js@@ -0,0 +1,259 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const Module = require("node:module");+const ts = require("typescript");+const { createDb } = require("./harness/db.js");+const {+ installBrowserGlobals,+ resetBrowserGlobals,+ establishValidatedAuth,+ enableSync,+ stopSyncTimers,+ localStorage,+ window,+} = require("./harness/browserGlobals.js");+const { createElectronApi } = require("./harness/electronApiBridge.js");+const { createFakeCloud } = require("./harness/fakeCloud.js");+const { SyncService } = require("../../src/services/SyncService.ts");++const PRIVATE_NOTE = {+ id: "cloud-a",+ client_note_id: "client-note",+ title: "Account A private note",+ content: "Account A private draft",+ note_type: "personal",+ folder_id: null,+ space_id: null,+ user_id: "account-a",+ created_at: "2026-01-01T00:00:00.000Z",+ updated_at: "2026-01-01T00:00:00.000Z",+ revision: 1,+};++const collisions = [+ { name: "another account", accountId: "account-b", cloudId: "cloud-a" },+ { name: "another cloud identity", accountId: "account-a", cloudId: "cloud-b" },+ { name: "another account and cloud identity", accountId: "account-b", cloudId: "cloud-b" },+];++function collidingCloudNote({ accountId, cloudId }) {+ return {+ ...PRIVATE_NOTE,+ id: cloudId,+ user_id: accountId,+ content: "Incoming collision text",+ updated_at: "2026-01-02T00:00:00.000Z",+ revision: 2,+ };+}++function seedPrivateNote(db, accountId) {+ db.setActiveAccountId("account-a");+ const row = db.upsertNoteFromCloud(PRIVATE_NOTE, null);+ db.setActiveAccountId(accountId);+ return row;+}++for (const collision of collisions) {+ test(`a client-ID collision with ${collision.name} returns no note`, (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = seedPrivateNote(db, collision.accountId);++ assert.equal(+ db.getNote(row.id)?.id ?? null,+ collision.accountId === "account-a" ? row.id : null+ );+ assert.equal(+ db.getNoteByClientId(row.client_note_id)?.id ?? null,+ collision.accountId === "account-a" ? row.id : null+ );+ const result = db.upsertNoteFromCloud(collidingCloudNote(collision), null);++ assert.deepEqual(db.db.prepare("SELECT * FROM notes WHERE id = ?").get(row.id), row);+ assert.equal(result, null);+ });+}++// Execute the exact production callback; only the native window broadcast is+// replaced. Copying its truthiness guard here would hide the original leak.+function cloudUpsertHandler(db, broadcast, notifyVectorChanges) {+ const source = fs.readFileSync(path.join(__dirname, "../../src/helpers/ipcHandlers.js"), "utf8");+ const registration = source.match(+ /ipcMain\.handle\("db-upsert-note-from-cloud", ([\s\S]*?)\n {4}\}\);/+ );+ assert.ok(registration, "the cloud-note IPC callback must be present");+ return new Function("broadcastToWindows", "setImmediate", `return (${registration[1]}\n});`).call(+ { databaseManager: db, notifyVectorChanges },+ broadcast,+ setImmediate+ );+}++// Keep the real Zustand state, listeners, and container routing. The unrelated+// background sync singleton and React UI dependency are inert in this fixture.+function loadNoteStore() {+ const filename = path.join(__dirname, "../../src/stores/noteStore.ts");+ const compiled = ts.transpileModule(fs.readFileSync(filename, "utf8"), {+ fileName: filename,+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },+ }).outputText;+ const loaded = new Module(filename, module);+ loaded.filename = filename;+ loaded.paths = Module._nodeModulePaths(path.dirname(filename));+ const defaultRequire = loaded.require.bind(loaded);+ loaded.require = (specifier) => {+ if (specifier === "../services/SyncService.js") {+ return { syncService: { setNoteOpen() {}, requestSyncAll() {}, debouncedPush() {} } };+ }+ if (specifier === "../components/notes/shared") return { findDefaultFolder: () => null };+ return defaultRequire(specifier);+ };+ loaded._compile(compiled, filename);+ return loaded.exports;+}++for (const collision of collisions) {+ test(`a pull skips ${collision.name} at IPC and renderer while the next note arrives`, async (t) => {+ const db = createDb(t);+ if (!db) return;+ const protectedRow = seedPrivateNote(db, collision.accountId);+ const validCloudNote = {+ ...PRIVATE_NOTE,+ id: "valid-cloud-note",+ client_note_id: "valid-client-note",+ title: "Valid following note",+ content: "Visible to the active account",+ user_id: collision.accountId,+ };+ const fallback = createFakeCloud();+ const cloud = {+ request: async (options) =>+ options.path.startsWith("/api/notes/list")+ ? { success: true, data: { notes: [collidingCloudNote(collision), validCloudNote] } }+ : fallback.request(options),+ };+ resetBrowserGlobals();+ installBrowserGlobals();+ enableSync();+ const events = [];+ const results = [];+ let onNoteSynced;+ let vectorChanges = 0;+ const handler = cloudUpsertHandler(+ db,+ (channel, note) => {+ events.push([channel, note.id]);+ if (channel === "note-synced") onNoteSynced(note);+ },+ () => vectorChanges+++ );+ window.electronAPI = {+ ...createElectronApi(db, { cloud }),+ getNotes: async (...args) => db.getNotes(...args),+ getFolderNoteCounts: async () => db.getFolderNoteCounts(),+ onNoteSynced: (callback) => {+ onNoteSynced = callback;+ return () => {};+ },+ upsertNoteFromCloud: async (...args) => {+ const result = handler(null, ...args);+ results.push(result?.id ?? null);+ return result;+ },+ };+ await establishValidatedAuth(collision.accountId);+ const service = new SyncService();+ t.after(() => {+ stopSyncTimers(service);+ resetBrowserGlobals();+ });+ const store = loadNoteStore();+ const privateSpaceId = db.getPrivateSpaceId();+ await store.initializeNotes();+ await store.loadSpaces();+ await store.loadContainerNotes(store.spaceContainerKey(privateSpaceId));+ for (const folder of await store.loadFolders()) {+ await store.loadContainerNotes(store.folderContainerKey(folder.id));+ }+ store.setActiveContext(privateSpaceId, null);+ const expectedProtectedId = collision.accountId === "account-a" ? protectedRow.id : null;+ assert.equal(store.getNoteFromStore(protectedRow.id)?.id ?? null, expectedProtectedId);++ const complete = await service.pullNotes();+ await new Promise(setImmediate);+ const accepted = db.getNoteByClientId(validCloudNote.client_note_id);+ assert.ok(accepted, "the valid row after the collision must persist");+ assert.equal(accepted.account_id, collision.accountId);+ assert.equal(accepted.content, "Visible to the active account");+ assert.deepEqual(+ {+ complete,+ results,+ events,+ vectorChanges,+ protectedRendererId: store.getNoteFromStore(protectedRow.id)?.id ?? null,+ validRendererContent: store.getNoteFromStore(accepted.id)?.content ?? null,+ },+ {+ complete: true,+ results: [null, accepted.id],+ events: [["note-synced", accepted.id]],+ vectorChanges: 1,+ protectedRendererId: expectedProtectedId,+ validRendererContent: "Visible to the active account",+ }+ );+ assert.ok(+ localStorage.getItem("lastSyncedAt.notes"),+ "a skipped collision must not stall the cursor"+ );+ assert.deepEqual(+ db.db.prepare("SELECT * FROM notes WHERE id = ?").get(protectedRow.id),+ protectedRow+ );+ });+}++test("cloud pulls still adopt an unattributed note and move it between private and team spaces", (t) => {+ const db = createDb(t);+ if (!db) return;+ const original = db.saveNote("Signed-out note", "Original local text").note;+ assert.equal(original.account_id, null);+ assert.equal(original.cloud_id, null);+ db.setActiveAccountId("account-a");+ const cloudNote = { ...PRIVATE_NOTE, client_note_id: original.client_note_id };+ const adopted = db.upsertNoteFromCloud(cloudNote, null);+ assert.equal(adopted.id, original.id);+ assert.equal(adopted.account_id, "account-a");+ assert.equal(adopted.cloud_id, "cloud-a");+ assert.equal(adopted.content, "Account A private draft");++ const team = db.upsertSpaceFromCloud({ id: "cloud-team", name: "Team" });+ const teamNote = db.upsertNoteFromCloud(+ { ...cloudNote, space_id: "cloud-team", content: "Team copy", revision: 2 },+ null,+ team.id+ );+ assert.equal(teamNote.id, original.id);+ assert.equal(teamNote.space_id, team.id);+ assert.equal(teamNote.account_id, null);+ assert.equal(db.getNote(original.id).content, "Team copy");+ db.setActiveAccountId("account-b");+ assert.equal(db.getNote(original.id), null);+ db.setActiveAccountId("account-a");++ const privateNote = db.upsertNoteFromCloud(+ { ...cloudNote, content: "Private again", revision: 3 },+ null,+ db.getPrivateSpaceId()+ );+ assert.equal(privateNote.id, original.id);+ assert.equal(privateNote.space_id, db.getPrivateSpaceId());+ assert.equal(privateNote.account_id, "account-a");+ assert.equal(db.getNote(original.id).content, "Private again");+ db.setActiveAccountId("account-b");+ assert.equal(db.getNote(original.id), null);+});diff --git a/test/helpers/noteCreateConcurrentEdits.test.js b/test/helpers/noteCreateConcurrentEdits.test.jsnew file mode 100644index 000000000..330ec27ab--- /dev/null+++ b/test/helpers/noteCreateConcurrentEdits.test.js@@ -0,0 +1,159 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createDb } = require("./harness/db.js");+const { resolveCloudNoteCreate } = require("../../src/services/noteCreateAck.ts");+const { buildNoteUpdatePayload } = require("../../src/helpers/cloudSyncGuards.js");++const UPDATED = "2026-10-09T10:00:00.000Z";++function fresh(db) {+ const note = db.saveNote("Lost first response", "Original content").note;+ db.updateNote(note.id, {+ enhanced_content: "Original summary",+ enhancement_prompt: "Original prompt",+ enhanced_at_content_hash: "original-hash",+ enhancement_template_id: "original-template",+ transcript: "Protected transcript",+ });+ return db.getNote(note.id);+}++function response(note, overrides = {}) {+ return {+ id: `cloud-${note.id}`,+ client_note_id: note.client_note_id,+ user_id: "owner",+ content: note.content,+ enhanced_content: note.enhanced_content,+ enhancement_prompt: note.enhancement_prompt,+ enhanced_at_content_hash: note.enhanced_at_content_hash,+ enhancement_template_id: note.enhancement_template_id,+ content_state: "set",+ enhanced_content_state: "set",+ revision: 2,+ write_applied: true,+ created_at: UPDATED,+ updated_at: UPDATED,+ ...overrides,+ };+}++function cleared(note, field) {+ return response(note, {+ [field]: field === "content" ? "" : null,+ [`${field}_state`]: "clear",+ ...(field === "enhanced_content" && {+ enhancement_prompt: null,+ enhanced_at_content_hash: null,+ }),+ });+}++function dependencies(db) {+ return {+ acknowledge: (...args) => db.acknowledgeNoteCreate(...args),+ deleteCloud: () => assert.fail("An idempotent retry does not own the existing server row"),+ };+}++for (const field of ["content", "enhanced_content"]) {+ test(`${field}: an in-flight clear and Undo that restores the submitted text remains a new set`, async (t) => {+ const db = createDb(t);+ if (!db) return;+ const snapshot = fresh(db);+ db.updateNote(+ snapshot.id,+ { [field]: "", clear_fields: [field] },+ {+ undoable: true,+ expected: snapshot,+ }+ );+ assert.equal(db.undoNoteUpdate(db.getNoteUndos()[0].token).success, true);+ assert.equal(db.getNote(snapshot.id)[field], snapshot[field]);+ const outcome = await resolveCloudNoteCreate(+ snapshot,+ cleared(snapshot, field),+ dependencies(db)+ );+ assert.equal(outcome, "pending");+ const local = db.getNote(snapshot.id);+ assert.equal(+ local[field],+ snapshot[field],+ "Undo is later local intent, even when values match"+ );+ assert.equal(local[`${field}_sync_operation`], "set");+ });+}++test("a later title Undo survives reconciliation of an unrelated cleared field", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const snapshot = fresh(db);+ db.updateNote(snapshot.id, { title: "Assistant title" }, { undoable: true, expected: snapshot });+ const token = db.getNoteUndos()[0].token;+ assert.equal(+ await resolveCloudNoteCreate(snapshot, cleared(snapshot, "content"), dependencies(db)),+ "pending"+ );+ assert.equal(db.getNote(snapshot.id).content, "");+ assert.equal(db.getNoteUndos()[0]?.token, token);+ assert.equal(db.undoNoteUpdate(token).success, true);+ assert.equal(db.getNote(snapshot.id).title, snapshot.title);+ assert.equal(db.getNote(snapshot.id).content, "");+});++test("local edit generations migrate additively, survive reopen, and reject renderer overrides", (t) => {+ const db = createDb(t);+ if (!db) return;+ const snapshot = fresh(db);+ db.db.exec("ALTER TABLE notes DROP COLUMN content_edit_generation");+ db.db.exec("ALTER TABLE notes DROP COLUMN enhanced_content_edit_generation");+ db.db.close();+ db.initDatabase();+ assert.equal(db.getNote(snapshot.id).content_edit_generation, 0);+ assert.equal(db.getNote(snapshot.id).enhanced_content_edit_generation, 0);+ db.updateNote(snapshot.id, { content: "New text", content_edit_generation: 90 });+ db.updateNote(snapshot.id, { enhancement_template_id: "New template" });+ db.updateNote(snapshot.id, { title: "Only title", enhanced_content_edit_generation: 90 });+ db.db.close();+ db.initDatabase();+ assert.equal(db.getNote(snapshot.id).content_edit_generation, 1);+ assert.equal(db.getNote(snapshot.id).enhanced_content_edit_generation, 1);+ assert.equal(+ buildNoteUpdatePayload(db.getNote(snapshot.id), null).content_edit_generation,+ undefined+ );+});++for (const field of ["content", "enhanced_content"]) {+ test(`${field}: PATCH acknowledgement also preserves a same-value later Undo`, (t) => {+ const db = createDb(t);+ if (!db) return;+ const original = fresh(db);+ db.acknowledgeNoteCreate(original.id, original, `cloud-${original.id}`, UPDATED, null, {+ cloudRevision: 0,+ });+ db.updateNote(original.id, { [field]: "Submitted edit" });+ const snapshot = db.getNote(original.id);+ db.updateNote(+ original.id,+ { [field]: "", clear_fields: [field] },+ { undoable: true, expected: snapshot }+ );+ db.undoNoteUpdate(db.getNoteUndos()[0].token);+ const ack = db.markNoteSyncedIfUnchanged(+ original.id,+ snapshot,+ snapshot.cloud_id,+ UPDATED,+ null,+ 1,+ response(snapshot)+ );+ assert.equal(ack.outcome, "pending");+ assert.equal(db.getNote(original.id)[field], "Submitted edit");+ assert.equal(db.getNote(original.id)[`${field}_sync_operation`], "set");+ });+}diff --git a/test/helpers/noteCreateReconciliation.test.js b/test/helpers/noteCreateReconciliation.test.jsnew file mode 100644index 000000000..ed6f6988d--- /dev/null+++ b/test/helpers/noteCreateReconciliation.test.js@@ -0,0 +1,399 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createDb } = require("./harness/db.js");+const globals = require("./harness/browserGlobals.js");+const { createElectronApi } = require("./harness/electronApiBridge.js");+const { createFakeCloud } = require("./harness/fakeCloud.js");+const { SyncService } = require("../../src/services/SyncService.ts");+const { resolveCloudNoteCreate } = require("../../src/services/noteCreateAck.ts");+const { readNoteConflictIds } = require("../../src/lib/noteConflictRegistry.ts");++function setup(t) {+ const db = createDb(t);+ assert.ok(db);+ const id = db.saveNote("Lost response", "Original notes").note.id;+ db.updateNote(id, {+ enhanced_content: "Original summary",+ enhancement_prompt: "Prompt",+ enhancement_template_id: "template",+ enhanced_at_content_hash: "hash",+ transcript: "Transcript",+ });+ const snapshot = db.getNote(id);+ const cloud = {+ ...snapshot,+ id: "cloud-note",+ user_id: "user-harness",+ folder_id: null,+ space_id: null,+ revision: 2,+ content_state: null,+ enhanced_content_state: null,+ updated_at: "2026-10-09T20:00:00.000Z",+ write_applied: true,+ row_created: false,+ };+ const acknowledge = (receipt = cloud, options) =>+ resolveCloudNoteCreate(+ snapshot,+ receipt,+ {+ acknowledge: async (...args) => db.acknowledgeNoteCreate(...args),+ deleteCloud: () => assert.fail("An existing row is not an orphan of this request"),+ },+ options+ );+ return { db, id, snapshot, cloud, acknowledge };+}++function reopen(db) {+ const filename = db.db.name;+ db.db.close();+ db.db = new (require("better-sqlite3"))(filename);+}++async function sync(t, db, cloud, { fail = false, missing = false } = {}) {+ globals.resetBrowserGlobals();+ globals.installBrowserGlobals();+ globals.enableSync();+ const fallback = createFakeCloud();+ const wire = {+ calls: [],+ async request(opts) {+ this.calls.push(opts);+ if (opts.path.startsWith("/api/notes/list")) {+ if (fail) return { success: false, status: 503, error: "offline" };+ return { success: true, data: { notes: missing ? [] : [cloud] } };+ }+ if (opts.path === "/api/notes/update") assert.fail("Must reconcile before PATCH");+ return fallback.request(opts);+ },+ };+ globals.window.electronAPI = createElectronApi(db, { cloud: wire });+ await globals.establishValidatedAuth();+ const service = new SyncService();+ t.after(() => globals.stopSyncTimers(service));+ return { service, wire };+}++function clear(cloud, field) {+ cloud[field] = field === "content" ? "" : null;+ cloud[`${field}_state`] = "clear";+ if (field === "enhanced_content") {+ cloud.enhancement_prompt = null;+ cloud.enhanced_at_content_hash = null;+ }+}++function lean(cloud) {+ const { id, client_note_id, updated_at, revision, write_applied, row_created } = cloud;+ return { id, client_note_id, updated_at, revision, write_applied, row_created };+}++for (const field of ["content", "enhanced_content"]) {+ for (const later of [null, "title", field, "enhancement_template_id"]) {+ test(`create receipt reconciles ${field} and preserves later ${later ?? "no edit"}`, async (t) => {+ const { db, id, cloud, acknowledge } = setup(t);+ clear(cloud, field);+ if (later) db.updateNote(id, { [later]: "Later edit" });+ await acknowledge();+ const note = db.getNote(id);+ const summaryEdited = field === "enhanced_content" && later === "enhancement_template_id";+ assert.equal(+ note[field] ?? "",+ later === field || summaryEdited+ ? later === field+ ? "Later edit"+ : "Original summary"+ : ""+ );+ assert.equal(+ note[`${field}_sync_operation`],+ later === field || summaryEdited ? "set" : null+ );+ assert.equal(note.sync_status, later ? "pending" : "synced");+ assert.equal(note.cloud_revision, cloud.revision);+ assert.equal(note.transcript, "Transcript");+ if (field === "enhanced_content" && !summaryEdited && later !== field) {+ assert.equal(note.enhancement_prompt, null);+ assert.equal(note.enhanced_at_content_hash, null);+ assert.equal(note.enhancement_template_id, "template");+ }+ if (later) assert.equal(note[later], "Later edit");+ });+ }++ test(`a lean create receipt recovers ${field} after failed/missing pulls and restart`, async (t) => {+ const { db, id, cloud, acknowledge } = setup(t);+ clear(cloud, field);+ await acknowledge(lean(cloud));+ assert.equal(db.getNote(id).sync_status, "pending");+ assert.ok(db.getNote(id).cloud_create_pending);+ assert.equal(db.getNote(id).cloud_create_rejected, 0);+ assert.equal(db.getNote(id).cloud_revision, null);+ reopen(db);+ await (await sync(t, db, cloud, { fail: true })).service.pushPendingNotes();+ await (await sync(t, db, cloud, { missing: true })).service.pushPendingNotes();+ assert.ok(db.getNote(id).cloud_create_pending);+ const { service } = await sync(t, db, cloud);+ await service.pullNotes(false, true);+ await service.pullNotes(false, true);+ reopen(db);+ assert.equal(db.getNote(id)[field] ?? "", "");+ assert.equal(db.getNote(id).sync_status, "synced");+ assert.equal(db.getNote(id).cloud_revision, cloud.revision);+ assert.equal(db.getNote(id).cloud_create_pending, null);+ });+}++for (const invalidated of [false, true]) {+ test(`an applied retry does not authorize orphan deletion (invalidated=${invalidated})`, async () => {+ const snapshot = { id: 42, client_note_id: "client-note" };+ for (const row_created of [false, undefined]) {+ const result = await resolveCloudNoteCreate(+ snapshot,+ {+ id: "existing",+ client_note_id: snapshot.client_note_id,+ write_applied: true,+ row_created,+ },+ {+ acknowledge: async () => ({ success: true, outcome: "orphaned" }),+ deleteCloud: () => assert.fail("No insertion proof"),+ },+ { requestStillCurrent: () => !invalidated }+ );+ assert.equal(result, "orphan-unproven");+ }+ });+}++test("a later server revision during deferred acknowledgement requires Keep/Refresh", async (t) => {+ const { db, id, snapshot, cloud, acknowledge } = setup(t);+ await acknowledge(lean(cloud));+ db.updateNote(id, { title: "My later title" });+ cloud.revision += 1;+ cloud.content = "Other device edit";+ const { service } = await sync(t, db, cloud);+ await service.pushPendingNotes();+ assert.ok(readNoteConflictIds().has(snapshot.client_note_id));+ assert.equal(db.getNote(id).title, "My later title");+ assert.equal(db.getNote(id).cloud_revision, null);+ assert.ok(db.getNote(id).cloud_create_pending);+ db.setNoteCloudBase(id, cloud.updated_at, cloud.revision, { keepLocal: true, cloudNote: cloud });+ assert.equal(db.getNote(id).cloud_create_pending, null);+});++test("Refresh clears deferred create recovery and takes the authoritative row", async (t) => {+ const { db, id, cloud, acknowledge } = setup(t);+ await acknowledge(lean(cloud));+ clear(cloud, "content");+ db.upsertNoteFromCloud(cloud, null);+ assert.equal(db.getNote(id).cloud_create_pending, null);+ assert.equal(db.getNote(id).content, "");+ assert.equal(db.getNote(id).sync_status, "synced");+});++test("a partial migration receipt reconciles text but leaves omitted work pending", async (t) => {+ const { db, id, cloud, acknowledge } = setup(t);+ clear(cloud, "content");+ await acknowledge(cloud, { settleIfUnchanged: false });+ assert.equal(db.getNote(id).content, "");+ assert.equal(db.getNote(id).content_sync_operation, null);+ assert.equal(db.getNote(id).sync_status, "pending");+ assert.equal(db.getNote(id).transcript, "Transcript");+});++test("API rollback without revisions retains unknown blanks while resolving a lean receipt", async (t) => {+ const { db, id, cloud, acknowledge } = setup(t);+ delete cloud.revision;+ delete cloud.content_state;+ delete cloud.enhanced_content_state;+ delete cloud.write_applied;+ delete cloud.row_created;+ cloud.content = "";+ await acknowledge(lean(cloud));+ reopen(db);+ await (await sync(t, db, cloud)).service.pullNotes(false, true);+ assert.equal(db.getNote(id).sync_status, "synced");+ assert.equal(db.getNote(id).content, "Original notes");+ assert.equal(db.getNote(id).cloud_revision, null);+ assert.equal(db.getNote(id).cloud_create_pending, null);+});++for (const receiptRevision of [true, false]) {+ test(`deferred create ignores an older pull (revision=${receiptRevision})`, async (t) => {+ const { db, id, cloud, acknowledge } = setup(t);+ if (!receiptRevision) delete cloud.revision;+ await acknowledge(lean(cloud));+ const stale = {+ ...cloud,+ revision: receiptRevision ? 1 : undefined,+ updated_at: "2026-10-09T19:00:00.000Z",+ };+ await (await sync(t, db, stale)).service.pullNotes(false, true);+ assert.equal(db.getNote(id).cloud_revision, null);+ assert.ok(db.getNote(id).cloud_create_pending);+ assert.equal(db.getNote(id).sync_status, "pending");+ await (await sync(t, db, cloud)).service.pullNotes(false, true);+ assert.equal(db.getNote(id).sync_status, "synced");+ assert.equal(db.getNote(id).cloud_create_pending, null);+ });+}++test("a deferred receipt preserves a later local edit while reconciling untouched text", async (t) => {+ const { db, id, cloud, acknowledge } = setup(t);+ clear(cloud, "content");+ await acknowledge(lean(cloud));+ db.updateNote(id, { title: "Later title" });+ reopen(db);+ await (await sync(t, db, cloud)).service.pullNotes(false, true);+ assert.equal(db.getNote(id).content, "");+ assert.equal(db.getNote(id).content_sync_operation, null);+ assert.equal(db.getNote(id).title, "Later title");+ assert.equal(db.getNote(id).sync_status, "pending");+ assert.equal(db.getNote(id).cloud_create_pending, null);+});++test("a deferred receipt with no later edit takes a newer server row as a whole", async (t) => {+ const { db, id, cloud, acknowledge } = setup(t);+ await acknowledge(lean(cloud));+ cloud.revision++;+ cloud.title = "Newer cloud title";+ clear(cloud, "content");+ await (await sync(t, db, cloud)).service.pullNotes(false, true);+ assert.equal(db.getNote(id).title, cloud.title);+ assert.equal(db.getNote(id).content, "");+ assert.equal(db.getNote(id).sync_status, "synced");+ assert.equal(db.getNote(id).cloud_revision, cloud.revision);+});++test("create acknowledgements never consume a deliberate clear that POST did not deliver", async (t) => {+ const { db, id, cloud } = setup(t);+ db.updateNote(id, { content: "", clear_fields: ["content"] });+ const snapshot = db.getNote(id);+ await resolveCloudNoteCreate(snapshot, cloud, {+ acknowledge: async (...args) => db.acknowledgeNoteCreate(...args),+ deleteCloud: () => assert.fail("Not an orphan"),+ });+ assert.equal(db.getNote(id).content, "");+ assert.equal(db.getNote(id).content_sync_operation, "clear");+ assert.equal(db.getNote(id).sync_status, "pending");+ assert.equal(db.getNote(id).cloud_revision, cloud.revision);+});++test("identity forks drop deferred receipts and prevent late acknowledgement", async (t) => {+ const { db, id, cloud, acknowledge } = setup(t);+ await acknowledge(lean(cloud));+ db.updateNote(id, { client_note_id: "forked", cloud_id: null });+ assert.equal(db.getNote(id).cloud_create_pending, null);+ assert.equal(await acknowledge(cloud), "orphan-unproven");+ assert.equal(db.getNote(id).cloud_id, null);+});++for (const batch of [false, true]) {+ for (const field of ["content", "enhanced_content"]) {+ test(`SyncService forwards ${batch ? "batch" : "single"} authoritative ${field} receipts`, async (t) => {+ const { db, id, cloud } = setup(t);+ clear(cloud, field);+ const { service } = await sync(t, db, cloud);+ const original = globals.window.electronAPI.cloudApiRequest;+ let creates = 0;+ globals.window.electronAPI.cloudApiRequest = async (opts) => {+ if (opts.path === (batch ? "/api/notes/batch-create" : "/api/notes/create")) {+ creates++;+ const input = batch ? opts.body.notes[0] : opts.body;+ assert.equal(input.updated_at, undefined);+ assert.equal(input.base_revision, undefined);+ return { success: true, data: batch ? { created: [cloud] } : cloud };+ }+ return original(opts);+ };+ if (batch) await service.pushPendingNotes();+ else await service.pushNote(id);+ assert.equal(creates, 1);+ assert.equal(db.getNote(id)[field] ?? "", "");+ assert.equal(db.getNote(id).sync_status, "synced");+ assert.equal(db.getNote(id)[`${field}_sync_operation`], null);+ });+ }+}++for (const field of ["content", "enhanced_content"]) {+ test(`legacy migration reconciles ${field} while retaining its omitted work`, async (t) => {+ const { db, id, snapshot, cloud } = setup(t);+ clear(cloud, field);+ await sync(t, db, cloud);+ globals.window.electronAPI.getNotes = async () => [snapshot];+ const original = globals.window.electronAPI.cloudApiRequest;+ let creates = 0;+ globals.window.electronAPI.cloudApiRequest = async (opts) => {+ if (opts.path === "/api/notes/batch-create") {+ creates++;+ assert.equal(opts.body.notes[0].enhanced_at_content_hash, "hash");+ assert.equal(opts.body.notes[0].transcript, undefined);+ return { success: true, data: { created: [cloud] } };+ }+ return original(opts);+ };+ const { startMigration } = require("../../src/stores/noteStore.ts");+ await startMigration();+ assert.equal(creates, 1);+ assert.equal(db.getNote(id)[field] ?? "", "");+ assert.equal(db.getNote(id)[`${field}_sync_operation`], null);+ assert.equal(db.getNote(id).sync_status, "pending");+ assert.equal(db.getNote(id).transcript, "Transcript");+ assert.equal(db.getNote(id).enhanced_at_content_hash, field === "content" ? "hash" : null);+ });+}++for (const field of ["content", "enhanced_content"]) {+ for (const editsText of [false, true]) {+ test(`Keep after deferred ${field} create sends only later edits (editsText=${editsText})`, async (t) => {+ const { db, id, snapshot, cloud, acknowledge } = setup(t);+ clear(cloud, field);+ await acknowledge(lean(cloud));+ db.updateNote(id, {+ title: "My later title",+ ...(editsText && { [field]: "My later text" }),+ });+ cloud.revision++;+ cloud.title = "Other device title";+ reopen(db);+ const { service } = await sync(t, db, cloud);+ const original = globals.window.electronAPI.cloudApiRequest;+ const patches = [];+ globals.window.electronAPI.cloudApiRequest = async (opts) => {+ if (opts.path === "/api/notes/update") {+ patches.push(opts.body);+ return {+ success: true,+ data: {+ ...cloud,+ ...JSON.parse(JSON.stringify(opts.body)),+ revision: cloud.revision + 1,+ },+ };+ }+ return original(opts);+ };+ await service.pushPendingNotes();+ assert.equal(patches.length, 0);+ assert.ok(readNoteConflictIds().has(snapshot.client_note_id));+ db.setNoteCloudBase(id, cloud.updated_at, cloud.revision, {+ keepLocal: true,+ cloudNote: cloud,+ });+ require("../../src/stores/noteStore.ts").clearNoteConflict(snapshot.client_note_id);+ await service.pushNote(id);+ assert.equal(patches.length, 1);+ assert.equal(patches[0].title, "My later title");+ assert.equal(patches[0].base_revision, cloud.revision);+ assert.equal(patches[0][field], editsText ? "My later text" : undefined);+ assert.equal(patches[0].field_updates[field], editsText ? "set" : undefined);+ assert.equal(db.getNote(id)[field] ?? "", editsText ? "My later text" : "");+ assert.equal(db.getNote(id).cloud_create_pending, null);+ });+ }+}diff --git a/test/helpers/noteFieldSync.test.js b/test/helpers/noteFieldSync.test.jsnew file mode 100644index 000000000..13a6bcce6--- /dev/null+++ b/test/helpers/noteFieldSync.test.js@@ -0,0 +1,1505 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createDb } = require("./harness/db.js");+const {+ installBrowserGlobals,+ resetBrowserGlobals,+ establishValidatedAuth,+ enableSync,+ stopSyncTimers,+ localStorage: localStorageStub,+ window: windowStub,+} = require("./harness/browserGlobals.js");+const { createElectronApi } = require("./harness/electronApiBridge.js");+const { createFakeCloud } = require("./harness/fakeCloud.js");+const { SyncService } = require("../../src/services/SyncService.ts");+const {+ buildNoteCreatePayload,+ buildNoteUpdatePayload,+ isCloudNoteNewer,+} = require("../../src/helpers/cloudSyncGuards.js");+const { noteAwaitsCloudResolution } = require("../../src/helpers/noteFieldSync.js");+const {+ readNoteConflictIds,+ readNoteConflicts,+ removeNoteConflictId,+} = require("../../src/lib/noteConflictRegistry.ts");+const { documentSaveUpdates } = require("../../src/lib/noteEditorPendingSave.ts");++const INITIAL = {+ id: "cloud-note",+ client_note_id: "client-note",+ title: "Meeting",+ content: "Personal notes\n\nRemove this section",+ enhanced_content: "Summary\n\nRemove this section",+ enhancement_prompt: "Summarize",+ enhancement_template_id: "template",+ enhanced_at_content_hash: "hash",+ transcript: "Original transcript",+ note_type: "meeting",+ folder_id: null,+ space_id: null,+ user_id: "user-harness",+ created_at: "2026-01-01T00:00:00.000Z",+ updated_at: "2026-01-01T00:00:00.000Z",+ revision: 7,+ content_state: null,+ enhanced_content_state: null,+};+const copy = (value) => JSON.parse(JSON.stringify(value));+const SUMMARY_KEYS = ["enhancement_prompt", "enhancement_template_id", "enhanced_at_content_hash"];++test("explicit server clears replace stored text while an empty transcript remains protected", (t) => {+ const db = createDb(t);+ if (!db) return;+ const original = db.upsertNoteFromCloud(INITIAL, null);+ db.upsertNoteFromCloud(+ {+ ...INITIAL,+ revision: 8,+ content: "",+ enhanced_content: null,+ content_state: "clear",+ enhanced_content_state: "clear",+ transcript: null,+ },+ null+ );+ reopen(db);+ const reopened = db.getNote(original.id);+ assert.equal(reopened.content, "");+ assert.equal(reopened.enhanced_content, null);+ assert.equal(reopened.enhancement_prompt, null);+ // The template is the note's choice and survives a summary clear.+ assert.equal(reopened.enhancement_template_id, INITIAL.enhancement_template_id);+ assert.equal(reopened.transcript, INITIAL.transcript);+});++// Only HTTP is simulated here. The API companion tests run its real SQL and+// validation; this fixture exercises the desktop save/push/ack/pull boundary.+function protocolCloud(initial = INITIAL) {+ let row = copy(initial);+ const fallback = createFakeCloud();+ const calls = [];+ // The text each clear removed: a legacy write resending exactly it is ignored.+ const removed = {};+ return {+ calls,+ row: () => copy(row),+ replace: (next) => {+ row = copy(next);+ },+ async request(opts) {+ calls.push(copy(opts));+ if (opts.path.startsWith("/api/notes/list"))+ return { success: true, data: { notes: [copy(row)] } };+ if (opts.path !== "/api/notes/update") return fallback.request(opts);+ const input = copy(opts.body);+ const revisioned = Number.isSafeInteger(row.revision);+ const mobile = opts.headers?.["x-openwhispr-platform"] === "mobile";+ if (input.base_revision !== undefined && input.base_revision !== row.revision)+ return {+ success: false,+ status: 409,+ code: "note_version_conflict",+ details: { note: copy(row) },+ };+ for (const [field, operation] of Object.entries(input.field_updates ?? {})) {+ if ((operation === "clear") === Boolean(input[field]?.trim()))+ return { success: false, status: 400, code: "validation_error" };+ }+ row.title = input.title ?? row.title;+ for (const field of ["content", "enhanced_content"]) {+ let operation = input.field_updates?.[field];+ if (+ !operation &&+ !mobile &&+ input.base_revision === undefined &&+ input[field] === removed[field]+ )+ continue;+ // Only mobile's timestamp-based legacy blank is an explicit clear.+ // Desktop blanks still write, but leave their intent unknown.+ if (!operation && input[field]?.trim()) operation = "set";+ if (!operation && input[field] === "" && input.base_revision === undefined) {+ if (revisioned && mobile && input.base_updated_at) operation = "clear";+ else {+ if (revisioned && row[field]) row[`${field}_state`] = null;+ row[field] = "";+ continue;+ }+ }+ if (!operation) continue;+ if (operation === "clear") removed[field] = row[field];+ row[field] = operation === "clear" ? (field === "content" ? "" : null) : input[field];+ if (revisioned) row[`${field}_state`] = operation;+ if (field === "enhanced_content") {+ for (const meta of ["enhancement_prompt", "enhanced_at_content_hash"])+ row[meta] = operation === "clear" ? null : (input[meta] ?? null);+ if (operation === "set")+ row.enhancement_template_id = input.enhancement_template_id ?? null;+ }+ }+ if (revisioned) row.revision += 1;+ row.updated_at = new Date(Date.parse(row.updated_at) + 1).toISOString();+ return { success: true, data: copy(row) };+ },+ };+}++async function client(t, db, cloud) {+ resetBrowserGlobals();+ installBrowserGlobals();+ enableSync();+ windowStub.electronAPI = createElectronApi(db, { cloud });+ await establishValidatedAuth();+ const service = new SyncService();+ t.after(() => stopSyncTimers(service));+ return service;+}++function reopen(db) {+ const filename = db.db.name;+ db.db.close();+ db.db = new (require("better-sqlite3"))(filename);+}++for (const field of ["content", "enhanced_content"]) {+ test(`${field}: an offline deliberate clear reaches a second client and survives reopen; Undo is a newer edit`, async (t) => {+ const a = createDb(t);+ const b = createDb(t);+ if (!a || !b) return;+ const cloud = protocolCloud();+ const noteA = a.upsertNoteFromCloud(INITIAL, null);+ const noteB = b.upsertNoteFromCloud(INITIAL, null);+ assert.equal(a.updateNote(noteA.id, { clear_fields: [field] }).success, true);+ // A later title autosave resends the now-blank document after debounce.+ a.updateNote(noteA.id, { title: "Renamed offline", [field]: a.getNote(noteA.id)[field] });+ reopen(a);+ assert.equal(a.getNote(noteA.id)[`${field}_sync_operation`], "clear");+ await (await client(t, a, cloud)).pushPendingNotes();+ assert.equal(a.getNote(noteA.id).sync_status, "synced");+ await (await client(t, b, cloud)).pullNotes(false, true);+ reopen(b);+ assert.equal(b.getNote(noteB.id)[field] ?? "", "");+ assert.equal(b.getNote(noteB.id).transcript, INITIAL.transcript);+ const other = field === "content" ? "enhanced_content" : "content";+ assert.equal(b.getNote(noteB.id)[other], INITIAL[other]);+ if (field === "enhanced_content") {+ for (const meta of ["enhancement_prompt", "enhanced_at_content_hash"])+ assert.equal(b.getNote(noteB.id)[meta], null);+ assert.equal(b.getNote(noteB.id).enhancement_template_id, INITIAL.enhancement_template_id);+ }+ a.updateNote(noteA.id, { [field]: INITIAL[field] });+ await (await client(t, a, cloud)).pushPendingNotes();+ await (await client(t, b, cloud)).pullNotes(false, true);+ assert.equal(b.getNote(noteB.id)[field], INITIAL[field]);+ assert.equal(b.getNote(noteB.id).cloud_revision, 9);+ cloud.replace({ ...INITIAL, updated_at: "2099-01-01T00:00:00Z" });+ await (await client(t, b, cloud)).pullNotes(false, true);+ assert.equal(+ b.getNote(noteB.id).cloud_revision,+ 9,+ "an old revision cannot win through clock skew"+ );+ });++ test(`${field}: absent, null, blank and unmarked whitespace pulls preserve good text`, (t) => {+ const db = createDb(t);+ if (!db) return;+ const original = db.upsertNoteFromCloud(INITIAL, null);+ for (const value of [undefined, null, "", "\t\n", "\u00a0"]) {+ const incoming = { ...INITIAL, revision: 8, [field]: value };+ delete incoming[`${field}_state`];+ db.upsertNoteFromCloud(copy(incoming), null);+ assert.equal(db.getNote(original.id)[field], INITIAL[field]);+ assert.equal(db.getNote(original.id).transcript, INITIAL.transcript);+ }+ });++ test(`${field}: a partial edit and a clear followed by in-flight Undo retain separate intent`, (t) => {+ const db = createDb(t);+ if (!db) return;+ const original = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(original.id, { [field]: "Retained section" });+ assert.equal(buildNoteUpdatePayload(db.getNote(original.id), null).field_updates[field], "set");+ db.updateNote(original.id, { clear_fields: [field] });+ const snapshot = db.getNote(original.id);+ db.updateNote(original.id, { [field]: INITIAL[field] });+ const result = db.markNoteSyncedIfUnchanged(+ original.id,+ snapshot,+ INITIAL.id,+ "2026-01-01T00:00:01Z",+ INITIAL.user_id,+ 8+ );+ assert.equal(result.outcome, "pending");+ const pending = db.getNote(original.id);+ assert.equal(pending[field], INITIAL[field]);+ assert.equal(pending[`${field}_sync_operation`], "set");+ assert.equal(buildNoteUpdatePayload(pending, null).base_revision, 8);+ db.markNoteSyncedIfUnchanged(+ original.id,+ pending,+ INITIAL.id,+ "2026-01-01T00:00:02Z",+ INITIAL.user_id,+ 9+ );+ db.markNoteSyncedIfUnchanged(+ original.id,+ snapshot,+ INITIAL.id,+ "2099-01-01T00:00:00Z",+ INITIAL.user_id,+ 8+ );+ assert.equal(db.getNote(original.id).cloud_revision, 9);+ });+}++test("against an API without revisions, a clear with a timestamp base pushes as a blank and settles", (t) => {+ const db = createDb(t);+ if (!db) return;+ const { revision: _revision, ...legacy } = INITIAL;+ const row = db.upsertNoteFromCloud(legacy, null);+ db.updateNote(row.id, { clear_fields: ["content", "enhanced_content"] });+ const pending = db.getNote(row.id);+ // A server that keeps revisions would store this legacy blank as unknown+ // intent, not a clear, so there the clear waits for a revision.+ assert.equal(noteAwaitsCloudResolution(pending, true), true);+ assert.equal(noteAwaitsCloudResolution(pending, false), false);+ const payload = buildNoteUpdatePayload(pending, null);+ assert.equal(payload.base_revision, undefined);+ assert.equal(payload.base_updated_at, INITIAL.updated_at);+ assert.equal(payload.content, "");+ assert.equal(payload.enhanced_content, "");+ // A pre-protocol API answers without a revision; the ack still settles.+ assert.equal(+ db.markNoteSyncedIfUnchanged(row.id, pending, INITIAL.id, INITIAL.updated_at).outcome,+ "synced"+ );+ assert.equal(db.getNote(row.id).content_sync_operation, null);+});++test("an unconfirmed local blank is never pushed as a clear", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { content: "", enhanced_content: null, title: "Renamed" });+ const payload = buildNoteUpdatePayload(db.getNote(row.id), null);+ assert.equal("content" in JSON.parse(JSON.stringify(payload)), false);+ assert.equal("enhanced_content" in JSON.parse(JSON.stringify(payload)), false);+ assert.deepEqual(payload.field_updates, {});+});++test("a clear on a pre-guard row adopts the revision without a false conflict", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { cloud_updated_at: null, cloud_revision: null });+ db.db.prepare("UPDATE notes SET cloud_revision = NULL WHERE id = ?").run(row.id);+ db.updateNote(row.id, { clear_fields: ["content"] });+ assert.equal(noteAwaitsCloudResolution(db.getNote(row.id), true), true);+ assert.equal(noteAwaitsCloudResolution(db.getNote(row.id), false), false);+ const cloud = protocolCloud();+ await (await client(t, db, cloud)).pushPendingNotes();+ assert.equal(readNoteConflictIds().has(INITIAL.client_note_id), false);+ assert.equal(db.getNote(row.id).sync_status, "synced");+ assert.equal(cloud.row().content, "");+ assert.equal(cloud.row().content_state, "clear");+ assert.ok(+ cloud.calls.findIndex((call) => call.path.startsWith("/api/notes/list")) <+ cloud.calls.findIndex((call) => call.path === "/api/notes/update")+ );+});++test("rejects unsupported/contradictory clears; another cloud row or account is skipped, not thrown", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ assert.equal(db.updateNote(row.id, { clear_fields: ["transcript"] }).success, false);+ assert.equal(+ db.updateNote(row.id, { content: "Keep me", clear_fields: ["content"] }).success,+ false+ );+ assert.equal(db.getNote(row.id).transcript, INITIAL.transcript);+ const skipped = db.upsertNoteFromCloud({ ...INITIAL, id: "other-cloud", content: "Other" }, null);+ assert.equal(skipped, null);+ assert.equal(db.getNote(row.id).content, INITIAL.content);+ db.updateNote(row.id, { cloud_id: null, client_note_id: "forked-identity" });+ assert.equal(db.getNote(row.id).cloud_revision, null);+ assert.equal(+ db.markNoteSyncedIfUnchanged(row.id, row, INITIAL.id, INITIAL.updated_at, INITIAL.user_id, 8)+ .outcome,+ "identity-changed"+ );+});++test("pulls adopt unattributed rows and personal<->team moves instead of aborting", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const unattributed = db.upsertNoteFromCloud(INITIAL, null);+ db.db.prepare("UPDATE notes SET account_id = NULL WHERE id = ?").run(unattributed.id);+ const moved = db.upsertNoteFromCloud(+ { ...INITIAL, revision: 8, title: "Edited elsewhere" },+ null+ );+ assert.equal(moved.title, "Edited elsewhere");+ assert.equal(moved.account_id, db.getNote(unattributed.id).account_id);++ // A full pull carries on past such a row to the notes after it.+ db.db.prepare("UPDATE notes SET account_id = NULL WHERE id = ?").run(unattributed.id);+ const second = { ...INITIAL, id: "cloud-2", client_note_id: "client-2", title: "Brand new" };+ const cloud = {+ request: async (opts) =>+ opts.path.startsWith("/api/notes/list")+ ? {+ success: true,+ data: { notes: [{ ...INITIAL, revision: 9, title: "Again" }, second] },+ }+ : createFakeCloud().request(opts),+ };+ assert.equal(await (await client(t, db, cloud)).pullNotes(false, true), true);+ assert.equal(db.getNote(unattributed.id).title, "Again");+ assert.equal(db.getNoteByClientId("client-2")?.title, "Brand new");+});++test("an API without revisions still applies pulls and settles pushes", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ const { revision: _revision, ...legacy } = INITIAL;+ db.upsertNoteFromCloud(+ { ...legacy, title: "Edited after rollback", updated_at: "2026-02-01T00:00:00.000Z" },+ null+ );+ assert.equal(db.getNote(row.id).title, "Edited after rollback");+ assert.equal(db.getNote(row.id).cloud_revision, null);+ assert.equal(isCloudNoteNewer({ updated_at: "2099-01-01T00:00:00Z" }, db.getNote(row.id)), true);+ db.updateNote(row.id, { title: "Local" });+ const snapshot = db.getNote(row.id);+ db.db.prepare("UPDATE notes SET cloud_revision = 9 WHERE id = ?").run(row.id);+ assert.equal(+ db.markNoteSyncedIfUnchanged(row.id, snapshot, INITIAL.id, INITIAL.updated_at).outcome,+ "pending",+ "the snapshot no longer matches the row's revision"+ );+ const current = db.getNote(row.id);+ assert.equal(+ db.markNoteSyncedIfUnchanged(row.id, current, INITIAL.id, INITIAL.updated_at).outcome,+ "synced"+ );+ assert.equal(db.getNote(row.id).cloud_revision, null);+});++test("creating a note with typed text settles in one request; a clear still follows", (t) => {+ const db = createDb(t);+ if (!db) return;+ for (const [edit, expected] of [+ [{ content: "Typed offline" }, "synced"],+ [{ clear_fields: ["content"] }, "pending"],+ ]) {+ const note = db.saveNote("Offline", "Draft").note;+ db.updateNote(note.id, edit);+ const snapshot = db.getNote(note.id);+ const ack = db.acknowledgeNoteCreate(+ note.id,+ snapshot,+ `cloud-${note.id}`,+ INITIAL.updated_at,+ null,+ { cloudRevision: 0 }+ );+ assert.equal(ack.outcome, expected);+ const after = db.getNote(note.id);+ assert.equal(after.content_sync_operation, expected === "synced" ? null : "clear");+ }+});++test("revisions order same-timestamp pulls and outrank clock skew", () => {+ const local = { cloud_revision: 8, updated_at: INITIAL.updated_at };+ assert.equal(isCloudNoteNewer({ ...INITIAL, revision: 9 }, local), true);+ assert.equal(+ isCloudNoteNewer({ ...INITIAL, revision: 7, updated_at: "2099-01-01T00:00:00Z" }, local),+ false+ );+});++test("Keep merges per field: local edits stay, untouched fields take the cloud's set or clear", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { title: "Local rename" });+ // A revision adopted at a pull grants no edit.+ db.setNoteCloudBase(row.id, INITIAL.updated_at, 8);+ assert.deepEqual(buildNoteUpdatePayload(db.getNote(row.id), null).field_updates, {});+ db.updateNote(row.id, { content: "Edited locally" });+ const cloudNote = {+ ...INITIAL,+ revision: 9,+ content: "Edited elsewhere",+ enhanced_content: "Rewritten elsewhere",+ enhancement_prompt: "Other prompt",+ enhanced_at_content_hash: "other-hash",+ enhancement_template_id: "other-template",+ enhanced_content_state: "set",+ };+ const { note } = db.setNoteCloudBase(row.id, INITIAL.updated_at, 9, {+ keepLocal: true,+ cloudNote,+ });+ assert.equal(note.content, "Edited locally");+ for (const key of [+ "enhanced_content",+ "enhancement_prompt",+ "enhanced_at_content_hash",+ "enhancement_template_id",+ ])+ assert.equal(note[key], cloudNote[key]);+ assert.equal(note.title, "Local rename");+ assert.deepEqual(buildNoteUpdatePayload(note, null).field_updates, { content: "set" });+ assert.equal(db.setNoteCloudBase(row.id, INITIAL.updated_at, 8).success, false);+ assert.equal(db.getNote(row.id).cloud_revision, 9);+});++test("Keep takes another device's clear of a field this device never edited", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { content: "Edited locally" });+ const result = db.setNoteCloudBase(row.id, INITIAL.updated_at, 8, {+ keepLocal: true,+ cloudNote: {+ ...INITIAL,+ revision: 8,+ content: "",+ content_state: "clear",+ enhanced_content: null,+ enhanced_content_state: "clear",+ },+ });+ assert.equal(result.note.content, "Edited locally");+ assert.equal(result.note.enhanced_content, null);+ assert.equal(result.note.enhancement_prompt, null);+ assert.equal(result.note.enhanced_at_content_hash, null);+ assert.equal(result.note.enhancement_template_id, INITIAL.enhancement_template_id);+ assert.deepEqual(buildNoteUpdatePayload(result.note, null).field_updates, { content: "set" });+});++test("Keep never treats an unmarked cloud blank as a clear and never re-pushes untouched text", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { title: "Local rename" });+ const { note } = db.setNoteCloudBase(row.id, INITIAL.updated_at, 9, {+ keepLocal: true,+ cloudNote: { ...INITIAL, revision: 9, content: "", enhanced_content: null },+ });+ assert.equal(note.content, INITIAL.content);+ assert.equal(note.enhanced_content, INITIAL.enhanced_content);+ assert.deepEqual(buildNoteUpdatePayload(note, null).field_updates, {});+});++test("a rejected create retry links without a fresh base and parks stale intent as a conflict", async (t) => {+ const { resolveCloudNoteCreate } = require("../../src/services/noteCreateAck.ts");+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { cloud_id: null, content: "Offline edit" });+ const snapshot = db.getNote(row.id);+ const cloud = protocolCloud({+ ...INITIAL,+ revision: 12,+ content: "Newer device edit",+ content_state: "set",+ updated_at: "2026-01-02T00:00:00Z",+ });+ const outcome = await resolveCloudNoteCreate(+ snapshot,+ { ...cloud.row(), write_applied: false },+ {+ acknowledge: (...args) => db.acknowledgeNoteCreate(...args),+ deleteCloud: () => assert.fail("Rejected create must never delete"),+ }+ );+ assert.equal(outcome, "write-rejected");+ assert.equal(db.getNote(row.id).cloud_revision, null);+ assert.equal(db.getNote(row.id).cloud_updated_at, INITIAL.updated_at, "no fresh base");+ reopen(db);+ assert.equal(db.getNote(row.id).cloud_create_rejected, 1);+ assert.equal(noteAwaitsCloudResolution(db.getNote(row.id), false), true);+ const service = await client(t, db, cloud);+ await service.pushPendingNotes();+ await service.pullNotes(false, true);+ await service.pushPendingNotes();+ assert.equal(cloud.row().content, "Newer device edit");+ assert.equal(db.getNote(row.id).content, "Offline edit");+ assert.notEqual(db.getNote(row.id).sync_status, "synced");+});++test("a rejected legacy create stays parked across failed pulls, restart, and debounced push", async (t) => {+ const { resolveCloudNoteCreate } = require("../../src/services/noteCreateAck.ts");+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { cloud_id: null, cloud_updated_at: null, content: "Old local text" });+ const snapshot = db.getNote(row.id);+ await resolveCloudNoteCreate(+ snapshot,+ { ...INITIAL, write_applied: false },+ {+ acknowledge: (...args) => db.acknowledgeNoteCreate(...args),+ deleteCloud: () => assert.fail("Never delete a rejected create"),+ }+ );+ reopen(db);+ const fallback = createFakeCloud();+ let patches = 0;+ const cloud = {+ request: async (opts) => {+ if (opts.path.startsWith("/api/notes/list")) throw new Error("Offline");+ if (opts.path === "/api/notes/update") patches++;+ return fallback.request(opts);+ },+ };+ const service = await client(t, db, cloud);+ await service.pushPendingNotes();+ const requestRetry = t.mock.method(service, "requestSyncAll", () => {});+ await service.pushNote(row.id);+ assert.equal(requestRetry.mock.callCount(), 1);+ assert.equal(patches, 0);+ assert.equal(db.getNote(row.id).cloud_create_rejected, 1);+ // Keep clears quarantine only through the deliberate conflict resolution.+ db.setNoteCloudBase(row.id, INITIAL.updated_at, INITIAL.revision);+ assert.equal(db.getNote(row.id).cloud_create_rejected, 1);+ db.setNoteCloudBase(row.id, INITIAL.updated_at, INITIAL.revision, { keepLocal: true });+ assert.equal(db.getNote(row.id).cloud_create_rejected, 0);+ assert.equal(buildNoteUpdatePayload(db.getNote(row.id), null).field_updates.content, "set");+});++const listCalls = (cloud, kind) =>+ cloud.calls.filter((call) => {+ if (!call.path.startsWith("/api/notes/list")) return false;+ const query = new URLSearchParams(call.path.split("?")[1] ?? "");+ if (kind === "probe") return query.get("limit") === "1";+ return query.get("limit") !== "1" && !query.has("since");+ });+const updateCalls = (cloud) => cloud.calls.filter((call) => call.path === "/api/notes/update");+const withoutRevision = (db, id) =>+ db.db.prepare("UPDATE notes SET cloud_revision = NULL WHERE id = ?").run(id);++function unansweredRevisionProbeOnce(+ cloud,+ response = { success: false, status: 503, error: "Temporary capability discovery outage" }+) {+ let failed = false;+ return {+ ...cloud,+ async request(opts) {+ const query = new URLSearchParams(opts.path.split("?")[1] ?? "");+ if (!failed && opts.path.startsWith("/api/notes/list") && query.get("limit") === "1") {+ failed = true;+ cloud.calls.push(copy(opts));+ return copy(response);+ }+ return cloud.request(opts);+ },+ };+}++for (const field of ["content", "enhanced_content"]) {+ for (const timestampBase of [true, false]) {+ const baseLabel = timestampBase ? "with a timestamp base" : "without a timestamp base";++ test(`${field}: legacy blanks ${baseLabel} distinguish desktop unknown intent from mobile clears`, async () => {+ for (const platform of ["desktop", "mobile"]) {+ const cloud = protocolCloud();+ const result = await cloud.request({+ path: "/api/notes/update",+ headers: { "x-openwhispr-platform": platform },+ body: {+ id: INITIAL.id,+ [field]: "",+ ...(timestampBase ? { base_updated_at: INITIAL.updated_at } : {}),+ },+ });+ const clear = platform === "mobile" && timestampBase;+ assert.equal(result.success, true);+ assert.equal(cloud.row()[field] ?? "", "");+ assert.equal(cloud.row()[`${field}_state`], clear ? "clear" : null);+ if (field === "enhanced_content") {+ assert.equal(cloud.row().enhancement_prompt, clear ? null : INITIAL.enhancement_prompt);+ assert.equal(+ cloud.row().enhanced_at_content_hash,+ clear ? null : INITIAL.enhanced_at_content_hash+ );+ assert.equal(cloud.row().enhancement_template_id, INITIAL.enhancement_template_id);+ }+ }+ });++ test(`${field}: failed capability discovery ${baseLabel} preserves a clear until a revisioned retry converges`, async (t) => {+ const a = createDb(t);+ const b = createDb(t);+ if (!a || !b) return;+ const noteA = a.upsertNoteFromCloud(INITIAL, null);+ const noteB = b.upsertNoteFromCloud(INITIAL, null);+ withoutRevision(a, noteA.id);+ if (!timestampBase)+ a.db.prepare("UPDATE notes SET cloud_updated_at = NULL WHERE id = ?").run(noteA.id);+ a.updateNote(noteA.id, { clear_fields: [field] });+ const cloud = unansweredRevisionProbeOnce(protocolCloud());+ const service = await client(t, a, cloud);+ const ack = t.mock.method(windowStub.electronAPI, "markNoteSyncedIfUnchanged");+ const adoptBase = t.mock.method(windowStub.electronAPI, "setNoteCloudBase");++ await service.pushPendingNotes();+ assert.equal(listCalls(cloud, "probe").length, 1);+ assert.equal(updateCalls(cloud).length, 0);+ assert.equal(ack.mock.callCount(), 0);+ assert.equal(adoptBase.mock.callCount(), 0);+ assert.deepEqual(cloud.row(), INITIAL);+ reopen(a);+ assert.equal(a.getNote(noteA.id).sync_status, "pending");+ assert.equal(a.getNote(noteA.id)[`${field}_sync_operation`], "clear");+ assert.equal(a.getNote(noteA.id).cloud_revision, null);++ await service.pushPendingNotes();+ assert.equal(listCalls(cloud, "probe").length, 2);+ assert.equal(listCalls(cloud, "full").length, 1);+ assert.equal(adoptBase.mock.callCount(), 1);+ assert.deepEqual(adoptBase.mock.calls[0].arguments, [+ noteA.id,+ INITIAL.updated_at,+ INITIAL.revision,+ ]);+ assert.equal(updateCalls(cloud).length, 1);+ const payload = updateCalls(cloud)[0].body;+ assert.equal(payload.base_revision, INITIAL.revision);+ assert.equal(payload.base_updated_at, INITIAL.updated_at);+ assert.deepEqual(payload.field_updates, { [field]: "clear" });+ assert.equal(payload[field], "");+ assert.equal(ack.mock.callCount(), 1);+ assert.equal(a.getNote(noteA.id).sync_status, "synced");+ assert.equal(a.getNote(noteA.id)[`${field}_sync_operation`], null);+ assert.equal(a.getNote(noteA.id).cloud_revision, cloud.row().revision);+ assert.equal(cloud.row()[`${field}_state`], "clear");++ await (await client(t, b, cloud)).pullNotes(false, true);+ reopen(b);+ const peer = b.getNote(noteB.id);+ assert.equal(peer[field] ?? "", "");+ const other = field === "content" ? "enhanced_content" : "content";+ assert.equal(peer[other], INITIAL[other]);+ assert.equal(peer.transcript, INITIAL.transcript);+ assert.equal(peer.cloud_revision, cloud.row().revision);+ assert.equal(peer.enhancement_template_id, INITIAL.enhancement_template_id);+ for (const meta of ["enhancement_prompt", "enhanced_at_content_hash"])+ assert.equal(peer[meta], field === "enhanced_content" ? null : INITIAL[meta]);+ });++ test(`${field}: observed old API ${baseLabel} retains the legacy clear fallback`, async (t) => {+ const db = createDb(t);+ if (!db) return;+ const {+ revision: _revision,+ content_state: _contentState,+ enhanced_content_state: _summaryState,+ ...legacy+ } = INITIAL;+ const row = db.upsertNoteFromCloud(legacy, null);+ if (!timestampBase)+ db.db.prepare("UPDATE notes SET cloud_updated_at = NULL WHERE id = ?").run(row.id);+ db.updateNote(row.id, { clear_fields: [field] });+ const cloud = protocolCloud(legacy);+ const service = await client(t, db, cloud);+ const ack = t.mock.method(windowStub.electronAPI, "markNoteSyncedIfUnchanged");+ await service.pushPendingNotes();+ assert.equal(listCalls(cloud, "probe").length, 1);+ assert.equal(listCalls(cloud, "full").length, 0);+ assert.equal(updateCalls(cloud).length, 1);+ const payload = updateCalls(cloud)[0].body;+ assert.equal(payload.base_revision, undefined);+ assert.equal(payload.field_updates, undefined);+ assert.equal(payload.base_updated_at, timestampBase ? INITIAL.updated_at : undefined);+ assert.equal(payload[field], "");+ assert.equal(cloud.row()[field], "");+ assert.equal(cloud.row().revision, undefined);+ assert.equal(ack.mock.callCount(), 1);+ assert.equal(db.getNote(row.id).sync_status, "synced");+ assert.equal(db.getNote(row.id)[`${field}_sync_operation`], null);+ assert.equal(db.getNote(row.id).cloud_revision, null);+ assert.equal(db.getNote(row.id).transcript, INITIAL.transcript);+ });+ }++ test(`${field}: a stale timestamp base after failed discovery remains a pending conflict`, async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ withoutRevision(db, row.id);+ db.updateNote(row.id, { clear_fields: [field] });+ const cloud = unansweredRevisionProbeOnce(protocolCloud());+ const service = await client(t, db, cloud);+ const ack = t.mock.method(windowStub.electronAPI, "markNoteSyncedIfUnchanged");+ await service.pushPendingNotes();+ const newer = {+ ...INITIAL,+ [field]: "Edited elsewhere during the outage",+ updated_at: "2026-01-02T00:00:00.000Z",+ revision: 8,+ };+ cloud.replace(newer);+ await service.pushPendingNotes();+ await service.pushPendingNotes();+ assert.equal(listCalls(cloud, "probe").length, 2);+ assert.equal(listCalls(cloud, "full").length, 1);+ assert.equal(updateCalls(cloud).length, 0);+ assert.equal(ack.mock.callCount(), 0);+ assert.equal(readNoteConflictIds().has(INITIAL.client_note_id), true);+ assert.deepEqual(cloud.row(), newer);+ assert.equal(db.getNote(row.id).sync_status, "pending");+ assert.equal(db.getNote(row.id)[`${field}_sync_operation`], "clear");+ assert.equal(db.getNote(row.id).cloud_revision, null);+ assert.equal(db.getNote(row.id).cloud_updated_at, INITIAL.updated_at);+ });+}++for (const [kind, notes] of [+ ["empty", []],+ [+ "access-removed",+ [{ id: INITIAL.id, client_note_id: INITIAL.client_note_id, access_removed: true }],+ ],+]) {+ test(`${kind} discovery remains unknown until a readable revision allows both clears`, async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ withoutRevision(db, row.id);+ db.updateNote(row.id, { clear_fields: ["content", "enhanced_content"] });+ const cloud = unansweredRevisionProbeOnce(protocolCloud(), { success: true, data: { notes } });+ const service = await client(t, db, cloud);+ const ack = t.mock.method(windowStub.electronAPI, "markNoteSyncedIfUnchanged");+ await service.pushPendingNotes();+ assert.equal(updateCalls(cloud).length, 0);+ assert.equal(ack.mock.callCount(), 0);+ assert.equal(db.getNote(row.id).sync_status, "pending");+ assert.equal(db.getNote(row.id).content_sync_operation, "clear");+ assert.equal(db.getNote(row.id).enhanced_content_sync_operation, "clear");+ assert.equal(db.getNote(row.id).cloud_revision, null);+ assert.deepEqual(cloud.row(), INITIAL);+ await service.pushPendingNotes();+ assert.equal(listCalls(cloud, "probe").length, 2);+ assert.equal(listCalls(cloud, "full").length, 1);+ assert.equal(updateCalls(cloud).length, 1);+ assert.equal(updateCalls(cloud)[0].body.base_revision, INITIAL.revision);+ assert.deepEqual(updateCalls(cloud)[0].body.field_updates, {+ content: "clear",+ enhanced_content: "clear",+ });+ assert.equal(ack.mock.callCount(), 1);+ assert.equal(db.getNote(row.id).sync_status, "synced");+ assert.equal(cloud.row().content_state, "clear");+ assert.equal(cloud.row().enhanced_content_state, "clear");+ });+}++function rejectCreate(db, row, { cloudUpdatedAt = INITIAL.updated_at } = {}) {+ db.updateNote(row.id, { cloud_id: null, cloud_updated_at: cloudUpdatedAt, content: "Offline" });+ const snapshot = db.getNote(row.id);+ db.acknowledgeNoteCreate(row.id, snapshot, INITIAL.id, cloudUpdatedAt, null, {+ settleIfUnchanged: false,+ writeRejected: true,+ });+ return db.getNote(row.id);+}++test("a rejected create already surfaced as a conflict is not re-pulled every pass", async (t) => {+ const db = createDb(t);+ if (!db) return;+ rejectCreate(db, db.upsertNoteFromCloud(INITIAL, null));+ const cloud = protocolCloud({ ...INITIAL, revision: 12, content: "Newer elsewhere" });+ const service = await client(t, db, cloud);+ await service.pushPendingNotes();+ assert.equal(readNoteConflictIds().has(INITIAL.client_note_id), true);+ await service.pushPendingNotes();+ await service.pushPendingNotes();+ assert.equal(listCalls(cloud, "full").length, 1);+ assert.equal(updateCalls(cloud).length, 0);+});++test("a base-less clear pushes as before against an API without revisions", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const { revision: _revision, ...legacy } = INITIAL;+ const row = db.upsertNoteFromCloud(legacy, null);+ db.db.prepare("UPDATE notes SET cloud_updated_at = NULL WHERE id = ?").run(row.id);+ db.updateNote(row.id, { clear_fields: ["content"] });+ const cloud = protocolCloud(legacy);+ const service = await client(t, db, cloud);+ // Rows a pull returned already show the server keeps no revisions.+ await service.pullNotes(false, true);+ await service.pushPendingNotes();+ await service.pushPendingNotes();+ assert.equal(listCalls(cloud, "full").length, 1);+ assert.equal(listCalls(cloud, "probe").length, 0);+ assert.equal(updateCalls(cloud)[0].body.content, "");+ assert.equal(db.getNote(row.id).sync_status, "synced");+});++test("a debounced push leaves a base-less clear to the full pass until revisions are ruled out", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.db+ .prepare("UPDATE notes SET cloud_updated_at = NULL, cloud_revision = NULL WHERE id = ?")+ .run(row.id);+ db.updateNote(row.id, { clear_fields: ["content"] });+ const cloud = protocolCloud();+ const service = await client(t, db, cloud);+ const requestPass = t.mock.method(service, "requestSyncAll", () => {});+ await service.pushNote(row.id);+ assert.equal(requestPass.mock.callCount(), 1);+ assert.equal(updateCalls(cloud).length, 0);+});++test("a base-less clear the pull cannot resolve waits without a full pull every pass", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.db+ .prepare("UPDATE notes SET cloud_updated_at = NULL, cloud_revision = NULL WHERE id = ?")+ .run(row.id);+ db.updateNote(row.id, { clear_fields: ["content"] });+ // The server keeps revisions but this note is missing from its list.+ const cloud = protocolCloud({ ...INITIAL, id: "cloud-other", client_note_id: "client-other" });+ const service = await client(t, db, cloud);+ for (let pass = 0; pass < 3; pass++) await service.pushPendingNotes();+ assert.equal(listCalls(cloud, "full").length, 1);+ assert.equal(updateCalls(cloud).length, 0);+ assert.equal(db.getNote(row.id).content_sync_operation, "clear");+});++// A delta feed with nothing new: an unchanged row never re-enters it.+function quietDelta(cloud) {+ return {+ request: async (opts) => {+ if (!opts.path.includes("since=")) return cloud.request(opts);+ cloud.calls.push(copy(opts));+ return { success: true, data: { notes: [] } };+ },+ };+}++// Another device cleared content while this one ran a release that kept the+// text; the delta cursor never re-delivers that row.+async function clearedElsewhere(t) {+ const db = createDb(t);+ if (!db) return null;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ withoutRevision(db, row.id);+ const cloud = protocolCloud();+ await cloud.request({+ path: "/api/notes/update",+ body: { id: INITIAL.id, base_revision: 7, field_updates: { content: "clear" }, content: "" },+ });+ // That release's pull kept the text but took the row's timestamps.+ db.db+ .prepare("UPDATE notes SET cloud_updated_at = ?, updated_at = ? WHERE id = ?")+ .run(cloud.row().updated_at, cloud.row().updated_at, row.id);+ return { db, row, cloud };+}++test("a push ack takes the server's clear of a field this device never edited", async (t) => {+ const ctx = await clearedElsewhere(t);+ if (!ctx) return;+ const { db, row, cloud } = ctx;+ db.updateNote(row.id, { title: "Renamed" });+ await (await client(t, db, cloud)).pushPendingNotes();+ const note = db.getNote(row.id);+ assert.equal(cloud.row().content, "", "the stale text was not resurrected");+ assert.equal(note.content, "");+ assert.equal(note.sync_status, "synced");+ assert.equal(note.cloud_revision, cloud.row().revision);+ db.updateNote(row.id, { content: "Typed after the clear" });+ await (await client(t, db, cloud)).pushPendingNotes();+ assert.equal(cloud.row().content, "Typed after the clear");+});++test("a debounced push ack takes the server's clear too", async (t) => {+ const ctx = await clearedElsewhere(t);+ if (!ctx) return;+ const { db, row, cloud } = ctx;+ db.updateNote(row.id, { title: "Renamed" });+ await (await client(t, db, cloud)).pushNote(row.id);+ assert.equal(db.getNote(row.id).content, "");+ assert.equal(db.getNote(row.id).sync_status, "synced");+});++test("an ack never overwrites a blank or summary metadata typed while the push was in flight", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { title: "Renamed" });+ const snapshot = db.getNote(row.id);+ db.updateNote(row.id, { content: "" });+ db.updateNote(row.id, { enhancement_prompt: "Typed prompt" });+ db.markNoteSyncedIfUnchanged(row.id, snapshot, INITIAL.id, INITIAL.updated_at, null, 8, {+ ...INITIAL,+ revision: 8,+ });+ assert.equal(db.getNote(row.id).content, "");+ assert.equal(db.getNote(row.id).enhancement_prompt, "Typed prompt");+ assert.notEqual(db.getNote(row.id).sync_status, "synced");+});++test("a pull applies a clean pre-revision row whole, so a missed clear arrives", async (t) => {+ const ctx = await clearedElsewhere(t);+ if (!ctx) return;+ const { db, row, cloud } = ctx;+ await (await client(t, db, cloud)).pullNotes(false, true);+ assert.equal(db.getNote(row.id).content, "");+ assert.equal(db.getNote(row.id).cloud_revision, cloud.row().revision);+});++test("one snapshot pull per session backfills clean rows synced before revisions", async (t) => {+ const ctx = await clearedElsewhere(t);+ if (!ctx) return;+ const { db, row, cloud } = ctx;+ // A row the pull cannot resolve keeps the count up; it still pulls once.+ withoutRevision(+ db,+ db.upsertNoteFromCloud(+ { ...INITIAL, id: "cloud-missing", client_note_id: "client-missing" },+ null+ ).id+ );+ const service = await client(t, db, quietDelta(cloud));+ localStorageStub.setItem("lastSyncedAt.notes", "2026-06-01T00:00:00.000Z");+ await service.syncNotes();+ await service.syncNotes();+ assert.equal(db.getNote(row.id).content, "");+ assert.equal(listCalls(cloud, "full").length, 1);+});++test("an API without revisions never gets the revision backfill pull", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const { revision: _revision, ...legacy } = INITIAL;+ db.upsertNoteFromCloud(legacy, null);+ const cloud = protocolCloud(legacy);+ const service = await client(t, db, quietDelta(cloud));+ localStorageStub.setItem("lastSyncedAt.notes", "2026-06-01T00:00:00.000Z");+ await service.syncNotes();+ await service.syncNotes();+ assert.equal(listCalls(cloud, "full").length, 0);+ assert.equal(listCalls(cloud, "probe").length, 1);+});++test("a push ack restores text the device left out as an unconfirmed blank", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { content: "", title: "Renamed" });+ const cloud = protocolCloud();+ await (await client(t, db, cloud)).pushPendingNotes();+ assert.equal(db.getNote(row.id).content, INITIAL.content);+ assert.equal(db.getNote(row.id).sync_status, "synced");+});++test("an in-flight ack adopts only fields untouched since the push", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { title: "Renamed" });+ const snapshot = db.getNote(row.id);+ db.updateNote(row.id, { content: "Typed after the push" });+ const result = db.markNoteSyncedIfUnchanged(+ row.id,+ snapshot,+ INITIAL.id,+ "2026-01-01T00:00:01.000Z",+ INITIAL.user_id,+ 8,+ {+ ...INITIAL,+ revision: 8,+ content: "",+ content_state: "clear",+ enhanced_content: "Server summary",+ enhanced_content_state: "set",+ enhancement_prompt: "Server prompt",+ }+ );+ assert.equal(result.outcome, "pending");+ const note = db.getNote(row.id);+ assert.equal(note.content, "Typed after the push");+ assert.equal(note.content_sync_operation, "set");+ assert.equal(note.enhanced_content, "Server summary");+ assert.equal(note.enhancement_prompt, "Server prompt");+ assert.equal(note.enhanced_content_sync_operation, null);+ assert.equal(result.note.enhanced_content, "Server summary");+});++test("a pending pre-revision row with a stale base surfaces a conflict instead of overwriting", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ withoutRevision(db, row.id);+ db.updateNote(row.id, { content: "Local edit" });+ const cloud = protocolCloud({+ ...INITIAL,+ revision: 9,+ content: "Newer elsewhere",+ updated_at: "2026-01-05T00:00:00.000Z",+ });+ const service = await client(t, db, cloud);+ await service.pullNotes(false, true);+ assert.equal(readNoteConflictIds().has(INITIAL.client_note_id), true);+ assert.equal(db.getNote(row.id).cloud_revision, null);+ await service.pushPendingNotes();+ assert.equal(updateCalls(cloud).length, 0);+ assert.equal(cloud.row().content, "Newer elsewhere");+});++test("Refresh after a local clear drops the stale clear, so the next push is valid", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { clear_fields: ["content"] });+ const cloud = protocolCloud({ ...INITIAL, revision: 8, content: "Newer elsewhere" });+ db.upsertNoteFromCloud(cloud.row(), null);+ assert.equal(db.getNote(row.id).content_sync_operation, null);+ db.updateNote(row.id, { title: "Renamed" });+ await (await client(t, db, cloud)).pushPendingNotes();+ assert.equal(db.getNote(row.id).sync_status, "synced");+ assert.equal(cloud.row().content, "Newer elsewhere");+});++test("Refresh of a rejected create un-parks it", (t) => {+ const db = createDb(t);+ if (!db) return;+ const parked = rejectCreate(db, db.upsertNoteFromCloud(INITIAL, null));+ assert.equal(parked.cloud_create_rejected, 1);+ db.upsertNoteFromCloud({ ...INITIAL, revision: 12 }, null);+ assert.equal(db.getNote(parked.id).cloud_create_rejected, 0);+ assert.equal(noteAwaitsCloudResolution(db.getNote(parked.id), true), false);+});++test("a pull never applies another account's row", (t) => {+ const db = createDb(t);+ if (!db) return;+ db.setActiveAccountId("account-a");+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.setActiveAccountId("account-b");+ db.upsertNoteFromCloud({ ...INITIAL, revision: 8, title: "Other account" }, null);+ const stored = db.db.prepare("SELECT * FROM notes WHERE id = ?").get(row.id);+ assert.equal(stored.title, INITIAL.title);+ assert.equal(stored.account_id, "account-a");+});++test("only a changed text field, or changed summary metadata, becomes a set", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, {+ title: "Renamed",+ content: INITIAL.content,+ enhanced_content: INITIAL.enhanced_content,+ });+ assert.deepEqual(buildNoteUpdatePayload(db.getNote(row.id), null).field_updates, {});+ db.updateNote(row.id, { enhancement_prompt: "New prompt" });+ assert.deepEqual(buildNoteUpdatePayload(db.getNote(row.id), null).field_updates, {+ enhanced_content: "set",+ });+});++test("a local summary clear drops its prompt and hash but keeps the template", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ const { note } = db.updateNote(row.id, { clear_fields: ["enhanced_content"] });+ assert.equal(note.enhancement_prompt, null);+ assert.equal(note.enhanced_at_content_hash, null);+ assert.equal(note.enhancement_template_id, INITIAL.enhancement_template_id);+});++test("a batch create the server refused stays parked", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const note = db.saveNote("Offline", "Draft").note;+ const cloud = protocolCloud();+ const rejecting = {+ request: async (opts) =>+ opts.path === "/api/notes/batch-create"+ ? {+ success: true,+ data: {+ created: opts.body.notes.map((input) => ({+ client_note_id: input.client_note_id,+ id: "cloud-existing",+ updated_at: "2026-01-09T00:00:00.000Z",+ revision: 12,+ write_applied: false,+ })),+ },+ }+ : cloud.request(opts),+ };+ const service = await client(t, db, rejecting);+ t.mock.method(service, "requestSyncAll", () => {});+ await service.pushPendingNotes();+ const parked = db.getNote(note.id);+ assert.equal(parked.cloud_create_rejected, 1);+ assert.equal(parked.cloud_id, "cloud-existing");+ assert.equal(parked.cloud_revision, null);+ assert.notEqual(parked.sync_status, "synced");+});++test("create payloads never carry a revision base or field operations", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { content: "Edited" });+ const payload = buildNoteCreatePayload(db.getNote(row.id), null);+ assert.equal("base_revision" in payload, false);+ assert.equal("field_updates" in payload, false);+ assert.equal(payload.content, "Edited");+ // A create carries the whole note, whatever revision a fork left behind.+ assert.equal(payload.enhanced_content, INITIAL.enhanced_content);+ for (const key of SUMMARY_KEYS) assert.equal(payload[key], INITIAL[key], key);+});++test("rejected creates never settle or take the response's base, at either ack", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(row.id, { cloud_id: null, content: "Offline" });+ const snapshot = db.getNote(row.id);+ // Even a caller that asks to settle cannot settle a refused write.+ const ack = db.acknowledgeNoteCreate(row.id, snapshot, INITIAL.id, INITIAL.updated_at, null, {+ writeRejected: true,+ });+ assert.equal(ack.outcome, "pending");+ const parked = db.getNote(row.id);+ assert.equal(parked.cloud_create_rejected, 1);+ const patchAck = db.markNoteSyncedIfUnchanged(+ row.id,+ parked,+ INITIAL.id,+ "2026-01-09T00:00:00.000Z",+ INITIAL.user_id,+ 12,+ { ...INITIAL, revision: 12, content: "Newer elsewhere" }+ );+ assert.equal(patchAck.outcome, "pending");+ const after = db.getNote(row.id);+ assert.equal(after.cloud_create_rejected, 1);+ assert.equal(after.cloud_revision, null);+ assert.equal(after.cloud_updated_at, INITIAL.updated_at);+ assert.equal(after.content, "Offline");+});++test("an upsert older than the acknowledged revision is ignored", (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ db.upsertNoteFromCloud(+ { ...INITIAL, revision: 6, title: "Stale", updated_at: "2099-01-01T00:00:00.000Z" },+ null+ );+ assert.equal(db.getNote(row.id).title, INITIAL.title);+ assert.equal(db.getNote(row.id).cloud_revision, INITIAL.revision);+});++test("a rejected create surfaces a conflict even when the cloud row is older than the local edit", async (t) => {+ const db = createDb(t);+ if (!db) return;+ rejectCreate(db, db.upsertNoteFromCloud(INITIAL, null), { cloudUpdatedAt: null });+ const cloud = protocolCloud();+ await (await client(t, db, cloud)).pullNotes(false, true);+ assert.equal(readNoteConflictIds().has(INITIAL.client_note_id), true);+ assert.equal(db.getNoteByClientId(INITIAL.client_note_id).content, "Offline");+});++// --- Local text is the user's (F1), clears wait for a revision (F2), and+// opless text never travels on a revision-aware write (F3). ---++const DatabaseManager = require("../../src/helpers/database.js");+const SYNC_OPERATION_COLUMNS = ["content_sync_operation", "enhanced_content_sync_operation"];++// The database as a release without sync operations left it; reopening runs+// the upgrade.+function downgradeToReleasedSchema(db) {+ for (const column of SYNC_OPERATION_COLUMNS)+ db.db.exec(`ALTER TABLE notes DROP COLUMN ${column}`);+}+function upgrade(db) {+ db.db.close();+ db.initDatabase();+}+const operations = (note) => SYNC_OPERATION_COLUMNS.map((column) => note[column] ?? null);++test("every local writer records the text it writes as a set", (t) => {+ const db = createDb(t);+ if (!db) return;+ const typed = db.saveNote("Typed", "Typed body").note;+ assert.deepEqual(operations(typed), ["set", null]);+ assert.deepEqual(operations(db.saveNote("Meeting", "", "meeting").note), [null, null]);+ const { noteIds } = db.importNotes([+ { clientNoteId: "import-typed", title: "Imported", content: "Imported body" },+ { clientNoteId: "import-blank", title: "Blank", content: " " },+ ]);+ assert.deepEqual(+ noteIds.map((id) => operations(db.getNote(id))),+ [+ ["set", null],+ [null, null],+ ]+ );+ const pulled = db.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(pulled.id, { content: "Edited" });+ assert.deepEqual(operations(db.getNote(pulled.id)), ["set", null]);+ const assisted = db.upsertNoteFromCloud(+ { ...INITIAL, id: "cloud-assisted", client_note_id: "client-assisted" },+ null+ );+ const result = db.updateNote(+ assisted.id,+ { enhanced_content: "Rewritten summary" },+ { undoable: true, expected: db.getNote(assisted.id) }+ );+ assert.equal(result.success, true);+ assert.deepEqual(operations(db.getNote(assisted.id)), [null, "set"]);+});++test("a create ack resets the operations a rejected create keeps; creates never send them", (t) => {+ const db = createDb(t);+ if (!db) return;+ const settled = db.saveNote("Settled", "Typed body").note;+ assert.equal(+ db.acknowledgeNoteCreate(settled.id, settled, "cloud-settled", INITIAL.updated_at, null, {+ cloudRevision: 0,+ }).outcome,+ "synced"+ );+ assert.deepEqual(operations(db.getNote(settled.id)), [null, null]);+ const rejected = db.saveNote("Rejected", "A offline text").note;+ const payload = buildNoteCreatePayload(rejected, null);+ assert.equal("field_updates" in payload, false);+ assert.equal("base_revision" in payload, false);+ assert.equal(payload.content, "A offline text");+ db.acknowledgeNoteCreate(rejected.id, rejected, "cloud-rejected", INITIAL.updated_at, null, {+ writeRejected: true,+ });+ assert.deepEqual(operations(db.getNote(rejected.id)), ["set", null]);+});++// S6c: the create was written, the server row changed, and the retry was+// refused. Keep must deliver the text this device created, not take the+// server's copy of a field it "never edited".+test("Keep after a refused create keeps and delivers the note's own text", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const note = db.saveNote("Rejected", "A offline text").note;+ const server = {+ ...INITIAL,+ client_note_id: note.client_note_id,+ title: "Rejected",+ content: "Server newer text",+ content_state: "set",+ enhanced_content: null,+ revision: 12,+ updated_at: "2026-01-09T00:00:00.000Z",+ };+ db.acknowledgeNoteCreate(note.id, note, server.id, null, null, { writeRejected: true });+ const kept = db.setNoteCloudBase(note.id, server.updated_at, server.revision, {+ keepLocal: true,+ cloudNote: server,+ }).note;+ assert.equal(kept.content, "A offline text");+ assert.deepEqual(buildNoteUpdatePayload(kept, null).field_updates, { content: "set" });+ const cloud = protocolCloud(server);+ await (await client(t, db, cloud)).pushPendingNotes();+ assert.equal(cloud.row().content, "A offline text");+ assert.equal(db.getNote(note.id).sync_status, "synced");+});++test("the upgrade marks unsynced text from a release as a set, once", (t) => {+ const db = createDb(t);+ if (!db) return;+ const synced = db.upsertNoteFromCloud(INITIAL, null);+ const edited = db.upsertNoteFromCloud(+ { ...INITIAL, id: "cloud-edited", client_note_id: "client-edited" },+ null+ );+ const blanked = db.upsertNoteFromCloud(+ { ...INITIAL, id: "cloud-blanked", client_note_id: "client-blanked" },+ null+ );+ const fresh = db.saveNote("Never synced", "Offline body").note;+ downgradeToReleasedSchema(db);+ // What a release wrote: an edit, a blank, a new note; no operations.+ db.db+ .prepare("UPDATE notes SET content = ?, sync_status = 'pending' WHERE id = ?")+ .run("Offline edit", edited.id);+ db.db+ .prepare(+ "UPDATE notes SET content = '', enhanced_content = NULL, sync_status = 'error' WHERE id = ?"+ )+ .run(blanked.id);+ upgrade(db);+ assert.deepEqual(operations(db.getNote(synced.id)), [null, null]);+ assert.deepEqual(operations(db.getNote(edited.id)), ["set", "set"]);+ assert.deepEqual(+ operations(db.getNote(blanked.id)),+ [null, null],+ "a release's blank is no clear"+ );+ assert.deepEqual(operations(db.getNote(fresh.id)), ["set", null]);+ db.db+ .prepare(+ "UPDATE notes SET content_sync_operation = NULL, enhanced_content_sync_operation = NULL"+ )+ .run();+ upgrade(db);+ assert.deepEqual(operations(db.getNote(edited.id)), [null, null], "runs only once");+});++test("a database from before sync status marks all its text as a set", (t) => {+ const db = createDb(t);+ if (!db) return;+ const Database = db.db.constructor;+ const bare = new Database(":memory:");+ t.after(() => bare.close());+ bare.exec(`+ CREATE TABLE notes (id INTEGER PRIMARY KEY, content TEXT, enhanced_content TEXT,+ content_sync_operation TEXT, enhanced_content_sync_operation TEXT);+ INSERT INTO notes (content, enhanced_content) VALUES ('Body', NULL), ('', 'Summary');+ `);+ DatabaseManager.prototype._markUnsyncedNoteTextAsSet.call({ db: bare });+ assert.deepEqual(+ bare+ .prepare("SELECT content_sync_operation, enhanced_content_sync_operation FROM notes")+ .all()+ .map(Object.values),+ [+ ["set", null],+ [null, "set"],+ ]+ );+});++// U3: an offline edit made on a release, then the upgrade, then a conflict.+test("Keep after the upgrade keeps an offline edit made on a release", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ withoutRevision(db, row.id);+ downgradeToReleasedSchema(db);+ db.db+ .prepare("UPDATE notes SET content = ?, sync_status = 'pending' WHERE id = ?")+ .run("Offline edit made on a release", row.id);+ upgrade(db);+ const cloud = protocolCloud({+ ...INITIAL,+ revision: 8,+ title: "Renamed elsewhere",+ updated_at: "2026-01-05T00:00:00.000Z",+ });+ const service = await client(t, db, cloud);+ await service.pullNotes(false, true);+ const conflict = readNoteConflicts()[INITIAL.client_note_id];+ assert.ok(conflict, "the stale base surfaces a conflict");+ const kept = db.setNoteCloudBase(row.id, conflict.updated_at, conflict.revision, {+ keepLocal: true,+ cloudNote: conflict,+ }).note;+ removeNoteConflictId(INITIAL.client_note_id);+ assert.equal(kept.content, "Offline edit made on a release");+ await service.pushPendingNotes();+ assert.equal(cloud.row().content, "Offline edit made on a release");+});++// U1: the server stores a desktop's legacy blank as unknown intent, so a clear+// pushed without a revision would never reach other devices.+test("a clear on a row with a timestamp base and no revision waits for one, then pushes as a clear", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ withoutRevision(db, row.id);+ db.updateNote(row.id, { title: "Meeting", content: "", clear_fields: ["content"] });+ const cloud = protocolCloud();+ const service = await client(t, db, cloud);+ const requestPass = t.mock.method(service, "requestSyncAll", () => {});+ await service.pushNote(row.id);+ assert.equal(requestPass.mock.callCount(), 1);+ assert.equal(updateCalls(cloud).length, 0, "the debounced push leaves it to the full pass");+ await service.pushPendingNotes();+ assert.equal(listCalls(cloud, "full").length, 1);+ const [push] = updateCalls(cloud);+ assert.equal(push.body.base_revision, INITIAL.revision);+ assert.deepEqual(push.body.field_updates, { content: "clear" });+ assert.equal(cloud.row().content_state, "clear");+ assert.equal(db.getNote(row.id).sync_status, "synced");+});++// N3: this device kept its text over a blank another client never marked as a+// clear. Sending that text back would overwrite newer text written elsewhere.+test("a revision-aware push leaves out text and summary metadata without an operation", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const row = db.upsertNoteFromCloud(INITIAL, null);+ const blank = { ...INITIAL, revision: 9, content: "", enhanced_content: null };+ db.upsertNoteFromCloud(blank, null);+ assert.equal(db.getNote(row.id).content, INITIAL.content, "the pull kept the local text");+ db.updateNote(row.id, { title: "Renamed" });+ const body = JSON.parse(JSON.stringify(buildNoteUpdatePayload(db.getNote(row.id), null)));+ for (const key of ["content", "enhanced_content", ...SUMMARY_KEYS])+ assert.equal(key in body, false, key);+ assert.deepEqual(body.field_updates, {});+ const cloud = protocolCloud(blank);+ await (await client(t, db, cloud)).pushPendingNotes();+ assert.equal(cloud.row().title, "Renamed");+ assert.equal(cloud.row().content, "", "the kept text was not resent");+ // An edit carries its field (and a summary edit its metadata); a row+ // without a revision still sends the full snapshot.+ db.updateNote(row.id, { enhanced_content: "Edited summary" });+ const edited = buildNoteUpdatePayload(db.getNote(row.id), null);+ assert.equal(edited.enhanced_content, "Edited summary");+ assert.equal(edited.enhancement_prompt, INITIAL.enhancement_prompt);+ assert.equal("content" in JSON.parse(JSON.stringify(edited)), false);+ withoutRevision(db, row.id);+ assert.equal(buildNoteUpdatePayload(db.getNote(row.id), null).content, INITIAL.content);+});++// U2b: an ack applies a clear made elsewhere while the editor's title save+// waits. The save then writes only the title, so the clear stays.+test("a title save after an ack applied a clear does not bring the text back", async (t) => {+ const ctx = await clearedElsewhere(t);+ if (!ctx) return;+ const { db, row, cloud } = ctx;+ const draft = db.getNote(row.id);+ db.updateNote(row.id, { title: "T1" });+ await (await client(t, db, cloud)).pushPendingNotes();+ assert.equal(db.getNote(row.id).content, "", "the ack took the clear");+ db.updateNote(+ row.id,+ documentSaveUpdates({+ noteId: row.id,+ title: "T12",+ content: draft.content,+ contentEdited: false,+ clearContent: false,+ })+ );+ assert.equal(db.getNote(row.id).content, "");+ assert.equal(db.getNote(row.id).content_sync_operation, null);+ await (await client(t, db, cloud)).pushPendingNotes();+ assert.equal(cloud.row().title, "T12");+ assert.equal(cloud.row().content, "");+ assert.equal(cloud.row().content_state, "clear");+});diff --git a/test/helpers/noteRevisionRecovery.test.js b/test/helpers/noteRevisionRecovery.test.jsnew file mode 100644index 000000000..4badab841--- /dev/null+++ b/test/helpers/noteRevisionRecovery.test.js@@ -0,0 +1,344 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createDb } = require("./harness/db.js");+const {+ installBrowserGlobals,+ resetBrowserGlobals,+ establishValidatedAuth,+ enableSync,+ stopSyncTimers,+ localStorage: localStorageStub,+ window: windowStub,+} = require("./harness/browserGlobals.js");+const { createElectronApi } = require("./harness/electronApiBridge.js");+const { SyncService } = require("../../src/services/SyncService.ts");+const { readNoteConflicts } = require("../../src/lib/noteConflictRegistry.ts");++const INITIAL = {+ id: "cloud-note",+ client_note_id: "client-note",+ title: "Meeting",+ content: "Personal notes",+ enhanced_content: "Summary",+ enhancement_prompt: "Summarize",+ enhancement_template_id: "template",+ enhanced_at_content_hash: "hash",+ transcript: "Original transcript",+ note_type: "meeting",+ folder_id: null,+ space_id: null,+ user_id: "user-harness",+ created_at: "2026-01-01T00:00:00.000Z",+ updated_at: "2026-01-01T00:00:00.000Z",+ revision: 7,+ content_state: null,+ enhanced_content_state: null,+};+const OTHER = { ...INITIAL, id: "cloud-other", client_note_id: "client-other" };+const copy = (value) => JSON.parse(JSON.stringify(value));++// HTTP alone is simulated. Every delta is quiet, so unchanged pre-revision+// rows can recover only through a full snapshot. Writes require explicit,+// revision-guarded clears; a legacy blank cannot make these tests converge.+function recoveryCloud({ notes = [INITIAL], failedSnapshots = 0, probeNote = notes[0] } = {}) {+ const rows = new Map(notes.map((note) => [note.id, copy(note)]));+ const calls = [];+ return {+ calls,+ row: (id = INITIAL.id) => copy(rows.get(id)),+ async request(opts) {+ calls.push(copy(opts));+ if (opts.path.startsWith("/api/notes/list")) {+ const query = new URLSearchParams(opts.path.split("?")[1]);+ if (query.get("limit") === "1")+ return { success: true, data: { notes: [copy(probeNote)] } };+ if (query.has("since")) return { success: true, data: { notes: [] } };+ if (failedSnapshots > 0) {+ failedSnapshots--;+ return { success: false, status: 503, error: "Snapshot temporarily unavailable" };+ }+ return { success: true, data: { notes: [...rows.values()].map(copy) } };+ }+ assert.equal(opts.path, "/api/notes/update", "unexpected HTTP request");+ const input = opts.body;+ const row = rows.get(input.id);+ if (input.base_revision !== row.revision)+ return { success: false, status: 409, code: "note_version_conflict" };+ const operations = Object.entries(input.field_updates ?? {});+ if (+ operations.length === 0 ||+ operations.some(+ ([field, operation]) =>+ !["content", "enhanced_content"].includes(field) ||+ operation !== "clear" ||+ input[field] !== ""+ )+ )+ return { success: false, status: 400, code: "validation_error" };+ for (const [field] of operations) {+ row[field] = field === "content" ? "" : null;+ row[`${field}_state`] = "clear";+ if (field === "enhanced_content") {+ row.enhancement_prompt = null;+ row.enhanced_at_content_hash = null;+ }+ }+ row.revision++;+ row.updated_at = new Date(Date.parse(row.updated_at) + 1).toISOString();+ return { success: true, data: copy(row) };+ },+ };+}++function listCalls(cloud, kind) {+ return cloud.calls.filter((call) => {+ if (!call.path.startsWith("/api/notes/list")) return false;+ const query = new URLSearchParams(call.path.split("?")[1]);+ if (kind === "probe") return query.get("limit") === "1";+ if (kind === "delta") return query.has("since");+ return query.get("limit") !== "1" && !query.has("since");+ });+}++const updateCalls = (cloud) => cloud.calls.filter((call) => call.path === "/api/notes/update");++function preRevisionNote(db, cloudNote = INITIAL) {+ const note = db.upsertNoteFromCloud(cloudNote, null);+ db.db.prepare("UPDATE notes SET cloud_revision = NULL WHERE id = ?").run(note.id);+ return db.getNote(note.id);+}++async function client(t, db, cloud) {+ resetBrowserGlobals();+ installBrowserGlobals();+ enableSync();+ windowStub.electronAPI = createElectronApi(db, { cloud });+ await establishValidatedAuth();+ localStorageStub.setItem("lastSyncedAt.notes", "2026-06-01T00:00:00.000Z");+ const service = new SyncService();+ t.after(() => stopSyncTimers(service));+ return service;+}++function reopen(db) {+ const filename = db.db.name;+ db.db.close();+ db.db = new (require("better-sqlite3"))(filename);+}++function assertCleared(note, field) {+ assert.equal(note[field], field === "content" ? "" : null);+ assert.equal(note[`${field}_sync_operation`], null);+ assert.equal(note.cloud_revision, 8);+ assert.equal(note.sync_status, "synced");+ const untouched = field === "content" ? "enhanced_content" : "content";+ assert.equal(note[untouched], INITIAL[untouched]);+ assert.equal(note.transcript, INITIAL.transcript);+ assert.equal(note.enhancement_template_id, INITIAL.enhancement_template_id);+ assert.equal(note.enhancement_prompt, field === "content" ? INITIAL.enhancement_prompt : null);+ assert.equal(+ note.enhanced_at_content_hash,+ field === "content" ? INITIAL.enhanced_at_content_hash : null+ );+}++for (const field of ["content", "enhanced_content"]) {+ test(`${field}: a failed clear recovery retries on the next quiet sync pass`, async (t) => {+ const db = createDb(t);+ const secondDb = createDb(t);+ if (!db || !secondDb) return;+ const note = preRevisionNote(db);+ const secondNote = secondDb.upsertNoteFromCloud(INITIAL, null);+ db.updateNote(note.id, { clear_fields: [field] });+ const cloud = recoveryCloud({ failedSnapshots: 1 });+ const service = await client(t, db, cloud);+ const adoption = t.mock.method(windowStub.electronAPI, "setNoteCloudBase");++ await service.syncNotes();+ assert.equal(listCalls(cloud, "probe").length, 1);+ assert.equal(listCalls(cloud, "snapshot").length, 1);+ assert.equal(listCalls(cloud, "delta").length, 1);+ assert.equal(updateCalls(cloud).length, 0);+ assert.equal(db.getNote(note.id).cloud_revision, null);+ assert.equal(db.getNote(note.id).sync_status, "pending");+ assert.equal(db.getNote(note.id)[`${field}_sync_operation`], "clear");+ assert.equal(cloud.row()[field], INITIAL[field]);++ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 2, "failed recovery must be retried");+ assert.deepEqual(adoption.mock.calls[0].arguments, [note.id, INITIAL.updated_at, 7]);+ assert.equal(updateCalls(cloud).length, 1);+ const [patch] = updateCalls(cloud);+ assert.equal(patch.method, "PATCH");+ assert.equal(patch.body.base_revision, 7);+ assert.deepEqual(patch.body.field_updates, { [field]: "clear" });+ assert.equal(cloud.row()[`${field}_state`], "clear");+ assert.equal(cloud.row()[field], field === "content" ? "" : null);+ reopen(db);+ assertCleared(db.getNote(note.id), field);++ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 2);+ assert.equal(listCalls(cloud, "delta").length, 3);+ assert.equal(updateCalls(cloud).length, 1);+ const secondService = await client(t, secondDb, cloud);+ assert.equal(await secondService.pullNotes(false, true), true);+ reopen(secondDb);+ assertCleared(secondDb.getNote(secondNote.id), field);+ });+}++test("a clean pre-revision row retries a failed snapshot and receives a missed clear", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const note = preRevisionNote(db);+ const missing = preRevisionNote(db, OTHER);+ const cloud = recoveryCloud({+ notes: [{ ...INITIAL, revision: 8, content: "", content_state: "clear" }],+ failedSnapshots: 1,+ });+ const service = await client(t, db, cloud);++ await service.syncNotes();+ assert.equal(listCalls(cloud, "probe").length, 1);+ assert.equal(listCalls(cloud, "snapshot").length, 1);+ assert.equal(db.getNote(note.id).content, INITIAL.content);+ assert.equal(db.getNote(note.id).cloud_revision, null);+ assert.equal(db.getNote(note.id).sync_status, "synced");++ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 2, "failed backfill must be retried");+ reopen(db);+ assertCleared(db.getNote(note.id), "content");+ assert.equal(db.getNote(missing.id).cloud_revision, null);+ assert.equal(db.countNotesMissingRevision(), 1);+ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 2, "a completed snapshot stays bounded");+ assert.equal(listCalls(cloud, "delta").length, 3);+ assert.equal(updateCalls(cloud).length, 0);+});++test("repeated failures permit at most one snapshot per recovery path per ordinary pass", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const pending = preRevisionNote(db);+ const clean = preRevisionNote(db, OTHER);+ db.updateNote(pending.id, { clear_fields: ["content"] });+ const cloud = recoveryCloud({ notes: [INITIAL, OTHER], failedSnapshots: 6 });+ const service = await client(t, db, cloud);+ const requestPass = t.mock.method(service, "requestSyncAll", () => {});++ for (let pass = 1; pass <= 3; pass++) {+ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, pass * 2);+ assert.equal(listCalls(cloud, "delta").length, pass);+ assert.equal(updateCalls(cloud).length, 0);+ assert.equal(db.getNote(pending.id).sync_status, "pending");+ assert.equal(db.getNote(pending.id).content_sync_operation, "clear");+ assert.equal(db.getNote(pending.id).cloud_revision, null);+ assert.equal(db.getNote(clean.id).sync_status, "synced");+ assert.equal(db.getNote(clean.id).cloud_revision, null);+ assert.equal(cloud.row().content, INITIAL.content);+ assert.equal(requestPass.mock.callCount(), 0, "recovery must not schedule another pass");+ }+ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 7);+ assert.equal(listCalls(cloud, "probe").length, 1);+ assert.equal(updateCalls(cloud).length, 1);+ assertCleared(db.getNote(pending.id), "content");+ assert.equal(db.getNote(clean.id).cloud_revision, 7);+ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 7);+ assert.equal(requestPass.mock.callCount(), 0);+});++for (const empty of [false, true]) {+ test(`a completed ${empty ? "empty" : "unrelated-row"} snapshot does not repeatedly recover absent notes`, async (t) => {+ const db = createDb(t);+ if (!db) return;+ const pending = preRevisionNote(db);+ const clean = preRevisionNote(db, OTHER);+ db.updateNote(pending.id, { clear_fields: ["content"] });+ const unrelated = { ...INITIAL, id: "cloud-unrelated", client_note_id: "client-unrelated" };+ const cloud = recoveryCloud({ notes: empty ? [] : [unrelated], probeNote: unrelated });+ const service = await client(t, db, cloud);++ for (let pass = 0; pass < 3; pass++) await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 2, "one completed pull for each path");+ assert.equal(listCalls(cloud, "delta").length, 3);+ assert.equal(updateCalls(cloud).length, 0);+ assert.equal(db.getNote(pending.id).sync_status, "pending");+ assert.equal(db.getNote(pending.id).content_sync_operation, "clear");+ assert.equal(db.getNote(pending.id).cloud_revision, null);+ assert.equal(db.getNote(clean.id).cloud_revision, null);+ assert.equal(db.getNote(clean.id).content, INITIAL.content);+ });+}++test("a parked revision snapshot retries after the missing folder arrives", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const note = preRevisionNote(db);+ const cloud = recoveryCloud({+ notes: [+ { ...INITIAL, folder_id: "cloud-folder", revision: 8, content: "", content_state: "clear" },+ ],+ });+ const service = await client(t, db, cloud);++ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 1);+ assert.equal(db.getNote(note.id).cloud_revision, null);+ assert.equal(db.getNote(note.id).content, INITIAL.content);+ assert.equal(db.getNote(note.id).folder_id, note.folder_id);+ const folder = db.upsertFolderFromCloud(+ {+ id: "cloud-folder",+ client_folder_id: "client-folder",+ name: "Recovered folder",+ created_at: INITIAL.created_at,+ updated_at: INITIAL.updated_at,+ },+ db.getPrivateSpaceId()+ );++ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 2, "HTTP success alone is not completion");+ assertCleared(db.getNote(note.id), "content");+ assert.equal(db.getNote(note.id).folder_id, folder.id);+ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 2);+ assert.equal(updateCalls(cloud).length, 0);+});++test("a retry that finds a changed cloud base keeps the clear as an unresolved conflict", async (t) => {+ const db = createDb(t);+ if (!db) return;+ const note = preRevisionNote(db);+ db.updateNote(note.id, { clear_fields: ["content"] });+ const changed = {+ ...INITIAL,+ revision: 8,+ content: "Newer cloud text",+ updated_at: "2026-01-02T00:00:00.000Z",+ };+ const cloud = recoveryCloud({ notes: [changed], failedSnapshots: 1 });+ const service = await client(t, db, cloud);++ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 1);+ assert.deepEqual(readNoteConflicts(), {});+ await service.syncNotes();+ assert.equal(listCalls(cloud, "snapshot").length, 2);+ assert.deepEqual(readNoteConflicts()[INITIAL.client_note_id], changed);+ for (let pass = 0; pass < 2; pass++) await service.syncNotes();+ reopen(db);+ assert.equal(listCalls(cloud, "snapshot").length, 2);+ assert.equal(updateCalls(cloud).length, 0);+ assert.equal(db.getNote(note.id).content, "");+ assert.equal(db.getNote(note.id).content_sync_operation, "clear");+ assert.equal(db.getNote(note.id).sync_status, "pending");+ assert.equal(db.getNote(note.id).cloud_revision, null);+ assert.equal(cloud.row().content, changed.content);+ assert.deepEqual(readNoteConflicts()[INITIAL.client_note_id], changed);+});diff --git a/test/helpers/noteUndoIpc.test.js b/test/helpers/noteUndoIpc.test.jsindex f35eaf03b..a7175b14b 100644--- a/test/helpers/noteUndoIpc.test.js+++ b/test/helpers/noteUndoIpc.test.js@@ -72,6 +72,8 @@ function anything() {const RESTORED = { id: 7, title: "Before the assistant" };let undoResult;+let createAckResult;+let createAckArgs;const effects = { vectors: 0, mirrored: [] };test.before(() => {@@ -81,7 +83,13 @@ test.before(() => {const target = {notifyVectorChanges: () => effects.vectors++,_asyncMirrorWrite: (note) => effects.mirrored.push(note),- databaseManager: { undoNoteUpdate: () => undoResult },+ databaseManager: {+ undoNoteUpdate: () => undoResult,+ acknowledgeNoteCreate: (...args) => {+ createAckArgs = args;+ return createAckResult;+ },+ },};Ctor.prototype.setupHandlers.call(new Proxy(target, {@@ -118,3 +126,26 @@ test("a refused Undo writes nothing anywhere", async () => {assert.equal(effects.vectors, 0);assert.deepEqual(effects.mirrored, []);});++test("a reconciled create broadcasts the authoritative note and wakes the index", async () => {+ sent.length = 0;+ effects.vectors = 0;+ const cloudNote = { id: 7, content: "", enhanced_content: null };+ createAckResult = { success: true, outcome: "synced", note: cloudNote };+ const args = [7, { client_note_id: "client-7" }, "cloud-7", "timestamp", "owner", { cloudNote }];+ assert.equal(await handlers.get("db-acknowledge-note-create")(null, ...args), createAckResult);+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(createAckArgs, args);+ assert.deepEqual(sent, [["note-synced", cloudNote]]);+ assert.equal(effects.vectors, 1);+});++test("an unresolved create publishes no note state", async () => {+ sent.length = 0;+ effects.vectors = 0;+ createAckResult = { success: true, outcome: "awaiting-cloud" };+ await handlers.get("db-acknowledge-note-create")(null, 7, {}, "cloud-7");+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(sent, []);+ assert.equal(effects.vectors, 0);+});diff --git a/test/helpers/spacesDatabase.test.js b/test/helpers/spacesDatabase.test.jsindex 3e9ef6b45..81818d32c 100644--- a/test/helpers/spacesDatabase.test.js+++ b/test/helpers/spacesDatabase.test.js@@ -968,7 +968,7 @@ test("acknowledgeNoteCreate settles only the exact create snapshot", (t) => {"migration-cloud-id","2026-07-29T11:30:00.000Z",null,- false+ { settleIfUnchanged: false });const afterPartial = db.getNote(partial.id);assert.equal(partialAck.outcome, "pending");@@ -1753,3 +1753,17 @@ test("upsertSpaceFromCloud never adopts by team for multi-team spaces", (t) => {assert.notEqual(fresh.client_space_id, "legacy-client-id");assert.equal(fresh.sync_status, "pending", "a genuinely new space still backfills");});++test("a deferred create receipt retains team retraction while personal backup is off", (t) => {+ const db = createDb(t);+ if (!db) return;+ const team = createTestTeamSpace(db, { name: "Deferred move" }).space;+ const note = db.saveNote("Draft", "team work", "personal", null, null, null, team.id).note;+ db.updateNote(note.id, { space_id: db.getPrivateSpaceId(), folder_id: null });+ const ack = db.acknowledgeNoteCreate(note.id, note, "team-cloud", null, null, {+ requiresReconciliation: true,+ });+ assert.equal(ack.outcome, "awaiting-cloud");+ assert.equal(db.getNote(note.id).left_team, 1);+ assert.ok(db.getPendingNotes("team").some((candidate) => candidate.id === note.id));+});diff --git a/test/helpers/syncScenarios.test.js b/test/helpers/syncScenarios.test.jsindex d3a8397c5..01c3d660f 100644--- a/test/helpers/syncScenarios.test.js+++ b/test/helpers/syncScenarios.test.js@@ -299,7 +299,11 @@ test("S2 two devices: an older empty shell never destroys the transcript and the.slice(mark).filter((c) => c.method === "PATCH" && c.path === "/api/notes/update");assert.equal(patches.length, 1, "A must attempt exactly one push for its stale shell");- assert.equal(patches[0].body.content, "", "A really did offer an empty body");+ assert.equal(+ patches[0].body.content,+ undefined,+ "A's empty body is unconfirmed, so it is left out rather than offered as a clear"+ );assert.equal(patches[0].body.updated_at,F_TITLE,diff --git a/test/helpers/syncServiceNotes.test.js b/test/helpers/syncServiceNotes.test.jsindex 3a80fa862..879ba3dda 100644--- a/test/helpers/syncServiceNotes.test.js+++ b/test/helpers/syncServiceNotes.test.js@@ -600,12 +600,34 @@ test("a note pull failure is contained: the pass finishes and later stages stillconst errors = silenceConsoleErrors(t);const note = db.saveNote("Pending note", "body", "personal").note;+ // Model an older API's incomplete receipt; the normal fake now returns+ // authoritative text, which can settle without waiting for a list request.+ const retries = [];+ t.mock.method(service, "requestSyncAll", (reason) => retries.push(reason));+ const request = windowStub.electronAPI.cloudApiRequest;+ t.mock.method(windowStub.electronAPI, "cloudApiRequest", async (options) => {+ const result = await request(options);+ if (options.path === "/api/notes/batch-create" && result.success) {+ result.data.created = result.data.created.map(({ id, client_note_id, updated_at }) => ({+ id,+ client_note_id,+ updated_at,+ }));+ }+ return result;+ });cloud.failWith("/api/notes/list", { status: 500, error: "list exploded" });await service.syncAll(true);- assert.equal(db.getNote(note.id).sync_status, "synced", "the push before the pull still lands");+ assert.equal(cloud.note(note.client_note_id).content, "body", "the push before the pull lands");+ assert.equal(+ db.getNote(note.id).sync_status,+ "pending",+ "an incomplete receipt still needs an authoritative row before settling"+ );assert.equal(cloud.logFor("/api/transcriptions/list").length, 1, "later stages still run");assert.equal(cloud.logFor("/api/snippets/list").length, 1);+ assert.ok(retries.includes("retry"), "the incomplete create asks for a recovery pass");assert.equal(localStorageStub.getItem("lastSyncedAt.notes"),null,diff --git a/test/lib/noteEditorPendingSave.test.js b/test/lib/noteEditorPendingSave.test.jsindex 157518b20..43ad6c164 100644--- a/test/lib/noteEditorPendingSave.test.js+++ b/test/lib/noteEditorPendingSave.test.js@@ -97,7 +97,7 @@ test("rejects foreign and stale source-note mutations without changing the drafttest("collects document and enhanced writes under their captured owner", async () => {const { collectPendingNoteWrites } = await load();- const documentA = { noteId: 1, title: "A title", content: "A body" };+ const documentA = { noteId: 1, title: "A title", content: "A body", contentEdited: true };const enhancedA = { noteId: 1, enhancedContent: "A enhancement" };assert.deepEqual(collectPendingNoteWrites(null, null), []);@@ -130,7 +130,7 @@ test("keeps document and enhanced writes with different owners separate", asyncassert.deepEqual(collectPendingNoteWrites(- { noteId: 1, title: "A title", content: "0" },+ { noteId: 1, title: "A title", content: "0", contentEdited: true },{ noteId: 2, enhancedContent: null }),[@@ -140,12 +140,120 @@ test("keeps document and enhanced writes with different owners separate", async},{noteId: 2,- updates: { enhanced_content: null },+ updates: { enhanced_content: null, clear_fields: ["enhanced_content"] },},]);});+test("a save payload carries a clear only for emptied notes or a blank summary", async () => {+ const { documentSaveUpdates, enhancedSaveUpdates } = await load();++ assert.deepEqual(+ documentSaveUpdates({+ noteId: 1,+ title: "A title",+ content: "",+ contentEdited: true,+ clearContent: true,+ }),+ { title: "A title", content: "", clear_fields: ["content"] }+ );+ // A blank body alone is untrusted (a title edit, a load that came back empty).+ assert.deepEqual(+ documentSaveUpdates({+ noteId: 1,+ title: "A title",+ content: "",+ contentEdited: true,+ clearContent: false,+ }),+ { title: "A title", content: "" }+ );+ for (const blank of [null, "", " \n"]) {+ assert.deepEqual(enhancedSaveUpdates({ noteId: 1, enhancedContent: blank }), {+ enhanced_content: blank,+ clear_fields: ["enhanced_content"],+ });+ }+ assert.deepEqual(enhancedSaveUpdates({ noteId: 1, enhancedContent: "A summary" }), {+ enhanced_content: "A summary",+ });+});++// The draft's notes may predate a pull or ack the store applied while the+// save waited; writing them back would turn a clear into an edit.+test("a save with only a title edit writes only the title", async () => {+ const { documentSaveUpdates, collectPendingNoteWrites, planNoteTransition } = await load();+ const titleOnly = {+ noteId: 1,+ title: "Retitled",+ content: "Stale notes",+ contentEdited: false,+ clearContent: false,+ };+ assert.deepEqual(documentSaveUpdates(titleOnly), { title: "Retitled" });+ assert.deepEqual(collectPendingNoteWrites(titleOnly, { noteId: 1, enhancedContent: "S" }), [+ { noteId: 1, updates: { title: "Retitled", enhanced_content: "S" } },+ ]);+ assert.deepEqual(planNoteTransition(null, titleOnly, null).writes, [+ { noteId: 1, updates: { title: "Retitled" } },+ ]);+});++test("pending clears flush with the writes they belong to", async () => {+ const { collectPendingNoteWrites } = await load();+ const cleared = {+ noteId: 1,+ title: "A title",+ content: "",+ contentEdited: true,+ clearContent: true,+ };+ const kept = {+ noteId: 1,+ title: "A title",+ content: "A body",+ contentEdited: true,+ clearContent: false,+ };++ assert.deepEqual(collectPendingNoteWrites(cleared, null), [+ { noteId: 1, updates: { title: "A title", content: "", clear_fields: ["content"] } },+ ]);+ assert.deepEqual(collectPendingNoteWrites(null, { noteId: 1, enhancedContent: "" }), [+ { noteId: 1, updates: { enhanced_content: "", clear_fields: ["enhanced_content"] } },+ ]);+ assert.deepEqual(collectPendingNoteWrites(cleared, { noteId: 1, enhancedContent: "" }), [+ {+ noteId: 1,+ updates: {+ title: "A title",+ content: "",+ enhanced_content: "",+ clear_fields: ["content", "enhanced_content"],+ },+ },+ ]);+ assert.deepEqual(collectPendingNoteWrites(cleared, { noteId: 1, enhancedContent: "Summary" }), [+ {+ noteId: 1,+ updates: {+ title: "A title",+ content: "",+ enhanced_content: "Summary",+ clear_fields: ["content"],+ },+ },+ ]);+ assert.deepEqual(collectPendingNoteWrites(kept, { noteId: 1, enhancedContent: "Summary" }), [+ {+ noteId: 1,+ updates: { title: "A title", content: "A body", enhanced_content: "Summary" },+ },+ ]);+});+test("models B's editor event before the A-to-B parent transition, then returns to A", async () => {const { applyNoteDraftMutation, planNoteTransition } = await load();const noteA = note(1, "A body", "A enhancement");@@ -208,6 +316,7 @@ test("edit A then immediately switch to B keeps empty, zero, and raw content ownnoteId: editedA.noteId,title: editedA.title,content: editedA.content,+ contentEdited: true,};assert.equal(applyNoteDraftMutation(editedA, {@@ -271,7 +380,7 @@ test("an overview transition flushes captured owners and clears the draft", asynconst transition = planNoteTransition(null,- { noteId: 1, title: "A title", content: "A body" },+ { noteId: 1, title: "A title", content: "A body", contentEdited: true },{ noteId: 2, enhancedContent: "B enhancement" });diff --git a/test/services/assistantNoteUndo.test.js b/test/services/assistantNoteUndo.test.jsindex d6cbc0cc5..a3dacc331 100644--- a/test/services/assistantNoteUndo.test.js+++ b/test/services/assistantNoteUndo.test.js@@ -166,10 +166,10 @@ test("safe assistant edits and atomic Undo", async (t) => {assert.equal(result.success, true);assert.deepEqual(result.data.updatedFields, [field]);const key = field === "summary" ? "enhanced_content" : field;- assert.equal(database.getNote(note.id)[key], "");+ assert.equal(database.getNote(note.id)[key] ?? "", "");database.db.close();database.db = new (require("better-sqlite3"))(path.join(directory, "transcriptions.db"));- assert.equal(database.getNote(note.id)[key], "");+ assert.equal(database.getNote(note.id)[key] ?? "", "");assert.equal(database.undoNoteUpdate(tokenFor(note.id)).success, true);const restored = database.getNote(note.id);for (const key of [@@ -184,6 +184,15 @@ test("safe assistant edits and atomic Undo", async (t) => {assert.equal(tokenFor(note.id), undefined);});+ await t.test("Undo of a first summary is a clear that syncs", async () => {+ const note = database.saveNote("Untouched", "Private notes", "meeting").note;+ await edit(database.getNote(note.id), { summary: "Written by the assistant" });+ assert.equal(database.undoNoteUpdate(tokenFor(note.id)).success, true);+ const restored = database.getNote(note.id);+ assert.equal(restored.enhanced_content ?? "", "");+ assert.equal(restored.enhanced_content_sync_operation, "clear");+ });+await t.test("partial section removal; edits in one turn share an Undo, a later turn's stands alone",async () => {@@ -379,7 +388,9 @@ test("safe assistant edits and atomic Undo", async (t) => {"2026-10-09","owner-one");+ // The create carried the edited text, so it settles in one request.assert.equal(ack.outcome, "synced");+ assert.equal(database.getNote(note.id).cloud_id, `cloud-${note.id}`);assert.equal(tokenFor(note.id), token);assert.equal(database.undoNoteUpdate(token).success, true);assert.equal(database.getNote(note.id).title, note.title);@@ -452,17 +463,20 @@ test("safe assistant edits and atomic Undo", async (t) => {assert.equal(database.getNote(note.id).transcript, note.transcript);});- await t.test("clearing a never-written summary writes nothing and keeps the last Undo", async () => {- const note = fresh();- database.updateNote(note.id, { enhanced_content: null });- await edit(note, { title: "Renamed first" }, "turn-1");- const token = tokenFor(note.id);- database.updateNote(note.id, { sync_status: "synced" });- assert.equal((await edit(note, { clear_fields: ["summary"] }, "turn-2")).success, true);- assert.equal(database.getNote(note.id).enhanced_content, null);- assert.equal(database.getNote(note.id).sync_status, "synced");- assert.equal(tokenFor(note.id), token);- });+ await t.test(+ "clearing a never-written summary writes nothing and keeps the last Undo",+ async () => {+ const note = fresh();+ database.updateNote(note.id, { enhanced_content: null });+ await edit(note, { title: "Renamed first" }, "turn-1");+ const token = tokenFor(note.id);+ database.updateNote(note.id, { sync_status: "synced" });+ assert.equal((await edit(note, { clear_fields: ["summary"] }, "turn-2")).success, true);+ assert.equal(database.getNote(note.id).enhanced_content, null);+ assert.equal(database.getNote(note.id).sync_status, "synced");+ assert.equal(tokenFor(note.id), token);+ }+ );await t.test("a toast's discard retires only its own recovery", async () => {const note = fresh();diff --git a/test/services/noteCreateAck.test.js b/test/services/noteCreateAck.test.jsindex 17291928b..42f168c60 100644--- a/test/services/noteCreateAck.test.js+++ b/test/services/noteCreateAck.test.js@@ -16,6 +16,7 @@ test("resolveCloudNoteCreate deletes a proven orphan create", async () => {client_note_id: note.client_note_id,updated_at: "2026-07-29T10:00:00.000Z",user_id: "owner-42",+ row_created: true,},{acknowledge: async (...args) => {@@ -34,7 +35,13 @@ test("resolveCloudNoteCreate deletes a proven orphan create", async () => {"cloud-note-42","2026-07-29T10:00:00.000Z","owner-42",- true,+ {+ settleIfUnchanged: true,+ cloudRevision: null,+ writeRejected: false,+ cloudNote: undefined,+ requiresReconciliation: true,+ },]);assert.deepEqual(calls[1], ["delete", "cloud-note-42"]);});@@ -75,7 +82,7 @@ test("resolveCloudNoteCreate leaves newer local work pending without cleanup", alet deleted = false;const result = await resolveCloudNoteCreate(note,- { id: "cloud-note-42", client_note_id: note.client_note_id },+ { id: "cloud-note-42", client_note_id: note.client_note_id, row_created: true },{acknowledge: async () => ({ success: true, outcome: "pending" }),deleteCloud: async () => {@@ -94,7 +101,7 @@ test("resolveCloudNoteCreate treats orphan cleanup as best-effort", async () =>let reported = null;const result = await resolveCloudNoteCreate(note,- { id: "cloud-note-42", client_note_id: note.client_note_id },+ { id: "cloud-note-42", client_note_id: note.client_note_id, row_created: true },{acknowledge: async () => ({ success: true, outcome: "orphaned" }),deleteCloud: async () => {@@ -123,6 +130,7 @@ test("resolveCloudNoteCreateBatch routes migration results by snapshot identity"id: "cloud-note-84",client_note_id: otherNote.client_note_id,updated_at: "2026-07-29T14:00:00.000Z",+ row_created: true,},],{@@ -136,7 +144,20 @@ test("resolveCloudNoteCreateBatch routes migration results by snapshot identity");assert.deepEqual(acknowledgements, [- [otherNote.id, otherNote, "cloud-note-84", "2026-07-29T14:00:00.000Z", null, false],+ [+ otherNote.id,+ otherNote,+ "cloud-note-84",+ "2026-07-29T14:00:00.000Z",+ null,+ {+ settleIfUnchanged: false,+ cloudRevision: null,+ writeRejected: false,+ cloudNote: undefined,+ requiresReconciliation: true,+ },+ ],]);assert.deepEqual(deleted, ["cloud-note-84"]);assert.deepEqual(results, ["orphan-cleaned"]);@@ -210,7 +231,7 @@ test("an account reset cleans an invalidated migration without touching SQLite",accountGeneration += 1;let acknowledged = false;const deleted = [];- const cloud = { id: "old-account-cloud", client_note_id: note.client_note_id };+ const cloud = { id: "old-account-cloud", client_note_id: note.client_note_id, row_created: true };const results = await resolveCloudNoteCreateBatch([note],[cloud],@@ -231,3 +252,59 @@ test("an account reset cleans an invalidated migration without touching SQLite",assert.deepEqual(deleted, ["old-account-cloud"]);assert.deepEqual(results, ["orphan-cleaned"]);});++for (const invalidated of [false, true]) {+ test(`a rejected create never cleans an existing row (invalidated=${invalidated})`, async () => {+ const { resolveCloudNoteCreate } = await import("../../src/services/noteCreateAck.ts");+ let acknowledged = false;+ const outcome = await resolveCloudNoteCreate(+ note,+ {+ id: "protected",+ client_note_id: note.client_note_id,+ revision: 12,+ write_applied: false,+ },+ {+ acknowledge: async (...args) => {+ acknowledged = true;+ // No fresh base or revision: the server never wrote this request.+ assert.deepEqual(args[5], {+ settleIfUnchanged: false,+ cloudRevision: null,+ writeRejected: true,+ });+ return { success: true, outcome: "orphaned" };+ },+ deleteCloud: () => assert.fail("Rejected create is not owned by this request"),+ },+ { requestStillCurrent: () => !invalidated }+ );+ assert.equal(outcome, "write-rejected");+ assert.equal(acknowledged, !invalidated);+ });+}++for (const blocked of [{ deleted_at: "2026-10-09T10:00:00Z" }, { access_removed: true }]) {+ test(`create receipt cannot adopt an unavailable row: ${Object.keys(blocked)[0]}`, async () => {+ const { resolveCloudNoteCreate } = await import("../../src/services/noteCreateAck.ts");+ const note = { id: 42, client_note_id: "unavailable-note" };+ assert.equal(+ await resolveCloudNoteCreate(+ note,+ {+ id: "cloud-unavailable",+ client_note_id: note.client_note_id,+ content: "Text",+ enhanced_content: null,+ ...blocked,+ },+ {+ acknowledge: () => assert.fail("Unavailable row cannot be adopted"),+ deleteCloud: () => assert.fail("Unavailable row cannot be deleted"),+ }+ ),+ "unresolved"+ );+ });+}diff --git a/test/services/noteEditPersistence.test.js b/test/services/noteEditPersistence.test.jsindex eb936c9dc..a173e3b0a 100644--- a/test/services/noteEditPersistence.test.js+++ b/test/services/noteEditPersistence.test.js@@ -103,7 +103,7 @@ test("note edits preserve separate stored fields, reopen correctly, and report f(await updateNoteTool.execute({ id: note.id, clear_fields: ["summary"] })).success,true);- assert.equal(database.getNote(note.id).enhanced_content, "");+ assert.equal(database.getNote(note.id).enhanced_content, null);assert.equal(database.getNote(note.id).content, CONTENT);assert.equal((await updateNoteTool.execute({ id: note.id, clear_fields: ["content"] })).success,diff --git a/test/stores/actionProcessingNoteOutput.test.js b/test/stores/actionProcessingNoteOutput.test.jsindex 4ba2b8b6c..43802f915 100644--- a/test/stores/actionProcessingNoteOutput.test.js+++ b/test/stores/actionProcessingNoteOutput.test.js@@ -359,6 +359,7 @@ test("a run hands Undo the summary fields it overwrote, and the title when it reLABELS);await waitFor(() => updates.length === 1, "the rewrite to be written");+ // A summary to put back is a plain set, never a clear.assert.deepEqual(store.consumeAppliedEvents(), [{ noteId: 15, action: shorten, previous: summaryFields },]);@@ -378,9 +379,9 @@ test("a run hands Undo the summary fields it overwrote, and the title when it reassert.deepEqual(previous, { ...summaryFields, title: STORED_NOTE.title });});-test("Undo of a first summary clears it with an empty string, which sync can't ignore", async (t) => {- // The API keeps its copy when a push sends null (COALESCE), so a null here- // would bring the undone summary back on the next pull.+test("Undo of a first summary is an explicit clear, which syncs to every device", async (t) => {+ // A blank without clear_fields stays local, so the undone summary would come+ // back on the next pull and stay on teammates' devices.const { store, updates } = await loadStore(t, {title: "Untitled Note",enhanced_content: null,@@ -398,7 +399,8 @@ test("Undo of a first summary clears it with an empty string, which sync can't i);await waitFor(() => updates.length === 1, "the first summary to be written");const [{ previous }] = store.consumeAppliedEvents();- assert.equal(previous.enhanced_content, "");+ assert.equal(previous.enhanced_content, null);+ assert.deepEqual(previous.clear_fields, ["enhanced_content"]);});test("a write the database refused offers no Undo and reports the failure", async (t) => {