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

38.7 KB
Raw Blame
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
import messagesRoutes from './messages.js';

vi.mock('../services/humanActivity.js', () => ({ deleteEvents: vi.fn().mockResolvedValue({ deleted: 0 }) }));
vi.mock('../services/tribe.js', () => ({ deleteAutoTouchpoints: vi.fn().mockResolvedValue({ touchpoints: 0, auditRows: 0 }) }));
vi.mock('../services/messageEvaluator.js', () => ({ evaluateMessages: vi.fn(), generateReplyBody: vi.fn() }));
import { evaluateMessages, generateReplyBody } from '../services/messageEvaluator.js';
import { ServerError, errorEvents } from '../lib/errorHandler.js';
const observeError = () => {};
beforeAll(() => errorEvents.on('error', observeError));
afterAll(() => errorEvents.off('error', observeError));

vi.mock('../services/messageActions.js', () => ({ executeAction: vi.fn() }));
import { executeAction } from '../services/messageActions.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(),
  updateMessageEvaluations: vi.fn(),
  getMessage: vi.fn(),
  getThread: vi.fn(),
  refreshMessage: vi.fn(),
  refreshMessages: vi.fn(),
  deleteCache: vi.fn()
}));

vi.mock('../services/messageDrafts.js', () => ({
  listDrafts: vi.fn(),
  createDraft: vi.fn(),
  updateDraft: vi.fn(),
  approveDraft: vi.fn(),
  reconcileDraftSend: vi.fn(),
  deleteDraft: vi.fn(),
  deleteDraftsByAccountId: vi.fn()
}));

vi.mock('../services/messageTriageRules.js', () => ({ listRules: vi.fn(), deleteRule: vi.fn() }));
import { listRules, deleteRule } from '../services/messageTriageRules.js';

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()
}));

vi.mock('../services/messageTokenExtractor.js', () => ({
  getToken: vi.fn(),
  getTokenStatus: vi.fn(),
  testApi: vi.fn(),
  clearTokenCache: 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 humanActivity from '../services/humanActivity.js';
import * as tribe from '../services/tribe.js';
import * as messageSender from '../services/messageSender.js';
import * as messagePlaywrightSync from '../services/messagePlaywrightSync.js';
import * as messageTokenExtractor from '../services/messageTokenExtractor.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();
  });

  describe('POST /api/messages/evaluate', () => {
    it('uses a bounded pending selection and persists evaluations', async () => {
      const messages = Array.from({ length: 20 }, (_, i) => ({ id: `message-${i}` }));
      messageSync.getMessages.mockResolvedValue({ messages, total: 51 });
      const evaluations = Object.fromEntries(messages.map(m => [m.id, { score: 1 }]));
      evaluateMessages.mockResolvedValue({ evaluations });
      const response = await request(app).post('/api/messages/evaluate').send({});
      expect(response.status).toBe(200);
      expect(messageSync.getMessages).toHaveBeenCalledWith({ unevaluatedOnly: true, limit: 20 });
      expect(evaluateMessages).toHaveBeenCalledWith(messages);
      expect(messageSync.updateMessageEvaluations).toHaveBeenCalledWith(evaluations);
      expect(response.body).toEqual({ evaluations, missingMessageIds: [] });
    });

    it('selects explicit IDs before pagination and reports missing IDs', async () => {
      const messages = [{ id: 'message-100' }];
      messageSync.getMessages.mockResolvedValue({ messages, total: 1 });
      evaluateMessages.mockResolvedValue({ evaluations: { 'message-100': { score: 1 } } });
      const messageIds = ['message-100', 'absent'];
      const response = await request(app).post('/api/messages/evaluate').send({ accountId: VALID_UUID, messageIds });
      expect(messageSync.getMessages).toHaveBeenCalledWith({ accountId: VALID_UUID, messageIds, unevaluatedOnly: false, limit: 100 });
      expect(evaluateMessages).toHaveBeenCalledWith(messages);
      expect(response.body.missingMessageIds).toEqual(['absent']);
    });

    it('reports an entirely missing selection without calling a provider', async () => {
      messageSync.getMessages.mockResolvedValue({ messages: [], total: 0 });
      const response = await request(app).post('/api/messages/evaluate').send({ messageIds: ['absent'] });
      expect(response.body).toEqual({ evaluations: {}, missingMessageIds: ['absent'] });
      expect(evaluateMessages).not.toHaveBeenCalled();
    });

    it.each([{ accountId: 'invalid' }, { accountId: 4 }, { messageIds: 'message-1' }, { messageIds: [] }, { messageIds: [' '] }, { messageIds: [4] }, { messageIds: Array(101).fill('id') }])('rejects invalid selection %j before provider work', async body => {
      const response = await request(app).post('/api/messages/evaluate').send(body);
      expect(response.status).toBe(400);
      expect(response.body.error).toBeDefined();
      expect(messageSync.getMessages).not.toHaveBeenCalled();
      expect(evaluateMessages).not.toHaveBeenCalled();
    });
  });

  describe('unavailable persisted Messages stores', () => {
    it('returns the shared non-success envelope for draft reads and creates', async () => {
      const error = new ServerError('Message drafts storage is unavailable or invalid; original data preserved', { status: 503, code: 'MESSAGE_DRAFTS_UNAVAILABLE' });
      messageDrafts.listDrafts.mockRejectedValueOnce(error);
      messageDrafts.createDraft.mockRejectedValueOnce(error);
      messageAccounts.getAccount.mockResolvedValueOnce({ id: VALID_UUID, type: 'gmail' });
      const read = await request(app).get('/api/messages/drafts');
      const create = await request(app).post('/api/messages/drafts').send({ accountId: VALID_UUID, body: 'Example message' });
      for (const response of [read, create]) {
        expect(response.status).toBe(503);
        expect(response.body).toMatchObject({ error: error.message, code: 'MESSAGE_DRAFTS_UNAVAILABLE' });
      }
    });

    it('returns the shared non-success envelope for triage reads and deletion', async () => {
      const error = new ServerError('Message triage rules storage is unavailable or invalid; original data preserved', { status: 503, code: 'MESSAGE_TRIAGE_RULES_UNAVAILABLE' });
      listRules.mockRejectedValueOnce(error);
      deleteRule.mockRejectedValueOnce(error);
      for (const response of [await request(app).get('/api/messages/triage-rules'), await request(app).delete('/api/messages/triage-rules/0')]) {
        expect(response.status).toBe(503);
        expect(response.body).toMatchObject({ error: error.message, code: 'MESSAGE_TRIAGE_RULES_UNAVAILABLE' });
      }
    });
  });

  // === 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(400);
    });

    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(400);
    });
  });

  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);
      expect(humanActivity.deleteEvents).toHaveBeenCalledWith({ accountId: VALID_UUID });
      expect(tribe.deleteAutoTouchpoints).toHaveBeenCalledWith({ accountId: 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('cleans up historical orphan data even when the account is absent', async () => {
      messageAccounts.updateAccount.mockResolvedValue(null);
      messageAccounts.deleteAccount.mockResolvedValue(false);

      const response = await request(app).delete(`/api/messages/accounts/${VALID_UUID}`);

      expect(response.status).toBe(204);
      expect(messageSync.deleteCache).toHaveBeenCalledWith(VALID_UUID);
      expect(messageDrafts.deleteDraftsByAccountId).toHaveBeenCalledWith(VALID_UUID);
    });
  });

  // === 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);
      // An omitted mode is left for syncAccount to resolve against the account's supported default.
      expect(messageSync.syncAccount).toHaveBeenCalledWith(VALID_UUID, undefined, { mode: undefined });
    });

    it('forwards an explicit mode and surfaces an unsupported-mode rejection as 400', async () => {
      messageSync.syncAccount.mockResolvedValue({ error: 'teams accounts do not support unread sync', status: 400 });

      const response = await request(app).post(`/api/messages/sync/${VALID_UUID}`).send({ mode: 'unread' });

      expect(messageSync.syncAccount).toHaveBeenCalledWith(VALID_UUID, undefined, { mode: 'unread' });
      expect(response.status).toBe(400);
      expect(response.body.error).toContain('unread');
    });

    it('rejects an unknown sync mode instead of silently syncing unread', async () => {
      const response = await request(app).post(`/api/messages/sync/${VALID_UUID}`).send({ mode: 'everything' });

      expect(response.status).toBe(400);
      expect(response.body.code).toBe('VALIDATION_ERROR');
      expect(messageSync.syncAccount).not.toHaveBeenCalled();
    });

    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: 'api' };
      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: 'api' })
      );
    });

    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 });

      // validateRequest returns 400 for invalid input
      expect(response.status).toBe(400);
    });
  });

  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('returns screening/setup failures without persisting or announcing a fake AI draft', async () => {
      const emit = vi.fn();
      app.set('io', { emit });
      messageAccounts.getAccount.mockResolvedValue({ id: VALID_UUID, type: 'gmail' });
      messageSync.getMessage.mockResolvedValue({ id: 'message-example', bodyText: 'Example message.', from: { email: '[email protected]' } });
      generateReplyBody.mockRejectedValue(new ServerError('Configure a local API provider in Models > LLMs > Abuse Guard.', { status: 422, code: 'untrusted-content-provider-unavailable' }));
      const response = await request(app).post('/api/messages/drafts/generate').send({ accountId: VALID_UUID, replyToMessageId: 'message-example' });
      expect(response.status).toBe(422);
      expect(response.body.code).toBe('untrusted-content-provider-unavailable');
      expect(response.body.error).toContain('Abuse Guard');
      expect(messageDrafts.createDraft).not.toHaveBeenCalled();
      expect(emit).not.toHaveBeenCalledWith('messages:draft:created', expect.anything());
    });

    it('addresses a generated email reply to the original sender with a normalized subject', async () => {
      messageAccounts.getAccount.mockResolvedValue({ id: VALID_UUID, type: 'gmail' });
      messageSync.getMessage.mockResolvedValue({ id: 'message-example', subject: 'Lunch?', from: { email: '[email protected]' }, bodyText: 'Example.' });
      generateReplyBody.mockResolvedValue({ body: 'Synthetic generated reply' });
      messageDrafts.createDraft.mockImplementation(async (d) => ({ id: DRAFT_UUID, ...d }));
      const response = await request(app).post('/api/messages/drafts/generate').send({ accountId: VALID_UUID, replyToMessageId: 'message-example' });
      expect(response.status).toBe(201);
      expect(messageDrafts.createDraft).toHaveBeenCalledWith(expect.objectContaining({ to: ['[email protected]'], subject: 'Re: Lunch?', body: 'Synthetic generated reply' }));

      messageSync.getMessage.mockResolvedValue({ id: 'message-example', subject: 'RE: Lunch?', from: { email: '[email protected]' } });
      await request(app).post('/api/messages/drafts/generate').send({ accountId: VALID_UUID, replyToMessageId: 'message-example' });
      expect(messageDrafts.createDraft).toHaveBeenLastCalledWith(expect.objectContaining({ subject: 'RE: Lunch?' }));
    });

    it('leaves delivery fields empty for Teams replies', async () => {
      messageAccounts.getAccount.mockResolvedValue({ id: VALID_UUID, type: 'teams' });
      messageSync.getMessage.mockResolvedValue({ id: 'message-example', subject: 'Chat', from: { email: '[email protected]' } });
      generateReplyBody.mockResolvedValue({ body: 'Synthetic generated reply' });
      messageDrafts.createDraft.mockImplementation(async (d) => ({ id: DRAFT_UUID, ...d }));
      await request(app).post('/api/messages/drafts/generate').send({ accountId: VALID_UUID, replyToMessageId: 'message-example' });
      expect(messageDrafts.createDraft).toHaveBeenCalledWith(expect.objectContaining({ to: [], subject: '' }));
    });

    it('returns typed errors and creates no draft when the original or its sender is unavailable', async () => {
      messageAccounts.getAccount.mockResolvedValue({ id: VALID_UUID, type: 'gmail' });
      messageSync.getMessage.mockResolvedValue(null);
      let response = await request(app).post('/api/messages/drafts/generate').send({ accountId: VALID_UUID, replyToMessageId: 'missing' });
      expect(response.status).toBe(404);
      expect(response.body.code).toBe('REPLY_ORIGINAL_NOT_FOUND');

      messageSync.getMessage.mockResolvedValue({ id: 'm', subject: 'Hi', from: {} });
      response = await request(app).post('/api/messages/drafts/generate').send({ accountId: VALID_UUID, replyToMessageId: 'm' });
      expect(response.status).toBe(422);
      expect(response.body.code).toBe('REPLY_TARGET_UNAVAILABLE');
      expect(messageDrafts.createDraft).not.toHaveBeenCalled();
    });

    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/reconcile', () => {
    it('validates the mailbox outcome and attempt identity, returns the updated draft, and emits only invalidation', async () => {
      const emit = vi.fn();
      app.set('io', { emit });
      const updated = { id: DRAFT_UUID, status: 'draft', sendAttemptId: DRAFT_UUID_2 };
      messageDrafts.reconcileDraftSend.mockResolvedValue(updated);
      const data = { attemptId: DRAFT_UUID_2, outcome: 'not_sent' };
      const response = await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/reconcile`).send(data);
      expect(response.status).toBe(200);
      expect(response.body).toEqual(updated);
      expect(messageDrafts.reconcileDraftSend).toHaveBeenCalledWith(DRAFT_UUID, data);
      expect(emit).toHaveBeenCalledWith('messages:changed', {});
      messageDrafts.reconcileDraftSend.mockClear();
      for (const invalid of [{ outcome: 'not_sent' }, { attemptId: DRAFT_UUID_2, outcome: 'retry' }]) {
        expect((await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/reconcile`).send(invalid)).status).toBe(400);
      }
      expect(messageDrafts.reconcileDraftSend).not.toHaveBeenCalled();
      messageDrafts.reconcileDraftSend.mockRejectedValueOnce(new ServerError('Draft state conflict', { status: 409, code: 'DRAFT_STATE_CONFLICT' }));
      const conflict = await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/reconcile`).send(data);
      expect(conflict.status).toBe(409);
      expect(conflict.body.code).toBe('DRAFT_STATE_CONFLICT');
    });
  });

  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, status: 404, code: 'DRAFT_NOT_FOUND', 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 a typed 409 for an ineligible send', async () => {
      messageSender.sendDraft.mockResolvedValue({ success: false, status: 409, code: 'DRAFT_STATE_CONFLICT', error: 'Draft not approved' });

      const response = await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/send`);

      expect(response.status).toBe(409);
      expect(response.body.error).toBe('Draft not approved');
      expect(response.body.code).toBe('DRAFT_STATE_CONFLICT');
    });
  });

  it.each([
    ['post', '/approve', 'approveDraft'],
    ['put', '', 'updateDraft'],
    ['post', '/send', 'sendDraft']
  ])('returns the conflict envelope from %s drafts/:id%s', async (method, suffix, service) => {
    const owner = service === 'sendDraft' ? messageSender : messageDrafts;
    owner[service].mockRejectedValueOnce(new ServerError('Draft state conflict', { status: 409, code: 'DRAFT_STATE_CONFLICT' }));
    const response = await request(app)[method](`/api/messages/drafts/${DRAFT_UUID}${suffix}`).send({});
    expect(response.status).toBe(409);
    expect(response.body).toMatchObject({ error: 'Draft state conflict', code: 'DRAFT_STATE_CONFLICT' });
  });

  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);
    });
  });

  // === Thread Route ===

  describe('GET /api/messages/thread/:accountId/:threadId', () => {
    it('should return thread messages', async () => {
      const threadMessages = [
        { id: 'msg-1', subject: 'Hello', threadId: 'thread-1' },
        { id: 'msg-2', subject: 'Hello', threadId: 'thread-1' }
      ];
      messageSync.getThread.mockResolvedValue(threadMessages);

      const response = await request(app).get(`/api/messages/thread/${VALID_UUID}/thread-1`);

      expect(response.status).toBe(200);
      expect(response.body.messages).toHaveLength(2);
      expect(messageSync.getThread).toHaveBeenCalledWith(VALID_UUID, 'thread-1');
    });

    it('should return 400 for invalid accountId', async () => {
      const response = await request(app).get(`/api/messages/thread/${INVALID_UUID}/thread-1`);

      expect(response.status).toBe(400);
      expect(response.body.error).toBe('Invalid accountId format');
    });

    it('should return empty array for unknown threadId', async () => {
      messageSync.getThread.mockResolvedValue([]);

      const response = await request(app).get(`/api/messages/thread/${VALID_UUID}/unknown`);

      expect(response.status).toBe(200);
      expect(response.body.messages).toHaveLength(0);
    });
  });

  // === 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');
    });
  });

  describe('POST /api/messages/fetch-full/:accountId', () => {
    it('refreshes preview-only messages in one batch', async () => {
      messageAccounts.getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook' });
      messageSync.getMessages.mockResolvedValue({
        messages: [
          { id: 'msg-1', bodyFull: false },
          { id: 'msg-2', bodyFull: true },
          { id: 'msg-3', bodyFull: false },
        ],
        total: 3,
      });
      messageSync.refreshMessages.mockResolvedValue({ updated: 2, results: [[], []] });

      const response = await request(app).post(`/api/messages/fetch-full/${VALID_UUID}`);

      expect(response.status).toBe(200);
      expect(response.body).toEqual({ updated: 2, total: 2, truncated: false });
      expect(messageSync.refreshMessages).toHaveBeenCalledTimes(1);
      expect(messageSync.refreshMessages).toHaveBeenCalledWith(VALID_UUID, ['msg-1', 'msg-3']);
    });
  });

  // === 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 the Google API, 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({ provider: 'teams', results: { matched: 5 }, status: 'ok' });

      const response = await request(app).post('/api/messages/selectors/teams/test');

      expect(response.status).toBe(200);
      expect(response.body.status).toBe('ok');
      expect(response.body.provider).toBe('teams');
      expect(response.body.results).toEqual({ matched: 5 });
    });

    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');
    });
  });

  describe('POST /api/messages/debug/test-token', () => {
    it('trims the provider API result to a status summary without message payloads', async () => {
      messageTokenExtractor.getToken.mockResolvedValue({
        token: 'tok-abcdef',
        fresh: true,
        decoded: { exp: 1893456000, aud: 'https://outlook.office.com', scp: 'Mail.Read' }
      });
      messageTokenExtractor.testApi.mockResolvedValue({
        success: true,
        count: 2,
        messages: [
          { id: 'm1', subject: 'Private subject', bodyContent: 'private-body-content' },
          { id: 'm2', subject: 'Another', bodyContent: 'more-private-content' }
        ]
      });

      const response = await request(app)
        .post('/api/messages/debug/test-token')
        .send({ provider: 'outlook' });

      expect(response.status).toBe(200);
      expect(response.body.api).toEqual({ success: true, count: 2 });
      const serialized = JSON.stringify(response.body);
      expect(serialized).not.toContain('private-body-content');
      expect(serialized).not.toContain('Private subject');
    });

    it('passes through status and error fields when the API test fails', async () => {
      messageTokenExtractor.getToken.mockResolvedValue({
        token: 'tok-abcdef',
        fresh: false,
        decoded: {}
      });
      messageTokenExtractor.testApi.mockResolvedValue({
        success: false,
        status: 401,
        error: 'InvalidAuthenticationToken'
      });

      const response = await request(app)
        .post('/api/messages/debug/test-token')
        .send({ provider: 'outlook' });

      expect(response.status).toBe(200);
      expect(response.body.api).toEqual({ success: false, status: 401, error: 'InvalidAuthenticationToken' });
    });
  });
});

describe('message browser action conflict envelope', () => {
  it('preserves both IDs and returns a typed 409 without broadcasting a change', async () => {
    const app = express();
    const emit = vi.fn();
    app.set('io', { emit });
    app.use(express.json());
    app.use('/api/messages', messagesRoutes);
    executeAction.mockRejectedValueOnce(new ServerError('Sync the account and retry.', { status: 409, code: 'MESSAGE_IDENTITY_CONFLICT' }));
    const response = await request(app).post(`/api/messages/${VALID_UUID}/${VALID_UUID_2}/action`).send({ action: 'delete' });
    expect(executeAction).toHaveBeenCalledWith(VALID_UUID, VALID_UUID_2, 'delete');
    expect(response.status).toBe(409);
    expect(response.body).toMatchObject({ error: 'Sync the account and retry.', code: 'MESSAGE_IDENTITY_CONFLICT' });
    expect(emit).not.toHaveBeenCalledWith('messages:changed', expect.anything());
  });
});