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: full email body capture, conversation threads, thread API

Adam Eivy9a1ab3873bfa
diff --git a/client/src/components/messages/MessageDetail.jsx b/client/src/components/messages/MessageDetail.jsx
index d17cd5b865..9b201a2996 100644
--- a/client/src/components/messages/MessageDetail.jsx
+++ b/client/src/components/messages/MessageDetail.jsx
@@ -1,5 +1,5 @@
-import { useState } from 'react';
-import { ArrowLeft, Reply, Sparkles, Send } from 'lucide-react';
+import { useState, useEffect } from 'react';
+import { ArrowLeft, Reply, Sparkles, Send, MessageSquare } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../services/api';
@@ -8,9 +8,21 @@ export default function MessageDetail({ message, accounts, onBack }) {
const [replyBody, setReplyBody] = useState('');
const [generating, setGenerating] = useState(false);
const [generatedDraftId, setGeneratedDraftId] = useState(null);
+ const [threadMessages, setThreadMessages] = useState([]);
+ const [threadLoading, setThreadLoading] = useState(false);
const account = accounts.find(a => a.id === message.accountId) || accounts[0];
+ // Load thread messages if this message is part of a thread
+ useEffect(() => {
+ if (!message.threadId || !message.accountId) return;
+ setThreadLoading(true);
+ api.getMessageThread(message.accountId, message.threadId)
+ .then(data => setThreadMessages(data?.messages || []))
+ .catch(() => setThreadMessages([]))
+ .finally(() => setThreadLoading(false));
+ }, [message.threadId, message.accountId]);
+
const handleGenerateReply = async () => {
if (!account) return toast.error('No account available');
setGenerating(true);
@@ -50,6 +62,10 @@ export default function MessageDetail({ message, accounts, onBack }) {
setGeneratedDraftId(null);
};
+ // Show thread or single message
+ const hasThread = threadMessages.length > 1;
+ const displayMessages = hasThread ? threadMessages : [message];
+
return (
<div className="space-y-4">
<button
@@ -59,24 +75,49 @@ export default function MessageDetail({ message, accounts, onBack }) {
<ArrowLeft size={16} /> Back to inbox
</button>
- <div className="p-4 bg-port-card rounded-lg border border-port-border space-y-3">
+ <div className="p-4 bg-port-card rounded-lg border border-port-border">
<h2 className="text-lg font-medium text-white">{message.subject || '(no subject)'}</h2>
- <div className="flex items-center gap-4 text-sm">
- <span className="text-gray-400">
- From: <span className="text-white">{message.from?.name || message.from?.email || 'Unknown'}</span>
- </span>
- {message.date && (
- <span className="text-gray-500">{new Date(message.date).toLocaleString()}</span>
- )}
- </div>
- {message.to?.length > 0 && (
- <div className="text-sm text-gray-500">To: {message.to.map(t => t.email || t).join(', ')}</div>
+ {hasThread && (
+ <div className="flex items-center gap-2 mt-1 text-xs text-gray-500">
+ <MessageSquare size={12} />
+ <span>{threadMessages.length} messages in conversation</span>
+ </div>
)}
- <div className="pt-3 border-t border-port-border text-sm text-gray-300 whitespace-pre-wrap">
- {message.bodyText || '(no content)'}
- </div>
</div>
+ {threadLoading ? (
+ <div className="text-sm text-gray-500 animate-pulse">Loading conversation...</div>
+ ) : (
+ <div className="space-y-3">
+ {displayMessages.map((msg, i) => (
+ <div
+ key={msg.id || i}
+ className="p-4 bg-port-card rounded-lg border border-port-border space-y-2"
+ >
+ <div className="flex items-center gap-4 text-sm">
+ <span className="text-gray-400">
+ From: <span className="text-white">{msg.from?.name || msg.from?.email || 'Unknown'}</span>
+ </span>
+ {msg.date && (
+ <span className="text-gray-500">{new Date(msg.date).toLocaleString()}</span>
+ )}
+ </div>
+ {msg.to?.length > 0 && (
+ <div className="text-xs text-gray-500">
+ To: {msg.to.map(t => typeof t === 'string' ? t : t.email || t).join(', ')}
+ </div>
+ )}
+ <div className="pt-2 border-t border-port-border text-sm text-gray-300 whitespace-pre-wrap">
+ {msg.bodyText || '(no content)'}
+ </div>
+ {!msg.bodyFull && msg.bodyText && (
+ <div className="text-xs text-gray-600 italic">Preview only — re-sync for full content</div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
<div className="flex items-center gap-2">
<button
onClick={() => setShowReply(!showReply)}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index a5a86a7345..6cf84a3251 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1628,6 +1628,7 @@ export const getMessageInbox = (params = {}) => {
return request(`/messages/inbox${str ? `?${str}` : ''}`);
};
export const getMessageDetail = (accountId, messageId) => request(`/messages/${accountId}/${messageId}`);
+export const getMessageThread = (accountId, threadId) => request(`/messages/thread/${accountId}/${threadId}`);
export const getMessageDrafts = (params = {}) => {
const qs = new URLSearchParams();
if (params.accountId) qs.set('accountId', params.accountId);
diff --git a/server/routes/messages.js b/server/routes/messages.js
index de24ee910d..09ecae8cc4 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -304,6 +304,16 @@ router.post('/selectors/:provider/test', asyncHandler(async (req, res) => {
res.json(result);
}));
+// === Thread Route ===
+router.get('/thread/:accountId/:threadId', asyncHandler(async (req, res) => {
+ if (!z.string().uuid().safeParse(req.params.accountId).success) {
+ return res.status(400).json({ error: 'Invalid accountId format' });
+ }
+ if (!req.params.threadId) return res.status(400).json({ error: 'threadId is required' });
+ const messages = await messageSync.getThread(req.params.accountId, req.params.threadId);
+ res.json({ messages });
+}));
+
// === Message Detail Route (last to avoid capturing /launch, /selectors paths) ===
const messageParamsSchema = z.object({
accountId: z.string().uuid(),
diff --git a/server/routes/messages.test.js b/server/routes/messages.test.js
index f1bfefcf11..7ff0b2cae5 100644
--- a/server/routes/messages.test.js
+++ b/server/routes/messages.test.js
@@ -18,6 +18,7 @@ vi.mock('../services/messageSync.js', () => ({
getSyncStatus: vi.fn(),
getMessages: vi.fn(),
getMessage: vi.fn(),
+ getThread: vi.fn(),
deleteCache: vi.fn()
}));
@@ -476,6 +477,40 @@ describe('Messages Routes', () => {
});
});
+ // === Thread Route ===
+
+ describe('GET /api/messages/thread/:accountId/:threadId', () => {
+ it('should return thread messages', async () => {
+ const threadMessages = [
+ { id: 'msg-1', subject: 'Hello', threadId: 'thread-1' },
+ { id: 'msg-2', subject: 'Hello', threadId: 'thread-1' }
+ ];
+ messageSync.getThread.mockResolvedValue(threadMessages);
+
+ const response = await request(app).get(`/api/messages/thread/${VALID_UUID}/thread-1`);
+
+ expect(response.status).toBe(200);
+ expect(response.body.messages).toHaveLength(2);
+ expect(messageSync.getThread).toHaveBeenCalledWith(VALID_UUID, 'thread-1');
+ });
+
+ it('should return 400 for invalid accountId', async () => {
+ const response = await request(app).get(`/api/messages/thread/${INVALID_UUID}/thread-1`);
+
+ expect(response.status).toBe(400);
+ expect(response.body.error).toBe('Invalid accountId format');
+ });
+
+ it('should return empty array for unknown threadId', async () => {
+ messageSync.getThread.mockResolvedValue([]);
+
+ const response = await request(app).get(`/api/messages/thread/${VALID_UUID}/unknown`);
+
+ expect(response.status).toBe(200);
+ expect(response.body.messages).toHaveLength(0);
+ });
+ });
+
// === Message Detail Route ===
describe('GET /api/messages/:accountId/:messageId', () => {
diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.js
index 7b54bd49ec..2872f2d30e 100644
--- a/server/services/messagePlaywrightSync.js
+++ b/server/services/messagePlaywrightSync.js
@@ -152,6 +152,7 @@ export async function syncPlaywright(account, cache, io, options = {}) {
const sels = allSelectors[account.type] || {};
// Use CDP Runtime.evaluate to extract messages from the page DOM
+ // Phase 1: Scrape list view to get message summaries
const extractScript = buildExtractionScript(account.type, sels, mode);
const extracted = await evaluateOnPage(page, extractScript);
@@ -161,32 +162,213 @@ export async function syncPlaywright(account, cache, io, options = {}) {
return { messages: [], status: 'extraction-failed' };
}
- io?.emit('messages:sync:progress', { accountId: account.id, current: extracted.length, total: extracted.length });
-
- // Convert extracted data to message format
- const messages = extracted.map(msg => ({
- id: uuidv4(),
- externalId: makeExternalId(msg.date || '', msg.from || '', msg.subject || ''),
- threadId: null,
- from: { name: msg.from || '', email: msg.fromEmail || '' },
- to: [],
- cc: [],
- subject: msg.subject || '',
- bodyText: msg.preview || '',
- date: msg.date || new Date().toISOString(),
- 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()
- }));
+ console.log(`📧 Found ${extracted.length} conversations in list view`);
+
+ // Phase 2: Click into each conversation to get full body + thread messages
+ // Only fetch detail for messages we haven't already cached with full body
+ const existingMap = new Map(cache.messages.filter(m => m.externalId && m.bodyFull).map(m => [m.externalId, true]));
+ const messages = [];
+ let detailsFetched = 0;
+
+ for (let i = 0; i < extracted.length; i++) {
+ const msg = extracted[i];
+ const extId = makeExternalId(msg.date || '', msg.from || '', msg.subject || '');
+ io?.emit('messages:sync:progress', { accountId: account.id, current: i + 1, total: extracted.length });
+
+ // Skip detail fetch if we already have full body cached
+ if (existingMap.has(extId)) {
+ messages.push({
+ id: uuidv4(),
+ externalId: extId,
+ threadId: msg.threadKey || null,
+ from: { name: msg.from || '', email: msg.fromEmail || '' },
+ to: [], cc: [],
+ subject: msg.subject || '',
+ bodyText: msg.preview || '',
+ bodyFull: false, // will keep existing cached full body
+ date: msg.date || new Date().toISOString(),
+ 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()
+ });
+ continue;
+ }
+
+ // Click into conversation to get full body + thread
+ if (account.type === 'outlook') {
+ const detail = await fetchOutlookConversationDetail(page, i);
+ if (detail && detail.length > 0) {
+ detailsFetched++;
+ // Thread key groups all messages in this conversation
+ const threadKey = `thread-${extId}`;
+ for (const threadMsg of detail) {
+ messages.push({
+ id: uuidv4(),
+ externalId: makeExternalId(threadMsg.date || msg.date || '', threadMsg.from || msg.from || '', msg.subject || ''),
+ threadId: threadKey,
+ from: { name: threadMsg.from || msg.from || '', email: threadMsg.fromEmail || msg.fromEmail || '' },
+ to: threadMsg.to || [],
+ cc: threadMsg.cc || [],
+ subject: msg.subject || '',
+ bodyText: threadMsg.body || msg.preview || '',
+ bodyFull: true,
+ date: threadMsg.date || msg.date || new Date().toISOString(),
+ 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()
+ });
+ }
+ } else {
+ // Fallback: use list preview if detail extraction failed
+ messages.push({
+ id: uuidv4(),
+ externalId: extId,
+ threadId: null,
+ from: { name: msg.from || '', email: msg.fromEmail || '' },
+ to: [], cc: [],
+ subject: msg.subject || '',
+ bodyText: msg.preview || '',
+ bodyFull: false,
+ date: msg.date || new Date().toISOString(),
+ 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()
+ });
+ }
+ } else {
+ // Non-outlook: use list preview as before
+ messages.push({
+ id: uuidv4(),
+ externalId: extId,
+ threadId: null,
+ from: { name: msg.from || '', email: msg.fromEmail || '' },
+ to: [], cc: [],
+ subject: msg.subject || '',
+ bodyText: msg.preview || '',
+ bodyFull: false,
+ date: msg.date || new Date().toISOString(),
+ 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()
+ });
+ }
+ }
+
+ console.log(`📧 Fetched detail for ${detailsFetched}/${extracted.length} conversations`);
return { messages, status: 'success' };
}
+/**
+ * Click into an Outlook conversation row and extract the full body + all thread messages.
+ * Returns an array of { from, fromEmail, to, cc, date, body } for each message in the thread.
+ */
+async function fetchOutlookConversationDetail(page, rowIndex) {
+ // Click the row to open the conversation
+ const clickResult = await evaluateOnPage(page, `
+ (async function() {
+ const listbox = document.querySelector("[role='listbox']");
+ if (!listbox) return false;
+ const rows = listbox.querySelectorAll('[role="option"]');
+ const row = rows[${rowIndex}];
+ if (!row) return false;
+ row.click();
+ // Wait for reading pane to load
+ await new Promise(r => setTimeout(r, 1500));
+ return true;
+ })()
+ `);
+
+ if (!clickResult) return null;
+
+ // Extract all messages in the conversation from the reading pane
+ const threadMessages = await evaluateOnPage(page, `
+ (function() {
+ // Outlook reading pane: conversation view shows multiple messages
+ // Each message in the thread is in a div with role="document" or a message container
+ const results = [];
+
+ // Try conversation view: multiple message items
+ const msgContainers = document.querySelectorAll('[aria-label="Message body"], [role="document"]');
+
+ if (msgContainers.length > 0) {
+ for (const container of msgContainers) {
+ // Walk up to find the message wrapper with sender/date info
+ let wrapper = container.closest('[data-convid]') || container.closest('[tabindex]') || container.parentElement?.parentElement;
+
+ // Extract sender from header area
+ let from = '', fromEmail = '', date = '';
+ const to = [], cc = [];
+
+ // Look for sender info near this message body
+ const headerArea = wrapper || container.previousElementSibling || container.parentElement;
+ if (headerArea) {
+ // Sender name
+ const senderEl = headerArea.querySelector('span[aria-label*="From"]')
+ || headerArea.querySelector('button[aria-label*="email"]')
+ || headerArea.querySelector('span.lpc-hoverTarget');
+ from = senderEl?.textContent?.trim() || '';
+ fromEmail = senderEl?.getAttribute('aria-label')?.match(/[\\w.-]+@[\\w.-]+/)?.[0] || '';
+
+ // Date
+ const dateEl = headerArea.querySelector('time') || headerArea.querySelector('span[title*="/"]');
+ date = dateEl?.getAttribute('datetime') || dateEl?.getAttribute('title') || dateEl?.textContent?.trim() || '';
+
+ // To/CC
+ const toEls = headerArea.querySelectorAll('span[aria-label*="To"]');
+ toEls.forEach(el => {
+ const email = el.textContent?.trim();
+ if (email) to.push(email);
+ });
+ }
+
+ // Full body text
+ const body = container.innerText?.trim() || '';
+ if (body) {
+ results.push({ from, fromEmail, to, cc, date, body });
+ }
+ }
+ }
+
+ // Fallback: single message view — grab entire reading pane content
+ if (results.length === 0) {
+ const readingPane = document.querySelector('[aria-label="Reading Pane"]')
+ || document.querySelector('[role="main"]')
+ || document.querySelector('.customScrollBar');
+ if (readingPane) {
+ const body = readingPane.innerText?.trim() || '';
+ if (body) {
+ results.push({ from: '', fromEmail: '', to: [], cc: [], date: '', body });
+ }
+ }
+ }
+
+ return results;
+ })()
+ `);
+
+ return threadMessages;
+}
+
function buildExtractionScript(type, sels, mode = 'unread') {
if (type === 'outlook') {
const maxMessages = mode === 'full' ? 200 : 100;
@@ -247,7 +429,7 @@ function buildExtractionScript(type, sels, mode = 'unread') {
date = dateMatch?.[1] || '';
}
- return { from, fromEmail, subject, date, preview: preview.slice(0, 300), isUnread, isPinned, isFlagged, isReplied, hasMeetingInvite };
+ return { from, fromEmail, subject, date, preview, isUnread, isPinned, isFlagged, isReplied, hasMeetingInvite };
}
function scrapeVisible() {
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 02ed82a90c..549672cba6 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -96,6 +96,18 @@ export async function getMessage(accountId, messageId) {
return { ...msg, accountId: msg.accountId || accountId };
}
+/**
+ * Get all messages in a thread, sorted chronologically.
+ */
+export async function getThread(accountId, threadId) {
+ if (!threadId) return [];
+ const cache = await loadCache(accountId);
+ return cache.messages
+ .filter(m => m.threadId === threadId)
+ .map(m => ({ ...m, accountId: m.accountId || accountId }))
+ .sort((a, b) => safeDate(a.date) - safeDate(b.date));
+}
+
export async function syncAccount(accountId, io, options = {}) {
if (syncLocks.has(accountId)) return { error: 'Sync already in progress', status: 409 };
@@ -125,7 +137,7 @@ export async function syncAccount(accountId, io, options = {}) {
const newMessages = Array.isArray(providerResult) ? providerResult : providerResult?.messages ?? [];
const providerStatus = Array.isArray(providerResult) ? 'success' : providerResult?.status ?? 'success';
- // Deduplicate by externalId; update flags on existing messages
+ // Deduplicate by externalId; update flags and body 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) {
@@ -140,6 +152,13 @@ export async function syncAccount(accountId, io, options = {}) {
if (msg.isFlagged !== undefined) existing.isFlagged = msg.isFlagged;
if (msg.isReplied !== undefined) existing.isReplied = msg.isReplied;
if (msg.hasMeetingInvite !== undefined) existing.hasMeetingInvite = msg.hasMeetingInvite;
+ // Upgrade body if new sync fetched full content
+ if (msg.bodyFull && msg.bodyText) {
+ existing.bodyText = msg.bodyText;
+ existing.bodyFull = true;
+ }
+ // Set threadId if newly available
+ if (msg.threadId && !existing.threadId) existing.threadId = msg.threadId;
}
}
cache.messages.push(...uniqueNew);