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: batch Outlook full-message cache refreshes

[._.]/ Adam Eivy24367a361d36
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 63c4e4e074..c4a1d4be1b 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -14532,7 +14532,7 @@
"sources": [
{
"source": "server/routes/messages.js",
- "line": 500
+ "line": 495
}
]
},
@@ -14543,7 +14543,7 @@
"sources": [
{
"source": "server/routes/messages.js",
- "line": 435
+ "line": 430
}
]
},
@@ -14609,7 +14609,7 @@
"sources": [
{
"source": "server/routes/messages.js",
- "line": 425
+ "line": 420
}
]
},
@@ -14620,7 +14620,7 @@
"sources": [
{
"source": "server/routes/messages.js",
- "line": 492
+ "line": 487
}
]
},
@@ -14631,7 +14631,7 @@
"sources": [
{
"source": "server/routes/messages.js",
- "line": 456
+ "line": 451
}
]
},
@@ -14642,7 +14642,7 @@
"sources": [
{
"source": "server/routes/messages.js",
- "line": 451
+ "line": 446
}
]
},
diff --git a/server/routes/messages.js b/server/routes/messages.js
index 698a492cf4..618f66712f 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -410,12 +410,7 @@ router.post('/fetch-full/:accountId', asyncHandler(async (req, res) => {
const allResult = await messageSync.getMessages({ accountId, limit: FULL_BODY_REFRESH_LIMIT });
const truncated = allResult.messages.length >= FULL_BODY_REFRESH_LIMIT;
const toRefresh = force ? allResult.messages : allResult.messages.filter(m => m.bodyFull === false);
- let updated = 0;
-
- for (const msg of toRefresh) {
- const result = await messageSync.refreshMessage(accountId, msg.id);
- if (result) updated++;
- }
+ const { updated } = await messageSync.refreshMessages(accountId, toRefresh.map(msg => msg.id));
if (updated > 0) req.app.get('io')?.emit('messages:changed', {});
res.json({ updated, total: toRefresh.length, truncated });
diff --git a/server/routes/messages.test.js b/server/routes/messages.test.js
index 9128fe3e2b..ec92ef919e 100644
--- a/server/routes/messages.test.js
+++ b/server/routes/messages.test.js
@@ -19,6 +19,8 @@ vi.mock('../services/messageSync.js', () => ({
getMessages: vi.fn(),
getMessage: vi.fn(),
getThread: vi.fn(),
+ refreshMessage: vi.fn(),
+ refreshMessages: vi.fn(),
deleteCache: vi.fn()
}));
@@ -549,6 +551,28 @@ describe('Messages Routes', () => {
});
});
+ describe('POST /api/messages/fetch-full/:accountId', () => {
+ it('refreshes preview-only messages in one batch', async () => {
+ messageAccounts.getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook' });
+ messageSync.getMessages.mockResolvedValue({
+ messages: [
+ { id: 'msg-1', bodyFull: false },
+ { id: 'msg-2', bodyFull: true },
+ { id: 'msg-3', bodyFull: false },
+ ],
+ total: 3,
+ });
+ messageSync.refreshMessages.mockResolvedValue({ updated: 2, results: [[], []] });
+
+ const response = await request(app).post(`/api/messages/fetch-full/${VALID_UUID}`);
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ updated: 2, total: 2, truncated: false });
+ expect(messageSync.refreshMessages).toHaveBeenCalledTimes(1);
+ expect(messageSync.refreshMessages).toHaveBeenCalledWith(VALID_UUID, ['msg-1', 'msg-3']);
+ });
+ });
+
// === Browser Launch Route ===
describe('POST /api/messages/launch/:accountId', () => {
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index c66d5609e3..2c889d0adf 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -15,7 +15,7 @@ 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
+// against every other mutator (#2537): `syncAccount`, `refreshMessages`, 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
@@ -343,46 +343,17 @@ export async function syncAccount(accountId, io, options = {}) {
return result;
}
-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) {
- console.log(`📧 Refresh: message ${messageId} not found in cache`);
- return null;
- }
-
- const account = await getAccount(accountId);
- if (!account) {
- console.log(`📧 Refresh: account ${accountId} not found`);
- return null;
- }
-
- console.log(`📧 Refreshing "${message.subject}" via ${account.type}`);
- const { refreshMessageDetail } = await import('./messagePlaywrightSync.js');
- const detail = await refreshMessageDetail(account, message);
- // Structured error from refreshMessageDetail
- if (detail && detail.error) return detail;
- if (!detail || !Array.isArray(detail) || detail.length === 0) {
- console.log(`📧 Refresh: no detail returned`);
- return { error: 'extraction-failed', message: 'Could not extract message content — the message may not be visible in the Outlook inbox' };
- }
-
+function mergeRefreshedMessage(cache, existingByExternalId, accountId, source, message, detail) {
function makeExternalId(date, sender, subject) {
return 'pw-' + createHash('md5').update(`${date}|${sender}|${subject}`).digest('hex').slice(0, 12);
}
- const threadKey = message.threadId || `thread-${message.externalId || messageId}`;
- const existingMap = new Map(cache.messages.filter(m => m.externalId).map(m => [m.externalId, m]));
+ const threadKey = message.threadId || `thread-${message.externalId || message.id}`;
const updatedMessages = [];
for (const threadMsg of detail) {
const extId = makeExternalId(threadMsg.date || message.date || '', threadMsg.from || message.from?.name || '', message.subject || '');
- const existing = existingMap.get(extId);
+ const existing = existingByExternalId.get(extId);
if (existing) {
// Use ?? not ||: a genuinely empty-body message (body === '') is a valid
// full extraction and must overwrite the old text, not collapse back to it
@@ -413,10 +384,11 @@ export async function refreshMessage(accountId, messageId) {
isReplied: message.isReplied ?? false,
hasMeetingInvite: message.hasMeetingInvite ?? false,
labels: [],
- source: account.type,
+ source,
syncedAt: new Date().toISOString()
};
cache.messages.push(newMsg);
+ existingByExternalId.set(extId, newMsg);
updatedMessages.push(newMsg);
}
}
@@ -431,11 +403,64 @@ export async function refreshMessage(accountId, messageId) {
updatedMessages.push(message);
}
- await saveCache(accountId, cache);
return updatedMessages.map(m => ({ ...m, accountId }));
+}
+
+export async function refreshMessages(accountId, messageIds) {
+ if (messageIds.length === 0) return { results: [], updated: 0 };
+
+ // A full-body refresh can touch hundreds of messages. Keep the whole batch in
+ // the existing per-account write queue so it loads and saves the shared cache
+ // once instead of rewriting the complete JSON file for every message.
+ return queueAccountWrite(accountId, async () => {
+ const cache = await loadCache(accountId);
+ const account = await getAccount(accountId);
+ if (!account) {
+ console.log(`📧 Refresh: account ${accountId} not found`);
+ return { results: messageIds.map(() => null), updated: 0 };
+ }
+
+ const { refreshMessageDetail } = await import('./messagePlaywrightSync.js');
+ const messagesById = new Map(cache.messages.map(message => [message.id, message]));
+ const existingByExternalId = new Map(cache.messages.filter(message => message.externalId).map(message => [message.externalId, message]));
+ const results = [];
+ let updated = 0;
+
+ for (const messageId of messageIds) {
+ const message = messagesById.get(messageId);
+ if (!message) {
+ console.log(`📧 Refresh: message ${messageId} not found in cache`);
+ results.push(null);
+ continue;
+ }
+
+ console.log(`📧 Refreshing "${message.subject}" via ${account.type}`);
+ const detail = await refreshMessageDetail(account, message);
+ // Structured error from refreshMessageDetail
+ if (detail && detail.error) {
+ results.push(detail);
+ continue;
+ }
+ if (!detail || !Array.isArray(detail) || detail.length === 0) {
+ console.log(`📧 Refresh: no detail returned`);
+ results.push({ error: 'extraction-failed', message: 'Could not extract message content — the message may not be visible in the Outlook inbox' });
+ continue;
+ }
+
+ results.push(mergeRefreshedMessage(cache, existingByExternalId, accountId, account.type, message, detail));
+ updated++;
+ }
+
+ if (updated > 0) await saveCache(accountId, cache);
+ return { results, updated };
});
}
+export async function refreshMessage(accountId, messageId) {
+ const { results } = await refreshMessages(accountId, [messageId]);
+ return results[0] ?? null;
+}
+
export async function updateMessageEvaluations(evaluations) {
await ensureDir(CACHE_DIR);
const { readdir } = await import('fs/promises');
diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.js
index 31db0652bf..c743126bcf 100644
--- a/server/services/messageSync.test.js
+++ b/server/services/messageSync.test.js
@@ -79,7 +79,7 @@ vi.mock('./userTimezone.js', () => ({
import { readdir, unlink } from 'fs/promises';
import { tryReadFile as readFile, atomicWrite } from '../lib/fileUtils.js';
-import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage, updateMessageEvaluations, logMessageTouchpoints, aggregatePagedMessages } from './messageSync.js';
+import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage, refreshMessages, updateMessageEvaluations, logMessageTouchpoints, aggregatePagedMessages } from './messageSync.js';
import { autoLogTouchpoints } from './tribe.js';
import { getAccount, updateSyncStatus } from './messageAccounts.js';
import { syncGmail } from './messageGmailSync.js';
@@ -670,6 +670,31 @@ describe('refreshMessage', () => {
const original = result.find(m => m.id === 'msg-1');
expect(original.bodyText).toBe('');
});
+
+ it('loads and saves the cache once when refreshing multiple messages', async () => {
+ readFile.mockResolvedValue(JSON.stringify({
+ syncCursor: null,
+ messages: [
+ { id: 'msg-1', bodyText: 'preview 1', from: { name: 'Alice' }, subject: 'One', date: '2026-01-01' },
+ { id: 'msg-2', bodyText: 'preview 2', from: { name: 'Bob' }, subject: 'Two', date: '2026-01-02' },
+ ]
+ }));
+ getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook' });
+ refreshMessageDetail
+ .mockResolvedValueOnce([{ from: 'Alice', date: '2026-01-01', body: 'full 1' }])
+ .mockResolvedValueOnce([{ from: 'Bob', date: '2026-01-02', body: 'full 2' }]);
+
+ const result = await refreshMessages(VALID_UUID, ['msg-1', 'msg-2']);
+
+ expect(result.updated).toBe(2);
+ expect(readFile).toHaveBeenCalledTimes(1);
+ expect(getAccount).toHaveBeenCalledTimes(1);
+ expect(refreshMessageDetail).toHaveBeenCalledTimes(2);
+ expect(atomicWrite).toHaveBeenCalledTimes(1);
+ const savedMessages = atomicWrite.mock.calls[0][1].messages;
+ expect(savedMessages.find(message => message.id === 'msg-1').bodyText).toBe('full 1');
+ expect(savedMessages.find(message => message.id === 'msg-2').bodyText).toBe('full 2');
+ });
});
// ─── Per-account write-tail serialization (#2537) ───