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: keep mailbox content out of operational logs (#8646)
[._.]/ Adam Eivyc5d0e4343dfa
diff --git a/server/lib/README.md b/server/lib/README.mdindex d636a86cfc..68e0fc2fdb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -756,3 +756,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `chatgptText.js` | `stripChatgptCitations(text)` removes opaque ChatGPT citation tokens while preserving ordinary Markdown and asset links. || `modelComparisonComposite.js` | `buildModelComparisonComposite(observations, inventory)` derives a stable sourced index with calibrated and effort estimates, route-specific price references and explicit research gaps. |++| `messageLogError.js` | `messageLogError(error)` projects mailbox failures to allowlisted codes and HTTP error status, excluding provider text and credentials. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 1677c01735..6ba2346eff 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -739,3 +739,4 @@ export * from './markdownImages.js';export * from './chatgptText.js';export * from './modelComparisonComposite.js';+export * from './messageLogError.js';diff --git a/server/lib/messageLogError.js b/server/lib/messageLogError.jsnew file mode 100644index 0000000000..7edf269386--- /dev/null+++ b/server/lib/messageLogError.js@@ -0,0 +1,14 @@+// Mail provider diagnostics can contain subjects, addresses, bodies and credentials.+// Never include free text, stacks or arbitrary provider codes in operational logs.+const SAFE_CODES = new Set([+ 'ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'ETIMEDOUT',+ 'ABORT_ERR', 'SEND_FAILED', 'GMAIL_SEND_FAILED', 'GMAIL_NOT_CONFIGURED'+]);++export function messageLogError(error) {+ const code = SAFE_CODES.has(error?.code) ? error.code : 'MAIL_OPERATION_FAILED';+ const status = error?.response?.status ?? error?.status;+ return Number.isInteger(status) && status >= 400 && status <= 599+ ? `${code} HTTP ${status}`+ : code;+}diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.jsindex ea088e2c20..5b1437a82f 100644--- a/server/services/messageAccounts.js+++ b/server/services/messageAccounts.js@@ -65,7 +65,7 @@ export async function createAccount(data) {createdAt: new Date().toISOString()};await saveAccounts(accounts);- console.log(`📧 Message account created: ${data.name} (${data.type})`);+ console.log(`📧 Message account created: ${id} (${data.type})`);return accounts[id];});}diff --git a/server/services/messageActions.js b/server/services/messageActions.jsindex da4d5293bf..ae4ca0a1be 100644--- a/server/services/messageActions.js+++ b/server/services/messageActions.js@@ -87,17 +87,17 @@ export async function executeAction(accountId, messageId, action) {await executeGmailApiAction(message, action);} else if (account.type === 'outlook') {const page = await ensureProviderPage(account.type);- console.log(`📧 ${action} message "${message.subject}" via ${account.type} browser`);+ console.log(`📧 ${action} message ${message.id} via ${account.type} browser`);await executeOutlookAction(page, message.subject || '', action);} else if (account.type === 'gmail') {// Fallback to browser if no apiIdconst page = await ensureProviderPage(account.type);- console.log(`📧 ${action} message "${message.subject}" via gmail browser`);+ console.log(`📧 ${action} message ${message.id} via gmail browser`);const script = buildGmailActionScript((message.subject || '').replace(/'/g, "\\'").replace(/\n/g, ' '), action);const result = await evaluateOnPage(page, script);if (!result || result.error) {if (result?.notInInbox) {- console.log(`📧 "${message.subject}" not found in inbox, cleaning up local cache`);+ console.log(`📧 ${message.id} not found in inbox, cleaning up local cache`);} else {throw new Error(result?.error || `${action} failed`);}@@ -118,7 +118,7 @@ export async function executeAction(accountId, messageId, action) {}await removeFromCache(accountId, messageId);- console.log(`📧 ${action} complete for "${message.subject}"`);+ console.log(`📧 ${action} complete for ${message.id}`);return { success: true, action, messageId };}@@ -138,14 +138,14 @@ async function executeGmailApiAction(message, action) {if (action === 'delete') {await gmailClient.users.messages.trash({ userId: 'me', id: message.apiId });- console.log(`📧 Gmail API: trashed "${message.subject}"`);+ console.log(`📧 Gmail API: trashed ${message.id}`);} else if (action === 'archive') {await gmailClient.users.messages.modify({userId: 'me',id: message.apiId,requestBody: { removeLabelIds: ['INBOX'] }});- console.log(`📧 Gmail API: archived "${message.subject}"`);+ console.log(`📧 Gmail API: archived ${message.id}`);}}@@ -188,7 +188,7 @@ async function executeOutlookAction(page, subject, action) {const selectResult = await evaluateOnPage(page, selectScript);if (!selectResult || selectResult.error) {if (selectResult?.notInInbox) {- console.log(`📧 "${subject}" not found in inbox, cleaning up local cache`);+ console.log(`📧 Message not found in inbox, cleaning up local cache`);return;}throw new Error(selectResult?.error || 'Failed to select message');diff --git a/server/services/messageApiSync.js b/server/services/messageApiSync.jsindex 9c3fbea27f..6070fc4b4a 100644--- a/server/services/messageApiSync.js+++ b/server/services/messageApiSync.js@@ -31,13 +31,13 @@ export async function syncOutlookApi(account, cache, io, options = {}) {const tokenResult = await getToken('outlook');if (tokenResult.error) {- console.log(`📧 API sync unavailable for ${account.email}: ${tokenResult.message}`);+ console.log(`📧 API sync unavailable for account ${account.id}: TOKEN_UNAVAILABLE`);return null; // Signal to fall back to Playwright}const token = tokenResult.token;const maxMessages = mode === 'full' ? 200 : 100;- console.log(`📧 API sync (${mode}) for ${account.email}`);+ console.log(`📧 API sync (${mode}) for account ${account.id}`);// Build query — unread mode filters to unread onlylet filter = '';@@ -63,8 +63,8 @@ export async function syncOutlookApi(account, cache, io, options = {}) {}, GRAPH_API_TIMEOUT_MS);if (!response.ok) {- const text = await response.text().catch(() => '');- console.log(`📧 API sync failed (${response.status}): ${text.slice(0, 200)}`);+ await response.text().catch(() => ''); // Drain the body without logging provider content.+ console.warn(`📧 API sync failed for account ${account.id}: HTTP ${response.status}`);if (response.status === 401) {// Token expired — clear cache so next sync re-extractsclearTokenCache('outlook');diff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.jsindex 07668b7a39..1d30f1fafb 100644--- a/server/services/messageDrafts.js+++ b/server/services/messageDrafts.js@@ -69,7 +69,7 @@ export async function createDraft(data) {};drafts.push(draft);await saveDrafts(drafts);- console.log(`📝 Message draft created: "${draft.subject}" via ${draft.sendVia}`);+ console.log(`📝 Message draft created: ${draft.id} via ${draft.sendVia}`);return draft;});}diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex 455ef0af9d..0e8f397881 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -3,6 +3,7 @@* Uses the shared Google OAuth client from googleAuth.js (same credentials as Calendar).*/+import { messageLogError } from '../lib/messageLogError.js';import { gmail } from '@googleapis/gmail';import { v4 as uuidv4 } from '../lib/uuid.js';import crypto from 'crypto';@@ -26,7 +27,7 @@ function makeExternalId(gmailId) {*/export async function fetchSendAsAliases(gmailClient) {const res = await gmailClient.users.settings.sendAs.list({ userId: 'me' }).catch((err) => {- console.warn(`📧 Gmail send-as alias fetch failed: ${err.message}`);+ console.warn(`📧 Gmail send-as alias fetch failed: ${messageLogError(err)}`);return null;});if (!res) return null; // sentinel: fetch failed — do not clobber the stored aliases@@ -228,7 +229,7 @@ export async function syncGmail(account, cache, io, options = {}) {const auth = await getAuthenticatedClient();if (!auth) {- console.log(`📧 Gmail sync for ${account.email}: Google OAuth not configured`);+ console.log(`📧 Gmail sync for account ${account.id}: Google OAuth not configured`);return { messages: [], status: 'not-configured' };}@@ -245,7 +246,7 @@ export async function syncGmail(account, cache, io, options = {}) {const passes = gmailSyncPasses(mode, ingestSent, maxMessages);const totalCap = passes.reduce((sum, p) => sum + p.cap, 0);- console.log(`📧 Gmail API sync (${mode}${ingestSent ? '+sent' : ''}) for ${account.email}`);+ console.log(`📧 Gmail API sync (${mode}${ingestSent ? '+sent' : ''}) for account ${account.id}`);// Step 1: List message IDs — one pass per (query, cap), each paginated fully up// to its cap and deduped across passes (a thread can appear in both inbox and@@ -281,7 +282,7 @@ export async function syncGmail(account, cache, io, options = {}) {// drops the account rather than nudging on incomplete reply evidence.const sentTruncated = ingestSent && truncated.includes(sentQuery());if (sentTruncated) {- console.warn(`📧 Gmail sent-mail coverage partial for ${account.email} — >${SENT_INGEST_MAX} sent in ${SENT_INGEST_DAYS}d; reply detection paused for this account until a full sync`);+ console.warn(`📧 Gmail sent-mail coverage partial for account ${account.id} — >${SENT_INGEST_MAX} sent in ${SENT_INGEST_DAYS}d; reply detection paused for this account until a full sync`);}console.log(`📧 Gmail: found ${messageIds.length} message IDs, fetching details`);@@ -297,7 +298,7 @@ export async function syncGmail(account, cache, io, options = {}) {const batch = messageIds.slice(i, i + BATCH_SIZE);const results = await Promise.all(batch.map(({ id: gmailId }) =>gmailClient.users.messages.get({ userId: 'me', id: gmailId, format: 'full' })- .catch(err => { console.log(`📧 Gmail: failed to fetch ${gmailId}: ${err.message}`); return null; })+ .catch(err => { console.warn(`📧 Gmail: failed to fetch message detail: ${messageLogError(err)}`); return null; })));for (let j = 0; j < results.length; j++) {@@ -373,7 +374,7 @@ export async function syncGmail(account, cache, io, options = {}) {// reply detection isn't trusted for this account anyway, so don't over-signal.)const sentCoveragePartial = sentTruncated || (ingestSent && detailFetchFailures > 0);if (ingestSent && detailFetchFailures > 0 && !sentTruncated) {- console.warn(`📧 Gmail: ${detailFetchFailures} message detail fetch(es) failed for ${account.email} — reply detection paused for this account this sync (incomplete coverage)`);+ console.warn(`📧 Gmail: ${detailFetchFailures} message detail fetch(es) failed for account ${account.id} — reply detection paused for this account this sync (incomplete coverage)`);}console.log(`📧 Gmail API sync complete: ${inboxMessages.length} inbox, ${sentMessages.length} sent (activity-only)`);@@ -420,7 +421,7 @@ export async function sendGmail(account, draft) {userId: 'me',requestBody: { raw }}).catch(err => {- console.error(`📧 Gmail send failed: ${err.message}`);+ console.error(`📧 Gmail send failed: ${messageLogError(err)}`);return null;});@@ -428,6 +429,6 @@ export async function sendGmail(account, draft) {return { success: false, error: 'Gmail API send failed', status: 502, code: 'GMAIL_SEND_FAILED' };}- console.log(`📧 Gmail sent: ${draft.subject} (id: ${result.data?.id})`);+ console.log(`📧 Gmail sent: draft ${draft.id}`);return { success: true };}diff --git a/server/services/messageLogging.test.js b/server/services/messageLogging.test.jsnew file mode 100644index 0000000000..330f0e5e20--- /dev/null+++ b/server/services/messageLogging.test.js@@ -0,0 +1,150 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { join } from 'path';++const doubles = vi.hoisted(() => ({+ files: new Map(),+ send: vi.fn(), list: vi.fn(), get: vi.fn(), trash: vi.fn(), modify: vi.fn(),+ fetch: vi.fn(), token: vi.fn(), evaluate: vi.fn()+}));+vi.mock('../lib/fileUtils.js', async (original) => ({+ ...await original(),+ PATHS: { messages: '/mock/messages' },+ ensureDir: async () => {},+ tryReadFile: async path => doubles.files.get(path) ?? null,+ atomicWrite: async (path, value) => { doubles.files.set(path, JSON.stringify(value)); }+}));+vi.mock('./readinessNotify.js', () => ({ noteReadinessChanged: () => {} }));+vi.mock('./googleAuth.js', () => ({ getAuthenticatedClient: async () => ({}) }));+vi.mock('@googleapis/gmail', () => ({+ gmail: () => ({ users: {+ messages: { send: doubles.send, list: doubles.list, get: doubles.get, trash: doubles.trash, modify: doubles.modify },+ settings: { sendAs: { list: async () => ({ data: { sendAs: [] } }) } }+ } })+}));+vi.mock('../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: doubles.fetch }));+vi.mock('./messageTokenExtractor.js', () => ({ getToken: doubles.token, clearTokenCache: () => {} }));+vi.mock('./browserService.js', () => ({+ findOrOpenPage: async () => ({ url: 'https://outlook.office.com/mail/', webSocketDebuggerUrl: 'ws://example.invalid' }),+ listCdpPages: async () => [{ url: 'https://outlook.office.com/mail/', webSocketDebuggerUrl: 'ws://example.invalid' }],+ isAuthPage: () => false,+ evaluateOnPage: doubles.evaluate+}));+vi.mock('./userTimezone.js', () => ({ getUserTimezone: async () => 'UTC' }));+vi.mock('./humanActivity.js', () => ({ recordEvents: async () => ({ recorded: 0 }) }));+vi.mock('./tribe.js', () => ({ autoLogTouchpoints: async () => ({ created: 0 }) }));+vi.mock('./messageTriageRules.js', () => ({ recordCorrection: async () => {} }));++import { createAccount } from './messageAccounts.js';+import { createDraft, getDraft, updateDraft } from './messageDrafts.js';+import { sendDraft } from './messageSender.js';+import { syncAccount, refreshMessage, getMessage } from './messageSync.js';+import { syncOutlookApi } from './messageApiSync.js';+import { executeAction } from './messageActions.js';+import { syncPlaywright, sendPlaywright } from './messagePlaywrightSync.js';++const PRIVATE = {+ subject: 'SYNTHETIC_PRIVATE_SUBJECT',+ body: 'SYNTHETIC_PRIVATE_BODY',+ name: 'SYNTHETIC_PRIVATE_DISPLAY_NAME',+ email: '[email protected]'+};+const credential = 'Bearer synthetic-credential-must-not-be-logged';+const failure = () => Object.assign(+ new Error(Object.values(PRIVATE).join(' ') + ' ' + credential),+ { code: PRIVATE.subject, response: { status: 403 } }+);+let logs;+function output() { return logs.flatMap(spy => spy.mock.calls.flat()).join('\n'); }+function expectPrivateOutputAbsent() {+ for (const marker of [...Object.values(PRIVATE), credential]) expect(output()).not.toContain(marker);+}+function seedMessage(account) {+ const message = { id: 'local-message-1', apiId: 'api-message-1', subject: PRIVATE.subject, bodyText: PRIVATE.body, from: { name: PRIVATE.name, email: PRIVATE.email } };+ doubles.files.set(join('/mock/messages/cache', account.id + '.json'), JSON.stringify({ messages: [message] }));+ return message;+}++beforeEach(() => {+ vi.clearAllMocks();+ doubles.files.clear();+ doubles.send.mockResolvedValue({ data: { id: 'api-message-1' } });+ doubles.list.mockResolvedValue({ data: { messages: [] } });+ doubles.get.mockResolvedValue({ data: {} });+ doubles.token.mockResolvedValue({ token: 'synthetic-token' });+ doubles.evaluate.mockResolvedValue({ notInInbox: true, error: 'Not found' });+ logs = ['log', 'warn', 'error'].map(method => vi.spyOn(console, method).mockImplementation(() => {}));+});+afterEach(() => vi.restoreAllMocks());++describe('mailbox operational log privacy', () => {+ it('creates and sends drafts without duplicating content, including provider failure diagnostics', async () => {+ const account = await createAccount({ ...PRIVATE, type: 'gmail' });+ const draft = await createDraft({ ...PRIVATE, to: [PRIVATE.email], accountId: account.id });+ await updateDraft(draft.id, { status: 'approved' });+ expect(await sendDraft(draft.id)).toEqual({ success: true });+ expect((await getDraft(draft.id)).status).toBe('sent');+ expect((await getDraft(draft.id)).body).toBe(PRIVATE.body);++ await updateDraft(draft.id, { status: 'approved' });+ doubles.send.mockRejectedValueOnce(failure());+ expect(await sendDraft(draft.id)).toMatchObject({ success: false, code: 'GMAIL_SEND_FAILED' });+ expect((await getDraft(draft.id)).status).toBe('failed');+ expect(output()).toContain(draft.id);+ expect(output()).toContain(account.id);+ expect(output()).toContain('HTTP 403');+ expect(output()).toContain('GMAIL_SEND_FAILED');+ expectPrivateOutputAbsent();+ });++ it('syncs accounts without names or addresses and keeps transport errors bounded', async () => {+ const account = await createAccount({ ...PRIVATE, type: 'gmail' });+ await syncAccount(account.id);+ doubles.list.mockRejectedValueOnce(failure());+ await syncAccount(account.id);+ expect(output()).toContain(account.id);+ expect(output()).toContain('HTTP 403');+ expectPrivateOutputAbsent();+ });++ it('does not log Outlook response bodies or token diagnostics while falling back', async () => {+ const account = await createAccount({ ...PRIVATE, type: 'outlook' });+ doubles.fetch.mockResolvedValue({ ok: false, status: 403, text: async () => failure().message });+ expect(await syncOutlookApi(account, {})).toMatchObject({ status: 'api-error' });+ doubles.token.mockResolvedValueOnce({ error: true, message: failure().message });+ expect(await syncOutlookApi(account, {})).toBeNull();+ doubles.evaluate.mockResolvedValueOnce([]);+ await syncPlaywright(account, { messages: [] });+ await sendPlaywright(account, PRIVATE);+ expect(output()).toContain('HTTP 403');+ expect(output()).toContain(account.id);+ expectPrivateOutputAbsent();+ });++ it('refreshes and removes an Outlook message without logging its subject', async () => {+ const account = await createAccount({ ...PRIVATE, type: 'outlook' });+ const message = seedMessage(account);+ doubles.evaluate.mockResolvedValueOnce({ found: false, hasListbox: true });+ await refreshMessage(account.id, message.id);+ expect(await executeAction(account.id, message.id, 'archive')).toMatchObject({ success: true });+ expect(await getMessage(account.id, message.id)).toBeNull();+ expect(output()).toContain(message.id);+ expectPrivateOutputAbsent();+ });++ it('archives and deletes Gmail messages through the API and browser fallback without subjects', async () => {+ const account = await createAccount({ ...PRIVATE, type: 'gmail' });+ for (const action of ['archive', 'delete']) {+ const message = seedMessage(account);+ expect(await executeAction(account.id, message.id, action)).toMatchObject({ success: true });+ expect(await getMessage(account.id, message.id)).toBeNull();+ }+ const message = seedMessage(account);+ delete message.apiId;+ doubles.files.set(join('/mock/messages/cache', account.id + '.json'), JSON.stringify({ messages: [message] }));+ expect(await executeAction(account.id, message.id, 'delete')).toMatchObject({ success: true });+ expect(doubles.modify).toHaveBeenCalledOnce();+ expect(doubles.trash).toHaveBeenCalledOnce();+ expect(output()).toContain(message.id);+ expectPrivateOutputAbsent();+ });+});diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.jsindex c41c571891..8cd99c40ea 100644--- a/server/services/messagePlaywrightSync.js+++ b/server/services/messagePlaywrightSync.js@@ -44,7 +44,7 @@ export async function launchProvider(accountType) {const url = accountType === 'teams' ? TEAMS_URL : OUTLOOK_URL;const page = await findOrOpenPage(url).catch(() => null);if (!page) return { success: false, error: 'Failed to open browser tab — is portos-browser running?' };- console.log(`📧 Launched ${accountType} in CDP browser: ${page.url}`);+ console.log(`📧 Launched ${accountType} in CDP browser`);return { success: true, url: page.url, pageId: page.id, title: page.title };}@@ -60,7 +60,7 @@ export async function launchProvider(accountType) {export async function syncPlaywright(account, cache, io, options = {}) {const mode = options.mode || 'unread';const targetUrl = account.type === 'teams' ? TEAMS_URL : OUTLOOK_URL;- console.log(`📧 Playwright sync (${mode}) for ${account.email} (${account.type})`);+ console.log(`📧 Playwright sync (${mode}) for account ${account.id} (${account.type})`);// Find the provider page in CDP browserconst page = await findOrOpenPage(targetUrl).catch(() => null);@@ -490,10 +490,10 @@ export async function refreshMessageDetail(account, message) {return { error: 'auth-required', message: 'Login required — sign into Outlook first' };}- console.log(`📧 Refresh: clicking into "${message.subject}"`);+ console.log(`📧 Refresh: clicking into ${message.id}`);const detail = await fetchOutlookConversationDetail(page, message.subject, message.from?.name);if (!detail) {- console.log(`📧 Refresh: click/extraction failed for "${message.subject}"`);+ console.log(`📧 Refresh: click/extraction failed for ${message.id}`);} else {console.log(`📧 Refresh: extracted ${detail.length} thread messages`);}@@ -504,7 +504,7 @@ export async function refreshMessageDetail(account, message) {* Send message via Playwright browser automation*/export async function sendPlaywright(account, draft) {- console.log(`📧 Playwright send for ${account.email} (${account.type}) — automation pending`);+ console.log(`📧 Playwright send for account ${account.id} (${account.type}) — automation pending`);return { success: false, error: 'Playwright send not yet implemented', status: 501, code: 'NOT_IMPLEMENTED' };}diff --git a/server/services/messageSender.js b/server/services/messageSender.jsindex 63ac06f25b..0474083242 100644--- a/server/services/messageSender.js+++ b/server/services/messageSender.js@@ -1,3 +1,4 @@+import { messageLogError } from '../lib/messageLogError.js';import { getDraft, updateDraft } from './messageDrafts.js';import { getAccount } from './messageAccounts.js';@@ -21,7 +22,7 @@ export async function sendDraft(draftId, io) {}await updateDraft(draftId, { status: 'sending' });- console.log(`📧 Sending draft "${draft.subject}" via ${draft.sendVia}`);+ console.log(`📧 Sending draft ${draft.id} via ${draft.sendVia}`);const dispatch = async () => {if (draft.sendVia === 'api') {@@ -33,7 +34,7 @@ export async function sendDraft(draftId, io) {};const result = await dispatch().catch(async (error) => {- console.error(`📧 Draft send threw for "${draft.subject}": ${error.message}`);+ console.error(`📧 Draft send threw for ${draft.id}: ${messageLogError(error)}`);return { success: false, status: 502, code: 'SEND_FAILED', error: error.message };});@@ -41,11 +42,11 @@ export async function sendDraft(draftId, io) {await updateDraft(draftId, { status: 'sent' });io?.emit('messages:draft:sent', { draftId });io?.emit('messages:changed', {});- console.log(`📧 Draft sent successfully: "${draft.subject}"`);+ console.log(`📧 Draft sent successfully: ${draft.id}`);} else {- await updateDraft(draftId, { status: 'failed' }).catch(err => console.warn(`⚠️ Failed to mark draft as failed: ${err.message}`));+ await updateDraft(draftId, { status: 'failed' }).catch(err => console.warn(`⚠️ Failed to mark draft as failed: ${messageLogError(err)}`));const errorMsg = result?.error ?? 'Unknown error sending draft';- console.log(`📧 Draft send failed: ${errorMsg}`);+ console.error(`📧 Draft send failed: ${messageLogError(result)}`);return { success: false, status: result?.status ?? 500, code: result?.code ?? 'SEND_FAILED', error: errorMsg };}diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 65f800259c..0ccff1b69b 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -1,3 +1,4 @@+import { messageLogError } from '../lib/messageLogError.js';import { createHash } from 'crypto';import { join } from 'path';@@ -159,7 +160,7 @@ export async function syncAccount(accountId, io, options = {}) {syncLocks.set(accountId, true);const mode = options.mode || 'unread';io?.emit('messages:sync:started', { accountId, mode });- console.log(`📧 Starting ${mode} sync for ${account.name} (${account.type})`);+ console.log(`📧 Starting ${mode} sync for account ${account.id} (${account.type})`);const providerSync = async () => {// The initial read may predate queued deletion. Recheck under the cache@@ -176,11 +177,11 @@ export async function syncAccount(accountId, io, options = {}) {// Try API sync first (fast), fall back to Playwright (slow)const { syncOutlookApi } = await import('./messageApiSync.js');providerResult = await syncOutlookApi(account, cache, io, { mode }).catch(err => {- console.log(`📧 API sync error, falling back to Playwright: ${err.message}`);+ console.log(`📧 API sync error, falling back to Playwright: ${messageLogError(err)}`);return null;});if (!providerResult) {- console.log(`📧 Falling back to Playwright sync for ${account.email}`);+ console.log(`📧 Falling back to Playwright sync for account ${account.id}`);const { syncPlaywright } = await import('./messagePlaywrightSync.js');providerResult = await syncPlaywright(account, cache, io, { mode });}@@ -242,7 +243,7 @@ export async function syncAccount(accountId, io, options = {}) {const before = cache.messages.length;cache.messages = cache.messages.filter(m => !m.externalId || fetchedIds.has(m.externalId));pruned = before - cache.messages.length;- if (pruned > 0) console.log(`🧹 Pruned ${pruned} stale messages from ${account.name}`);+ if (pruned > 0) console.log(`🧹 Pruned ${pruned} stale messages from account ${account.id}`);}// Trim to maxMessages@@ -261,7 +262,7 @@ export async function syncAccount(accountId, io, options = {}) {// prior auto-log failure self-heals on the next sync. Deduped per thread+day// (partial unique index), so re-scanning already-logged messages is a no-op.await logMessageTouchpoints(account, cache.messages).catch((err) =>- console.error(`🤝 Tribe auto-log failed for account ${accountId}: ${err.message}`));+ console.error(`🤝 Tribe auto-log failed for account ${accountId}: ${messageLogError(err)}`));// Apply + persist the owner's Gmail send-as aliases (#2831) BEFORE the activity// ingest below, so THIS sync's `messageActivityCandidates` already excludes every@@ -287,11 +288,11 @@ export async function syncAccount(accountId, io, options = {}) {let repaired = true;await repairActivityAliasParticipants(account, previousAliases, sendAsAliases).catch((err) => {repaired = false;- console.error(`🗓️ Activity alias backfill failed for account ${accountId} — deferring alias persist so the next sync retries: ${err.message}`);+ console.error(`🗓️ Activity alias backfill failed for account ${accountId} — deferring alias persist so the next sync retries: ${messageLogError(err)}`);});if (repaired) {await updateSendAsAliases(accountId, sendAsAliases).catch((err) =>- console.error(`📧 Send-as alias persist failed for account ${accountId}: ${err.message}`));+ console.error(`📧 Send-as alias persist failed for account ${accountId}: ${messageLogError(err)}`));}}@@ -303,7 +304,7 @@ export async function syncAccount(accountId, io, options = {}) {let activityIngestFailed = false;await recordMessageActivity(account, [...cache.messages, ...sentMessages]).catch((err) => {activityIngestFailed = true;- console.error(`🗓️ Activity ingest failed for account ${accountId}: ${err.message}`);+ console.error(`🗓️ Activity ingest failed for account ${accountId}: ${messageLogError(err)}`);});// Reply-detection watermark (#2796): stamp when a Gmail account with sent-ingest@@ -319,14 +320,14 @@ export async function syncAccount(accountId, io, options = {}) {// full watermark (or a stale recent one) would let a replied thread look// unanswered. Stamping partial keeps the account fail-closed until a clean sync.await markSentIngested(accountId, { partial: sentTruncated || activityIngestFailed }).catch((err) =>- console.error(`🤝 Sent-ingest watermark failed for account ${accountId}: ${err.message}`));+ console.error(`🤝 Sent-ingest watermark failed for account ${accountId}: ${messageLogError(err)}`));}io?.emit('messages:sync:completed', { accountId, newMessages: uniqueNew.length, pruned, status: providerStatus });if (providerStatus === 'success') {io?.emit('messages:changed', {});}- console.log(`📧 Sync complete for ${account.name}: ${uniqueNew.length} new, ${pruned} pruned, status=${providerStatus}`);+ console.log(`📧 Sync complete for account ${account.id}: ${uniqueNew.length} new, ${pruned} pruned, status=${providerStatus}`);return { newMessages: uniqueNew.length, pruned, total: cache.messages.length, status: providerStatus };};@@ -336,7 +337,7 @@ export async function syncAccount(accountId, io, options = {}) {// blocks a second concurrent sync; the tail additionally orders the sync's// write against the other cache mutators so none clobbers the others.const result = await queueAccountWrite(accountId, providerSync).catch(async (error) => {- console.error(`📧 Sync failed for ${account.name} (${account.type}): ${error.message}`);+ console.error(`📧 Sync failed for account ${account.id} (${account.type}): ${messageLogError(error)}`);await updateSyncStatus(accountId, 'error').catch(() => {});io?.emit('messages:sync:failed', { accountId, error: error.message });return { error: error.message, status: 502 };@@ -438,7 +439,7 @@ export async function refreshMessages(accountId, messageIds) {continue;}- console.log(`📧 Refreshing "${message.subject}" via ${account.type}`);+ console.log(`📧 Refreshing ${message.id} via ${account.type}`);const detail = await refreshMessageDetail(account, message);// Structured error from refreshMessageDetailif (detail && detail.error) {