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: add unified email/messaging management system

Adam Eivy7b9e819b5a66
diff --git a/client/src/App.jsx b/client/src/App.jsx
index f14cf41aec..f9b845065b 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -51,6 +51,7 @@ const CyberCity = lazyWithReload(() => import('./pages/CyberCity'));
const AppDetail = lazyWithReload(() => import('./pages/AppDetail'));
const FeatureAgents = lazyWithReload(() => import('./pages/FeatureAgents'));
const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetail'));
+const Messages = lazyWithReload(() => import('./pages/Messages'));
// Loading fallback for lazy-loaded pages
const PageLoader = () => (
@@ -106,6 +107,8 @@ export default function App() {
<Route path="instances" element={<Instances />} />
<Route path="meatspace" element={<Navigate to="/meatspace/overview" replace />} />
<Route path="meatspace/:tab" element={<MeatSpace />} />
+ <Route path="messages" element={<Navigate to="/messages/inbox" replace />} />
+ <Route path="messages/:tab" element={<Messages />} />
<Route path="jira" element={<Navigate to="/devtools/jira" replace />} />
<Route path="devtools/jira" element={<Jira />} />
<Route path="city" element={<CyberCity />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 40eeef4b28..285b49c6ce 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -57,7 +57,8 @@ import {
Database,
Shield,
Wand2,
- Zap
+ Zap,
+ Mail
} from 'lucide-react';
/* global __APP_VERSION__ */
import Logo from './Logo';
@@ -171,6 +172,7 @@ const navItems = [
{ to: '/meatspace/post', label: 'POST', icon: Zap }
]
},
+ { to: '/messages/inbox', label: 'Messages', icon: Mail, single: true },
{ to: '/security', label: 'Security', icon: Camera, single: true },
{ to: '/settings', label: 'Settings', icon: Settings, single: true },
{ to: '/shell', label: 'Shell', icon: SquareTerminal, single: true },
@@ -604,6 +606,7 @@ export default function Layout() {
location.pathname.startsWith('/feature-agents') ||
location.pathname.startsWith('/insights') ||
location.pathname.startsWith('/meatspace') ||
+ location.pathname.startsWith('/messages') ||
location.pathname.startsWith('/agents') ||
location.pathname === '/shell' ||
location.pathname.startsWith('/city') ||
diff --git a/client/src/components/messages/AccountsTab.jsx b/client/src/components/messages/AccountsTab.jsx
new file mode 100644
index 0000000000..975d5e2740
--- /dev/null
+++ b/client/src/components/messages/AccountsTab.jsx
@@ -0,0 +1,165 @@
+import { useState } from 'react';
+import { Plus, Trash2, RefreshCw, Mail, Globe, MessageSquare } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../../services/api';
+
+const TYPE_ICONS = { gmail: Mail, outlook: Globe, teams: MessageSquare };
+const TYPE_LABELS = { gmail: 'Gmail (MCP)', outlook: 'Outlook (Playwright)', teams: 'Teams (Playwright)' };
+
+export default function AccountsTab({ accounts, onRefresh }) {
+ const [showForm, setShowForm] = useState(false);
+ const [form, setForm] = useState({ name: '', type: 'gmail', email: '' });
+ const [saving, setSaving] = useState(false);
+ const [deleting, setDeleting] = useState(null);
+
+ const handleCreate = async () => {
+ if (!form.name) return toast.error('Name is required');
+ setSaving(true);
+ await api.createMessageAccount(form);
+ setSaving(false);
+ setShowForm(false);
+ setForm({ name: '', type: 'gmail', email: '' });
+ toast.success('Account created');
+ onRefresh();
+ };
+
+ const handleDelete = async (id) => {
+ setDeleting(id);
+ await api.deleteMessageAccount(id);
+ setDeleting(null);
+ toast.success('Account deleted');
+ onRefresh();
+ };
+
+ const handleToggle = async (account) => {
+ await api.updateMessageAccount(account.id, { enabled: !account.enabled });
+ toast.success(account.enabled ? 'Account disabled' : 'Account enabled');
+ onRefresh();
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <h2 className="text-lg font-semibold text-white">Accounts</h2>
+ <button
+ onClick={() => setShowForm(!showForm)}
+ className="flex items-center gap-2 px-3 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 transition-colors"
+ >
+ <Plus size={16} />
+ Add Account
+ </button>
+ </div>
+
+ {showForm && (
+ <div className="p-4 bg-port-card rounded-lg border border-port-border space-y-3">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Name</label>
+ <input
+ type="text"
+ value={form.name}
+ onChange={(e) => setForm(f => ({ ...f, name: e.target.value }))}
+ placeholder="e.g. Work Gmail"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Type</label>
+ <select
+ value={form.type}
+ onChange={(e) => setForm(f => ({ ...f, type: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white focus:outline-none focus:border-port-accent"
+ >
+ <option value="gmail">Gmail (MCP)</option>
+ <option value="outlook">Outlook (Playwright)</option>
+ <option value="teams">Teams (Playwright)</option>
+ </select>
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Email</label>
+ <input
+ type="email"
+ value={form.email}
+ onChange={(e) => setForm(f => ({ ...f, email: e.target.value }))}
+ placeholder="[email protected]"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={handleCreate}
+ disabled={saving}
+ className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 transition-colors disabled:opacity-50"
+ >
+ {saving ? 'Creating...' : 'Create'}
+ </button>
+ <button
+ onClick={() => setShowForm(false)}
+ className="px-4 py-2 bg-port-border text-gray-300 rounded-lg text-sm hover:bg-port-border/80 transition-colors"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
+ {accounts.length === 0 && !showForm && (
+ <div className="text-center py-12 text-gray-500">
+ <Mail size={48} className="mx-auto mb-4 opacity-50" />
+ <p>No accounts configured</p>
+ <p className="text-sm mt-1">Add a Gmail, Outlook, or Teams account to get started</p>
+ </div>
+ )}
+
+ <div className="space-y-2">
+ {accounts.map((account) => {
+ const Icon = TYPE_ICONS[account.type] || Mail;
+ return (
+ <div
+ key={account.id}
+ className="flex items-center justify-between p-4 bg-port-card rounded-lg border border-port-border"
+ >
+ <div className="flex items-center gap-3">
+ <Icon size={20} className={account.enabled ? 'text-port-accent' : 'text-gray-600'} />
+ <div>
+ <div className="text-sm font-medium text-white">{account.name}</div>
+ <div className="text-xs text-gray-500">
+ {TYPE_LABELS[account.type]} · {account.email || 'No email set'}
+ </div>
+ {account.lastSyncAt && (
+ <div className="text-xs text-gray-600">
+ Last sync: {new Date(account.lastSyncAt).toLocaleString()} ({account.lastSyncStatus})
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => handleToggle(account)}
+ className={`px-2 py-1 rounded text-xs transition-colors ${
+ account.enabled
+ ? 'bg-port-success/20 text-port-success'
+ : 'bg-gray-700 text-gray-400'
+ }`}
+ >
+ {account.enabled ? 'Enabled' : 'Disabled'}
+ </button>
+ <button
+ onClick={() => handleDelete(account.id)}
+ disabled={deleting === account.id}
+ className="p-1 text-gray-500 hover:text-port-error transition-colors"
+ title="Delete account"
+ >
+ {deleting === account.id ? (
+ <RefreshCw size={16} className="animate-spin" />
+ ) : (
+ <Trash2 size={16} />
+ )}
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/messages/DraftsTab.jsx b/client/src/components/messages/DraftsTab.jsx
new file mode 100644
index 0000000000..b51bc65edb
--- /dev/null
+++ b/client/src/components/messages/DraftsTab.jsx
@@ -0,0 +1,133 @@
+import { useState, useEffect, useCallback } from 'react';
+import { FileText, Trash2, Send, Check, RefreshCw } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../../services/api';
+
+export default function DraftsTab({ accounts }) {
+ const [drafts, setDrafts] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const fetchDrafts = useCallback(async () => {
+ setLoading(true);
+ const data = await api.getMessageDrafts().catch(() => []);
+ setDrafts(data || []);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchDrafts();
+ }, [fetchDrafts]);
+
+ const handleApprove = async (id) => {
+ await api.approveMessageDraft(id);
+ setDrafts(prev => prev.map(d => d.id === id ? { ...d, status: 'approved' } : d));
+ toast.success('Draft approved');
+ };
+
+ const handleSend = async (id) => {
+ const result = await api.sendMessageDraft(id).catch(() => null);
+ if (result) {
+ setDrafts(prev => prev.map(d => d.id === id ? { ...d, status: 'sent' } : d));
+ toast.success('Message sent');
+ }
+ };
+
+ const handleDelete = async (id) => {
+ await api.deleteMessageDraft(id);
+ setDrafts(prev => prev.filter(d => d.id !== id));
+ toast.success('Draft deleted');
+ };
+
+ const getAccountName = (accountId) => {
+ const account = accounts.find(a => a.id === accountId);
+ return account?.name || 'Unknown';
+ };
+
+ const statusColors = {
+ draft: 'bg-gray-700 text-gray-300',
+ pending_review: 'bg-port-warning/20 text-port-warning',
+ approved: 'bg-port-success/20 text-port-success',
+ sending: 'bg-port-accent/20 text-port-accent',
+ sent: 'bg-port-success/20 text-port-success',
+ failed: 'bg-port-error/20 text-port-error'
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <h2 className="text-lg font-semibold text-white">Drafts</h2>
+ <button
+ onClick={fetchDrafts}
+ className="p-2 text-gray-400 hover:text-white transition-colors"
+ >
+ <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
+ </button>
+ </div>
+
+ {drafts.length === 0 && !loading && (
+ <div className="text-center py-12 text-gray-500">
+ <FileText size={48} className="mx-auto mb-4 opacity-50" />
+ <p>No drafts</p>
+ <p className="text-sm mt-1">Generate AI replies from the Inbox or create manual drafts</p>
+ </div>
+ )}
+
+ <div className="space-y-2">
+ {drafts.map((draft) => (
+ <div
+ key={draft.id}
+ className="p-4 bg-port-card rounded-lg border border-port-border space-y-2"
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <span className={`px-2 py-0.5 rounded text-xs ${statusColors[draft.status] || ''}`}>
+ {draft.status}
+ </span>
+ <span className="text-xs text-gray-500">{getAccountName(draft.accountId)}</span>
+ {draft.generatedBy === 'ai' && (
+ <span className="text-xs text-purple-400">AI generated</span>
+ )}
+ </div>
+ <div className="flex items-center gap-1">
+ {draft.status === 'draft' && (
+ <button
+ onClick={() => handleApprove(draft.id)}
+ className="p-1 text-gray-400 hover:text-port-success transition-colors"
+ title="Approve"
+ >
+ <Check size={16} />
+ </button>
+ )}
+ {draft.status === 'approved' && (
+ <button
+ onClick={() => handleSend(draft.id)}
+ className="p-1 text-gray-400 hover:text-port-accent transition-colors"
+ title="Send"
+ >
+ <Send size={16} />
+ </button>
+ )}
+ {['draft', 'pending_review', 'failed'].includes(draft.status) && (
+ <button
+ onClick={() => handleDelete(draft.id)}
+ className="p-1 text-gray-400 hover:text-port-error transition-colors"
+ title="Delete"
+ >
+ <Trash2 size={16} />
+ </button>
+ )}
+ </div>
+ </div>
+ <div className="text-sm text-white">{draft.subject || '(no subject)'}</div>
+ {draft.to?.length > 0 && (
+ <div className="text-xs text-gray-500">To: {draft.to.join(', ')}</div>
+ )}
+ <div className="text-sm text-gray-400 whitespace-pre-wrap line-clamp-3">
+ {draft.body}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/messages/InboxTab.jsx b/client/src/components/messages/InboxTab.jsx
new file mode 100644
index 0000000000..3ac01deef5
--- /dev/null
+++ b/client/src/components/messages/InboxTab.jsx
@@ -0,0 +1,112 @@
+import { useState, useEffect, useCallback } from 'react';
+import { Mail, Search, RefreshCw, ChevronRight } from 'lucide-react';
+import * as api from '../../services/api';
+import MessageDetail from './MessageDetail';
+
+export default function InboxTab({ accounts }) {
+ const [messages, setMessages] = useState([]);
+ const [total, setTotal] = useState(0);
+ const [loading, setLoading] = useState(true);
+ const [search, setSearch] = useState('');
+ const [selectedAccount, setSelectedAccount] = useState('');
+ const [selectedMessage, setSelectedMessage] = useState(null);
+
+ const fetchMessages = useCallback(async () => {
+ setLoading(true);
+ const params = {};
+ if (selectedAccount) params.accountId = selectedAccount;
+ if (search) params.search = search;
+ const result = await api.getMessageInbox(params).catch(() => ({ messages: [], total: 0 }));
+ setMessages(result.messages || []);
+ setTotal(result.total || 0);
+ setLoading(false);
+ }, [selectedAccount, search]);
+
+ useEffect(() => {
+ fetchMessages();
+ }, [fetchMessages]);
+
+ if (selectedMessage) {
+ return (
+ <MessageDetail
+ message={selectedMessage}
+ accounts={accounts}
+ onBack={() => setSelectedMessage(null)}
+ />
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center gap-3">
+ <div className="relative flex-1">
+ <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
+ <input
+ type="text"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search messages..."
+ className="w-full pl-9 pr-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ <select
+ value={selectedAccount}
+ onChange={(e) => setSelectedAccount(e.target.value)}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white focus:outline-none focus:border-port-accent"
+ >
+ <option value="">All accounts</option>
+ {accounts.map(a => (
+ <option key={a.id} value={a.id}>{a.name}</option>
+ ))}
+ </select>
+ <button
+ onClick={fetchMessages}
+ className="p-2 text-gray-400 hover:text-white transition-colors"
+ title="Refresh"
+ >
+ <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
+ </button>
+ </div>
+
+ <div className="text-sm text-gray-500">{total} messages</div>
+
+ {messages.length === 0 && !loading && (
+ <div className="text-center py-12 text-gray-500">
+ <Mail size={48} className="mx-auto mb-4 opacity-50" />
+ <p>No messages yet</p>
+ <p className="text-sm mt-1">Add an account and sync to get started</p>
+ </div>
+ )}
+
+ <div className="space-y-1">
+ {messages.map((msg) => (
+ <button
+ key={msg.id}
+ onClick={() => setSelectedMessage(msg)}
+ className={`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors hover:bg-port-card ${
+ msg.isRead ? 'opacity-70' : ''
+ }`}
+ >
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className={`text-sm truncate ${msg.isRead ? 'text-gray-400' : 'text-white font-medium'}`}>
+ {msg.from?.name || msg.from?.email || 'Unknown'}
+ </span>
+ <span className="text-xs text-gray-600 shrink-0">
+ {msg.date ? new Date(msg.date).toLocaleDateString() : ''}
+ </span>
+ </div>
+ <div className={`text-sm truncate ${msg.isRead ? 'text-gray-500' : 'text-gray-300'}`}>
+ {msg.subject || '(no subject)'}
+ </div>
+ <div className="text-xs text-gray-600 truncate">
+ {msg.bodyText?.substring(0, 100) || ''}
+ </div>
+ </div>
+ <ChevronRight size={16} className="text-gray-600 shrink-0" />
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/messages/MessageDetail.jsx b/client/src/components/messages/MessageDetail.jsx
new file mode 100644
index 0000000000..6fe01580f9
--- /dev/null
+++ b/client/src/components/messages/MessageDetail.jsx
@@ -0,0 +1,119 @@
+import { useState } from 'react';
+import { ArrowLeft, Reply, Sparkles, Send } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../../services/api';
+
+export default function MessageDetail({ message, accounts, onBack }) {
+ const [showReply, setShowReply] = useState(false);
+ const [replyBody, setReplyBody] = useState('');
+ const [generating, setGenerating] = useState(false);
+
+ const account = accounts.find(a => a.id === message.accountId) || accounts[0];
+
+ const handleGenerateReply = async () => {
+ if (!account) return toast.error('No account available');
+ setGenerating(true);
+ const draft = await api.generateMessageDraft({
+ accountId: account.id,
+ replyToMessageId: message.id,
+ threadId: message.threadId,
+ context: `Replying to: "${message.subject}" from ${message.from?.name || message.from?.email}`,
+ instructions: ''
+ }).catch(() => null);
+ setGenerating(false);
+ if (draft) {
+ setReplyBody(draft.body);
+ setShowReply(true);
+ toast.success('AI draft generated');
+ }
+ };
+
+ const handleCreateDraft = async () => {
+ if (!account) return toast.error('No account available');
+ await api.createMessageDraft({
+ accountId: account.id,
+ replyToMessageId: message.id,
+ threadId: message.threadId,
+ to: [message.from?.email].filter(Boolean),
+ subject: `Re: ${message.subject || ''}`,
+ body: replyBody,
+ generatedBy: 'manual',
+ sendVia: account.provider
+ });
+ toast.success('Draft saved');
+ setShowReply(false);
+ setReplyBody('');
+ };
+
+ return (
+ <div className="space-y-4">
+ <button
+ onClick={onBack}
+ className="flex items-center gap-2 text-sm text-gray-400 hover:text-white transition-colors"
+ >
+ <ArrowLeft size={16} /> Back to inbox
+ </button>
+
+ <div className="p-4 bg-port-card rounded-lg border border-port-border space-y-3">
+ <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>
+ )}
+ <div className="pt-3 border-t border-port-border text-sm text-gray-300 whitespace-pre-wrap">
+ {message.bodyText || '(no content)'}
+ </div>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => setShowReply(!showReply)}
+ className="flex items-center gap-2 px-3 py-2 bg-port-accent/10 text-port-accent rounded-lg text-sm hover:bg-port-accent/20 transition-colors"
+ >
+ <Reply size={16} /> Reply
+ </button>
+ <button
+ onClick={handleGenerateReply}
+ disabled={generating}
+ className="flex items-center gap-2 px-3 py-2 bg-purple-500/10 text-purple-400 rounded-lg text-sm hover:bg-purple-500/20 transition-colors disabled:opacity-50"
+ >
+ <Sparkles size={16} className={generating ? 'animate-pulse' : ''} />
+ {generating ? 'Generating...' : 'AI Reply'}
+ </button>
+ </div>
+
+ {showReply && (
+ <div className="p-4 bg-port-card rounded-lg border border-port-border space-y-3">
+ <textarea
+ value={replyBody}
+ onChange={(e) => setReplyBody(e.target.value)}
+ placeholder="Write your reply..."
+ rows={6}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y"
+ />
+ <div className="flex gap-2">
+ <button
+ onClick={handleCreateDraft}
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 transition-colors"
+ >
+ <Send size={16} /> Save Draft
+ </button>
+ <button
+ onClick={() => { setShowReply(false); setReplyBody(''); }}
+ className="px-4 py-2 bg-port-border text-gray-300 rounded-lg text-sm hover:bg-port-border/80 transition-colors"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/messages/SyncTab.jsx b/client/src/components/messages/SyncTab.jsx
new file mode 100644
index 0000000000..b0e93bff9b
--- /dev/null
+++ b/client/src/components/messages/SyncTab.jsx
@@ -0,0 +1,181 @@
+import { useState, useEffect, useCallback } from 'react';
+import { RefreshCw, Play, AlertCircle, Settings } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../../services/api';
+import socket from '../../services/socket';
+
+export default function SyncTab({ accounts, onRefresh }) {
+ const [syncing, setSyncing] = useState({});
+ const [selectors, setSelectors] = useState({});
+ const [editingSelector, setEditingSelector] = useState(null);
+ const [selectorForm, setSelectorForm] = useState({});
+
+ const fetchSelectors = useCallback(async () => {
+ const data = await api.getMessageSelectors().catch(() => ({}));
+ setSelectors(data || {});
+ }, []);
+
+ useEffect(() => {
+ fetchSelectors();
+
+ const onSyncStarted = ({ accountId }) => {
+ setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
+ };
+ const onSyncCompleted = ({ accountId, newMessages }) => {
+ setSyncing(prev => ({ ...prev, [accountId]: null }));
+ toast.success(`Sync complete: ${newMessages} new messages`);
+ onRefresh();
+ };
+ const onAuthRequired = ({ accountId }) => {
+ setSyncing(prev => ({ ...prev, [accountId]: 'auth-required' }));
+ toast('Login required -- open Browser page to authenticate', { icon: '\uD83D\uDD10' });
+ };
+
+ socket.on('messages:sync:started', onSyncStarted);
+ socket.on('messages:sync:completed', onSyncCompleted);
+ socket.on('messages:sync:auth-required', onAuthRequired);
+
+ return () => {
+ socket.off('messages:sync:started', onSyncStarted);
+ socket.off('messages:sync:completed', onSyncCompleted);
+ socket.off('messages:sync:auth-required', onAuthRequired);
+ };
+ }, [fetchSelectors, onRefresh]);
+
+ const handleSync = async (accountId) => {
+ setSyncing(prev => ({ ...prev, [accountId]: 'syncing' }));
+ await api.syncMessageAccount(accountId).catch(() => {
+ setSyncing(prev => ({ ...prev, [accountId]: null }));
+ });
+ };
+
+ const handleSaveSelectors = async (provider) => {
+ await api.updateMessageSelectors(provider, selectorForm);
+ toast.success(`${provider} selectors updated`);
+ setEditingSelector(null);
+ fetchSelectors();
+ };
+
+ const handleTestSelectors = async (provider) => {
+ const result = await api.testMessageSelectors(provider).catch(() => null);
+ if (result) toast.success(`Selector test: ${result.status}`);
+ };
+
+ return (
+ <div className="space-y-6">
+ {/* Sync Status */}
+ <div>
+ <h2 className="text-lg font-semibold text-white mb-3">Sync Status</h2>
+ {accounts.length === 0 && (
+ <p className="text-gray-500 text-sm">No accounts configured. Add one in the Accounts tab.</p>
+ )}
+ <div className="space-y-2">
+ {accounts.map((account) => (
+ <div
+ key={account.id}
+ className="flex items-center justify-between p-4 bg-port-card rounded-lg border border-port-border"
+ >
+ <div>
+ <div className="text-sm font-medium text-white">{account.name}</div>
+ <div className="text-xs text-gray-500">
+ {account.lastSyncAt
+ ? `Last sync: ${new Date(account.lastSyncAt).toLocaleString()}`
+ : 'Never synced'}
+ {account.lastSyncStatus && ` (${account.lastSyncStatus})`}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ {syncing[account.id] === 'auth-required' && (
+ <span className="flex items-center gap-1 text-xs text-port-warning">
+ <AlertCircle size={14} /> Auth required
+ </span>
+ )}
+ {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>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Selector Configuration */}
+ <div>
+ <h2 className="text-lg font-semibold text-white mb-3">DOM Selectors</h2>
+ <p className="text-sm text-gray-500 mb-3">
+ Playwright selectors for scraping Outlook and Teams. Edit if the DOM structure changes.
+ </p>
+ {Object.entries(selectors).map(([provider, sels]) => (
+ <div key={provider} className="mb-4 p-4 bg-port-card rounded-lg border border-port-border">
+ <div className="flex items-center justify-between mb-2">
+ <h3 className="text-sm font-medium text-white capitalize">{provider}</h3>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => handleTestSelectors(provider)}
+ className="text-xs text-gray-400 hover:text-white transition-colors"
+ >
+ Test
+ </button>
+ <button
+ onClick={() => {
+ setEditingSelector(editingSelector === provider ? null : provider);
+ setSelectorForm(sels);
+ }}
+ className="text-xs text-gray-400 hover:text-white transition-colors"
+ >
+ <Settings size={14} />
+ </button>
+ </div>
+ </div>
+ {editingSelector === provider ? (
+ <div className="space-y-2">
+ {Object.entries(selectorForm).map(([key, val]) => (
+ <div key={key} className="flex items-center gap-2">
+ <label className="text-xs text-gray-500 w-32 shrink-0">{key}</label>
+ <input
+ type="text"
+ value={val}
+ onChange={(e) => setSelectorForm(f => ({ ...f, [key]: e.target.value }))}
+ className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-white font-mono focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ ))}
+ <div className="flex gap-2 mt-2">
+ <button
+ onClick={() => handleSaveSelectors(provider)}
+ className="px-3 py-1 bg-port-accent text-white rounded text-xs hover:bg-port-accent/80"
+ >
+ Save
+ </button>
+ <button
+ onClick={() => setEditingSelector(null)}
+ className="px-3 py-1 bg-port-border text-gray-300 rounded text-xs hover:bg-port-border/80"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="space-y-1">
+ {Object.entries(sels).map(([key, val]) => (
+ <div key={key} className="flex text-xs">
+ <span className="text-gray-500 w-32 shrink-0">{key}</span>
+ <span className="text-gray-400 font-mono truncate">{val}</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/Messages.jsx b/client/src/pages/Messages.jsx
new file mode 100644
index 0000000000..fe47f28770
--- /dev/null
+++ b/client/src/pages/Messages.jsx
@@ -0,0 +1,105 @@
+import { useParams, useNavigate } from 'react-router-dom';
+import { Mail, RefreshCw } from 'lucide-react';
+import { useState, useEffect, useCallback } from 'react';
+import * as api from '../services/api';
+
+import InboxTab from '../components/messages/InboxTab';
+import AccountsTab from '../components/messages/AccountsTab';
+import DraftsTab from '../components/messages/DraftsTab';
+import SyncTab from '../components/messages/SyncTab';
+
+const TABS = [
+ { id: 'inbox', label: 'Inbox', icon: Mail },
+ { id: 'accounts', label: 'Accounts', icon: Mail },
+ { id: 'drafts', label: 'Drafts', icon: Mail },
+ { id: 'sync', label: 'Sync', icon: RefreshCw }
+];
+
+export default function Messages() {
+ const { tab } = useParams();
+ const navigate = useNavigate();
+ const activeTab = tab || 'inbox';
+ const [accounts, setAccounts] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const fetchAccounts = useCallback(async () => {
+ const data = await api.getMessageAccounts().catch(() => []);
+ setAccounts(data || []);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchAccounts();
+ }, [fetchAccounts]);
+
+ const handleTabChange = (tabId) => {
+ navigate(`/messages/${tabId}`);
+ };
+
+ const renderTabContent = () => {
+ switch (activeTab) {
+ case 'inbox':
+ return <InboxTab accounts={accounts} />;
+ case 'accounts':
+ return <AccountsTab accounts={accounts} onRefresh={fetchAccounts} />;
+ case 'drafts':
+ return <DraftsTab accounts={accounts} />;
+ case 'sync':
+ return <SyncTab accounts={accounts} onRefresh={fetchAccounts} />;
+ default:
+ return <InboxTab accounts={accounts} />;
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-full">
+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full">
+ <div className="flex items-center justify-between p-4 border-b border-port-border">
+ <div className="flex items-center gap-3">
+ <Mail className="w-8 h-8 text-port-accent" />
+ <div>
+ <h1 className="text-xl font-bold text-white">Messages</h1>
+ <p className="text-sm text-gray-500">Unified email and messaging management</p>
+ </div>
+ </div>
+ <div className="flex items-center gap-4 text-sm">
+ <span className="text-gray-500">{accounts.length} accounts</span>
+ </div>
+ </div>
+
+ <div className="flex border-b border-port-border">
+ {TABS.map((tabItem) => {
+ const Icon = tabItem.icon;
+ const isActive = activeTab === tabItem.id;
+ return (
+ <button
+ key={tabItem.id}
+ onClick={() => handleTabChange(tabItem.id)}
+ className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${
+ isActive
+ ? 'text-port-accent border-b-2 border-port-accent bg-port-accent/5'
+ : 'text-gray-400 hover:text-white hover:bg-port-card'
+ }`}
+ role="tab"
+ aria-selected={isActive}
+ >
+ <Icon size={16} aria-hidden="true" />
+ {tabItem.label}
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="flex-1 overflow-auto p-4">
+ {renderTabContent()}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index bf0edb0d75..f71ac4527a 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1610,6 +1610,38 @@ export const setGitHubSecret = (name, value) =>
export const syncGitHubSecret = (name) =>
request(`/github/secrets/${encodeURIComponent(name)}/sync`, { method: 'POST' });
+// Messages
+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 getSyncStatus = (accountId) => request(`/messages/sync/${accountId}/status`);
+export const getMessageInbox = (params = {}) => {
+ const qs = new URLSearchParams();
+ if (params.accountId) qs.set('accountId', params.accountId);
+ if (params.search) qs.set('search', params.search);
+ if (params.limit) qs.set('limit', params.limit);
+ if (params.offset) qs.set('offset', params.offset);
+ return request(`/messages/inbox?${qs}`);
+};
+export const getMessageDetail = (accountId, messageId) => request(`/messages/${accountId}/${messageId}`);
+export const getMessageDrafts = (params = {}) => {
+ const qs = new URLSearchParams();
+ if (params.accountId) qs.set('accountId', params.accountId);
+ if (params.status) qs.set('status', params.status);
+ return request(`/messages/drafts?${qs}`);
+};
+export const createMessageDraft = (data) => request('/messages/drafts', { method: 'POST', body: JSON.stringify(data) });
+export const generateMessageDraft = (data) => request('/messages/drafts/generate', { method: 'POST', body: JSON.stringify(data) });
+export const updateMessageDraft = (id, data) => request(`/messages/drafts/${id}`, { method: 'PUT', body: JSON.stringify(data) });
+export const approveMessageDraft = (id) => request(`/messages/drafts/${id}/approve`, { method: 'POST' });
+export const sendMessageDraft = (id) => request(`/messages/drafts/${id}/send`, { method: 'POST' });
+export const deleteMessageDraft = (id) => request(`/messages/drafts/${id}`, { method: 'DELETE' });
+export const getMessageSelectors = () => request('/messages/selectors');
+export const updateMessageSelectors = (provider, selectors) => request(`/messages/selectors/${provider}`, { method: 'PUT', body: JSON.stringify({ selectors }) });
+export const testMessageSelectors = (provider) => request(`/messages/selectors/${provider}/test`, { method: 'POST' });
+
// Default export for simplified imports
export default {
get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),
diff --git a/server/index.js b/server/index.js
index 76eba9e286..1625fa5b4c 100644
--- a/server/index.js
+++ b/server/index.js
@@ -36,6 +36,7 @@ import notificationsRoutes from './routes/notifications.js';
import standardizeRoutes from './routes/standardize.js';
import brainRoutes from './routes/brain.js';
import mediaRoutes from './routes/media.js';
+import messagesRoutes from './routes/messages.js';
import genomeRoutes from './routes/genome.js';
import digitalTwinRoutes from './routes/digital-twin.js';
import socialAccountsRoutes from './routes/socialAccounts.js';
@@ -226,6 +227,7 @@ app.use('/api/notifications', notificationsRoutes);
app.use('/api/standardize', standardizeRoutes);
app.use('/api/brain', brainRoutes);
app.use('/api/media', mediaRoutes);
+app.use('/api/messages', messagesRoutes);
app.use('/api/digital-twin/social-accounts', socialAccountsRoutes);
app.use('/api/meatspace/genome', genomeRoutes);
app.use('/api/digital-twin/identity', identityRoutes);
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index c92c8ef5d3..4e5d60b3ee 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -29,7 +29,8 @@ export const PATHS = {
reports: join(__lib_dirname, '../../data/cos/reports'),
// AI Agent Personalities data
agentPersonalities: join(__lib_dirname, '../../data/agents'),
- meatspace: join(__lib_dirname, '../../data/meatspace')
+ meatspace: join(__lib_dirname, '../../data/meatspace'),
+ messages: join(__lib_dirname, '../../data/messages')
};
/**
diff --git a/server/routes/messages.js b/server/routes/messages.js
new file mode 100644
index 0000000000..57dcb6e7f5
--- /dev/null
+++ b/server/routes/messages.js
@@ -0,0 +1,204 @@
+import express from 'express';
+import { z } from 'zod';
+import { asyncHandler } from '../lib/errorHandler.js';
+import * as messageAccounts from '../services/messageAccounts.js';
+import * as messageSync from '../services/messageSync.js';
+import * as messageDrafts from '../services/messageDrafts.js';
+import * as messageSender from '../services/messageSender.js';
+import { getSelectors, updateSelectors, testSelectors } from '../services/messagePlaywrightSync.js';
+
+const router = express.Router();
+
+// === Validation Schemas ===
+const createAccountSchema = z.object({
+ name: z.string().min(1),
+ type: z.enum(['gmail', 'outlook', 'teams']),
+ email: z.string().email().optional().default(''),
+ syncConfig: z.object({
+ maxAge: z.string().optional(),
+ maxMessages: z.number().int().positive().optional(),
+ syncInterval: z.number().int().positive().optional()
+ }).optional()
+});
+
+const updateAccountSchema = z.object({
+ name: z.string().min(1).optional(),
+ email: z.string().email().optional(),
+ enabled: z.boolean().optional(),
+ syncConfig: z.object({
+ maxAge: z.string().optional(),
+ maxMessages: z.number().int().positive().optional(),
+ syncInterval: z.number().int().positive().optional()
+ }).optional()
+});
+
+const createDraftSchema = z.object({
+ accountId: z.string().uuid(),
+ replyToMessageId: z.string().optional(),
+ threadId: z.string().optional(),
+ to: z.array(z.string()).optional().default([]),
+ cc: z.array(z.string()).optional().default([]),
+ subject: z.string().optional().default(''),
+ body: z.string().optional().default(''),
+ generatedBy: z.enum(['ai', 'manual']).optional().default('manual'),
+ sendVia: z.enum(['mcp', 'playwright']).optional().default('mcp')
+});
+
+const updateDraftSchema = z.object({
+ to: z.array(z.string()).optional(),
+ cc: z.array(z.string()).optional(),
+ subject: z.string().optional(),
+ body: z.string().optional(),
+ status: z.enum(['draft', 'pending_review', 'approved']).optional()
+});
+
+const generateDraftSchema = z.object({
+ accountId: z.string().uuid(),
+ replyToMessageId: z.string().optional(),
+ threadId: z.string().optional(),
+ context: z.string().optional().default(''),
+ instructions: z.string().optional().default('')
+});
+
+const updateSelectorsSchema = z.object({
+ selectors: z.record(z.string())
+});
+
+// === Account Routes ===
+router.get('/accounts', asyncHandler(async (req, res) => {
+ const accounts = await messageAccounts.listAccounts();
+ res.json(accounts);
+}));
+
+router.post('/accounts', asyncHandler(async (req, res) => {
+ const data = createAccountSchema.parse(req.body);
+ const account = await messageAccounts.createAccount(data);
+ req.app.get('io')?.emit('messages:changed', {});
+ res.status(201).json(account);
+}));
+
+router.put('/accounts/:id', asyncHandler(async (req, res) => {
+ const updates = updateAccountSchema.parse(req.body);
+ const account = await messageAccounts.updateAccount(req.params.id, updates);
+ if (!account) return res.status(404).json({ error: 'Account not found' });
+ req.app.get('io')?.emit('messages:changed', {});
+ res.json(account);
+}));
+
+router.delete('/accounts/:id', asyncHandler(async (req, res) => {
+ const deleted = await messageAccounts.deleteAccount(req.params.id);
+ if (!deleted) return res.status(404).json({ error: 'Account not found' });
+ req.app.get('io')?.emit('messages:changed', {});
+ res.status(204).send();
+}));
+
+// === Sync Routes ===
+router.post('/sync/:accountId', asyncHandler(async (req, res) => {
+ const io = req.app.get('io');
+ const result = await messageSync.syncAccount(req.params.accountId, io);
+ if (result.error) return res.status(404).json({ error: result.error });
+ res.json(result);
+}));
+
+router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {
+ const status = await messageSync.getSyncStatus(req.params.accountId);
+ if (!status) return res.status(404).json({ error: 'Account not found' });
+ res.json(status);
+}));
+
+// === Inbox Routes ===
+router.get('/inbox', asyncHandler(async (req, res) => {
+ const { accountId, search, limit, offset } = req.query;
+ const result = await messageSync.getMessages({
+ accountId,
+ search,
+ limit: limit ? parseInt(limit, 10) : 50,
+ offset: offset ? parseInt(offset, 10) : 0
+ });
+ res.json(result);
+}));
+
+router.get('/:accountId/:messageId', asyncHandler(async (req, res) => {
+ const message = await messageSync.getMessage(req.params.accountId, req.params.messageId);
+ if (!message) return res.status(404).json({ error: 'Message not found' });
+ res.json(message);
+}));
+
+// === Draft Routes ===
+router.get('/drafts', asyncHandler(async (req, res) => {
+ const { accountId, status } = req.query;
+ const drafts = await messageDrafts.listDrafts({ accountId, status });
+ res.json(drafts);
+}));
+
+router.post('/drafts', asyncHandler(async (req, res) => {
+ const data = createDraftSchema.parse(req.body);
+ const draft = await messageDrafts.createDraft(data);
+ req.app.get('io')?.emit('messages:draft:created', { draftId: draft.id });
+ res.status(201).json(draft);
+}));
+
+router.post('/drafts/generate', asyncHandler(async (req, res) => {
+ const data = generateDraftSchema.parse(req.body);
+ // AI draft generation - stub for now
+ // TODO: Use portos-ai-toolkit for provider selection and model tiers
+ const draft = await messageDrafts.createDraft({
+ accountId: data.accountId,
+ replyToMessageId: data.replyToMessageId,
+ threadId: data.threadId,
+ subject: '',
+ body: `[AI-generated reply placeholder]\n\nContext: ${data.context}\nInstructions: ${data.instructions}`,
+ generatedBy: 'ai',
+ sendVia: 'mcp' // Will be determined by account type
+ });
+ req.app.get('io')?.emit('messages:draft:created', { draftId: draft.id });
+ res.status(201).json(draft);
+}));
+
+router.put('/drafts/:id', asyncHandler(async (req, res) => {
+ const updates = updateDraftSchema.parse(req.body);
+ const draft = await messageDrafts.updateDraft(req.params.id, updates);
+ if (!draft) return res.status(404).json({ error: 'Draft not found' });
+ res.json(draft);
+}));
+
+router.post('/drafts/:id/approve', asyncHandler(async (req, res) => {
+ const draft = await messageDrafts.approveDraft(req.params.id);
+ if (!draft) return res.status(404).json({ error: 'Draft not found' });
+ res.json(draft);
+}));
+
+router.post('/drafts/:id/send', asyncHandler(async (req, res) => {
+ const io = req.app.get('io');
+ const result = await messageSender.sendDraft(req.params.id, io);
+ if (!result.success) {
+ const status = result.error?.includes('not found') ? 404 : 400;
+ return res.status(status).json({ error: result.error });
+ }
+ res.json(result);
+}));
+
+router.delete('/drafts/:id', asyncHandler(async (req, res) => {
+ const deleted = await messageDrafts.deleteDraft(req.params.id);
+ if (!deleted) return res.status(404).json({ error: 'Draft not found' });
+ res.status(204).send();
+}));
+
+// === Selector Routes ===
+router.get('/selectors', asyncHandler(async (req, res) => {
+ const selectors = await getSelectors();
+ res.json(selectors);
+}));
+
+router.put('/selectors/:provider', asyncHandler(async (req, res) => {
+ const { selectors } = updateSelectorsSchema.parse(req.body);
+ const updated = await updateSelectors(req.params.provider, selectors);
+ res.json(updated);
+}));
+
+router.post('/selectors/:provider/test', asyncHandler(async (req, res) => {
+ const result = await testSelectors(req.params.provider);
+ res.json(result);
+}));
+
+export default router;
diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.js
new file mode 100644
index 0000000000..15c66f6bcc
--- /dev/null
+++ b/server/services/messageAccounts.js
@@ -0,0 +1,83 @@
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { v4 as uuidv4 } from 'uuid';
+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+
+const ACCOUNTS_FILE = join(PATHS.messages, 'accounts.json');
+
+async function loadAccounts() {
+ await ensureDir(PATHS.messages);
+ const content = await readFile(ACCOUNTS_FILE, 'utf-8').catch(() => null);
+ if (!content) return {};
+ return safeJSONParse(content, {}, { context: 'messageAccounts' });
+}
+
+async function saveAccounts(accounts) {
+ await ensureDir(PATHS.messages);
+ await writeFile(ACCOUNTS_FILE, JSON.stringify(accounts, null, 2));
+}
+
+export async function listAccounts() {
+ const accounts = await loadAccounts();
+ return Object.values(accounts).sort((a, b) => a.name.localeCompare(b.name));
+}
+
+export async function getAccount(id) {
+ const accounts = await loadAccounts();
+ return accounts[id] || null;
+}
+
+export async function createAccount(data) {
+ const accounts = await loadAccounts();
+ const id = uuidv4();
+ accounts[id] = {
+ id,
+ name: data.name,
+ type: data.type, // gmail, outlook, teams
+ provider: data.type === 'gmail' ? 'mcp' : 'playwright',
+ email: data.email || '',
+ enabled: true,
+ syncConfig: {
+ maxAge: data.syncConfig?.maxAge || '30d',
+ maxMessages: data.syncConfig?.maxMessages || 500,
+ syncInterval: data.syncConfig?.syncInterval || 300000
+ },
+ lastSyncAt: null,
+ lastSyncStatus: null,
+ createdAt: new Date().toISOString()
+ };
+ await saveAccounts(accounts);
+ console.log(`📧 Message account created: ${data.name} (${data.type})`);
+ return accounts[id];
+}
+
+export async function updateAccount(id, updates) {
+ const accounts = await loadAccounts();
+ if (!accounts[id]) return null;
+ const { name, email, enabled, syncConfig } = updates;
+ if (name !== undefined) accounts[id].name = name;
+ if (email !== undefined) accounts[id].email = email;
+ if (enabled !== undefined) accounts[id].enabled = enabled;
+ if (syncConfig) accounts[id].syncConfig = { ...accounts[id].syncConfig, ...syncConfig };
+ accounts[id].updatedAt = new Date().toISOString();
+ await saveAccounts(accounts);
+ return accounts[id];
+}
+
+export async function deleteAccount(id) {
+ const accounts = await loadAccounts();
+ if (!accounts[id]) return false;
+ delete accounts[id];
+ await saveAccounts(accounts);
+ console.log(`🗑️ Message account deleted: ${id}`);
+ return true;
+}
+
+export async function updateSyncStatus(id, status) {
+ const accounts = await loadAccounts();
+ if (!accounts[id]) return null;
+ accounts[id].lastSyncAt = new Date().toISOString();
+ accounts[id].lastSyncStatus = status;
+ await saveAccounts(accounts);
+ return accounts[id];
+}
diff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.js
new file mode 100644
index 0000000000..605c9ef645
--- /dev/null
+++ b/server/services/messageDrafts.js
@@ -0,0 +1,80 @@
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { v4 as uuidv4 } from 'uuid';
+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+
+const DRAFTS_FILE = join(PATHS.messages, 'drafts.json');
+
+async function loadDrafts() {
+ await ensureDir(PATHS.messages);
+ const content = await readFile(DRAFTS_FILE, 'utf-8').catch(() => null);
+ if (!content) return [];
+ return safeJSONParse(content, [], { context: 'messageDrafts' });
+}
+
+async function saveDrafts(drafts) {
+ await ensureDir(PATHS.messages);
+ await writeFile(DRAFTS_FILE, JSON.stringify(drafts, null, 2));
+}
+
+export async function listDrafts(filters = {}) {
+ let drafts = await loadDrafts();
+ if (filters.accountId) drafts = drafts.filter(d => d.accountId === filters.accountId);
+ if (filters.status) drafts = drafts.filter(d => d.status === filters.status);
+ return drafts.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
+}
+
+export async function getDraft(id) {
+ const drafts = await loadDrafts();
+ return drafts.find(d => d.id === id) || null;
+}
+
+export async function createDraft(data) {
+ const drafts = await loadDrafts();
+ const draft = {
+ id: uuidv4(),
+ accountId: data.accountId,
+ replyToMessageId: data.replyToMessageId || null,
+ threadId: data.threadId || null,
+ to: data.to || [],
+ cc: data.cc || [],
+ subject: data.subject || '',
+ body: data.body || '',
+ status: 'draft',
+ generatedBy: data.generatedBy || 'manual',
+ sendVia: data.sendVia || 'mcp',
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ };
+ drafts.push(draft);
+ await saveDrafts(drafts);
+ console.log(`📝 Message draft created: "${draft.subject}" via ${draft.sendVia}`);
+ return draft;
+}
+
+export async function updateDraft(id, updates) {
+ const drafts = await loadDrafts();
+ const idx = drafts.findIndex(d => d.id === id);
+ if (idx === -1) return null;
+ const allowed = ['to', 'cc', 'subject', 'body', 'status'];
+ for (const key of allowed) {
+ if (updates[key] !== undefined) drafts[idx][key] = updates[key];
+ }
+ drafts[idx].updatedAt = new Date().toISOString();
+ await saveDrafts(drafts);
+ return drafts[idx];
+}
+
+export async function approveDraft(id) {
+ return updateDraft(id, { status: 'approved' });
+}
+
+export async function deleteDraft(id) {
+ const drafts = await loadDrafts();
+ const idx = drafts.findIndex(d => d.id === id);
+ if (idx === -1) return false;
+ drafts.splice(idx, 1);
+ await saveDrafts(drafts);
+ console.log(`🗑️ Message draft deleted: ${id}`);
+ return true;
+}
diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.js
new file mode 100644
index 0000000000..93d18c5bcd
--- /dev/null
+++ b/server/services/messageGmailSync.js
@@ -0,0 +1,21 @@
+/**
+ * Sync Gmail messages via MCP
+ * This is a stub that returns an empty array until Gmail MCP is configured.
+ * When MCP is available, this will call the Gmail API through the MCP bridge.
+ */
+export async function syncGmail(account, cache, io) {
+ console.log(`📧 Gmail sync for ${account.email} — MCP integration pending`);
+ io?.emit('messages:sync:progress', { accountId: account.id, current: 0, total: 0 });
+ // TODO: Integrate with Gmail MCP when available
+ // The MCP bridge would call gmail.users.messages.list and gmail.users.messages.get
+ return [];
+}
+
+/**
+ * Send email via Gmail MCP
+ */
+export async function sendGmail(account, draft) {
+ console.log(`📧 Gmail send for ${account.email} — MCP integration pending`);
+ // TODO: Integrate with Gmail MCP when available
+ return { success: false, error: 'Gmail MCP not configured' };
+}
diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.js
new file mode 100644
index 0000000000..93edb37271
--- /dev/null
+++ b/server/services/messagePlaywrightSync.js
@@ -0,0 +1,53 @@
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+
+const SELECTORS_FILE = join(PATHS.messages, 'selectors.json');
+
+export async function getSelectors() {
+ const content = await readFile(SELECTORS_FILE, 'utf-8').catch(() => null);
+ if (!content) return {};
+ return safeJSONParse(content, {}, { context: 'messageSelectors' });
+}
+
+export async function updateSelectors(provider, selectors) {
+ const all = await getSelectors();
+ all[provider] = selectors;
+ await ensureDir(PATHS.messages);
+ await writeFile(SELECTORS_FILE, JSON.stringify(all, null, 2));
+ return all[provider];
+}
+
+/**
+ * Sync messages via Playwright CDP browser automation
+ * Uses browser_snapshot (accessibility tree) as primary extraction
+ */
+export async function syncPlaywright(account, cache, io) {
+ console.log(`📧 Playwright sync for ${account.email} (${account.type}) — automation pending`);
+ io?.emit('messages:sync:progress', { accountId: account.id, current: 0, total: 0 });
+ // TODO: Connect to CDP browser on port 5556
+ // 1. Navigate to Outlook/Teams
+ // 2. Check for Okta login page → emit messages:sync:auth-required if detected
+ // 3. Use browser_snapshot for accessibility tree extraction
+ // 4. Fall back to CSS selectors from selectors.json
+ // 5. Extract messages and return array
+ return [];
+}
+
+/**
+ * Send message via Playwright browser automation
+ */
+export async function sendPlaywright(account, draft) {
+ console.log(`📧 Playwright send for ${account.email} (${account.type}) — automation pending`);
+ // TODO: Connect to CDP browser, fill compose form, send
+ return { success: false, error: 'Playwright send not configured' };
+}
+
+/**
+ * Test selectors against the current page
+ */
+export async function testSelectors(provider) {
+ console.log(`📧 Testing ${provider} selectors — automation pending`);
+ // TODO: Connect to CDP, run selector tests, return results
+ return { provider, results: {}, status: 'pending' };
+}
diff --git a/server/services/messageSender.js b/server/services/messageSender.js
new file mode 100644
index 0000000000..32fd335796
--- /dev/null
+++ b/server/services/messageSender.js
@@ -0,0 +1,35 @@
+import { getDraft, updateDraft } from './messageDrafts.js';
+import { getAccount } from './messageAccounts.js';
+
+export async function sendDraft(draftId, io) {
+ const draft = await getDraft(draftId);
+ if (!draft) return { success: false, error: 'Draft not found' };
+ if (draft.status !== 'approved') return { success: false, error: `Draft status is "${draft.status}", must be "approved"` };
+
+ const account = await getAccount(draft.accountId);
+ if (!account) return { success: false, error: 'Account not found' };
+
+ await updateDraft(draftId, { status: 'sending' });
+ console.log(`📧 Sending draft "${draft.subject}" via ${draft.sendVia}`);
+
+ let result;
+ if (draft.sendVia === 'mcp') {
+ const { sendGmail } = await import('./messageGmailSync.js');
+ result = await sendGmail(account, draft);
+ } else {
+ const { sendPlaywright } = await import('./messagePlaywrightSync.js');
+ result = await sendPlaywright(account, draft);
+ }
+
+ if (result.success) {
+ await updateDraft(draftId, { status: 'sent' });
+ io?.emit('messages:draft:sent', { draftId });
+ io?.emit('messages:changed', {});
+ console.log(`📧 Draft sent successfully: "${draft.subject}"`);
+ } else {
+ await updateDraft(draftId, { status: 'failed' });
+ console.log(`📧 Draft send failed: ${result.error}`);
+ }
+
+ return result;
+}
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
new file mode 100644
index 0000000000..8fdd4b9596
--- /dev/null
+++ b/server/services/messageSync.js
@@ -0,0 +1,122 @@
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { getAccount, updateSyncStatus } from './messageAccounts.js';
+
+const CACHE_DIR = join(PATHS.messages, 'cache');
+
+async function loadCache(accountId) {
+ await ensureDir(CACHE_DIR);
+ const filePath = join(CACHE_DIR, `${accountId}.json`);
+ const content = await readFile(filePath, 'utf-8').catch(() => null);
+ if (!content) return { syncCursor: null, messages: [] };
+ return safeJSONParse(content, { syncCursor: null, messages: [] }, { context: `messageCache:${accountId}` });
+}
+
+async function saveCache(accountId, cache) {
+ await ensureDir(CACHE_DIR);
+ const filePath = join(CACHE_DIR, `${accountId}.json`);
+ await writeFile(filePath, JSON.stringify(cache, null, 2));
+}
+
+export async function getMessages(options = {}) {
+ const { accountId, search, limit = 50, offset = 0 } = options;
+ // If specific account, just load that cache
+ if (accountId) {
+ const cache = await loadCache(accountId);
+ let messages = cache.messages;
+ if (search) {
+ const q = search.toLowerCase();
+ messages = messages.filter(m =>
+ m.subject?.toLowerCase().includes(q) ||
+ m.from?.name?.toLowerCase().includes(q) ||
+ m.from?.email?.toLowerCase().includes(q) ||
+ m.bodyText?.toLowerCase().includes(q)
+ );
+ }
+ return {
+ messages: messages.sort((a, b) => new Date(b.date) - new Date(a.date)).slice(offset, offset + limit),
+ total: messages.length
+ };
+ }
+
+ // Otherwise aggregate across all account caches
+ await ensureDir(CACHE_DIR);
+ const { readdir } = await import('fs/promises');
+ const files = await readdir(CACHE_DIR).catch(() => []);
+ let allMessages = [];
+ for (const file of files) {
+ if (!file.endsWith('.json')) continue;
+ const cache = await loadCache(file.replace('.json', ''));
+ allMessages.push(...cache.messages);
+ }
+ if (search) {
+ const q = search.toLowerCase();
+ allMessages = allMessages.filter(m =>
+ m.subject?.toLowerCase().includes(q) ||
+ m.from?.name?.toLowerCase().includes(q) ||
+ m.from?.email?.toLowerCase().includes(q) ||
+ m.bodyText?.toLowerCase().includes(q)
+ );
+ }
+ allMessages.sort((a, b) => new Date(b.date) - new Date(a.date));
+ return {
+ messages: allMessages.slice(offset, offset + limit),
+ total: allMessages.length
+ };
+}
+
+export async function getMessage(accountId, messageId) {
+ const cache = await loadCache(accountId);
+ return cache.messages.find(m => m.id === messageId) || null;
+}
+
+export async function syncAccount(accountId, io) {
+ const account = await getAccount(accountId);
+ if (!account) return { error: 'Account not found' };
+
+ io?.emit('messages:sync:started', { accountId });
+ console.log(`📧 Starting sync for ${account.name} (${account.type})`);
+
+ const cache = await loadCache(accountId);
+ let newMessages = [];
+
+ // Provider-specific sync
+ if (account.type === 'gmail') {
+ const { syncGmail } = await import('./messageGmailSync.js');
+ newMessages = await syncGmail(account, cache, io);
+ } else if (account.type === 'outlook' || account.type === 'teams') {
+ const { syncPlaywright } = await import('./messagePlaywrightSync.js');
+ newMessages = await syncPlaywright(account, cache, io);
+ }
+
+ // Deduplicate by externalId
+ const existingIds = new Set(cache.messages.map(m => m.externalId));
+ const uniqueNew = newMessages.filter(m => !existingIds.has(m.externalId));
+ cache.messages.push(...uniqueNew);
+
+ // Trim to maxMessages
+ if (account.syncConfig?.maxMessages && cache.messages.length > account.syncConfig.maxMessages) {
+ cache.messages.sort((a, b) => new Date(b.date) - new Date(a.date));
+ cache.messages = cache.messages.slice(0, account.syncConfig.maxMessages);
+ }
+
+ await saveCache(accountId, cache);
+ await updateSyncStatus(accountId, 'success');
+
+ io?.emit('messages:sync:completed', { accountId, newMessages: uniqueNew.length });
+ io?.emit('messages:changed', {});
+ console.log(`📧 Sync complete for ${account.name}: ${uniqueNew.length} new messages`);
+
+ return { newMessages: uniqueNew.length, total: cache.messages.length };
+}
+
+export async function getSyncStatus(accountId) {
+ const account = await getAccount(accountId);
+ if (!account) return null;
+ return {
+ accountId,
+ lastSyncAt: account.lastSyncAt,
+ lastSyncStatus: account.lastSyncStatus
+ };
+}