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: Gmail API sync and send via Google OAuth (M50 P7)

Adam Eivy083a3b793a9f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index df0f2a6c36..c2018b5f31 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +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.
- **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/PLAN.md b/PLAN.md
index 74faa3a3d0..9c6abe115d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -64,7 +64,9 @@ See [GOALS.md](./GOALS.md) for project goals and direction.
### Planned
-- [ ] **M50 P1-P4**: Email Management - Gmail + Outlook integration, AI categorization and priority extraction, Digital Twin voice drafting, review-before-send outbox, Brain knowledge capture
+- [x] **M50 P1-P6**: Email Management - Outlook API+Playwright sync, AI triage with security hardening, draft generation, thread capture, per-action models, full Messages UI (Inbox/Drafts/Sync/Config)
+- [x] **M50 P7**: Email Management - Gmail API sync (same OAuth as Calendar), full body extraction, thread grouping, send via Gmail API
+- [ ] **M50 P8-P9**: Email Management - Digital Twin voice drafting, CoS automation & rules, auto-send with AI review gate
- [ ] **M34 P5-P7**: Digital Twin - Multi-modal capture, advanced testing, personas
- [ ] **M42 P5**: Unified Digital Twin Identity System - Cross-Insights Engine. See [Identity System](./docs/features/identity-system.md)
- [x] **M56**: Telegram Bot Integration - External notification channel via Telegram bot. ChatId allowlisting, notification forwarding with rate limiting and type filtering, conversational commands (/status, /goals, /agents, /checkin, /help), goal check-in persistence. Replaces M47.
@@ -132,17 +134,17 @@ Extends the existing goal system in `server/services/identity.js` and `data/digi
### M50: Messages (Email Management)
-Multi-provider email integration — Gmail via MCP, Outlook/Teams via CDP browser automation (Playwright). Unified Messages page with Inbox, Drafts, Sync, and Config sub-pages.
+Multi-provider email integration — Gmail via Google API (shared OAuth with Calendar), Outlook/Teams via CDP browser automation (Playwright). Unified Messages page with Inbox, Drafts, Sync, and Config sub-pages.
Always review before send — AI-generated drafts go to an outbox queue. The user reviews, edits, and approves each response before it's sent. No auto-send.
-**Completed:** P1-P6.5 (Email sync, AI triage, reply generation, thread capture, config, per-action models, prompt injection hardening, per-message re-fetch). See git history for details.
+**Completed:** P1-P7 (Email sync, AI triage, reply generation, thread capture, config, per-action models, prompt injection hardening, per-message re-fetch, Gmail API sync+send). See git history for details.
**Remaining:**
-- [ ] **P7: Digital Twin voice drafting** — Draft responses using Digital Twin voice/style (reads COMMUNICATION.md, PERSONALITY.md, VALUES.md + recent thread context)
-- [ ] **P8: CoS Automation & Rules** — Automated classification on new emails via CoS job, rule-based pre-filtering, email-to-task pipeline, priority email notifications
-- [ ] **P9: Auto-Send with AI Review Gate** — Remove human-in-the-loop for trusted accounts. Before auto-sending, a second LLM call reviews the draft against the original email for: prompt injection artifacts, off-topic content, tone/identity drift, leaked system instructions. Configurable per-account trust level (manual → review-assisted → auto-send). See [Messages Security](./docs/features/messages-security.md) for threat model.
+- [ ] **P8: Digital Twin voice drafting** — Draft responses using Digital Twin voice/style (reads COMMUNICATION.md, PERSONALITY.md, VALUES.md + recent thread context)
+- [ ] **P9: CoS Automation & Rules** — Automated classification on new emails via CoS job, rule-based pre-filtering, email-to-task pipeline, priority email notifications
+- [ ] **P10: Auto-Send with AI Review Gate** — Remove human-in-the-loop for trusted accounts. Before auto-sending, a second LLM call reviews the draft against the original email for: prompt injection artifacts, off-topic content, tone/identity drift, leaked system instructions. Configurable per-account trust level (manual → review-assisted → auto-send). See [Messages Security](./docs/features/messages-security.md) for threat model.
**Data:** `data/messages/accounts.json`, `data/messages/cache/{accountId}.json`, `data/messages/selectors.json`, `settings.json` (messages key for AI config + templates)
diff --git a/client/src/components/messages/ConfigTab.jsx b/client/src/components/messages/ConfigTab.jsx
index ffdb87775f..8260123a6c 100644
--- a/client/src/components/messages/ConfigTab.jsx
+++ b/client/src/components/messages/ConfigTab.jsx
@@ -1,12 +1,12 @@
import { useState, useEffect, useCallback } from 'react';
-import { Plus, Trash2, RefreshCw, Mail, Globe, MessageSquare, Save } from 'lucide-react';
+import { Plus, Trash2, RefreshCw, Mail, Globe, MessageSquare, Save, AlertTriangle, ExternalLink } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../services/api';
import ProviderModelSelector from '../ProviderModelSelector';
import useProviderModels from '../../hooks/useProviderModels';
const TYPE_ICONS = { gmail: Mail, outlook: Globe, teams: MessageSquare };
-const TYPE_LABELS = { gmail: 'Gmail (MCP)', outlook: 'Outlook (Playwright)', teams: 'Teams (Playwright)' };
+const TYPE_LABELS = { gmail: 'Gmail (API)', outlook: 'Outlook (Playwright)', teams: 'Teams (Playwright)' };
const DEFAULT_REPLY_TEMPLATE = `You are a professional email assistant. Draft a reply to the following email.
@@ -42,6 +42,10 @@ export default function ConfigTab({ accounts, setAccounts }) {
const [clearingCache, setClearingCache] = useState(null);
const [confirmClear, setConfirmClear] = useState(null);
+ // Google OAuth status for Gmail accounts
+ const [googleAuth, setGoogleAuth] = useState(null);
+ const [reauthorizing, setReauthorizing] = useState(false);
+
// AI config
const [config, setConfig] = useState(null);
const [configLoading, setConfigLoading] = useState(true);
@@ -74,6 +78,28 @@ export default function ConfigTab({ accounts, setAccounts }) {
useEffect(() => { loadConfig(); }, [loadConfig]);
+ // Check Google OAuth status when Gmail accounts exist
+ const hasGmailAccount = accounts.some(a => a.type === 'gmail');
+ useEffect(() => {
+ if (hasGmailAccount) {
+ api.getGoogleAuthStatus().then(setGoogleAuth).catch(() => {});
+ }
+ }, [hasGmailAccount]);
+
+ const handleReauthorize = () => {
+ setReauthorizing(true);
+ api.getGoogleAuthUrl()
+ .then(({ url }) => { window.open(url, '_blank'); })
+ .catch(() => toast.error('Failed to get auth URL'))
+ .finally(() => setReauthorizing(false));
+ };
+
+ const handleEnableGmailApi = () => {
+ api.enableGmailApi()
+ .then(r => toast.success(r.message))
+ .catch(() => toast.error('Failed to open Gmail API page'));
+ };
+
const handleSaveConfig = async () => {
const patch = {
messages: {
@@ -165,69 +191,6 @@ export default function ConfigTab({ accounts, setAccounts }) {
return (
<div className="space-y-8">
- {/* AI Provider & Model */}
- <section>
- <h2 className="text-lg font-semibold text-white mb-3">AI Provider & Model</h2>
- <p className="text-sm text-gray-500 mb-3">
- Configure separate AI providers for email triage (classification) and reply generation.
- </p>
- <div className="space-y-3">
- {renderProviderSection(
- 'Triage',
- 'Classifies emails as reply/archive/delete/review with priority. A fast, cheap model works well here.',
- triage
- )}
- {renderProviderSection(
- 'Reply Generation',
- 'Generates draft email replies. A more capable model produces better responses.',
- reply
- )}
- </div>
- </section>
-
- {/* Prompt Templates */}
- <section>
- <h2 className="text-lg font-semibold text-white mb-3">Prompt Templates</h2>
- <p className="text-sm text-gray-500 mb-3">
- Templates used when generating AI draft replies. Use {'{{variable}}'} syntax for substitution.
- Available: {'{{from}}'}, {'{{subject}}'}, {'{{body}}'}, {'{{instructions}}'}.
- </p>
- {configLoading ? (
- <RefreshCw size={16} className="text-port-accent animate-spin" />
- ) : (
- <div className="space-y-4">
- <div className="p-4 bg-port-card rounded-lg border border-port-border">
- <label className="block text-sm font-medium text-gray-300 mb-2">Reply Template</label>
- <textarea
- value={config.replyTemplate}
- onChange={(e) => updateTemplate('replyTemplate', e.target.value)}
- rows={8}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white font-mono placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y"
- />
- </div>
- <div className="p-4 bg-port-card rounded-lg border border-port-border">
- <label className="block text-sm font-medium text-gray-300 mb-2">Forward Template</label>
- <textarea
- value={config.forwardTemplate}
- onChange={(e) => updateTemplate('forwardTemplate', e.target.value)}
- rows={6}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white font-mono placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y"
- />
- </div>
- <div className="flex items-center gap-3">
- <button
- onClick={handleSaveConfig}
- disabled={!configDirty}
- 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 disabled:opacity-50"
- >
- <Save size={14} /> Save Config
- </button>
- {configDirty && <span className="text-xs text-port-warning">Unsaved changes</span>}
- </div>
- </div>
- )}
- </section>
-
{/* Accounts */}
<section>
<div className="flex items-center justify-between mb-3">
@@ -241,6 +204,57 @@ export default function ConfigTab({ accounts, setAccounts }) {
</button>
</div>
+ {hasGmailAccount && (
+ <div className="p-4 mb-4 bg-port-card border border-port-border rounded-lg space-y-3">
+ <h3 className="text-sm font-medium text-white">Gmail Setup</h3>
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-sm">
+ <span className={`w-2 h-2 rounded-full ${googleAuth?.hasTokens ? 'bg-port-success' : 'bg-port-error'}`} />
+ <span className="text-gray-300">Google OAuth</span>
+ </div>
+ {googleAuth?.hasTokens ? (
+ <button
+ onClick={handleReauthorize}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors"
+ title="Re-authorize to update permissions"
+ >
+ <RefreshCw size={12} />
+ Re-authorize
+ </button>
+ ) : (
+ <button
+ onClick={handleReauthorize}
+ disabled={reauthorizing}
+ className="flex items-center gap-1.5 px-3 py-1.5 bg-port-warning/20 text-port-warning text-xs rounded-lg hover:bg-port-warning/30 transition-colors disabled:opacity-50"
+ >
+ <ExternalLink size={14} />
+ Authorize
+ </button>
+ )}
+ </div>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-sm">
+ <span className="w-2 h-2 rounded-full bg-gray-500" />
+ <span className="text-gray-300">Gmail API enabled</span>
+ </div>
+ <button
+ onClick={handleEnableGmailApi}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors"
+ title="Open Google Cloud Console to enable Gmail API"
+ >
+ <ExternalLink size={12} />
+ Enable in Console
+ </button>
+ </div>
+ </div>
+ <p className="text-xs text-gray-500">
+ Gmail requires: 1) Gmail API enabled in Google Cloud Console, 2) Google OAuth authorized with Gmail scopes.
+ If sync fails with "API not enabled", click "Enable in Console" above.
+ </p>
+ </div>
+ )}
+
{showForm && (
<div className="p-4 bg-port-card rounded-lg border border-port-border space-y-3 mb-4">
<div>
@@ -260,7 +274,7 @@ export default function ConfigTab({ accounts, setAccounts }) {
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="gmail">Gmail (API)</option>
<option value="outlook">Outlook (Playwright)</option>
<option value="teams">Teams (Playwright)</option>
</select>
@@ -365,6 +379,69 @@ export default function ConfigTab({ accounts, setAccounts }) {
})}
</div>
</section>
+
+ {/* AI Provider & Model */}
+ <section>
+ <h2 className="text-lg font-semibold text-white mb-3">AI Provider & Model</h2>
+ <p className="text-sm text-gray-500 mb-3">
+ Configure separate AI providers for email triage (classification) and reply generation.
+ </p>
+ <div className="space-y-3">
+ {renderProviderSection(
+ 'Triage',
+ 'Classifies emails as reply/archive/delete/review with priority. A fast, cheap model works well here.',
+ triage
+ )}
+ {renderProviderSection(
+ 'Reply Generation',
+ 'Generates draft email replies. A more capable model produces better responses.',
+ reply
+ )}
+ </div>
+ </section>
+
+ {/* Prompt Templates */}
+ <section>
+ <h2 className="text-lg font-semibold text-white mb-3">Prompt Templates</h2>
+ <p className="text-sm text-gray-500 mb-3">
+ Templates used when generating AI draft replies. Use {'{{variable}}'} syntax for substitution.
+ Available: {'{{from}}'}, {'{{subject}}'}, {'{{body}}'}, {'{{instructions}}'}.
+ </p>
+ {configLoading ? (
+ <RefreshCw size={16} className="text-port-accent animate-spin" />
+ ) : (
+ <div className="space-y-4">
+ <div className="p-4 bg-port-card rounded-lg border border-port-border">
+ <label className="block text-sm font-medium text-gray-300 mb-2">Reply Template</label>
+ <textarea
+ value={config.replyTemplate}
+ onChange={(e) => updateTemplate('replyTemplate', e.target.value)}
+ rows={8}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white font-mono placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y"
+ />
+ </div>
+ <div className="p-4 bg-port-card rounded-lg border border-port-border">
+ <label className="block text-sm font-medium text-gray-300 mb-2">Forward Template</label>
+ <textarea
+ value={config.forwardTemplate}
+ onChange={(e) => updateTemplate('forwardTemplate', e.target.value)}
+ rows={6}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white font-mono placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y"
+ />
+ </div>
+ <div className="flex items-center gap-3">
+ <button
+ onClick={handleSaveConfig}
+ disabled={!configDirty}
+ 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 disabled:opacity-50"
+ >
+ <Save size={14} /> Save Config
+ </button>
+ {configDirty && <span className="text-xs text-port-warning">Unsaved changes</span>}
+ </div>
+ </div>
+ )}
+ </section>
</div>
);
}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index d8260900af..5e8984d1d1 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1730,6 +1730,7 @@ export const executeMessageAction = (accountId, messageId, 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' });
+export const enableGmailApi = () => request('/messages/gmail/enable-api', { method: 'POST' });
// Calendar
export const getCalendarAccounts = () => request('/calendar/accounts');
diff --git a/server/routes/messages.js b/server/routes/messages.js
index 247aceb5a1..22dff5e6fb 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -46,7 +46,7 @@ const createDraftSchema = z.object({
subject: z.string().optional().default(''),
body: z.string().optional().default(''),
generatedBy: z.enum(['ai', 'manual']).optional().default('manual'),
- sendVia: z.enum(['mcp', 'playwright']).optional()
+ sendVia: z.enum(['api', 'playwright']).optional()
});
const updateDraftSchema = z.object({
@@ -199,7 +199,7 @@ router.post('/drafts', asyncHandler(async (req, res) => {
const data = validateRequest(createDraftSchema, req.body);
const account = await messageAccounts.getAccount(data.accountId);
if (!account) return res.status(404).json({ error: 'Account not found' });
- const derivedSendVia = account.type === 'gmail' ? 'mcp' : 'playwright';
+ const derivedSendVia = account.type === 'gmail' ? 'api' : 'playwright';
if (data.sendVia && data.sendVia !== derivedSendVia) {
return res.status(400).json({ error: `sendVia "${data.sendVia}" conflicts with account type "${account.type}" (expected "${derivedSendVia}")` });
}
@@ -237,7 +237,7 @@ router.post('/drafts/generate', asyncHandler(async (req, res) => {
subject: '',
body: replyBody,
generatedBy: 'ai',
- sendVia: account.provider || (account.type === 'gmail' ? 'mcp' : 'playwright')
+ sendVia: account.type === 'gmail' ? 'api' : 'playwright'
});
req.app.get('io')?.emit('messages:draft:created', { draftId: draft.id });
res.status(201).json(draft);
@@ -290,12 +290,37 @@ router.post('/launch/:accountId', asyncHandler(async (req, res) => {
}
const account = await messageAccounts.getAccount(req.params.accountId);
if (!account) return res.status(404).json({ error: 'Account not found' });
- if (account.type === 'gmail') return res.status(400).json({ error: 'Gmail uses MCP, not browser automation' });
+ if (account.type === 'gmail') return res.status(400).json({ error: 'Gmail uses the Google API, not browser automation' });
const result = await launchProvider(account.type);
if (!result.success) return res.status(503).json({ error: result.error });
res.json(result);
}));
+// === Gmail API Enable Route ===
+router.post('/gmail/enable-api', asyncHandler(async (req, res) => {
+ const { getCredentials } = await import('../services/googleAuth.js');
+ const credentials = await getCredentials();
+
+ // Try to detect the project ID from the stored client ID
+ const clientId = credentials?.clientId || '';
+ const projectMatch = clientId.match(/^(\d+)-/);
+ const projectId = projectMatch ? projectMatch[1] : '';
+ const projectParam = projectId ? `?project=${projectId}` : '';
+ const enableUrl = `https://console.cloud.google.com/apis/library/gmail.googleapis.com${projectParam}`;
+
+ // Try to open in browser
+ const { navigateToUrl } = await import('../services/browserService.js');
+ const opened = await navigateToUrl(enableUrl).catch(() => null);
+
+ res.json({
+ success: !!opened,
+ url: enableUrl,
+ message: opened
+ ? 'Opened Gmail API page in browser. Click "Enable" if not already enabled.'
+ : 'Could not open browser. Visit the URL manually to enable the Gmail API.'
+ });
+}));
+
// === Selector Routes ===
router.get('/selectors', asyncHandler(async (req, res) => {
const selectors = await getSelectors();
diff --git a/server/routes/messages.test.js b/server/routes/messages.test.js
index 7ff0b2cae5..a35b27cba7 100644
--- a/server/routes/messages.test.js
+++ b/server/routes/messages.test.js
@@ -320,7 +320,7 @@ describe('Messages Routes', () => {
describe('POST /api/messages/drafts', () => {
it('should create a draft', async () => {
const draftData = { accountId: VALID_UUID, subject: 'Test', body: 'Hello' };
- const account = { id: VALID_UUID, type: 'gmail', provider: 'mcp' };
+ const account = { id: VALID_UUID, type: 'gmail', provider: 'api' };
const created = { id: DRAFT_UUID, ...draftData, status: 'draft' };
messageAccounts.getAccount.mockResolvedValue(account);
@@ -333,7 +333,7 @@ describe('Messages Routes', () => {
expect(response.status).toBe(201);
expect(response.body.id).toBe(DRAFT_UUID);
expect(messageDrafts.createDraft).toHaveBeenCalledWith(
- expect.objectContaining({ accountId: VALID_UUID, sendVia: 'mcp' })
+ expect.objectContaining({ accountId: VALID_UUID, sendVia: 'api' })
);
});
@@ -569,7 +569,7 @@ describe('Messages Routes', () => {
const response = await request(app).post(`/api/messages/launch/${VALID_UUID}`);
expect(response.status).toBe(400);
- expect(response.body.error).toBe('Gmail uses MCP, not browser automation');
+ expect(response.body.error).toBe('Gmail uses the Google API, not browser automation');
});
it('should return 503 if launch fails', async () => {
diff --git a/server/services/googleAuth.js b/server/services/googleAuth.js
index 4026fbcfd4..f593cfeb00 100644
--- a/server/services/googleAuth.js
+++ b/server/services/googleAuth.js
@@ -6,7 +6,11 @@ import { ensureDir, PATHS } from '../lib/fileUtils.js';
const AUTH_DIR = join(PATHS.calendar, 'google-auth');
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'];
+const SCOPES = [
+ 'https://www.googleapis.com/auth/calendar.readonly',
+ 'https://www.googleapis.com/auth/gmail.readonly',
+ 'https://www.googleapis.com/auth/gmail.send'
+];
export const OAUTH_REDIRECT_URI = `http://localhost:${process.env.PORT || 5555}/api/calendar/google/oauth/callback`;
let oAuth2Client = null;
diff --git a/server/services/googleOAuthAutoConfig.js b/server/services/googleOAuthAutoConfig.js
index 6a6eda2cdf..5468432179 100644
--- a/server/services/googleOAuthAutoConfig.js
+++ b/server/services/googleOAuthAutoConfig.js
@@ -139,25 +139,25 @@ export async function runAutomatedSetup(userEmail, io) {
const project = projectMatch ? projectMatch[1] : '';
const projectParam = project ? `?project=${project}` : '';
- // === Step 1: Enable Google Calendar API ===
- emit('enable-api', 'Enabling Google Calendar API...');
- page = await navAndWait(`https://console.cloud.google.com/apis/library/calendar-json.googleapis.com${projectParam}`, 5000);
- if (page) {
+ // === Step 1: Enable Google APIs ===
+ async function enableApi(name, librarySlug) {
+ emit('enable-api', `Enabling ${name}...`);
+ page = await navAndWait(`https://console.cloud.google.com/apis/library/${librarySlug}${projectParam}`, 5000);
+ if (!page) return;
const alreadyEnabled = await evaluateOnPage(page, `
document.body.innerText.includes('API enabled') || document.body.innerText.includes('MANAGE') || document.body.innerText.includes('Manage')
`);
if (!alreadyEnabled) {
- // Button text is "Enable" with aria-label "enable this API"
const clicked = await clickByText(page, ['enable this api', 'Enable']);
- if (clicked) {
- emit('enable-api', 'Calendar API enable clicked, waiting...');
- await sleep(6000);
- }
+ if (clicked) { emit('enable-api', `${name} enable clicked, waiting...`); await sleep(6000); }
} else {
- emit('enable-api', 'Calendar API already enabled');
+ emit('enable-api', `${name} already enabled`);
}
}
+ await enableApi('Google Calendar API', 'calendar-json.googleapis.com');
+ await enableApi('Gmail API', 'gmail.googleapis.com');
+
// === Step 2: Configure OAuth consent / Google Auth Platform ===
emit('consent', 'Configuring OAuth consent screen...');
page = await navAndWait(`https://console.cloud.google.com/auth/overview${projectParam}`, 5000);
diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.js
index eadab7a9ff..63d3a49b89 100644
--- a/server/services/messageAccounts.js
+++ b/server/services/messageAccounts.js
@@ -35,7 +35,7 @@ export async function createAccount(data) {
id,
name: data.name,
type: data.type, // gmail, outlook, teams
- provider: data.type === 'gmail' ? 'mcp' : 'playwright',
+ provider: data.type === 'gmail' ? 'api' : 'playwright',
email: data.email || '',
enabled: true,
syncConfig: {
diff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.js
index cd0be57766..29f728cf0a 100644
--- a/server/services/messageDrafts.js
+++ b/server/services/messageDrafts.js
@@ -43,7 +43,7 @@ export async function createDraft(data) {
body: data.body || '',
status: 'draft',
generatedBy: data.generatedBy || 'manual',
- sendVia: data.sendVia || 'mcp',
+ sendVia: data.sendVia || 'api',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.js
index 9ee83d524e..553683f5ff 100644
--- a/server/services/messageGmailSync.js
+++ b/server/services/messageGmailSync.js
@@ -1,21 +1,238 @@
/**
- * 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.
+ * Gmail API sync — fetches messages and sends drafts via the Google API.
+ * Uses the shared Google OAuth client from googleAuth.js (same credentials as Calendar).
*/
-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 { messages: [], status: 'not-configured' };
+
+import { google } from 'googleapis';
+import { v4 as uuidv4 } from 'uuid';
+import crypto from 'crypto';
+import { getAuthenticatedClient } from './googleAuth.js';
+
+function makeExternalId(gmailId) {
+ return 'api-gmail-' + crypto.createHash('md5').update(gmailId).digest('hex').slice(0, 12);
+}
+
+function getHeader(headers, name) {
+ return headers?.find(h => h.name.toLowerCase() === name.toLowerCase())?.value || '';
+}
+
+function decodeBase64Url(str) {
+ if (!str) return '';
+ let padded = str.replace(/-/g, '+').replace(/_/g, '/');
+ padded += '=='.slice(0, (4 - (padded.length % 4)) % 4);
+ return Buffer.from(padded, 'base64').toString('utf-8');
+}
+
+/**
+ * Extract plain text body from Gmail message payload.
+ * Walks multipart structure looking for text/plain, falls back to text/html.
+ */
+function extractBody(payload) {
+ if (!payload) return '';
+
+ // Simple message with body data directly
+ if (payload.body?.data) {
+ return decodeBase64Url(payload.body.data);
+ }
+
+ // Multipart — search parts recursively
+ if (payload.parts) {
+ // Prefer text/plain
+ for (const part of payload.parts) {
+ if (part.mimeType === 'text/plain' && part.body?.data) {
+ return 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(/&nbsp;/g, ' ').replace(/\s+/g, ' ').trim();
+ }
+ }
+ // Recurse into nested multipart
+ for (const part of payload.parts) {
+ if (part.parts) {
+ const nested = extractBody(part);
+ if (nested) return nested;
+ }
+ }
+ }
+
+ return '';
+}
+
+/**
+ * Parse recipient string "Name <email>" or just "email"
+ */
+function parseRecipients(headerValue) {
+ if (!headerValue) return [];
+ return headerValue.split(',').map(r => {
+ const match = r.trim().match(/<([^>]+)>/);
+ return match ? match[1] : r.trim();
+ }).filter(Boolean);
+}
+
+/**
+ * Parse sender into { name, email }
+ */
+function parseSender(fromHeader) {
+ if (!fromHeader) return { name: '', email: '' };
+ const match = fromHeader.match(/^(.*?)\s*<([^>]+)>$/);
+ if (match) return { name: match[1].replace(/^"|"$/g, '').trim(), email: match[2] };
+ return { name: '', email: fromHeader.trim() };
+}
+
+/**
+ * Sync Gmail messages via the Google API.
+ * @param {object} account - Account config
+ * @param {object} cache - Existing cache
+ * @param {object} io - Socket.IO instance
+ * @param {object} options - { mode: 'unread' | 'full' }
+ * @returns {{ messages, status, syncMethod }}
+ */
+export async function syncGmail(account, cache, io, options = {}) {
+ const mode = options.mode || 'unread';
+ const auth = await getAuthenticatedClient();
+
+ if (!auth) {
+ console.log(`📧 Gmail sync for ${account.email}: Google OAuth not configured`);
+ return { messages: [], status: 'not-configured' };
+ }
+
+ const gmail = google.gmail({ version: 'v1', auth });
+ const maxMessages = mode === 'full' ? 200 : 100;
+ const query = mode === 'unread' ? 'is:unread in:inbox' : 'in:inbox';
+
+ console.log(`📧 Gmail API sync (${mode}) for ${account.email}`);
+
+ // Step 1: List message IDs
+ const messageIds = [];
+ let pageToken = null;
+
+ do {
+ io?.emit('messages:sync:progress', { accountId: account.id, current: messageIds.length, total: maxMessages });
+
+ const listResult = await gmail.users.messages.list({
+ userId: 'me',
+ q: query,
+ maxResults: Math.min(100, maxMessages - messageIds.length),
+ ...(pageToken && { pageToken })
+ });
+
+ const items = listResult.data.messages || [];
+ messageIds.push(...items);
+ pageToken = listResult.data.nextPageToken;
+ } while (pageToken && messageIds.length < maxMessages);
+
+ console.log(`📧 Gmail: found ${messageIds.length} message IDs, fetching details`);
+
+ // Step 2: Fetch full message details in parallel batches
+ const messages = [];
+ const BATCH_SIZE = 10;
+
+ for (let i = 0; i < messageIds.length; i += BATCH_SIZE) {
+ io?.emit('messages:sync:progress', { accountId: account.id, current: i, total: messageIds.length });
+
+ const batch = messageIds.slice(i, i + BATCH_SIZE);
+ const results = await Promise.all(batch.map(({ id: gmailId }) =>
+ gmail.users.messages.get({ userId: 'me', id: gmailId, format: 'full' })
+ .catch(err => { console.log(`📧 Gmail: failed to fetch ${gmailId}: ${err.message}`); return null; })
+ ));
+
+ for (let j = 0; j < results.length; j++) {
+ if (!results[j]) continue;
+ const data = results[j].data;
+ const { id: gmailId, threadId: gmailThreadId } = batch[j];
+ const headers = data.payload?.headers || [];
+ const from = parseSender(getHeader(headers, 'From'));
+ const labelIds = data.labelIds || [];
+ const bodyText = extractBody(data.payload);
+
+ messages.push({
+ id: uuidv4(),
+ externalId: makeExternalId(gmailId),
+ apiId: gmailId,
+ conversationId: gmailThreadId || null,
+ threadId: gmailThreadId ? `conv-${crypto.createHash('md5').update(gmailThreadId).digest('hex').slice(0, 12)}` : null,
+ from,
+ to: parseRecipients(getHeader(headers, 'To')),
+ cc: parseRecipients(getHeader(headers, 'Cc')),
+ subject: getHeader(headers, 'Subject'),
+ bodyText,
+ bodyFull: !!bodyText,
+ date: data.internalDate ? new Date(parseInt(data.internalDate)).toISOString() : new Date().toISOString(),
+ isRead: !labelIds.includes('UNREAD'),
+ isUnread: labelIds.includes('UNREAD'),
+ isPinned: false,
+ isFlagged: labelIds.includes('STARRED'),
+ isReplied: false,
+ hasMeetingInvite: (getHeader(headers, 'Subject') || '').toLowerCase().includes('invitation'),
+ importance: labelIds.includes('IMPORTANT') ? 'High' : 'Normal',
+ categories: labelIds.filter(l => !['INBOX', 'UNREAD', 'STARRED', 'IMPORTANT', 'SENT', 'DRAFT'].includes(l)),
+ labels: labelIds,
+ source: 'gmail',
+ syncMethod: 'api',
+ syncedAt: new Date().toISOString()
+ });
+ }
+ }
+
+ if (io && messages.length > 0) {
+ io.emit('messages:sync:message', { accountId: account.id, messages });
+ }
+
+ console.log(`📧 Gmail API sync complete: ${messages.length} messages fetched`);
+ return { messages, status: 'success', syncMethod: 'api' };
}
/**
- * Send email via Gmail MCP
+ * Send email via Gmail API.
+ * @param {object} account - Account config
+ * @param {object} draft - Draft with to, cc, subject, body
+ * @returns {{ success: boolean, error?: string }}
*/
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', status: 501, code: 'GMAIL_MCP_NOT_CONFIGURED' };
+ const auth = await getAuthenticatedClient();
+ if (!auth) {
+ return { success: false, error: 'Google OAuth not configured', status: 502, code: 'GMAIL_NOT_CONFIGURED' };
+ }
+
+ const gmail = google.gmail({ version: 'v1', auth });
+
+ // Build RFC 2822 message
+ const toLine = Array.isArray(draft.to) ? draft.to.join(', ') : draft.to;
+ const lines = [
+ `To: ${toLine}`,
+ `Subject: ${draft.subject || ''}`,
+ 'Content-Type: text/plain; charset=utf-8',
+ 'MIME-Version: 1.0'
+ ];
+ if (draft.cc) {
+ const ccLine = Array.isArray(draft.cc) ? draft.cc.join(', ') : draft.cc;
+ lines.push(`Cc: ${ccLine}`);
+ }
+ if (draft.replyToMessageId && draft.threadId) {
+ // For replies, set In-Reply-To and References headers
+ lines.push(`In-Reply-To: ${draft.replyToMessageId}`);
+ lines.push(`References: ${draft.replyToMessageId}`);
+ }
+ lines.push('', draft.body || '');
+
+ const raw = Buffer.from(lines.join('\r\n')).toString('base64url');
+
+ const result = await gmail.users.messages.send({
+ userId: 'me',
+ requestBody: { raw }
+ }).catch(err => {
+ console.error(`📧 Gmail send failed: ${err.message}`);
+ return null;
+ });
+
+ if (!result) {
+ return { success: false, error: 'Gmail API send failed', status: 502, code: 'GMAIL_SEND_FAILED' };
+ }
+
+ console.log(`📧 Gmail sent: ${draft.subject} (id: ${result.data?.id})`);
+ return { success: true };
}
diff --git a/server/services/messageSender.js b/server/services/messageSender.js
index 6c224aa302..84599cbbb6 100644
--- a/server/services/messageSender.js
+++ b/server/services/messageSender.js
@@ -2,7 +2,7 @@ import { getDraft, updateDraft } from './messageDrafts.js';
import { getAccount } from './messageAccounts.js';
const ACCOUNT_TYPE_TO_SEND_VIA = {
- gmail: 'mcp',
+ gmail: 'api',
outlook: 'playwright',
teams: 'playwright'
};
@@ -24,7 +24,7 @@ export async function sendDraft(draftId, io) {
console.log(`📧 Sending draft "${draft.subject}" via ${draft.sendVia}`);
const dispatch = async () => {
- if (draft.sendVia === 'mcp') {
+ if (draft.sendVia === 'api') {
const { sendGmail } = await import('./messageGmailSync.js');
return sendGmail(account, draft);
}
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 0788980fbc..a39566ce6e 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -125,7 +125,7 @@ export async function syncAccount(accountId, io, options = {}) {
let providerResult;
if (account.type === 'gmail') {
const { syncGmail } = await import('./messageGmailSync.js');
- providerResult = await syncGmail(account, cache, io);
+ providerResult = await syncGmail(account, cache, io, { mode });
} else if (account.type === 'outlook') {
// Try API sync first (fast), fall back to Playwright (slow)
const { syncOutlookApi } = await import('./messageApiSync.js');