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: fix error handling, naming, sync resilience, and input validation
Adam Eivy1fcd98942071
diff --git a/client/src/components/messages/AccountsTab.jsx b/client/src/components/messages/AccountsTab.jsxindex 975d5e2740..084c54230a 100644--- a/client/src/components/messages/AccountsTab.jsx+++ b/client/src/components/messages/AccountsTab.jsx@@ -15,8 +15,9 @@ export default function AccountsTab({ accounts, onRefresh }) {const handleCreate = async () => {if (!form.name) return toast.error('Name is required');setSaving(true);- await api.createMessageAccount(form);+ const result = await api.createMessageAccount(form).catch(() => null);setSaving(false);+ if (!result) return toast.error('Failed to create account');setShowForm(false);setForm({ name: '', type: 'gmail', email: '' });toast.success('Account created');@@ -25,14 +26,16 @@ export default function AccountsTab({ accounts, onRefresh }) {const handleDelete = async (id) => {setDeleting(id);- await api.deleteMessageAccount(id);+ const result = await api.deleteMessageAccount(id).catch(() => null);setDeleting(null);+ if (result === null) return toast.error('Failed to delete account');toast.success('Account deleted');onRefresh();};const handleToggle = async (account) => {- await api.updateMessageAccount(account.id, { enabled: !account.enabled });+ const result = await api.updateMessageAccount(account.id, { enabled: !account.enabled }).catch(() => null);+ if (!result) return toast.error('Failed to update account');toast.success(account.enabled ? 'Account disabled' : 'Account enabled');onRefresh();};diff --git a/client/src/pages/Messages.jsx b/client/src/pages/Messages.jsxindex fe47f28770..f7c4cbb7c6 100644--- a/client/src/pages/Messages.jsx+++ b/client/src/pages/Messages.jsx@@ -18,7 +18,8 @@ const TABS = [export default function Messages() {const { tab } = useParams();const navigate = useNavigate();- const activeTab = tab || 'inbox';+ const VALID_TABS = TABS.map(t => t.id);+ const activeTab = VALID_TABS.includes(tab) ? tab : 'inbox';const [accounts, setAccounts] = useState([]);const [loading, setLoading] = useState(true);diff --git a/client/src/services/api.js b/client/src/services/api.jsindex f71ac4527a..217106c3b7 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1616,7 +1616,7 @@ export const createMessageAccount = (data) => request('/messages/accounts', { meexport const updateMessageAccount = (id, data) => request(`/messages/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data) });export const deleteMessageAccount = (id) => request(`/messages/accounts/${id}`, { method: 'DELETE' });export const syncMessageAccount = (accountId) => request(`/messages/sync/${accountId}`, { method: 'POST' });-export const getSyncStatus = (accountId) => request(`/messages/sync/${accountId}/status`);+export const getMessageSyncStatus = (accountId) => request(`/messages/sync/${accountId}/status`);export const getMessageInbox = (params = {}) => {const qs = new URLSearchParams();if (params.accountId) qs.set('accountId', params.accountId);diff --git a/server/routes/messages.js b/server/routes/messages.jsindex 57dcb6e7f5..d8d655586e 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -109,11 +109,16 @@ router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {// === Inbox Routes ===router.get('/inbox', asyncHandler(async (req, res) => {const { accountId, search, limit, offset } = req.query;+ let parsedLimit = limit !== undefined ? parseInt(limit, 10) : 50;+ if (Number.isNaN(parsedLimit) || parsedLimit <= 0) parsedLimit = 50;+ if (parsedLimit > 100) parsedLimit = 100;+ let parsedOffset = offset !== undefined ? parseInt(offset, 10) : 0;+ if (Number.isNaN(parsedOffset) || parsedOffset < 0) parsedOffset = 0;const result = await messageSync.getMessages({accountId,search,- limit: limit ? parseInt(limit, 10) : 50,- offset: offset ? parseInt(offset, 10) : 0+ limit: parsedLimit,+ offset: parsedOffset});res.json(result);}));@@ -140,6 +145,8 @@ router.post('/drafts', asyncHandler(async (req, res) => {router.post('/drafts/generate', asyncHandler(async (req, res) => {const data = generateDraftSchema.parse(req.body);+ const account = await messageAccounts.getAccount(data.accountId);+ if (!account) return res.status(404).json({ error: 'Account not found' });// AI draft generation - stub for now// TODO: Use portos-ai-toolkit for provider selection and model tiersconst draft = await messageDrafts.createDraft({@@ -149,7 +156,7 @@ router.post('/drafts/generate', asyncHandler(async (req, res) => {subject: '',body: `[AI-generated reply placeholder]\n\nContext: ${data.context}\nInstructions: ${data.instructions}`,generatedBy: 'ai',- sendVia: 'mcp' // Will be determined by account type+ sendVia: account.provider || (account.type === 'gmail' ? 'mcp' : 'playwright')});req.app.get('io')?.emit('messages:draft:created', { draftId: draft.id });res.status(201).json(draft);diff --git a/server/services/messageSender.js b/server/services/messageSender.jsindex 32fd335796..6499e55ff6 100644--- a/server/services/messageSender.js+++ b/server/services/messageSender.js@@ -13,21 +13,28 @@ export async function sendDraft(draftId, io) {console.log(`📧 Sending draft "${draft.subject}" via ${draft.sendVia}`);let result;- if (draft.sendVia === 'mcp') {- const { sendGmail } = await import('./messageGmailSync.js');- result = await sendGmail(account, draft);- } else {+ const dispatch = async () => {+ if (draft.sendVia === 'mcp') {+ const { sendGmail } = await import('./messageGmailSync.js');+ return sendGmail(account, draft);+ }const { sendPlaywright } = await import('./messagePlaywrightSync.js');- result = await sendPlaywright(account, draft);- }+ return sendPlaywright(account, draft);+ };++ 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) {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' });+ } else if (result.error) {+ await updateDraft(draftId, { status: 'failed' }).catch(() => {});console.log(`📧 Draft send failed: ${result.error}`);}diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 8fdd4b9596..9cb42e7cf6 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -24,7 +24,7 @@ export async function getMessages(options = {}) {// If specific account, just load that cacheif (accountId) {const cache = await loadCache(accountId);- let messages = cache.messages;+ let messages = cache.messages.map(m => ({ ...m, accountId: m.accountId || accountId }));if (search) {const q = search.toLowerCase();messages = messages.filter(m =>@@ -47,8 +47,9 @@ export async function getMessages(options = {}) {let allMessages = [];for (const file of files) {if (!file.endsWith('.json')) continue;- const cache = await loadCache(file.replace('.json', ''));- allMessages.push(...cache.messages);+ const fileAccountId = file.replace('.json', '');+ const cache = await loadCache(fileAccountId);+ allMessages.push(...cache.messages.map(m => ({ ...m, accountId: m.accountId || fileAccountId })));}if (search) {const q = search.toLowerCase();@@ -81,34 +82,45 @@ export async function syncAccount(accountId, io) {const cache = await loadCache(accountId);let newMessages = [];- // Provider-specific sync- if (account.type === 'gmail') {- const { syncGmail } = await import('./messageGmailSync.js');- newMessages = await syncGmail(account, cache, io);- } else if (account.type === 'outlook' || account.type === 'teams') {- const { syncPlaywright } = await import('./messagePlaywrightSync.js');- newMessages = await syncPlaywright(account, cache, io);- }+ let uniqueNew;+ const providerSync = async () => {+ if (account.type === 'gmail') {+ const { syncGmail } = await import('./messageGmailSync.js');+ newMessages = await syncGmail(account, cache, io);+ } else if (account.type === 'outlook' || account.type === 'teams') {+ const { syncPlaywright } = await import('./messagePlaywrightSync.js');+ newMessages = await syncPlaywright(account, cache, io);+ }- // Deduplicate by externalId- const existingIds = new Set(cache.messages.map(m => m.externalId));- const uniqueNew = newMessages.filter(m => !existingIds.has(m.externalId));- cache.messages.push(...uniqueNew);+ // 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));+ cache.messages.push(...uniqueNew);- // Trim to maxMessages- if (account.syncConfig?.maxMessages && cache.messages.length > account.syncConfig.maxMessages) {- cache.messages.sort((a, b) => new Date(b.date) - new Date(a.date));- cache.messages = cache.messages.slice(0, account.syncConfig.maxMessages);- }+ // Trim to maxMessages+ if (account.syncConfig?.maxMessages && cache.messages.length > account.syncConfig.maxMessages) {+ cache.messages.sort((a, b) => new Date(b.date) - new Date(a.date));+ cache.messages = cache.messages.slice(0, account.syncConfig.maxMessages);+ }- await saveCache(accountId, cache);- await updateSyncStatus(accountId, 'success');+ await saveCache(accountId, cache);+ await updateSyncStatus(accountId, 'success');++ io?.emit('messages:sync:completed', { accountId, newMessages: uniqueNew.length });+ io?.emit('messages:changed', {});+ console.log(`📧 Sync complete for ${account.name}: ${uniqueNew.length} new messages`);++ return { newMessages: uniqueNew.length, total: cache.messages.length };+ };- io?.emit('messages:sync:completed', { accountId, newMessages: uniqueNew.length });- io?.emit('messages:changed', {});- console.log(`📧 Sync complete for ${account.name}: ${uniqueNew.length} new messages`);+ const result = await providerSync().catch(async (error) => {+ console.error(`📧 Sync failed for ${account.name} (${account.type}): ${error.message}`);+ await updateSyncStatus(accountId, 'error').catch(() => {});+ io?.emit('messages:sync:failed', { accountId, error: error.message });+ throw error;+ });- return { newMessages: uniqueNew.length, total: cache.messages.length };+ return result;}export async function getSyncStatus(accountId) {