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
feat([issue-2796]): extend Tribe unanswered-thread detection to Gmail via per-account sent ingestion
[._.]/ Adam Eivy6594bc2f671a
diff --git a/client/src/components/messages/ConfigTab.jsx b/client/src/components/messages/ConfigTab.jsxindex 11d12a9743..5f1b156e6b 100644--- a/client/src/components/messages/ConfigTab.jsx+++ b/client/src/components/messages/ConfigTab.jsx@@ -174,6 +174,22 @@ export default function ConfigTab({ accounts, setAccounts }) {setAccounts(prev => prev.map(a => a.id === account.id ? { ...a, enabled: !a.enabled } : a));};+ // Per-account reply detection: ingest sent mail so Tribe-outreach won't nudge an+ // already-replied thread (#2796). Default-on for Gmail (absent === on).+ const handleToggleIngestSent = async (account) => {+ const next = account.syncConfig?.ingestSent === false; // flipping to enabled+ const result = await api.updateMessageAccount(+ account.id,+ { syncConfig: { ...account.syncConfig, ingestSent: next } },+ { silent: true }+ ).catch(() => null);+ if (!result) return toast.error('Failed to update account');+ toast.success(next ? 'Reply detection enabled' : 'Reply detection disabled');+ setAccounts(prev => prev.map(a => a.id === account.id+ ? { ...a, syncConfig: { ...a.syncConfig, ingestSent: next } }+ : a));+ };+const handleClearCache = async (accountId) => {if (confirmClear !== accountId) {setConfirmClear(accountId);@@ -355,6 +371,19 @@ export default function ConfigTab({ accounts, setAccounts }) {</div></div><div className="flex items-center gap-2">+ {account.type === 'gmail' && (+ <button+ onClick={() => handleToggleIngestSent(account)}+ className={`px-2 py-1 rounded text-xs transition-colors ${+ account.syncConfig?.ingestSent !== false+ ? 'bg-port-accent/20 text-port-accent'+ : 'bg-gray-700 text-gray-400'+ }`}+ title="Ingest sent mail so Tribe outreach won't nudge threads you've already replied to"+ >+ {account.syncConfig?.ingestSent !== false ? 'Reply detection: on' : 'Reply detection: off'}+ </button>+ )}<buttononClick={() => handleToggle(account)}className={`px-2 py-1 rounded text-xs transition-colors ${diff --git a/server/routes/messages.js b/server/routes/messages.jsindex 9f835f97a8..b92a382d17 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -28,7 +28,9 @@ const createAccountSchema = z.object({syncConfig: z.object({maxAge: z.string().optional(),maxMessages: z.number().int().positive().optional(),- syncInterval: z.number().int().positive().optional()+ syncInterval: z.number().int().positive().optional(),+ // Per-account reply-detection ingestion (Gmail sent mail → timeline). #2796.+ ingestSent: z.boolean().optional()}).optional()});@@ -39,7 +41,9 @@ const updateAccountSchema = z.object({syncConfig: z.object({maxAge: z.string().optional(),maxMessages: z.number().int().positive().optional(),- syncInterval: z.number().int().positive().optional()+ syncInterval: z.number().int().positive().optional(),+ // Per-account reply-detection ingestion (Gmail sent mail → timeline). #2796.+ ingestSent: z.boolean().optional()}).optional()});diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.jsindex 2b58f68608..18881598b0 100644--- a/server/services/messageAccounts.js+++ b/server/services/messageAccounts.js@@ -41,7 +41,13 @@ export async function createAccount(data) {syncConfig: {maxAge: data.syncConfig?.maxAge || '30d',maxMessages: data.syncConfig?.maxMessages || 500,- syncInterval: data.syncConfig?.syncInterval || 300000+ syncInterval: data.syncConfig?.syncInterval || 300000,+ // Ingest sent mail into the human-activity timeline as `message.sent` events+ // so Tribe-outreach reply detection can see a thread as answered (#2796).+ // Only Gmail has a sent-fetch path today; default it on there, off elsewhere.+ // Absent (existing accounts) is treated as on for Gmail by the readers, so a+ // migration isn't needed — this only makes new accounts' stored state explicit.+ ingestSent: data.syncConfig?.ingestSent ?? (data.type === 'gmail')},lastSyncAt: null,lastSyncStatus: null,diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex 389d36f72a..bf54025a8f 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -13,6 +13,27 @@ 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.+export const SENT_INGEST_DAYS = 14;++/**+ * 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.+ */+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)`;+}+function getHeader(headers, name) {return headers?.find(h => h.name.toLowerCase() === name.toLowerCase())?.value || '';}@@ -122,9 +143,12 @@ export async function syncGmail(account, cache, io, options = {}) {const gmailClient = gmail({ version: 'v1', auth });const maxMessages = mode === 'full' ? 200 : 100;- const query = mode === 'unread' ? 'is:unread in:inbox' : 'in:inbox';+ // 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);- console.log(`📧 Gmail API sync (${mode}) for ${account.email}`);+ console.log(`📧 Gmail API sync (${mode}${ingestSent ? '+sent' : ''}) for ${account.email}`);// Step 1: List message IDsconst messageIds = [];diff --git a/server/services/messageGmailSync.test.js b/server/services/messageGmailSync.test.jsnew file mode 100644index 0000000000..f290165e26--- /dev/null+++ b/server/services/messageGmailSync.test.js@@ -0,0 +1,24 @@+import { describe, it, expect } from 'vitest';++import { buildGmailQuery, SENT_INGEST_DAYS } from './messageGmailSync.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');+ });++ 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 fetch to the 14-day outreach detection window', () => {+ expect(SENT_INGEST_DAYS).toBe(14);+ expect(buildGmailQuery('full', true)).toContain('newer_than:14d');+ });+});diff --git a/server/services/tribeOutreach.js b/server/services/tribeOutreach.jsindex 8cfe02c0f5..f1a95870e6 100644--- a/server/services/tribeOutreach.js+++ b/server/services/tribeOutreach.js@@ -17,10 +17,11 @@* and files a DRAFT through `messageDrafts.createDraft`. It NEVER auto-sends —* the user reviews/approves/sends through the existing draft pipeline.*- * The detection layer is source-agnostic: it works across every message source- * that records `message.sent`/`message.received` activity events — Gmail/Outlook- * (#2033), iMessage (#2151), Signal (#2154) — because it keys off the timeline,- * not any one provider's cache.+ * The detection layer is source-agnostic in shape but gated to sources whose+ * ingestion records BOTH directions per conversation, so an "unanswered" verdict is+ * trustworthy: iMessage (#2151) and Signal (#2154) source-wide, and Gmail (#2033)+ * PER ACCOUNT once its sent mail is ingested as `message.sent` (#2796). See+ * `buildTwoWayGate` for the per-account gate.*/import { ServerError } from '../lib/errorHandler.js';@@ -47,13 +48,58 @@ const MESSAGE_KINDS = new Set(['message.sent', 'message.received']);// retroactive backfill would need to re-read chat.db by rowid (macOS + Full Disk// Access only), so it's deliberately not attempted here.//-// Sources whose ingestion records BOTH directions per conversation, so an-// "unanswered" verdict is trustworthy. iMessage (#2151) and Signal (#2154) emit a-// `message.sent` for every outgoing turn; email sync ingests the inbox only (no-// `message.sent`), so a reply is invisible to the timeline and every stale inbound-// would read as unanswered forever. Email/other one-way sources are deferred until-// per-account sent/replied ingestion exists — see #2796.-const TWO_WAY_SOURCES = new Set(['imessage', 'signal']);+// Chat sources ingest BOTH directions per conversation intrinsically — iMessage+// (#2151) and Signal (#2154) emit a `message.sent` for every outgoing turn — so an+// "unanswered" verdict is always trustworthy regardless of which account it came+// through. They are two-way source-wide.+const TWO_WAY_CHAT_SOURCES = new Set(['imessage', 'signal']);++// Email sources can ALSO be two-way, but only PER ACCOUNT (#2796). Gmail's API+// sync gained an opt-out `syncConfig.ingestSent` (default on) that pulls `in:sent`+// into the same cache the timeline ingest reads, so a replied thread cancels its+// own inbound via the existing `lastSentT >= inbound` answered-check. The gate must+// key on the specific accountId, NOT the source: a source-wide gate would let ONE+// gmail account's sent import vouch for EVERY gmail account — including ones with no+// sent evidence, whose every stale inbound would then read as unanswered forever.+// Outlook/Teams ingest the inbox only (no sent-fetch path yet), so they stay+// one-way until one is added — an inbound from them is never surfaced.+const SENT_INGEST_SOURCES = new Set(['gmail']);++/**+ * Pure per-account two-way gate (unit-tested without a DB). Given the message-+ * account list, returns the sources worth scanning and an `isTwoWay(event)`+ * predicate. An email account counts as two-way only when ALL of: its provider has+ * a sent-ingest path (`SENT_INGEST_SOURCES`), it isn't opted out+ * (`syncConfig.ingestSent !== false` — absent means the default-on capability), AND+ * it has an owner email set. The email is required because sent-vs-received+ * direction is derived from sender === owner (see `messageActivityCandidates`); with+ * no owner email, an account never produces `message.sent` events, so trusting it+ * would make every inbound read as unanswered.+ *+ * @param {Array} accounts message-account records ({ id, type, email, syncConfig })+ * @returns {{ sources: string[], isTwoWay: (ev: object) => boolean }}+ */+export function buildTwoWayGate(accounts = []) {+ const twoWayEmailAccountIds = new Set(+ (accounts || [])+ .filter((a) =>+ SENT_INGEST_SOURCES.has(a?.type) &&+ a?.syncConfig?.ingestSent !== false &&+ String(a?.email || '').trim() !== '')+ .map((a) => a.id)+ );+ // Only scan an email source when at least one of its accounts is two-way — a+ // one-way-only provider is never queried, so a high-volume inbox can't burn the+ // per-source 2000-row cap on data we'd discard anyway.+ const sources = new Set(TWO_WAY_CHAT_SOURCES);+ for (const a of accounts || []) {+ if (twoWayEmailAccountIds.has(a?.id)) sources.add(a.type);+ }+ const isTwoWay = (ev) =>+ TWO_WAY_CHAT_SOURCES.has(ev?.source) ||+ (ev?.accountId != null && twoWayEmailAccountIds.has(ev.accountId));+ return { sources: [...sources], isTwoWay };+}// Channel-appropriate reply prompt for chat outreach — generateReplyBody's default// template is email-toned ("Write a professional reply to this email"), which reads@@ -175,13 +221,20 @@ export async function findUnansweredTribeThreads({staleAfterHours = DEFAULT_STALE_HOURS,limit = DEFAULT_LIMIT,} = {}) {- const [{ listEvents }, { loadResolverContext, enrichActivityEvent }] = await Promise.all([+ const [{ listEvents }, { loadResolverContext, enrichActivityEvent }, { listAccounts }] = await Promise.all([import('./humanActivity.js'),import('./identityResolve.js'),+ import('./messageAccounts.js'),]);const ctx = await loadResolverContext().catch(() => null);if (!ctx) return [];+ // Per-account two-way gate: which sources to scan, and which inbound events are+ // trustworthy (chat source-wide, email only from sent-ingesting accounts).+ const { sources: twoWaySources, isTwoWay } = buildTwoWayGate(+ await listAccounts().catch(() => [])+ );+ if (twoWaySources.length === 0) return [];const ringById = new Map((ctx.people || []).map((p) => [p.id, p.ring]));const nameById = new Map((ctx.people || []).map((p) => [p.id, p.name]));// No non-external Tribe people → nothing to nudge about; skip the timeline scan.@@ -197,7 +250,7 @@ export async function findUnansweredTribeThreads({// mark a thread answered.const received = [];const sent = [];- await Promise.all([...TWO_WAY_SOURCES].map((src) =>+ await Promise.all(twoWaySources.map((src) =>// Fail CLOSED per source: if EITHER direction's query fails, drop this source's// turns entirely. Substituting [] for only the failed direction would leave// received without its sent counterpart, making every inbound look unanswered@@ -222,10 +275,15 @@ export async function findUnansweredTribeThreads({// Drop Tapbacks/reactions from both directions — a reaction is not a message// awaiting a reply (it must not anchor an "unanswered" thread), and a sent- // reaction is not a real reply (it must not mark a thread answered).- const tagged = sent.filter((ev) => !ev.metadata?.isReaction);+ // reaction is not a real reply (it must not mark a thread answered). Also drop any+ // event from a non-two-way account: querying source `gmail` returns events from+ // ALL gmail accounts, but only the sent-ingesting ones are trustworthy — a reply+ // from a one-way account is invisible, so its inbound must not surface (and its+ // sent turns, if any lingered, must not vouch for another account's thread).+ const tagged = sent.filter((ev) => !ev.metadata?.isReaction && isTwoWay(ev));for (const ev of received) {if (ev.metadata?.isReaction) continue;+ if (!isTwoWay(ev)) continue;// Scope to 1:1 conversations — a chat with more than one counterpart is a// group, where "you never replied" rarely means a personal obligation and// multi-sender turns can't be cleanly attributed or anchored. A 1:1 chat's@@ -276,9 +334,11 @@ const inflightOutreach = new Map();* it through the existing draft-then-approve pipeline. USER-ACTION-GATED: only ever* called from an explicit request (the Tribe Outreach panel / an opt-in automation)* — it is the single LLM entry point here and must never be wired into a boot/sweep- * path. Detection only surfaces the two-way chat sources (iMessage/Signal), which- * carry no message account and no programmatic send channel, so the draft is always- * grounded from the timeline and filed as review-only — never auto-sent.+ * path. Detection surfaces the two-way sources — chat (iMessage/Signal) plus+ * sent-ingesting Gmail accounts (#2796) — grounding the reply from the timeline by+ * the detected conversation key (chatGuid / conversationId / threadId / handle). The+ * draft is always filed as review-only (`sendVia: 'review'`) — never auto-sent, even+ * for email, which the user approves/sends through the existing draft pipeline.** @returns {Promise<{ draft, person: { id, name } | null }>}*/diff --git a/server/services/tribeOutreach.test.js b/server/services/tribeOutreach.test.jsindex a2ee244b65..9c0da74fcb 100644--- a/server/services/tribeOutreach.test.js+++ b/server/services/tribeOutreach.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { groupUnansweredThreads, generateOutreachDraft } from './tribeOutreach.js';+import { groupUnansweredThreads, generateOutreachDraft, buildTwoWayGate } from './tribeOutreach.js';// generateOutreachDraft dynamically imports these — mock them so the draft-side// logic (idempotent reuse, anchoring the reply to the detected inbound) is@@ -161,6 +161,54 @@ describe('groupUnansweredThreads', () => {});});+describe('buildTwoWayGate (per-account #2796)', () => {+ const gmail = (over) => ({ id: 'g1', type: 'gmail', email: '[email protected]', syncConfig: {}, ...over });++ it('chat sources are always two-way, no account needed', () => {+ const { sources, isTwoWay } = buildTwoWayGate([]);+ expect(sources).toEqual(expect.arrayContaining(['imessage', 'signal']));+ expect(isTwoWay({ source: 'imessage' })).toBe(true);+ expect(isTwoWay({ source: 'signal', accountId: null })).toBe(true);+ });++ it('a Gmail account with an email and default (absent) ingestSent is two-way', () => {+ const { sources, isTwoWay } = buildTwoWayGate([gmail()]);+ expect(sources).toContain('gmail');+ expect(isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(true);+ });++ it('opting a Gmail account out (ingestSent:false) drops it from the gate', () => {+ const { sources, isTwoWay } = buildTwoWayGate([gmail({ syncConfig: { ingestSent: false } })]);+ expect(sources).not.toContain('gmail');+ expect(isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(false);+ });++ it('a Gmail account with no owner email is NOT two-way (sent direction underivable)', () => {+ const { isTwoWay } = buildTwoWayGate([gmail({ email: '' })]);+ expect(isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(false);+ });++ it('does NOT let one Gmail account vouch for another (per-account, not source-wide)', () => {+ // g1 ingests sent; g2 opted out. Both are source `gmail`, but only g1's events+ // are trustworthy — a source-wide gate would wrongly trust g2's inbound too.+ const gate = buildTwoWayGate([+ gmail({ id: 'g1' }),+ gmail({ id: 'g2', email: '[email protected]', syncConfig: { ingestSent: false } }),+ ]);+ expect(gate.sources).toContain('gmail'); // scanned because g1 is two-way+ expect(gate.isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(true);+ expect(gate.isTwoWay({ source: 'gmail', accountId: 'g2' })).toBe(false);+ });++ it('Outlook is never two-way (no sent-fetch path yet), even with ingestSent:true', () => {+ const { sources, isTwoWay } = buildTwoWayGate([+ { id: 'o1', type: 'outlook', email: '[email protected]', syncConfig: { ingestSent: true } },+ ]);+ expect(sources).not.toContain('outlook');+ expect(isTwoWay({ source: 'outlook', accountId: 'o1' })).toBe(false);+ });+});+describe('generateOutreachDraft', () => {beforeEach(() => {vi.clearAllMocks();