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
feat: keep daily-log voice dictation when autosaving mid-edit
[._.]/ Adam Eivy37b64cc510f2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4b3de16860..0d3566719f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **Daily Log no longer parks autosave when voice dictation lands mid-edit.** A spoken segment is merged into the textarea (append-at-end, caret restored) instead of leaving the user to Save or refresh, and full-content saves send the last-seen `updatedAt` as `ifMatchUpdatedAt`. When a concurrent append advances that clock, the server returns 409 `STALE_JOURNAL` with the current entry; the client folds in any missing voice segments and retries once so an in-flight PUT cannot silently drop dictation.+- **Series Autopilot can learn which models actually work at each step.** AI run history now distinguishes technical completion from a later editorial keep/revert decision and aggregates evidence by orchestration step, creative-versus-judge role, provider, model, and reasoning effort. The new opt-in selector requires multiple quality-reviewed samples plus a positive reliability threshold, ignores disabled providers and removed models, and remains a soft default beneath explicit run choices and exact prompt-stage pins. The Options panel reports how much attributed and quality-reviewed evidence exists, while local APIs expose the full metrics and allow an operator to correct or backfill a historical outcome, including its effort when the older run predates effort telemetry. Concurrent metadata updates for one run are serialized so provider telemetry cannot overwrite its Autopilot step/role attribution, and internal structure-verification calls retain the judge role instead of inheriting their repairer's creative role. Foundation judges record contract-valid responses separately from true editorial approval, and foundation repairs automatically record accepted versus rolled-back outcomes, so a model that finishes a long run but makes the story worse is not learned as a success.- **Foundation structure repair retains shrinking corrective progress.** A broad structure rewrite whose specialized arc verification improved from many blockers to a smaller residual used to get one correction attempt and then roll the entire improvement back. The repair now continues a bounded correction sequence while the blocker count stays monotonic, still restoring the original checkpoint if the set grows or cannot clear within the cap.diff --git a/PLAN.md b/PLAN.mdindex 3ad25f732d..05b3ccc2a7 100644--- a/PLAN.md+++ b/PLAN.md@@ -49,21 +49,12 @@ rest — each is a perf/cleanup item, none is a correctness bug:last-writer-wins isn't guaranteed to be newest-content. Only affects installswith the "Auto-mirror to Obsidian on every save" toggle on. Consider alsore-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.+- [x] Close the dictation/autosave overwrite race properly. The client now+ merges an incoming voice segment into the textarea (append-at-end, caret+ restored) even while dirty, and PUTs carry `ifMatchUpdatedAt` so a concurrent+ append that advances the LWW clock returns 409 `STALE_JOURNAL` with the current+ entry — the client folds missing voice segments in and retries once. Removes+ the `voiceConflict` park and the "save or refresh to see it" product decision.- [ ] Extract a `useAutosave` hook when a second consumer appears. The daily lognow has ~60 lines of autosave machinery inline (debounce + max-wait ceiling +single-flight + failure-toast dedup + blur/visibility/unmount flush). The onlydiff --git a/client/src/components/brain/tabs/DailyLogTab.jsx b/client/src/components/brain/tabs/DailyLogTab.jsxindex c4b518ae10..256086bb80 100644--- a/client/src/components/brain/tabs/DailyLogTab.jsx+++ b/client/src/components/brain/tabs/DailyLogTab.jsx@@ -56,6 +56,33 @@ const shiftDate = (iso, days) => {return date.toISOString().slice(0, 10);};+// Append a dictated/typed segment to free-form journal text. Idempotent when+// the segment text is already present (socket replay / double-fire). Shared by+// the live socket path and the 409-retry merge so both stay byte-identical.+export const appendJournalSegment = (content, text) => {+ if (typeof text !== 'string' || text.length === 0) return content || '';+ const prev = content || '';+ if (prev.includes(text)) return prev;+ return prev ? `${prev.replace(/\s+$/, '')}\n\n${text}` : text;+};++// Re-apply any voice segments the server holds that the local body is missing+// — the recovery path after a STALE_JOURNAL 409 (an append landed while a PUT+// was in flight). Non-voice concurrent edits are left to the server entry's+// content only when local is empty; otherwise local typing wins and voice is+// folded back in.+export const mergeMissingVoiceSegments = (localContent, serverEntry) => {+ let next = localContent || '';+ const segs = Array.isArray(serverEntry?.segments) ? serverEntry.segments : [];+ for (const seg of segs) {+ if (seg?.source === 'voice' && typeof seg.text === 'string' && seg.text) {+ next = appendJournalSegment(next, seg.text);+ }+ }+ if (!next && serverEntry?.content) return serverEntry.content;+ return next;+};+export default function DailyLogTab() {const [date, setDate] = useState(localToday());// Backend today — resolved via GET /daily-log/today on mount so the@@ -80,12 +107,6 @@ 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@@ -109,10 +130,6 @@ export default function DailyLogTab() {// 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).- const dirtyRef = useRef(false);// Monotonic counter of outstanding loadEntry() calls so an older fetch// resolving after a newer one can't overwrite the entry state for the// wrong date (common when prev/next is mashed or the server-today fetch@@ -127,7 +144,6 @@ export default function DailyLogTab() {const pendingDictationRef = useRef(null);const dirty = content !== (entry?.content || '');- dirtyRef.current = dirty;const loadEntry = useCallback(async (d, { silent = false } = {}) => {if (!silent) setLoading(true);@@ -136,7 +152,6 @@ export default function DailyLogTab() {if (reqId !== loadRequestRef.current) return;const data = res?.entry || null;loadedDateRef.current = d;- setVoiceConflict(false);setEntry(data);setContent(data?.content || '');if (!silent) setLoading(false);@@ -235,20 +250,26 @@ export default function DailyLogTab() {});if (appendedDate === date) {setEntry((prev) => patchFullEntry(prev));- // Only sync the textarea when the user has no unsaved edits —- // otherwise an incoming voice segment would clobber whatever they're- // in the middle of typing. The entry state still updates so the- // segment count badge reflects the append.- if (!dirtyRef.current) {- setContent((prevContent) => (prevContent- ? `${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: '📝' });- }+ // Always fold the segment into the textarea — including when the user+ // has unsaved edits. Replacing wholesale used to drop typed text; the+ // previous fix parked autosave instead, which left the segment invisible+ // until Save/refresh and still lost it if a PUT was already in flight.+ // Append-at-end keeps mid-entry typing intact; restore the caret so a+ // controlled-textarea re-render doesn't jump the cursor to the end.+ setContent((prevContent) => {+ const next = appendJournalSegment(prevContent, appendedText);+ const el = editorRef.current;+ if (el && document.activeElement === el && next !== prevContent) {+ const start = el.selectionStart;+ const end = el.selectionEnd;+ queueMicrotask(() => {+ if (editorRef.current === el) {+ try { el.setSelectionRange(start, end); } catch { /* detached */ }+ }+ });+ }+ return next;+ });}};const onDictation = (payload) => {@@ -290,30 +311,44 @@ 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.+ // Adopt the server's entry wholesale, textarea included.const applyEntry = (next) => {- setVoiceConflict(false);setEntry(next);setContent(next.content || '');setHistory((prev) => upsertHistory(prev, next));};+ // One PUT attempt. Returns `{ entry }`, `{ stale, entry }` on concurrency+ // conflict, or null on transport/other failure. Never toasts — the caller+ // owns failure UX so auto vs explicit saves can differ.+ const putDailyLog = async (targetDate, body, ifMatchUpdatedAt) => {+ try {+ return await api.updateDailyLog(targetDate, body, {+ silent: true,+ ...(ifMatchUpdatedAt ? { ifMatchUpdatedAt } : {}),+ });+ } catch (err) {+ if (err?.code === 'STALE_JOURNAL' && err.context?.entry) {+ return { stale: true, entry: err.context.entry };+ }+ return null;+ }+ };+// 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;+ let body = content;+ // Optimistic concurrency token — the last entry.updatedAt we observed.+ // Voice appends advance it server-side; a PUT with a stale token 409s so+ // we can fold the segment in and retry instead of clobbering it.+ let ifMatch = entry?.updatedAt || null;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@@ -321,11 +356,29 @@ export default function DailyLogTab() {// against an already-unhealthy server.firstDirtyAtRef.current = null;setSaving(true);- const res = await api.updateDailyLog(targetDate, body, { silent: true }).catch(() => null);+ let res = await putDailyLog(targetDate, body, ifMatch);+ // One bounded retry: merge any voice segments the concurrent write added,+ // advance the ifMatch clock, and re-PUT. A second conflict (another append+ // mid-retry) falls through as failure — the next autosave tick retries.+ if (res?.stale) {+ const serverEntry = res.entry;+ body = mergeMissingVoiceSegments(body, serverEntry);+ ifMatch = serverEntry.updatedAt || null;+ if (loadedDateRef.current === targetDate && mountedRef.current) {+ setEntry(serverEntry);+ setHistory((prev) => upsertHistory(prev, serverEntry));+ // Fold the segment into the live textarea too when the user hasn't+ // typed past the body we just tried to save.+ setContent((prev) => (prev === content+ ? body+ : mergeMissingVoiceSegments(prev, serverEntry)));+ }+ res = await putDailyLog(targetDate, body, ifMatch);+ }savingRef.current = false;if (!mountedRef.current) return;setSaving(false);- if (!res?.entry) {+ if (!res?.entry || res.stale) {if (!auto || !autoSaveFailedRef.current) toast.error('Save failed');autoSaveFailedRef.current = true;lastFailedBodyRef.current = body;@@ -333,10 +386,10 @@ export default function DailyLogTab() {}autoSaveFailedRef.current = false;lastFailedBodyRef.current = null;- // 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.+ // Adopt the server's metadata but deliberately leave the textarea alone+ // when the user typed during the in-flight PUT — those keystrokes stay in+ // `content` and stay dirty against res.entry.content, so the next tick+ // saves them. applyEntry() would revert them to the server's echo.if (loadedDateRef.current === targetDate) {setEntry(res.entry);setHistory((prev) => upsertHistory(prev, res.entry));@@ -344,17 +397,13 @@ export default function DailyLogTab() {if (!auto) toast.success('Saved');};- const handleSave = () => {- // Explicit save = the user choosing their edits over the unmerged segment.- setVoiceConflict(false);- return saveRef.current?.();- };+ const handleSave = () => 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) {+ if (!dirty || loadedDateRef.current !== date) {firstDirtyAtRef.current = null;return undefined;}@@ -370,7 +419,7 @@ export default function DailyLogTab() {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]);+ }, [content, dirty, saving, 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@@ -439,7 +488,6 @@ export default function DailyLogTab() {}toast.success('Deleted');setConfirmDelete(false);- setVoiceConflict(false);setEntry(null);setContent('');setHistory((prev) => prev.filter((h) => h.date !== date));@@ -503,12 +551,7 @@ export default function DailyLogTab() {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' : '';@@ -761,7 +804,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}+ {saveStatus ? <span> · {saveStatus}</span> : null}</div></div><buttondiff --git a/client/src/components/brain/tabs/DailyLogTab.test.jsx b/client/src/components/brain/tabs/DailyLogTab.test.jsxindex 2cd35d9f8c..ab66ca37fc 100644--- a/client/src/components/brain/tabs/DailyLogTab.test.jsx+++ b/client/src/components/brain/tabs/DailyLogTab.test.jsx@@ -82,7 +82,10 @@ beforeEach(() => {const date = d === 'today' ? TODAY : d;return { date, entry: store[date] || null };});- api.updateDailyLog.mockImplementation(async (date, content) => ({ date, entry: entryFor(date, content) }));+ api.updateDailyLog.mockImplementation(async (date, content) => ({+ date,+ entry: { ...entryFor(date, content), updatedAt: `${date}T12:30:00Z` },+ }));api.listDailyLogs.mockResolvedValue({ records: [] });api.getDailyLogSettings.mockResolvedValue({});api.getActivityDigestSettings.mockResolvedValue({});@@ -105,16 +108,16 @@ const backgroundTab = async () => {});};-// 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) => {+// Unsaved typed edits, then a dictated segment lands server-side. Delivered+// in its own act() so React commits state before any timer advances — as the+// real socket event does. The segment is merged into the textarea (no park).+const typeThenReceiveVoiceSegment = async (typed, spoken = 'spoken words') => {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' },+ text: spoken,+ segment: { text: spoken, at: `${TODAY}T12:01:00Z`, source: 'voice' },segmentCount: 2,updatedAt: `${TODAY}T12:01:00Z`,});@@ -132,7 +135,10 @@ describe('DailyLogTab autosave', () => {await act(async () => { await vi.advanceTimersByTimeAsync(200); });expect(api.updateDailyLog).toHaveBeenCalledTimes(1);- expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'a new thought', { silent: true });+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'a new thought', {+ silent: true,+ ifMatchUpdatedAt: `${TODAY}T12:00:00Z`,+ });});it('coalesces a burst of keystrokes into one save', async () => {@@ -145,7 +151,10 @@ describe('DailyLogTab autosave', () => {await act(async () => { await vi.advanceTimersByTimeAsync(1600); });expect(api.updateDailyLog).toHaveBeenCalledTimes(1);- expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'abcd', { silent: true });+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'abcd', {+ silent: true,+ ifMatchUpdatedAt: `${TODAY}T12:00:00Z`,+ });});it('still saves during an uninterrupted typing run (max-wait ceiling)', async () => {@@ -166,7 +175,10 @@ describe('DailyLogTab autosave', () => {await act(async () => { await vi.advanceTimersByTimeAsync(0); });expect(api.updateDailyLog).toHaveBeenCalledTimes(1);- expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'typed then left', { silent: true });+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'typed then left', {+ silent: true,+ ifMatchUpdatedAt: `${TODAY}T12:00:00Z`,+ });});it('saves when the tab is backgrounded', async () => {@@ -174,7 +186,10 @@ describe('DailyLogTab autosave', () => {fireEvent.change(editor(), { target: { value: 'backgrounded' } });await backgroundTab();- expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'backgrounded', { silent: true });+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'backgrounded', {+ silent: true,+ ifMatchUpdatedAt: `${TODAY}T12:00:00Z`,+ });});it('flushes on unmount so an edit inside the debounce window is not lost', async () => {@@ -184,7 +199,10 @@ describe('DailyLogTab autosave', () => {// 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 });+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'typed then navigated away', {+ silent: true,+ ifMatchUpdatedAt: `${TODAY}T12:00:00Z`,+ });});it('does not save when nothing changed', async () => {@@ -269,13 +287,19 @@ describe('DailyLogTab autosave', () => {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) });+ release = () => resolve({+ date,+ entry: { ...entryFor(date, content), updatedAt: `${date}T12:30:00Z` },+ });}));await renderTab();fireEvent.change(editor(), { target: { value: 'first' } });await act(async () => { await vi.advanceTimersByTimeAsync(1600); });- expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'first', { silent: true });+ expect(api.updateDailyLog).toHaveBeenCalledWith(TODAY, 'first', {+ silent: true,+ ifMatchUpdatedAt: `${TODAY}T12:00:00Z`,+ });// Type while the PUT is still open, then let it resolve.fireEvent.change(editor(), { target: { value: 'first second' } });@@ -286,7 +310,10 @@ describe('DailyLogTab autosave', () => {// ...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 });+ expect(api.updateDailyLog).toHaveBeenLastCalledWith(TODAY, 'first second', {+ silent: true,+ ifMatchUpdatedAt: `${TODAY}T12:30:00Z`,+ });});it('never writes one day\'s text into another after a date change', async () => {@@ -312,78 +339,93 @@ describe('DailyLogTab autosave', () => {expect(editor().value).toBe('old day');});- it('parks autosave when a dictated segment lands mid-edit', async () => {+ it('merges a dictated segment into dirty text and keeps autosaving', async () => {await renderTab();- await typeThenReceiveVoiceSegment('my unsaved edit');- await act(async () => { await vi.advanceTimersByTimeAsync(3000); });+ await typeThenReceiveVoiceSegment('my unsaved edit', 'spoken words');- expect(api.updateDailyLog).not.toHaveBeenCalled();- expect(screen.getByText(/Autosave paused/i)).toBeInTheDocument();+ // Textarea keeps typed text AND the new segment — no park, no toast gate.+ expect(editor().value).toBe('my unsaved edit\n\nspoken words');+ expect(screen.queryByText(/Autosave paused/i)).not.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 });+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ expect(api.updateDailyLog).toHaveBeenCalledWith(+ TODAY,+ 'my unsaved edit\n\nspoken words',+ { silent: true, ifMatchUpdatedAt: `${TODAY}T12:01:00Z` },+ );});- // 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 () => {+ it('blur flush after a mid-edit voice segment still saves the merge', async () => {await renderTab();- await typeThenReceiveVoiceSegment('my unsaved edit');+ await typeThenReceiveVoiceSegment('my unsaved edit', 'spoken words');fireEvent.blur(editor());await act(async () => { await vi.advanceTimersByTimeAsync(0); });- expect(api.updateDailyLog).not.toHaveBeenCalled();+ expect(api.updateDailyLog).toHaveBeenCalledWith(+ TODAY,+ 'my unsaved edit\n\nspoken words',+ { silent: true, ifMatchUpdatedAt: `${TODAY}T12:01:00Z` },+ );});- it('parks the background flush too', async () => {+ it('background flush after a mid-edit voice segment still saves the merge', async () => {await renderTab();- await typeThenReceiveVoiceSegment('my unsaved edit');+ await typeThenReceiveVoiceSegment('my unsaved edit', 'spoken words');await backgroundTab();- expect(api.updateDailyLog).not.toHaveBeenCalled();+ expect(api.updateDailyLog).toHaveBeenCalledWith(+ TODAY,+ 'my unsaved edit\n\nspoken words',+ { silent: true, ifMatchUpdatedAt: `${TODAY}T12:01:00Z` },+ );});- it('lifts the park once the entry is re-adopted from the server', async () => {- api.appendDailyLog.mockResolvedValue({ entry: entryFor(TODAY, 'server text') });+ it('retries a STALE_JOURNAL 409 by folding in the concurrent voice segment', async () => {+ const staleEntry = {+ date: TODAY,+ content: 'existing\n\nspoken mid-flight',+ segments: [+ { text: 'existing', at: `${TODAY}T12:00:00Z`, source: 'edit' },+ { text: 'spoken mid-flight', at: `${TODAY}T12:02:00Z`, source: 'voice' },+ ],+ segmentCount: 2,+ updatedAt: `${TODAY}T12:02:00Z`,+ obsidianPath: null,+ };+ let calls = 0;+ api.updateDailyLog.mockImplementation(async (date, content, opts) => {+ calls += 1;+ if (calls === 1) {+ const err = new Error('Daily log was modified since you last loaded it');+ err.code = 'STALE_JOURNAL';+ err.status = 409;+ err.context = { entry: staleEntry };+ throw err;+ }+ return {+ date,+ entry: { ...entryFor(date, content), updatedAt: `${date}T12:03:00Z` },+ };+ });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' } });+ fireEvent.change(editor(), { target: { value: 'typed while speaking' } });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 });+ // First attempt used the pre-append clock; retry merges the voice text+ // and re-PUTs against the server's new updatedAt.+ expect(api.updateDailyLog).toHaveBeenCalledTimes(2);+ expect(api.updateDailyLog.mock.calls[0]).toEqual([+ TODAY,+ 'typed while speaking',+ { silent: true, ifMatchUpdatedAt: `${TODAY}T12:00:00Z` },+ ]);+ expect(api.updateDailyLog.mock.calls[1]).toEqual([+ TODAY,+ 'typed while speaking\n\nspoken mid-flight',+ { silent: true, ifMatchUpdatedAt: `${TODAY}T12:02:00Z` },+ ]);+ // Textarea reflects the merged recovery (no further typing in this test).+ expect(editor().value).toBe('typed while speaking\n\nspoken mid-flight');});it('shows save status in the toolbar', async () => {diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex 7fde7fbaf1..0b57d4ad43 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -299,10 +299,20 @@ export const appendDailyLog = (date, text, source = 'text', options = {}) => req`/brain/daily-log/${encodeURIComponent(date)}/append`,{ method: 'POST', body: JSON.stringify({ text, source }), ...options });-export const updateDailyLog = (date, content, options = {}) => request(- `/brain/daily-log/${encodeURIComponent(date)}`,- { method: 'PUT', body: JSON.stringify({ content }), ...options }-);+export const updateDailyLog = (date, content, options = {}) => {+ // `ifMatchUpdatedAt` is an optimistic concurrency token (the entry's+ // updatedAt the client last observed). It rides in the JSON body; the rest+ // of `options` (silent, headers, …) are request() fetch options.+ const { ifMatchUpdatedAt, ...requestOptions } = options;+ const body = { content };+ if (ifMatchUpdatedAt !== undefined && ifMatchUpdatedAt !== null) {+ body.ifMatchUpdatedAt = ifMatchUpdatedAt;+ }+ return request(+ `/brain/daily-log/${encodeURIComponent(date)}`,+ { method: 'PUT', body: JSON.stringify(body), ...requestOptions }+ );+};export const deleteDailyLog = (date, options = {}) => request(`/brain/daily-log/${encodeURIComponent(date)}`,{ method: 'DELETE', ...options }diff --git a/server/routes/brain.test.js b/server/routes/brain.test.jsindex 0aa2a290f2..c5b2b951e7 100644--- a/server/routes/brain.test.js+++ b/server/routes/brain.test.js@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';+import { ServerError } from '../lib/errorHandler.js';import brainRoutes from './brain.js';// Mock the brain service@@ -1301,6 +1302,42 @@ describe('Brain Routes', () => {.send({ content: 'replaced' });expect(res.status).toBe(200);expect(res.body.entry.content).toBe('replaced');+ expect(journal.setJournalContent).toHaveBeenCalledWith('2026-04-17', 'replaced', {+ ifMatchUpdatedAt: null,+ });+ });++ it('forwards ifMatchUpdatedAt to the service', async () => {+ journal.setJournalContent.mockResolvedValue({ id: 'j1', date: '2026-04-17', content: 'x', segments: [] });+ const res = await request(app)+ .put('/api/brain/daily-log/2026-04-17')+ .send({ content: 'x', ifMatchUpdatedAt: '2026-04-17T12:00:00.000Z' });+ expect(res.status).toBe(200);+ expect(journal.setJournalContent).toHaveBeenCalledWith('2026-04-17', 'x', {+ ifMatchUpdatedAt: '2026-04-17T12:00:00.000Z',+ });+ });++ it('surfaces STALE_JOURNAL as 409 with the current entry in context', async () => {+ const current = {+ id: 'j1',+ date: '2026-04-17',+ content: 'existing\n\nspoken',+ updatedAt: '2026-04-17T12:01:00.000Z',+ segments: [{ text: 'spoken', source: 'voice' }],+ };+ const err = new ServerError('Daily log was modified since you last loaded it', {+ status: 409,+ code: 'STALE_JOURNAL',+ context: { entry: current },+ });+ journal.setJournalContent.mockRejectedValue(err);+ const res = await request(app)+ .put('/api/brain/daily-log/2026-04-17')+ .send({ content: 'typed', ifMatchUpdatedAt: '2026-04-17T12:00:00.000Z' });+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('STALE_JOURNAL');+ expect(res.body.context.entry.content).toContain('spoken');});});diff --git a/server/routes/brainDailyLog.js b/server/routes/brainDailyLog.jsindex 9167cd0052..4175a4f58d 100644--- a/server/routes/brainDailyLog.js+++ b/server/routes/brainDailyLog.js@@ -127,14 +127,21 @@ router.post('/daily-log/:date/draft', asyncHandler(async (req, res) => {/*** PUT /api/brain/daily-log/:date — full content replace+ *+ * Optional `ifMatchUpdatedAt` (ISO string from the client's last-known entry)+ * is an optimistic concurrency token: when present, a concurrent voice append+ * or peer write that advanced `updatedAt` returns 409 STALE_JOURNAL with the+ * current entry in `context.entry` so the client can merge and retry instead+ * of silently dropping the concurrent work.*/router.put('/daily-log/:date', asyncHandler(async (req, res) => {const date = await resolveJournalDate(req.params.date);- const { content } = req.body || {};+ const { content, ifMatchUpdatedAt } = req.body || {};if (typeof content !== 'string') {throw new ServerError('content is required', { status: 400, code: 'BAD_REQUEST' });}- const entry = await journal.setJournalContent(date, content);+ const match = typeof ifMatchUpdatedAt === 'string' ? ifMatchUpdatedAt : null;+ const entry = await journal.setJournalContent(date, content, { ifMatchUpdatedAt: match });res.json({ date, entry });}));diff --git a/server/services/brainJournal.js b/server/services/brainJournal.jsindex 1593544d62..e472880128 100644--- a/server/services/brainJournal.js+++ b/server/services/brainJournal.js@@ -25,6 +25,7 @@import { join } from 'path';import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';+import { ServerError } from '../lib/errorHandler.js';import { replaceMarkedSection } from '../lib/markedSection.js';import * as brainStorage from './brainStorage.js';import { brainEvents, now } from './brainStorage.js';@@ -254,10 +255,38 @@ function scheduleObsidianSync(entry) {pendingObsidianSyncs.set(date, next);}-export async function setJournalContent(date, content) {+/**+ * Full-content rewrite for a day.+ *+ * @param {string} date ISO YYYY-MM-DD+ * @param {string} content Replacement body+ * @param {{ ifMatchUpdatedAt?: string|null }} [opts]+ * When `ifMatchUpdatedAt` is a non-empty string, the write is rejected with+ * `STALE_JOURNAL` (409) if the on-disk entry's `updatedAt` differs — i.e. a+ * concurrent voice append, another tab, or a peer moved the LWW clock since+ * the client last observed it. The error's `context.entry` is the current+ * record so the client can merge and retry. Absent/empty ifMatch is a+ * force-write (legacy callers, explicit "save my edits" without a base).+ */+export async function setJournalContent(date, content, { ifMatchUpdatedAt } = {}) {if (!isIsoDate(date)) throw new Error(`invalid date: ${date}`);const entry = await storeMutex(async () => {const existing = await getEntry(date);+ // Precondition: a full rewrite based on a known updatedAt must not clobber+ // a concurrent append (voice dictation is the common case — the client+ // autosave and the append share the same day key).+ if (+ typeof ifMatchUpdatedAt === 'string'+ && ifMatchUpdatedAt.length > 0+ && existing?.updatedAt+ && existing.updatedAt !== ifMatchUpdatedAt+ ) {+ throw new ServerError('Daily log was modified since you last loaded it', {+ status: 409,+ code: 'STALE_JOURNAL',+ context: { entry: existing },+ });+ }const clean = content || '';const next = {...(existing || newEntry(date)),diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.jsindex 2b797dc918..f74b31433b 100644--- a/server/services/brainJournal.test.js+++ b/server/services/brainJournal.test.js@@ -40,7 +40,12 @@ vi.mock('./obsidian.js', () => ({// real while staying isolated from disk. Mirrors brainStorage semantics:// getById/getAll strip tombstones and re-attach the map key as `id`;// upsertWithId stores the record verbatim and stamps createdAt/updatedAt.-const { journalRecords } = vi.hoisted(() => ({ journalRecords: new Map() }));+// `updatedAt` advances per write (monotonic fake clock) so ifMatch concurrency+// tests can observe a real LWW move between append and rewrite.+const { journalRecords, clock } = vi.hoisted(() => ({+ journalRecords: new Map(),+ clock: { n: 0 },+}));vi.mock('./brainStorage.js', () => ({brainEvents: { emit: vi.fn() },now: () => '2026-04-17T12:00:00.000Z',@@ -54,17 +59,23 @@ vi.mock('./brainStorage.js', () => ({.map(([id, rec]) => ({ id, ...rec }))),upsertWithId: vi.fn(async (_type, id, record) => {const existing = journalRecords.get(id);+ clock.n += 1;+ const stamp = `2026-04-17T12:00:${String(clock.n).padStart(2, '0')}.000Z`;const stored = {...record,- createdAt: existing?.createdAt ?? '2026-04-17T12:00:00.000Z',- updatedAt: '2026-04-17T12:00:00.000Z',+ createdAt: existing?.createdAt ?? stamp,+ updatedAt: stamp,};journalRecords.set(id, stored);return { id, ...stored };}),remove: vi.fn(async (_type, id) => {if (!journalRecords.has(id)) return false;- journalRecords.set(id, { _deleted: true, updatedAt: '2026-04-17T12:00:00.000Z' });+ clock.n += 1;+ journalRecords.set(id, {+ _deleted: true,+ updatedAt: `2026-04-17T12:00:${String(clock.n).padStart(2, '0')}.000Z`,+ });return true;}),}));@@ -88,6 +99,7 @@ describe('brainJournal', () => {rmSync(TEMP_ROOT, { recursive: true, force: true });mkdirSync(TEMP_ROOT, { recursive: true });journalRecords.clear();+ clock.n = 0;journal._clearObsidianLocationsCacheForTest();vi.clearAllMocks();});@@ -209,6 +221,43 @@ describe('brainJournal', () => {entry: { content: 'brand new' },});});++ it('rejects a stale ifMatchUpdatedAt with STALE_JOURNAL and the current entry', async () => {+ const first = await journal.setJournalContent('2026-04-17', 'typed');+ await journal.appendJournal('2026-04-17', 'spoken', { source: 'voice' });+ await expect(+ journal.setJournalContent('2026-04-17', 'typed plus more', {+ ifMatchUpdatedAt: first.updatedAt,+ }),+ ).rejects.toMatchObject({+ status: 409,+ code: 'STALE_JOURNAL',+ context: {+ entry: expect.objectContaining({+ content: expect.stringContaining('spoken'),+ }),+ },+ });+ // On-disk content must be untouched by the rejected rewrite.+ const current = await journal.getJournal('2026-04-17');+ expect(current.content).toContain('spoken');+ expect(current.content).not.toContain('typed plus more');+ });++ it('accepts a rewrite when ifMatchUpdatedAt matches the current clock', async () => {+ const first = await journal.setJournalContent('2026-04-17', 'base');+ const next = await journal.setJournalContent('2026-04-17', 'revised', {+ ifMatchUpdatedAt: first.updatedAt,+ });+ expect(next.content).toBe('revised');+ });++ it('force-writes when ifMatchUpdatedAt is omitted (legacy callers)', async () => {+ await journal.setJournalContent('2026-04-17', 'base');+ await journal.appendJournal('2026-04-17', 'spoken', { source: 'voice' });+ const forced = await journal.setJournalContent('2026-04-17', 'overwrite all');+ expect(forced.content).toBe('overwrite all');+ });});describe('deleteJournal', () => {