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 (codex): activity-only sent mail, reliability watermark, alias direction, email draft tone
[._.]/ Adam Eivyaa5340353688
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 91e2627f67..41c47162e5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,7 +22,7 @@## Tribe outreach-- **[issue-2796]** Tribe unanswered-thread nudges now cover Gmail, not just iMessage/Signal: Gmail sync ingests your recent sent mail into the activity timeline (per-account, default-on, opt out via a new "Reply detection" toggle in Messages > Config), so a thread you've already replied to is no longer surfaced as needing outreach while a genuinely unanswered email within the window still is.+- **[issue-2796]** Tribe unanswered-thread nudges now cover Gmail, not just iMessage/Signal: Gmail sync ingests your recent sent mail into the activity timeline (as activity only — sent mail never enters your inbox), so a thread you've already replied to is no longer surfaced as needing outreach while a genuinely unanswered email within the window still is. Reply detection is per-account (default-on for Gmail, opt out via a new "Reply detection" toggle in Messages > Config), only trusts an account once its sent history is actually present and current (so a just-upgraded or sync-failing account can't emit false nudges), honors Gmail's send-as aliases, and drafts email replies in an email tone rather than a text-message one. Follow-on hardening (per-account event querying, full sent-window coverage) tracked in #2820.## Changeddiff --git a/server/services/humanActivity.js b/server/services/humanActivity.jsindex 7fb0a6682d..1ab608bfce 100644--- a/server/services/humanActivity.js+++ b/server/services/humanActivity.js@@ -178,11 +178,15 @@ 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;+ // Direction: prefer Gmail's authoritative SENT label when the provider supplies+ // labels — it correctly marks mail sent from a "send-as" alias (where From ≠+ // account.email), which a bare From-vs-owner match would misclassify as received+ // and so never cancel its inbound in outreach detection (#2796). Sources without+ // labels (Outlook/other) fall back to matching the sender against the owner.+ const labels = Array.isArray(message.labels) ? message.labels : null;+ const sent = labels+ ? labels.includes('SENT')+ : (Boolean(selfEmail) && fromEmail === selfEmail);const participants = normalizeParticipants([message.from,...(message.to || []),diff --git a/server/services/humanActivity.test.js b/server/services/humanActivity.test.jsindex 3662bcc69e..f89353f080 100644--- a/server/services/humanActivity.test.js+++ b/server/services/humanActivity.test.js@@ -185,6 +185,16 @@ describe('messageActivityCandidates', () => {// Sent turns carry no counterpart handle (mirrors iMessage); email groups by threadId.expect(sent.metadata.handle).toBeNull();});+ it('classifies a reply as sent via the Gmail SENT label even from a send-as alias (#2796)', () => {+ // From ([email protected]) != account owner ([email protected]), but the SENT label+ // is authoritative — without it the reply is misclassified received and never+ // cancels its inbound.+ const [c] = messageActivityCandidates(account, [+ { externalId: 'e9', date: '2026-07-04T12:00:00Z', from: '[email protected]', to: ['[email protected]'], subject: 'Re: Hey', labels: ['SENT'] },+ ]);+ expect(c.kind).toBe('message.sent');+ expect(c.metadata.handle).toBeNull();+ });});describe('calendarActivityCandidates', () => {diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.jsindex 18881598b0..3405290d81 100644--- a/server/services/messageAccounts.js+++ b/server/services/messageAccounts.js@@ -88,3 +88,15 @@ export async function updateSyncStatus(id, status) {await saveAccounts(accounts);return accounts[id];}++// Stamp the reply-detection watermark (#2796): the last time this account+// successfully ingested sent mail into the activity timeline. The Tribe-outreach+// detector trusts an account as two-way only when this is set and recent, so an+// account is never trusted before its sent history actually exists.+export async function markSentIngested(id, at = new Date().toISOString()) {+ const accounts = await loadAccounts();+ if (!accounts[id]) return null;+ accounts[id].sentIngestedAt = at;+ await saveAccounts(accounts);+ return accounts[id];+}diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex eb3d2f5837..508d0739be 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -21,11 +21,13 @@ function makeExternalId(gmailId) {// 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;+// Sent mail gets its OWN fetch budget (a separate list pass), never a share of the+// inbox cap — sent is activity-only and must not crowd inbox out of the primary+// sync. This also bounds the per-sync detail-fetch cost (sent isn't cached, so it's+// re-fetched each sync). 14 days of a normal person's replies fit under this; a+// heavier sender whose replies fall beyond it is a filed follow-up (full date-bounded+// pagination / fail-closed) — see the issue linked from the changelog.+export const SENT_INGEST_MAX = 100;// The inbox search query for a sync mode. `unread` scopes to unread inbox; `full`// takes the whole inbox (capped downstream).@@ -254,12 +256,27 @@ export async function syncGmail(account, cache, io, options = {}) {}}- if (io && messages.length > 0) {- io.emit('messages:sync:message', { accountId: account.id, messages });+ // Split inbox vs sent: sent mail is ingested ONLY for the human-activity timeline+ // (reply detection, #2796) — it must NOT enter the inbox cache, or it would show+ // up in /api/messages/inbox, run through triage/eval, and compete with real inbox+ // mail under the maxMessages trim (which could evict a message before its activity+ // is recorded). A message the user sent carries Gmail's SENT label and no INBOX+ // label; anything with INBOX (including a self-addressed SENT+INBOX message) stays+ // inbox. syncAccount records sent activity from `sentMessages` separately.+ const inboxMessages = [];+ const sentMessages = [];+ for (const m of messages) {+ const lbl = m.labels || [];+ if (lbl.includes('SENT') && !lbl.includes('INBOX')) sentMessages.push(m);+ else inboxMessages.push(m);}- console.log(`📧 Gmail API sync complete: ${messages.length} messages fetched`);- return { messages, status: 'success', syncMethod: 'api' };+ if (io && inboxMessages.length > 0) {+ io.emit('messages:sync:message', { accountId: account.id, messages: inboxMessages });+ }++ console.log(`📧 Gmail API sync complete: ${inboxMessages.length} inbox, ${sentMessages.length} sent (activity-only)`);+ return { messages: inboxMessages, sentMessages, status: 'success', syncMethod: 'api' };}/**diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex b9f75665da..9037f4aa82 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -2,7 +2,7 @@import { createHash } from 'crypto';import { join } from 'path';import { atomicWrite, ensureDir, filterBySearch as genericFilterBySearch, PATHS, safeDate, safeJSONParse, UUID_RE, tryReadFile } from '../lib/fileUtils.js';-import { getAccount, updateSyncStatus } from './messageAccounts.js';+import { getAccount, updateSyncStatus, markSentIngested } from './messageAccounts.js';import { getUserTimezone, getLocalParts } from '../lib/timezone.js';import { v4 as uuidv4 } from '../lib/uuid.js';import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';@@ -191,6 +191,9 @@ export async function syncAccount(accountId, io, options = {}) {// Support structured result { messages, status } or plain arrayconst newMessages = Array.isArray(providerResult) ? providerResult : providerResult?.messages ?? [];const providerStatus = Array.isArray(providerResult) ? 'success' : providerResult?.status ?? 'success';+ // Sent mail (Gmail reply-detection ingest, #2796) is activity-only: recorded to+ // the timeline but never added to the inbox cache/eval/trim. Kept separate here.+ const sentMessages = Array.isArray(providerResult) ? [] : (providerResult?.sentMessages ?? []);// Deduplicate by externalId; update flags and body on existing messagesconst existingMap = new Map(cache.messages.filter(m => m.externalId).map(m => [m.externalId, m]));@@ -250,9 +253,21 @@ export async function syncAccount(accountId, io, options = {}) {// Populate the human-activity timeline (#2150) — secondary effect, must NOT// fail the sync. Idempotent on (source, dedupe_key), so re-scanning the full// cache each sync is a no-op for already-recorded messages. Machine-local.- await recordMessageActivity(account, cache.messages).catch((err) =>+ // Sent mail (activity-only, #2796) is fed IN ADDITION to the cached inbox mail+ // so it records `message.sent` events without ever entering the inbox cache.+ await recordMessageActivity(account, [...cache.messages, ...sentMessages]).catch((err) =>console.error(`🗓️ Activity ingest failed for account ${accountId}: ${err.message}`));+ // Reply-detection watermark (#2796): stamp when a Gmail account with sent-ingest+ // enabled completes a successful sync, so the outreach detector only trusts an+ // account whose sent history is actually present and recent. Without this, an+ // account default-on at upgrade (or after an OAuth/sync failure) would be trusted+ // before any reply evidence exists, producing false "unanswered" nudges.+ if (providerStatus === 'success' && account.type === 'gmail' && account.syncConfig?.ingestSent !== false) {+ await markSentIngested(accountId).catch((err) =>+ console.error(`🤝 Sent-ingest watermark failed for account ${accountId}: ${err.message}`));+ }+io?.emit('messages:sync:completed', { accountId, newMessages: uniqueNew.length, pruned, status: providerStatus });if (providerStatus === 'success') {io?.emit('messages:changed', {});diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.jsindex e949dcf456..6e02ce35fb 100644--- a/server/services/messageSync.test.js+++ b/server/services/messageSync.test.js@@ -34,7 +34,8 @@ vi.mock('../lib/fileUtils.js', () => ({vi.mock('./messageAccounts.js', () => ({getAccount: vi.fn(),- updateSyncStatus: vi.fn()+ updateSyncStatus: vi.fn(),+ markSentIngested: vi.fn(() => Promise.resolve())}));vi.mock('./messageGmailSync.js', () => ({diff --git a/server/services/tribeOutreach.js b/server/services/tribeOutreach.jsindex 083c71fd35..3584277dfa 100644--- a/server/services/tribeOutreach.js+++ b/server/services/tribeOutreach.js@@ -68,24 +68,38 @@ 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.+ * 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);+ * - it has an owner email set (sent-vs-received direction needs it — see+ * `messageActivityCandidates`; without it no `message.sent` events are produced,+ * so every inbound would read as unanswered);+ * - it is enabled (a disabled account never syncs, so its sent history never+ * updates — trusting it would nudge on stale/absent reply evidence);+ * - it has a RECENT sent-ingest watermark (`sentIngestedAt` within `coverageMs`).+ * This is the reliability guard: an account default-on at upgrade, or one whose+ * OAuth/sync has been failing, has no current sent evidence — trusting it on+ * config alone would produce false "unanswered" nudges for already-replied+ * threads. `coverageMs` defaults to Infinity (presence-only) for pure tests; the+ * real caller passes the detection window.*- * @param {Array} accounts message-account records ({ id, type, email, syncConfig })+ * @param {Array} accounts message-account records ({ id, type, email, enabled, syncConfig, sentIngestedAt })+ * @param {{ now?: number, coverageMs?: number }} opts staleness bound for the watermark* @returns {{ sources: string[], isTwoWay: (ev: object) => boolean }}*/-export function buildTwoWayGate(accounts = []) {+export function buildTwoWayGate(accounts = [], { now = Date.now(), coverageMs = Infinity } = {}) {const twoWayEmailAccountIds = new Set((accounts || [])- .filter((a) =>- SENT_INGEST_SOURCES.has(a?.type) &&- a?.syncConfig?.ingestSent !== false &&- String(a?.email || '').trim() !== '')+ .filter((a) => {+ if (!SENT_INGEST_SOURCES.has(a?.type)) return false;+ if (a?.syncConfig?.ingestSent === false) return false;+ if (String(a?.email || '').trim() === '') return false;+ if (a?.enabled === false) return false;+ const at = Date.parse(a?.sentIngestedAt);+ if (Number.isNaN(at)) return false; // never successfully ingested sent mail+ return (now - at) <= coverageMs; // stale watermark → coverage can't be trusted+ }).map((a) => a.id));// Only scan an email source when at least one of its accounts is two-way — a@@ -108,6 +122,19 @@ export function buildTwoWayGate(accounts = []) {// actually reaches the model (the default template omits it and drops it silently).const OUTREACH_CHAT_TEMPLATE = 'Write a brief, warm, casual reply to reconnect over a text message. Keep it short and personal — no email subject line, no formal salutation or sign-off.{{#instructions}}\n\nAdditional guidance: {{instructions}}{{/instructions}}\n\nFrom: {{from}}\nTheir message:\n{{body}}';+// Channel-appropriate reply prompt for EMAIL outreach (#2796). Email threads can now+// reach draft generation, and the chat template above explicitly forbids a salutation/+// sign-off — wrong for email. This one asks for a natural greeting + sign-off while+// staying warm and concise, and (like the chat one) resolves the {{#instructions}}+// block so caller guidance reaches the model (the default template drops it silently).+const OUTREACH_EMAIL_TEMPLATE = 'Write a brief, warm, personal email reply to reconnect. Keep it genuine and concise, with a natural greeting and a friendly sign-off.{{#instructions}}\n\nAdditional guidance: {{instructions}}{{/instructions}}\n\nFrom: {{from}}\nTheir message:\n{{body}}';++// Chat sources are the two-way messaging apps; everything else here is email-shaped.+// Picks the channel-appropriate outreach reply template.+export function outreachTemplateForSource(source) {+ return TWO_WAY_CHAT_SOURCES.has(source) ? OUTREACH_CHAT_TEMPLATE : OUTREACH_EMAIL_TEMPLATE;+}+// A conversation is keyed by the most specific stable identifier available:// chatGuid (iMessage), conversationId (Signal — its outbound turns carry no// handle, so keying on the shared conversationId is the only thing that unifies@@ -229,10 +256,14 @@ export async function findUnansweredTribeThreads({const ctx = await loadResolverContext().catch(() => null);if (!ctx) return [];+ const now = Date.now();+ const withinMs = withinDays * DAY_MS;// Per-account two-way gate: which sources to scan, and which inbound events are- // trustworthy (chat source-wide, email only from sent-ingesting accounts).+ // trustworthy (chat source-wide, email only from sent-ingesting accounts whose+ // reply-evidence watermark covers the detection window).const { sources: twoWaySources, isTwoWay } = buildTwoWayGate(- await listAccounts().catch(() => [])+ await listAccounts().catch(() => []),+ { now, coverageMs: withinMs });const ringById = new Map((ctx.people || []).map((p) => [p.id, p.ring]));const nameById = new Map((ctx.people || []).map((p) => [p.id, p.name]));@@ -240,8 +271,7 @@ export async function findUnansweredTribeThreads({const hasTribe = (ctx.people || []).some((p) => p.ring && p.ring !== 'external');if (!hasTribe) return [];- const now = Date.now();- const from = new Date(now - withinDays * DAY_MS).toISOString();+ const from = new Date(now - withinMs).toISOString();// Query each two-way source × kind separately, each with its own 2000-row cap.// A single shared query would let a high-volume source (e.g. thousands of// imported email events) fill the newest-2000 slice and push older iMessage /@@ -302,7 +332,7 @@ export async function findUnansweredTribeThreads({const threads = groupUnansweredThreads(tagged, {now,staleAfterMs: staleAfterHours * HOUR_MS,- withinMs: withinDays * DAY_MS,+ withinMs,});return threads.slice(0, Math.max(0, limit));}@@ -451,7 +481,9 @@ async function generateOutreachDraftImpl({const aiResult = await generateReplyBody(replyTo, instructions, {useVoice,threadMessages,- templateOverride: OUTREACH_CHAT_TEMPLATE,+ // Channel-appropriate template: casual/no-signoff for chat, greeting+signoff for+ // email (Gmail threads now reach here via #2796).+ templateOverride: outreachTemplateForSource(source),}).catch((err) => {console.error(`❌ Outreach draft generation failed: ${err.message}`);return null;diff --git a/server/services/tribeOutreach.test.js b/server/services/tribeOutreach.test.jsindex 9c0da74fcb..1372c8054a 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, buildTwoWayGate } from './tribeOutreach.js';+import { groupUnansweredThreads, generateOutreachDraft, buildTwoWayGate, outreachTemplateForSource } from './tribeOutreach.js';// generateOutreachDraft dynamically imports these — mock them so the draft-side// logic (idempotent reuse, anchoring the reply to the detected inbound) is@@ -162,30 +162,47 @@ describe('groupUnansweredThreads', () => {});describe('buildTwoWayGate (per-account #2796)', () => {- const gmail = (over) => ({ id: 'g1', type: 'gmail', email: '[email protected]', syncConfig: {}, ...over });+ const NOW = Date.parse('2026-07-18T12:00:00Z');+ const recent = new Date(NOW - 3600000).toISOString(); // 1h ago — fresh watermark+ const OPTS = { now: NOW, coverageMs: 14 * 86400000 };+ // A trustworthy Gmail account: email set, enabled, sent-ingest on, recent watermark.+ const gmail = (over) => ({ id: 'g1', type: 'gmail', email: '[email protected]', enabled: true, syncConfig: {}, sentIngestedAt: recent, ...over });it('chat sources are always two-way, no account needed', () => {- const { sources, isTwoWay } = buildTwoWayGate([]);+ const { sources, isTwoWay } = buildTwoWayGate([], OPTS);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()]);+ it('a Gmail account with email, default ingestSent, and a recent watermark is two-way', () => {+ const { sources, isTwoWay } = buildTwoWayGate([gmail()], OPTS);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 } })]);+ const { sources, isTwoWay } = buildTwoWayGate([gmail({ syncConfig: { ingestSent: false } })], OPTS);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);+ expect(buildTwoWayGate([gmail({ email: '' })], OPTS).isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(false);+ });++ it('a disabled Gmail account is NOT two-way (its sent history never syncs)', () => {+ expect(buildTwoWayGate([gmail({ enabled: false })], OPTS).isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(false);+ });++ it('a Gmail account with NO sent-ingest watermark is NOT two-way (upgrade/first-sync window)', () => {+ // Default-on at upgrade but no sync yet → no reply evidence → must not be trusted.+ expect(buildTwoWayGate([gmail({ sentIngestedAt: undefined })], OPTS).isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(false);+ });++ it('a STALE watermark (older than the detection window) drops the account (sync failing)', () => {+ const stale = new Date(NOW - 20 * 86400000).toISOString(); // 20d ago > 14d window+ expect(buildTwoWayGate([gmail({ sentIngestedAt: stale })], OPTS).isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(false);});it('does NOT let one Gmail account vouch for another (per-account, not source-wide)', () => {@@ -194,7 +211,7 @@ describe('buildTwoWayGate (per-account #2796)', () => {const gate = buildTwoWayGate([gmail({ id: 'g1' }),gmail({ id: 'g2', email: '[email protected]', syncConfig: { ingestSent: false } }),- ]);+ ], OPTS);expect(gate.sources).toContain('gmail'); // scanned because g1 is two-wayexpect(gate.isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(true);expect(gate.isTwoWay({ source: 'gmail', accountId: 'g2' })).toBe(false);@@ -202,13 +219,28 @@ describe('buildTwoWayGate (per-account #2796)', () => {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 } },- ]);+ { id: 'o1', type: 'outlook', email: '[email protected]', enabled: true, syncConfig: { ingestSent: true }, sentIngestedAt: recent },+ ], OPTS);expect(sources).not.toContain('outlook');expect(isTwoWay({ source: 'outlook', accountId: 'o1' })).toBe(false);});});+describe('outreachTemplateForSource (#2796)', () => {+ it('uses a no-signoff casual template for chat sources', () => {+ const t = outreachTemplateForSource('imessage');+ expect(t).toContain('text message');+ expect(t).toContain('no formal salutation or sign-off');+ expect(outreachTemplateForSource('signal')).toBe(t);+ });+ it('uses a greeting+signoff email template for Gmail (not the chat template)', () => {+ const t = outreachTemplateForSource('gmail');+ expect(t).toContain('email reply');+ expect(t).toContain('sign-off');+ expect(t).not.toContain('no formal salutation');+ });+});+describe('generateOutreachDraft', () => {beforeEach(() => {vi.clearAllMocks();