Skip to content

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

fix([issue-3717]): let the user force-save a note the iCloud dataless screen wrongly refuses

[._.]/ Adam Eivydcb1659f3ae7
diff --git a/client/src/components/brain/tabs/NotesTab.jsx b/client/src/components/brain/tabs/NotesTab.jsx
index cb575285fa..90e64fc991 100644
--- a/client/src/components/brain/tabs/NotesTab.jsx
+++ b/client/src/components/brain/tabs/NotesTab.jsx
@@ -24,6 +24,7 @@ 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 { clickableProps } from '../../../lib/a11yKeyboard.js';
import OfflineNotesNotice from '../../OfflineNotesNotice.jsx';
@@ -72,6 +73,13 @@ export default function NotesTab() {
// Confirm delete
const { 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();
+
const searchRef = useRef(null);
const editorRef = useRef(null);
@@ -153,12 +161,21 @@ export default function NotesTab() {
setLoadingNote(false);
};
- const handleSaveNote = async () => {
+ // `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, selectedNote.path, noteContent).catch(() => null);
+ 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');
@@ -477,7 +494,7 @@ export default function NotesTab() {
{editing ? (
<>
<button
- onClick={handleSaveNote}
+ onClick={() => handleSaveNote()}
disabled={saving}
className="flex items-center gap-1 px-3 py-1.5 rounded bg-port-accent text-white text-sm hover:bg-port-accent/80 disabled:opacity-50"
>
@@ -521,6 +538,20 @@ 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}
+ />
+ )}
+
{/* Note content */}
<div className="flex-1 min-h-0 overflow-auto flex">
{/* Main content area */}
diff --git a/client/src/components/brain/tabs/NotesTab.test.jsx b/client/src/components/brain/tabs/NotesTab.test.jsx
index e6012f17c3..99ed5e7f6a 100644
--- a/client/src/components/brain/tabs/NotesTab.test.jsx
+++ b/client/src/components/brain/tabs/NotesTab.test.jsx
@@ -136,3 +136,75 @@ describe('NotesTab header touch targets', () => {
expect(padRight).toBeGreaterThanOrEqual(rightOffset + clearWidth);
});
});
+
+/**
+ * The iCloud force-save escape hatch — #3717.
+ *
+ * The server refuses to overwrite a note whose bytes look offloaded, because that
+ * write blocks the process. The screen can false-positive on a genuinely-local
+ * file, and when it does no amount of retrying clears it — so the user gets a way
+ * through. These pin BOTH halves: the way through exists, and it never opens on
+ * its own.
+ */
+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' });
+
+ const openEditor = async () => {
+ await renderTab();
+ await act(async () => { fireEvent.click(screen.getByText('a')); });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Edit' })); });
+ };
+
+ const clickSave = async () => {
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Save/ })); });
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getNotesVaults.mockResolvedValue([{ id: 'vault-1', name: 'Example Vault', path: '/example/vault' }]);
+ api.detectNotesVaults.mockResolvedValue([]);
+ api.scanNotesVault.mockResolvedValue({ notes: [NOTE], total: 1 });
+ api.getNotesVaultFolders.mockResolvedValue({ folders: [] });
+ api.getNotesVaultTags.mockResolvedValue({ tags: [] });
+ api.getNote.mockResolvedValue({ ...NOTE, content: 'body', body: 'body', backlinks: [] });
+ });
+
+ it('offers no override on the first refusal', async () => {
+ api.updateNote.mockRejectedValue(evicted());
+ await openEditor();
+
+ await clickSave();
+
+ expect(screen.queryByRole('button', { name: 'Save anyway' })).toBeNull();
+ });
+
+ it('offers the override on the second consecutive refusal and forces only on that click', async () => {
+ api.updateNote.mockRejectedValue(evicted());
+ await openEditor();
+
+ await clickSave();
+ await clickSave();
+
+ // Neither ordinary save may have forced — that would make the override the
+ // retry default and re-admit the blocking write with no user decision.
+ for (const call of api.updateNote.mock.calls) {
+ expect(call[3]).toEqual({ force: false });
+ }
+
+ api.updateNote.mockResolvedValue({ ...NOTE, content: 'body' });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Save anyway' })); });
+
+ expect(api.updateNote).toHaveBeenLastCalledWith('vault-1', 'a.md', 'body', { force: true });
+ });
+
+ it('does not arm on an unrelated failure', async () => {
+ api.updateNote.mockRejectedValue(Object.assign(new Error('nope'), { code: 'INVALID_PATH' }));
+ 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.jsx
index b040a9880d..ac6c216657 100644
--- a/client/src/components/wiki/tabs/BrowseTab.jsx
+++ b/client/src/components/wiki/tabs/BrowseTab.jsx
@@ -10,6 +10,7 @@ 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';
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' }];
@@ -30,6 +31,13 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres
const [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();
+
// Handle deep-link from overview
useEffect(() => {
if (location.state?.openNote) {
@@ -48,12 +56,21 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres
setLoadingNote(false);
};
- const handleSaveNote = async () => {
+ // `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, selectedNote.path, noteContent).catch(() => null);
+ 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');
@@ -237,7 +254,7 @@ export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefres
{editing ? (
<>
<button
- onClick={handleSaveNote}
+ onClick={() => handleSaveNote()}
disabled={saving}
className="flex items-center gap-1 px-3 py-1.5 rounded bg-port-accent text-white text-sm hover:bg-port-accent/80 disabled:opacity-50"
>
@@ -281,6 +298,20 @@ 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}
+ />
+ )}
+
{/* Note content */}
<div className="flex-1 min-h-0 overflow-auto flex">
<div className="flex-1 min-w-0">
diff --git a/client/src/components/wiki/tabs/BrowseTab.test.jsx b/client/src/components/wiki/tabs/BrowseTab.test.jsx
index d59f8d13d6..461d572c80 100644
--- a/client/src/components/wiki/tabs/BrowseTab.test.jsx
+++ b/client/src/components/wiki/tabs/BrowseTab.test.jsx
@@ -66,3 +66,61 @@ describe('BrowseTab responsive list/detail', () => {
await waitFor(() => expect(screen.getByText('Select a page to view')).toBeInTheDocument());
});
});
+
+/**
+ * The iCloud force-save escape hatch — #3717. Mirrored from NotesTab: the same
+ * lockout is reachable from the wiki editor, so the same way out has to be wired
+ * 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' });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getNote.mockResolvedValue(sampleNote);
+ });
+
+ const openEditor = async () => {
+ renderTab();
+ fireEvent.click(screen.getByText('Example Source'));
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));
+ };
+
+ const clickSave = async () => {
+ const before = api.updateNote.mock.calls.length;
+ fireEvent.click(screen.getByRole('button', { name: /Save/ }));
+ await waitFor(() => expect(api.updateNote.mock.calls.length).toBe(before + 1));
+ };
+
+ it('arms "Save anyway" only on the second refusal, and only it forces', async () => {
+ api.updateNote.mockRejectedValue(evicted());
+ await openEditor();
+
+ await clickSave();
+ expect(screen.queryByRole('button', { name: 'Save anyway' })).toBeNull();
+
+ await clickSave();
+ const forceAnyway = await screen.findByRole('button', { name: 'Save anyway' });
+ // An ordinary save must never carry `force` — that would make the override
+ // the retry default and re-admit the blocking write with no user decision.
+ for (const call of api.updateNote.mock.calls) {
+ expect(call[3]).toEqual({ force: false });
+ }
+
+ api.updateNote.mockResolvedValue(sampleNote);
+ fireEvent.click(forceAnyway);
+ await waitFor(() => expect(api.updateNote).toHaveBeenLastCalledWith(
+ 'v1', 'wiki/sources/example.md', sampleNote.content, { force: true }
+ ));
+ });
+
+ it('does not arm on an unrelated save failure', async () => {
+ api.updateNote.mockRejectedValue(Object.assign(new Error('nope'), { code: 'INVALID_PATH' }));
+ 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.md
index c9dc6c85ba..2a966af877 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -96,6 +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. |
| `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.js
index d68140b80e..2510a2c1f5 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -23,6 +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 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.js
new file mode 100644
index 0000000000..9dfc584a10
--- /dev/null
+++ b/client/src/hooks/useForceSaveGate.js
@@ -0,0 +1,48 @@
+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.jsx
new file mode 100644
index 0000000000..f512ab8f74
--- /dev/null
+++ b/client/src/hooks/useForceSaveGate.test.jsx
@@ -0,0 +1,74 @@
+/**
+ * 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/services/apiNotes.js b/client/src/services/apiNotes.js
index fd642ed712..21be212a61 100644
--- a/client/src/services/apiNotes.js
+++ b/client/src/services/apiNotes.js
@@ -30,10 +30,14 @@ export const createNote = (vaultId, path, content = '') => request(`/notes/vault
body: JSON.stringify({ path, content })
});
-export const updateNote = (vaultId, path, content) =>
+// `force` bypasses the server's iCloud dataless screen (#3717). Only ever pass
+// it from an explicit user click on the "Save anyway" override — never as an
+// automatic retry.
+export const updateNote = (vaultId, path, content, { force = false, ...options } = {}) =>
request(`/notes/vaults/${vaultId}/note?path=${encodeURIComponent(path)}`, {
method: 'PUT',
- body: JSON.stringify({ content })
+ body: JSON.stringify({ content, force }),
+ ...options
});
export const deleteNote = (vaultId, path) =>
diff --git a/server/lib/notesValidation.js b/server/lib/notesValidation.js
index a6519a09f8..5920bb2bd7 100644
--- a/server/lib/notesValidation.js
+++ b/server/lib/notesValidation.js
@@ -42,7 +42,11 @@ export const createNoteSchema = z.object({
});
export const updateNoteSchema = z.object({
- content: z.string().max(500000)
+ content: z.string().max(500000),
+ // Deliberate user override for a false-positive iCloud dataless screen (#3717):
+ // bypass the screen and issue the write. Defaults off so every ordinary save —
+ // and every background mirror — keeps the refuse-to-block guard.
+ force: z.boolean().optional().default(false)
});
export const searchQuerySchema = z.object({
diff --git a/server/lib/notesValidation.test.js b/server/lib/notesValidation.test.js
index ac58e1a80a..c4f5d6fb65 100644
--- a/server/lib/notesValidation.test.js
+++ b/server/lib/notesValidation.test.js
@@ -109,6 +109,16 @@ describe('notesValidation', () => {
expect(updateNoteSchema.safeParse({ content: '' }).success).toBe(true);
expect(updateNoteSchema.safeParse({ content: 'updated' }).success).toBe(true);
});
+
+ // #3717: `force` re-admits the blocking write the iCloud screen exists to
+ // prevent, so it must default OFF and must not be reachable by coercion —
+ // a truthy string in a stray body would silently disarm the guard.
+ it('defaults force off and only accepts a real boolean', () => {
+ expect(updateNoteSchema.safeParse({ content: 'x' }).data.force).toBe(false);
+ expect(updateNoteSchema.safeParse({ content: 'x', force: true }).data.force).toBe(true);
+ expect(updateNoteSchema.safeParse({ content: 'x', force: 'true' }).success).toBe(false);
+ expect(updateNoteSchema.safeParse({ content: 'x', force: 1 }).success).toBe(false);
+ });
});
describe('searchQuerySchema', () => {
diff --git a/server/routes/notes.js b/server/routes/notes.js
index 7c09d38632..d1ac0ee3a4 100644
--- a/server/routes/notes.js
+++ b/server/routes/notes.js
@@ -22,9 +22,12 @@ import {
const router = Router();
const NOT_FOUND_CODES = new Set(['VAULT_NOT_FOUND', 'NOTE_NOT_FOUND']);
-// The note exists but iCloud has evicted its bytes — a transient condition that
-// heals once the background `brctl download` completes, so it's 503 (retry me),
-// not 404 (gone) or 400 (your request was wrong).
+// The note exists but iCloud reports its bytes as evicted — usually transient
+// (it heals once the background `brctl download` completes), so 503, not 404
+// (gone) or 400 (your request was wrong). Not ALWAYS transient: the screen can
+// false-positive on a genuinely-local sparse/compressed file, which no amount of
+// retrying clears — the service says so in the message and the UI offers a
+// force-save override on the second refusal (#3717).
const UNAVAILABLE_CODES = new Set(['NOTE_EVICTED']);
const errorStatus = (code) => {
if (NOT_FOUND_CODES.has(code)) return 404;
@@ -114,8 +117,8 @@ router.post('/vaults/:id/note', asyncHandler(async (req, res) => {
router.put('/vaults/:id/note', asyncHandler(async (req, res) => {
const { path } = validateRequest(notePathSchema, req.query);
- const { content } = validateRequest(updateNoteSchema, req.body);
- const result = await obsidian.updateNote(req.params.id, path, content);
+ const { content, force } = validateRequest(updateNoteSchema, req.body);
+ const result = await obsidian.updateNote(req.params.id, path, content, { force });
throwOnError(result);
res.json(result);
}));
diff --git a/server/routes/notes.test.js b/server/routes/notes.test.js
index 2350c45497..482587be78 100644
--- a/server/routes/notes.test.js
+++ b/server/routes/notes.test.js
@@ -14,6 +14,7 @@ import { request } from '../lib/testHelper.js';
vi.mock('../services/obsidian.js', () => ({
getNote: vi.fn(),
scanVault: vi.fn(),
+ updateNote: vi.fn(),
}));
const obsidian = await import('../services/obsidian.js');
@@ -28,6 +29,7 @@ app.use(errorMiddleware);
beforeEach(() => {
obsidian.getNote.mockReset();
obsidian.scanVault.mockReset();
+ obsidian.updateNote.mockReset();
});
describe('GET /api/notes/vaults/:id/note error mapping', () => {
@@ -60,6 +62,38 @@ describe('GET /api/notes/vaults/:id/note error mapping', () => {
});
});
+/**
+ * The force-save escape hatch (#3717). The dataless screen can false-positive on
+ * a genuinely-local sparse/compressed file, and on the write path that used to be
+ * an unrecoverable lockout. `force` is the way back — so the handler must pass it
+ * through verbatim AND must default it off, or every background save inherits it.
+ */
+describe('PUT /api/notes/vaults/:id/note force pass-through', () => {
+ it('defaults force to false when the body omits it', async () => {
+ obsidian.updateNote.mockResolvedValue({ path: 'a.md' });
+
+ const res = await request(app).put('/api/notes/vaults/v1/note?path=a.md').send({ content: 'hi' });
+
+ expect(res.status).toBe(200);
+ expect(obsidian.updateNote).toHaveBeenCalledWith('v1', 'a.md', 'hi', { force: false });
+ });
+
+ it('forwards an explicit force:true', async () => {
+ obsidian.updateNote.mockResolvedValue({ path: 'a.md' });
+
+ await request(app).put('/api/notes/vaults/v1/note?path=a.md').send({ content: 'hi', force: true });
+
+ expect(obsidian.updateNote).toHaveBeenCalledWith('v1', 'a.md', 'hi', { force: true });
+ });
+
+ 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' });
+
+ expect(res.status).toBe(400);
+ expect(obsidian.updateNote).not.toHaveBeenCalled();
+ });
+});
+
describe('GET /api/notes/vaults/:id/scan', () => {
it('forwards skippedUnavailable so a short vault is distinguishable from an offloaded one', async () => {
obsidian.scanVault.mockResolvedValue({
diff --git a/server/services/obsidian.js b/server/services/obsidian.js
index b8433af002..daedfd6601 100644
--- a/server/services/obsidian.js
+++ b/server/services/obsidian.js
@@ -271,7 +271,18 @@ export async function getNote(vaultId, notePath, { includeBacklinks = true } = {
};
}
-export async function updateNote(vaultId, notePath, content) {
+/**
+ * Overwrite an existing note.
+ *
+ * @param {string} vaultId
+ * @param {string} notePath - vault-relative path.
+ * @param {string} content
+ * @param {object} [options]
+ * @param {boolean} [options.force=false] - Bypass the iCloud dataless screen and
+ * issue the write regardless. **Only ever set from a deliberate user action**
+ * (see the escape-hatch note below); background mirrors must leave it off.
+ */
+export async function updateNote(vaultId, notePath, content, { force = false } = {}) {
const vault = await getVaultById(vaultId);
if (!vault) return { error: 'VAULT_NOT_FOUND' };
@@ -294,12 +305,42 @@ export async function updateNote(vaultId, notePath, content) {
// and WAITS (bounded, in a child process — cancellable, which the kernel write
// is not) rather than fire-and-forget. brctl exit 0 only means the download was
// accepted, so re-screen before trusting it and refuse if it's still dataless.
- if (await isSuspectedDataless(fullPath)) {
+ //
+ // ## The escape hatch (#3717)
+ //
+ // The screen infers "dataless" from `size > 0 && blocks === 0`, which also
+ // matches a genuinely-local sparse or `decmpfs`-compressed file. On a read that
+ // false positive self-limits; on this write path it was PERMANENT — `brctl`
+ // exits 0 with nothing to fetch, the re-screen still says dataless, and the
+ // note could never be saved again from the UI. `force` restores the user's
+ // agency. It re-admits exactly one blocking write, which is what this guard
+ // exists to prevent — so it must only ever arrive from an explicit click, never
+ // as a retry default, and never from `upsertNote`'s background mirrors.
+ if (force) {
+ console.warn(`⚠️ force-save bypassing the iCloud dataless screen for note: ${notePath}`);
+ } else if (await isSuspectedDataless(fullPath)) {
+ // Snapshot before/after so the refusal can say something TRUE about retrying.
+ // This is deliberately messaging-only: the verdict stays the re-screen below,
+ // which is already the strictest form of "did it actually materialize" —
+ // `blocks` moving off zero IS the completion signal, so gating the write on
+ // `mtime` too would only let a still-dataless file through when a metadata
+ // sync touched it (#3717 option 1, taken for the message and rejected for the
+ // guard).
+ const before = await stat(fullPath).catch(() => null);
await materializeAndWait(fullPath, { label: 'Obsidian note' });
if (await isSuspectedDataless(fullPath)) {
+ const after = await stat(fullPath).catch(() => null);
+ // Unknown (a stat failed) counts as "moved": never claim a download is
+ // hopeless on evidence we don't have.
+ const moved = !before || !after
+ || before.blocks !== after.blocks
+ || before.mtimeMs !== after.mtimeMs;
return {
error: 'NOTE_EVICTED',
- message: 'This note is stored in iCloud and has not been downloaded to this Mac yet. A download was requested — try again shortly.'
+ stalled: !moved,
+ message: moved
+ ? 'This note is stored in iCloud and has not been downloaded to this Mac yet. A download is in progress — try again shortly.'
+ : 'This note looks offloaded to iCloud, but asking iCloud to download it changed nothing, so waiting will not help. If the note really is on this Mac, save it again and choose "Save anyway".'
};
}
}
diff --git a/server/services/obsidianEvicted.test.js b/server/services/obsidianEvicted.test.js
index a99e397c5c..5abc06d92e 100644
--- a/server/services/obsidianEvicted.test.js
+++ b/server/services/obsidianEvicted.test.js
@@ -216,6 +216,80 @@ describe('obsidian updateNote against an evicted note', () => {
expect(icloud.isSuspectedDataless).not.toHaveBeenCalled();
});
+ /**
+ * The force-save escape hatch — #3717.
+ *
+ * The screen infers dataless from `size > 0 && blocks === 0`, which also matches
+ * a genuinely-local sparse/compressed file. On this write path that false
+ * positive was PERMANENT (brctl exits 0 with nothing to fetch, the re-screen
+ * still says dataless, forever), so the note could never be saved again. These
+ * pin the way out, and pin that it stays shut unless someone explicitly opens it.
+ */
+ it('force writes the note past a screen that will never clear', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ icloud.isSuspectedDataless.mockResolvedValue(true);
+
+ const result = await updateNote(vaultId, NOTE, 'REPLACEMENT', { force: true });
+
+ expect(result.error).toBeUndefined();
+ expect(readFileSync(join(VAULT_DIR, NOTE), 'utf-8')).toBe('REPLACEMENT');
+ });
+
+ it('force skips the screen entirely rather than re-running a hopeless materialize', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ icloud.isSuspectedDataless.mockResolvedValue(true);
+
+ await updateNote(vaultId, NOTE, 'REPLACEMENT', { force: true });
+
+ // The whole point of the override is that the user has asserted the file is
+ // local; paying another bounded brctl wait first would just re-add the delay
+ // the lockout is made of.
+ expect(icloud.materializeAndWait).not.toHaveBeenCalled();
+ expect(icloud.isSuspectedDataless).not.toHaveBeenCalled();
+ });
+
+ it('force is opt-in — an absent or false flag still refuses', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ icloud.isSuspectedDataless.mockResolvedValue(true);
+
+ expect((await updateNote(vaultId, NOTE, 'A')).error).toBe('NOTE_EVICTED');
+ expect((await updateNote(vaultId, NOTE, 'B', {})).error).toBe('NOTE_EVICTED');
+ expect((await updateNote(vaultId, NOTE, 'C', { force: false })).error).toBe('NOTE_EVICTED');
+ expect(readFileSync(join(VAULT_DIR, NOTE), 'utf-8')).toBe(ORIGINAL);
+ });
+
+ it('does not promise a retry when the download changed nothing', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ icloud.isSuspectedDataless.mockResolvedValue(true);
+
+ // The note on disk is an ordinary local file, so brctl cannot move `blocks`
+ // or `mtime` — exactly the false-positive lockout. Telling the user to "try
+ // again shortly" here is a lie; nothing is in flight.
+ const result = await updateNote(vaultId, NOTE, 'REPLACEMENT');
+
+ expect(result.stalled).toBe(true);
+ expect(result.message).not.toMatch(/try again shortly/i);
+ expect(result.message).toMatch(/Save anyway/);
+ });
+
+ it('still says "try again shortly" when the download actually moved the file', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ icloud.isSuspectedDataless.mockResolvedValue(true);
+ // A real in-flight download changes the file on disk. Grow it far enough that
+ // `blocks` has to move whatever the filesystem's block size is, rather than
+ // leaning on sub-millisecond mtime resolution.
+ icloud.materializeAndWait.mockImplementation(async () => {
+ writeFileSync(join(VAULT_DIR, NOTE), 'x'.repeat(256 * 1024));
+ return true;
+ });
+
+ const result = await updateNote(vaultId, NOTE, 'REPLACEMENT');
+
+ expect(result.error).toBe('NOTE_EVICTED');
+ expect(result.stalled).toBe(false);
+ expect(result.message).toMatch(/try again shortly/i);
+ });
+
it('upsertNote degrades to a skipped mirror, never a hang or a throw', async () => {
const icloud = await import('../lib/icloudFile.js');
icloud.isSuspectedDataless.mockResolvedValue(true);