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: P6.5 per-message refresh, fetch-full, and cache clear endpoints

Adam Eivy37b56c931168
diff --git a/server/routes/messages.js b/server/routes/messages.js
index 09ecae8cc4..18a21a0067 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -314,12 +314,60 @@ router.get('/thread/:accountId/:threadId', asyncHandler(async (req, res) => {
res.json({ messages });
}));
-// === Message Detail Route (last to avoid capturing /launch, /selectors paths) ===
+// === Message params schema (shared by detail + refresh routes) ===
const messageParamsSchema = z.object({
accountId: z.string().uuid(),
messageId: z.string().min(1)
});
+// === Per-message refresh ===
+router.post('/:accountId/:messageId/refresh', asyncHandler(async (req, res) => {
+ const parsed = messageParamsSchema.safeParse(req.params);
+ if (!parsed.success) return res.status(400).json({ error: 'Invalid accountId or messageId format' });
+ const { accountId, messageId } = parsed.data;
+ const message = await messageSync.getMessage(accountId, messageId);
+ if (!message) return res.status(404).json({ error: 'Message not found' });
+ const updated = await messageSync.refreshMessage(accountId, messageId);
+ if (!updated) return res.status(502).json({ error: 'Failed to refresh message detail' });
+ req.app.get('io')?.emit('messages:changed', {});
+ res.json(updated);
+}));
+
+// === Fetch full content for preview-only messages ===
+router.post('/fetch-full/:accountId', asyncHandler(async (req, res) => {
+ if (!z.string().uuid().safeParse(req.params.accountId).success) {
+ return res.status(400).json({ error: 'Invalid account ID format' });
+ }
+ const { accountId } = req.params;
+ const account = await messageAccounts.getAccount(accountId);
+ if (!account) return res.status(404).json({ error: 'Account not found' });
+ if (account.type !== 'outlook') return res.json({ updated: 0, total: 0 });
+
+ const allResult = await messageSync.getMessages({ accountId, limit: 1000 });
+ const previewOnly = allResult.messages.filter(m => m.bodyFull === false);
+ let updated = 0;
+
+ for (const msg of previewOnly) {
+ const result = await messageSync.refreshMessage(accountId, msg.id);
+ if (result) updated++;
+ }
+
+ if (updated > 0) req.app.get('io')?.emit('messages:changed', {});
+ res.json({ updated, total: previewOnly.length });
+}));
+
+// === Clear account cache ===
+router.post('/accounts/:id/cache/clear', asyncHandler(async (req, res) => {
+ if (!z.string().uuid().safeParse(req.params.id).success) {
+ return res.status(400).json({ error: 'Invalid account ID format' });
+ }
+ await messageSync.deleteCache(req.params.id);
+ req.app.get('io')?.emit('messages:changed', {});
+ res.status(204).send();
+}));
+
+// === Message Detail Route (last to avoid capturing /launch, /selectors paths) ===
+
router.get('/:accountId/:messageId', asyncHandler(async (req, res) => {
const parsed = messageParamsSchema.safeParse(req.params);
if (!parsed.success) return res.status(400).json({ error: 'Invalid accountId or messageId format' });
diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.js
index 224f691500..f6c6f9fe22 100644
--- a/server/services/messagePlaywrightSync.js
+++ b/server/services/messagePlaywrightSync.js
@@ -526,6 +526,25 @@ function buildExtractionScript(type, sels, mode = 'unread') {
return '[]';
}
+/**
+ * Re-fetch detail for a single message via CDP browser automation.
+ * Returns updated thread messages array or null.
+ */
+export async function refreshMessageDetail(account, message) {
+ if (account.type !== 'outlook') return null;
+ const page = await findOrOpenPage(OUTLOOK_URL).catch(() => null);
+ if (!page) {
+ console.log(`📧 No CDP browser available for refresh`);
+ return null;
+ }
+ if (isAuthPage(page)) {
+ console.log(`📧 Auth required for ${account.type} — login page detected`);
+ return null;
+ }
+ const detail = await fetchOutlookConversationDetail(page, message.subject, message.from?.name);
+ return detail;
+}
+
/**
* Send message via Playwright browser automation
*/
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 549672cba6..a6238ed615 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -193,6 +193,77 @@ export async function syncAccount(accountId, io, options = {}) {
return result;
}
+export async function refreshMessage(accountId, messageId) {
+ const cache = await loadCache(accountId);
+ const message = cache.messages.find(m => m.id === messageId);
+ if (!message) return null;
+
+ const account = await getAccount(accountId);
+ if (!account) return null;
+
+ const { refreshMessageDetail } = await import('./messagePlaywrightSync.js');
+ const detail = await refreshMessageDetail(account, message);
+ if (!detail || detail.length === 0) return null;
+
+ const { default: crypto } = await import('crypto');
+ const { v4: uuidv4 } = await import('uuid');
+ function makeExternalId(date, sender, subject) {
+ return 'pw-' + crypto.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 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);
+ if (existing) {
+ existing.bodyText = threadMsg.body || existing.bodyText;
+ existing.bodyFull = true;
+ if (!existing.threadId) existing.threadId = threadKey;
+ if (threadMsg.to?.length) existing.to = threadMsg.to;
+ if (threadMsg.cc?.length) existing.cc = threadMsg.cc;
+ updatedMessages.push(existing);
+ } else {
+ const newMsg = {
+ id: uuidv4(),
+ externalId: extId,
+ threadId: threadKey,
+ from: { name: threadMsg.from || message.from?.name || '', email: threadMsg.fromEmail || message.from?.email || '' },
+ to: threadMsg.to || [],
+ cc: threadMsg.cc || [],
+ subject: message.subject || '',
+ bodyText: threadMsg.body || '',
+ bodyFull: true,
+ date: threadMsg.date || message.date || new Date().toISOString(),
+ isRead: message.isRead ?? true,
+ isUnread: message.isUnread ?? false,
+ isPinned: message.isPinned ?? false,
+ isFlagged: message.isFlagged ?? false,
+ isReplied: message.isReplied ?? false,
+ hasMeetingInvite: message.hasMeetingInvite ?? false,
+ labels: [],
+ source: account.type,
+ syncedAt: new Date().toISOString()
+ };
+ cache.messages.push(newMsg);
+ updatedMessages.push(newMsg);
+ }
+ }
+
+ // Update the original message too if it wasn't matched by externalId
+ if (!updatedMessages.find(m => m.id === message.id)) {
+ message.bodyText = detail[0]?.body || message.bodyText;
+ message.bodyFull = true;
+ if (!message.threadId) message.threadId = threadKey;
+ updatedMessages.push(message);
+ }
+
+ await saveCache(accountId, cache);
+ return updatedMessages.map(m => ({ ...m, accountId }));
+}
+
export async function updateMessageEvaluations(evaluations) {
await ensureDir(CACHE_DIR);
const { readdir } = await import('fs/promises');