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
address review: schema consistency, UUID validation, sync:failed listener, tests, quality fixes
Adam Eivybaf6b232d832
diff --git a/client/src/components/messages/DraftsTab.jsx b/client/src/components/messages/DraftsTab.jsxindex b51bc65edb..57786b7e9d 100644--- a/client/src/components/messages/DraftsTab.jsx+++ b/client/src/components/messages/DraftsTab.jsx@@ -19,7 +19,8 @@ export default function DraftsTab({ accounts }) {}, [fetchDrafts]);const handleApprove = async (id) => {- await api.approveMessageDraft(id);+ const result = await api.approveMessageDraft(id).catch(() => null);+ if (!result) return;setDrafts(prev => prev.map(d => d.id === id ? { ...d, status: 'approved' } : d));toast.success('Draft approved');};@@ -33,7 +34,8 @@ export default function DraftsTab({ accounts }) {};const handleDelete = async (id) => {- await api.deleteMessageDraft(id);+ const ok = await api.deleteMessageDraft(id).then(() => true).catch(() => false);+ if (!ok) return;setDrafts(prev => prev.filter(d => d.id !== id));toast.success('Draft deleted');};diff --git a/client/src/components/messages/MessageDetail.jsx b/client/src/components/messages/MessageDetail.jsxindex 6fe01580f9..dc12274c15 100644--- a/client/src/components/messages/MessageDetail.jsx+++ b/client/src/components/messages/MessageDetail.jsx@@ -30,7 +30,7 @@ export default function MessageDetail({ message, accounts, onBack }) {const handleCreateDraft = async () => {if (!account) return toast.error('No account available');- await api.createMessageDraft({+ const result = await api.createMessageDraft({accountId: account.id,replyToMessageId: message.id,threadId: message.threadId,@@ -39,7 +39,8 @@ export default function MessageDetail({ message, accounts, onBack }) {body: replyBody,generatedBy: 'manual',sendVia: account.provider- });+ }).catch(() => null);+ if (!result) return;toast.success('Draft saved');setShowReply(false);setReplyBody('');diff --git a/client/src/components/messages/SyncTab.jsx b/client/src/components/messages/SyncTab.jsxindex eb2e05785d..610797f8e1 100644--- a/client/src/components/messages/SyncTab.jsx+++ b/client/src/components/messages/SyncTab.jsx@@ -30,15 +30,21 @@ export default function SyncTab({ accounts, onRefresh }) {setSyncing(prev => ({ ...prev, [accountId]: 'auth-required' }));toast('Login required -- open Browser page to authenticate', { icon: '\uD83D\uDD10' });};+ const onSyncFailed = ({ accountId, error }) => {+ setSyncing(prev => ({ ...prev, [accountId]: null }));+ toast.error(`Sync failed: ${error ?? 'unknown error'}`);+ };socket.on('messages:sync:started', onSyncStarted);socket.on('messages:sync:completed', onSyncCompleted);socket.on('messages:sync:auth-required', onAuthRequired);+ socket.on('messages:sync:failed', onSyncFailed);return () => {socket.off('messages:sync:started', onSyncStarted);socket.off('messages:sync:completed', onSyncCompleted);socket.off('messages:sync:auth-required', onAuthRequired);+ socket.off('messages:sync:failed', onSyncFailed);};}, [fetchSelectors, onRefresh]);@@ -55,7 +61,8 @@ export default function SyncTab({ accounts, onRefresh }) {};const handleSaveSelectors = async (provider) => {- await api.updateMessageSelectors(provider, selectorForm);+ const result = await api.updateMessageSelectors(provider, selectorForm).catch(() => null);+ if (!result) return;toast.success(`${provider} selectors updated`);setEditingSelector(null);fetchSelectors();diff --git a/server/routes/messages.js b/server/routes/messages.jsindex 4c79c0758c..aac3dc01f6 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -23,7 +23,7 @@ const createAccountSchema = z.object({const updateAccountSchema = z.object({name: z.string().min(1).optional(),- email: z.string().email().optional(),+ email: z.union([z.string().email(), z.literal('')]).optional(),enabled: z.boolean().optional(),syncConfig: z.object({maxAge: z.string().optional(),@@ -103,6 +103,9 @@ router.delete('/accounts/:id', asyncHandler(async (req, res) => {// === Sync Routes ===router.post('/sync/:accountId', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.accountId).success) {+ return res.status(400).json({ error: 'Invalid account ID format' });+ }const io = req.app.get('io');const result = await messageSync.syncAccount(req.params.accountId, io);if (result.error) return res.status(404).json({ error: result.error });@@ -110,6 +113,9 @@ router.post('/sync/:accountId', asyncHandler(async (req, res) => {}));router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.accountId).success) {+ return res.status(400).json({ error: 'Invalid account ID format' });+ }const status = await messageSync.getSyncStatus(req.params.accountId);if (!status) return res.status(404).json({ error: 'Account not found' });res.json(status);@@ -174,6 +180,9 @@ router.post('/drafts/generate', asyncHandler(async (req, res) => {}));router.put('/drafts/:id', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.id).success) {+ return res.status(400).json({ error: 'Invalid draft ID format' });+ }const updates = updateDraftSchema.parse(req.body);const draft = await messageDrafts.updateDraft(req.params.id, updates);if (!draft) return res.status(404).json({ error: 'Draft not found' });@@ -181,12 +190,18 @@ router.put('/drafts/:id', asyncHandler(async (req, res) => {}));router.post('/drafts/:id/approve', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.id).success) {+ return res.status(400).json({ error: 'Invalid draft ID format' });+ }const draft = await messageDrafts.approveDraft(req.params.id);if (!draft) return res.status(404).json({ error: 'Draft not found' });res.json(draft);}));router.post('/drafts/:id/send', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.id).success) {+ return res.status(400).json({ error: 'Invalid draft ID format' });+ }const io = req.app.get('io');const result = await messageSender.sendDraft(req.params.id, io);if (!result.success) {@@ -197,6 +212,9 @@ router.post('/drafts/:id/send', asyncHandler(async (req, res) => {}));router.delete('/drafts/:id', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.id).success) {+ return res.status(400).json({ error: 'Invalid draft ID format' });+ }const deleted = await messageDrafts.deleteDraft(req.params.id);if (!deleted) return res.status(404).json({ error: 'Draft not found' });res.status(204).send();@@ -218,6 +236,9 @@ router.get('/:accountId/:messageId', asyncHandler(async (req, res) => {// === Browser Launch Route ===router.post('/launch/:accountId', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.accountId).success) {+ return res.status(400).json({ error: 'Invalid account ID format' });+ }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' });diff --git a/server/routes/messages.test.js b/server/routes/messages.test.jsnew file mode 100644index 0000000000..bd6c32af55--- /dev/null+++ b/server/routes/messages.test.js@@ -0,0 +1,604 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import request from 'supertest';+import messagesRoutes from './messages.js';++// Mock the services+vi.mock('../services/messageAccounts.js', () => ({+ listAccounts: vi.fn(),+ getAccount: vi.fn(),+ createAccount: vi.fn(),+ updateAccount: vi.fn(),+ deleteAccount: vi.fn(),+ updateSyncStatus: vi.fn()+}));++vi.mock('../services/messageSync.js', () => ({+ syncAccount: vi.fn(),+ getSyncStatus: vi.fn(),+ getMessages: vi.fn(),+ getMessage: vi.fn(),+ deleteCache: vi.fn()+}));++vi.mock('../services/messageDrafts.js', () => ({+ listDrafts: vi.fn(),+ createDraft: vi.fn(),+ updateDraft: vi.fn(),+ approveDraft: vi.fn(),+ deleteDraft: vi.fn(),+ deleteDraftsByAccountId: vi.fn()+}));++vi.mock('../services/messageSender.js', () => ({+ sendDraft: vi.fn()+}));++vi.mock('../services/messagePlaywrightSync.js', () => ({+ getSelectors: vi.fn(),+ updateSelectors: vi.fn(),+ testSelectors: vi.fn(),+ launchProvider: vi.fn()+}));++// Import mocked modules+import * as messageAccounts from '../services/messageAccounts.js';+import * as messageSync from '../services/messageSync.js';+import * as messageDrafts from '../services/messageDrafts.js';+import * as messageSender from '../services/messageSender.js';+import * as messagePlaywrightSync from '../services/messagePlaywrightSync.js';++const VALID_UUID = '11111111-1111-1111-1111-111111111111';+const VALID_UUID_2 = '22222222-2222-2222-2222-222222222222';+const DRAFT_UUID = '33333333-3333-3333-3333-333333333333';+const DRAFT_UUID_2 = '44444444-4444-4444-4444-444444444444';+const INVALID_UUID = 'not-a-uuid';++describe('Messages Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/messages', messagesRoutes);+ vi.clearAllMocks();+ });++ // === Account Routes ===++ describe('GET /api/messages/accounts', () => {+ it('should return list of accounts', async () => {+ const mockAccounts = [+ { id: VALID_UUID, name: 'Work Gmail', type: 'gmail' }+ ];+ messageAccounts.listAccounts.mockResolvedValue(mockAccounts);++ const response = await request(app).get('/api/messages/accounts');++ expect(response.status).toBe(200);+ expect(response.body).toEqual(mockAccounts);+ });++ it('should return empty array when no accounts exist', async () => {+ messageAccounts.listAccounts.mockResolvedValue([]);++ const response = await request(app).get('/api/messages/accounts');++ expect(response.status).toBe(200);+ expect(response.body).toHaveLength(0);+ });+ });++ describe('POST /api/messages/accounts', () => {+ it('should create a new account', async () => {+ const newAccount = { name: 'Work Gmail', type: 'gmail', email: '[email protected]' };+ const created = { id: VALID_UUID, ...newAccount, enabled: true };+ messageAccounts.createAccount.mockResolvedValue(created);++ const response = await request(app)+ .post('/api/messages/accounts')+ .send(newAccount);++ expect(response.status).toBe(201);+ expect(response.body.id).toBe(VALID_UUID);+ expect(messageAccounts.createAccount).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'Work Gmail', type: 'gmail' })+ );+ });++ it('should return 400 for missing name', async () => {+ const response = await request(app)+ .post('/api/messages/accounts')+ .send({ type: 'gmail' });++ expect(response.status).toBe(500); // Zod throws, no error middleware in test+ });++ it('should return 400 for invalid type', async () => {+ const response = await request(app)+ .post('/api/messages/accounts')+ .send({ name: 'Test', type: 'yahoo' });++ expect(response.status).toBe(500); // Zod throws, no error middleware in test+ });+ });++ describe('PUT /api/messages/accounts/:id', () => {+ it('should update an account', async () => {+ const updated = { id: VALID_UUID, name: 'Updated', type: 'gmail' };+ messageAccounts.updateAccount.mockResolvedValue(updated);++ const response = await request(app)+ .put(`/api/messages/accounts/${VALID_UUID}`)+ .send({ name: 'Updated' });++ expect(response.status).toBe(200);+ expect(response.body.name).toBe('Updated');+ expect(messageAccounts.updateAccount).toHaveBeenCalledWith(VALID_UUID, { name: 'Updated' });+ });++ it('should return 400 for invalid UUID', async () => {+ const response = await request(app)+ .put(`/api/messages/accounts/${INVALID_UUID}`)+ .send({ name: 'Updated' });++ expect(response.status).toBe(400);+ expect(response.body.error).toBe('Invalid account ID format');+ });++ it('should return 404 if account not found', async () => {+ messageAccounts.updateAccount.mockResolvedValue(null);++ const response = await request(app)+ .put(`/api/messages/accounts/${VALID_UUID}`)+ .send({ name: 'Updated' });++ expect(response.status).toBe(404);+ expect(response.body.error).toBe('Account not found');+ });+ });++ describe('DELETE /api/messages/accounts/:id', () => {+ it('should delete an account', async () => {+ messageAccounts.deleteAccount.mockResolvedValue(true);+ messageSync.deleteCache.mockResolvedValue();+ messageDrafts.deleteDraftsByAccountId.mockResolvedValue();++ const response = await request(app).delete(`/api/messages/accounts/${VALID_UUID}`);++ expect(response.status).toBe(204);+ expect(messageAccounts.deleteAccount).toHaveBeenCalledWith(VALID_UUID);+ expect(messageSync.deleteCache).toHaveBeenCalledWith(VALID_UUID);+ expect(messageDrafts.deleteDraftsByAccountId).toHaveBeenCalledWith(VALID_UUID);+ });++ it('should return 400 for invalid UUID', async () => {+ const response = await request(app).delete(`/api/messages/accounts/${INVALID_UUID}`);++ expect(response.status).toBe(400);+ expect(response.body.error).toBe('Invalid account ID format');+ });++ it('should return 404 if account not found', async () => {+ messageAccounts.deleteAccount.mockResolvedValue(false);++ const response = await request(app).delete(`/api/messages/accounts/${VALID_UUID}`);++ expect(response.status).toBe(404);+ expect(response.body.error).toBe('Account not found');+ });+ });++ // === Sync Routes ===++ describe('POST /api/messages/sync/:accountId', () => {+ it('should trigger sync for an account', async () => {+ messageSync.syncAccount.mockResolvedValue({ newMessages: 5, total: 100 });++ const response = await request(app).post(`/api/messages/sync/${VALID_UUID}`);++ expect(response.status).toBe(200);+ expect(response.body.newMessages).toBe(5);+ expect(messageSync.syncAccount).toHaveBeenCalledWith(VALID_UUID, undefined);+ });++ it('should return 400 for invalid UUID', async () => {+ const response = await request(app).post(`/api/messages/sync/${INVALID_UUID}`);++ expect(response.status).toBe(400);+ expect(response.body.error).toBe('Invalid account ID format');+ });++ it('should return 404 if account not found', async () => {+ messageSync.syncAccount.mockResolvedValue({ error: 'Account not found' });++ const response = await request(app).post(`/api/messages/sync/${VALID_UUID}`);++ expect(response.status).toBe(404);+ expect(response.body.error).toBe('Account not found');+ });+ });++ describe('GET /api/messages/sync/:accountId/status', () => {+ it('should return sync status', async () => {+ const status = { accountId: VALID_UUID, lastSyncAt: '2026-01-01T00:00:00Z', lastSyncStatus: 'success' };+ messageSync.getSyncStatus.mockResolvedValue(status);++ const response = await request(app).get(`/api/messages/sync/${VALID_UUID}/status`);++ expect(response.status).toBe(200);+ expect(response.body.lastSyncStatus).toBe('success');+ });++ it('should return 404 if account not found', async () => {+ messageSync.getSyncStatus.mockResolvedValue(null);++ const response = await request(app).get(`/api/messages/sync/${VALID_UUID}/status`);++ expect(response.status).toBe(404);+ });+ });++ // === Inbox Routes ===++ describe('GET /api/messages/inbox', () => {+ it('should return messages', async () => {+ const result = { messages: [{ id: 'msg-1', subject: 'Hello' }], total: 1 };+ messageSync.getMessages.mockResolvedValue(result);++ const response = await request(app).get('/api/messages/inbox');++ expect(response.status).toBe(200);+ expect(response.body.messages).toHaveLength(1);+ expect(response.body.total).toBe(1);+ });++ it('should pass accountId filter', async () => {+ messageSync.getMessages.mockResolvedValue({ messages: [], total: 0 });++ await request(app).get(`/api/messages/inbox?accountId=${VALID_UUID}`);++ expect(messageSync.getMessages).toHaveBeenCalledWith(+ expect.objectContaining({ accountId: VALID_UUID })+ );+ });++ it('should return 400 for invalid accountId format', async () => {+ const response = await request(app).get(`/api/messages/inbox?accountId=${INVALID_UUID}`);++ expect(response.status).toBe(400);+ expect(response.body.error).toBe('Invalid accountId format');+ });++ it('should clamp limit to 100', async () => {+ messageSync.getMessages.mockResolvedValue({ messages: [], total: 0 });++ await request(app).get('/api/messages/inbox?limit=999');++ expect(messageSync.getMessages).toHaveBeenCalledWith(+ expect.objectContaining({ limit: 100 })+ );+ });++ it('should default limit to 50 for invalid values', async () => {+ messageSync.getMessages.mockResolvedValue({ messages: [], total: 0 });++ await request(app).get('/api/messages/inbox?limit=abc');++ expect(messageSync.getMessages).toHaveBeenCalledWith(+ expect.objectContaining({ limit: 50 })+ );+ });+ });++ // === Draft Routes ===++ describe('GET /api/messages/drafts', () => {+ it('should return list of drafts', async () => {+ const drafts = [{ id: DRAFT_UUID, subject: 'Re: Hello', status: 'draft' }];+ messageDrafts.listDrafts.mockResolvedValue(drafts);++ const response = await request(app).get('/api/messages/drafts');++ expect(response.status).toBe(200);+ expect(response.body).toHaveLength(1);+ });++ it('should pass accountId and status filters', async () => {+ messageDrafts.listDrafts.mockResolvedValue([]);++ await request(app).get(`/api/messages/drafts?accountId=${VALID_UUID}&status=draft`);++ expect(messageDrafts.listDrafts).toHaveBeenCalledWith({+ accountId: VALID_UUID,+ status: 'draft'+ });+ });+ });++ 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 created = { id: DRAFT_UUID, ...draftData, status: 'draft' };++ messageAccounts.getAccount.mockResolvedValue(account);+ messageDrafts.createDraft.mockResolvedValue(created);++ const response = await request(app)+ .post('/api/messages/drafts')+ .send(draftData);++ expect(response.status).toBe(201);+ expect(response.body.id).toBe(DRAFT_UUID);+ expect(messageDrafts.createDraft).toHaveBeenCalledWith(+ expect.objectContaining({ accountId: VALID_UUID, sendVia: 'mcp' })+ );+ });++ it('should return 404 if account not found', async () => {+ messageAccounts.getAccount.mockResolvedValue(null);++ const response = await request(app)+ .post('/api/messages/drafts')+ .send({ accountId: VALID_UUID });++ expect(response.status).toBe(404);+ expect(response.body.error).toBe('Account not found');+ });++ it('should reject invalid accountId format', async () => {+ const response = await request(app)+ .post('/api/messages/drafts')+ .send({ accountId: INVALID_UUID });++ // Zod validation failure for uuid+ expect(response.status).toBe(500);+ });+ });++ describe('POST /api/messages/drafts/generate', () => {+ it('should generate a draft', async () => {+ const account = { id: VALID_UUID, type: 'outlook', provider: 'playwright' };+ const created = { id: DRAFT_UUID, generatedBy: 'ai', status: 'draft' };++ messageAccounts.getAccount.mockResolvedValue(account);+ messageDrafts.createDraft.mockResolvedValue(created);++ const response = await request(app)+ .post('/api/messages/drafts/generate')+ .send({ accountId: VALID_UUID, context: 'meeting follow-up' });++ expect(response.status).toBe(201);+ expect(response.body.generatedBy).toBe('ai');+ });++ it('should return 404 if account not found', async () => {+ messageAccounts.getAccount.mockResolvedValue(null);++ const response = await request(app)+ .post('/api/messages/drafts/generate')+ .send({ accountId: VALID_UUID });++ expect(response.status).toBe(404);+ expect(response.body.error).toBe('Account not found');+ });+ });++ describe('PUT /api/messages/drafts/:id', () => {+ it('should update a draft', async () => {+ const updated = { id: DRAFT_UUID, subject: 'Updated', status: 'draft' };+ messageDrafts.updateDraft.mockResolvedValue(updated);++ const response = await request(app)+ .put(`/api/messages/drafts/${DRAFT_UUID}`)+ .send({ subject: 'Updated' });++ expect(response.status).toBe(200);+ expect(response.body.subject).toBe('Updated');+ });++ it('should return 404 if draft not found', async () => {+ messageDrafts.updateDraft.mockResolvedValue(null);++ const response = await request(app)+ .put(`/api/messages/drafts/${DRAFT_UUID_2}`)+ .send({ subject: 'Updated' });++ expect(response.status).toBe(404);+ expect(response.body.error).toBe('Draft not found');+ });+ });++ describe('POST /api/messages/drafts/:id/approve', () => {+ it('should approve a draft', async () => {+ const approved = { id: DRAFT_UUID, status: 'approved' };+ messageDrafts.approveDraft.mockResolvedValue(approved);++ const response = await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/approve`);++ expect(response.status).toBe(200);+ expect(response.body.status).toBe('approved');+ });++ it('should return 404 if draft not found', async () => {+ messageDrafts.approveDraft.mockResolvedValue(null);++ const response = await request(app).post(`/api/messages/drafts/${DRAFT_UUID_2}/approve`);++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/messages/drafts/:id/send', () => {+ it('should send a draft', async () => {+ messageSender.sendDraft.mockResolvedValue({ success: true });++ const response = await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/send`);++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 404 if draft not found', async () => {+ messageSender.sendDraft.mockResolvedValue({ success: false, error: 'Draft not found' });++ const response = await request(app).post(`/api/messages/drafts/${DRAFT_UUID_2}/send`);++ expect(response.status).toBe(404);+ });++ it('should return 400 for non-not-found errors', async () => {+ messageSender.sendDraft.mockResolvedValue({ success: false, error: 'Draft not approved' });++ const response = await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/send`);++ expect(response.status).toBe(400);+ expect(response.body.error).toBe('Draft not approved');+ });+ });++ describe('DELETE /api/messages/drafts/:id', () => {+ it('should delete a draft', async () => {+ messageDrafts.deleteDraft.mockResolvedValue(true);++ const response = await request(app).delete(`/api/messages/drafts/${DRAFT_UUID}`);++ expect(response.status).toBe(204);+ });++ it('should return 404 if draft not found', async () => {+ messageDrafts.deleteDraft.mockResolvedValue(false);++ const response = await request(app).delete(`/api/messages/drafts/${DRAFT_UUID_2}`);++ expect(response.status).toBe(404);+ });+ });++ // === Message Detail Route ===++ describe('GET /api/messages/:accountId/:messageId', () => {+ it('should return a message', async () => {+ const message = { id: 'msg-1', subject: 'Hello', accountId: VALID_UUID };+ messageSync.getMessage.mockResolvedValue(message);++ const response = await request(app).get(`/api/messages/${VALID_UUID}/msg-1`);++ expect(response.status).toBe(200);+ expect(response.body.subject).toBe('Hello');+ });++ it('should return 400 for invalid accountId', async () => {+ const response = await request(app).get(`/api/messages/${INVALID_UUID}/msg-1`);++ expect(response.status).toBe(400);+ expect(response.body.error).toBe('Invalid accountId or messageId format');+ });++ it('should return 404 if message not found', async () => {+ messageSync.getMessage.mockResolvedValue(null);++ const response = await request(app).get(`/api/messages/${VALID_UUID}/msg-1`);++ expect(response.status).toBe(404);+ expect(response.body.error).toBe('Message not found');+ });+ });++ // === Browser Launch Route ===++ describe('POST /api/messages/launch/:accountId', () => {+ it('should launch browser for outlook account', async () => {+ messageAccounts.getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook' });+ messagePlaywrightSync.launchProvider.mockResolvedValue({ success: true });++ const response = await request(app).post(`/api/messages/launch/${VALID_UUID}`);++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(messagePlaywrightSync.launchProvider).toHaveBeenCalledWith('outlook');+ });++ it('should return 404 if account not found', async () => {+ messageAccounts.getAccount.mockResolvedValue(null);++ const response = await request(app).post(`/api/messages/launch/${VALID_UUID}`);++ expect(response.status).toBe(404);+ });++ it('should return 400 for gmail accounts', async () => {+ messageAccounts.getAccount.mockResolvedValue({ id: VALID_UUID, type: 'gmail' });++ 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');+ });++ it('should return 503 if launch fails', async () => {+ messageAccounts.getAccount.mockResolvedValue({ id: VALID_UUID, type: 'teams' });+ messagePlaywrightSync.launchProvider.mockResolvedValue({ success: false, error: 'Browser not found' });++ const response = await request(app).post(`/api/messages/launch/${VALID_UUID}`);++ expect(response.status).toBe(503);+ });+ });++ // === Selector Routes ===++ describe('GET /api/messages/selectors', () => {+ it('should return selectors', async () => {+ const selectors = { outlook: { inbox: '.inbox' }, teams: { chat: '.chat' } };+ messagePlaywrightSync.getSelectors.mockResolvedValue(selectors);++ const response = await request(app).get('/api/messages/selectors');++ expect(response.status).toBe(200);+ expect(response.body).toEqual(selectors);+ });+ });++ describe('PUT /api/messages/selectors/:provider', () => {+ it('should update selectors for a valid provider', async () => {+ const updated = { inbox: '.new-inbox' };+ messagePlaywrightSync.updateSelectors.mockResolvedValue(updated);++ const response = await request(app)+ .put('/api/messages/selectors/outlook')+ .send({ selectors: { inbox: '.new-inbox' } });++ expect(response.status).toBe(200);+ expect(messagePlaywrightSync.updateSelectors).toHaveBeenCalledWith('outlook', { inbox: '.new-inbox' });+ });++ it('should return 400 for invalid provider', async () => {+ const response = await request(app)+ .put('/api/messages/selectors/gmail')+ .send({ selectors: { inbox: '.inbox' } });++ expect(response.status).toBe(400);+ expect(response.body.error).toBe('Invalid provider');+ });+ });++ describe('POST /api/messages/selectors/:provider/test', () => {+ it('should test selectors for a valid provider', async () => {+ messagePlaywrightSync.testSelectors.mockResolvedValue({ success: true, matched: 5 });++ const response = await request(app).post('/api/messages/selectors/teams/test');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should return 400 for invalid provider', async () => {+ const response = await request(app).post('/api/messages/selectors/gmail/test');++ expect(response.status).toBe(400);+ expect(response.body.error).toBe('Invalid provider');+ });+ });+});diff --git a/server/services/messageSender.js b/server/services/messageSender.jsindex 661828c3aa..2d03f55902 100644--- a/server/services/messageSender.js+++ b/server/services/messageSender.js@@ -12,7 +12,6 @@ export async function sendDraft(draftId, io) {await updateDraft(draftId, { status: 'sending' });console.log(`📧 Sending draft "${draft.subject}" via ${draft.sendVia}`);- let result;const dispatch = async () => {if (draft.sendVia === 'mcp') {const { sendGmail } = await import('./messageGmailSync.js');@@ -22,21 +21,21 @@ export async function sendDraft(draftId, io) {return sendPlaywright(account, draft);};- result = await dispatch().catch(async (error) => {+ const result = await dispatch().catch(async (error) => {console.error(`📧 Draft send threw for "${draft.subject}": ${error.message}`);- await updateDraft(draftId, { status: 'failed' }).catch(() => {});return { success: false, error: error.message };});- if (result.success) {+ if (result?.success) {await updateDraft(draftId, { status: 'sent' });io?.emit('messages:draft:sent', { draftId });io?.emit('messages:changed', {});console.log(`📧 Draft sent successfully: "${draft.subject}"`);} else {await updateDraft(draftId, { status: 'failed' }).catch(() => {});- console.log(`📧 Draft send failed: ${result.error || 'Unknown error'}`);- if (!result.error) result = { success: false, error: 'Unknown error sending draft' };+ const errorMsg = result?.error ?? 'Unknown error sending draft';+ console.log(`📧 Draft send failed: ${errorMsg}`);+ return { success: false, error: errorMsg };}return result;diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 06d1b852b8..209faabc29 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -6,6 +6,17 @@ import { getAccount, updateSyncStatus } from './messageAccounts.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;+function filterBySearch(messages, search) {+ if (!search) return messages;+ const q = search.toLowerCase();+ return messages.filter(m =>+ m.subject?.toLowerCase().includes(q) ||+ m.from?.name?.toLowerCase().includes(q) ||+ m.from?.email?.toLowerCase().includes(q) ||+ m.bodyText?.toLowerCase().includes(q)+ );+}+async function loadCache(accountId) {if (!UUID_RE.test(accountId)) throw new Error(`Invalid accountId: ${accountId}`);await ensureDir(CACHE_DIR);@@ -27,15 +38,7 @@ export async function getMessages(options = {}) {if (accountId) {const cache = await loadCache(accountId);let messages = cache.messages.map(m => ({ ...m, accountId: m.accountId || accountId }));- if (search) {- const q = search.toLowerCase();- messages = messages.filter(m =>- m.subject?.toLowerCase().includes(q) ||- m.from?.name?.toLowerCase().includes(q) ||- m.from?.email?.toLowerCase().includes(q) ||- m.bodyText?.toLowerCase().includes(q)- );- }+ messages = filterBySearch(messages, search);return {messages: messages.sort((a, b) => new Date(b.date) - new Date(a.date)).slice(offset, offset + limit),total: messages.length@@ -53,15 +56,7 @@ export async function getMessages(options = {}) {const cache = await loadCache(fileAccountId);allMessages.push(...cache.messages.map(m => ({ ...m, accountId: m.accountId || fileAccountId })));}- if (search) {- const q = search.toLowerCase();- allMessages = allMessages.filter(m =>- m.subject?.toLowerCase().includes(q) ||- m.from?.name?.toLowerCase().includes(q) ||- m.from?.email?.toLowerCase().includes(q) ||- m.bodyText?.toLowerCase().includes(q)- );- }+ allMessages = filterBySearch(allMessages, search);allMessages.sort((a, b) => new Date(b.date) - new Date(a.date));return {messages: allMessages.slice(offset, offset + limit),@@ -90,10 +85,9 @@ export async function syncAccount(accountId, io) {console.log(`📧 Starting sync for ${account.name} (${account.type})`);const cache = await loadCache(accountId);- let newMessages = [];- let uniqueNew;const providerSync = async () => {+ let newMessages = [];if (account.type === 'gmail') {const { syncGmail } = await import('./messageGmailSync.js');newMessages = await syncGmail(account, cache, io);@@ -104,7 +98,7 @@ export async function syncAccount(accountId, io) {// Deduplicate by externalId (skip dedup for messages without externalId)const existingIds = new Set(cache.messages.map(m => m.externalId).filter(Boolean));- uniqueNew = newMessages.filter(m => !m.externalId || !existingIds.has(m.externalId));+ const uniqueNew = newMessages.filter(m => !m.externalId || !existingIds.has(m.externalId));cache.messages.push(...uniqueNew);// Trim to maxMessages