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: Outlook sync extraction and add Sync Unread / Full Sync modes

Adam Eivya087257b06a6
diff --git a/client/src/components/messages/SyncTab.jsx b/client/src/components/messages/SyncTab.jsx
index 9c4fe1a805..3ce7d72a93 100644
--- a/client/src/components/messages/SyncTab.jsx
+++ b/client/src/components/messages/SyncTab.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
-import { RefreshCw, Play, AlertCircle, Settings, Globe } from 'lucide-react';
+import { RefreshCw, Play, AlertCircle, Settings, Globe, Mail, MailOpen } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../services/api';
import socket from '../../services/socket';
@@ -7,7 +7,7 @@ import socket from '../../services/socket';
// Default selectors for supported providers — ensures editor cards always render,
// even on fresh installs before selectors.json exists.
const DEFAULT_SELECTORS = {
- outlook: { messageRow: "[role='listitem']" },
+ outlook: { messageRow: "[role='listbox'] [role='option']" },
teams: { messageItem: "[role='listitem']" },
};
@@ -69,9 +69,9 @@ export default function SyncTab({ accounts, onRefresh }) {
if (result?.success) toast.success('Browser tab opened — log in if needed, then sync');
};
- const handleSync = async (accountId) => {
+ const handleSync = async (accountId, mode = 'unread') => {
setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
- await api.syncMessageAccount(accountId).catch(() => {
+ await api.syncMessageAccount(accountId, mode).catch(() => {
setSyncing(prev => ({ ...prev, [accountId]: null }));
});
};
@@ -130,13 +130,24 @@ export default function SyncTab({ accounts, onRefresh }) {
{syncing[account.id] === 'syncing' ? (
<RefreshCw size={16} className="text-port-accent animate-spin" />
) : (
- <button
- onClick={() => handleSync(account.id)}
- disabled={!account.enabled}
- className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/10 text-port-accent rounded text-sm hover:bg-port-accent/20 transition-colors disabled:opacity-50"
- >
- <Play size={14} /> Sync
- </button>
+ <>
+ <button
+ onClick={() => handleSync(account.id, 'unread')}
+ disabled={!account.enabled}
+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/10 text-port-accent rounded text-sm hover:bg-port-accent/20 transition-colors disabled:opacity-50"
+ title="Sync unread messages only"
+ >
+ <MailOpen size={14} /> Sync Unread
+ </button>
+ <button
+ onClick={() => handleSync(account.id, 'full')}
+ disabled={!account.enabled}
+ className="flex items-center gap-1 px-3 py-1.5 bg-port-border text-gray-300 rounded text-sm hover:bg-port-border/80 transition-colors disabled:opacity-50"
+ title="Sync all visible messages"
+ >
+ <Mail size={14} /> Full Sync
+ </button>
+ </>
)}
</div>
</div>
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 67e0a6e215..39f32e717d 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1615,7 +1615,7 @@ export const getMessageAccounts = () => request('/messages/accounts');
export const createMessageAccount = (data) => request('/messages/accounts', { method: 'POST', body: JSON.stringify(data) });
export const updateMessageAccount = (id, data) => request(`/messages/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data) });
export const deleteMessageAccount = (id) => request(`/messages/accounts/${id}`, { method: 'DELETE' });
-export const syncMessageAccount = (accountId) => request(`/messages/sync/${accountId}`, { method: 'POST' });
+export const syncMessageAccount = (accountId, mode = 'unread') => request(`/messages/sync/${accountId}`, { method: 'POST', body: JSON.stringify({ mode }) });
export const getMessageSyncStatus = (accountId) => request(`/messages/sync/${accountId}/status`);
export const getMessageInbox = (params = {}) => {
const qs = new URLSearchParams();
diff --git a/server/routes/messages.js b/server/routes/messages.js
index 5c889f891d..a973bc61a8 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -107,8 +107,9 @@ router.post('/sync/: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 mode = ['unread', 'full'].includes(req.body?.mode) ? req.body.mode : 'unread';
const io = req.app.get('io');
- const result = await messageSync.syncAccount(req.params.accountId, io);
+ const result = await messageSync.syncAccount(req.params.accountId, io, { mode });
if (result.error) return res.status(result.status || 404).json({ error: result.error });
res.json(result);
}));
diff --git a/server/routes/messages.test.js b/server/routes/messages.test.js
index b2227c02fa..f1bfefcf11 100644
--- a/server/routes/messages.test.js
+++ b/server/routes/messages.test.js
@@ -199,7 +199,7 @@ describe('Messages Routes', () => {
expect(response.status).toBe(200);
expect(response.body.newMessages).toBe(5);
- expect(messageSync.syncAccount).toHaveBeenCalledWith(VALID_UUID, undefined);
+ expect(messageSync.syncAccount).toHaveBeenCalledWith(VALID_UUID, undefined, { mode: 'unread' });
});
it('should return 400 for invalid UUID', async () => {
diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.js
index 38b964cef9..7b54bd49ec 100644
--- a/server/services/messagePlaywrightSync.js
+++ b/server/services/messagePlaywrightSync.js
@@ -69,7 +69,7 @@ async function evaluateOnPage(page, expression) {
return new Promise((resolve) => {
const ws = new WebSocket(wsUrl);
- const timer = setTimeout(() => { ws.close(); resolve(null); }, 15000);
+ const timer = setTimeout(() => { ws.close(); resolve(null); }, 60000);
ws.on('open', () => {
ws.send(JSON.stringify({
@@ -121,11 +121,16 @@ export async function launchProvider(accountType) {
/**
* Sync messages via CDP browser automation
* Connects to the portos-browser CDP instance, finds the provider page,
- * and scrapes messages using DOM evaluation
+ * and scrapes messages using DOM evaluation.
+ * @param {object} account
+ * @param {object} cache
+ * @param {object} io - Socket.IO instance
+ * @param {object} options - { mode: 'unread' | 'full' }
*/
-export async function syncPlaywright(account, cache, io) {
+export async function syncPlaywright(account, cache, io, options = {}) {
+ const mode = options.mode || 'unread';
const targetUrl = account.type === 'teams' ? TEAMS_URL : OUTLOOK_URL;
- console.log(`📧 Playwright sync for ${account.email} (${account.type})`);
+ console.log(`📧 Playwright sync (${mode}) for ${account.email} (${account.type})`);
// Find the provider page in CDP browser
const page = await findOrOpenPage(targetUrl).catch(() => null);
@@ -147,7 +152,7 @@ export async function syncPlaywright(account, cache, io) {
const sels = allSelectors[account.type] || {};
// Use CDP Runtime.evaluate to extract messages from the page DOM
- const extractScript = buildExtractionScript(account.type, sels);
+ const extractScript = buildExtractionScript(account.type, sels, mode);
const extracted = await evaluateOnPage(page, extractScript);
if (!extracted || !Array.isArray(extracted)) {
@@ -169,7 +174,12 @@ export async function syncPlaywright(account, cache, io) {
subject: msg.subject || '',
bodyText: msg.preview || '',
date: msg.date || new Date().toISOString(),
- isRead: msg.isRead ?? true,
+ isRead: !(msg.isUnread ?? false),
+ isUnread: msg.isUnread ?? false,
+ isPinned: msg.isPinned ?? false,
+ isFlagged: msg.isFlagged ?? false,
+ isReplied: msg.isReplied ?? false,
+ hasMeetingInvite: msg.hasMeetingInvite ?? false,
labels: [],
source: account.type,
syncedAt: new Date().toISOString()
@@ -177,23 +187,97 @@ export async function syncPlaywright(account, cache, io) {
return { messages, status: 'success' };
}
-function buildExtractionScript(type, sels) {
+function buildExtractionScript(type, sels, mode = 'unread') {
if (type === 'outlook') {
- const listSel = sels.messageRow || "[role='listitem']";
+ const maxMessages = mode === 'full' ? 200 : 100;
+ const maxScrolls = mode === 'full' ? 20 : 10;
+ // Scrolling extraction: scrapes visible rows, scrolls, repeats
return `
- (function() {
- const rows = document.querySelectorAll(${JSON.stringify(listSel)});
- return Array.from(rows).slice(0, 50).map(row => {
- const text = row.innerText || '';
- const lines = text.split('\\n').map(l => l.trim()).filter(Boolean);
- return {
- from: lines[0] || '',
- subject: lines[1] || '',
- preview: lines[2] || '',
- date: lines[3] || '',
- isRead: !row.querySelector('[aria-label*="Unread"]')
- };
- });
+ (async function() {
+ const listbox = document.querySelector("[role='listbox']");
+ if (!listbox) return [];
+ const seen = new Map();
+ let scrollAttempts = 0;
+ const maxMsg = ${maxMessages};
+ const maxScroll = ${maxScrolls};
+ const unreadOnly = ${mode === 'unread'};
+
+ function extractRow(row) {
+ const ariaLabel = row.getAttribute('aria-label') || '';
+ const isUnread = !!row.querySelector('button[aria-label="Mark as read"]');
+ const isPinned = !!row.querySelector('button[aria-label*="Unpin"]');
+ const isFlagged = !!row.querySelector('button[aria-label*="Unflag"]');
+ const isReplied = ariaLabel.includes('Replied');
+ const hasMeetingInvite = !!row.querySelector('button[aria-label="RSVP"]');
+
+ const avatarSpan = row.querySelector('div[aria-label="Select a conversation"] > span[aria-label]');
+ const from = avatarSpan?.getAttribute('aria-label') || '';
+
+ const checkbox = row.querySelector('div[aria-label="Select a conversation"]');
+ const contentArea = checkbox?.parentElement?.nextElementSibling;
+ const contentDivs = contentArea ? Array.from(contentArea.children) : [];
+
+ let subject = '', date = '', preview = '', fromEmail = '';
+
+ if (contentDivs.length >= 3) {
+ const senderDiv = contentDivs[0];
+ const emailSpan = senderDiv?.querySelector('span[title*="@"]');
+ fromEmail = emailSpan?.getAttribute('title') || '';
+
+ const subDateDiv = contentDivs[1];
+ const spans = subDateDiv ? Array.from(subDateDiv.querySelectorAll('span')) : [];
+ subject = spans[0]?.textContent?.trim() || '';
+ const dateSpan = spans.find(s => s.getAttribute('title')?.match(/\\d{4}/));
+ date = dateSpan?.getAttribute('title') || spans[spans.length - 1]?.textContent?.trim() || '';
+
+ preview = contentDivs[2]?.textContent?.trim() || '';
+ } else if (contentDivs.length >= 1) {
+ const allSpans = contentDivs[0]?.querySelectorAll('span[title]') || [];
+ const spanArr = Array.from(allSpans);
+ const emailSpan = spanArr.find(s => (s.getAttribute('title') || '').includes('@'));
+ fromEmail = emailSpan?.getAttribute('title') || '';
+ // In compact layout: first titled span is sender, second is subject
+ const titledSpans = spanArr.filter(s => s.closest('[class]'));
+ subject = titledSpans.length > 1 ? titledSpans[titledSpans.length - 1]?.textContent?.trim() || '' : '';
+ // Fallback: find span whose text differs from sender name
+ if (!subject) {
+ subject = spanArr.find(s => s.textContent?.trim() && s.textContent.trim() !== from && !(s.getAttribute('title') || '').includes('@'))?.textContent?.trim() || '';
+ }
+ const dateMatch = ariaLabel.match(/(\\d{1,2}\\/\\d{1,2}(?:\\/\\d{2,4})?)/);
+ date = dateMatch?.[1] || '';
+ }
+
+ return { from, fromEmail, subject, date, preview: preview.slice(0, 300), isUnread, isPinned, isFlagged, isReplied, hasMeetingInvite };
+ }
+
+ function scrapeVisible() {
+ const rows = listbox.querySelectorAll('[role="option"]');
+ let added = 0;
+ for (const row of rows) {
+ if (seen.size >= maxMsg) break;
+ const data = extractRow(row);
+ if (!data.from && !data.subject) continue;
+ const key = data.from + '|' + data.subject + '|' + data.date;
+ if (seen.has(key)) continue;
+ if (unreadOnly && !data.isUnread) continue;
+ seen.set(key, data);
+ added++;
+ }
+ return added;
+ }
+
+ scrapeVisible();
+ const scrollContainer = listbox.closest('[role="region"]') || listbox.parentElement;
+ while (scrollAttempts < maxScroll && seen.size < maxMsg) {
+ scrollContainer.scrollBy(0, 600);
+ await new Promise(r => setTimeout(r, 500));
+ const added = scrapeVisible();
+ if (added === 0) scrollAttempts++;
+ else scrollAttempts = 0;
+ }
+ // Scroll back to top
+ scrollContainer.scrollTo(0, 0);
+ return Array.from(seen.values());
})()
`;
}
@@ -210,7 +294,11 @@ function buildExtractionScript(type, sels) {
subject: '',
preview: lines[1] || '',
date: lines[2] || '',
- isRead: true
+ isUnread: false,
+ isPinned: false,
+ isFlagged: false,
+ isReplied: false,
+ hasMeetingInvite: false
};
});
})()
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 7bb2211f6f..82ff4ad0bc 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -96,7 +96,7 @@ export async function getMessage(accountId, messageId) {
return { ...msg, accountId: msg.accountId || accountId };
}
-export async function syncAccount(accountId, io) {
+export async function syncAccount(accountId, io, options = {}) {
if (syncLocks.has(accountId)) return { error: 'Sync already in progress', status: 409 };
const account = await getAccount(accountId);
@@ -104,8 +104,9 @@ export async function syncAccount(accountId, io) {
if (!account.enabled) return { error: 'Account is disabled', status: 400 };
syncLocks.set(accountId, true);
- io?.emit('messages:sync:started', { accountId });
- console.log(`📧 Starting sync for ${account.name} (${account.type})`);
+ const mode = options.mode || 'unread';
+ io?.emit('messages:sync:started', { accountId, mode });
+ console.log(`📧 Starting ${mode} sync for ${account.name} (${account.type})`);
const providerSync = async () => {
const cache = await loadCache(accountId);
@@ -115,7 +116,7 @@ export async function syncAccount(accountId, io) {
providerResult = await syncGmail(account, cache, io);
} else if (account.type === 'outlook' || account.type === 'teams') {
const { syncPlaywright } = await import('./messagePlaywrightSync.js');
- providerResult = await syncPlaywright(account, cache, io);
+ providerResult = await syncPlaywright(account, cache, io, { mode });
} else {
throw new Error(`Unsupported account type: ${account.type}`);
}
@@ -124,9 +125,23 @@ export async function syncAccount(accountId, io) {
const newMessages = Array.isArray(providerResult) ? providerResult : providerResult?.messages ?? [];
const providerStatus = Array.isArray(providerResult) ? 'success' : providerResult?.status ?? 'success';
- // Deduplicate by externalId (skip dedup for messages without externalId)
- const existingIds = new Set(cache.messages.map(m => m.externalId).filter(Boolean));
- const uniqueNew = newMessages.filter(m => !m.externalId || !existingIds.has(m.externalId));
+ // Deduplicate by externalId; update flags on existing messages
+ const existingMap = new Map(cache.messages.filter(m => m.externalId).map(m => [m.externalId, m]));
+ const uniqueNew = [];
+ for (const msg of newMessages) {
+ if (!msg.externalId || !existingMap.has(msg.externalId)) {
+ uniqueNew.push(msg);
+ } else {
+ // Update flags on existing message
+ const existing = existingMap.get(msg.externalId);
+ if (msg.isUnread !== undefined) existing.isUnread = msg.isUnread;
+ if (msg.isRead !== undefined) existing.isRead = msg.isRead;
+ if (msg.isPinned !== undefined) existing.isPinned = msg.isPinned;
+ if (msg.isFlagged !== undefined) existing.isFlagged = msg.isFlagged;
+ if (msg.isReplied !== undefined) existing.isReplied = msg.isReplied;
+ if (msg.hasMeetingInvite !== undefined) existing.hasMeetingInvite = msg.hasMeetingInvite;
+ }
+ }
cache.messages.push(...uniqueNew);
// Trim to maxMessages
diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.js
index 364f3a1c44..74914c4930 100644
--- a/server/services/messageSync.test.js
+++ b/server/services/messageSync.test.js
@@ -287,20 +287,25 @@ describe('syncAccount', () => {
expect(result.total).toBe(1);
expect(result.status).toBe('success');
expect(updateSyncStatus).toHaveBeenCalledWith(VALID_UUID, 'success');
- expect(mockIo.emit).toHaveBeenCalledWith('messages:sync:started', { accountId: VALID_UUID });
+ expect(mockIo.emit).toHaveBeenCalledWith('messages:sync:started', { accountId: VALID_UUID, mode: 'unread' });
expect(mockIo.emit).toHaveBeenCalledWith('messages:sync:completed', expect.objectContaining({ accountId: VALID_UUID, newMessages: 1 }));
expect(mockIo.emit).toHaveBeenCalledWith('messages:changed', {});
});
- it('should call syncPlaywright for outlook accounts', async () => {
+ it('should call syncPlaywright for outlook accounts with mode', async () => {
getAccount.mockResolvedValue({ id: VALID_UUID, name: 'Outlook', type: 'outlook', enabled: true });
readFile.mockResolvedValue(JSON.stringify({ syncCursor: null, messages: [] }));
syncPlaywright.mockResolvedValue([]);
updateSyncStatus.mockResolvedValue();
- const result = await syncAccount(VALID_UUID, mockIo);
+ const result = await syncAccount(VALID_UUID, mockIo, { mode: 'full' });
- expect(syncPlaywright).toHaveBeenCalled();
+ expect(syncPlaywright).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'outlook' }),
+ expect.any(Object),
+ mockIo,
+ { mode: 'full' }
+ );
expect(result.newMessages).toBe(0);
});