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: serialize messageSync cache mutators under per-account locks (#2537)

Adam Eivy8d49d720384e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4cb3eaebb2..2e6ec78369 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,7 @@
## Fixed
+- **[issue-2537] Serialize message-cache mutators under a per-account write lock.** `refreshMessage` and `updateMessageEvaluations` did their `load → mutate → saveCache` outside the per-account `syncLocks`, so a full-body refresh or an evaluation write racing a concurrent sync (or each other) could clobber the other's update on the shared `data/messages/cache/<accountId>.json` file. All three cache mutators (`syncAccount`, `refreshMessage`, `updateMessageEvaluations`) now route their write region through one per-account tail (`createKeyCachedQueue`), so each awaits the previous and re-reads the freshest persisted state before merging — mirroring `issueWriteTail` in `pipeline/issues.js`. The existing `syncLocks` boolean still rejects a duplicate in-flight sync with 409. Regression tests assert two concurrent mutators both persist.
- **[issue-2543] Cancel stale ⌘K global search responses and clear the Security device-change restart timer.** The command palette's global `search(query)` effect debounced the request but had no in-flight guard, so a slow response for an older query could resolve after the user typed on and overwrite the newer query's results (or flip the loading spinner off prematurely) — the sibling catalog-search effect already used a `cancelled` flag. The global-search effect now mirrors that `cancelled` guard so only the latest query's response applies. Separately, `Security.jsx`'s device-change handler scheduled `setTimeout(startMedia, 100)` with no clear on unmount or before rescheduling, so rapid device switches stacked multiple `startMedia()` calls and a navigation-away could fire the restart into an unmounted component; the timer id is now held in a ref, cleared before each reschedule, and cleared in an unmount cleanup effect. A regression test asserts a stale search response can't clobber the current query's results.
- **POST session run page crashed (React error #130) when transitioning into a cognitive drill.** `DrillTransition.jsx`'s `DOMAIN_ICONS` map was missing a `cognitive` entry, yet `DRILL_TO_DOMAIN` maps every cognitive drill type (n-back, digit-span, stroop, schulte-table, mental-rotation, reaction-time) to the `cognitive` domain — so finishing a drill whose successor was a cognitive drill (e.g. a Doubling Chain followed by a cognitive drill) resolved the transition-card icon to `undefined` and blanked the run page with a minified React error. Added the `cognitive: Brain` icon and hardened the lookup to fall back to `ChevronRight` for any unmapped domain, so a future domain gap degrades gracefully instead of crashing. A regression test renders the transition for every `DRILL_TO_DOMAIN` type.
- **[issue-2549] Enforce the Windows `.exe` basename contract in the CoS Runner allowlist test.** The `allowedCommands.test.js` case for a Windows absolute path (`C:\\...\\claude.exe`) ended on `expect(typeof result).toBe('boolean')`, which passes for any boolean — so on POSIX CI the Windows path handling was never actually asserted and a regression would go unnoticed. It's replaced with concrete assertions: a POSIX-style `.exe` path (`/opt/tools/claude.exe`) that exercises the basename-then-strip logic deterministically on every OS (allowed), a matching rejection for a non-allowlisted `.exe` (`/opt/tools/bash.exe`), and a per-platform assertion for the real backslash form that expects `true` on `win32` and `false` on POSIX (where `path.basename` doesn't split backslashes). Both new assertions were verified to fail against a broken implementation (dropping the `.exe` strip; forcing `win32` basename on POSIX). Test-only change — no runtime behavior change.
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 829c00d243..6e17330864 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -5,10 +5,25 @@ import { atomicWrite, ensureDir, filterBySearch as genericFilterBySearch, PATHS,
import { getAccount, updateSyncStatus } from './messageAccounts.js';
import { getUserTimezone, getLocalParts } from '../lib/timezone.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
const CACHE_DIR = join(PATHS.messages, 'cache');
+// `syncLocks` is a boolean re-entrancy guard that rejects a *duplicate* in-flight
+// sync for an account with a 409 (you never want two full syncs racing).
const syncLocks = new Map();
+// Per-account cache write tail. EVERY load→mutate→saveCache region for an account
+// routes through this single tail so it serializes against the account's sync and
+// against every other mutator (#2537): `syncAccount`, `refreshMessage`, and
+// `updateMessageEvaluations` all share the one `${accountId}.json` cache file, so
+// two that interleave their load/save would clobber each other's writes. The tail
+// makes each one await the previous and re-read the freshest persisted state
+// inside its serialized region — mirroring `issueWriteTail` in pipeline/issues.js.
+const accountWriteQueue = createKeyCachedQueue();
+function queueAccountWrite(accountId, work) {
+ return accountWriteQueue(accountId, work);
+}
+
const MESSAGE_SEARCH_FIELDS = ['subject', 'from.name', 'from.email', 'bodyText'];
function filterBySearch(messages, search) {
return genericFilterBySearch(messages, search, MESSAGE_SEARCH_FIELDS);
@@ -215,7 +230,11 @@ export async function syncAccount(accountId, io, options = {}) {
return { newMessages: uniqueNew.length, pruned, total: cache.messages.length, status: providerStatus };
};
- const result = await providerSync().catch(async (error) => {
+ // Serialize the load→mutate→save region against `refreshMessage` /
+ // `updateMessageEvaluations` on the same account (#2537). `syncLocks` already
+ // blocks a second concurrent sync; the tail additionally orders the sync's
+ // write against the other cache mutators so none clobbers the others.
+ const result = await queueAccountWrite(accountId, providerSync).catch(async (error) => {
console.error(`📧 Sync failed for ${account.name} (${account.type}): ${error.message}`);
await updateSyncStatus(accountId, 'error').catch(() => {});
io?.emit('messages:sync:failed', { accountId, error: error.message });
@@ -228,6 +247,11 @@ export async function syncAccount(accountId, io, options = {}) {
}
export async function refreshMessage(accountId, messageId) {
+ // Serialize the whole load→extract→mutate→save region through the per-account
+ // tail (#2537) so a concurrent sync or evaluation update can't clobber the
+ // refreshed body (and vice versa). The cache is (re)loaded inside the tail so
+ // it merges against the freshest persisted state.
+ return queueAccountWrite(accountId, async () => {
const cache = await loadCache(accountId);
const message = cache.messages.find(m => m.id === messageId);
if (!message) {
@@ -312,6 +336,7 @@ export async function refreshMessage(accountId, messageId) {
await saveCache(accountId, cache);
return updatedMessages.map(m => ({ ...m, accountId }));
+ });
}
export async function updateMessageEvaluations(evaluations) {
@@ -322,15 +347,20 @@ export async function updateMessageEvaluations(evaluations) {
if (!file.endsWith('.json')) continue;
const accountId = file.replace('.json', '');
if (!UUID_RE.test(accountId)) continue;
- const cache = await loadCache(accountId);
- let changed = false;
- for (const msg of cache.messages) {
- if (evaluations[msg.id]) {
- msg.evaluation = evaluations[msg.id];
- changed = true;
+ // Serialize each account's load→mutate→save through the per-account tail
+ // (#2537) so a concurrent sync/refresh doesn't clobber the written
+ // evaluations (and vice versa); the cache reloads inside the tail.
+ await queueAccountWrite(accountId, async () => {
+ const cache = await loadCache(accountId);
+ let changed = false;
+ for (const msg of cache.messages) {
+ if (evaluations[msg.id]) {
+ msg.evaluation = evaluations[msg.id];
+ changed = true;
+ }
}
- }
- if (changed) await saveCache(accountId, cache);
+ if (changed) await saveCache(accountId, cache);
+ });
}
}
diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.js
index 7bb7b0fe72..e000d3020f 100644
--- a/server/services/messageSync.test.js
+++ b/server/services/messageSync.test.js
@@ -76,7 +76,7 @@ vi.mock('../lib/timezone.js', () => ({
import { readdir, unlink } from 'fs/promises';
import { tryReadFile as readFile, atomicWrite } from '../lib/fileUtils.js';
-import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage, logMessageTouchpoints } from './messageSync.js';
+import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage, updateMessageEvaluations, logMessageTouchpoints } from './messageSync.js';
import { autoLogTouchpoints } from './tribe.js';
import { getAccount, updateSyncStatus } from './messageAccounts.js';
import { syncGmail } from './messageGmailSync.js';
@@ -596,6 +596,74 @@ describe('refreshMessage', () => {
});
});
+// ─── Per-account write-tail serialization (#2537) ───
+// These prove the cache mutators (`updateMessageEvaluations`, `refreshMessage`)
+// serialize against each other on the same account so two concurrent load→save
+// regions can't clobber each other. The mock is stateful — reads see the last
+// write — and each op takes a tick, so an UNSERIALIZED implementation would load
+// stale state and lose the other op's update, failing these assertions.
+
+describe('cache mutator serialization (#2537)', () => {
+ const tick = () => new Promise((r) => setTimeout(r, 5));
+
+ // Wire readFile/atomicWrite to a shared in-memory cache so interleaved
+ // load→save regions race exactly as they would on disk.
+ function statefulCache(initial) {
+ let stored = initial;
+ readFile.mockImplementation(async () => {
+ await tick();
+ return JSON.stringify(stored);
+ });
+ atomicWrite.mockImplementation(async (_path, data) => {
+ await tick();
+ stored = data;
+ });
+ return () => stored;
+ }
+
+ it('serializes syncAccount against refreshMessage (both writes survive)', async () => {
+ const getStored = statefulCache({
+ messages: [{ id: 'msg-1', externalId: 'ext-1', from: { name: 'Ada' }, subject: 'Hi', date: '2026-01-01', bodyText: 'old' }],
+ });
+ getAccount.mockResolvedValue({ id: VALID_UUID, name: 'Gmail', type: 'gmail', enabled: true });
+ updateSyncStatus.mockResolvedValue();
+ // Sync appends a brand-new message (ext-2); refresh rewrites msg-1's body.
+ syncGmail.mockResolvedValue([{ id: 'srv-2', externalId: 'ext-2', subject: 'New', date: '2026-01-02', from: { name: 'Bob' } }]);
+ refreshMessageDetail.mockResolvedValue([{ from: 'Ada', date: '2026-01-01', body: 'refreshed body' }]);
+
+ await Promise.all([
+ syncAccount(VALID_UUID, null),
+ refreshMessage(VALID_UUID, 'msg-1'),
+ ]);
+
+ const messages = getStored().messages;
+ // Serialization preserves BOTH: the synced message AND the refreshed body.
+ // An unserialized interleave drops whichever saved first.
+ expect(messages.find((m) => m.externalId === 'ext-2')).toBeTruthy();
+ expect(messages.find((m) => m.id === 'msg-1').bodyText).toBe('refreshed body');
+ });
+
+ it('serializes refreshMessage against updateMessageEvaluations (both writes survive)', async () => {
+ const getStored = statefulCache({
+ messages: [{ id: 'msg-1', from: { name: 'Ada' }, subject: 'Hi', date: '2026-01-01', bodyText: 'old' }],
+ });
+ readdir.mockImplementation(async () => [`${VALID_UUID}.json`]);
+ getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook' });
+ refreshMessageDetail.mockResolvedValue([{ from: 'Ada', date: '2026-01-01', body: 'refreshed body' }]);
+
+ // Body refresh and evaluation update both mutate msg-1 concurrently.
+ await Promise.all([
+ refreshMessage(VALID_UUID, 'msg-1'),
+ updateMessageEvaluations({ 'msg-1': { score: 9 } }),
+ ]);
+
+ const msg1 = getStored().messages.find((m) => m.id === 'msg-1');
+ // Serialization preserves BOTH writes; a clobber would drop one of them.
+ expect(msg1.bodyText).toBe('refreshed body');
+ expect(msg1.evaluation).toEqual({ score: 9 });
+ });
+});
+
describe('logMessageTouchpoints — candidate building (#2033)', () => {
const account = { id: VALID_UUID, type: 'gmail', email: '[email protected]' };