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

22.0 KB
Raw Blame
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router';

const api = vi.hoisted(() => ({
  evaluateMessages: vi.fn(),
  executeMessageAction: vi.fn(),
  fetchFullContent: vi.fn(),
  generateMessageDraft: vi.fn(),
  getMessageDetail: vi.fn(),
  getMessageInbox: vi.fn(),
  getMessageThread: vi.fn(),
  getSettings: vi.fn(),
  syncMessageAccount: vi.fn(),
}));
const toast = vi.hoisted(() => Object.assign(vi.fn(), {
  error: vi.fn(),
  success: vi.fn(),
  warning: vi.fn(),
}));
const socket = vi.hoisted(() => ({ on: vi.fn(), off: vi.fn(), emit: vi.fn() }));

vi.mock('../../services/api', () => api);
vi.mock('../ui/Toast', () => ({ default: toast }));
vi.mock('../../services/socket', () => ({ default: socket }));

const InboxTab = (await import('./InboxTab')).default;
const { latestSyncAt } = await import('./InboxTab');

const HOUR_AGO = new Date(Date.now() - 60 * 60 * 1000).toISOString();

const neverSyncedAccount = {
  id: '11111111-1111-1111-1111-111111111111',
  name: 'Personal',
  type: 'gmail',
  email: '[email protected]',
  enabled: true,
  lastSyncAt: null,
};
const syncedAccount = { ...neverSyncedAccount, lastSyncAt: HOUR_AGO };

function renderInbox(accounts, { route = '/messages/inbox' } = {}) {
  return render(
    <MemoryRouter initialEntries={[route]}>
      <Routes>
        <Route path="/messages/inbox" element={<InboxTab accounts={accounts} />} />
        <Route path="/messages/config" element={<div>CONFIG SCREEN</div>} />
      </Routes>
    </MemoryRouter>,
  );
}

function LocationProbe() {
  const location = useLocation();
  return <output data-testid="location">{location.pathname}{location.search}</output>;
}

function renderInboxWithLocation(accounts, { route = '/messages/inbox' } = {}) {
  return render(
    <MemoryRouter initialEntries={[route]}>
      <LocationProbe />
      <Routes>
        <Route path="/messages/inbox" element={<InboxTab accounts={accounts} />} />
      </Routes>
    </MemoryRouter>
  );
}

beforeEach(() => {
  vi.clearAllMocks();
  api.getMessageInbox.mockResolvedValue({ messages: [], total: 0 });
  api.getMessageDetail.mockResolvedValue(null);
  api.getMessageThread.mockResolvedValue({ messages: [] });
  api.getSettings.mockResolvedValue({});
  api.syncMessageAccount.mockResolvedValue({ newMessages: 0, pruned: 0 });
});

describe('InboxTab sync reconciliation', () => {
  const rows = Array.from({ length: 50 }, (_, i) => ({
    id: `synthetic-${i}`, externalId: `external-${i}`, accountId: syncedAccount.id,
    subject: `Synthetic summary ${i}`, from: { name: 'Example Sender' }, date: HOUR_AGO, preview: 'Compact preview',
  }));

  it('coalesces completed syncs into one bounded summary read without hydrating bodies', async () => {
    api.getMessageInbox.mockResolvedValue({ messages: rows, total: 5000 });
    renderInbox([syncedAccount]);
    await waitFor(() => expect(screen.getAllByText(/^Synthetic summary /)).toHaveLength(50));
    const completed = socket.on.mock.calls.find(([event]) => event === 'messages:sync:completed')[1];
    expect(socket.on.mock.calls.some(([event]) => event === 'messages:sync:message')).toBe(false);
    api.getMessageInbox.mockResolvedValue({ messages: rows.map(row => ({ ...row, subject: row.subject.replace('summary', 'updated') })), total: 5500 });
    act(() => {
      completed({ accountId: syncedAccount.id, newMessages: 500, status: 'success' });
      completed({ accountId: syncedAccount.id, newMessages: 0, status: 'partial' });
    });
    await waitFor(() => expect(screen.getAllByText(/^Synthetic updated /)).toHaveLength(50));
    expect(api.getMessageInbox).toHaveBeenCalledTimes(2);
    expect(api.getMessageInbox).toHaveBeenLastCalledWith({ summary: true }, expect.objectContaining({ silent: true }));
    expect(api.getMessageDetail).not.toHaveBeenCalled();
  });

  it('ignores another account completion and reconciles the selected account on reconnect', async () => {
    api.getMessageInbox.mockResolvedValue({ messages: rows, total: 5000 });
    const view = renderInbox([syncedAccount]);
    await waitFor(() => expect(screen.getAllByText(/^Synthetic summary /)).toHaveLength(50));
    fireEvent.change(screen.getByRole('combobox'), { target: { value: syncedAccount.id } });
    await waitFor(() => expect(api.getMessageInbox).toHaveBeenCalledTimes(2));
    await waitFor(() => expect(screen.getAllByText(/^Synthetic summary /)).toHaveLength(50));
    const completed = socket.on.mock.calls.filter(([event]) => event === 'messages:sync:completed').at(-1)[1];
    await act(async () => { completed({ accountId: 'other-account', status: 'success' }); });
    expect(api.getMessageInbox).toHaveBeenCalledTimes(2);
    const reconnect = socket.on.mock.calls.filter(([event]) => event === 'connect').at(-1)[1];
    await act(async () => { reconnect(); });
    expect(api.getMessageInbox).toHaveBeenCalledTimes(3);
    expect(api.getMessageInbox).toHaveBeenLastCalledWith({ summary: true, accountId: syncedAccount.id }, expect.objectContaining({ silent: true }));
    view.unmount();
    expect(socket.off).toHaveBeenCalledWith('messages:sync:completed', completed);
    await act(async () => { completed({ accountId: syncedAccount.id, status: 'success' }); });
    expect(api.getMessageInbox).toHaveBeenCalledTimes(3);
  });
});

describe('latestSyncAt', () => {
  it('returns null when no account has ever synced', () => {
    expect(latestSyncAt([neverSyncedAccount, { ...neverSyncedAccount, id: 'b' }])).toBeNull();
  });

  it('returns null for a missing list rather than throwing', () => {
    expect(latestSyncAt(null)).toBeNull();
  });

  it('skips an unparseable timestamp instead of reporting it as the newest sync', () => {
    expect(latestSyncAt([{ id: 'a', lastSyncAt: 'not-a-date' }])).toBeNull();
  });

  it('compares parsed dates, not raw strings, so an offset stamp sorts correctly', () => {
    // 2026-01-31T20:00-05:00 is 2026-02-01T01:00Z — later than the Z stamp, even
    // though it sorts earlier lexicographically.
    const zStamp = '2026-02-01T00:00:00.000Z';
    const offsetStamp = '2026-01-31T20:00:00.000-05:00';
    expect(latestSyncAt([{ id: 'a', lastSyncAt: zStamp }, { id: 'b', lastSyncAt: offsetStamp }]))
      .toBe(offsetStamp);
  });

  it('picks the newest timestamp and ignores accounts that never synced', () => {
    const older = '2026-01-01T00:00:00.000Z';
    const newer = '2026-02-01T00:00:00.000Z';
    const accounts = [
      { id: 'a', lastSyncAt: older },
      neverSyncedAccount,
      { id: 'c', lastSyncAt: newer },
    ];
    expect(latestSyncAt(accounts)).toBe(newer);
  });
});

describe('InboxTab empty state', () => {
  it('tells a user with zero accounts to add one, and routes them to Config', async () => {
    renderInbox([]);

    expect(await screen.findByText('No messages yet')).toBeInTheDocument();
    expect(screen.getByText('Add an account and sync to get started')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: /add an account/i }));
    expect(await screen.findByText('CONFIG SCREEN')).toBeInTheDocument();
  });

  it('offers a sync when an account exists but has never synced', async () => {
    renderInbox([neverSyncedAccount]);

    expect(await screen.findByText('Nothing synced yet')).toBeInTheDocument();
    expect(screen.getByText('Pull your latest mail to fill the inbox')).toBeInTheDocument();
    // The stale "add an account" advice must be gone once one is configured.
    expect(screen.queryByText('Add an account and sync to get started')).not.toBeInTheDocument();

    const emptyStateSync = screen.getAllByRole('button', { name: /sync unread/i }).at(-1);
    fireEvent.click(emptyStateSync);

    await waitFor(() => expect(api.syncMessageAccount).toHaveBeenCalledTimes(1));
    expect(api.syncMessageAccount).toHaveBeenCalledWith(neverSyncedAccount.id, 'unread', { silent: true });
  });

  it('keeps the never-synced copy when every account sync fails', async () => {
    api.syncMessageAccount.mockRejectedValue(new Error('imap unreachable'));
    renderInbox([neverSyncedAccount]);

    await screen.findByText('Nothing synced yet');
    fireEvent.click(screen.getAllByRole('button', { name: /sync unread/i }).at(-1));

    await waitFor(() => expect(toast.error).toHaveBeenCalled());
    await waitFor(() => expect(api.getMessageInbox).toHaveBeenCalledTimes(2));
    expect(toast.success).not.toHaveBeenCalled();
    expect(screen.getByText('Nothing synced yet')).toBeInTheDocument();
  });

  it('reports an empty result with the last sync time once a sync has run', async () => {
    renderInbox([syncedAccount]);

    expect(await screen.findByText('Your inbox is empty')).toBeInTheDocument();
    expect(screen.getByText(/last synced 1h ago/i)).toBeInTheDocument();
  });

  it('offers to clear filters when a triage filter is hiding everything', async () => {
    renderInbox([syncedAccount], { route: '/messages/inbox?triage=reply' });

    expect(await screen.findByText('No messages match this view')).toBeInTheDocument();
    expect(screen.getByText(/last synced 1h ago/i)).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: /clear filters/i }));

    expect(await screen.findByText('Your inbox is empty')).toBeInTheDocument();
  });

  it('scopes the sync question to the filtered account, not the whole list', async () => {
    const otherNeverSynced = { ...neverSyncedAccount, id: '22222222-2222-2222-2222-222222222222', name: 'Work' };
    renderInbox([syncedAccount, otherNeverSynced]);

    // Unfiltered, one account has synced — so the list is genuinely empty.
    expect(await screen.findByText('Your inbox is empty')).toBeInTheDocument();

    fireEvent.change(screen.getByRole('combobox'), { target: { value: otherNeverSynced.id } });

    // Filtered to the account that has never synced, the other account's
    // timestamp says nothing useful — offer the sync instead.
    expect(await screen.findByText('Nothing synced yet')).toBeInTheDocument();
  });

  it('does not claim there are no accounts when the account list failed to load', async () => {
    renderInbox(null);

    expect(await screen.findByText('Could not load your mail accounts')).toBeInTheDocument();
    expect(screen.queryByText('No messages yet')).not.toBeInTheDocument();
    expect(screen.queryByText('Nothing synced yet')).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: /open config/i }));
    expect(await screen.findByText('CONFIG SCREEN')).toBeInTheDocument();
  });

  it('says the message list failed to load instead of claiming an empty inbox (#10279)', async () => {
    api.getMessageInbox.mockRejectedValueOnce(new Error('offline'));
    renderInbox([syncedAccount]);

    expect(await screen.findByText('Could not load messages.')).toBeInTheDocument();
    expect(screen.queryByText('Your inbox is empty')).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    expect(await screen.findByText('Your inbox is empty')).toBeInTheDocument();
    expect(screen.queryByText('Could not load messages.')).not.toBeInTheDocument();
  });
});

describe('InboxTab sync capability (#9968)', () => {
  const gmail = { ...syncedAccount, syncModes: ['unread', 'full'], hasReadState: true };
  const teams = {
    ...syncedAccount, id: '33333333-3333-3333-3333-333333333333', name: 'Chat', type: 'teams',
    syncModes: ['full'], hasReadState: false,
  };

  it('skips Teams in an aggregate unread sync and says so', async () => {
    renderInbox([gmail, teams]);
    await screen.findByText('Your inbox is empty');

    fireEvent.click(screen.getAllByRole('button', { name: /sync unread/i })[0]);

    await waitFor(() => expect(api.syncMessageAccount).toHaveBeenCalledTimes(1));
    expect(api.syncMessageAccount).toHaveBeenCalledWith(gmail.id, 'unread', { silent: true });
    expect(toast.warning).toHaveBeenCalledWith(expect.stringContaining('Skipping Chat'));
  });

  it('runs Full Sync on every account, Teams included', async () => {
    renderInbox([gmail, teams]);
    await screen.findByText('Your inbox is empty');

    fireEvent.click(screen.getByRole('button', { name: 'Full Sync' }));

    await waitFor(() => expect(api.syncMessageAccount).toHaveBeenCalledTimes(2));
    expect(api.syncMessageAccount).toHaveBeenCalledWith(gmail.id, 'full', { silent: true });
    expect(api.syncMessageAccount).toHaveBeenCalledWith(teams.id, 'full', { silent: true });
    expect(toast.warning).not.toHaveBeenCalled();
  });

  it('offers only Full Sync, in the toolbar and the empty state, when only Teams is in scope', async () => {
    renderInbox([{ ...teams, lastSyncAt: null }]);

    expect(await screen.findByText('Nothing synced yet')).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /sync unread/i })).not.toBeInTheDocument();
    const fullSyncButtons = screen.getAllByRole('button', { name: 'Full Sync' });
    expect(fullSyncButtons).toHaveLength(2); // toolbar + empty-state action

    fireEvent.click(fullSyncButtons.at(-1));
    await waitFor(() => expect(api.syncMessageAccount).toHaveBeenCalledWith(teams.id, 'full', { silent: true }));
  });

  it('restores the unread action when the account filter narrows to a capable account', async () => {
    renderInbox([gmail, teams]);
    await screen.findByText('Your inbox is empty');

    fireEvent.change(screen.getByRole('combobox'), { target: { value: teams.id } });
    await act(async () => {});
    expect(screen.queryByRole('button', { name: /sync unread/i })).not.toBeInTheDocument();

    fireEvent.change(screen.getByRole('combobox'), { target: { value: gmail.id } });
    await act(async () => {});
    expect(screen.getAllByRole('button', { name: /sync unread/i }).length).toBeGreaterThan(0);
  });

  it('renders unknown read state neutrally, distinct from read and unread rows', async () => {
    const row = (id, flags) => ({
      id, accountId: gmail.id, threadId: null, subject: `Subject ${id}`, bodyText: 'preview',
      from: { name: `Sender ${id}`, email: `${id}@example.com` }, date: HOUR_AGO, ...flags,
    });
    api.getMessageInbox.mockResolvedValue({ total: 3, messages: [
      row('unread', { isRead: false, isUnread: true }),
      row('read', { isRead: true, isUnread: false }),
      row('unknown', { isRead: null, isUnread: null }),
    ] });
    renderInbox([gmail]);

    const sender = async (id) => (await screen.findByText(`Sender ${id}`));
    expect((await sender('unread')).className).toContain('font-medium');
    expect((await sender('read')).className).toContain('text-gray-400');
    const unknown = await sender('unknown');
    expect(unknown.className).not.toContain('font-medium');
    expect(unknown.className).not.toContain('text-gray-400');
    expect(unknown.closest('div.group').className).not.toContain('opacity-70');
    expect((await sender('read')).closest('div.group').className).toContain('opacity-70');
  });
});

describe('InboxTab message selection URL', () => {
  const message = {
    id: 'message-1',
    accountId: neverSyncedAccount.id,
    subject: 'A message to inspect',
    bodyText: 'Message body',
    from: { name: 'Example Sender' },
    date: '2026-08-16T00:00:00.000Z',
    source: 'gmail',
    evaluation: { action: 'reply', priority: 'medium' },
  };

  it('opens a selected message while preserving triage in the URL and removes selection on back', async () => {
    const { bodyText, ...summary } = message;
    api.getMessageInbox.mockResolvedValue({ messages: [{ ...summary, preview: 'Short preview' }], total: 5000 });
    api.getMessageDetail.mockResolvedValue(message);
    renderInboxWithLocation([neverSyncedAccount], { route: '/messages/inbox?triage=reply' });
    expect(await screen.findByText('Short preview')).toBeInTheDocument();
    expect(api.getMessageInbox).toHaveBeenCalledWith({ summary: true }, expect.objectContaining({ silent: true, signal: expect.any(AbortSignal) }));
    expect(api.getMessageDetail).not.toHaveBeenCalled();

    fireEvent.click(await screen.findByRole('button', { name: /a message to inspect/i }));
    expect(await screen.findByText('Message body')).toBeInTheDocument();
    expect(screen.getByTestId('location')).toHaveTextContent(
      `/messages/inbox?triage=reply&message=${message.id}&account=${message.accountId}`,
    );

    fireEvent.click(screen.getByRole('button', { name: 'Back' }));
    await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/messages/inbox?triage=reply'));
  });

  it('fetches a URL-selected message when it is missing from the current list', async () => {
    api.getMessageDetail.mockResolvedValue(message);
    renderInboxWithLocation([neverSyncedAccount], {
      route: `/messages/inbox?triage=review&message=${message.id}&account=${message.accountId}`,
    });

    expect(await screen.findByText('Message body')).toBeInTheDocument();
    expect(api.getMessageDetail).toHaveBeenCalledWith(neverSyncedAccount.id, message.id, { silent: true });
    expect(screen.getByTestId('location')).toHaveTextContent(
      `/messages/inbox?triage=review&message=${message.id}&account=${message.accountId}`,
    );
  });

  it.each(['resolve', 'reject'])('ignores a late %s from a previously selected summary', async (outcome) => {
    let finishFirst;
    const pending = new Promise((resolve, reject) => { finishFirst = outcome === 'resolve' ? resolve : reject; });
    const second = { ...message, id: 'message-2', subject: 'Second selection', bodyText: 'Second full body' };
    api.getMessageInbox.mockResolvedValue({ messages: [message, second].map(({ bodyText, ...row }) => ({ ...row, preview: 'Summary only' })), total: 2 });
    api.getMessageDetail.mockReturnValueOnce(pending).mockResolvedValueOnce(second);
    renderInboxWithLocation([neverSyncedAccount]);

    fireEvent.click(await screen.findByRole('button', { name: /a message to inspect/i }));
    await waitFor(() => expect(api.getMessageDetail).toHaveBeenCalledTimes(1));
    fireEvent.click(screen.getByRole('button', { name: /second selection/i }));
    expect(await screen.findByText('Second full body')).toBeInTheDocument();
    await act(async () => finishFirst(outcome === 'resolve' ? message : new Error('Synthetic stale failure')));
    expect(screen.getByText('Second full body')).toBeInTheDocument();
    expect(screen.getByTestId('location')).toHaveTextContent('message=message-2');
    expect(api.getMessageDetail).toHaveBeenCalledTimes(2);
  });

  it('keeps sender text in the row and wraps the toolbar instead of a single overflowing flex', async () => {
    api.getMessageInbox.mockResolvedValue({ messages: [message], total: 1 });
    const { container } = renderInbox([neverSyncedAccount]);

    expect(await screen.findByText('Example Sender')).toBeInTheDocument();
    expect(screen.getByRole('tablist', { name: 'Triage filters' })).toHaveClass('overflow-x-auto');
    const row = screen.getByText('Example Sender').closest('.group');
    expect(row.className).toMatch(/flex-col/);
    expect(row.className).toMatch(/sm:flex-row/);
    const toolbar = container.querySelector('input[aria-label="Search messages"]').closest('.flex.flex-col');
    expect(toolbar).toBeTruthy();
    expect(toolbar.className).toMatch(/sm:flex-row/);
  });
});

describe('InboxTab triage tab bar (#7244)', () => {
  const message = {
    id: 'message-1',
    accountId: neverSyncedAccount.id,
    subject: 'A message to inspect',
    bodyText: 'Message body',
    from: { name: 'Example Sender' },
    date: '2026-08-16T00:00:00.000Z',
    source: 'gmail',
    evaluation: { action: 'reply', priority: 'medium' },
  };

  it('keeps one tab stop on the bar and moves it with arrow keys, updating the URL', async () => {
    api.getMessageInbox.mockResolvedValue({ messages: [message], total: 1 });
    renderInboxWithLocation([syncedAccount]);

    const tablist = await screen.findByRole('tablist', { name: 'Triage filters' });
    const tabs = within(tablist).getAllByRole('tab');
    expect(tabs).toHaveLength(6);
    // One tab stop for the whole bar — the active "All" filter — and the
    // per-filter count still rides the tab label.
    expect(tabs.filter((t) => t.getAttribute('tabindex') === '0')).toHaveLength(1);
    const allTab = screen.getByRole('tab', { name: /^All/ });
    expect(allTab).toHaveAttribute('tabindex', '0');
    expect(within(allTab).getByText('1')).toBeInTheDocument();

    // ArrowRight moves the tab stop and the active filter together; the filter
    // change lands in the URL like a click does.
    const replyTab = screen.getByRole('tab', { name: /^Reply/ });
    allTab.focus();
    fireEvent.keyDown(allTab, { key: 'ArrowRight' });
    expect(replyTab).toHaveAttribute('aria-selected', 'true');
    expect(document.activeElement).toBe(replyTab);
    expect(screen.getByTestId('location')).toHaveTextContent('triage=reply');

    // Home/End jump to the ends of the bar.
    const untriagedTab = screen.getByRole('tab', { name: /^Untriaged/ });
    fireEvent.keyDown(replyTab, { key: 'End' });
    expect(document.activeElement).toBe(untriagedTab);
    expect(untriagedTab).toHaveAttribute('aria-selected', 'true');
    fireEvent.keyDown(untriagedTab, { key: 'Home' });
    expect(document.activeElement).toBe(allTab);
    expect(allTab).toHaveAttribute('aria-selected', 'true');
  });
});

it('retains the requested inbox row and displays the actionable identity conflict', async () => {
  const row = { id: 'requested', accountId: neverSyncedAccount.id, subject: 'Keep this message', from: { name: 'Example Sender' }, date: HOUR_AGO, source: 'gmail' };
  api.getMessageInbox.mockResolvedValue({ messages: [row], total: 1 });
  api.executeMessageAction.mockRejectedValueOnce(Object.assign(new Error('Sync the account and retry.'), { status: 409, code: 'MESSAGE_IDENTITY_CONFLICT' }));
  renderInbox([neverSyncedAccount]);
  expect(await screen.findByText(row.subject)).toBeInTheDocument();
  fireEvent.click(screen.getByRole('button', { name: 'Delete', exact: true }));
  await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Sync the account and retry.'));
  expect(api.executeMessageAction).toHaveBeenCalledWith(row.accountId, row.id, 'delete', { silent: true });
  expect(screen.getByText(row.subject)).toBeInTheDocument();
  expect(screen.getByRole('button', { name: 'Delete', exact: true })).not.toBeDisabled();
});