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: Gmail API actions, HTML email rendering, compact message header
Adam Eivy4c0b0edfdaea
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c2018b5f31..2c2225329a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,6 @@## Added-- **M50 P7: Gmail API Sync** — Gmail integration via Google API (same OAuth as Calendar). Syncs inbox messages with full body extraction, thread grouping, label mapping, and starred/read status. Sends email via Gmail API with RFC 2822 formatting and reply threading. Replaces MCP stub with direct API calls.+- **M50 P7: Gmail API Sync** — Gmail integration via Google API (same OAuth as Calendar). Syncs inbox messages with full body extraction, thread grouping, label mapping, and starred/read status. Sends email via Gmail API with RFC 2822 formatting and reply threading. Archive/delete via API (no browser needed). HTML email rendering in sandboxed iframe. Compact message detail header. Gmail setup checklist in Config with OAuth and API enable controls.- **M56: Telegram Bot Integration** — Telegram bot for external notifications and conversational commands. Configure bot token and chat ID in Settings. Forwards PortOS notifications (filterable by type) to Telegram with rate limiting. Bot commands: `/status`, `/goals`, `/agents`, `/checkin`, `/help`. Check-in responses are persisted for goal tracking.- **M49 P1: Goal Todos & Progress Tracking** — Enhanced goal model with explicit progress percentage, todo sub-tasks (with priority and time estimates), velocity tracking (percent/month with trend), projected completion dates, and time tracking aggregates. Progress bar and todos visible in both goal list rows and detail panel.diff --git a/client/src/components/messages/MessageDetail.jsx b/client/src/components/messages/MessageDetail.jsxindex 050e79982a..dd985edcea 100644--- a/client/src/components/messages/MessageDetail.jsx+++ b/client/src/components/messages/MessageDetail.jsx@@ -1,8 +1,62 @@-import { useState, useEffect } from 'react';-import { ArrowLeft, Reply, Sparkles, Send, MessageSquare, RefreshCw } from 'lucide-react';+import { useState, useEffect, useRef, useCallback } from 'react';+import { ArrowLeft, Reply, Sparkles, Send, MessageSquare, RefreshCw, Archive, Trash2 } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../services/api';+/**+ * Renders HTML email content in a sandboxed iframe.+ * Strips scripts, sets sandbox restrictions, and auto-resizes to content height.+ */+function SafeHtmlBody({ html }) {+ const iframeRef = useRef(null);++ const writeContent = useCallback(() => {+ const iframe = iframeRef.current;+ if (!iframe) return;++ // Strip script tags and event handlers from HTML+ const sanitized = html+ .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')+ .replace(/\s+on\w+\s*=\s*["'][^"']*["']/gi, '')+ .replace(/\s+on\w+\s*=\s*\S+/gi, '');++ const doc = iframe.contentDocument;+ if (!doc) return;++ doc.open();+ doc.write(`<!DOCTYPE html><html><head><style>+ body { margin: 0; padding: 8px; font-family: -apple-system, sans-serif; font-size: 14px; color: #d1d5db; background: transparent; word-wrap: break-word; overflow-wrap: break-word; }+ a { color: #3b82f6; }+ img { max-width: 100%; height: auto; }+ table { max-width: 100% !important; }+ </style></head><body>${sanitized}</body></html>`);+ doc.close();++ // Auto-resize iframe to content height+ const resize = () => {+ const h = doc.documentElement?.scrollHeight || doc.body?.scrollHeight;+ if (h) iframe.style.height = `${h + 16}px`;+ };+ resize();+ // Resize again after images load+ doc.querySelectorAll('img').forEach(img => img.addEventListener('load', resize));+ }, [html]);++ useEffect(() => {+ writeContent();+ }, [writeContent]);++ return (+ <iframe+ ref={iframeRef}+ sandbox="allow-same-origin"+ className="w-full border-0 min-h-[100px]"+ style={{ background: 'transparent' }}+ title="Email content"+ />+ );+}+export default function MessageDetail({ message, accounts, onBack }) {const [showReply, setShowReply] = useState(false);const [replyBody, setReplyBody] = useState('');@@ -12,6 +66,7 @@ export default function MessageDetail({ message, accounts, onBack }) {const [threadLoading, setThreadLoading] = useState(false);const [refreshing, setRefreshing] = useState(false);const [displayedMessage, setDisplayedMessage] = useState(message);+ const [actioning, setActioning] = useState(null);// Sync displayedMessage when the message prop changes (e.g., selecting a different message)useEffect(() => {@@ -36,7 +91,6 @@ export default function MessageDetail({ message, accounts, onBack }) {setRefreshing(false);if (!result) return;if (result.error) return toast.error(result.error);- // Result is the updated messages arrayif (Array.isArray(result)) {const updated = result.find(m => m.id === message.id) || result[0];if (updated) setDisplayedMessage(prev => ({ ...prev, ...updated }));@@ -84,29 +138,73 @@ export default function MessageDetail({ message, accounts, onBack }) {setGeneratedDraftId(null);};+ const handleAction = (action) => {+ if (!displayedMessage.accountId) return;+ setActioning(action);+ api.executeMessageAction(displayedMessage.accountId, displayedMessage.id, action)+ .then(() => {+ toast.success(`Message ${action}d`);+ onBack();+ })+ .catch(() => toast.error(`Failed to ${action} message`))+ .finally(() => setActioning(null));+ };+// Show thread or single messageconst hasThread = threadMessages.length > 1;const displayMessages = hasThread ? threadMessages : [displayedMessage];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">- <h2 className="text-lg font-medium text-white">{displayedMessage.subject || '(no subject)'}</h2>- {hasThread && (- <div className="flex items-center gap-2 mt-1 text-xs text-gray-500">- <MessageSquare size={12} />- <span>{threadMessages.length} messages in conversation</span>- </div>- )}+ {/* Header: back + subject + actions — single compact row */}+ <div className="flex items-center gap-3 px-3 py-2 bg-port-card rounded-lg border border-port-border">+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors shrink-0">+ <ArrowLeft size={16} />+ </button>+ <div className="flex-1 min-w-0">+ <h2 className="text-sm font-medium text-white truncate">{displayedMessage.subject || '(no subject)'}</h2>+ {hasThread && (+ <span className="text-xs text-gray-500">{threadMessages.length} messages</span>+ )}+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <button onClick={() => setShowReply(!showReply)} className="p-1.5 text-port-accent hover:bg-port-accent/10 rounded transition-colors" title="Reply"><Reply size={14} /></button>+ <button onClick={handleGenerateReply} disabled={generating} className="p-1.5 text-purple-400 hover:bg-purple-500/10 rounded transition-colors disabled:opacity-50" title="AI Reply"><Sparkles size={14} className={generating ? 'animate-pulse' : ''} /></button>+ <button onClick={handleRefresh} disabled={refreshing} className="p-1.5 text-port-accent hover:bg-port-accent/10 rounded transition-colors disabled:opacity-50" title="Refresh"><RefreshCw size={14} className={refreshing ? 'animate-spin' : ''} /></button>+ <span className="w-px h-4 bg-port-border mx-0.5" />+ <button onClick={() => handleAction('archive')} disabled={!!actioning} className="p-1.5 text-port-warning hover:bg-port-warning/10 rounded transition-colors disabled:opacity-50" title="Archive"><Archive size={14} /></button>+ <button onClick={() => handleAction('delete')} disabled={!!actioning} className="p-1.5 text-port-error hover:bg-port-error/10 rounded transition-colors disabled:opacity-50" title="Delete"><Trash2 size={14} /></button>+ </div></div>+ {/* Reply composer */}+ {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(''); setGeneratedDraftId(null); }}+ 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>+ )}++ {/* Message body / thread */}{threadLoading ? (<div className="text-sm text-gray-500 animate-pulse">Loading conversation...</div>) : (@@ -129,8 +227,12 @@ export default function MessageDetail({ message, accounts, onBack }) {To: {msg.to.map(t => typeof t === 'string' ? t : t.email || t).join(', ')}</div>)}- <div className="pt-2 border-t border-port-border text-sm text-gray-300 whitespace-pre-wrap">- {msg.bodyText || '(no content)'}+ <div className="pt-2 border-t border-port-border text-sm text-gray-300">+ {msg.bodyHtml ? (+ <SafeHtmlBody html={msg.bodyHtml} />+ ) : (+ <div className="whitespace-pre-wrap">{msg.bodyText || '(no content)'}</div>+ )}</div>{!msg.bodyFull && msg.bodyText && (<div className="text-xs text-gray-600 italic">Preview only — re-sync for full content</div>@@ -139,57 +241,6 @@ export default function MessageDetail({ message, accounts, onBack }) {))}</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>- <button- onClick={handleRefresh}- disabled={refreshing}- 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 disabled:opacity-50"- >- <RefreshCw size={16} className={refreshing ? 'animate-spin' : ''} />- {refreshing ? 'Fetching...' : 'Refresh'}- </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(''); setGeneratedDraftId(null); }}- 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/server/services/googleAuth.js b/server/services/googleAuth.jsindex f593cfeb00..28669bcdf1 100644--- a/server/services/googleAuth.js+++ b/server/services/googleAuth.js@@ -8,8 +8,7 @@ const CREDENTIALS_FILE = join(AUTH_DIR, 'credentials.json');const TOKENS_FILE = join(AUTH_DIR, 'tokens.json');const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly',- 'https://www.googleapis.com/auth/gmail.readonly',- 'https://www.googleapis.com/auth/gmail.send'+ 'https://www.googleapis.com/auth/gmail.modify'];export const OAUTH_REDIRECT_URI = `http://localhost:${process.env.PORT || 5555}/api/calendar/google/oauth/callback`;diff --git a/server/services/messageActions.js b/server/services/messageActions.jsindex f250e777c4..7a25825c1e 100644--- a/server/services/messageActions.js+++ b/server/services/messageActions.js@@ -84,17 +84,17 @@ export async function executeAction(accountId, messageId, action) {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);-- console.log(`📧 ${action} message "${message.subject}" via ${account.type} browser`);-- if (account.type === 'outlook') {+ // Gmail: use API directly instead of browser automation+ if (account.type === 'gmail' && message.apiId) {+ await executeGmailApiAction(message, action);+ } else if (account.type === 'outlook') {+ const page = await ensureProviderPage(account.type);+ console.log(`📧 ${action} message "${message.subject}" via ${account.type} browser`);await executeOutlookAction(page, message.subject || '', action);- } else {+ } else if (account.type === 'gmail') {+ // Fallback to browser if no apiId+ const page = await ensureProviderPage(account.type);+ console.log(`📧 ${action} message "${message.subject}" via gmail browser`);const script = buildGmailActionScript((message.subject || '').replace(/'/g, "\\'").replace(/\n/g, ' '), action);const result = await evaluateOnPage(page, script);if (!result || result.error) {@@ -104,6 +104,8 @@ export async function executeAction(accountId, messageId, action) {throw new Error(result?.error || `${action} failed`);}}+ } else {+ throw new Error(`${action} not supported for ${account.type}`);}// Record triage correction if user chose differently than the AI@@ -123,6 +125,32 @@ export async function executeAction(accountId, messageId, action) {return { success: true, action, messageId };}+/**+ * Execute archive/delete on Gmail via the Google API.+ * Archive = remove INBOX label. Delete = move to trash.+ */+async function executeGmailApiAction(message, action) {+ const { google } = await import('googleapis');+ const { getAuthenticatedClient } = await import('./googleAuth.js');++ const auth = await getAuthenticatedClient();+ if (!auth) throw new Error('Google OAuth not configured');++ const gmail = google.gmail({ version: 'v1', auth });++ if (action === 'delete') {+ await gmail.users.messages.trash({ userId: 'me', id: message.apiId });+ console.log(`📧 Gmail API: trashed "${message.subject}"`);+ } else if (action === 'archive') {+ await gmail.users.messages.modify({+ userId: 'me',+ id: message.apiId,+ requestBody: { removeLabelIds: ['INBOX'] }+ });+ console.log(`📧 Gmail API: archived "${message.subject}"`);+ }+}+/*** Execute archive/delete on Outlook via CDP: find+click message, then send key via protocol.*/diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex 553683f5ff..456927f16b 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -24,42 +24,77 @@ function decodeBase64Url(str) {}/**- * Extract plain text body from Gmail message payload.- * Walks multipart structure looking for text/plain, falls back to text/html.+ * Convert HTML to readable plain text by stripping style/script/head blocks, then tags.+ */+function htmlToText(html) {+ return html+ .replace(/<head\b[^>]*>[\s\S]*?<\/head>/gi, '')+ .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '')+ .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')+ .replace(/<br\s*\/?>/gi, '\n')+ .replace(/<\/p>/gi, '\n\n')+ .replace(/<\/div>/gi, '\n')+ .replace(/<\/tr>/gi, '\n')+ .replace(/<\/li>/gi, '\n')+ .replace(/<[^>]*>/g, '')+ .replace(/ /g, ' ')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, "'")+ .replace(/‌/g, '')+ .replace(/\n{3,}/g, '\n\n')+ .replace(/[ \t]+/g, ' ')+ .trim();+}++/**+ * Extract text and HTML body from Gmail message payload.+ * Returns { text, html } — prefers text/plain for text, keeps raw HTML separately.*/function extractBody(payload) {- if (!payload) return '';+ if (!payload) return { text: '', html: '' };// Simple message with body data directlyif (payload.body?.data) {- return decodeBase64Url(payload.body.data);+ const content = decodeBase64Url(payload.body.data);+ const isHtml = payload.mimeType === 'text/html';+ return {+ text: isHtml ? htmlToText(content) : content,+ html: isHtml ? content : ''+ };}- // Multipart — search parts recursively+ // Multipart — collect both text/plain and text/htmlif (payload.parts) {- // Prefer text/plain+ let text = '';+ let html = '';+for (const part of payload.parts) {- if (part.mimeType === 'text/plain' && part.body?.data) {- return decodeBase64Url(part.body.data);+ if (part.mimeType === 'text/plain' && part.body?.data && !text) {+ text = decodeBase64Url(part.body.data);}- }- // Fall back to text/html (strip tags for plain text)- for (const part of payload.parts) {- if (part.mimeType === 'text/html' && part.body?.data) {- const html = decodeBase64Url(part.body.data);- return html.replace(/<[^>]*>/g, '').replace(/ /g, ' ').replace(/\s+/g, ' ').trim();+ if (part.mimeType === 'text/html' && part.body?.data && !html) {+ html = decodeBase64Url(part.body.data);}- }- // Recurse into nested multipart- for (const part of payload.parts) {- if (part.parts) {+ // Recurse into nested multipart+ if (part.parts && !text && !html) {const nested = extractBody(part);- if (nested) return nested;+ if (nested.text) text = nested.text;+ if (nested.html) html = nested.html;}}++ // If no plain text but have HTML, derive text from HTML+ if (!text && html) {+ text = htmlToText(html);+ }++ return { text, html };}- return '';+ return { text: '', html: '' };}/**@@ -147,7 +182,7 @@ export async function syncGmail(account, cache, io, options = {}) {const headers = data.payload?.headers || [];const from = parseSender(getHeader(headers, 'From'));const labelIds = data.labelIds || [];- const bodyText = extractBody(data.payload);+ const body = extractBody(data.payload);messages.push({id: uuidv4(),@@ -159,8 +194,9 @@ export async function syncGmail(account, cache, io, options = {}) {to: parseRecipients(getHeader(headers, 'To')),cc: parseRecipients(getHeader(headers, 'Cc')),subject: getHeader(headers, 'Subject'),- bodyText,- bodyFull: !!bodyText,+ bodyText: body.text,+ bodyHtml: body.html || undefined,+ bodyFull: !!(body.text || body.html),date: data.internalDate ? new Date(parseInt(data.internalDate)).toISOString() : new Date().toISOString(),isRead: !labelIds.includes('UNREAD'),isUnread: labelIds.includes('UNREAD'),diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex a39566ce6e..63ae2d394e 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -169,6 +169,7 @@ export async function syncAccount(accountId, io, options = {}) {if (msg.bodyFull && msg.bodyText) {existing.bodyText = msg.bodyText;existing.bodyFull = true;+ if (msg.bodyHtml) existing.bodyHtml = msg.bodyHtml;}// Set threadId if newly availableif (msg.threadId && !existing.threadId) existing.threadId = msg.threadId;