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: preserve cached mail until inbox coverage is complete (#8526)
[._.]/ Adam Eivy569a96ae49db
diff --git a/server/services/messageApiSync.js b/server/services/messageApiSync.jsindex 34320fa3d9..9c3fbea27f 100644--- a/server/services/messageApiSync.js+++ b/server/services/messageApiSync.js@@ -52,6 +52,7 @@ export async function syncOutlookApi(account, cache, io, options = {}) {const messages = [];let url = baseUrl;let page = 0;+ let validMembership = true;while (url && messages.length < maxMessages) {page++;@@ -85,6 +86,10 @@ export async function syncOutlookApi(account, cache, io, options = {}) {const items = data.value;for (const m of items) {+ if (!m || typeof m.Id !== 'string' || !m.Id) {+ validMembership = false;+ continue;+ }const extId = makeExternalId('ol', m.Id);const msg = {id: uuidv4(),@@ -119,7 +124,9 @@ export async function syncOutlookApi(account, cache, io, options = {}) {}// Follow @odata.nextLink for pagination- url = data['@odata.nextLink'] || null;+ const nextLink = data['@odata.nextLink'];+ if (nextLink != null && (typeof nextLink !== 'string' || !nextLink)) validMembership = false;+ url = typeof nextLink === 'string' ? nextLink : null;if (messages.length >= maxMessages) break;}@@ -129,5 +136,5 @@ export async function syncOutlookApi(account, cache, io, options = {}) {}console.log(`📧 API sync complete: ${messages.length} messages fetched in ${page} page(s)`);- return { messages, status: 'success', syncMethod: 'api' };+ return { messages, inboxComplete: mode === 'full' && !url && validMembership, status: 'success', syncMethod: 'api' };}diff --git a/server/services/messageApiSync.test.js b/server/services/messageApiSync.test.jsindex 388de5835e..874fcb2c4f 100644--- a/server/services/messageApiSync.test.js+++ b/server/services/messageApiSync.test.js@@ -44,6 +44,7 @@ describe('syncOutlookApi — malformed-body masquerade guard', () => {const result = await syncOutlookApi(ACCOUNT, { messages: [] }, null, { mode: 'full' });expect(result.status).toBe('success');expect(result.messages).toEqual([]);+ expect(result.inboxComplete).toBe(true);});it('parses messages from a valid populated body', async () => {@@ -52,5 +53,32 @@ describe('syncOutlookApi — malformed-body masquerade guard', () => {expect(result.status).toBe('success');expect(result.messages).toHaveLength(1);expect(result.messages[0].subject).toBe('Hello');+ expect(result.inboxComplete).toBe(false);});+ it('does not certify a capped listing with another page', async () => {+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({+ value: Array.from({ length: 200 }, (_, i) => ({ Id: 'mail-' + i })),+ '@odata.nextLink': 'https://outlook.office.com/next',+ }));+ const result = await syncOutlookApi(ACCOUNT, {}, null, { mode: 'full' });+ expect(result.messages).toHaveLength(200);+ expect(result.inboxComplete).toBe(false);+ });++ it('certifies a full snapshot only after its last page', async () => {+ fetchWithTimeout.mockResolvedValueOnce(mockJsonResponse({+ value: [{ Id: 'a' }], '@odata.nextLink': 'https://outlook.office.com/next',+ })).mockResolvedValueOnce(mockJsonResponse({ value: [{ Id: 'b' }] }));+ const result = await syncOutlookApi(ACCOUNT, {}, null, { mode: 'full' });+ expect(result.messages).toHaveLength(2);+ expect(result.inboxComplete).toBe(true);+ });++ it('merges valid rows without certifying malformed membership', async () => {+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({ value: [{ Id: 'a' }, {}] }));+ const result = await syncOutlookApi(ACCOUNT, {}, null, { mode: 'full' });+ expect(result.messages).toHaveLength(1);+ expect(result.inboxComplete).toBe(false);+ });+});diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex 35ad6d7472..455ef0af9d 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -259,7 +259,19 @@ export async function syncGmail(account, cache, io, options = {}) {maxResults,...(pageToken && { pageToken }),});- return { messages: listResult.data.messages || [], nextPageToken: listResult.data.nextPageToken || null };+ const data = listResult.data;+ // Gmail omits messages for an empty inbox, but a missing/malformed body+ // cannot prove that the inbox is empty.+ if (!data || typeof data !== 'object' || Array.isArray(data)+ || (data.messages !== undefined && !Array.isArray(data.messages))+ || (data.nextPageToken !== undefined && typeof data.nextPageToken !== 'string')) {+ throw new Error('Malformed Gmail message listing');+ }+ const listed = data.messages ?? [];+ if (listed.some(item => !item || typeof item.id !== 'string' || !item.id)) {+ throw new Error('Malformed Gmail message ID');+ }+ return { messages: listed, nextPageToken: data.nextPageToken || null };},{ onProgress: (current) => io?.emit('messages:sync:progress', { accountId: account.id, current, total: totalCap }) },);@@ -289,7 +301,11 @@ export async function syncGmail(account, cache, io, options = {}) {));for (let j = 0; j < results.length; j++) {- if (!results[j]) { detailFetchFailures++; continue; }+ if (!results[j]?.data || results[j].data.id !== batch[j].id+ || !Array.isArray(results[j].data.labelIds) || !results[j].data.payload) {+ detailFetchFailures++;+ continue;+ }const data = results[j].data;const { id: gmailId, threadId: gmailThreadId } = batch[j];const headers = data.payload?.headers || [];@@ -361,7 +377,8 @@ export async function syncGmail(account, cache, io, options = {}) {}console.log(`📧 Gmail API sync complete: ${inboxMessages.length} inbox, ${sentMessages.length} sent (activity-only)`);- return { messages: inboxMessages, sentMessages, sentTruncated: sentCoveragePartial, sendAsAliases, status: 'success', syncMethod: 'api' };+ const inboxComplete = mode === 'full' && !truncated.includes(inboxQuery(mode)) && detailFetchFailures === 0;+ return { messages: inboxMessages, inboxComplete, sentMessages, sentTruncated: sentCoveragePartial, sendAsAliases, status: 'success', syncMethod: 'api' };}/**diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.jsindex 2021fbd8b1..c41c571891 100644--- a/server/services/messagePlaywrightSync.js+++ b/server/services/messagePlaywrightSync.js@@ -171,7 +171,8 @@ export async function syncPlaywright(account, cache, io, options = {}) {}console.log(`📧 Fetched detail for ${detailsFetched}/${extracted.length} conversations`);- return { messages, status: 'success' };+ // A bounded DOM scrape cannot prove complete inbox membership.+ return { messages, inboxComplete: false, status: 'success' };}/**diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 2c889d0adf..783de144e9 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -231,9 +231,10 @@ export async function syncAccount(accountId, io, options = {}) {}cache.messages.push(...uniqueNew);- // Reconcile: remove cached messages no longer present in inbox during full sync+ // Only explicit, exhaustive inbox coverage authorizes membership deletion.+ // Legacy arrays and bounded/partial successes still merge, but never prune.let pruned = 0;- if (mode === 'full' && providerStatus === 'success' && newMessages.length > 0) {+ if (mode === 'full' && providerStatus === 'success' && providerResult?.inboxComplete === true) {const fetchedIds = new Set(newMessages.filter(m => m.externalId).map(m => m.externalId));const before = cache.messages.length;cache.messages = cache.messages.filter(m => !m.externalId || fetchedIds.has(m.externalId));diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.jsindex 59857d2496..770bea9598 100644--- a/server/services/messageSync.test.js+++ b/server/services/messageSync.test.js@@ -35,9 +35,19 @@ vi.mock('../lib/fileUtils.js', () => ({vi.mock('./messageAccounts.js', () => ({getAccount: vi.fn(),updateSyncStatus: vi.fn(),- markSentIngested: vi.fn(() => Promise.resolve())+ markSentIngested: vi.fn(() => Promise.resolve()),+ updateSendAsAliases: vi.fn(() => Promise.resolve())}));+const gmailApi = vi.hoisted(() => ({ list: vi.fn(), get: vi.fn() }));+vi.mock('@googleapis/gmail', () => ({+ gmail: () => ({ users: {+ messages: gmailApi,+ settings: { sendAs: { list: async () => ({ data: { sendAs: [] } }) } },+ } }),+}));+vi.mock('./googleAuth.js', () => ({ getAuthenticatedClient: async () => ({}) }));+vi.mock('./messageGmailSync.js', () => ({syncGmail: vi.fn()}));@@ -92,7 +102,7 @@ import { readdir, unlink } from 'fs/promises';import { tryReadFile as readFile, atomicWrite } from '../lib/fileUtils.js';import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage, refreshMessages, updateMessageEvaluations, logMessageTouchpoints, aggregatePagedMessages } from './messageSync.js';import { autoLogTouchpoints } from './tribe.js';-import { getAccount, updateSyncStatus } from './messageAccounts.js';+import { getAccount, updateSyncStatus, markSentIngested } from './messageAccounts.js';import { syncGmail } from './messageGmailSync.js';import { syncPlaywright, refreshMessageDetail } from './messagePlaywrightSync.js';@@ -849,3 +859,84 @@ describe('logMessageTouchpoints — candidate building (#2033)', () => {expect(candidates[0].dedupeKey).toBe(`msg:${VALID_UUID}:thread-tz:2026-06-01`);});});++// Real Gmail adapter through persisted syncAccount: detail loss must not erase evaluations.+describe('full inbox coverage contract', () => {+ const externalId = id => 'api-gmail-' + createHash('md5').update(id).digest('hex').slice(0, 12);+ let saved;+ beforeEach(async () => {+ saved = { messages: [+ { id: 'local-a', externalId: externalId('a'), date: '2026-01-02' },+ { id: 'local-b', externalId: externalId('b'), date: '2026-01-01', evaluation: { priority: 'high' } },+ { id: 'local-only' },+ ] };+ readFile.mockImplementation(async () => JSON.stringify(saved));+ atomicWrite.mockImplementation(async (_path, data) => { saved = structuredClone(data); });+ getAccount.mockResolvedValue({ id: VALID_UUID, name: 'Example inbox', email: '[email protected]', type: 'gmail', enabled: true });+ syncGmail.mockImplementation((await vi.importActual('./messageGmailSync.js')).syncGmail);+ gmailApi.list.mockImplementation(async ({ q }) => ({+ data: { messages: q === 'in:inbox' ? [{ id: 'a' }, { id: 'b' }] : [] },+ }));+ gmailApi.get.mockImplementation(async ({ id }) => ({+ data: { id, labelIds: ['INBOX'], payload: { headers: [] } },+ }));+ });++ it('preserves identity and evaluation through failure and retry, then reconciles complete snapshots', async () => {+ gmailApi.get.mockImplementationOnce(async () => ({+ data: { id: 'a', labelIds: ['INBOX', 'UNREAD'], payload: { headers: [] } },+ })).mockRejectedValueOnce(new Error('temporary detail failure'));+ await syncAccount(VALID_UUID, null, { mode: 'full' });+ expect(saved.messages).toHaveLength(3);+ expect(saved.messages[0]).toMatchObject({ id: 'local-a', isUnread: true });+ expect(saved.messages[1]).toMatchObject({ id: 'local-b', evaluation: { priority: 'high' } });+ expect(markSentIngested).toHaveBeenLastCalledWith(VALID_UUID, expect.objectContaining({ partial: true }));+ await syncAccount(VALID_UUID, null, { mode: 'full' });+ expect(saved.messages[1]).toMatchObject({ id: 'local-b', evaluation: { priority: 'high' } });+ gmailApi.list.mockResolvedValue({ data: { messages: [{ id: 'b' }] } });+ await syncAccount(VALID_UUID, null, { mode: 'full' });+ expect(saved.messages.map(m => m.id)).toEqual(['local-b', 'local-only']);+ gmailApi.list.mockResolvedValue({ data: {} });+ await syncAccount(VALID_UUID, null, { mode: 'full' });+ expect(saved.messages).toEqual([{ id: 'local-only' }]);+ });++ it('retains unseen mail when the Gmail inbox reaches its cap', async () => {+ gmailApi.list.mockImplementation(async ({ q, maxResults, pageToken }) => ({+ data: q === 'in:inbox' ? {+ messages: Array.from({ length: maxResults }, (_, i) => ({ id: 'new-' + (Number(pageToken || 0) + i) })),+ nextPageToken: String(Number(pageToken || 0) + maxResults),+ } : {},+ }));+ await syncAccount(VALID_UUID, null, { mode: 'full' });+ expect(saved.messages.find(m => m.id === 'local-b')).toMatchObject({ evaluation: { priority: 'high' } });+ expect(saved.messages).toHaveLength(203);+ });++ it.each([+ ['legacy array', [{ id: 'new', externalId: 'new' }], 'full'],+ ['unproven browser success', { messages: [], status: 'success', inboxComplete: false }, 'full'],+ ['unread snapshot', { messages: [], status: 'success', inboxComplete: true }, 'unread'],+ ['partial status', { messages: [], status: 'partial', inboxComplete: true }, 'full'],+ ])('does not prune on %s', async (_name, result, mode) => {+ syncGmail.mockResolvedValue(result);+ await syncAccount(VALID_UUID, null, { mode });+ expect(saved.messages.find(m => m.id === 'local-b')).toMatchObject({ evaluation: { priority: 'high' } });+ });++ it('keeps configured retention independent of incomplete membership', async () => {+ getAccount.mockResolvedValue({ id: VALID_UUID, type: 'gmail', enabled: true, syncConfig: { maxMessages: 1 } });+ syncGmail.mockResolvedValue({ messages: [], status: 'success', inboxComplete: false });+ await syncAccount(VALID_UUID, null, { mode: 'full' });+ expect(saved.messages.map(m => m.id)).toEqual(['local-a']);+ });++ it('does not certify malformed details or listings', async () => {+ gmailApi.get.mockResolvedValue({ data: {} });+ await syncAccount(VALID_UUID, null, { mode: 'full' });+ expect(saved.messages).toHaveLength(3);+ gmailApi.list.mockResolvedValue({ data: { messages: 'invalid' } });+ expect(await syncAccount(VALID_UUID, null, { mode: 'full' })).toMatchObject({ status: 502 });+ expect(saved.messages).toHaveLength(3);+ });+});