Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-3717]): arm the force-save override from the server's verdict, not a blind retry count
[._.]/ Adam Eivy311b85b51d5c
diff --git a/client/src/components/ForceSaveNoteRow.jsx b/client/src/components/ForceSaveNoteRow.jsxnew file mode 100644index 0000000000..f4642e3189--- /dev/null+++ b/client/src/components/ForceSaveNoteRow.jsx@@ -0,0 +1,30 @@+import InlineConfirmRow from './ui/InlineConfirmRow';++/**+ * "iCloud won't let this note save — write it anyway?" confirm row (#3717).+ *+ * Shown by an Obsidian note editor once `useNoteSave` reports `forceOffered`:+ * the server has twice refused this note with a verdict that retrying cannot+ * clear (see the hook for the two conditions). Confirming issues the write past+ * the guard, which is why this is a row the user has to answer and never an+ * automatic retry.+ *+ * Renders nothing when not offered, so callers can drop it in unconditionally.+ * Shared by Brain Notes and the Wiki browser — the same lockout is reachable+ * from both, and the copy must not drift between them.+ */+export default function ForceSaveNoteRow({ offered, onConfirm, onCancel }) {+ if (!offered) return null;+ return (+ <InlineConfirmRow+ variant="separator"+ tone="warning"+ question="iCloud keeps reporting this note as not downloaded, so saving is refused. Write it anyway?"+ confirmText="Save anyway"+ confirmTitle="Bypass the iCloud download check and write this note"+ cancelText="Keep waiting"+ onConfirm={onConfirm}+ onCancel={onCancel}+ />+ );+}diff --git a/client/src/components/brain/tabs/NotesTab.jsx b/client/src/components/brain/tabs/NotesTab.jsxindex 90e64fc991..9a7e17609e 100644--- a/client/src/components/brain/tabs/NotesTab.jsx+++ b/client/src/components/brain/tabs/NotesTab.jsx@@ -24,9 +24,10 @@ import InlineConfirmRow from '../../ui/InlineConfirmRow';import FolderPicker from '../../FolderPicker';import { timeAgo, formatBytes } from '../../../utils/formatters';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';-import { useForceSaveGate } from '../../../hooks/useForceSaveGate.js';+import { useNoteSave } from '../../../hooks/useNoteSave.js';import { clickableProps } from '../../../lib/a11yKeyboard.js';import OfflineNotesNotice from '../../OfflineNotesNotice.jsx';+import ForceSaveNoteRow from '../../ForceSaveNoteRow.jsx';export default function NotesTab() {// Vault state@@ -50,7 +51,6 @@ export default function NotesTab() {const [selectedNote, setSelectedNote] = useState(null);const [noteContent, setNoteContent] = useState('');const [editing, setEditing] = useState(false);- const [saving, setSaving] = useState(false);const [loadingNote, setLoadingNote] = useState(false);// Search state@@ -73,12 +73,12 @@ export default function NotesTab() {// Confirm deleteconst { isConfirming: isConfirmingDelete, requestDelete, cancelDelete } = useConfirmDelete();- // Escape hatch for a note the iCloud dataless screen refuses to save (#3717).- const {- isArmed: isForceSaveArmed,- recordFailure: recordEvictedSave,- reset: resetForceSave- } = useForceSaveGate();+ // Owns the write plus the iCloud force-save escape hatch (#3717).+ const { saving, save, forceOffered, dismissForce } = useNoteSave({+ vaultId: selectedVaultId,+ notePath: selectedNote?.path || null,+ content: noteContent+ });const searchRef = useRef(null);const editorRef = useRef(null);@@ -161,26 +161,15 @@ export default function NotesTab() {setLoadingNote(false);};- // `force` bypasses the server's iCloud dataless screen and is ONLY ever passed- // from the "Save anyway" override the gate arms after two consecutive- // NOTE_EVICTED refusals (#3717) — never from the Save button or ⌘S.- const handleSaveNote = async ({ force = false } = {}) => {- if (!selectedNote) return;- const notePath = selectedNote.path;- setSaving(true);- const data = await api.updateNote(selectedVaultId, notePath, noteContent, { force })- .catch((err) => {- if (err?.code === 'NOTE_EVICTED') recordEvictedSave(notePath);- return null;- });- setSaving(false);- if (data) {- resetForceSave();- setSelectedNote(data);- setEditing(false);- toast.success('Note saved');- loadNotes(); // Refresh metadata- }+ // `force` is ONLY ever passed by <ForceSaveNoteRow>'s confirm (#3717) — never+ // by the Save button or ⌘S.+ const handleSaveNote = async (options) => {+ const data = await save(options);+ if (!data) return;+ setSelectedNote(data);+ setEditing(false);+ toast.success('Note saved');+ loadNotes(); // Refresh metadata};const handleCreateNote = async () => {@@ -538,19 +527,11 @@ export default function NotesTab() {/>)}- {/* Force-save escape hatch: only after two consecutive iCloud refusals (#3717) */}- {isForceSaveArmed(selectedNote.path) && (- <InlineConfirmRow- variant="separator"- tone="warning"- question="iCloud keeps reporting this note as not downloaded, so saving is refused. Write it anyway?"- confirmText="Save anyway"- confirmTitle="Bypass the iCloud download check and write this note"- cancelText="Keep waiting"- onConfirm={() => handleSaveNote({ force: true })}- onCancel={resetForceSave}- />- )}+ <ForceSaveNoteRow+ offered={forceOffered}+ onConfirm={() => handleSaveNote({ force: true })}+ onCancel={dismissForce}+ />{/* Note content */}<div className="flex-1 min-h-0 overflow-auto flex">diff --git a/client/src/components/brain/tabs/NotesTab.test.jsx b/client/src/components/brain/tabs/NotesTab.test.jsxindex 99ed5e7f6a..ba4bc076c8 100644--- a/client/src/components/brain/tabs/NotesTab.test.jsx+++ b/client/src/components/brain/tabs/NotesTab.test.jsx@@ -148,7 +148,11 @@ describe('NotesTab header touch targets', () => {*/describe('NotesTab iCloud force save', () => {const NOTE = { path: 'a.md', name: 'a', folder: '', size: 12, tags: [], modifiedAt: new Date().toISOString() };- const evicted = () => Object.assign(new Error('evicted'), { code: 'NOTE_EVICTED' });+ // A refusal the server flags as `stalled` — its own before/after check found+ // the download moved nothing, so retrying provably cannot clear it. Only this+ // shape may arm the override.+ const evicted = ({ stalled = true } = {}) =>+ Object.assign(new Error('evicted'), { code: 'NOTE_EVICTED', context: { stalled } });const openEditor = async () => {await renderTab();@@ -207,4 +211,17 @@ describe('NotesTab iCloud force save', () => {expect(screen.queryByRole('button', { name: 'Save anyway' })).toBeNull();});++ it('does not arm while a download is genuinely in flight', async () => {+ // The transient case: waiting IS the right answer, and forcing here would+ // issue the blocking write the guard exists to prevent. An impatient user+ // clicking Save twice must not be handed the override.+ api.updateNote.mockRejectedValue(evicted({ stalled: false }));+ await openEditor();++ await clickSave();+ await clickSave();++ expect(screen.queryByRole('button', { name: 'Save anyway' })).toBeNull();+ });});diff --git a/client/src/components/wiki/tabs/BrowseTab.jsx b/client/src/components/wiki/tabs/BrowseTab.jsxindex ac6c216657..5398bac608 100644--- a/client/src/components/wiki/tabs/BrowseTab.jsx+++ b/client/src/components/wiki/tabs/BrowseTab.jsx@@ -10,7 +10,8 @@ import { timeAgo, formatBytes } from '../../../utils/formatters';import { WIKI_CATEGORIES } from '../constants.jsx';import BrailleSpinner from '../../BrailleSpinner';import OfflineNotesNotice from '../../OfflineNotesNotice.jsx';-import { useForceSaveGate } from '../../../hooks/useForceSaveGate.js';+import { useNoteSave } from '../../../hooks/useNoteSave.js';+import ForceSaveNoteRow from '../../ForceSaveNoteRow.jsx';const WIKI_FOLDERS = WIKI_CATEGORIES.map(c => ({ key: c.folder, label: c.label, icon: c.icon, color: c.textClass }));const RAW_FOLDERS = [{ key: 'raw', label: 'Raw Sources', icon: FolderOpen, color: 'text-gray-400' }];@@ -20,7 +21,6 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefresconst [selectedNote, setSelectedNote] = useState(null);const [noteContent, setNoteContent] = useState('');const [editing, setEditing] = useState(false);- const [saving, setSaving] = useState(false);const [loadingNote, setLoadingNote] = useState(false);const [expandedFolders, setExpandedFolders] = useState(new Set(['wiki/sources', 'wiki/entities', 'wiki/concepts']));const [activeSection, setActiveSection] = useState('wiki');@@ -31,12 +31,12 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefresconst [confirmDelete, setConfirmDelete] = useState(null);const editorRef = useRef(null);- // Escape hatch for a note the iCloud dataless screen refuses to save (#3717).- const {- isArmed: isForceSaveArmed,- recordFailure: recordEvictedSave,- reset: resetForceSave- } = useForceSaveGate();+ // Owns the write plus the iCloud force-save escape hatch (#3717).+ const { saving, save, forceOffered, dismissForce } = useNoteSave({+ vaultId,+ notePath: selectedNote?.path || null,+ content: noteContent+ });// Handle deep-link from overviewuseEffect(() => {@@ -56,26 +56,15 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefressetLoadingNote(false);};- // `force` bypasses the server's iCloud dataless screen and is ONLY ever passed- // from the "Save anyway" override the gate arms after two consecutive- // NOTE_EVICTED refusals (#3717) — never from the Save button or ⌘S.- const handleSaveNote = async ({ force = false } = {}) => {- if (!selectedNote) return;- const notePath = selectedNote.path;- setSaving(true);- const data = await api.updateNote(vaultId, notePath, noteContent, { force })- .catch((err) => {- if (err?.code === 'NOTE_EVICTED') recordEvictedSave(notePath);- return null;- });- setSaving(false);- if (data) {- resetForceSave();- setSelectedNote(data);- setEditing(false);- toast.success('Note saved');- onRefresh();- }+ // `force` is ONLY ever passed by <ForceSaveNoteRow>'s confirm (#3717) — never+ // by the Save button or ⌘S.+ const handleSaveNote = async (options) => {+ const data = await save(options);+ if (!data) return;+ setSelectedNote(data);+ setEditing(false);+ toast.success('Note saved');+ onRefresh();};const handleDeleteNote = async (notePath) => {@@ -298,19 +287,11 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres/>)}- {/* Force-save escape hatch: only after two consecutive iCloud refusals (#3717) */}- {isForceSaveArmed(selectedNote.path) && (- <InlineConfirmRow- variant="separator"- tone="warning"- question="iCloud keeps reporting this note as not downloaded, so saving is refused. Write it anyway?"- confirmText="Save anyway"- confirmTitle="Bypass the iCloud download check and write this note"- cancelText="Keep waiting"- onConfirm={() => handleSaveNote({ force: true })}- onCancel={resetForceSave}- />- )}+ <ForceSaveNoteRow+ offered={forceOffered}+ onConfirm={() => handleSaveNote({ force: true })}+ onCancel={dismissForce}+ />{/* Note content */}<div className="flex-1 min-h-0 overflow-auto flex">diff --git a/client/src/components/wiki/tabs/BrowseTab.test.jsx b/client/src/components/wiki/tabs/BrowseTab.test.jsxindex 461d572c80..e576c95b63 100644--- a/client/src/components/wiki/tabs/BrowseTab.test.jsx+++ b/client/src/components/wiki/tabs/BrowseTab.test.jsx@@ -73,7 +73,10 @@ describe('BrowseTab responsive list/detail', () => {* here, and it must stay shut until the same page has been refused twice.*/describe('BrowseTab iCloud force save', () => {- const evicted = () => Object.assign(new Error('evicted'), { code: 'NOTE_EVICTED' });+ // Only a refusal the server flags as `stalled` (retrying cannot help) may arm+ // the override; a transient one must not.+ const evicted = ({ stalled = true } = {}) =>+ Object.assign(new Error('evicted'), { code: 'NOTE_EVICTED', context: { stalled } });beforeEach(() => {vi.clearAllMocks();@@ -123,4 +126,14 @@ describe('BrowseTab iCloud force save', () => {expect(screen.queryByRole('button', { name: 'Save anyway' })).toBeNull();});++ it('does not arm while a download is genuinely in flight', async () => {+ api.updateNote.mockRejectedValue(evicted({ stalled: false }));+ await openEditor();++ await clickSave();+ await clickSave();++ expect(screen.queryByRole('button', { name: 'Save anyway' })).toBeNull();+ });});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 2a966af877..de6a0d2a25 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -96,7 +96,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useConfirmDelete` | Single-at-a-time `{ confirmingId, isConfirming, requestDelete, cancelDelete, confirmDelete }` for arming one list/card row at a time. | New destructive list action — pair with `<InlineConfirmRow>` / `<ConfirmButtonPair>` instead of deleting on the raw trash click. || `useEscapeKey` | `useEscapeKey(active, handler)` — call `handler` on Escape while `active`. | Non-modal dismissables (in-context popovers/cards); Modal owns Esc for true modals. || `useFocusTrap` | `useFocusTrap(active, containerRef, { initialFocusRef? })` — moves focus into the container on open, traps Tab/Shift+Tab so it can't escape to the page behind, and restores focus to the opener on close (WCAG 2.4.3 / 2.1.2). | Modal surfaces (dialogs, drawers, lightboxes). Already wired into `Modal` and `Drawer` — reach for it when hand-rolling a new overlay. |-| `useForceSaveGate` | `useForceSaveGate(threshold = 2)` → `{ isArmed(key), recordFailure(key), reset() }` — reveals a deliberate "do it anyway" override only after the SAME target fails N times in a row; keyed by target, so switching targets disarms. | A guard legitimately refuses an action but can false-positive and lock the user out (iCloud-evicted note save, #3717). Pair with `<InlineConfirmRow tone="warning">`; never wire the override as the retry default. |+| `useNoteSave` | `useNoteSave({ vaultId, notePath, content })` → `{ saving, save({ force }), forceOffered, dismissForce }` — writes an Obsidian note and owns the iCloud force-save escape hatch: `forceOffered` turns on only after the server has twice refused the SAME note with a `stalled` (retrying-cannot-help) verdict. | Any editor that saves a vault note. Render `<ForceSaveNoteRow offered={forceOffered}>` next to the editor; never call `save({ force: true })` from anything but that row's confirm. || `useCmdKSearch` | `⌘K` open/close state. | Anywhere that needs to toggle the palette. || `useContainerWidth` | `[ref, width]` via ResizeObserver. | Layout responds to a specific container's width. || `useCooldownTick` | 1-second ticker over a `{ id: epochMs }` cooldown map; fires `onAllExpired` once when every deadline passes. | Rate-limit countdown labels that need to refetch when the last cooldown clears (agents tabs pattern). |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 2510a2c1f5..9f5fcfc34c 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -23,7 +23,7 @@ export { default as useContainerWidth } from './useContainerWidth.js';export { default as useEscapeKey } from './useEscapeKey.js';export { default as useFieldDraft } from './useFieldDraft.js';export { default as useFocusTrap } from './useFocusTrap.js';-export { default as useForceSaveGate } from './useForceSaveGate.js';+export { default as useNoteSave } from './useNoteSave.js';export { default as useImageGenQueue } from './useImageGenQueue.js';export { default as useImageRenderSettings } from './useImageRenderSettings.js';export { default as useUserTimezone } from './useUserTimezone.js';diff --git a/client/src/hooks/useForceSaveGate.js b/client/src/hooks/useForceSaveGate.jsdeleted file mode 100644index 9dfc584a10..0000000000--- a/client/src/hooks/useForceSaveGate.js+++ /dev/null@@ -1,48 +0,0 @@-import { useCallback, useState } from 'react';--/**- * Arm a deliberate "do it anyway" override after N consecutive failures against- * the SAME target.- *- * Built for the iCloud force-save escape hatch (#3717): an Obsidian note whose- * bytes look offloaded is refused rather than written, because overwriting a- * dataless file blocks the process. That screen can false-positive on a- * genuinely-local file, and when it does the refusal is permanent — so the user- * needs a way through. The override must never be the *default* retry path- * (it re-admits exactly the blocking write the guard exists to prevent), so it- * stays hidden until the same target has failed twice in a row and then requires- * its own explicit click.- *- * Keyed by target, so switching to a different note disarms automatically and a- * one-off failure elsewhere can't arm the note you're looking at.- *- * Returns:- * isArmed(key) — true once `key` has failed `threshold` times in a row- * recordFailure(key)— count one failure for `key` (resets the count on a switch)- * reset() — disarm (wire to a successful save and to the row's cancel)- *- * @param {number} [threshold=2] - consecutive failures before the override shows.- */-export function useForceSaveGate(threshold = 2) {- const [failure, setFailure] = useState({ key: null, count: 0 });-- const recordFailure = useCallback((key) => {- setFailure(prev => (prev.key === key ? { key, count: prev.count + 1 } : { key, count: 1 }));- }, []);-- // Returning the same object when already clear keeps the common case — every- // successful save calls this — from re-rendering the editor for nothing.- const reset = useCallback(- () => setFailure(prev => (prev.key === null ? prev : { key: null, count: 0 })),- [],- );-- const isArmed = useCallback(- (key) => Boolean(key) && failure.key === key && failure.count >= threshold,- [failure, threshold],- );-- return { isArmed, recordFailure, reset };-}--export default useForceSaveGate;diff --git a/client/src/hooks/useForceSaveGate.test.jsx b/client/src/hooks/useForceSaveGate.test.jsxdeleted file mode 100644index f512ab8f74..0000000000--- a/client/src/hooks/useForceSaveGate.test.jsx+++ /dev/null@@ -1,74 +0,0 @@-/**- * useForceSaveGate — #3717.- *- * The gate guards an override that re-admits the exact blocking write the iCloud- * dataless screen exists to prevent. So the properties worth pinning are the ones- * that keep it SHUT: it must not arm on a single failure, must not carry across- * notes, and must close again the moment a save succeeds.- */--import { describe, it, expect } from 'vitest';-import { renderHook, act } from '@testing-library/react';-import { useForceSaveGate } from './useForceSaveGate.js';--describe('useForceSaveGate', () => {- it('stays disarmed after a single failure', () => {- const { result } = renderHook(() => useForceSaveGate());-- act(() => result.current.recordFailure('a.md'));-- expect(result.current.isArmed('a.md')).toBe(false);- });-- it('arms on the second consecutive failure for the same target', () => {- const { result } = renderHook(() => useForceSaveGate());-- act(() => result.current.recordFailure('a.md'));- act(() => result.current.recordFailure('a.md'));-- expect(result.current.isArmed('a.md')).toBe(true);- });-- it('never arms a target the user is not looking at', () => {- const { result } = renderHook(() => useForceSaveGate());-- act(() => result.current.recordFailure('a.md'));- act(() => result.current.recordFailure('a.md'));-- expect(result.current.isArmed('b.md')).toBe(false);- expect(result.current.isArmed(null)).toBe(false);- expect(result.current.isArmed(undefined)).toBe(false);- });-- it('restarts the count when the target changes', () => {- const { result } = renderHook(() => useForceSaveGate());-- act(() => result.current.recordFailure('a.md'));- act(() => result.current.recordFailure('b.md'));-- // Two failures total, but not two in a row on either note.- expect(result.current.isArmed('a.md')).toBe(false);- expect(result.current.isArmed('b.md')).toBe(false);- });-- it('disarms on reset', () => {- const { result } = renderHook(() => useForceSaveGate());-- act(() => result.current.recordFailure('a.md'));- act(() => result.current.recordFailure('a.md'));- act(() => result.current.reset());-- expect(result.current.isArmed('a.md')).toBe(false);- });-- it('honors a custom threshold', () => {- const { result } = renderHook(() => useForceSaveGate(3));-- act(() => result.current.recordFailure('a.md'));- act(() => result.current.recordFailure('a.md'));- expect(result.current.isArmed('a.md')).toBe(false);-- act(() => result.current.recordFailure('a.md'));- expect(result.current.isArmed('a.md')).toBe(true);- });-});diff --git a/client/src/hooks/useNoteSave.js b/client/src/hooks/useNoteSave.jsnew file mode 100644index 0000000000..05841d1a54--- /dev/null+++ b/client/src/hooks/useNoteSave.js@@ -0,0 +1,77 @@+import { useCallback, useState } from 'react';+import * as api from '../services/api';++// Consecutive non-transient refusals of the SAME note before the force-save+// override is offered. One is a bad-luck threshold: it would put a "write+// anyway" button in front of a user who has seen a single hiccup.+const REFUSALS_BEFORE_FORCE = 2;++const CLEARED = { path: null, count: 0 };++/**+ * Save an Obsidian note, with the iCloud force-save escape hatch (#3717).+ *+ * The server refuses to overwrite a note whose bytes look offloaded to iCloud,+ * because that write blocks the process uninterruptibly. The screen infers+ * "offloaded" from a real byte length with no local blocks, which an ordinary+ * sparse or `decmpfs`-compressed file also reports — and when it misfires, the+ * refusal is permanent: asking iCloud to download an already-local file succeeds+ * instantly and changes nothing. So the user needs a way through.+ *+ * Two conditions gate that override, and both matter:+ *+ * 1. The server must report the refusal as `stalled` — its own before/after+ * check found the download moved nothing, so retrying provably cannot help.+ * A genuinely in-flight download must NEVER arm the override; waiting is the+ * right answer there, and forcing would issue the blocking write the guard+ * exists to prevent.+ * 2. It must have happened twice in a row on the same note, and then it still+ * takes its own explicit click. The override is never a retry default.+ *+ * Both editors that write notes (Brain Notes, Wiki Browse) use this, so the+ * policy lives in one place rather than being mirrored into each of them.+ *+ * @param {object} params+ * @param {string} params.vaultId+ * @param {string|null} params.notePath - vault-relative path of the open note.+ * @param {string} params.content - editor buffer to write.+ * @returns {{ saving: boolean, save: (opts?: { force?: boolean }) => Promise<object|null>,+ * forceOffered: boolean, dismissForce: () => void }}+ * `save` resolves the updated note, or `null` when the write did not happen+ * (the API layer has already toasted the reason).+ */+export function useNoteSave({ vaultId, notePath, content }) {+ const [saving, setSaving] = useState(false);+ const [refusal, setRefusal] = useState(CLEARED);++ // Returning the previous object when already clear keeps the common case —+ // every successful save calls this — from re-rendering the editor for nothing.+ const clearRefusals = useCallback(+ () => setRefusal(prev => (prev.path === null ? prev : CLEARED)),+ [],+ );++ const save = useCallback(async ({ force = false } = {}) => {+ if (!notePath) return null;+ setSaving(true);+ const data = await api.updateNote(vaultId, notePath, content, { force }).catch((err) => {+ if (err?.code === 'NOTE_EVICTED' && err.context?.stalled) {+ setRefusal(prev => (+ prev.path === notePath ? { path: notePath, count: prev.count + 1 } : { path: notePath, count: 1 }+ ));+ }+ return null;+ });+ setSaving(false);+ if (data) clearRefusals();+ return data;+ }, [vaultId, notePath, content, clearRefusals]);++ const forceOffered = Boolean(notePath)+ && refusal.path === notePath+ && refusal.count >= REFUSALS_BEFORE_FORCE;++ return { saving, save, forceOffered, dismissForce: clearRefusals };+}++export default useNoteSave;diff --git a/client/src/hooks/useNoteSave.test.jsx b/client/src/hooks/useNoteSave.test.jsxnew file mode 100644index 0000000000..1c6d5e6af5--- /dev/null+++ b/client/src/hooks/useNoteSave.test.jsx@@ -0,0 +1,123 @@+/**+ * useNoteSave — the iCloud force-save escape hatch (#3717).+ *+ * The override this hook gates re-admits exactly the blocking write the server's+ * dataless screen exists to prevent, so the properties worth pinning are the ones+ * that keep it SHUT: it opens only for a refusal the server says retrying cannot+ * clear, only after two of those in a row on the same note, and it closes again+ * the moment a save succeeds.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';++const api = vi.hoisted(() => ({ updateNote: vi.fn() }));+vi.mock('../services/api', () => api);++const { useNoteSave } = await import('./useNoteSave.js');++const evicted = ({ stalled = true } = {}) =>+ Object.assign(new Error('evicted'), { code: 'NOTE_EVICTED', context: { stalled } });++const setup = (notePath = 'a.md') =>+ renderHook(props => useNoteSave(props), {+ initialProps: { vaultId: 'v1', notePath, content: 'body' },+ });++const failTwice = async (result) => {+ await act(async () => { await result.current.save(); });+ await act(async () => { await result.current.save(); });+};++beforeEach(() => vi.clearAllMocks());++describe('useNoteSave', () => {+ it('saves without forcing and reports the updated note', async () => {+ api.updateNote.mockResolvedValue({ path: 'a.md' });+ const { result } = setup();++ let data;+ await act(async () => { data = await result.current.save(); });++ expect(api.updateNote).toHaveBeenCalledWith('v1', 'a.md', 'body', { force: false });+ expect(data).toEqual({ path: 'a.md' });+ expect(result.current.forceOffered).toBe(false);+ });++ it('offers the override after two stalled refusals of the same note', async () => {+ api.updateNote.mockRejectedValue(evicted());+ const { result } = setup();++ await act(async () => { await result.current.save(); });+ expect(result.current.forceOffered).toBe(false);++ await act(async () => { await result.current.save(); });+ expect(result.current.forceOffered).toBe(true);+ });++ it('never offers it while a download is genuinely in flight', async () => {+ // `stalled: false` means the materialize attempt DID move the file — waiting+ // is the right answer, and forcing would issue the blocking write.+ api.updateNote.mockRejectedValue(evicted({ stalled: false }));+ const { result } = setup();++ await failTwice(result);++ expect(result.current.forceOffered).toBe(false);+ });++ it('ignores refusals that are not the eviction screen', async () => {+ api.updateNote.mockRejectedValue(Object.assign(new Error('nope'), { code: 'INVALID_PATH' }));+ const { result } = setup();++ await failTwice(result);++ expect(result.current.forceOffered).toBe(false);+ });++ it('restarts the count when the open note changes', async () => {+ api.updateNote.mockRejectedValue(evicted());+ const { result, rerender } = setup('a.md');++ await act(async () => { await result.current.save(); });+ rerender({ vaultId: 'v1', notePath: 'b.md', content: 'body' });+ await act(async () => { await result.current.save(); });++ // Two refusals total, but not two in a row on either note.+ expect(result.current.forceOffered).toBe(false);+ });++ it('closes the override on a successful save', async () => {+ api.updateNote.mockRejectedValue(evicted());+ const { result } = setup();+ await failTwice(result);+ expect(result.current.forceOffered).toBe(true);++ api.updateNote.mockResolvedValue({ path: 'a.md' });+ await act(async () => { await result.current.save({ force: true }); });++ expect(api.updateNote).toHaveBeenLastCalledWith('v1', 'a.md', 'body', { force: true });+ expect(result.current.forceOffered).toBe(false);+ });++ it('closes the override on dismiss without writing anything', async () => {+ api.updateNote.mockRejectedValue(evicted());+ const { result } = setup();+ await failTwice(result);++ act(() => result.current.dismissForce());++ expect(result.current.forceOffered).toBe(false);+ expect(api.updateNote).toHaveBeenCalledTimes(2);+ });++ it('is a no-op with no note open', async () => {+ const { result } = setup(null);++ let data;+ await act(async () => { data = await result.current.save(); });++ expect(data).toBeNull();+ expect(api.updateNote).not.toHaveBeenCalled();+ });+});diff --git a/server/routes/notes.js b/server/routes/notes.jsindex d1ac0ee3a4..93e45e5e35 100644--- a/server/routes/notes.js+++ b/server/routes/notes.js@@ -39,7 +39,15 @@ function throwOnError(result, fallbackMessage) {if (result?.error) {throw new ServerError(result.message || result.error, {status: errorStatus(result.error),- code: result.error+ code: result.error,+ // `stalled` is the service's verdict that this refusal is NOT transient —+ // the download changed nothing, so no amount of retrying clears it. It+ // rides the standard `context` channel (sanitized here, re-attached by+ // `apiCore.request` as `err.context`) because it is the only thing allowed+ // to arm the force-save override: a client-side retry counter would arm it+ // during a genuine in-flight download too, handing the user exactly the+ // blocking write this guard exists to prevent (#3717).+ ...(result.stalled === undefined ? {} : { context: { stalled: result.stalled } })});}if (result === null) {diff --git a/server/routes/notes.test.js b/server/routes/notes.test.jsindex 482587be78..b267c09571 100644--- a/server/routes/notes.test.js+++ b/server/routes/notes.test.js@@ -86,6 +86,33 @@ describe('PUT /api/notes/vaults/:id/note force pass-through', () => {expect(obsidian.updateNote).toHaveBeenCalledWith('v1', 'a.md', 'hi', { force: true });});+ it('forwards the stalled verdict so only a hopeless refusal can arm the override', async () => {+ obsidian.updateNote.mockResolvedValue({+ error: 'NOTE_EVICTED',+ stalled: true,+ message: 'iCloud changed nothing',+ });++ const res = await request(app).put('/api/notes/vaults/v1/note?path=a.md').send({ content: 'hi' });++ expect(res.status).toBe(503);+ // Without this the client can only guess, and would arm "Save anyway" during+ // a genuine in-flight download — the blocking write the guard prevents.+ expect(res.body.context).toEqual({ stalled: true });+ });++ it('says stalled:false for a refusal a retry can still clear', async () => {+ obsidian.updateNote.mockResolvedValue({+ error: 'NOTE_EVICTED',+ stalled: false,+ message: 'download in progress',+ });++ const res = await request(app).put('/api/notes/vaults/v1/note?path=a.md').send({ content: 'hi' });++ expect(res.body.context).toEqual({ stalled: false });+ });+it('rejects a non-boolean force rather than coercing it', async () => {const res = await request(app).put('/api/notes/vaults/v1/note?path=a.md').send({ content: 'hi', force: 'yes' });