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
fix: branch inbox empty state on account and sync state (#3281)
[._.]/ Adam Eivy9825fc6a40b3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ae3b5ce0df..bf8b88dcf0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -48,6 +48,7 @@- **A message thread no longer renders under the wrong message.** Selecting one message and then quickly selecting another could let the first thread's response arrive last and render beneath the second message's header. The same stale-response fix was applied to the Feature Agents Output and Runs tabs, where switching agents mid-request could show one agent's output — and its recorded agent id — under another agent's tab.- **Gmail can now be fully connected from Messages Config.** The page can create or accept Google OAuth credentials, returns to Messages after authorization, and labels an enabled Gmail account as pending until its Gmail permission is actually ready.+- **[issue-3281] An empty inbox now names the step that would actually fill it.** "No messages yet — add an account and sync to get started" was shown to everyone, including users whose account was already configured and whose Sync buttons were sitting directly above the message. The empty state now says what is left to do and carries the button for it: add an account when none is configured, Sync Unread when nothing has ever synced, and — once a sync has run — how long ago it was, with a Clear filters button when a search or triage tab is what is hiding the mail. A sync where every account errors no longer reports success or claims the inbox has been synced.## Music Videodiff --git a/client/src/components/messages/InboxTab.jsx b/client/src/components/messages/InboxTab.jsxindex b4def6a730..2f771f451f 100644--- a/client/src/components/messages/InboxTab.jsx+++ b/client/src/components/messages/InboxTab.jsx@@ -1,9 +1,10 @@import { useState, useEffect, useCallback, useRef, useMemo } from 'react';-import { Mail, Search, RefreshCw, ChevronRight, Sparkles, Archive, Trash2, Reply, Eye, Flag, Pin, Loader2 } from 'lucide-react';+import { Mail, Search, RefreshCw, ChevronRight, Sparkles, Archive, Trash2, Reply, Eye, Flag, Pin, Loader2, Settings, FilterX, AlertTriangle } from 'lucide-react';import { useNavigate, useSearchParams } from 'react-router-dom';import toast from '../ui/Toast';import * as api from '../../services/api';import socket from '../../services/socket';+import { timeAgo } from '../../utils/formatters';import MessageDetail from './MessageDetail';const ACTION_CONFIG = {@@ -33,7 +34,129 @@ const TRIAGE_TABS = [{ key: 'untriaged', label: 'Untriaged', icon: Mail, filter: m => !m.evaluation },];+const EMPTY_ACTION_CLASS = 'inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm transition-colors disabled:opacity-50';++/**+ * Newest `lastSyncAt` across the given accounts, or `null` when none has ever+ * synced. `null` here means "never synced" — never "synced and found nothing".+ * @param {Array<{lastSyncAt?: string|null}>} accounts+ * @returns {string|null} ISO timestamp or null+ */+export function latestSyncAt(accounts) {+ return (accounts || []).reduce((newest, a) => {+ const stamp = a?.lastSyncAt;+ if (!stamp) return newest;+ return !newest || stamp > newest ? stamp : newest;+ }, null);+}++/**+ * Empty state for the inbox list. The action the user still has to take depends+ * on where they actually are, so this branches instead of always telling them to+ * "add an account and sync" — advice that was wrong for every user who already+ * had an account configured (#3281).+ *+ * `accounts === null` is the load-failed / not-loaded sentinel and is distinct+ * from `[]` ("loaded, and there are genuinely no accounts"); likewise a null+ * `lastSyncAt` means "never synced", not "synced and found nothing".+ */+export function InboxEmptyState({ accounts, lastSyncAt, hasFilters, syncing, onSync, onClearFilters }) {+ const navigate = useNavigate();++ const body = (() => {+ if (accounts === null) return {+ Icon: AlertTriangle,+ title: 'Could not load your mail accounts',+ hint: 'The inbox cannot tell what is configured until that request succeeds.',+ action: (+ <button+ onClick={() => navigate('/messages/config')}+ className={`${EMPTY_ACTION_CLASS} bg-port-accent/10 text-port-accent hover:bg-port-accent/20`}+ >+ <Settings size={14} />+ Open Config+ </button>+ )+ };++ if (accounts.length === 0) return {+ Icon: Mail,+ title: 'No messages yet',+ hint: 'Add an account and sync to get started',+ action: (+ <button+ onClick={() => navigate('/messages/config')}+ className={`${EMPTY_ACTION_CLASS} bg-port-accent/10 text-port-accent hover:bg-port-accent/20`}+ >+ <Settings size={14} />+ Add an account+ </button>+ )+ };++ if (!lastSyncAt) return {+ Icon: RefreshCw,+ title: 'Nothing synced yet',+ hint: 'Pull your latest mail to fill the inbox',+ action: (+ <button+ onClick={onSync}+ disabled={syncing}+ className={`${EMPTY_ACTION_CLASS} bg-port-accent/10 text-port-accent hover:bg-port-accent/20`}+ >+ <RefreshCw size={14} className={syncing ? 'animate-spin' : ''} />+ {syncing ? 'Syncing...' : 'Sync Unread'}+ </button>+ )+ };++ if (hasFilters) return {+ Icon: Mail,+ title: 'No messages match this view',+ hint: `Last synced ${timeAgo(lastSyncAt)}`,+ action: (+ <button+ onClick={onClearFilters}+ className={`${EMPTY_ACTION_CLASS} bg-port-border text-gray-300 hover:bg-port-border/80`}+ >+ <FilterX size={14} />+ Clear filters+ </button>+ )+ };++ return {+ Icon: Mail,+ title: 'Your inbox is empty',+ hint: `The last sync brought back nothing new — last synced ${timeAgo(lastSyncAt)}`,+ action: (+ <button+ onClick={onSync}+ disabled={syncing}+ className={`${EMPTY_ACTION_CLASS} bg-port-accent/10 text-port-accent hover:bg-port-accent/20`}+ >+ <RefreshCw size={14} className={syncing ? 'animate-spin' : ''} />+ {syncing ? 'Syncing...' : 'Sync Unread'}+ </button>+ )+ };+ })();++ const { Icon, title, hint, action } = body;+ return (+ <div className="text-center py-12 px-4 text-gray-500">+ <Icon size={48} className="mx-auto mb-4 opacity-50" />+ <p className="text-gray-300">{title}</p>+ <p className="text-sm mt-1">{hint}</p>+ <div className="mt-4 flex justify-center">{action}</div>+ </div>+ );+}+export default function InboxTab({ accounts }) {+ // Everything below iterates the list; the `null` load-failed sentinel is only+ // meaningful to the empty state, which reads `accounts` directly.+ const accountList = useMemo(() => accounts || [], [accounts]);const [messages, setMessages] = useState([]);const [loading, setLoading] = useState(true);const [search, setSearch] = useState('');@@ -42,6 +165,9 @@ export default function InboxTab({ accounts }) {const [selectedMessage, setSelectedMessage] = useState(null);const [evaluating, setEvaluating] = useState(false);const [syncing, setSyncing] = useState(false);+ // Set once a sync in this session actually succeeded, so the empty state stops+ // saying "never synced" without waiting for the parent to refetch accounts.+ const [syncedAt, setSyncedAt] = useState(null);const [fetchingFull, setFetchingFull] = useState(false);const [actionInProgress, setActionInProgress] = useState(null);const debounceRef = useRef(null);@@ -106,22 +232,29 @@ export default function InboxTab({ accounts }) {const handleSync = async (mode) => {const targets = selectedAccount- ? accounts.filter(a => a.id === selectedAccount && a.enabled)- : accounts.filter(a => a.enabled);+ ? accountList.filter(a => a.id === selectedAccount && a.enabled)+ : accountList.filter(a => a.enabled);if (targets.length === 0) return toast.error('No enabled accounts to sync');setSyncing(true);let totalNew = 0;let totalPruned = 0;+ let succeeded = 0;for (const acct of targets) {toast(`Syncing ${acct.name} (${mode})...`, { icon: '📧' });const result = await api.syncMessageAccount(acct.id, mode, { silent: true }).catch(err => {toast.error(`${acct.name}: ${err?.message || 'Sync failed'}`);return null;});- if (result?.newMessages) totalNew += result.newMessages;- if (result?.pruned) totalPruned += result.pruned;+ if (!result) continue;+ succeeded += 1;+ if (result.newMessages) totalNew += result.newMessages;+ if (result.pruned) totalPruned += result.pruned;}setSyncing(false);+ // Every account failing is not a completed sync — say so, and leave the+ // "never synced" state intact so the empty state keeps offering the retry.+ if (succeeded === 0) return;+ setSyncedAt(new Date().toISOString());const parts = [`${totalNew} new`];if (totalPruned > 0) parts.push(`${totalPruned} removed`);toast.success(`Sync complete — ${parts.join(', ')}`);@@ -148,7 +281,7 @@ export default function InboxTab({ accounts }) {const handleQuickReply = async (msg, e) => {e.stopPropagation();- const account = accounts.find(a => a.id === msg.accountId) || accounts[0];+ const account = accountList.find(a => a.id === msg.accountId) || accountList[0];if (!account) return toast.error('No account available');toast('Generating AI reply...', { icon: '✨' });const draft = await api.generateMessageDraft({@@ -167,7 +300,7 @@ export default function InboxTab({ accounts }) {const handleAction = async (msg, action, e) => {e.stopPropagation();if (actionInProgress) return;- const account = accounts.find(a => a.id === msg.accountId);+ const account = accountList.find(a => a.id === msg.accountId);if (!account) return toast.error('No account found for this message');if (!ACTIONABLE_SOURCES.includes(msg.source || account.type)) {return toast.error(`${action} not supported for ${msg.source || account.type}`);@@ -197,11 +330,24 @@ export default function InboxTab({ accounts }) {[messages, currentTab]);+ // A sync that landed in this session wins over the (not-yet-refetched) account+ // timestamps; absent both, the user has genuinely never synced.+ const lastSyncAt = syncedAt || latestSyncAt(accountList);+ // Search and account are applied server-side in fetchMessages, the triage tab+ // client-side — all three narrow what the list can show, so all three make+ // "nothing here" a filtering result rather than an empty mailbox.+ const hasFilters = Boolean(debouncedSearch || selectedAccount || activeTab !== 'all');+ const clearFilters = () => {+ setSearch('');+ setSelectedAccount('');+ setActiveTab('all');+ };+if (selectedMessage) {return (<MessageDetailmessage={selectedMessage}- accounts={accounts}+ accounts={accountList}onBack={() => { setSelectedMessage(null); fetchMessages(); }}/>);@@ -226,7 +372,7 @@ export default function InboxTab({ accounts }) {className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white focus:outline-none focus:border-port-accent"><option value="">All accounts</option>- {accounts.map(a => (+ {accountList.map(a => (<option key={a.id} value={a.id}>{a.name}</option>))}</select>@@ -318,22 +464,16 @@ export default function InboxTab({ accounts }) {})}</div>- {(() => {- if (visibleMessages.length === 0 && !loading) return (- <div className="text-center py-12 text-gray-500">- <Mail size={48} className="mx-auto mb-4 opacity-50" />- {messages.length === 0 ? (- <>- <p>No messages yet</p>- <p className="text-sm mt-1">Add an account and sync to get started</p>- </>- ) : (- <p>No {currentTab.label.toLowerCase()} messages</p>- )}- </div>- );- return null;- })()}+ {visibleMessages.length === 0 && !loading && (+ <InboxEmptyState+ accounts={accounts}+ lastSyncAt={lastSyncAt}+ hasFilters={hasFilters}+ syncing={syncing}+ onSync={() => handleSync('unread')}+ onClearFilters={clearFilters}+ />+ )}<div className="space-y-1">{visibleMessages.map((msg) => {@@ -379,7 +519,7 @@ export default function InboxTab({ accounts }) {const cfg = ACTION_CONFIG[actionKey];const Icon = cfg.icon;const isRecommended = ev?.action === actionKey;- const msgSource = msg.source || accounts.find(a => a.id === msg.accountId)?.type;+ const msgSource = msg.source || accountList.find(a => a.id === msg.accountId)?.type;const isActionable = ['archive', 'delete'].includes(actionKey) && ACTIONABLE_SOURCES.includes(msgSource);const onClick = actionKey === 'reply'diff --git a/client/src/components/messages/InboxTab.test.jsx b/client/src/components/messages/InboxTab.test.jsxnew file mode 100644index 0000000000..4cd195a20c--- /dev/null+++ b/client/src/components/messages/InboxTab.test.jsx@@ -0,0 +1,142 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter, Route, Routes } from 'react-router-dom';++const api = vi.hoisted(() => ({+ evaluateMessages: vi.fn(),+ executeMessageAction: vi.fn(),+ fetchFullContent: vi.fn(),+ generateMessageDraft: vi.fn(),+ getMessageInbox: vi.fn(),+ syncMessageAccount: vi.fn(),+}));+const toast = vi.hoisted(() => Object.assign(vi.fn(), {+ error: vi.fn(),+ success: 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>,+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ api.getMessageInbox.mockResolvedValue({ messages: [], total: 0 });+ api.syncMessageAccount.mockResolvedValue({ newMessages: 0, pruned: 0 });+});++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('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());+ 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('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();+ });+});diff --git a/client/src/pages/Messages.jsx b/client/src/pages/Messages.jsxindex aef3fc9aa3..2b93735f7c 100644--- a/client/src/pages/Messages.jsx+++ b/client/src/pages/Messages.jsx@@ -30,15 +30,29 @@ export default function Messages() {const { chatKey } = useParams();const activeTab = useValidTab(TABS, 'inbox');const fullBleed = FULL_BLEED_TAB_IDS.has(activeTab);- const [accounts, setAccounts] = useState([]);+ // `null` = the account list never loaded (request failed) — deliberately distinct+ // from `[]`, which means "loaded, and there genuinely are no accounts". The inbox+ // empty state branches on that difference to avoid telling a user to add an+ // account they already have (#3281).+ const [accounts, setAccounts] = useState(null);const [loading, setLoading] = useState(true);const fetchAccounts = useCallback(async () => {- const data = await api.getMessageAccounts().catch(() => []);- setAccounts(data || []);+ const data = await api.getMessageAccounts().catch(() => null);+ setAccounts(Array.isArray(data) ? data : null);setLoading(false);}, []);+ // Tabs that only iterate accounts want a plain array; the load-failed sentinel+ // is forwarded to the inbox alone, which is the one surface that acts on it.+ const accountList = accounts || [];++ // ConfigTab mutates the list with functional updaters — normalize the sentinel+ // so `prev` is always an array there.+ const updateAccounts = useCallback((updater) => {+ setAccounts(prev => (typeof updater === 'function' ? updater(prev || []) : updater));+ }, []);+useEffect(() => {fetchAccounts();}, [fetchAccounts]);@@ -60,11 +74,11 @@ export default function Messages() {case 'inbox':return <InboxTab accounts={accounts} />;case 'config':- return <ConfigTab accounts={accounts} setAccounts={setAccounts} />;+ return <ConfigTab accounts={accountList} setAccounts={updateAccounts} />;case 'drafts':- return <DraftsTab accounts={accounts} />;+ return <DraftsTab accounts={accountList} />;case 'sync':- return <SyncTab accounts={accounts} onRefresh={fetchAccounts} />;+ return <SyncTab accounts={accountList} onRefresh={fetchAccounts} />;case 'imessage':return <IMessageTab />;default:@@ -96,7 +110,11 @@ export default function Messages() {icon={Mail}title="Messages"subtitle="Unified email and messaging management"- actions={<span className="text-sm text-gray-500">{accounts.length} accounts</span>}+ actions={(+ <span className="text-sm text-gray-500">+ {accounts === null ? 'Accounts unavailable' : `${accounts.length} accounts`}+ </span>+ )}/><TabPills tabs={TABS} activeTab={activeTab} onChange={handleTabChange} ariaLabel="Messages sections" />