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: AI email triage, real AI reply generation, fix validation bug

Adam Eivy7c8881a5c3a0
diff --git a/client/src/components/messages/InboxTab.jsx b/client/src/components/messages/InboxTab.jsx
index c717e5b0c1..44ee020c50 100644
--- a/client/src/components/messages/InboxTab.jsx
+++ b/client/src/components/messages/InboxTab.jsx
@@ -1,8 +1,23 @@
import { useState, useEffect, useCallback, useRef } from 'react';
-import { Mail, Search, RefreshCw, ChevronRight } from 'lucide-react';
+import { Mail, Search, RefreshCw, ChevronRight, Sparkles, Archive, Trash2, Reply, Eye, Flag, Pin } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import toast from 'react-hot-toast';
import * as api from '../../services/api';
import MessageDetail from './MessageDetail';
+const ACTION_CONFIG = {
+ reply: { icon: Reply, color: 'text-port-accent', bg: 'bg-port-accent/10', label: 'Reply' },
+ archive: { icon: Archive, color: 'text-gray-400', bg: 'bg-gray-500/10', label: 'Archive' },
+ delete: { icon: Trash2, color: 'text-port-error', bg: 'bg-port-error/10', label: 'Delete' },
+ review: { icon: Eye, color: 'text-port-warning', bg: 'bg-port-warning/10', label: 'Review' }
+};
+
+const PRIORITY_DOT = {
+ high: 'bg-port-error',
+ medium: 'bg-port-warning',
+ low: 'bg-gray-500'
+};
+
export default function InboxTab({ accounts }) {
const [messages, setMessages] = useState([]);
const [total, setTotal] = useState(0);
@@ -11,7 +26,9 @@ export default function InboxTab({ accounts }) {
const [debouncedSearch, setDebouncedSearch] = useState('');
const [selectedAccount, setSelectedAccount] = useState('');
const [selectedMessage, setSelectedMessage] = useState(null);
+ const [evaluating, setEvaluating] = useState(false);
const debounceRef = useRef(null);
+ const navigate = useNavigate();
useEffect(() => {
clearTimeout(debounceRef.current);
@@ -34,12 +51,48 @@ export default function InboxTab({ accounts }) {
fetchMessages();
}, [fetchMessages]);
+ const handleEvaluate = async () => {
+ setEvaluating(true);
+ const data = selectedAccount ? { accountId: selectedAccount } : {};
+ const result = await api.evaluateMessages(data).catch((err) => {
+ toast.error(err?.message || 'Evaluation failed');
+ return null;
+ });
+ setEvaluating(false);
+ if (!result) return;
+ const count = Object.keys(result.evaluations || {}).length;
+ toast.success(`Evaluated ${count} messages`);
+ // Merge evaluations into local state
+ setMessages(prev => prev.map(m => {
+ const ev = result.evaluations?.[m.id];
+ return ev ? { ...m, evaluation: ev } : m;
+ }));
+ };
+
+ const handleQuickReply = async (msg, e) => {
+ e.stopPropagation();
+ const account = accounts.find(a => a.id === msg.accountId) || accounts[0];
+ if (!account) return toast.error('No account available');
+ toast('Generating AI reply...', { icon: '✨' });
+ const draft = await api.generateMessageDraft({
+ accountId: account.id,
+ replyToMessageId: msg.id,
+ threadId: msg.threadId,
+ context: `Replying to: "${msg.subject}" from ${msg.from?.name || msg.from?.email}`,
+ instructions: ''
+ }).catch(() => null);
+ if (draft) {
+ toast.success('Draft created — opening Drafts');
+ navigate('/messages/drafts');
+ }
+ };
+
if (selectedMessage) {
return (
<MessageDetail
message={selectedMessage}
accounts={accounts}
- onBack={() => setSelectedMessage(null)}
+ onBack={() => { setSelectedMessage(null); fetchMessages(); }}
/>
);
}
@@ -67,6 +120,15 @@ export default function InboxTab({ accounts }) {
<option key={a.id} value={a.id}>{a.name}</option>
))}
</select>
+ <button
+ onClick={handleEvaluate}
+ disabled={evaluating}
+ className="flex items-center gap-1 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"
+ title="AI triage — evaluate messages for recommended actions"
+ >
+ <Sparkles size={14} className={evaluating ? 'animate-pulse' : ''} />
+ {evaluating ? 'Evaluating...' : 'Triage'}
+ </button>
<button
onClick={fetchMessages}
className="p-2 text-gray-400 hover:text-white transition-colors"
@@ -87,33 +149,76 @@ export default function InboxTab({ accounts }) {
)}
<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)'}
+ {messages.map((msg) => {
+ const ev = msg.evaluation;
+ const actionCfg = ev ? ACTION_CONFIG[ev.action] : null;
+ const ActionIcon = actionCfg?.icon;
+ return (
+ <div
+ key={msg.id}
+ className={`flex items-center gap-3 p-3 rounded-lg transition-colors hover:bg-port-card group ${
+ msg.isRead && !msg.isUnread ? 'opacity-70' : ''
+ }`}
+ >
+ {/* Priority dot + flags */}
+ <div className="flex flex-col items-center gap-1 w-4 shrink-0">
+ {ev && <span className={`w-2 h-2 rounded-full ${PRIORITY_DOT[ev.priority] || PRIORITY_DOT.medium}`} title={`${ev.priority} priority`} />}
+ {msg.isPinned && <Pin size={10} className="text-gray-500" />}
+ {msg.isFlagged && <Flag size={10} className="text-port-warning" />}
</div>
- <div className="text-xs text-gray-600 truncate">
- {msg.bodyText?.substring(0, 100) || ''}
+
+ {/* Message content — clickable */}
+ <button
+ onClick={() => setSelectedMessage(msg)}
+ className="flex-1 min-w-0 text-left"
+ >
+ <div className="flex items-center gap-2">
+ <span className={`text-sm truncate ${msg.isUnread || !msg.isRead ? 'text-white font-medium' : 'text-gray-400'}`}>
+ {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.isUnread || !msg.isRead ? 'text-gray-300' : 'text-gray-500'}`}>
+ {msg.subject || '(no subject)'}
+ </div>
+ <div className="text-xs text-gray-600 truncate">
+ {msg.bodyText?.substring(0, 100) || ''}
+ </div>
+ </button>
+
+ {/* Evaluation badge + quick action */}
+ <div className="flex items-center gap-2 shrink-0">
+ {ev && (
+ <span className={`flex items-center gap-1 px-2 py-1 rounded text-xs ${actionCfg.bg} ${actionCfg.color}`} title={ev.reason}>
+ {ActionIcon && <ActionIcon size={12} />}
+ {actionCfg.label}
+ </span>
+ )}
+ {ev?.action === 'reply' && (
+ <button
+ onClick={(e) => handleQuickReply(msg, e)}
+ className="flex items-center gap-1 px-2 py-1 bg-port-accent/10 text-port-accent rounded text-xs hover:bg-port-accent/20 transition-colors opacity-0 group-hover:opacity-100"
+ title="Generate AI reply draft"
+ >
+ <Sparkles size={12} /> Draft
+ </button>
+ )}
+ {!ev && (
+ <button
+ onClick={(e) => handleQuickReply(msg, e)}
+ className="flex items-center gap-1 px-2 py-1 bg-port-accent/10 text-port-accent rounded text-xs hover:bg-port-accent/20 transition-colors opacity-0 group-hover:opacity-100"
+ title="Generate AI reply draft"
+ >
+ <Reply size={12} /> Reply
+ </button>
+ )}
+ <ChevronRight size={16} className="text-gray-600" />
</div>
</div>
- <ChevronRight size={16} className="text-gray-600 shrink-0" />
- </button>
- ))}
+ );
+ })}
</div>
</div>
);
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 39f32e717d..a5a86a7345 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1617,6 +1617,7 @@ export const updateMessageAccount = (id, data) => request(`/messages/accounts/${
export const deleteMessageAccount = (id) => request(`/messages/accounts/${id}`, { method: 'DELETE' });
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 evaluateMessages = (data = {}) => request('/messages/evaluate', { method: 'POST', body: JSON.stringify(data) });
export const getMessageInbox = (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 a973bc61a8..de24ee910d 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -7,6 +7,7 @@ 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, launchProvider } from '../services/messagePlaywrightSync.js';
+import { evaluateMessages, generateReplyBody } from '../services/messageEvaluator.js';
const router = express.Router();
@@ -35,8 +36,8 @@ const updateAccountSchema = z.object({
const createDraftSchema = z.object({
accountId: z.string().uuid(),
- replyToMessageId: z.string().optional(),
- threadId: z.string().optional(),
+ replyToMessageId: z.string().nullish(),
+ threadId: z.string().nullish(),
to: z.array(z.string()).optional().default([]),
cc: z.array(z.string()).optional().default([]),
subject: z.string().optional().default(''),
@@ -55,8 +56,8 @@ const updateDraftSchema = z.object({
const generateDraftSchema = z.object({
accountId: z.string().uuid(),
- replyToMessageId: z.string().optional(),
- threadId: z.string().optional(),
+ replyToMessageId: z.string().nullish(),
+ threadId: z.string().nullish(),
context: z.string().optional().default(''),
instructions: z.string().optional().default('')
});
@@ -143,6 +144,30 @@ router.get('/inbox', asyncHandler(async (req, res) => {
res.json(result);
}));
+// === Evaluate Route ===
+router.post('/evaluate', asyncHandler(async (req, res) => {
+ const { accountId, messageIds } = req.body || {};
+ // Get messages to evaluate
+ let messages;
+ if (messageIds && Array.isArray(messageIds)) {
+ // Evaluate specific messages
+ const allResult = await messageSync.getMessages({ accountId, limit: 100 });
+ messages = allResult.messages.filter(m => messageIds.includes(m.id));
+ } else {
+ // Evaluate all unevaluated messages (up to 20)
+ const allResult = await messageSync.getMessages({ accountId, limit: 50 });
+ messages = allResult.messages.filter(m => !m.evaluation).slice(0, 20);
+ }
+ if (!messages.length) return res.json({ evaluations: {} });
+
+ const result = await evaluateMessages(messages);
+
+ // Store evaluations back on cached messages
+ await messageSync.updateMessageEvaluations(result.evaluations);
+
+ res.json(result);
+}));
+
// === Draft Routes ===
router.get('/drafts', asyncHandler(async (req, res) => {
const { accountId, status } = req.query;
@@ -171,14 +196,29 @@ router.post('/drafts/generate', asyncHandler(async (req, res) => {
const data = validateRequest(generateDraftSchema, req.body);
const account = await messageAccounts.getAccount(data.accountId);
if (!account) return res.status(404).json({ error: 'Account not found' });
- // AI draft generation - stub for now
- // TODO: Use portos-ai-toolkit for provider selection and model tiers
+
+ // Fetch the original message to build AI reply
+ let replyBody = '';
+ if (data.replyToMessageId) {
+ const originalMsg = await messageSync.getMessage(data.accountId, data.replyToMessageId);
+ if (originalMsg) {
+ const aiResult = await generateReplyBody(originalMsg, data.instructions).catch(err => {
+ console.log(`📧 AI reply generation failed, using placeholder: ${err.message}`);
+ return null;
+ });
+ replyBody = aiResult?.body || `[AI generation failed — configure provider in Messages > Config]\n\nContext: ${data.context}`;
+ }
+ }
+ if (!replyBody) {
+ replyBody = `[No original message found]\n\nContext: ${data.context}\nInstructions: ${data.instructions}`;
+ }
+
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}`,
+ body: replyBody,
generatedBy: 'ai',
sendVia: account.provider || (account.type === 'gmail' ? 'mcp' : 'playwright')
});
diff --git a/server/services/messageEvaluator.js b/server/services/messageEvaluator.js
new file mode 100644
index 0000000000..f5179a9a19
--- /dev/null
+++ b/server/services/messageEvaluator.js
@@ -0,0 +1,164 @@
+import { getSettings } from './settings.js';
+import { getProviderById } from './providers.js';
+
+const EVAL_PROMPT = `You are an email triage assistant. For each email below, recommend ONE action and a brief reason.
+
+Actions:
+- reply: Email requires or warrants a response from the user
+- archive: Informational, no action needed (newsletters, notifications, FYI)
+- delete: Junk, spam, or irrelevant
+- review: Needs the user to read but no reply needed (meeting invites, action items)
+
+Respond with ONLY a JSON array, one object per email:
+[{ "id": "MSG_ID", "action": "reply|archive|delete|review", "reason": "brief reason", "priority": "high|medium|low" }]
+
+Emails:
+`;
+
+function buildEvalPayload(messages) {
+ return messages.map(m => ({
+ id: m.id,
+ from: m.from?.name || m.from?.email || 'Unknown',
+ subject: m.subject || '(no subject)',
+ preview: (m.bodyText || '').slice(0, 300),
+ isUnread: m.isUnread ?? !m.isRead,
+ isFlagged: m.isFlagged ?? false,
+ hasMeetingInvite: m.hasMeetingInvite ?? false
+ }));
+}
+
+async function callProviderApi(provider, model, prompt) {
+ const endpoint = provider.endpoint?.replace(/\/$/, '');
+ if (!endpoint) throw new Error('Provider has no API endpoint');
+
+ const body = {
+ model: model || provider.defaultModel,
+ messages: [{ role: 'user', content: prompt }],
+ temperature: 0.2,
+ max_tokens: 2000
+ };
+
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ // Anthropic API uses x-api-key
+ if (provider.id?.includes('claude') || provider.id?.includes('anthropic') || endpoint.includes('anthropic')) {
+ headers['x-api-key'] = provider.apiKey;
+ headers['anthropic-version'] = '2023-06-01';
+ body.messages = [{ role: 'user', content: prompt }];
+ body.max_tokens = 2000;
+ delete body.max_tokens;
+ body.max_tokens = 2000;
+ }
+
+ const response = await fetch(endpoint + '/chat/completions', {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(30000)
+ });
+
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ throw new Error(`Provider API error ${response.status}: ${text.slice(0, 200)}`);
+ }
+
+ const data = await response.json();
+ // OpenAI-compatible response format
+ return data.choices?.[0]?.message?.content || '';
+}
+
+function parseEvalResponse(text, messageIds) {
+ // Extract JSON array from response (may have markdown fences)
+ const jsonMatch = text.match(/\[[\s\S]*\]/);
+ if (!jsonMatch) return null;
+
+ const parsed = JSON.parse(jsonMatch[0]);
+ if (!Array.isArray(parsed)) return null;
+
+ // Index by message ID, only keep valid entries
+ const validActions = new Set(['reply', 'archive', 'delete', 'review']);
+ const validPriorities = new Set(['high', 'medium', 'low']);
+ const result = {};
+ for (const entry of parsed) {
+ if (!entry.id || !messageIds.has(entry.id)) continue;
+ result[entry.id] = {
+ action: validActions.has(entry.action) ? entry.action : 'review',
+ reason: String(entry.reason || '').slice(0, 200),
+ priority: validPriorities.has(entry.priority) ? entry.priority : 'medium'
+ };
+ }
+ return result;
+}
+
+/**
+ * Evaluate a batch of messages and return action recommendations.
+ * @param {Array} messages - Messages to evaluate
+ * @returns {{ evaluations: Object<messageId, { action, reason, priority }> }}
+ */
+export async function evaluateMessages(messages) {
+ if (!messages.length) return { evaluations: {} };
+
+ const settings = await getSettings();
+ const msgConfig = settings?.messages || {};
+ const providerId = msgConfig.providerId;
+ const model = msgConfig.model;
+
+ if (!providerId) throw new Error('No AI provider configured for Messages — set one in Messages > Config');
+
+ const provider = await getProviderById(providerId);
+ if (!provider) throw new Error(`AI provider "${providerId}" not found`);
+ if (provider.type !== 'api') throw new Error('Message evaluation requires an API provider (not CLI)');
+
+ const payload = buildEvalPayload(messages);
+ const prompt = EVAL_PROMPT + JSON.stringify(payload, null, 2);
+
+ console.log(`📧 Evaluating ${messages.length} messages with ${provider.name}/${model || provider.defaultModel}`);
+ const response = await callProviderApi(provider, model, prompt);
+
+ const messageIds = new Set(messages.map(m => m.id));
+ const evaluations = parseEvalResponse(response, messageIds);
+ if (!evaluations) throw new Error('Failed to parse AI evaluation response');
+
+ console.log(`📧 Evaluated ${Object.keys(evaluations).length}/${messages.length} messages`);
+ return { evaluations };
+}
+
+/**
+ * Generate an AI reply draft for a message.
+ * @param {object} message - The message to reply to
+ * @param {string} instructions - Additional instructions
+ * @returns {{ body: string }}
+ */
+export async function generateReplyBody(message, instructions = '') {
+ const settings = await getSettings();
+ const msgConfig = settings?.messages || {};
+ const providerId = msgConfig.providerId;
+ const model = msgConfig.model;
+
+ if (!providerId) throw new Error('No AI provider configured for Messages — set one in Messages > Config');
+
+ const provider = await getProviderById(providerId);
+ if (!provider) throw new Error(`AI provider "${providerId}" not found`);
+ if (provider.type !== 'api') throw new Error('Reply generation requires an API provider (not CLI)');
+
+ // Build prompt from template
+ let template = msgConfig.replyTemplate || 'Write a professional reply to this email.\n\nFrom: {{from}}\nSubject: {{subject}}\nBody:\n{{body}}';
+ const vars = {
+ from: message.from?.name || message.from?.email || 'Unknown',
+ subject: message.subject || '',
+ body: message.bodyText || '',
+ instructions: instructions || ''
+ };
+ // Simple mustache-like substitution
+ for (const [key, val] of Object.entries(vars)) {
+ template = template.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), val);
+ }
+ // Handle conditional blocks {{#key}}...{{/key}}
+ template = template.replace(/\{\{#(\w+)\}\}([\s\S]*?)\{\{\/\1\}\}/g, (_, key, block) => {
+ return vars[key] ? block.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), vars[key]) : '';
+ });
+
+ console.log(`📧 Generating AI reply with ${provider.name}/${model || provider.defaultModel}`);
+ const response = await callProviderApi(provider, model, template);
+ return { body: response.trim() };
+}
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 82ff4ad0bc..02ed82a90c 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -174,6 +174,26 @@ export async function syncAccount(accountId, io, options = {}) {
return result;
}
+export async function updateMessageEvaluations(evaluations) {
+ await ensureDir(CACHE_DIR);
+ const { readdir } = await import('fs/promises');
+ const files = await readdir(CACHE_DIR).catch(() => []);
+ for (const file of files) {
+ if (!file.endsWith('.json')) continue;
+ const accountId = file.replace('.json', '');
+ if (!UUID_RE.test(accountId)) continue;
+ const cache = await loadCache(accountId);
+ let changed = false;
+ for (const msg of cache.messages) {
+ if (evaluations[msg.id]) {
+ msg.evaluation = evaluations[msg.id];
+ changed = true;
+ }
+ }
+ if (changed) await saveCache(accountId, cache);
+ }
+}
+
export async function getSyncStatus(accountId) {
const account = await getAccount(accountId);
if (!account) return null;