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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: message actions (archive/delete) with learnable triage rules
Adam Eivy8472431108db
diff --git a/client/src/components/messages/InboxTab.jsx b/client/src/components/messages/InboxTab.jsxindex 6ce3107f05..30b8bbd0fe 100644--- a/client/src/components/messages/InboxTab.jsx+++ b/client/src/components/messages/InboxTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback, useRef } from 'react';-import { Mail, Search, RefreshCw, ChevronRight, Sparkles, Archive, Trash2, Reply, Eye, Flag, Pin } from 'lucide-react';+import { Mail, Search, RefreshCw, ChevronRight, Sparkles, Archive, Trash2, Reply, Eye, Flag, Pin, Loader2 } from 'lucide-react';import { useNavigate } from 'react-router-dom';import toast from 'react-hot-toast';import * as api from '../../services/api';@@ -7,12 +7,17 @@ import socket from '../../services/socket';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' }+ reply: { icon: Reply, color: 'text-port-accent', bg: 'bg-port-accent/10', hoverBg: 'hover:bg-port-accent/20', label: 'Reply' },+ archive: { icon: Archive, color: 'text-gray-400', bg: 'bg-gray-500/10', hoverBg: 'hover:bg-gray-500/20', label: 'Archive' },+ delete: { icon: Trash2, color: 'text-port-error', bg: 'bg-port-error/10', hoverBg: 'hover:bg-port-error/20', label: 'Delete' },+ review: { icon: Eye, color: 'text-port-warning', bg: 'bg-port-warning/10', hoverBg: 'hover:bg-port-warning/20', label: 'Review' }};+const ACTION_ORDER = ['reply', 'review', 'archive', 'delete'];++// Email sources that support archive/delete actions+const ACTIONABLE_SOURCES = ['outlook', 'gmail'];+const PRIORITY_DOT = {high: 'bg-port-error',medium: 'bg-port-warning',@@ -149,6 +154,28 @@ export default function InboxTab({ accounts }) {}};+ const handleAction = async (msg, action, e) => {+ e.stopPropagation();+ if (actionInProgress) return;+ const account = accounts.find(a => a.id === msg.accountId);+ if (!account) return toast.error('No account found for this message');+ if (!ACTIONABLE_SOURCES.includes(msg.source || account.type)) {+ return toast.error(`${action} not supported for ${msg.source || account.type}`);+ }+ setActionInProgress(msg.id);+ toast(`${action === 'archive' ? 'Archiving' : 'Deleting'}...`, { icon: '📧' });+ const result = await api.executeMessageAction(msg.accountId, msg.id, action).catch(err => {+ toast.error(err?.message || `${action} failed`);+ return null;+ });+ setActionInProgress(null);+ if (result?.success) {+ toast.success(`Message ${action === 'archive' ? 'archived' : 'deleted'}`);+ setMessages(prev => prev.filter(m => m.id !== msg.id));+ setTotal(prev => Math.max(0, prev - 1));+ }+ };+if (selectedMessage) {return (<MessageDetail@@ -329,33 +356,47 @@ export default function InboxTab({ accounts }) {</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" />+ {/* Action buttons — always show all, highlight AI recommendation */}+ <div className="flex items-center gap-1 shrink-0">+ {ACTION_ORDER.map(actionKey => {+ const cfg = ACTION_CONFIG[actionKey];+ const Icon = cfg.icon;+ const isRecommended = ev?.action === actionKey;+ const msgSource = msg.source || accounts.find(a => a.id === msg.accountId)?.type;+ const isActionable = ['archive', 'delete'].includes(actionKey) && ACTIONABLE_SOURCES.includes(msgSource);++ const onClick = actionKey === 'reply'+ ? (e) => handleQuickReply(msg, e)+ : actionKey === 'review'+ ? (e) => { e.stopPropagation(); setSelectedMessage(msg); }+ : isActionable+ ? (e) => handleAction(msg, actionKey, e)+ : (e) => { e.stopPropagation(); setSelectedMessage(msg); };++ const title = isRecommended && ev?.reason+ ? `AI: ${cfg.label} — ${ev.reason}`+ : cfg.label;++ return (+ <button+ key={actionKey}+ onClick={onClick}+ disabled={actionInProgress === msg.id}+ className={`flex items-center p-1.5 rounded text-xs transition-colors cursor-pointer disabled:opacity-50 ${+ isRecommended+ ? `${cfg.bg} ${cfg.color} ring-1 ring-current`+ : 'text-gray-500 hover:text-gray-300 hover:bg-port-border/50'+ }`}+ title={title}+ >+ {actionInProgress === msg.id && isActionable+ ? <Loader2 size={14} className="animate-spin" />+ : <Icon size={14} />+ }+ </button>+ );+ })}+ <ChevronRight size={16} className="text-gray-600 ml-1" /></div></div>);diff --git a/client/src/services/api.js b/client/src/services/api.jsindex f93dc238ee..53f09550ea 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1717,7 +1717,7 @@ export const refreshMessage = (accountId, messageId) =>export const fetchFullContent = (accountId, { force } = {}) =>request(`/messages/fetch-full/${accountId}`, { method: 'POST', body: force ? JSON.stringify({ force: true }) : undefined });export const executeMessageAction = (accountId, messageId, action) =>- request(`/messages/${accountId}/${messageId}/action`, { method: 'POST', body: JSON.stringify({ action }) });+ request(`/messages/${accountId}/${messageId}/action`, { method: 'POST', body: JSON.stringify({ action }), silent: true });export const clearMessageCache = (accountId) =>request(`/messages/accounts/${accountId}/cache/clear`, { method: 'POST' });diff --git a/server/routes/messages.js b/server/routes/messages.jsindex 718c5c5bef..2202d5edf1 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -8,6 +8,8 @@ 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';+import { executeAction } from '../services/messageActions.js';+import { listRules, deleteRule } from '../services/messageTriageRules.js';const router = express.Router();@@ -144,6 +146,20 @@ router.get('/inbox', asyncHandler(async (req, res) => {res.json(result);}));+// === Triage Rules Routes ===+router.get('/triage-rules', asyncHandler(async (req, res) => {+ const rules = await listRules();+ res.json({ rules });+}));++router.delete('/triage-rules/:index', asyncHandler(async (req, res) => {+ const index = parseInt(req.params.index, 10);+ if (Number.isNaN(index) || index < 0) return res.status(400).json({ error: 'Invalid rule index' });+ const deleted = await deleteRule(index);+ if (!deleted) return res.status(404).json({ error: 'Rule not found' });+ res.status(204).send();+}));+// === Evaluate Route ===router.post('/evaluate', asyncHandler(async (req, res) => {const { accountId, messageIds } = req.body || {};@@ -370,6 +386,20 @@ router.post('/accounts/:id/cache/clear', asyncHandler(async (req, res) => {res.status(204).send();}));+// === Message Action Route (archive/delete) ===+router.post('/:accountId/:messageId/action', asyncHandler(async (req, res) => {+ const parsed = messageParamsSchema.safeParse(req.params);+ if (!parsed.success) return res.status(400).json({ error: 'Invalid accountId or messageId format' });+ const { accountId, messageId } = parsed.data;+ const action = req.body?.action;+ if (!['archive', 'delete'].includes(action)) {+ return res.status(400).json({ error: 'Invalid action — must be "archive" or "delete"' });+ }+ const result = await executeAction(accountId, messageId, action);+ req.app.get('io')?.emit('messages:changed', {});+ res.json(result);+}));+// === Message Detail Route (last to avoid capturing /launch, /selectors paths) ===router.get('/:accountId/:messageId', asyncHandler(async (req, res) => {diff --git a/server/services/messageActions.js b/server/services/messageActions.jsnew file mode 100644index 0000000000..ad168a0397--- /dev/null+++ b/server/services/messageActions.js@@ -0,0 +1,210 @@+import { getAccount } from './messageAccounts.js';+import { getMessage } from './messageSync.js';+import { findOrOpenPage, getPages, isAuthPage, evaluateOnPage } from './messagePlaywrightSync.js';+import { recordCorrection } from './messageTriageRules.js';+import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';++const CACHE_DIR = join(PATHS.messages, 'cache');+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++const PROVIDER_URLS = {+ outlook: 'https://outlook.office.com/mail/',+ gmail: 'https://mail.google.com/'+};++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));+}++async function removeFromCache(accountId, messageId) {+ const cache = await loadCache(accountId);+ cache.messages = cache.messages.filter(m => m.id !== messageId);+ await saveCache(accountId, cache);+}++/**+ * Wait for a provider page to be ready (past auth screens).+ * Auto-launches the tab if not open, then polls until auth completes or timeout.+ */+async function ensureProviderPage(accountType) {+ const url = PROVIDER_URLS[accountType];+ if (!url) throw new Error(`Unsupported provider: ${accountType}`);++ // Launch or find the tab+ console.log(`📧 Ensuring ${accountType} browser tab is ready...`);+ let page = await findOrOpenPage(url).catch(() => null);+ if (!page) throw new Error(`Failed to open ${accountType} browser tab — is portos-browser running?`);++ // If already on the mail page (not auth), we're good+ if (!isAuthPage(page)) return page;++ // Auth page detected — poll until the user logs in (up to 2 minutes)+ console.log(`📧 Auth page detected for ${accountType} — waiting for login...`);+ const maxWait = 120000;+ const pollInterval = 3000;+ const start = Date.now();++ while (Date.now() - start < maxWait) {+ await new Promise(r => setTimeout(r, pollInterval));+ const pages = await getPages().catch(() => []);+ const hostname = new URL(url).hostname;+ page = pages.find(p => p.url?.includes(hostname));+ if (page && !isAuthPage(page)) {+ console.log(`📧 ${accountType} auth complete, proceeding`);+ return page;+ }+ }++ throw new Error(`Login timed out — please sign into ${accountType} and try again`);+}++/**+ * Execute an action (archive/delete) on a message via CDP browser automation.+ * Auto-launches the browser tab and waits for auth if needed.+ */+export async function executeAction(accountId, messageId, action) {+ if (!UUID_RE.test(accountId)) throw new Error('Invalid accountId');+ if (!['archive', 'delete'].includes(action)) throw new Error(`Unsupported action: ${action}`);++ const account = await getAccount(accountId);+ if (!account) throw new Error('Account not found');++ const message = await getMessage(accountId, messageId);+ if (!message) throw new Error('Message not found');++ if (!PROVIDER_URLS[account.type]) {+ throw new Error(`${action} not supported for ${account.type}`);+ }++ const page = await ensureProviderPage(account.type);++ const safeSubject = (message.subject || '').replace(/'/g, "\\'").replace(/\n/g, ' ');+ const script = account.type === 'outlook'+ ? buildOutlookActionScript(safeSubject, action)+ : buildGmailActionScript(safeSubject, action);++ console.log(`📧 ${action} message "${message.subject}" via ${account.type} browser`);+ const result = await evaluateOnPage(page, script);++ if (!result || result.error) {+ const errorMsg = result?.error || `${action} failed — script returned no result`;+ // If message genuinely not in inbox, just clean up local cache+ if (result?.notInInbox) {+ console.log(`📧 "${message.subject}" not found in inbox, cleaning up local cache`);+ } else {+ throw new Error(errorMsg);+ }+ } else {+ console.log(`📧 ${action} executed in browser for "${message.subject}"`);+ }++ // Record triage correction if user chose differently than the AI+ const triaged = message.evaluation?.action;+ if (triaged && triaged !== action) {+ await recordCorrection({+ from: message.from?.name || message.from?.email || 'Unknown',+ subject: message.subject || '',+ triaged,+ corrected: action+ }).catch(() => {});+ }++ await removeFromCache(accountId, messageId);+ console.log(`📧 ${action} complete for "${message.subject}"`);++ return { success: true, action, messageId };+}++function buildOutlookActionScript(subject, action) {+ // Use the same listbox/option approach proven by the sync scraper,+ // then use keyboard shortcuts (Delete key or Backspace for archive)+ const keyCode = action === 'delete' ? 'Delete' : 'Backspace';+ return `(async () => {+ const listbox = document.querySelector("[role='listbox']");+ if (!listbox) return { error: 'No message list found — is Outlook inbox visible?' };++ const targetSubject = ${JSON.stringify(subject)}.toLowerCase();+ const scrollContainer = listbox.closest('[role="region"]') || listbox.parentElement;++ function findMatch() {+ const rows = listbox.querySelectorAll('[role="option"]');+ for (const row of rows) {+ const label = (row.getAttribute('aria-label') || '').toLowerCase();+ const text = (row.innerText || '').toLowerCase();+ if (label.includes(targetSubject) || text.includes(targetSubject)) return row;+ }+ return null;+ }++ // Search visible rows, then scroll to find+ let matched = findMatch();+ if (!matched && scrollContainer) {+ for (let i = 0; i < 15; i++) {+ scrollContainer.scrollBy(0, 600);+ await new Promise(r => setTimeout(r, 300));+ matched = findMatch();+ if (matched) break;+ }+ }+ if (!matched) return { error: 'Message not found in inbox view', notInInbox: true };++ // Select the message+ matched.scrollIntoView({ block: 'center' });+ await new Promise(r => setTimeout(r, 200));+ matched.click();+ await new Promise(r => setTimeout(r, 500));++ // Use keyboard shortcut — most reliable in Outlook web+ document.activeElement?.dispatchEvent(new KeyboardEvent('keydown', { key: '${keyCode}', code: '${keyCode}', bubbles: true }));+ await new Promise(r => setTimeout(r, 500));++ // Fallback: try toolbar button if keyboard didn't work+ const label = '${action === 'delete' ? 'Delete' : 'Archive'}';+ const btn = [...document.querySelectorAll('button[aria-label]')].find(b =>+ b.getAttribute('aria-label')?.toLowerCase().includes(label.toLowerCase()) && b.offsetParent !== null+ );+ if (btn) {+ btn.click();+ await new Promise(r => setTimeout(r, 500));+ }++ // Verify the message is gone from the list+ await new Promise(r => setTimeout(r, 500));+ const stillThere = findMatch();+ if (stillThere) return { error: 'Message still in inbox after ${action} attempt — action may not have worked' };++ return { success: true };+ })()`;+}++function buildGmailActionScript(subject, action) {+ const ariaLabel = action === 'archive' ? 'Archive' : 'Delete';+ return `(async () => {+ const rows = [...document.querySelectorAll('tr.zA, [role="row"]')];+ const row = rows.find(r => r.textContent?.includes('${subject}'));+ if (!row) return { error: 'Message not found in inbox view' };++ const checkbox = row.querySelector('[role="checkbox"], input[type="checkbox"]');+ if (checkbox) checkbox.click();+ await new Promise(r => setTimeout(r, 300));++ const btn = document.querySelector('[aria-label="${ariaLabel}"], [data-tooltip="${ariaLabel}"]');+ if (!btn) return { error: '${ariaLabel} button not found' };++ btn.click();+ await new Promise(r => setTimeout(r, 1000));+ return { success: true };+ })()`;+}diff --git a/server/services/messageEvaluator.js b/server/services/messageEvaluator.jsindex cfd3ae4f05..090aa4a279 100644--- a/server/services/messageEvaluator.js+++ b/server/services/messageEvaluator.js@@ -1,6 +1,7 @@import { getSettings } from './settings.js';import { getProviderById, getAllProviders } from './providers.js';import { createRun, executeApiRun, executeCliRun } from './runner.js';+import { buildRulesPromptSection } from './messageTriageRules.js';const EVAL_PROMPT = `You are an email triage assistant. For each email below, recommend ONE action and a brief reason.@@ -123,7 +124,8 @@ export async function evaluateMessages(messages) {const { provider, model } = await resolveProviderConfig('triage');const payload = buildEvalPayload(messages);- const prompt = EVAL_PROMPT + JSON.stringify(payload, null, 2) + '\n' + EVAL_PROMPT_SUFFIX;+ const rulesSection = await buildRulesPromptSection();+ const prompt = EVAL_PROMPT + rulesSection + JSON.stringify(payload, null, 2) + '\n' + EVAL_PROMPT_SUFFIX;console.log(`📧 Evaluating ${messages.length} messages with ${provider.name}/${model || provider.defaultModel}`);const response = await runPrompt(provider, model, prompt, 'messages-triage');diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.jsindex 065eb32059..917109c07b 100644--- a/server/services/messagePlaywrightSync.js+++ b/server/services/messagePlaywrightSync.js@@ -38,13 +38,13 @@ async function cdpFetch(path, options = {}) {return response;}-async function getPages() {+export async function getPages() {const response = await cdpFetch('/json/list');if (!response.ok) return [];return response.json();}-async function findOrOpenPage(targetUrl) {+export async function findOrOpenPage(targetUrl) {const pages = await getPages();// Find existing tab matching the targetconst existing = pages.find(p => p.url?.includes(new URL(targetUrl).hostname));@@ -55,13 +55,13 @@ async function findOrOpenPage(targetUrl) {return response.json();}-function isAuthPage(page) {+export function isAuthPage(page) {const url = page.url || '';const title = page.title || '';return AUTH_PATTERNS.some(p => url.includes(p) || title.includes(p));}-async function evaluateOnPage(page, expression) {+export async function evaluateOnPage(page, expression) {const wsUrl = page.webSocketDebuggerUrl;if (!wsUrl) return null;diff --git a/server/services/messageTriageRules.js b/server/services/messageTriageRules.jsnew file mode 100644index 0000000000..bdc5628cbb--- /dev/null+++ b/server/services/messageTriageRules.js@@ -0,0 +1,88 @@+import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';++const RULES_FILE = join(PATHS.messages, 'triage-rules.json');++async function loadRules() {+ await ensureDir(PATHS.messages);+ const content = await readFile(RULES_FILE, 'utf-8').catch(() => null);+ if (!content) return { rules: [] };+ return safeJSONParse(content, { rules: [] }, { context: 'triage-rules' });+}++async function saveRules(data) {+ await ensureDir(PATHS.messages);+ await writeFile(RULES_FILE, JSON.stringify(data, null, 2));+}++/**+ * Get all triage rules for injection into the LLM prompt.+ */+export async function getTriageRules() {+ const { rules } = await loadRules();+ return rules;+}++/**+ * Record a user correction: when they take a different action than the AI recommended.+ * Deduplicates by pattern — if the same sender/pattern already has a rule, update it.+ */+export async function recordCorrection({ from, subject, triaged, corrected }) {+ const data = await loadRules();+ // Build a pattern from the sender — strip email-specific parts for generalization+ const senderPattern = from || 'Unknown';+ // Check if we already have a rule for this sender+action combo+ const existing = data.rules.find(r =>+ r.senderPattern === senderPattern && r.correctedAction === corrected+ );+ if (existing) {+ existing.count = (existing.count || 1) + 1;+ existing.lastSeen = new Date().toISOString();+ existing.exampleSubject = subject;+ } else {+ data.rules.push({+ senderPattern,+ exampleSubject: subject || '',+ originalAction: triaged,+ correctedAction: corrected,+ count: 1,+ createdAt: new Date().toISOString(),+ lastSeen: new Date().toISOString()+ });+ }+ await saveRules(data);+ console.log(`📧 Triage rule recorded: "${senderPattern}" ${triaged} -> ${corrected}`);+}++/**+ * Build a prompt section describing user triage preferences.+ */+export async function buildRulesPromptSection() {+ const rules = await getTriageRules();+ if (!rules.length) return '';++ const lines = rules.map(r =>+ `- Emails from "${r.senderPattern}" should be "${r.correctedAction}" (not "${r.originalAction}"). Example subject: "${r.exampleSubject}"`+ );+ return `\n\nUser triage preferences (ALWAYS follow these rules — they override your default judgment):\n${lines.join('\n')}\n`;+}++/**+ * Delete a specific rule by index.+ */+export async function deleteRule(index) {+ const data = await loadRules();+ if (index < 0 || index >= data.rules.length) return false;+ data.rules.splice(index, 1);+ await saveRules(data);+ return true;+}++/**+ * Get all rules (for UI display).+ */+export async function listRules() {+ const { rules } = await loadRules();+ return rules;+}