Skip to content

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

fix(issue-2831): exclude Gmail send-as aliases from received-message participants

[._.]/ Adam Eivy7cebcc2305b0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e22e71ce9a..71bd5e3a3f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased
+## Tribe outreach
+
+- **[issue-2831] Unanswered 1:1 emails to a Gmail alias now surface as outreach nudges** — a message delivered to one of your Gmail send-as aliases (not your primary address) is correctly treated as a one-on-one conversation instead of a group thread, so a genuinely unanswered email to an alias no longer gets silently skipped. Your own alias addresses never appear as a Tribe contact.
+
## Security
- Guard paid-provider API keys against SSRF / key-exfiltration: `streamCompletion` (askService), voice-LLM endpoint resolution, and the local-LLM playground now validate a provider's endpoint through the shared endpoint guard before attaching the `Authorization: Bearer` header, so a mistyped or malicious custom endpoint (including cloud-metadata hosts) never receives the key unless the provider opts in via `allowCustomEndpoint`.
diff --git a/server/routes/messages.js b/server/routes/messages.js
index b92a382d17..698a492cf4 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -38,6 +38,9 @@ const updateAccountSchema = z.object({
name: z.string().min(1).optional(),
email: z.union([z.string().email(), z.literal('')]).optional(),
enabled: z.boolean().optional(),
+ // Gmail send-as aliases (#2831). Server-populated on sync, not typically set by the
+ // client; accepted here for schema parity so a round-tripped account payload validates.
+ sendAsAliases: z.array(z.string()).optional(),
syncConfig: z.object({
maxAge: z.string().optional(),
maxMessages: z.number().int().positive().optional(),
diff --git a/server/services/humanActivity.js b/server/services/humanActivity.js
index 802aa1c36a..27d83f5d57 100644
--- a/server/services/humanActivity.js
+++ b/server/services/humanActivity.js
@@ -169,6 +169,17 @@ function participantEmail(p) {
// received) is derived deterministically from the sender vs the account owner.
export function messageActivityCandidates(account, messages = []) {
const selfEmail = String(account?.email || '').trim().toLowerCase();
+ // Owner-address set: the primary account email PLUS every Gmail "send-as" alias
+ // (#2831). A received 1:1 message delivered to an alias (not account.email) would
+ // otherwise keep the alias as a second participant, making the thread look like a
+ // group and suppressing its Tribe-outreach nudge. Aliases are refreshed on sync
+ // (messageGmailSync → messageAccounts.sendAsAliases); absent/failed fetch leaves the
+ // set as just the primary email, i.e. today's behavior.
+ const ownerEmails = new Set(
+ [selfEmail, ...(Array.isArray(account?.sendAsAliases) ? account.sendAsAliases : [])]
+ .map((e) => String(e || '').trim().toLowerCase())
+ .filter(Boolean)
+ );
const source = account?.type || 'message';
const accountId = account?.id || null;
const out = [];
@@ -191,7 +202,7 @@ export function messageActivityCandidates(account, messages = []) {
message.from,
...(message.to || []),
...(message.cc || []),
- ]).filter((p) => !(p.email && p.email === selfEmail));
+ ]).filter((p) => !(p.email && ownerEmails.has(p.email)));
out.push({
source,
accountId,
diff --git a/server/services/humanActivity.test.js b/server/services/humanActivity.test.js
index f89353f080..d64ccbc33b 100644
--- a/server/services/humanActivity.test.js
+++ b/server/services/humanActivity.test.js
@@ -185,6 +185,29 @@ describe('messageActivityCandidates', () => {
// Sent turns carry no counterpart handle (mirrors iMessage); email groups by threadId.
expect(sent.metadata.handle).toBeNull();
});
+ it('excludes send-as aliases from participants so a received 1:1-to-alias stays 1:1 (#2831)', () => {
+ // A 1:1 email delivered to the owner's alias (not account.email). Without alias
+ // filtering the alias survives as a second participant and the thread looks like a
+ // group, suppressing its outreach nudge.
+ const aliasAccount = { id: 'acct-1', type: 'gmail', email: '[email protected]', sendAsAliases: ['[email protected]'] };
+ const [c] = messageActivityCandidates(aliasAccount, [
+ { externalId: 'e1', date: '2026-07-04T10:00:00Z', from: '[email protected]', to: ['[email protected]'], subject: 'Hey' },
+ ]);
+ const emails = c.participants.map((p) => p.email);
+ expect(emails).toEqual(['[email protected]']); // exactly one counterpart — a true 1:1
+ expect(emails).not.toContain('[email protected]');
+ expect(c.metadata.handle).toBe('[email protected]');
+ });
+ it('still filters only the primary email when no aliases are stored (back-compat, #2831)', () => {
+ // Absent sendAsAliases → today's behavior: only account.email is dropped.
+ const [c] = messageActivityCandidates(account, [
+ { externalId: 'e1', date: '2026-07-04T10:00:00Z', from: '[email protected]', to: ['[email protected]', '[email protected]'], subject: 'Hey' },
+ ]);
+ const emails = c.participants.map((p) => p.email);
+ expect(emails).toContain('[email protected]');
+ expect(emails).toContain('[email protected]'); // not a known alias → kept
+ expect(emails).not.toContain('[email protected]');
+ });
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
diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.js
index c5ae6a4b68..0310417a1f 100644
--- a/server/services/messageAccounts.js
+++ b/server/services/messageAccounts.js
@@ -49,6 +49,11 @@ export async function createAccount(data) {
// migration isn't needed — this only makes new accounts' stored state explicit.
ingestSent: data.syncConfig?.ingestSent ?? (data.type === 'gmail')
},
+ // Gmail send-as alias addresses (#2831), refreshed on each sync. Owner addresses
+ // beyond the primary `email`; used to exclude the owner from received-message
+ // participants so a 1:1 email delivered to an alias isn't misread as a group thread.
+ // Additive/back-compat: existing accounts lack the key and readers treat absent as [].
+ sendAsAliases: [],
lastSyncAt: null,
lastSyncStatus: null,
createdAt: new Date().toISOString()
@@ -80,6 +85,20 @@ export async function deleteAccount(id) {
return true;
}
+// Persist the account's Gmail send-as aliases (#2831), refreshed opportunistically on
+// each successful sync. Owner addresses beyond the primary `email`; consumed by
+// `messageActivityCandidates` to exclude ALL owner addresses (not just the primary)
+// from received-message participants. Lowercased + deduped; absent → [] for readers.
+export async function updateSendAsAliases(id, aliases = []) {
+ const accounts = await loadAccounts();
+ if (!accounts[id]) return null;
+ accounts[id].sendAsAliases = Array.isArray(aliases)
+ ? [...new Set(aliases.map((a) => String(a || '').trim().toLowerCase()).filter(Boolean))]
+ : [];
+ await saveAccounts(accounts);
+ return accounts[id];
+}
+
export async function updateSyncStatus(id, status) {
const accounts = await loadAccounts();
if (!accounts[id]) return null;
diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.js
index be05725a62..35ad6d7472 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);
}
+/**
+ * Fetch the account's Gmail "send-as" alias addresses (#2831) — the primary address
+ * plus every configured alias the owner can send/receive as. Used to exclude ALL owner
+ * addresses (not just account.email) from received-message participants, so a 1:1 email
+ * delivered to an alias isn't misread as a group thread and dropped by outreach detection.
+ *
+ * Best-effort with a `null` sentinel vs `[]` distinction: a FAILED call returns `null`
+ * so the caller keeps the previously-stored alias set (degrade to the primary email),
+ * while a SUCCESSFUL call returns the fetched list (possibly empty). The primary email
+ * is normally itself a `sendAs` entry, so a healthy account returns at least `[primary]`.
+ */
+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}`);
+ return null;
+ });
+ if (!res) return null; // sentinel: fetch failed — do not clobber the stored aliases
+ const list = res?.data?.sendAs || [];
+ return list.map((a) => String(a?.sendAsEmail || '').trim().toLowerCase()).filter(Boolean);
+}
+
// 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;
@@ -212,6 +233,11 @@ export async function syncGmail(account, cache, io, options = {}) {
}
const gmailClient = gmail({ version: 'v1', auth });
+ // Refresh the owner's send-as aliases opportunistically each sync (#2831) — one cheap
+ // settings call. Returned up to syncAccount so the activity timeline can exclude every
+ // owner address, not just the primary, from received-message participants. `null` on
+ // failure (keep prior stored set); an array (possibly empty) on success.
+ const sendAsAliases = await fetchSendAsAliases(gmailClient);
const maxMessages = mode === 'full' ? 200 : 100;
// Ingest sent mail unless the account explicitly opted out — the default-on
// capability powers per-account Tribe-outreach reply detection (#2796).
@@ -335,7 +361,7 @@ 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, status: 'success', syncMethod: 'api' };
+ return { messages: inboxMessages, sentMessages, sentTruncated: sentCoveragePartial, sendAsAliases, status: 'success', syncMethod: 'api' };
}
/**
diff --git a/server/services/messageGmailSync.test.js b/server/services/messageGmailSync.test.js
index 3e0c593bd1..eda9ef1074 100644
--- a/server/services/messageGmailSync.test.js
+++ b/server/services/messageGmailSync.test.js
@@ -5,6 +5,7 @@ import {
sentQuery,
gmailSyncPasses,
collectMessageIds,
+ fetchSendAsAliases,
SENT_INGEST_DAYS,
SENT_INGEST_MAX,
} from './messageGmailSync.js';
@@ -115,3 +116,28 @@ describe('collectMessageIds — full pagination', () => {
expect(SENT_INGEST_MAX).toBeGreaterThanOrEqual(1000);
});
});
+
+// Owner send-as alias fetch (#2831). Received 1:1 mail delivered to an alias must be
+// excludable from participants, so the sync fetches the account's send-as addresses.
+describe('fetchSendAsAliases', () => {
+ const clientReturning = (sendAs) => ({
+ users: { settings: { sendAs: { list: async () => ({ data: { sendAs } }) } } },
+ });
+
+ it('returns lowercased alias emails from the sendAs settings', async () => {
+ const client = clientReturning([
+ { sendAsEmail: '[email protected]', isPrimary: true },
+ { sendAsEmail: '[email protected]' },
+ ]);
+ expect(await fetchSendAsAliases(client)).toEqual(['[email protected]', '[email protected]']);
+ });
+
+ it('returns an empty array (not null) when the account has no sendAs entries', async () => {
+ expect(await fetchSendAsAliases(clientReturning([]))).toEqual([]);
+ });
+
+ it('returns the null sentinel (keep stored aliases) when the API call fails', async () => {
+ const client = { users: { settings: { sendAs: { list: async () => { throw new Error('boom'); } } } } };
+ expect(await fetchSendAsAliases(client)).toBeNull();
+ });
+});
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 3b2e066c93..ad54395f27 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, markSentIngested } from './messageAccounts.js';
+import { getAccount, updateSyncStatus, markSentIngested, updateSendAsAliases } from './messageAccounts.js';
import { getUserTimezone, getLocalParts } from '../lib/timezone.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
@@ -197,6 +197,11 @@ export async function syncAccount(accountId, io, options = {}) {
// Whether the sent window truncated at its ceiling this sync (#2820) — coverage
// is then partial, so the reply-detection watermark is marked partial (fail closed).
const sentTruncated = Array.isArray(providerResult) ? false : Boolean(providerResult?.sentTruncated);
+ // Gmail send-as aliases fetched this sync (#2831). `null` = fetch failed/not supplied
+ // (keep the stored set); an array = authoritative refresh. Applied in-memory below so
+ // the SAME sync's activity ingest excludes every owner address, and persisted for the
+ // next sync + the outreach detector's own reads.
+ const sendAsAliases = Array.isArray(providerResult) ? null : (providerResult?.sendAsAliases ?? null);
// Deduplicate by externalId; update flags and body on existing messages
const existingMap = new Map(cache.messages.filter(m => m.externalId).map(m => [m.externalId, m]));
@@ -253,6 +258,17 @@ export async function syncAccount(accountId, io, options = {}) {
await logMessageTouchpoints(account, cache.messages).catch((err) =>
console.error(`🤝 Tribe auto-log failed for account ${accountId}: ${err.message}`));
+ // Apply + persist the owner's Gmail send-as aliases (#2831) BEFORE the activity
+ // ingest below, so THIS sync's `messageActivityCandidates` already excludes every
+ // owner address (not just the primary email) from received-message participants.
+ // Best-effort: a `null` sentinel (fetch failed / non-Gmail provider) leaves the
+ // stored set untouched; persist failure must not fail the sync.
+ if (Array.isArray(sendAsAliases)) {
+ account.sendAsAliases = sendAsAliases;
+ await updateSendAsAliases(accountId, sendAsAliases).catch((err) =>
+ console.error(`📧 Send-as alias persist failed for account ${accountId}: ${err.message}`));
+ }
+
// 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.