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

feat(brain): autosave the daily log as you type and when it loses focus

[._.]/ Adam Eivyaf20862c74b0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f203b951ac..fb04a2c5d1 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,13 @@
# Unreleased Changes
+## Added
+
+- **The Brain daily log now saves itself.** Your entry is saved automatically as you type (about a second and a half after you pause, and at least every ten seconds during a long uninterrupted writing run), when you click away from the editor, when you switch tabs or navigate away, and when you background the tab or app — so a closed laptop or a backgrounded phone no longer loses the day. The toolbar shows the current state (`Unsaved…` / `Saving…` / `Saved`) in place of a toast on every autosave; the Save button and ⌘S still work and still confirm with a toast. Autosave never reverts what you're typing mid-save, never writes one day's text into another when you change dates, keeps debouncing instead of retrying per keystroke when the server is unreachable, and deliberately stands down when a dictated voice segment arrives while you have unsaved edits (the toolbar says "Autosave paused — save to keep your edits") — a full-content save would otherwise drop the segment.
+
+## Changed
+
+- Daily log entries now re-embed into the Chief-of-Staff memory index once you settle (coalesced per day, ~30s after your last edit) instead of on every single save. Autosave means a day's entry is now written every couple of seconds while you type; re-embedding per save would have meant an embedding call per typing pause — and, once a day's log grows past the embedding size budget, an unrequested AI summarization call each time too. Search results are unchanged; the index simply updates when you pause rather than mid-sentence, which also produces a better vector than embedding a half-typed sentence a hundred times. Journals now use the same debounced, coalesced re-embed path every other Brain record type already used.
+
## Internal
- **[issue-2706] Stage-seeding migrations now guard their own `data.reference` assets.** Migrations 189 (model-personality), 094 (object-attachment checks), and 182 (CWQE quality) each seed stage prompts on upgrade but shipped without a colocated test, so a rename or removal of a reference template would have surfaced only at runtime as "Stage not found" on a fresh install. Each now has a `.test.js` asserting it seeds when absent, no-ops on re-run, never clobbers a customized template or hand-tuned config entry, and — the point — that every `data.reference/prompts/stages/*.md` template it names and its `stage-config.json` entry actually ship. The guard is anchored to the migration's own stage list (now exposed on the object the seed helper returns), so adding a stage without shipping its template fails the suite instead of leaving it green against a stale hand-copied list. The three suites collapse to one `runSeedStageMigrationTests({ migration, stages, prefix })` call apiece via a new shared helper — the seed-family analogue of `_testHelpers.js`'s `runPromptMigrationTests`. (`scripts/migrations/_seedStageTestHelpers.js`)
diff --git a/PLAN.md b/PLAN.md
index 2533fa32ea..7aedfc8e53 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -16,6 +16,62 @@ conflicts as work proceeds). Speculative ideas now live as `future`-labeled
issues rather than a list here, so they can each be promoted, refined, or closed
independently.
+### Daily-log autosave follow-ups
+
+Deferred from the daily-log autosave PR. Autosave turned the daily-log save path
+from "a couple of writes a day" into "a write every ~1.5s while typing", which
+amplified several pre-existing inefficiencies on that path. The one that crossed
+a policy line (an LLM summarization call per save once a day's entry outgrows the
+embedding budget) was fixed in that PR by debouncing the journal re-embed
+(`queueJournalResync` in `server/services/brainMemoryBridge.js`). These are the
+rest — each is a perf/cleanup item, none is a correctness bug:
+
+- [ ] Delete the dead `journals:changed` event. `server/services/brainJournal.js`
+ emits it at lines ~259/298/335/356 as `{ records: await rawRecords() }`, and
+ `rawRecords()` (line ~142) rebuilds the entire date→entry map (two full object
+ copies of every journal day) — awaited inline before the save returns, so it
+ adds latency to every autosave. Verified there is **no** `brainEvents.on('journals:changed')`
+ listener anywhere in the repo; `brainMemoryBridge.js:633` documents that it
+ deliberately stopped listening. `brainEvents` is an in-process EventEmitter
+ (`brainStorage.js`) with no cross-install surface, so removal is compat-safe.
+ `server/services/brainJournal.test.js:141` asserts the emit and must be updated.
+ Skipped in the autosave PR as pre-existing dead-code cleanup outside its scope.
+- [ ] Cache the Obsidian sidecar. `loadObsidianLocations()`
+ (`server/services/brainJournal.js:85`) is `ensureDir` + `readJSONFile` with no
+ cache, called from `getEntry`, `putEntry`, and `rawRecords` — ~3 uncached file
+ reads + 3 `mkdir` syscalls per save, now once per autosave. Mirror the
+ write-through cache `brainStorage` already uses (`CACHE_TTL_MS = 2000`). Fixing
+ the item above removes one of the three call sites for free.
+- [ ] Serialize `scheduleObsidianSync` per date (`server/services/brainJournal.js:238`).
+ It rewrites the day's full markdown note fire-and-forget on every save, and its
+ own comment notes Obsidian lives on iCloud where "writes can stall for hundreds
+ of ms" — so at autosave cadence, overlapping writes to one file are possible and
+ last-writer-wins isn't guaranteed to be newest-content. Only affects installs
+ with the "Auto-mirror to Obsidian on every save" toggle on. Consider also
+ re-wording that toggle's label, whose "every save" now means something new.
+- [ ] Close the dictation/autosave overwrite race properly. Today the client
+ *parks* autosave when a voice segment lands while the user has unsaved edits
+ (`voiceConflict` in `client/src/components/brain/tabs/DailyLogTab.jsx`), because
+ `setJournalContent` replaces content wholesale and would drop the segment. The
+ park cannot close the narrow race where a segment lands server-side *after* a
+ PUT is already in flight. Deeper fix: merge the incoming segment into the
+ textarea client-side (the socket payload carries `text`, and the `!dirty` branch
+ already performs exactly that merge — this would delete the flag and its ~6 touch
+ sites), backed by an `updatedAt` precondition on the PUT so the server rejects a
+ stale overwrite instead of the client predicting it. `updatedAt` is already
+ stamped and already kept client-side; no precondition mechanism exists server-side
+ yet (no `If-Match`/`ifMatch` anywhere). Needs real-device validation of caret
+ behavior when the textarea is rewritten under the user — that risk is why it was
+ not done unilaterally in an autosave PR, and it reverses the deliberate existing
+ "save or refresh to see it" product decision.
+- [ ] Extract a `useAutosave` hook when a second consumer appears. The daily log
+ now has ~60 lines of autosave machinery inline (debounce + max-wait ceiling +
+ single-flight + failure-toast dedup + blur/visibility/unmount flush). The only
+ other debounced-save site, `client/src/pages/VideoTimelineEditor.jsx:281`
+ (`saveTimerRef`/`queueSave`), shares only "setTimeout + clearTimeout on cleanup"
+ and diverges on every other requirement — so extraction at N=2 would be ~6 config
+ knobs wrapping ~5 lines. Revisit at a third consumer.
+
### SongBook follow-ups
Deferred from the SongBook feature's post-review cleanup (see
diff --git a/client/src/components/brain/tabs/DailyLogTab.jsx b/client/src/components/brain/tabs/DailyLogTab.jsx
index 78eb2d75b4..ca4d868a36 100644
--- a/client/src/components/brain/tabs/DailyLogTab.jsx
+++ b/client/src/components/brain/tabs/DailyLogTab.jsx
@@ -8,6 +8,15 @@ import InlineConfirmRow from '../../ui/InlineConfirmRow';
import { FormField } from '../../ui/FormField';
import { onVoiceEvent, sendText, setDictation as setVoiceDictation } from '../../../services/voiceClient';
import BrailleSpinner from '../../BrailleSpinner';
+import useMounted from '../../../hooks/useMounted';
+import { useVisibilityEvent } from '../../../hooks/useVisibilityEvent';
+
+// Autosave cadence. The debounce keeps us from PUTting on every keystroke;
+// the max-wait ceiling exists because a pure debounce never fires at all
+// during a long uninterrupted typing run — the whole entry would sit unsaved
+// until the user paused.
+const AUTOSAVE_DEBOUNCE_MS = 1500;
+const AUTOSAVE_MAX_WAIT_MS = 10000;
// Slim shape kept in the sidebar history list — full `content`/`segments`
// would accumulate as the log grows and the sidebar never renders them.
@@ -70,7 +79,29 @@ export default function DailyLogTab() {
const [confirmDelete, setConfirmDelete] = useState(false);
const [syncing, setSyncing] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false);
+ // Set when a dictated segment landed while the user had unsaved edits, so
+ // the textarea and the server have diverged. Autosave stands down until the
+ // user resolves it — a full-content PUT would silently drop the segment
+ // (setJournalContent replaces content wholesale). The explicit Save button
+ // still works: clicking it is the user choosing their edits.
+ const [voiceConflict, setVoiceConflict] = useState(false);
const editorRef = useRef(null);
+ const mountedRef = useMounted();
+ // Single-flight gate. `saving` state lags re-renders, so the debounce timer
+ // and a blur flush can otherwise both fire a PUT for the same content.
+ const savingRef = useRef(false);
+ // Ref-stashed so the debounce effect, blur, visibilitychange, and Cmd+S all
+ // drive one save without re-subscribing on every keystroke.
+ const saveRef = useRef(null);
+ // Anchors the max-wait ceiling: when the current run of unsaved edits began.
+ const firstDirtyAtRef = useRef(null);
+ // Suppresses repeat failure toasts — a failing autosave retries on the next
+ // keystroke, so an unreachable server would otherwise toast every tick.
+ const autoSaveFailedRef = useRef(false);
+ // Which date the text in `content` actually belongs to. `date` flips before
+ // the new entry loads, so this is the only safe answer to "what am I about
+ // to overwrite?" — see the guard in saveRef.
+ const loadedDateRef = useRef(null);
// Ref mirror of the dirty flag so the socket event handler can check it
// without adding `content`/`entry` to the effect's dependency list
// (which would re-subscribe on every keystroke).
@@ -97,6 +128,8 @@ export default function DailyLogTab() {
const res = await api.getDailyLog(d).catch(() => null);
if (reqId !== loadRequestRef.current) return;
const data = res?.entry || null;
+ loadedDateRef.current = d;
+ setVoiceConflict(false);
setEntry(data);
setContent(data?.content || '');
if (!silent) setLoading(false);
@@ -204,6 +237,9 @@ export default function DailyLogTab() {
? `${prevContent.replace(/\s+$/, '')}\n\n${appendedText}`
: appendedText));
} else {
+ // Server and textarea have diverged — park autosave so it can't
+ // overwrite the segment with content that never contained it.
+ setVoiceConflict(true);
toast('Voice segment appended while you were editing — save or refresh to see it.', { icon: '📝' });
}
}
@@ -247,24 +283,92 @@ export default function DailyLogTab() {
return () => offs.forEach((off) => off());
}, [date]);
+ // Adopt the server's entry wholesale, textarea included — which is exactly
+ // the point any divergence with the server is resolved, so the voice-conflict
+ // park lifts here too.
const applyEntry = (next) => {
+ setVoiceConflict(false);
setEntry(next);
setContent(next.content || '');
setHistory((prev) => upsertHistory(prev, next));
};
- const handleSave = async () => {
+ // Reassigned every render so it always closes over fresh `content`/`date`
+ // without the callers needing it in a dependency list.
+ saveRef.current = async ({ auto = false } = {}) => {
+ if (savingRef.current || !dirty) return;
+ // Every automatic trigger (debounce, blur, backgrounding) funnels through
+ // here, so the voice-conflict park belongs here rather than in any one
+ // caller. An explicit save passes auto:false and is never parked.
+ if (auto && voiceConflict) return;
+ // `content` belongs to loadedDateRef, not necessarily `date`: changing the
+ // day flips `date` immediately while the new entry is still loading.
+ // Saving in that window would write this day's text into another day.
+ if (loadedDateRef.current !== date) return;
+ const targetDate = date;
+ const body = content;
+ savingRef.current = true;
+ // Anchor the ceiling at attempt time, not on success: resetting it only
+ // after a successful PUT would leave `waited` past the ceiling forever
+ // once a save failed, collapsing the debounce into a PUT per keystroke
+ // against an already-unhealthy server.
+ firstDirtyAtRef.current = null;
setSaving(true);
- const res = await api.updateDailyLog(date, content, { silent: true }).catch(() => null);
+ const res = await api.updateDailyLog(targetDate, body, { silent: true }).catch(() => null);
+ savingRef.current = false;
+ if (!mountedRef.current) return;
setSaving(false);
if (!res?.entry) {
- toast.error('Save failed');
+ if (!auto || !autoSaveFailedRef.current) toast.error('Save failed');
+ autoSaveFailedRef.current = true;
return;
}
- applyEntry(res.entry);
- toast.success('Saved');
+ autoSaveFailedRef.current = false;
+ // Adopt the server's metadata but deliberately leave the textarea alone.
+ // Anything typed during the in-flight PUT stays in `content` and stays
+ // dirty against res.entry.content, so the next tick saves it — whereas
+ // applyEntry() would revert those keystrokes to the server's echo.
+ if (loadedDateRef.current === targetDate) {
+ setEntry(res.entry);
+ setHistory((prev) => upsertHistory(prev, res.entry));
+ }
+ if (!auto) toast.success('Saved');
+ };
+
+ const handleSave = () => {
+ // Explicit save = the user choosing their edits over the unmerged segment.
+ setVoiceConflict(false);
+ return saveRef.current?.();
};
+ // Autosave. Re-arms on every render whose deps moved: each keystroke
+ // restarts the debounce, and `saving` flipping back to false re-checks for
+ // work that arrived mid-PUT (or was skipped by the single-flight gate).
+ useEffect(() => {
+ if (!dirty || voiceConflict || loadedDateRef.current !== date) {
+ firstDirtyAtRef.current = null;
+ return undefined;
+ }
+ if (firstDirtyAtRef.current === null) firstDirtyAtRef.current = Date.now();
+ const waited = Date.now() - firstDirtyAtRef.current;
+ const wait = Math.max(0, Math.min(AUTOSAVE_DEBOUNCE_MS, AUTOSAVE_MAX_WAIT_MS - waited));
+ const timer = setTimeout(() => saveRef.current?.({ auto: true }), wait);
+ return () => clearTimeout(timer);
+ }, [content, dirty, saving, voiceConflict, date]);
+
+ // Flush when the tab/app is backgrounded. Mobile browsers can freeze or
+ // discard the page without firing blur on the textarea, so the pending
+ // debounce timer would never run.
+ useVisibilityEvent((state) => {
+ if (state === 'hidden') saveRef.current?.({ auto: true });
+ });
+
+ // Flush on unmount (tab switch, route change). The debounce timer is cleared
+ // by its own cleanup, so without this any edit still inside the debounce
+ // window is silently dropped. The in-flight PUT outlives the component; its
+ // post-await setState is already gated on mountedRef.
+ useEffect(() => () => { saveRef.current?.({ auto: true }); }, []);
+
const handleAppend = async () => {
const text = quickAppend.trim();
if (!text) return;
@@ -319,6 +423,7 @@ export default function DailyLogTab() {
}
toast.success('Deleted');
setConfirmDelete(false);
+ setVoiceConflict(false);
setEntry(null);
setContent('');
setHistory((prev) => prev.filter((h) => h.date !== date));
@@ -381,6 +486,16 @@ export default function DailyLogTab() {
const isToday = date === serverToday;
const segmentCount = entry?.segments?.length ?? entry?.segmentCount ?? 0;
+ // Autosave is silent, so the toolbar carries the feedback the toast used to.
+ // The park only means anything while there's something unsaved to park, so
+ // `dirty` gates it — otherwise a resolved conflict would leave the toolbar
+ // telling the user to click a Save button that's disabled.
+ const parked = dirty && voiceConflict;
+ const saveStatus = saving ? 'Saving…'
+ : parked ? 'Autosave paused — save to keep your edits'
+ : dirty ? 'Unsaved…'
+ : entry ? 'Saved' : '';
+
const dateLabel = useMemo(() => {
try {
return new Date(`${date}T00:00:00`).toLocaleDateString(undefined, {
@@ -604,6 +719,7 @@ export default function DailyLogTab() {
<div className="text-xs text-gray-500 truncate">
{segmentCount} segment{segmentCount === 1 ? '' : 's'}
{entry?.obsidianPath ? ` · ${entry.obsidianPath}` : ''}
+ {saveStatus ? <span className={parked ? 'text-port-warning' : ''}> · {saveStatus}</span> : null}
</div>
</div>
<button
@@ -688,6 +804,7 @@ export default function DailyLogTab() {
ref={editorRef}
value={content}
onChange={(e) => setContent(e.target.value)}
+ onBlur={() => saveRef.current?.({ auto: true })}
placeholder={isToday
? "What's on your mind today? Type freely, append voice segments, or toggle dictation above…"
: 'This day\'s entry is empty.'}
diff --git a/client/src/components/brain/tabs/DailyLogTab.test.jsx b/client/src/components/brain/tabs/DailyLogTab.test.jsx
new file mode 100644
index 0000000000..212adc874e
--- /dev/null
+++ b/client/src/components/brain/tabs/DailyLogTab.test.jsx
@@ -0,0 +1,371 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, fireEvent, act } from '@testing-library/react';
+import { __resetVisibilityEventForTests } from '../../../hooks/useVisibilityEvent';
+
+// ── Mock toast ────────────────────────────────────────────────────────────────
+const mockToast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));
+vi.mock('../../ui/Toast', () => ({ default: mockToast }));
+
+// ── Mock voice client — capture handlers so tests can fire server events ──────
+const voice = vi.hoisted(() => ({
+ handlers: {},
+ onVoiceEvent: vi.fn(),
+ sendText: vi.fn(),
+ setDictation: vi.fn(),
+}));
+voice.onVoiceEvent.mockImplementation((event, fn) => {
+ voice.handlers[event] = fn;
+ return () => { delete voice.handlers[event]; };
+});
+vi.mock('../../../services/voiceClient', () => ({
+ onVoiceEvent: voice.onVoiceEvent,
+ sendText: voice.sendText,
+ setDictation: voice.setDictation,
+}));
+
+// ── Mock API ──────────────────────────────────────────────────────────────────
+const api = vi.hoisted(() => ({
+ getDailyLog: vi.fn(),
+ listDailyLogs: vi.fn(),
+ getDailyLogSettings: vi.fn(),
+ updateDailyLogSettings: vi.fn(),
+ getActivityDigestSettings: vi.fn(),
+ updateActivityDigestSettings: vi.fn(),
+ getProviders: vi.fn(),
+ updateDailyLog: vi.fn(),
+ appendDailyLog: vi.fn(),
+ deleteDailyLog: vi.fn(),
+ syncDailyLogsToObsidian: vi.fn(),
+ draftActivityDigest: vi.fn(),
+}));
+vi.mock('../../../services/api', () => api);
+vi.mock('../../../services/apiNotes', () => ({ getNotesVaults: vi.fn(async () => []) }));
+
+const DailyLogTab = (await import('./DailyLogTab')).default;
+
+const TODAY = '2026-07-17';
+const YESTERDAY = '2026-07-16';
+// Mirrors AUTOSAVE_MAX_WAIT_MS in the component.
+const AUTOSAVE_MAX_WAIT_MS = 10000;
+
+// Mirrors the server: setJournalContent stores `content` verbatim and echoes
+// the persisted entry back.
+const entryFor = (date, content) => ({
+ date,
+ content,
+ segments: content ? [{ text: content, at: `${date}T12:00:00Z`, source: 'edit' }] : [],
+ segmentCount: content ? 1 : 0,
+ updatedAt: `${date}T12:00:00Z`,
+ obsidianPath: null,
+});
+
+let store;
+
+const renderTab = async () => {
+ const result = render(<DailyLogTab />);
+ // Flush the mount fetches (entry + server-today + history + settings).
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ return result;
+};
+
+// The placeholder differs per day and the textarea unmounts behind the loading
+// spinner, so select the element itself — there is exactly one.
+const editor = () => document.querySelector('textarea');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(`${TODAY}T12:00:00`));
+ store = { [TODAY]: entryFor(TODAY, 'existing'), [YESTERDAY]: entryFor(YESTERDAY, 'old day') };
+
+ api.getDailyLog.mockImplementation(async (d) => {
+ const date = d === 'today' ? TODAY : d;
+ return { date, entry: store[date] || null };
+ });
+ api.updateDailyLog.mockImplementation(async (date, content) => ({ date, entry: entryFor(date, content) }));
+ api.listDailyLogs.mockResolvedValue({ records: [] });
+ api.getDailyLogSettings.mockResolvedValue({});
+ api.getActivityDigestSettings.mockResolvedValue({});
+ api.getProviders.mockResolvedValue({ providers: [] });
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ // The visibility hook is singleton-backed, and the visibilityState spy is a
+ // real getter override — both leak into later tests if not undone.
+ __resetVisibilityEventForTests();
+ vi.restoreAllMocks();
+});
+
+const backgroundTab = async () => {
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
+ await act(async () => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.advanceTimersByTimeAsync(0);
+ });
+};
+
+// Put the editor into the parked state: unsaved typed edits, then a dictated
+// segment lands server-side. Delivered in its own act() so React commits the
+// state before any timer advances — as the real socket event does.
+const typeThenReceiveVoiceSegment = async (typed) => {
+ fireEvent.change(editor(), { target: { value: typed } });
+ await act(async () => {
+ voice.handlers['voice:dailyLog:appended']({
+ date: TODAY,
+ text: 'spoken words',
+ segment: { text: 'spoken words', at: `${TODAY}T12:01:00Z`, source: 'voice' },
+ segmentCount: 2,
+ updatedAt: `${TODAY}T12:01:00Z`,
+ });
+ });
+};
+
+describe('DailyLogTab autosave', () => {
+ it('saves after the user stops typing', async () => {
+ await renderTab();
+ fireEvent.change(editor(), { target: { value: 'a new thought' } });
+
+ // Still within the debounce window — nothing sent yet.
+ await act(async () => { await vi.advanceTimersByTimeAsync(1400); });
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(200); });
+ expect(api.updateDailyLog).toHaveBeenCalledTimes(1);
+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'a new thought', { silent: true });
+ });
+
+ it('coalesces a burst of keystrokes into one save', async () => {
+ await renderTab();
+ for (const value of ['a', 'ab', 'abc', 'abcd']) {
+ fireEvent.change(editor(), { target: { value } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(100); });
+ }
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+ expect(api.updateDailyLog).toHaveBeenCalledTimes(1);
+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'abcd', { silent: true });
+ });
+
+ it('still saves during an uninterrupted typing run (max-wait ceiling)', async () => {
+ await renderTab();
+ // Keep typing forever at a cadence below the debounce — a pure debounce
+ // would never fire.
+ for (let i = 0; i < 20; i += 1) {
+ fireEvent.change(editor(), { target: { value: `word ${i}` } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(600); });
+ }
+ expect(api.updateDailyLog).toHaveBeenCalled();
+ });
+
+ it('saves immediately on blur without waiting for the debounce', async () => {
+ await renderTab();
+ fireEvent.change(editor(), { target: { value: 'typed then left' } });
+ fireEvent.blur(editor());
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+
+ expect(api.updateDailyLog).toHaveBeenCalledTimes(1);
+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'typed then left', { silent: true });
+ });
+
+ it('saves when the tab is backgrounded', async () => {
+ await renderTab();
+ fireEvent.change(editor(), { target: { value: 'backgrounded' } });
+ await backgroundTab();
+
+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'backgrounded', { silent: true });
+ });
+
+ it('flushes on unmount so an edit inside the debounce window is not lost', async () => {
+ const { unmount } = await renderTab();
+ fireEvent.change(editor(), { target: { value: 'typed then navigated away' } });
+
+ // Well inside the debounce window — the timer's own cleanup would drop it.
+ await act(async () => { unmount(); await vi.advanceTimersByTimeAsync(0); });
+
+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'typed then navigated away', { silent: true });
+ });
+
+ it('does not save when nothing changed', async () => {
+ await renderTab();
+ fireEvent.blur(editor());
+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+ });
+
+ it('autosaves silently — no success toast per tick', async () => {
+ await renderTab();
+ fireEvent.change(editor(), { target: { value: 'quiet' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+
+ expect(api.updateDailyLog).toHaveBeenCalled();
+ expect(mockToast.success).not.toHaveBeenCalled();
+ });
+
+ it('toasts once per failure run rather than on every retry', async () => {
+ api.updateDailyLog.mockRejectedValue(new Error('offline'));
+ await renderTab();
+
+ for (const value of ['x', 'xy', 'xyz']) {
+ fireEvent.change(editor(), { target: { value } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+ }
+
+ expect(api.updateDailyLog.mock.calls.length).toBeGreaterThan(1);
+ expect(mockToast.error).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps debouncing after a failure instead of PUTting per keystroke', async () => {
+ api.updateDailyLog.mockRejectedValue(new Error('offline'));
+ await renderTab();
+
+ // Cross the max-wait ceiling with a failing server: if the ceiling anchor
+ // only reset on success, `waited` would stay past it forever and every
+ // later keystroke would fire an immediate PUT at the dead server.
+ fireEvent.change(editor(), { target: { value: 'first' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(AUTOSAVE_MAX_WAIT_MS + 2000); });
+ api.updateDailyLog.mockClear();
+
+ // Now type a burst — a healthy debounce coalesces it into nothing yet.
+ for (const value of ['a', 'ab', 'abc', 'abcd', 'abcde']) {
+ fireEvent.change(editor(), { target: { value } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });
+ }
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+ expect(api.updateDailyLog).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps keystrokes typed while a save is in flight', async () => {
+ let release;
+ api.updateDailyLog.mockImplementation((date, content) => new Promise((resolve) => {
+ release = () => resolve({ date, entry: entryFor(date, content) });
+ }));
+ await renderTab();
+
+ fireEvent.change(editor(), { target: { value: 'first' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'first', { silent: true });
+
+ // Type while the PUT is still open, then let it resolve.
+ fireEvent.change(editor(), { target: { value: 'first second' } });
+ await act(async () => { release(); await vi.advanceTimersByTimeAsync(0); });
+
+ // The server echoed 'first'; the textarea must not revert to it.
+ expect(editor().value).toBe('first second');
+
+ // ...and the newer text still reaches the server on the next tick.
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+ expect(api.updateDailyLog).toHaveBeenLastCalledWith(TODAY, 'first second', { silent: true });
+ });
+
+ it('never writes one day\'s text into another after a date change', async () => {
+ // Hold the YESTERDAY load open so `date` has flipped while `content` still
+ // holds TODAY's text — the window the loadedDate guard protects.
+ let releaseLoad;
+ api.getDailyLog.mockImplementation((d) => {
+ if (d === YESTERDAY) return new Promise((resolve) => { releaseLoad = () => resolve({ date: d, entry: store[d] }); });
+ const date = d === 'today' ? TODAY : d;
+ return Promise.resolve({ date, entry: store[date] || null });
+ });
+ await renderTab();
+
+ fireEvent.change(editor(), { target: { value: "today's private text" } });
+ fireEvent.click(screen.getByTitle('Previous day'));
+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
+
+ // Autosave must stand down entirely while the target day is unresolved.
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+
+ await act(async () => { releaseLoad(); await vi.advanceTimersByTimeAsync(2000); });
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+ expect(editor().value).toBe('old day');
+ });
+
+ it('parks autosave when a dictated segment lands mid-edit', async () => {
+ await renderTab();
+ await typeThenReceiveVoiceSegment('my unsaved edit');
+ await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
+
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+ expect(screen.getByText(/Autosave paused/i)).toBeInTheDocument();
+
+ // The explicit Save button is the user choosing their edits — it still works.
+ fireEvent.click(screen.getByLabelText('Save'));
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'my unsaved edit', { silent: true });
+ });
+
+ // The park has to hold for every automatic trigger, not just the timer —
+ // blur and backgrounding reach the same PUT that would drop the segment.
+ it('parks the blur flush too', async () => {
+ await renderTab();
+ await typeThenReceiveVoiceSegment('my unsaved edit');
+
+ fireEvent.blur(editor());
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+ });
+
+ it('parks the background flush too', async () => {
+ await renderTab();
+ await typeThenReceiveVoiceSegment('my unsaved edit');
+
+ await backgroundTab();
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+ });
+
+ it('lifts the park once the entry is re-adopted from the server', async () => {
+ api.appendDailyLog.mockResolvedValue({ entry: entryFor(TODAY, 'server text') });
+ await renderTab();
+ await typeThenReceiveVoiceSegment('my unsaved edit');
+ expect(screen.getByText(/Autosave paused/i)).toBeInTheDocument();
+
+ // A quick-append adopts the server entry wholesale, resolving the divergence.
+ fireEvent.change(screen.getByPlaceholderText(/Quick append/i), { target: { value: 'note' } });
+ fireEvent.click(screen.getByText('Append'));
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+
+ // Otherwise the toolbar would tell the user to click a disabled Save button.
+ expect(screen.queryByText(/Autosave paused/i)).not.toBeInTheDocument();
+ expect(screen.getByText(/· Saved/)).toBeInTheDocument();
+
+ // ...and the park is genuinely lifted, not merely hidden by `dirty` being
+ // false: the next edit must autosave rather than stay parked forever.
+ api.updateDailyLog.mockClear();
+ fireEvent.change(editor(), { target: { value: 'server text plus more' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'server text plus more', { silent: true });
+ });
+
+ it('resumes autosaving after the voice conflict is resolved', async () => {
+ await renderTab();
+ fireEvent.change(editor(), { target: { value: 'edit one' } });
+ await act(async () => {
+ voice.handlers['voice:dailyLog:appended']({ date: TODAY, text: 'spoken', segmentCount: 2 });
+ });
+ await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
+ expect(api.updateDailyLog).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByLabelText('Save'));
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ api.updateDailyLog.mockClear();
+
+ fireEvent.change(editor(), { target: { value: 'edit two' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'edit two', { silent: true });
+ });
+
+ it('shows save status in the toolbar', async () => {
+ await renderTab();
+ expect(screen.getByText(/· Saved/)).toBeInTheDocument();
+
+ fireEvent.change(editor(), { target: { value: 'dirty now' } });
+ expect(screen.getByText(/· Unsaved…/)).toBeInTheDocument();
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+ expect(screen.getByText(/· Saved/)).toBeInTheDocument();
+ });
+});