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
fix(notes): preserve assistant edit fields and add safe Undo (#2602)
Joshua6b23868cb7ff
diff --git a/CLAUDE.md b/CLAUDE.mdindex dd0461254..6795d4b9f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -66,6 +66,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- Linux COSMIC: paste reads the focused app from cosmic-comp's `zcosmic_toplevel_info_v1` (`cosmicToplevel.js`, a minimal Wayland wire client, bound at version 1, which still sends app_id and state), never from xdotool, whose XWayland answer goes stale while a native Wayland window has focus. A known terminal is pasted through wtype (Ctrl+Shift+V; Shift+Insert for Konsole); everything else keeps uinput Shift+Insert, since COSMIC gives no PID to spot Electron apps hosting TUIs. Short terminal names (`st`) match whole words only, or every `com.system76.*` app id would read as a terminal- Linux: before any paste or selection-copy chord, `linux-fast-paste --capabilities --await-modifier-release <ms>` waits for physically held modifiers to be released (XKB state on X11, `EVIOCGKEY` on Wayland; `unknown` without `/dev/input` access pastes as before). A chord injected into held keys arrives as a different shortcut, and a virtual device cannot release another device's key (#2113). Still held after 1.5 s → not pasted, `reason: "modifiers-held"`, and the renderer shows the dictation-error pill with the transcript on the clipboard; a selection edit blocked the same way reports `code: "modifiers_held"` and gets the same pill (the assistant caret paste reports the same code, for logs only). `ydotoold`'s virtual keyboard is ignored, since an interrupted chord can leave its modifier down, and an unreadable key state is logged once per session. The wait runs before `pasteLinux` detects the target window, and a selection copy that had to wait looks the target up again, since focus can move while a key is held: a fresh capture then runs the command on its own (`focus_moved`), and a revalidated session declines as `target_changed`. Retry on a modifiers-held pill pastes the kept transcript again rather than recording again (the macOS/Windows push force-stop pill keeps its record-again Retry, since neither platform waits for held keys), ignores clicks while its paste is pending, and never dismisses a newer pill. `useAudioRecording` keeps the pill in processing until the paste attempt settles (the audio manager settles before the paste starts), but never reports that to main, which drops dictation hotkeys while processing; a paste held back after the next dictation started leaves the transcript on the clipboard without a pill. The helper measures its wait on `CLOCK_MONOTONIC`, since the JS watchdog kills it at timeout + 1 s- **database.js**: SQLite operations for transcription history+- **noteUndo.js**: Undo for assistant `update_note` edits. The tool passes `{ undoable, expected, turn }` to `db-update-note`; inside one transaction main refuses the edit if a guarded field changed since the tool read the note, writes it, and journals the previous values in `assistant_note_undo` (one row per note, bound to the account and kept 10 minutes). An `AFTER UPDATE` trigger retires the row when any guarded field changes again (manual save, sync pull, delete, identity or folder change), treating `''` and NULL as equal because a pull stores an empty field as NULL; sync acknowledgements don't retire it. Edits of one note in the same chat turn (`turn` = the assistant message id) share one Undo; `update_note` runs one note's edits in turn, since the AI SDK runs a step's tool calls concurrently. `AssistantNoteUndoListener` (control panel and dictation window) offers each edit once, in the first focused window (`db-claim-note-undo`); typing in the open note retires it (`discardNoteUndo`). The trigger is recreated and a journal of another shape is dropped at launch; if setup fails, edits save without Undo- **debugLogger.js**: Debug logging system with file output- **providerHttpErrors.js**: Pure ESM classifier for BYOK provider failures (transcription and AI models), shared by main (require(esm)) and renderer. `providerHttpError({ provider, status, body, headers, model, surface, selfHosted })` builds an Error carrying `code` (`PROVIDER_AUTH_FAILED`, `PROVIDER_QUOTA_EXHAUSTED`, …), `messageKey` (`providerErrors.*`), `messageParams`, `settingsTarget` (`speechToText`/`llms`, fixable errors only) and redacted `technicalDetails`; `asProviderError` classifies AI SDK, timeout and network errors and leaves already-keyed errors alone. Raw provider bodies never reach UI text. Rendered by `src/utils/describeProviderError.ts`- **devServerManager.js**: Vite dev server integrationdiff --git a/preload.js b/preload.jsindex dd58e779c..c475970cc 100644--- a/preload.js+++ b/preload.js@@ -229,7 +229,11 @@ contextBridge.exposeInMainWorld("electronAPI", {getNotes: (noteType, limit, folderId, spaceId) =>ipcRenderer.invoke("db-get-notes", noteType, limit, folderId, spaceId),getSpaceNotes: (spaceId, limit) => ipcRenderer.invoke("db-get-space-notes", spaceId, limit),- updateNote: (id, updates) => ipcRenderer.invoke("db-update-note", id, updates),+ updateNote: (id, updates, options) => ipcRenderer.invoke("db-update-note", id, updates, options),+ getNoteUndos: () => ipcRenderer.invoke("db-get-note-undos"),+ claimNoteUndo: (token) => ipcRenderer.invoke("db-claim-note-undo", token),+ undoNoteUpdate: (token) => ipcRenderer.invoke("db-undo-note-update", token),+ discardNoteUndo: (id, token) => ipcRenderer.invoke("db-discard-note-undo", id, token),deleteNote: (id) => ipcRenderer.invoke("db-delete-note", id),exportNote: (noteId, format) => ipcRenderer.invoke("export-note", noteId, format),exportTranscript: (noteId, format) => ipcRenderer.invoke("export-transcript", noteId, format),diff --git a/src/App.jsx b/src/App.jsxindex 27e744f34..5f0067e71 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -26,6 +26,7 @@ import { VoiceModePanelCore } from "./components/dictation/VoiceModePanelCore";import { PillTooltip } from "./components/dictation/PillTooltip";import { PillCommandMenu } from "./components/dictation/PillCommandMenu";import { LiquidCancelButton } from "./components/dictation/LiquidCancelButton";+import AssistantNoteUndoListener from "./components/notes/AssistantNoteUndoListener";import { createMainWindowResizeCoordinator } from "./utils/mainWindowResizeCoordinator";import {ASSISTANT_FOOTER_TRANSITION_TIMING,@@ -847,6 +848,8 @@ export default function App() {/>)}</VoiceModePanelCore>+ {/* The assistant panel edits notes here; its Undo shows once the panel has focus. */}+ <AssistantNoteUndoListener /></div>);}diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 35453ca7c..76c005bef 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -85,6 +85,7 @@ import { applyChineseScript, resolveChineseScriptTarget } from "../utils/chineseimport { getAgentName } from "../utils/agentName";import HistoryView from "./HistoryView";import BackgroundActionToastListener from "./notes/BackgroundActionToastListener";+import AssistantNoteUndoListener from "./notes/AssistantNoteUndoListener";import { providerErrorToastProps } from "../utils/describeProviderError";import SpaceSyncToastListener from "./notes/SpaceSyncToastListener";import { syncService } from "../services/SyncService.js";@@ -1307,6 +1308,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro</main></div><BackgroundActionToastListener />+ <AssistantNoteUndoListener /><SpaceSyncToastListener /></div>);diff --git a/src/components/notes/AssistantNoteUndoListener.tsx b/src/components/notes/AssistantNoteUndoListener.tsxnew file mode 100644index 000000000..93dbe28d8--- /dev/null+++ b/src/components/notes/AssistantNoteUndoListener.tsx@@ -0,0 +1,130 @@+import { useEffect, useRef } from "react";+import { useTranslation } from "react-i18next";+import { useToast } from "../ui/useToast";+import { ToastActionButton } from "../ui/Toast";+import { syncService } from "../../services/SyncService";+import logger from "../../utils/logger";++// Recovery belongs to the committed note, so cancellation and navigation cannot+// lose it along with a discarded chat tool result. An edit made while no window+// had focus is offered once one does.+export default function AssistantNoteUndoListener() {+ const { t } = useTranslation();+ const { toast, dismiss } = useToast();+ const visible = useRef(new Map<string, string>());+ const dismissRef = useRef(dismiss);+ dismissRef.current = dismiss;++ useEffect(() => {+ let active = true;+ let request = 0;+ let scope = 0;+ const clearVisible = () => {+ for (const id of visible.current.values()) dismissRef.current(id);+ visible.current.clear();+ };+ const refresh = async () => {+ const generation = ++request;+ const startScope = scope;+ const focused = () => document.hasFocus() && document.visibilityState !== "hidden";+ // An unfocused window still drops toasts whose recovery is gone (undone+ // or replaced in another window); only a focused one offers new ones.+ if (!focused() && !visible.current.size) return;+ try {+ const edits = await window.electronAPI.getNoteUndos();+ if (!active || generation !== request) return;+ const tokens = new Set(edits.map((edit) => edit.token));+ for (const [token, id] of visible.current) {+ if (tokens.has(token)) continue;+ dismissRef.current(id);+ visible.current.delete(token);+ }+ if (!focused()) return;+ for (const edit of edits) {+ if (visible.current.has(edit.token)) continue;+ // Main hands each edit to one window once, so it is not offered again+ // in another window or after a reload.+ if (!(await window.electronAPI.claimNoteUndo(edit.token))) continue;+ if (!active || scope !== startScope) return;+ let busy = false;+ const id = toast({+ title: t("notes.assistantUndo.applied", {+ title: edit.title || t("notes.list.untitled"),+ }),+ duration: 6000,+ // Only the close button retires the recovery; a toast that timed+ // out leaves it for the editor's discard or the TTL.+ onClose: () => {+ void window.electronAPI.discardNoteUndo(edit.noteId, edit.token);+ visible.current.delete(edit.token);+ },+ action: (+ <ToastActionButton+ onClick={async () => {+ if (busy) return;+ busy = true;+ try {+ const result = await window.electronAPI.undoNoteUpdate(edit.token);+ if (!active) return;+ // A refusal means the recovery is gone; a failed save keeps+ // it, so the toast stays for another try. A gone recovery+ // keeps the button disabled: the dismissed toast is still+ // clickable while it animates out.+ const gone = result.success || result.error === "note_changed";+ busy = gone;+ if (gone) {+ dismissRef.current(id);+ visible.current.delete(edit.token);+ }+ if (result.success) {+ syncService.debouncedPush("note", edit.noteId);+ } else {+ toast({+ description: t(+ gone ? "notes.assistantUndo.changed" : "notes.assistantUndo.failed"+ ),+ variant: "destructive",+ });+ }+ } catch {+ busy = false;+ if (active)+ toast({+ description: t("notes.assistantUndo.failed"),+ variant: "destructive",+ });+ }+ }}+ >+ {t("app.toasts.undo")}+ </ToastActionButton>+ ),+ });+ visible.current.set(edit.token, id);+ }+ } catch (error) {+ logger.warn("Failed to load note Undo", { error: String(error) }, "notes");+ }+ };+ const resetScope = () => {+ request++;+ scope++;+ clearVisible();+ void refresh();+ };+ void refresh();+ window.addEventListener("focus", refresh);+ const removeNoteListener = window.electronAPI.onNoteUpdated?.(refresh);+ const removeScopeListener = window.electronAPI.onActiveAccountScopeChanged?.(resetScope);+ return () => {+ active = false;+ request++;+ window.removeEventListener("focus", refresh);+ removeNoteListener?.();+ removeScopeListener?.();+ clearVisible();+ };+ }, [toast, t]);++ return null;+}diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 6bc08c1ca..e44233cfb 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -407,6 +407,7 @@ 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);@@ -434,6 +435,7 @@ export default function PersonalNotesView({}, []);const scheduleEnhancedSave = useCallback((snapshot: NoteEditorDraft) => {+ void window.electronAPI.discardNoteUndo?.(snapshot.noteId);const current = pendingEnhancedRef.current;if (current) clearTimeout(current.timer);diff --git a/src/components/ui/RichTextEditor.tsx b/src/components/ui/RichTextEditor.tsxindex 6951929bf..d1da713d1 100644--- a/src/components/ui/RichTextEditor.tsx+++ b/src/components/ui/RichTextEditor.tsx@@ -45,8 +45,11 @@ export function RichTextEditor({],content: value,editable: !disabled,- onUpdate: ({ editor: ed }) => {- if (suppressUpdateRef.current) return;+ onUpdate: ({ editor: ed, transaction }) => {+ // A plugin's appended change (the trailing paragraph after a list, added+ // on the first click) is not an edit; saving it would also discard the+ // assistant's Undo for the note.+ if (suppressUpdateRef.current || !transaction.docChanged) return;const md = (ed.storage as any).markdown.getMarkdown() as string;internalValueRef.current = md;diff --git a/src/config/prompts.ts b/src/config/prompts.tsindex 0390d4d47..0458df95c 100644--- a/src/config/prompts.ts+++ b/src/config/prompts.ts@@ -39,7 +39,7 @@ const TOOL_INSTRUCTIONS: Record<string, string> = {create_note:"Use create_note when the user asks you to create, write, or draft a new note. Whenever the note will go into a folder, call list_folders first and reuse an existing folder whose name is a reasonable fit for the note's topic (e.g. a new story belongs in an existing 'Stories' folder) — do this even when the user didn't name a folder but the content clearly fits one. Only pass a new folder name when nothing existing fits. Be tolerant of case, plurals, and typos.",update_note:- "Use update_note to modify an existing note's title, personal content, AI summary, or folder. Read get_note before editing, then change only the field containing the requested text: content for personal notes, summary for the AI Summary. For a section removal, remove that section from its original field and preserve all unrelated text exactly. Never copy the combined context, field labels, or transcript into content or summary. Only claim the edit was saved after update_note succeeds. If the current note's ID is provided in the context, use it directly. Otherwise, use search_notes first to find the note ID. When moving to a folder, call list_folders first and reuse an existing folder whose name fits the note's topic; only create a new folder when nothing existing fits.",+ "Use update_note to modify an existing note's title, personal content, AI summary, or folder. Read get_note before editing, then change only the field containing the requested text: content for personal notes, summary for the AI Summary. Only empty an entire field when the user asks to clear it or to remove text that is all of it: use clear_fields with content or summary; blank replacement fields are ignored. For a section removal, remove that section from its original field and preserve all unrelated text exactly. Never copy the combined context, field labels, or transcript into content or summary. Only claim the edit was saved after update_note succeeds. If the current note's ID is provided in the context, use it directly. Otherwise, use search_notes first to find the note ID. When moving to a folder, call list_folders first and reuse an existing folder whose name fits the note's topic; only create a new folder when nothing existing fits.",list_folders:"Use list_folders before create_note or update_note whenever a note is going into a folder, so you can reuse an existing folder whose name fits the note's topic instead of creating a near-duplicate.",web_search:diff --git a/src/helpers/database.js b/src/helpers/database.jsindex bbf5f8166..37aba8de8 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -2,6 +2,7 @@ const Database = require("better-sqlite3");const path = require("path");const fs = require("fs");const { randomUUID } = require("crypto");+const noteUndo = require("./noteUndo");const debugLogger = require("./debugLogger");const { buildNoteSearchQuery } = require("./noteSearch");const { normalizeStoredSpeakerCount } = require("./speakerCount");@@ -1497,6 +1498,14 @@ class DatabaseManager {)`);this._initVectorChangeJournal();+ try {+ noteUndo.initializeNoteUndo(this.db);+ this.noteUndoReady = true;+ } catch (error) {+ // Undo is a convenience: it must never keep the notes database from+ // opening. Without it, assistant edits save as plain updates.+ debugLogger.error("Assistant note Undo unavailable", { error: error.message }, "database");+ }return true;} catch (error) {@@ -3278,7 +3287,27 @@ class DatabaseManager {}}- updateNote(id, updates) {+ getNoteUndos() {+ return this.noteUndoReady ? noteUndo.getNoteUndos(this) : [];+ }++ claimNoteUndo(token) {+ return this.noteUndoReady && noteUndo.claimNoteUndo(this, token);+ }++ undoNoteUpdate(token) {+ if (!this.noteUndoReady) return { success: false, error: "note_changed" };+ return noteUndo.undoNoteUpdate(this, token);+ }++ discardNoteUndo(id, token) {+ if (this.noteUndoReady) noteUndo.discardNoteUndo(this, id, token);+ }++ updateNote(id, updates, options) {+ if (options?.undoable && this.noteUndoReady) {+ return noteUndo.updateNoteWithUndo(this, id, updates, options.expected, options.turn);+ }try {if (!this.db) throw new Error("Database not initialized");if (!this.getNote(id)) return { success: false, error: "Note not found" };diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 66b29326b..9e70c47de 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -2239,8 +2239,25 @@ class IPCHandlers {return this.databaseManager.getNotesForSpace(spaceId, limit);});- ipcMain.handle("db-update-note", async (event, id, updates) => {- const result = this.databaseManager.updateNote(id, updates);+ ipcMain.handle("db-get-note-undos", () => this.databaseManager.getNoteUndos());+ ipcMain.handle("db-claim-note-undo", (_event, token) =>+ this.databaseManager.claimNoteUndo(token)+ );+ ipcMain.handle("db-discard-note-undo", (_event, id, token) =>+ this.databaseManager.discardNoteUndo(id, token)+ );+ ipcMain.handle("db-undo-note-update", (_event, token) => {+ const result = this.databaseManager.undoNoteUpdate(token);+ if (result?.success && result?.note) {+ setImmediate(() => broadcastToWindows("note-updated", result.note));+ this.notifyVectorChanges();+ this._asyncMirrorWrite(result.note);+ }+ return result;+ });++ ipcMain.handle("db-update-note", async (event, id, updates, options) => {+ const result = this.databaseManager.updateNote(id, updates, options);if (result?.success && result?.note) {setImmediate(() => broadcastToWindows("note-updated", result.note));this.notifyVectorChanges();diff --git a/src/helpers/noteUndo.js b/src/helpers/noteUndo.jsnew file mode 100644index 000000000..ee8d581db--- /dev/null+++ b/src/helpers/noteUndo.js@@ -0,0 +1,187 @@+const { randomUUID } = require("crypto");++// Sync acknowledgements are not edits. All semantic changes (including SQL+// writers outside updateNote) retire the previous assistant's recovery token.+const GUARDED_FIELDS = [+ "title",+ "content",+ "enhanced_content",+ "enhancement_prompt",+ "enhancement_template_id",+ "enhanced_at_content_hash",+ "folder_id",+ "space_id",+ "transcript",+ "participants",+ "calendar_event_id",+ "deleted_at",+ "client_note_id",+ "account_id",+ "owner_user_id",+ "note_type",+ "created_at",+];+const EDITABLE_FIELDS = ["title", "content", "enhanced_content", "folder_id"];+// A cloud pull stores an empty field as NULL, so here and in the trigger ''+// and NULL are equal: the echo of a cleared summary is not a later edit.+const sameValue = (a, b) => (a ?? "") === (b ?? "");+// Outlives a cancelled turn, a renderer reload and an unfocused panel, but an+// edit is never offered again at a later launch.+const UNDO_TTL_MS = 10 * 60 * 1000;+// Every window lists live recoveries, but only the first focused one offers+// each as a toast, so an edit is not offered again in another window.+const offeredTokens = new Set();+// The chat turn (assistant message) that made each recovery.+const undoTurns = new Map();+const JOURNAL_COLUMNS = ["note_id", "token", "account_id", "previous", "created_at"];++// One transaction: a step that fails after the DROP would otherwise leave the+// triggers pointing at a missing journal, failing every note write.+const initializeNoteUndo = (db) => db.transaction(() => setUpJournal(db))();++function setUpJournal(db) {+ // Recoveries are short-lived, so a journal of another shape (an earlier+ // build's) is dropped rather than migrated.+ const columns = db+ .prepare("PRAGMA table_info(assistant_note_undo)")+ .all()+ .map((column) => column.name);+ if (columns.length && columns.join() !== JOURNAL_COLUMNS.join()) {+ db.exec("DROP TABLE assistant_note_undo");+ }+ db.exec(`+ CREATE TABLE IF NOT EXISTS assistant_note_undo (+ note_id INTEGER PRIMARY KEY REFERENCES notes(id) ON DELETE CASCADE,+ token TEXT NOT NULL UNIQUE,+ account_id TEXT,+ previous TEXT NOT NULL,+ created_at INTEGER NOT NULL+ );+ DROP TRIGGER IF EXISTS assistant_note_undo_update;+ CREATE TRIGGER assistant_note_undo_update AFTER UPDATE ON notes+ WHEN ${GUARDED_FIELDS.filter((field) => field !== "owner_user_id")+ .map((field) => `IFNULL(OLD.${field}, '') IS NOT IFNULL(NEW.${field}, '')`)+ .join(" OR ")}+ OR (OLD.owner_user_id IS NOT NULL AND OLD.owner_user_id IS NOT NEW.owner_user_id)+ BEGIN DELETE FROM assistant_note_undo WHERE note_id = NEW.id; END;+ DROP TRIGGER IF EXISTS assistant_note_undo_delete;+ CREATE TRIGGER assistant_note_undo_delete AFTER DELETE ON notes+ BEGIN DELETE FROM assistant_note_undo WHERE note_id = OLD.id; END;+ `);+ db.prepare("DELETE FROM assistant_note_undo WHERE created_at < ?").run(Date.now() - UNDO_TTL_MS);+}++function updateNoteWithUndo(manager, id, updates, expected, turn) {+ return manager.db.transaction(() => {+ const before = manager.getNote(id);+ if (!before || before.deleted_at) return { success: false, error: "Note not found" };+ if (!expected || GUARDED_FIELDS.some((key) => !sameValue(before[key], expected[key]))) {+ return { success: false, error: "Note changed. Read it again before editing." };+ }+ if (+ Object.keys(updates).some((key) => key !== "clear_fields" && !EDITABLE_FIELDS.includes(key))+ ) {+ return { success: false, error: "Unsupported assistant note field" };+ }+ if (updates.folder_id != null) {+ const folder = manager._getFolderInAccountScope(updates.folder_id);+ if (!folder || folder.deleted_at || folder.space_id !== before.space_id) {+ return { success: false, error: "Folder is no longer available in this space" };+ }+ }+ const previous = Object.fromEntries(+ Object.keys(updates)+ .filter((key) => key !== "clear_fields")+ .filter((key) => !sameValue(before[key], updates[key]))+ .map((key) => [key, before[key]])+ );+ if (!Object.keys(previous).length) return { success: true, note: before };+ // Read before the write: the update trigger retires the live recovery.+ const live = liveUndo(manager, "note_id", id);+ const result = manager.updateNote(id, updates);+ if (!result.success) return result;+ // 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;+ const merged = { ...previous, ...(sameTurn && JSON.parse(live.previous)) };+ if (live) undoTurns.delete(live.token);+ const token = randomUUID();+ manager.db+ .prepare(+ "INSERT OR REPLACE INTO assistant_note_undo (note_id, token, account_id, previous, created_at) VALUES (?, ?, ?, ?, ?)"+ )+ .run(id, token, manager.activeAccountId, JSON.stringify(merged), Date.now());+ if (turn != null) undoTurns.set(token, turn);+ return result;+ })();+}++// A recovery is usable only by the account that made it, within its TTL.+function liveUndo(manager, column, value) {+ return manager.db+ .prepare(+ `SELECT * FROM assistant_note_undo WHERE ${column} = ? AND account_id IS ? AND created_at >= ?`+ )+ .get(value, manager.activeAccountId, Date.now() - UNDO_TTL_MS);+}++function getNoteUndos(manager) {+ const scope = manager._accountScopeCondition("notes");+ return manager.db+ .prepare(+ `+ SELECT u.token, notes.id AS noteId, notes.title+ FROM assistant_note_undo u JOIN notes ON notes.id = u.note_id+ WHERE notes.deleted_at IS NULL AND u.account_id IS ? AND u.created_at >= ? AND ${scope.sql}+ `+ )+ .all(manager.activeAccountId, Date.now() - UNDO_TTL_MS, ...scope.params);+}++function undoNoteUpdate(manager, token) {+ return manager.db.transaction(() => {+ const saved = liveUndo(manager, "token", token);+ const note = saved && manager.getNote(saved.note_id);+ if (!note || note.deleted_at) return { success: false, error: "note_changed" };+ const previous = JSON.parse(saved.previous);+ if (previous.folder_id != null) {+ const folder = manager._getFolderInAccountScope(previous.folder_id);+ if (!folder || folder.deleted_at || folder.space_id !== note.space_id) {+ return { success: false, error: "note_changed" };+ }+ }+ const result = manager.updateNote(note.id, previous);+ if (result.success)+ manager.db.prepare("DELETE FROM assistant_note_undo WHERE token = ?").run(token);+ return result;+ })();+}++function claimNoteUndo(manager, token) {+ if (offeredTokens.has(token) || !liveUndo(manager, "token", token)) return false;+ offeredTokens.add(token);+ return true;+}++// Runs on every keystroke in the note editor, so it is a single statement.+function discardNoteUndo(manager, id, token) {+ const scope = manager._accountScopeCondition("notes");+ // A toast may expire after a newer edit; only that toast's token is retired.+ const byToken = token ? " AND token = ? AND account_id IS ?" : "";+ manager.db+ .prepare(+ `DELETE FROM assistant_note_undo WHERE note_id = ?+ AND note_id IN (SELECT id FROM notes WHERE ${scope.sql})${byToken}`+ )+ .run(id, ...scope.params, ...(token ? [token, manager.activeAccountId] : []));+}++module.exports = {+ UNDO_TTL_MS,+ initializeNoteUndo,+ updateNoteWithUndo,+ getNoteUndos,+ claimNoteUndo,+ undoNoteUpdate,+ discardNoteUndo,+};diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 38b20c70c..4dc09cfce 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -2560,6 +2560,11 @@"author": {"you": "أنت"}+ },+ "assistantUndo": {+ "applied": "حدّث المساعد «{{title}}»",+ "changed": "تغيّرت هذه الملاحظة بعد تعديل المساعد. لم يعد التراجع متاحًا.",+ "failed": "تعذّر التراجع عن التعديل. حاول مرة أخرى."}},"onboarding": {diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 64e9ed1f7..986bf3135 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -3774,6 +3774,11 @@"author": {"you": "Du"}+ },+ "assistantUndo": {+ "applied": "Der Assistent hat „{{title}}“ aktualisiert",+ "changed": "Diese Notiz wurde nach der Änderung des Assistenten erneut geändert. Rückgängig ist nicht mehr verfügbar.",+ "failed": "Die Änderung konnte nicht rückgängig gemacht werden. Bitte versuche es erneut."}},"dictionary": {diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex bff8d6693..e4d85a2b0 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -3774,6 +3774,11 @@"author": {"you": "You"}+ },+ "assistantUndo": {+ "applied": "Assistant updated “{{title}}”",+ "changed": "This note changed after the assistant edit. Undo is no longer available.",+ "failed": "Could not undo the edit. Please try again."}},"dictionary": {diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 7f4f96ca1..92b12ca2f 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -3475,6 +3475,11 @@"author": {"you": "Tú"}+ },+ "assistantUndo": {+ "applied": "El asistente actualizó «{{title}}»",+ "changed": "Esta nota cambió después de la edición del asistente. Ya no se puede deshacer.",+ "failed": "No se pudo deshacer la edición. Inténtalo de nuevo."}},"dictionary": {diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex db5c2f064..a58d08de8 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -3774,6 +3774,11 @@"author": {"you": "Vous"}+ },+ "assistantUndo": {+ "applied": "L’assistant a modifié « {{title}} »",+ "changed": "Cette note a changé après la modification de l’assistant. Il n’est plus possible de l’annuler.",+ "failed": "Impossible d’annuler la modification. Réessayez."}},"dictionary": {diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 127c976f6..64ff37f1a 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -3423,6 +3423,11 @@"author": {"you": "Tu"}+ },+ "assistantUndo": {+ "applied": "L’assistente ha aggiornato «{{title}}»",+ "changed": "Questa nota è cambiata dopo la modifica dell’assistente. Non è più possibile annullarla.",+ "failed": "Impossibile annullare la modifica. Riprova."}},"dictionary": {diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex dd762e125..66511e195 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -3351,6 +3351,11 @@"author": {"you": "自分"}+ },+ "assistantUndo": {+ "applied": "アシスタントが「{{title}}」を更新しました",+ "changed": "アシスタントの編集後にノートが変更されたため、元に戻せません。",+ "failed": "編集を元に戻せませんでした。もう一度お試しください。"}},"dictionary": {diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 32aa872bb..ebaa298a1 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -3423,6 +3423,11 @@"author": {"you": "Você"}+ },+ "assistantUndo": {+ "applied": "O assistente atualizou “{{title}}”",+ "changed": "Esta nota mudou após a edição do assistente. Já não é possível desfazer.",+ "failed": "Não foi possível desfazer a edição. Tente novamente."}},"dictionary": {diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 2cb7c823b..6dcc51573 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -3447,6 +3447,11 @@"author": {"you": "Вы"}+ },+ "assistantUndo": {+ "applied": "Ассистент обновил «{{title}}»",+ "changed": "После правки ассистента заметка была изменена. Отмена больше недоступна.",+ "failed": "Не удалось отменить правку. Повторите попытку."}},"dictionary": {diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 0cad52750..835d844e4 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -3423,6 +3423,11 @@"author": {"you": "你"}+ },+ "assistantUndo": {+ "applied": "助手已更新“{{title}}”",+ "changed": "助手编辑后,这篇笔记又发生了更改,无法撤销。",+ "failed": "无法撤销编辑,请重试。"}},"dictionary": {diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex a02f9ad1b..0dadd0c86 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -3423,6 +3423,11 @@"author": {"you": "你"}+ },+ "assistantUndo": {+ "applied": "助理已更新「{{title}}」",+ "changed": "助理編輯後,這篇筆記又有變更,無法復原。",+ "failed": "無法復原編輯,請再試一次。"}},"dictionary": {diff --git a/src/services/tools/updateNoteTool.ts b/src/services/tools/updateNoteTool.tsindex cd778ace9..d2a35becf 100644--- a/src/services/tools/updateNoteTool.ts+++ b/src/services/tools/updateNoteTool.ts@@ -2,6 +2,36 @@ import type { ToolDefinition, ToolExecutionContext, ToolResult } from "./ToolRegimport { resolveFolderId } from "./utils";import { syncService } from "../SyncService.js";+// The AI SDK runs a step's tool calls concurrently. Edits of one note take+// turns, so the second reads the first's write instead of failing main's check+// that the note is unchanged since this call read it.+const noteLocks = new Map<number, Promise<void>>();++async function lockNote(id: number): Promise<() => void> {+ const previous = noteLocks.get(id) ?? Promise.resolve();+ let release = (): void => {};+ const held = new Promise<void>((resolve) => (release = resolve));+ const tail = previous.then(() => held);+ noteLocks.set(id, tail);+ await previous;+ return () => {+ release();+ if (noteLocks.get(id) === tail) noteLocks.delete(id);+ };+}++// For the model only (the tool step shows displayText): a blank sent the old way+// to clear a field succeeds without clearing it, so say so plainly.+function ignoredFieldsGuidance(ignoredFields: string[]): string {+ const clearHint = ignoredFields.some((field) => field === "content" || field === "summary")+ ? " To empty content or summary, call update_note again with clear_fields; until then, don't tell the user a field was cleared."+ : "";+ return `Ignored blank ${ignoredFields.join(", ")}: nothing was cleared.${clearHint}`;+}++const isClearFields = (value: unknown): value is Array<"content" | "summary"> =>+ Array.isArray(value) && value.every((field) => field === "content" || field === "summary");+export const updateNoteTool: ToolDefinition = {name: "update_note",description:@@ -20,12 +50,18 @@ export const updateNoteTool: ToolDefinition = {content: {type: "string",description:- "Complete replacement of the user's personal notes only, not the AI summary or transcript. Omit unless editing this field; an empty string clears it.",+ "Complete replacement of the user's personal notes only, not the AI summary or transcript. Omit unless editing this field. Blank strings are ignored; use clear_fields only when the user explicitly asks to clear the entire field.",},summary: {type: "string",description:- "Complete replacement of the saved AI Summary only. Preserve unrelated sections exactly. Omit unless editing this field; an empty string clears it.",+ "Complete replacement of the saved AI Summary only. Preserve unrelated sections exactly. Omit unless editing this field. Blank strings are ignored; use clear_fields only when the user explicitly asks to clear the entire field.",+ },+ clear_fields: {+ type: "array",+ items: { type: "string", enum: ["content", "summary"] },+ description:+ "Fields to empty, only when the user asks to clear the field or to remove text that is all of it. For any other section removal, supply the remaining text instead. Never infer clear intent from an empty optional field.",},folder: {type: "string",@@ -41,31 +77,65 @@ export const updateNoteTool: ToolDefinition = {args: Record<string, unknown>,context?: ToolExecutionContext): Promise<ToolResult> {- const id = args.id as number;- const title = args.title as string | undefined;- const content = args.content as string | undefined;- const summary = args.summary as string | undefined;- const folderName = args.folder as string | undefined;-- if (!title && typeof content !== "string" && typeof summary !== "string" && !folderName) {+ // Models sometimes send the ID as a numeric string, which get_note accepts.+ const id = typeof args.id === "string" && /^\d+$/.test(args.id) ? Number(args.id) : args.id;+ const clearFields: unknown = args.clear_fields ?? [];+ const invalid = (argument: string): ToolResult => ({+ success: false,+ data: null,+ displayText: `Invalid note update argument: ${argument}`,+ });+ if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) return invalid("id");+ const invalidField = ["title", "content", "summary", "folder"].find(+ (key) => args[key] != null && typeof args[key] !== "string"+ );+ if (invalidField) return invalid(invalidField);+ if (!isClearFields(clearFields)) {+ return invalid('clear_fields (an array of "content" and/or "summary")');+ }+ const isBlank = (value: unknown): value is string => typeof value === "string" && !value.trim();+ const title = typeof args.title === "string" && args.title.trim() ? args.title : undefined;+ const folderName =+ typeof args.folder === "string" && args.folder.trim() ? args.folder : undefined;+ const updates: Parameters<typeof window.electronAPI.updateNote>[1] = {};+ const ignoredFields: string[] = [];+ if (title) updates.title = title;+ else if (isBlank(args.title)) ignoredFields.push("title");+ if (!folderName && isBlank(args.folder)) ignoredFields.push("folder");+ for (const field of ["content", "summary"] as const) {+ const value = args[field];+ const clear = clearFields.includes(field);+ if (clear && typeof value === "string" && value.trim()) {+ return {+ success: false,+ data: null,+ displayText: `Cannot replace and clear ${field} together`,+ };+ }+ if (clear) updates[field === "summary" ? "enhanced_content" : field] = "";+ else if (typeof value === "string" && value.trim())+ updates[field === "summary" ? "enhanced_content" : field] = value;+ else if (isBlank(value)) ignoredFields.push(field);+ }+ if (!Object.keys(updates).length && !folderName) {return {success: false,data: null,- displayText: "At least one of title, content, summary, or folder must be provided",+ displayText:+ "No changes supplied. Blank fields are ignored; to empty content or summary (a requested clear, or a removal that leaves nothing), use clear_fields.",};}+ const unlock = await lockNote(id);try {const note = await window.electronAPI.getNote(id);if (context?.signal.aborted) return { success: false, data: null, displayText: "" };if (!note) {return { success: false, data: null, displayText: `Note with ID ${id} not found` };}-- const updates: Record<string, string | number | null> = {};- if (title) updates.title = title;- if (typeof content === "string") updates.content = content;- if (typeof summary === "string") updates.enhanced_content = summary;+ if (note.deleted_at) {+ return { success: false, data: null, displayText: `Note with ID ${id} is in the trash` };+ }let folderCreated = false;if (folderName) {@@ -84,10 +154,29 @@ export const updateNoteTool: ToolDefinition = {}if (context?.signal.aborted) return { success: false, data: null, displayText: "" };- const result = await window.electronAPI.updateNote(id, updates);+ const result = await window.electronAPI.updateNote(+ id,+ {+ ...updates,+ ...(clearFields.length && {+ clear_fields: clearFields.map((field) =>+ field === "summary" ? "enhanced_content" : "content"+ ),+ }),+ },+ {+ undoable: true,+ expected: note,+ turn: context?.messageId,+ }+ );if (!result.success) {- return { success: false, data: null, displayText: "Failed to update note" };+ return {+ success: false,+ data: null,+ displayText: `Failed to update note${result.error ? `: ${result.error}` : ""}`,+ };}syncService.debouncedPush("note", id);@@ -98,9 +187,11 @@ export const updateNoteTool: ToolDefinition = {data: {id,title: title || note.title,+ ignoredFields,updatedFields: Object.keys(updates).map((field) =>field === "enhanced_content" ? "summary" : field),+ ...(ignoredFields.length > 0 && { guidance: ignoredFieldsGuidance(ignoredFields) }),},displayText: `Updated note: "${title || note.title}"${suffix}`,};@@ -110,6 +201,8 @@ export const updateNoteTool: ToolDefinition = {data: null,displayText: `Failed to update note: ${(error as Error).message}`,};+ } finally {+ unlock();}},};diff --git a/src/types/electron.ts b/src/types/electron.tsindex 4b62c9332..1aea28645 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1616,8 +1616,15 @@ declare global {owner_user_id?: string | null;updated_by_user_id?: string | null;left_team?: number;- }+ },+ options?: { undoable: true; expected: NoteItem; turn?: string }+ ) => Promise<{ success: boolean; note?: NoteItem; error?: string }>;+ getNoteUndos: () => Promise<Array<{ token: string; noteId: number; title: string }>>;+ claimNoteUndo: (token: string) => Promise<boolean>;+ undoNoteUpdate: (+ token: string) => Promise<{ success: boolean; note?: NoteItem; error?: string }>;+ discardNoteUndo: (id: number, token?: string) => Promise<void>;deleteNote: (id: number) => Promise<{ success: boolean }>;exportNote: (noteId: number,diff --git a/test/components/assistantNoteUndoListener.test.js b/test/components/assistantNoteUndoListener.test.jsnew file mode 100644index 000000000..43fb29547--- /dev/null+++ b/test/components/assistantNoteUndoListener.test.js@@ -0,0 +1,214 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRoot } = require("react-dom/client");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");+const { installInteractiveDom } = require("../lib/interactiveDom");++async function setup(t, focused = true) {+ const toasts = [],+ dismissed = [],+ calls = [],+ pushes = [];+ const listeners = new Map();+ // Main's claim: each recovery is offered by one window, once.+ const claimed = new Set();+ let edits = [],+ result = { success: true },+ root;+ const emit = async (event) => React.act(async () => listeners.get(event)?.());+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ delete globalThis.__assistantUndoToast;+ });+ installBrowserGlobals(t, {+ window: {+ addEventListener: (event, cb) => listeners.set(event, cb),+ removeEventListener: (event) => listeners.delete(event),+ electronAPI: {+ getNoteUndos: async () => edits,+ claimNoteUndo: async (token) => !claimed.has(token) && !!claimed.add(token),+ undoNoteUpdate: async (token) => {+ calls.push(token);+ if (result instanceof Error) throw result;+ return result;+ },+ discardNoteUndo: async (...args) => calls.push(args),+ onNoteUpdated: (cb) => {+ listeners.set("note", cb);+ return () => listeners.delete("note");+ },+ onActiveAccountScopeChanged: (cb) => {+ listeners.set("scope", cb);+ return () => listeners.delete("scope");+ },+ },+ },+ });+ const container = installInteractiveDom(t);+ globalThis.document.hasFocus = () => focused;+ globalThis.__assistantUndoToast = {+ pushes,+ toast: (props) => {+ toasts.push(props);+ return `toast-${toasts.length}`;+ },+ dismiss: (id) => dismissed.push(id),+ };+ const vite = await createRendererServer(t, {+ mockModules: {+ "/services/SyncService": `export const syncService = { debouncedPush: (...args) => globalThis.__assistantUndoToast.pushes.push(args) };`,+ "/ui/useToast": "export const useToast = () => globalThis.__assistantUndoToast;",+ "/ui/Toast": `import { createElement } from "react"; export const ToastActionButton = ({ onClick, children }) => createElement("button", { onClick }, children);`,+ },+ });+ await (await vite.ssrLoadModule("/i18n.ts")).default.changeLanguage("en");+ const { default: Listener } = await vite.ssrLoadModule(+ "/components/notes/AssistantNoteUndoListener.tsx"+ );+ const mount = async () => {+ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Listener)));+ };+ await mount();+ return {+ toasts,+ dismissed,+ calls,+ pushes,+ claimed,+ emit,+ setResult: (value) => {+ result = value;+ },+ setEdits: (value) => {+ edits = value;+ },+ focus: async () => {+ focused = true;+ await emit("focus");+ },+ blur: () => {+ focused = false;+ },+ remount: async () => {+ await React.act(async () => root.unmount());+ await mount();+ },+ };+}+const one = { noteId: 7, token: "first", title: "First note" };++test("a background window offers Undo once focused; it targets the edited note", async (t) => {+ const state = await setup(t, false);+ state.setEdits([one]);+ await state.emit("note");+ assert.equal(state.toasts.length, 0);+ await state.focus();+ assert.equal(state.toasts.length, 1);+ assert.match(state.toasts[0].title, /First note/);+ assert.equal(state.toasts[0].duration, 6000);+ await state.emit("focus");+ assert.equal(state.toasts.length, 1);+ await React.act(async () => state.toasts[0].action.props.onClick());+ assert.deepEqual(state.calls, ["first"]);+ assert.deepEqual(state.pushes, [["note", 7]]);+ assert.ok(state.dismissed.includes("toast-1"));+});++test("an edit offered elsewhere or before a reload is not offered again", async (t) => {+ const state = await setup(t);+ state.claimed.add("other-window");+ state.setEdits([{ ...one, token: "other-window" }]);+ await state.emit("note");+ assert.equal(state.toasts.length, 0, "another window already offered it");+ state.setEdits([one]);+ await state.emit("note");+ assert.equal(state.toasts.length, 1);+ await state.remount();+ assert.equal(state.toasts.length, 1, "a reload does not offer it again");+});++test("an unfocused window drops its toast once the recovery is gone", async (t) => {+ const state = await setup(t);+ state.setEdits([one]);+ await state.emit("note");+ state.blur();+ state.setEdits([]);+ await state.emit("note");+ assert.ok(state.dismissed.includes("toast-1"), "undone in the other window");+ assert.equal(state.toasts.length, 1);+});++test("a later edit replaces the old toast and unavailable Undo explains the refusal", async (t) => {+ const state = await setup(t);+ state.setEdits([one]);+ await state.emit("note");+ state.setEdits([{ ...one, token: "second" }]);+ await state.emit("note");+ assert.ok(state.dismissed.includes("toast-1"));+ state.setResult({ success: false, error: "note_changed" });+ await React.act(async () => state.toasts[1].action.props.onClick());+ assert.deepEqual(state.calls, ["second"]);+ assert.match(state.toasts[2].description, /changed.*Undo/);+ assert.ok(state.dismissed.includes("toast-2"), "a refused Undo cannot be clicked again");+ assert.deepEqual(state.pushes, []);+});++test("a failed restore keeps the toast; closing it retires only its recovery", async (t) => {+ const state = await setup(t);+ state.setEdits([{ ...one, title: "" }]);+ await state.emit("note");+ assert.match(state.toasts[0].title, /Untitled/);+ state.setResult({ success: false, error: "disk full" });+ await React.act(async () => state.toasts[0].action.props.onClick());+ assert.match(state.toasts[1].description, /Could not undo/);+ assert.equal(state.dismissed.includes("toast-1"), false);+ await React.act(async () => state.toasts[0].onClose());+ assert.deepEqual(state.calls.at(-1), [7, "first"]);+});++test("Undo errors stay visible and double clicks cannot issue parallel restores", async (t) => {+ const state = await setup(t);+ state.setEdits([one]);+ await state.emit("note");+ state.setResult(new Error("disk full"));+ await React.act(async () =>+ Promise.all([state.toasts[0].action.props.onClick(), state.toasts[0].action.props.onClick()])+ );+ assert.deepEqual(state.calls, ["first"]);+ assert.match(state.toasts[1].description, /Could not undo/);+ assert.deepEqual(state.pushes, []);+});++test("a click on a toast that is animating out after its Undo does nothing", async (t) => {+ const state = await setup(t);+ state.setEdits([one]);+ await state.emit("note");+ await React.act(async () => state.toasts[0].action.props.onClick());+ state.setResult({ success: false, error: "note_changed" });+ await React.act(async () => state.toasts[0].action.props.onClick());+ assert.deepEqual(state.calls, ["first"]);+ assert.equal(state.toasts.length, 1, "no error toast after a successful Undo");+});++test("scope changes dismiss old note names and ignore an outstanding list response", async (t) => {+ const state = await setup(t);+ state.setEdits([one]);+ await state.emit("note");+ let release;+ const original = globalThis.window.electronAPI.getNoteUndos;+ globalThis.window.electronAPI.getNoteUndos = () =>+ new Promise((resolve) => {+ release = resolve;+ });+ const old = state.emit("note");+ await new Promise((resolve) => setImmediate(resolve));+ globalThis.window.electronAPI.getNoteUndos = original;+ state.setEdits([]);+ await state.emit("scope");+ release([{ ...one, token: "stale" }]);+ await old;+ assert.equal(state.toasts.length, 1);+ assert.ok(state.dismissed.includes("toast-1"));+});diff --git a/test/components/personalNotesUndoDiscard.test.js b/test/components/personalNotesUndoDiscard.test.jsnew file mode 100644index 000000000..0b62183f2--- /dev/null+++ b/test/components/personalNotesUndoDiscard.test.js@@ -0,0 +1,114 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ 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.++const NOTE = {+ id: 11,+ title: "Standup",+ content: "Notes",+ enhanced_content: "Summary",+ transcript: "",+ folder_id: null,+ space_id: 1,+ note_type: "meeting",+};++const MOCKS = {+ "/ui/useToast": `+ const toast = () => "1";+ export const useToast = () => ({ toast, dismiss() {} });+ `,+ "/icons": `export const Plus = () => null; export const Sparkles = () => null;`,+ "./NoteEditor": `+ export default function NoteEditor(props) {+ globalThis.__editorProps = props;+ return null;+ }`,+ "./SpacesTree": `export default () => null;`,+ "/overview/ContainerOverview": `export const ContainerOverview = () => null;`,+ "./NotesStructureIntroDialog": `export default () => null;`,+ "./ActionManagerDialog": `export default () => null;`,+ "./AddNotesToFolderDialog": `export default () => null;`,+ "./NotesOnboarding": `export default () => null;`,+ "/hooks/useActionProcessing": `+ export const useActionProcessing = () => ({ state: "idle", actionName: null, runAction() {} });+ `,+ "/stores/actionStore": `export const getActionName = (action) => action.name;`,+ "/hooks/useNotesOnboarding": `+ export const useNotesOnboarding = () => ({ isComplete: true, complete() {} });+ `,+ "/hooks/useTeamSpacesCapability": `export const useTeamSpacesCapability = () => false;`,+ "/hooks/useAuth": `export const useAuth = () => ({ isSignedIn: false, user: null });`,+ "/stores/noteStore": `+ const note = () => globalThis.__note;+ export const setActiveNoteId = () => {};+ export const useActiveNoteId = () => note().id;+ export const useActiveNote = () => note();+ export const useNotes = () => [];+ export const useSpaces = () => [];+ export const useFolders = () => [];+ export const useActiveFolderId = () => null;+ export const useActiveContext = () => null;+ export const useIsTreeLoading = () => false;+ export const initializeNotes = async () => {};+ export const initializeNotesTree = async () => {};+ export const loadFolders = async () => {};+ export const setActiveContext = () => {};+ export const revealContainer = () => {};+ export const createFolder = async () => ({ success: false });+ export const getNoteFromStore = () => note();+ `,+};++test("editing either document retires the assistant's Undo before the delayed save", async (t) => {+ const calls = [];+ let root;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ delete globalThis.__editorProps;+ delete globalThis.__note;+ });+ globalThis.__note = NOTE;+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ getNote: async () => NOTE,+ updateNote: async (...args) => {+ calls.push(["save", ...args]);+ return { success: true };+ },+ discardNoteUndo: async (...args) => calls.push(["discard", ...args]),+ },+ setTimeout: (fn, ms) => setTimeout(fn, ms),+ },+ });+ const container = installHostDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-personal-notes-undo-discard-",+ mockModules: MOCKS,+ });+ const { default: PersonalNotesView } = await vite.ssrLoadModule(+ "/components/notes/PersonalNotesView.tsx"+ );+ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(PersonalNotesView)));++ await React.act(async () => globalThis.__editorProps.onContentChange(NOTE.id, "Typed"));+ assert.deepEqual(calls, [["discard", NOTE.id]], "retired before the save");+ await React.act(async () =>+ globalThis.__editorProps.enhancement.onChange(NOTE.id, "Typed summary")+ );+ assert.deepEqual(calls.at(-1), ["discard", NOTE.id]);+ assert.equal(calls.filter(([kind]) => kind === "save").length, 0);+});diff --git a/test/components/richTextEditor.test.js b/test/components/richTextEditor.test.jsindex 14d7260e3..c8edbb453 100644--- a/test/components/richTextEditor.test.js+++ b/test/components/richTextEditor.test.js@@ -763,6 +763,16 @@ async function openTableMenu(notes, caretCell = "Ana") {await notes.act(() => pointerDown(byLabel("notes.editor.table.actions")));}+test("clicking into a note that ends in a list saves nothing until the user edits", async (t) => {+ // The trailing-node plugin appends a paragraph on the first selection change;+ // saving that would also retire the assistant's Undo for the note.+ const notes = await mountNotes(t, "## Action items\n\n- Ana: draft the brief\n- Raj: book it");+ await notes.act(() => notes.editor().commands.setTextSelection(5));+ assert.equal(notes.saved(), undefined);+ await notes.act(() => notes.editor().commands.insertContent("ZZ"));+ assert.match(notes.saved(), /ZZ/);+});+test("Delete table from the menu works in a note that re-renders on every change", async (t) => {const notes = await mountNotes(t);await openTableMenu(notes);diff --git a/test/helpers/noteUndoIpc.test.js b/test/helpers/noteUndoIpc.test.jsnew file mode 100644index 000000000..f35eaf03b--- /dev/null+++ b/test/helpers/noteUndoIpc.test.js@@ -0,0 +1,120 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++// Registers the real handler closures against a fake `this` (the scaffolding+// from semanticSearchIpc.test.js): an Undo must reach every window, the search+// index and the note's mirror file like any other note write.+const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;+const handlers = new Map();+const sent = [];++const electronStub = {+ app: {+ getPath: () => "/tmp",+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: {+ handle: (channel, handler) => handlers.set(channel, handler),+ on: () => {},+ removeHandler: () => {},+ },+ net: { fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) },+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [+ {+ isDestroyed: () => false,+ webContents: { send: (channel, data) => sent.push([channel, data]) },+ },+ ];+ }++ static fromWebContents() {+ return null;+ }+ },+ shell: {},+ dialog: {},+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+};++Module._load = function loadWithElectronStub(request, parent, isMain) {+ if (request === "electron") return electronStub;+ if (parent?.filename === handlersModulePath && request === "./debugLogger") {+ return new Proxy({}, { get: () => () => {} });+ }+ return originalLoad.call(this, request, parent, isMain);+};++function anything() {+ return new Proxy(function () {}, {+ get: (_target, property) => {+ if (property === Symbol.toPrimitive || property === "toString") return () => "";+ if (property === "then") return undefined;+ return anything();+ },+ apply: () => anything(),+ });+}++const RESTORED = { id: 7, title: "Before the assistant" };+let undoResult;+const effects = { vectors: 0, mirrored: [] };++test.before(() => {+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const Ctor = IPCHandlers.default || IPCHandlers;+ const target = {+ notifyVectorChanges: () => effects.vectors++,+ _asyncMirrorWrite: (note) => effects.mirrored.push(note),+ databaseManager: { undoNoteUpdate: () => undoResult },+ };+ Ctor.prototype.setupHandlers.call(+ new Proxy(target, {+ get: (value, property) => (property in value ? value[property] : anything()),+ })+ );+});++test.after(() => {+ Module._load = originalLoad;+});++const undo = async () => {+ const result = await handlers.get("db-undo-note-update")(null, "token");+ await new Promise((resolve) => setImmediate(resolve));+ return result;+};++test("an Undo broadcasts the restored note, wakes the index and rewrites the mirror", async () => {+ undoResult = { success: true, note: RESTORED };+ assert.equal((await undo()).success, true);+ assert.deepEqual(sent, [["note-updated", RESTORED]]);+ assert.equal(effects.vectors, 1);+ assert.deepEqual(effects.mirrored, [RESTORED]);+});++test("a refused Undo writes nothing anywhere", async () => {+ sent.length = 0;+ effects.vectors = 0;+ effects.mirrored = [];+ undoResult = { success: false, error: "note_changed" };+ assert.equal((await undo()).success, false);+ assert.deepEqual(sent, []);+ assert.equal(effects.vectors, 0);+ assert.deepEqual(effects.mirrored, []);+});diff --git a/test/hooks/noteEditCancellation.test.js b/test/hooks/noteEditCancellation.test.jsindex 774650d95..6126e914d 100644--- a/test/hooks/noteEditCancellation.test.js+++ b/test/hooks/noteEditCancellation.test.js@@ -82,7 +82,11 @@ for (const boundary of ["note read", "conversation creation", "conversation loadt.mock.method(reasoning, "processTextStreamingCloud", (_messages, config) =>(async function* () {requests += 1;- await config.executeToolCall("update_note", JSON.stringify({ id: 7, summary: "" }), "edit");+ await config.executeToolCall(+ "update_note",+ JSON.stringify({ id: 7, clear_fields: ["summary"] }),+ "edit"+ );yield { type: "content", text: "Removed it." };yield { type: "done", finishReason: "stop" };})()diff --git a/test/hooks/noteEditSurfaces.test.js b/test/hooks/noteEditSurfaces.test.jsindex 907211598..aa7338e00 100644--- a/test/hooks/noteEditSurfaces.test.js+++ b/test/hooks/noteEditSurfaces.test.js@@ -62,7 +62,9 @@ for (const surface of ["note chat", "assistant panel"]) {clearInterval: noop,electronAPI: {getNote: async () => ({ ...stored }),- updateNote: async (_id, updates) => {+ updateNote: async (_id, updates, options) => {+ assert.equal(options.undoable, true);+ assert.equal(options.expected.id, stored.id);Object.assign(stored, updates);return { success: true };},@@ -128,6 +130,17 @@ for (const surface of ["note chat", "assistant panel"]) {yield { type: "tool_calls", calls: [call] };const saved = await execute(call.name, JSON.parse(call.arguments));assert.deepEqual(saved.updatedFields, ["summary"]);+ const renamed = await execute("update_note", {+ id: 7,+ title: "Renamed workshop",+ content: "",+ summary: "",+ });+ assert.deepEqual(renamed.updatedFields, ["title"]);+ assert.deepEqual(renamed.ignoredFields, ["content", "summary"]);+ assert.match(renamed.guidance, /nothing was cleared.*clear_fields/);+ assert.equal(stored.content, "Bring a notebook.");+ assert.equal(stored.enhanced_content, EDITED);yield {type: "tool_result",callId: "edit",@@ -214,6 +227,7 @@ for (const surface of ["note chat", "assistant panel"]) {assert.equal(settled, true);}assert.equal(stored.enhanced_content, EDITED);+ assert.equal(stored.title, "Renamed workshop");assert.equal(stored.content, "Bring a notebook.");assert.equal(stored.transcript, "Source transcript only.");assert.deepEqual(externalActions, []);diff --git a/test/services/assistantNoteUndo.test.js b/test/services/assistantNoteUndo.test.jsnew file mode 100644index 000000000..d6cbc0cc5--- /dev/null+++ b/test/services/assistantNoteUndo.test.js@@ -0,0 +1,624 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const Module = require("node:module");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");+const { UNDO_TTL_MS, initializeNoteUndo } = require("../../src/helpers/noteUndo");++// Real SQLite and the real tool/registry, with only Electron/provider transport stubbed.+test("safe assistant edits and atomic Undo", async (t) => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "ow-assistant-undo-"));+ const originalLoad = Module._load;+ let database;+ try {+ Module._load = function (request, parent, isMain) {+ if (request === "electron")+ return {+ app: { getPath: () => directory, getAppPath: () => process.cwd(), isReady: () => false },+ };+ return originalLoad.call(this, request, parent, isMain);+ };+ const DatabaseManager = require("../../src/helpers/database.js");+ database = new DatabaseManager();+ } finally {+ Module._load = originalLoad;+ }+ t.after(() => {+ database.db.close();+ fs.rmSync(directory, { recursive: true, force: true });+ });+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ getNote: async (id) => database.getNote(id),+ updateNote: async (id, updates, options) => database.updateNote(id, updates, options),+ getFolders: async (spaceId) => database.getFolders(spaceId),+ createFolder: async (name, spaceId) => database.createFolder(name, spaceId),+ },+ },+ });+ const vite = await createRendererServer(t);+ const { syncService } = await vite.ssrLoadModule("/services/SyncService.ts");+ const pushes = [];+ t.mock.method(syncService, "debouncedPush", (...args) => pushes.push(args));+ const { updateNoteTool } = await vite.ssrLoadModule("/services/tools/updateNoteTool.ts");+ const { executeTool } = await vite.ssrLoadModule("/services/tools/ToolRegistry.ts");+ const fresh = () => {+ const note = database.saveNote("Workshop", "Private notes", "meeting").note;+ database.updateNote(note.id, {+ enhanced_content: "## Decisions\nKeep it\n\n## Next\nDo it",+ transcript: "Source",+ enhancement_prompt: "Prompt",+ enhanced_at_content_hash: "hash",+ });+ return database.getNote(note.id);+ };+ const tokenFor = (id) => database.getNoteUndos().find((edit) => edit.noteId === id)?.token;+ const edit = (note, updates, turn) =>+ updateNoteTool.execute(+ { id: note.id, ...updates },+ turn && { messageId: turn, signal: new AbortController().signal }+ );++ for (const operation of ["rename", "move"])+ await t.test(+ `${operation} with extraneous blanks preserves documents and metadata`,+ async () => {+ const note = fresh();+ const folder = database.createFolder(`Folder ${note.id}`, note.space_id).folder;+ const result = await edit(note, {+ ...(operation === "rename" ? { title: "Renamed" } : { folder: folder.name }),+ content: "",+ summary: " \n ",+ });+ assert.equal(result.success, true);+ assert.deepEqual(result.data.ignoredFields, ["content", "summary"]);+ // The model is told the blanks cleared nothing; the user sees only the edit.+ assert.match(result.data.guidance, /nothing was cleared.*clear_fields/);+ assert.doesNotMatch(result.displayText, /blank|clear_fields/i);+ const saved = database.getNote(note.id);+ for (const key of [+ "content",+ "enhanced_content",+ "transcript",+ "enhancement_prompt",+ "enhanced_at_content_hash",+ ])+ assert.equal(saved[key], note[key]);+ assert.equal(+ saved[operation === "rename" ? "title" : "folder_id"],+ operation === "rename" ? "Renamed" : folder.id+ );+ assert.equal(database.undoNoteUpdate(tokenFor(note.id)).success, true);+ assert.equal(database.getNote(note.id).folder_id, note.folder_id);+ assert.equal(database.getNote(note.id).title, note.title);+ }+ );++ await t.test(+ "omitted/null fields are absent, wrong types fail, unmarked blanks never clear",+ async () => {+ const note = fresh();+ assert.equal(+ (await edit(note, { title: "Renamed", content: null, summary: null })).success,+ true+ );+ assert.equal(database.getNote(note.id).enhanced_content, note.enhanced_content);+ const token = tokenFor(note.id);+ for (const fields of [+ { content: 3 },+ { summary: false },+ { title: {} },+ { folder: [] },+ { clear_fields: "summary" },+ { clear_fields: ["transcript"] },+ { summary: "replacement", clear_fields: ["summary"] },+ { summary: "" },+ {},+ ]) {+ assert.equal((await edit(note, fields)).success, false, JSON.stringify(fields));+ assert.equal(tokenFor(note.id), token);+ assert.equal(database.getNote(note.id).content, note.content);+ assert.equal(database.getNote(note.id).enhanced_content, note.enhanced_content);+ }+ }+ );++ await t.test(+ "a numeric string ID edits the note; a malformed one names the argument",+ async () => {+ const note = fresh();+ assert.equal((await edit(note, { id: String(note.id), title: "By string" })).success, true);+ assert.equal(database.getNote(note.id).title, "By string");+ const result = await edit(note, { id: `${note.id}x`, title: "Rejected" });+ assert.equal(result.success, false);+ assert.equal(result.displayText, "Invalid note update argument: id");+ assert.equal(database.getNote(note.id).title, "By string");+ }+ );++ await t.test(+ "an expired recovery is neither offered nor restorable, and launch prunes it",+ async () => {+ const note = fresh();+ await edit(note, { title: "Old edit" });+ const token = tokenFor(note.id);+ database.db+ .prepare("UPDATE assistant_note_undo SET created_at = ? WHERE token = ?")+ .run(Date.now() - UNDO_TTL_MS - 1, token);+ assert.equal(tokenFor(note.id), undefined);+ assert.equal(database.undoNoteUpdate(token).success, false);+ assert.equal(database.getNote(note.id).title, "Old edit");+ initializeNoteUndo(database.db);+ const remaining = database.db+ .prepare("SELECT COUNT(*) AS count FROM assistant_note_undo WHERE token = ?")+ .get(token);+ assert.equal(remaining.count, 0);+ }+ );++ for (const field of ["content", "summary"])+ await t.test(`explicit ${field} clearing and reopen/Undo`, async () => {+ const note = fresh();+ const result = await edit(note, { clear_fields: [field] });+ 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], "");+ database.db.close();+ database.db = new (require("better-sqlite3"))(path.join(directory, "transcriptions.db"));+ 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 [+ "title",+ "content",+ "enhanced_content",+ "transcript",+ "enhancement_prompt",+ "enhanced_at_content_hash",+ ])+ assert.equal(restored[key], note[key]);+ assert.equal(tokenFor(note.id), undefined);+ });++ await t.test(+ "partial section removal; edits in one turn share an Undo, a later turn's stands alone",+ async () => {+ const note = fresh();+ await edit(note, { summary: "## Next\nDo it" }, "turn-1");+ const first = tokenFor(note.id);+ await edit(note, { title: "Renamed" }, "turn-1");+ const second = tokenFor(note.id);+ assert.notEqual(second, first);+ assert.equal(database.undoNoteUpdate(first).success, false);+ await edit(note, { content: "Later turn" }, "turn-2");+ assert.equal(database.undoNoteUpdate(tokenFor(note.id)).success, true);+ assert.equal(database.getNote(note.id).content, note.content);+ assert.equal(database.getNote(note.id).title, "Renamed", "an earlier turn stays applied");+ assert.equal(tokenFor(note.id), undefined);++ const other = fresh();+ await edit(other, { summary: "## Next\nDo it" }, "turn-3");+ await edit(other, { title: "Renamed" }, "turn-3");+ assert.equal(database.undoNoteUpdate(tokenFor(other.id)).success, true);+ assert.equal(database.getNote(other.id).title, other.title);+ assert.equal(database.getNote(other.id).enhanced_content, other.enhanced_content);+ }+ );++ await t.test("edits of one note in the same model step both apply", async () => {+ const note = fresh();+ const results = await Promise.all([+ edit(note, { summary: "## Next\nDo it" }, "step"),+ edit(note, { content: "Added reminder" }, "step"),+ ]);+ assert.deepEqual(+ results.map((result) => result.success),+ [true, true]+ );+ assert.equal(database.getNote(note.id).enhanced_content, "## Next\nDo it");+ assert.equal(database.getNote(note.id).content, "Added reminder");+ assert.equal(database.undoNoteUpdate(tokenFor(note.id)).success, true);+ assert.equal(database.getNote(note.id).enhanced_content, note.enhanced_content);+ assert.equal(database.getNote(note.id).content, note.content);+ });++ await t.test("the cloud pull echoing a cleared summary keeps Undo", async () => {+ const note = fresh();+ await edit(note, { clear_fields: ["summary"] });+ const token = tokenFor(note.id);+ const saved = database.getNote(note.id);+ database.upsertNoteFromCloud(+ {+ ...saved,+ id: `cloud-${note.id}`,+ created_at: "2026-10-09T00:00:00.000Z",+ updated_at: "2099-01-01T00:00:00.000Z",+ },+ saved.folder_id,+ saved.space_id+ );+ assert.equal(database.getNote(note.id).enhanced_content, null, "the pull stores NULL");+ assert.equal(tokenFor(note.id), token);+ assert.equal(database.undoNoteUpdate(token).success, true);+ assert.equal(database.getNote(note.id).enhanced_content, note.enhanced_content);+ });++ await t.test("each recovery is offered once", async () => {+ const note = fresh();+ await edit(note, { title: "Offered" });+ const token = tokenFor(note.id);+ assert.equal(database.claimNoteUndo(token), true);+ assert.equal(database.claimNoteUndo(token), false);+ assert.equal(database.claimNoteUndo("missing"), false);+ assert.equal(database.undoNoteUpdate(token).success, true, "claiming keeps it restorable");+ });++ await t.test("launch replaces an older Undo trigger", async () => {+ database.db.exec(`+ DROP TRIGGER assistant_note_undo_update;+ CREATE TRIGGER assistant_note_undo_update AFTER UPDATE ON notes BEGIN SELECT 1; END;+ `);+ initializeNoteUndo(database.db);+ const note = fresh();+ await edit(note, { title: "Renamed" });+ database.updateNote(note.id, { content: "Manual edit" });+ assert.equal(tokenFor(note.id), undefined);+ });++ await t.test("failed save rolls back and cannot create recovery or sync", async () => {+ const note = fresh();+ const before = pushes.length;+ const stub = t.mock.method(database, "updateNote", () => ({ success: false }));+ const result = await edit(note, { title: "Failed" });+ stub.mock.restore();+ assert.equal(result.success, false);+ assert.equal(tokenFor(note.id), undefined);+ assert.equal(pushes.length, before);+ assert.equal(database.getNote(note.id).title, note.title);+ });++ await t.test(+ "late committed save remains undoable after registry cancellation and note switch",+ async () => {+ const note = fresh();+ const other = fresh();+ const controller = new AbortController();+ let release, started;+ const saving = new Promise((resolve) => {+ started = resolve;+ });+ const stub = t.mock.method(globalThis.window.electronAPI, "updateNote", async (...args) => {+ const result = database.updateNote(...args);+ started();+ await new Promise((resolve) => {+ release = resolve;+ });+ return result;+ });+ // A failed assertion must not leave the stalled stub in place: every+ // later edit would wait on it forever.+ try {+ const pending = executeTool(+ updateNoteTool,+ { id: note.id, content: "Assistant replacement" },+ { signal: controller.signal }+ );+ await saving;+ controller.abort();+ assert.equal((await pending).success, false);+ assert.equal(database.getNote(other.id).content, other.content);+ assert.equal(database.undoNoteUpdate(tokenFor(note.id)).success, true);+ } finally {+ release?.();+ await new Promise((resolve) => setImmediate(resolve));+ stub.mock.restore();+ }+ assert.equal(database.getNote(note.id).content, note.content);+ }+ );++ for (const change of [+ "manual",+ "edit and revert",+ "cloud",+ "deleted",+ "hard deleted",+ "identity",+ "dirty draft",+ ])+ await t.test(`${change} prevents a stale Undo`, async () => {+ const note = fresh();+ await edit(note, { content: "Assistant replacement" });+ const token = tokenFor(note.id);+ if (change === "manual") database.updateNote(note.id, { title: "Manual title" });+ if (change === "edit and revert") {+ database.updateNote(note.id, { content: "Manual edit" });+ database.updateNote(note.id, { content: "Assistant replacement" });+ }+ if (change === "cloud")+ database.db.prepare("UPDATE notes SET content = 'Remote edit' WHERE id = ?").run(note.id);+ if (change === "deleted") database.updateNote(note.id, { deleted_at: "2026-10-09" });+ if (change === "hard deleted")+ database.db.prepare("DELETE FROM notes WHERE id = ?").run(note.id);+ if (change === "identity")+ database.updateNote(note.id, { client_note_id: "replacement-identity" });+ if (change === "dirty draft") database.discardNoteUndo(note.id);+ const before = database.getNote(note.id);+ assert.equal(database.undoNoteUpdate(token).success, false);+ assert.deepEqual(database.getNote(note.id), before);+ });++ await t.test(+ "sync acknowledgement preserves Undo and unrelated notes have independent tokens",+ async () => {+ const one = fresh(),+ two = fresh();+ await edit(one, { title: "One" });+ const token = tokenFor(one.id);+ await edit(two, { title: "Two" });+ database.updateNote(one.id, { sync_status: "synced", cloud_updated_at: "2026-10-09" });+ assert.equal(database.undoNoteUpdate(token).success, true);+ assert.equal(database.getNote(two.id).title, "Two");+ assert.ok(tokenFor(two.id));+ }+ );++ await t.test("first cloud create acknowledgement keeps recovery", async () => {+ const note = fresh();+ await edit(note, { title: "Synced edit" });+ const token = tokenFor(note.id);+ const snapshot = database.getNote(note.id);+ const ack = database.acknowledgeNoteCreate(+ note.id,+ snapshot,+ `cloud-${note.id}`,+ "2026-10-09",+ "owner-one"+ );+ assert.equal(ack.outcome, "synced");+ assert.equal(tokenFor(note.id), token);+ assert.equal(database.undoNoteUpdate(token).success, true);+ assert.equal(database.getNote(note.id).title, note.title);+ });++ await t.test("journal failure rolls back the edit; failed Undo retains recovery", async () => {+ const note = fresh();+ database.db.exec(+ "CREATE TEMP TRIGGER fail_undo_journal BEFORE INSERT ON assistant_note_undo BEGIN SELECT RAISE(ABORT, 'disk full'); END"+ );+ assert.equal((await edit(note, { title: "Must roll back" })).success, false);+ database.db.exec("DROP TRIGGER fail_undo_journal");+ assert.equal(database.getNote(note.id).title, note.title);+ assert.equal(tokenFor(note.id), undefined);+ await edit(note, { title: "Recoverable" });+ const token = tokenFor(note.id);+ const failure = t.mock.method(database, "updateNote", () => ({+ success: false,+ error: "disk full",+ }));+ assert.equal(database.undoNoteUpdate(token).success, false);+ failure.mock.restore();+ assert.equal(tokenFor(note.id), token);+ assert.equal(database.getNote(note.id).title, "Recoverable");+ });++ await t.test("a removal that would leave a field empty is pointed to clear_fields", async () => {+ const note = fresh();+ const result = await edit(note, { summary: " " });+ assert.equal(result.success, false);+ assert.match(result.displayText, /removal that leaves nothing\), use clear_fields/);+ const renamed = await edit(note, { title: "", folder: " ", content: "Kept" });+ assert.equal(renamed.success, true);+ assert.deepEqual(renamed.data.ignoredFields, ["title", "folder"]);+ assert.doesNotMatch(renamed.data.guidance, /clear_fields/);+ assert.equal(database.getNote(note.id).title, note.title);+ });++ await t.test("a trashed note is not edited", async () => {+ const note = fresh();+ database.updateNote(note.id, { deleted_at: "2026-10-09" });+ const result = await edit(note, { title: "Edited in the trash" });+ assert.equal(result.success, false);+ assert.match(result.displayText, /in the trash/);+ const trashed = database.getNote(note.id);+ assert.equal(+ database.updateNote(note.id, { title: "Direct" }, { undoable: true, expected: trashed })+ .success,+ false+ );+ assert.equal(database.getNote(note.id).title, note.title);+ assert.equal(tokenFor(note.id), undefined);+ });++ await t.test("an unchanged or unsupported edit writes nothing", async () => {+ const note = fresh();+ database.updateNote(note.id, { sync_status: "synced" });+ assert.equal((await edit(note, { title: note.title })).success, true);+ database.updateNote(note.id, { content: "" });+ database.updateNote(note.id, { sync_status: "synced" });+ assert.equal((await edit(note, { clear_fields: ["content"] })).success, true);+ assert.equal(database.getNote(note.id).sync_status, "synced");+ assert.equal(tokenFor(note.id), undefined);+ const direct = database.updateNote(+ note.id,+ { transcript: "Rewritten" },+ { undoable: true, expected: database.getNote(note.id) }+ );+ assert.equal(direct.success, false);+ 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("a toast's discard retires only its own recovery", async () => {+ const note = fresh();+ await edit(note, { title: "First" });+ const first = tokenFor(note.id);+ await edit(note, { title: "Second" });+ const second = tokenFor(note.id);+ database.discardNoteUndo(note.id, first);+ assert.equal(tokenFor(note.id), second);+ database.discardNoteUndo(note.id, second);+ assert.equal(tokenFor(note.id), undefined);+ });++ await t.test(+ "a folder that moved to another space is neither a target nor restored",+ async () => {+ database.setActiveAccountId("account-team");+ const team = database.db+ .prepare(+ "INSERT INTO spaces (client_space_id, kind, name) VALUES ('undo-team', 'team', 'Team')"+ )+ .run().lastInsertRowid;+ database.db+ .prepare("INSERT INTO space_accounts (space_id, account_id) VALUES (?, 'account-team')")+ .run(team);+ const moveToTeam = (folder) =>+ database.db.prepare("UPDATE folders SET space_id = ? WHERE id = ?").run(team, folder.id);+ const note = fresh();+ const target = database.createFolder(`Target ${note.id}`, note.space_id).folder;+ moveToTeam(target);+ const refused = database.updateNote(+ note.id,+ { folder_id: target.id },+ { undoable: true, expected: note }+ );+ assert.equal(refused.success, false);+ assert.equal(database.getNote(note.id).space_id, note.space_id);++ const original = database.createFolder(`Original ${note.id}`, note.space_id).folder;+ database.updateNote(note.id, { folder_id: original.id });+ await edit(database.getNote(note.id), { folder: `Moved ${note.id}` });+ moveToTeam(original);+ assert.equal(database.undoNoteUpdate(tokenFor(note.id)).success, false);+ assert.equal(database.getNote(note.id).space_id, note.space_id);+ database.setActiveAccountId(null);+ }+ );++ await t.test("a journal of an earlier shape is replaced at launch", async () => {+ database.db.exec(`+ DROP TABLE assistant_note_undo;+ CREATE TABLE assistant_note_undo (note_id INTEGER PRIMARY KEY, token TEXT, previous TEXT);+ `);+ initializeNoteUndo(database.db);+ const note = fresh();+ await edit(note, { title: "After repair" });+ assert.equal(database.undoNoteUpdate(tokenFor(note.id)).success, true);+ });++ await t.test("a setup that fails after dropping the journal leaves note writes working", (t) => {+ database.db.exec(`+ DROP TABLE assistant_note_undo;+ CREATE TABLE assistant_note_undo (note_id INTEGER PRIMARY KEY, token TEXT, previous TEXT);+ `);+ const exec = database.db.exec.bind(database.db);+ const failure = t.mock.method(database.db, "exec", (sql) => {+ if (sql.includes("CREATE TABLE")) throw new Error("SQLITE_FULL: database or disk is full");+ return exec(sql);+ });+ assert.throws(() => initializeNoteUndo(database.db), /SQLITE_FULL/);+ failure.mock.restore();+ const note = fresh();+ assert.equal(database.updateNote(note.id, { title: "Plain edit" }).success, true);+ initializeNoteUndo(database.db);+ });++ await t.test("without the journal, assistant edits still save", async () => {+ database.noteUndoReady = false;+ try {+ const note = fresh();+ assert.equal((await edit(note, { title: "No journal" })).success, true);+ assert.equal(database.getNote(note.id).title, "No journal");+ assert.deepEqual(database.getNoteUndos(), []);+ assert.equal(database.claimNoteUndo("any"), false);+ database.discardNoteUndo(note.id);+ } finally {+ database.noteUndoReady = true;+ }+ });++ await t.test("real account scope hides and refuses another account's recovery", async () => {+ database.setActiveAccountId("account-one");+ const note = fresh();+ await edit(note, { title: "Account one edit" });+ const token = tokenFor(note.id);+ assert.ok(token);+ database.setActiveAccountId("account-two");+ assert.equal(database.getNote(note.id), null);+ assert.equal(tokenFor(note.id), undefined);+ assert.equal(database.claimNoteUndo(token), false);+ assert.equal(database.undoNoteUpdate(token).success, false);+ database.setActiveAccountId("account-one");+ assert.equal(database.undoNoteUpdate(token).success, true);+ database.setActiveAccountId(null);+ });++ await t.test(+ "recovery remains bound to the originating account even for a shared local note",+ async () => {+ database.setActiveAccountId(null);+ const note = fresh();+ await edit(note, { title: "Signed-out edit" });+ const token = tokenFor(note.id);+ database.setActiveAccountId("another-account");+ assert.ok(database.getNote(note.id), "legacy local note remains readable by design");+ assert.equal(tokenFor(note.id), undefined);+ assert.equal(database.undoNoteUpdate(token).success, false);+ database.setActiveAccountId(null);+ assert.equal(database.undoNoteUpdate(token).success, true);+ assert.equal(database.getNote(note.id).title, note.title);+ }+ );++ await t.test("concurrent changes before commit fail truthfully", async () => {+ const note = fresh();+ const stub = t.mock.method(+ globalThis.window.electronAPI,+ "updateNote",+ async (id, updates, options) => {+ database.updateNote(id, { content: "Concurrent edit" });+ return database.updateNote(id, updates, options);+ }+ );+ const result = await edit(note, { summary: "New summary" });+ stub.mock.restore();+ assert.equal(result.success, false);+ assert.match(result.displayText, /Note changed/);+ assert.equal(database.getNote(note.id).content, "Concurrent edit");+ assert.equal(database.getNote(note.id).enhanced_content, note.enhanced_content);+ assert.equal(tokenFor(note.id), undefined);+ });++ await t.test("deleted previous folder and account switch cannot restore", async () => {+ const note = fresh();+ const folder = database.createFolder(`Original ${note.id}`, note.space_id).folder;+ database.updateNote(note.id, { folder_id: folder.id });+ await edit(note, { folder: `New ${note.id}` });+ const token = tokenFor(note.id);+ database.db.prepare("UPDATE folders SET deleted_at = '2026-10-09' WHERE id = ?").run(folder.id);+ assert.equal(database.undoNoteUpdate(token).success, false);+ const accountNote = fresh();+ await edit(accountNote, { title: "Changed" });+ const accountToken = tokenFor(accountNote.id);+ const scoped = t.mock.method(database, "getNote", () => null);+ assert.equal(database.undoNoteUpdate(accountToken).success, false);+ scoped.mock.restore();+ assert.equal(database.getNote(accountNote.id).title, "Changed");+ });+});diff --git a/test/services/noteEditPersistence.test.js b/test/services/noteEditPersistence.test.jsindex a42ef3c62..ff5d0f29b 100644--- a/test/services/noteEditPersistence.test.js+++ b/test/services/noteEditPersistence.test.js@@ -41,7 +41,7 @@ test("note edits preserve separate stored fields, reopen correctly, and report fwindow: {electronAPI: {getNote: async (id) => database.getNote(id),- updateNote: async (id, updates) => database.updateNote(id, updates),+ updateNote: async (id, updates, options) => database.updateNote(id, updates, options),},},});@@ -86,11 +86,29 @@ test("note edits preserve separate stored fields, reopen correctly, and report fassert.deepEqual(result.data.updatedFields, ["summary"]);});+ await t.test("rename with unrelated blank fields preserves both documents", async () => {+ const before = database.getNote(note.id);+ const result = await updateNoteTool.execute({+ id: note.id,+ title: "Renamed",+ content: "",+ summary: "",+ });+ assert.equal(result.success, true);+ assert.equal(database.getNote(note.id).content, before.content);+ assert.equal(database.getNote(note.id).enhanced_content, before.enhanced_content);+ });await t.test("explicit empty summary and content clear only the chosen field", async () => {- assert.equal((await updateNoteTool.execute({ id: note.id, summary: "" })).success, true);+ assert.equal(+ (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).content, CONTENT);- assert.equal((await updateNoteTool.execute({ id: note.id, content: "" })).success, true);+ assert.equal(+ (await updateNoteTool.execute({ id: note.id, clear_fields: ["content"] })).success,+ true+ );assert.equal(database.getNote(note.id).content, "");database.updateNote(note.id, { content: CONTENT, enhanced_content: SUMMARY });});