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 (claude): resolve email inbound to Tribe sender; give sent mail its own fetch budget
[._.]/ Adam Eivyced6b08c0202
diff --git a/server/services/humanActivity.js b/server/services/humanActivity.jsindex 6f04e4822b..7fb0a6682d 100644--- a/server/services/humanActivity.js+++ b/server/services/humanActivity.js@@ -178,6 +178,10 @@ export function messageActivityCandidates(account, messages = []) {const externalId = message.externalId || message.id;if (!externalId) continue;const fromEmail = participantEmail(message.from);+ // Direction by exact From-vs-owner match. NOTE: a reply sent from a Gmail+ // "send-as" alias (From ≠ account.email) is classified as received, not sent —+ // send-as aliases aren't stored per account, so we can't recognize them here.+ // Bounded impact: such a reply won't cancel its inbound in outreach detection.const sent = Boolean(selfEmail) && fromEmail === selfEmail;const participants = normalizeParticipants([message.from,@@ -197,6 +201,14 @@ export function messageActivityCandidates(account, messages = []) {threadId: message.threadId || null,externalId,channel: source,+ // The counterpart handle for a RECEIVED message is the sender's email —+ // set it so `enrichActivityEvent` (which resolves the top-level personId+ // from `metadata.handle`) can tag the Tribe sender, exactly as the iMessage+ // mapper does. Without this, email inbound never resolves to a person and+ // Tribe-outreach detection (#2796) drops every Gmail thread. Sent turns+ // carry no counterpart handle (mirrors iMessage); email threads group by+ // `threadId`, so handle is never the grouping key here.+ handle: sent ? null : (fromEmail || null),},});}diff --git a/server/services/humanActivity.test.js b/server/services/humanActivity.test.jsindex fc359f0545..3662bcc69e 100644--- a/server/services/humanActivity.test.js+++ b/server/services/humanActivity.test.js@@ -174,6 +174,17 @@ describe('messageActivityCandidates', () => {expect(messageActivityCandidates(account, [{ subject: 'no date' }])).toEqual([]);expect(messageActivityCandidates(account, [{ date: '2026-07-04T10:00:00Z' }])).toEqual([]);});+ it('sets metadata.handle to the sender email on received mail so the Tribe sender resolves (#2796)', () => {+ // enrichActivityEvent derives the top-level personId from metadata.handle; without+ // it, every email inbound is dropped and Tribe-outreach detection surfaces nothing.+ const [received, sent] = messageActivityCandidates(account, [+ { externalId: 'e1', date: '2026-07-04T10:00:00Z', from: '[email protected]', to: ['[email protected]'], subject: 'Hey' },+ { externalId: 'e2', date: '2026-07-04T11:00:00Z', from: '[email protected]', to: ['[email protected]'], subject: 'Re: Hey' },+ ]);+ expect(received.metadata.handle).toBe('[email protected]');+ // Sent turns carry no counterpart handle (mirrors iMessage); email groups by threadId.+ expect(sent.metadata.handle).toBeNull();+ });});describe('calendarActivityCandidates', () => {diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex bf54025a8f..eb3d2f5837 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -13,25 +13,44 @@ function makeExternalId(gmailId) {return 'api-gmail-' + crypto.createHash('md5').update(gmailId).digest('hex').slice(0, 12);}-// How far back to pull sent mail when reply-detection ingestion is on. Bounds the-// sent-folder fetch to the Tribe-outreach detection window (DEFAULT_WITHIN_DAYS=14-// in tribeOutreach.js) so a large sent folder can't crowd out inbox results — sent-// mail older than the window can't answer an inbound that's still actionable.+// How far back to pull sent mail when reply-detection ingestion is on. Must stay+// >= tribeOutreach's DEFAULT_WITHIN_DAYS (14) — a reply older than the detection+// window can't answer an inbound that's still actionable, so no need to ingest it;+// but if this were SHORTER than the window, a reply inside the window would be+// missed and its inbound would falsely read as unanswered. The coupling is pinned+// by a test in messageGmailSync.test.js.export const SENT_INGEST_DAYS = 14;+// Sent mail gets its OWN fetch budget (a separate list pass), NOT a share of the+// inbox cap: a heavy sender can send >100 mails in 14 days, and folding sent into+// one shared-cap query would evict unread-inbox messages from the primary sync.+// 14 days of a normal person's replies fit comfortably under this.+export const SENT_INGEST_MAX = 50;++// The inbox search query for a sync mode. `unread` scopes to unread inbox; `full`+// takes the whole inbox (capped downstream).+export function inboxQuery(mode) {+ return mode === 'unread' ? 'is:unread in:inbox' : 'in:inbox';+}++// Recent sent mail — no unread state, bounded by date instead. Ingested so it lands+// in the same cache the human-activity timeline reads, recording `message.sent`+// events that let Tribe-outreach detection see a Gmail thread as replied (#2796).+export function sentQuery() {+ return `in:sent newer_than:${SENT_INGEST_DAYS}d`;+}+/**- * Build the Gmail search query. Inbox is always fetched; when `ingestSent` is on- * (the per-account default, opt out via `syncConfig.ingestSent === false`) recent- * sent mail is ALSO fetched so it lands in the same cache the human-activity- * timeline ingests — recording `message.sent` events that let Tribe-outreach- * detection see a Gmail thread as replied (#2796). `unread` mode still only scopes- * the INBOX half to unread; sent mail has no unread state and is bounded by- * `newer_than` instead.+ * The ordered (query, cap) list-passes for one Gmail sync. Inbox always runs with+ * the full `inboxCap`; recent sent mail runs as a SEPARATE pass with its own+ * `SENT_INGEST_MAX` budget when the account opts into reply-detection ingestion+ * (the per-account default, opt out via `syncConfig.ingestSent === false`). Separate+ * passes mean sent volume never crowds the inbox out of a shared cap.*/-export function buildGmailQuery(mode, ingestSent) {- const inbox = mode === 'unread' ? 'is:unread in:inbox' : 'in:inbox';- if (!ingestSent) return inbox;- return `(${inbox}) OR (in:sent newer_than:${SENT_INGEST_DAYS}d)`;+export function gmailSyncPasses(mode, ingestSent, inboxCap) {+ const passes = [{ query: inboxQuery(mode), cap: inboxCap }];+ if (ingestSent) passes.push({ query: sentQuery(), cap: SENT_INGEST_MAX });+ return passes;}function getHeader(headers, name) {@@ -146,28 +165,40 @@ export async function syncGmail(account, cache, io, options = {}) {// Ingest sent mail unless the account explicitly opted out — the default-on// capability powers per-account Tribe-outreach reply detection (#2796).const ingestSent = account?.syncConfig?.ingestSent !== false;- const query = buildGmailQuery(mode, ingestSent);+ 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}`);- // Step 1: List message IDs+ // Step 1: List message IDs — one pass per (query, cap). Dedupe across passes by+ // gmail id (a thread can appear in both inbox and sent) so a message is fetched+ // and recorded once.const messageIds = [];- let pageToken = null;-- do {- io?.emit('messages:sync:progress', { accountId: account.id, current: messageIds.length, total: maxMessages });-- const listResult = await gmailClient.users.messages.list({- userId: 'me',- q: query,- maxResults: Math.min(100, maxMessages - messageIds.length),- ...(pageToken && { pageToken })- });-- const items = listResult.data.messages || [];- messageIds.push(...items);- pageToken = listResult.data.nextPageToken;- } while (pageToken && messageIds.length < maxMessages);+ const seenGmailIds = new Set();++ for (const pass of passes) {+ let pageToken = null;+ let fetched = 0;+ do {+ io?.emit('messages:sync:progress', { accountId: account.id, current: messageIds.length, total: totalCap });++ const listResult = await gmailClient.users.messages.list({+ userId: 'me',+ q: pass.query,+ maxResults: Math.min(100, pass.cap - fetched),+ ...(pageToken && { pageToken })+ });++ const items = listResult.data.messages || [];+ fetched += items.length;+ for (const item of items) {+ if (seenGmailIds.has(item.id)) continue;+ seenGmailIds.add(item.id);+ messageIds.push(item);+ }+ pageToken = listResult.data.nextPageToken;+ } while (pageToken && fetched < pass.cap);+ }console.log(`📧 Gmail: found ${messageIds.length} message IDs, fetching details`);diff --git a/server/services/messageGmailSync.test.js b/server/services/messageGmailSync.test.jsindex f290165e26..a64eeca218 100644--- a/server/services/messageGmailSync.test.js+++ b/server/services/messageGmailSync.test.js@@ -1,24 +1,54 @@import { describe, it, expect } from 'vitest';-import { buildGmailQuery, SENT_INGEST_DAYS } from './messageGmailSync.js';+import {+ inboxQuery,+ sentQuery,+ gmailSyncPasses,+ SENT_INGEST_DAYS,+ SENT_INGEST_MAX,+} from './messageGmailSync.js';+import { DEFAULT_WITHIN_DAYS } from './tribeOutreach.js';-// buildGmailQuery is the pure search-query core (#2796). Inbox is always scoped;-// sent mail is folded in only when the account opts into reply-detection ingestion,-// bounded to the outreach detection window so a big sent folder can't crowd out-// inbox results.-describe('buildGmailQuery', () => {- it('inbox-only when ingestSent is off', () => {- expect(buildGmailQuery('unread', false)).toBe('is:unread in:inbox');- expect(buildGmailQuery('full', false)).toBe('in:inbox');+// The Gmail sync's search-query core (#2796). Inbox and sent are fetched as+// SEPARATE list passes so a heavy sender's sent mail can't crowd unread inbox out+// of a shared cap.+describe('inboxQuery / sentQuery', () => {+ it('scopes the inbox pass to unread only in unread mode', () => {+ expect(inboxQuery('unread')).toBe('is:unread in:inbox');+ expect(inboxQuery('full')).toBe('in:inbox');});- it('folds recent sent mail in when ingestSent is on, keeping the unread scope on inbox only', () => {- expect(buildGmailQuery('unread', true)).toBe(`(is:unread in:inbox) OR (in:sent newer_than:${SENT_INGEST_DAYS}d)`);- expect(buildGmailQuery('full', true)).toBe(`(in:inbox) OR (in:sent newer_than:${SENT_INGEST_DAYS}d)`);+ it('bounds the sent pass by date to the detection window', () => {+ expect(sentQuery()).toBe(`in:sent newer_than:${SENT_INGEST_DAYS}d`);+ expect(SENT_INGEST_DAYS).toBe(14);});+});- it('bounds the sent fetch to the 14-day outreach detection window', () => {- expect(SENT_INGEST_DAYS).toBe(14);- expect(buildGmailQuery('full', true)).toContain('newer_than:14d');+describe('gmailSyncPasses', () => {+ it('is inbox-only (own cap) when ingestSent is off', () => {+ expect(gmailSyncPasses('unread', false, 100)).toEqual([+ { query: 'is:unread in:inbox', cap: 100 },+ ]);+ expect(gmailSyncPasses('full', false, 200)).toEqual([+ { query: 'in:inbox', cap: 200 },+ ]);+ });++ it('adds a separate sent pass with its OWN budget when ingestSent is on', () => {+ expect(gmailSyncPasses('unread', true, 100)).toEqual([+ { query: 'is:unread in:inbox', cap: 100 },+ { query: `in:sent newer_than:${SENT_INGEST_DAYS}d`, cap: SENT_INGEST_MAX },+ ]);+ // The inbox cap is untouched — sent mail never eats into it.+ expect(gmailSyncPasses('full', true, 200)[0]).toEqual({ query: 'in:inbox', cap: 200 });+ });+});++// Constant-coupling guard: the sent-fetch window must cover the outreach detection+// window, or a reply inside the window would be missed and its inbound would+// falsely read as unanswered.+describe('sent-ingest window covers the outreach detection window', () => {+ it('SENT_INGEST_DAYS >= DEFAULT_WITHIN_DAYS', () => {+ expect(SENT_INGEST_DAYS).toBeGreaterThanOrEqual(DEFAULT_WITHIN_DAYS);});});