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): scope outreach to two-way chat sources; fix draft grounding + UX races
[._.]/ Adam Eivy3b370c35e8a4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e93317a33c..c4d45ef814 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,7 +10,7 @@## Tribe-- **[issue-2158] Your Tribe now nudges you about messages you never replied to — with a reply ready to draft.** Beyond the existing "you haven't talked in a while" cadence reminders, PortOS now reads your activity timeline (iMessage, Signal, email) to spot inbound messages from people in your Tribe that you never answered, and surfaces them both as a proactive alert ("You never replied to 'dinner Friday?' — 3 days ago") and in a new **Waiting on a reply** panel on the Tribe → Care Queue tab. Each one has a **Draft reply** button that writes a reply grounded in the actual conversation and files it to your Messages drafts for review — it uses your configured AI provider only when you click, and nothing is ever sent automatically. Threads you've already answered, ones too fresh to nag about, and ones too old to still be worth a reply are all filtered out, and only people in your Tribe (not every contact) can trigger a nudge.+- **[issue-2158] Your Tribe now nudges you about messages you never replied to — with a reply ready to draft.** Beyond the existing "you haven't talked in a while" cadence reminders, PortOS now reads your activity timeline (iMessage and Signal) to spot inbound messages from people in your Tribe that you never answered, and surfaces them both as a proactive alert ("You never replied to 'dinner Friday?' — 3 days ago") and in a new **Waiting on a reply** panel on the Tribe → Care Queue tab. Each one has a **Draft reply** button that writes a reply grounded in the actual conversation and files it to your Messages drafts for review — it uses your configured AI provider only when you click, and nothing is ever sent automatically (iMessage/Signal drafts are review-only, so you copy and send them from your messaging app). Threads you've already answered, ones too fresh to nag about, and ones too old to still be worth a reply are all filtered out, and only people in your Tribe (not every contact) can trigger a nudge. (Email is intentionally out of scope for now — inbox-only sync can't see whether you already replied, so it isn't nudged.)## Addeddiff --git a/client/src/components/messages/DraftsTab.jsx b/client/src/components/messages/DraftsTab.jsxindex 5f0bd9b0d7..7e7da15be3 100644--- a/client/src/components/messages/DraftsTab.jsx+++ b/client/src/components/messages/DraftsTab.jsx@@ -96,7 +96,7 @@ export default function DraftsTab({ accounts }) {)}</div><div className="flex items-center gap-1">- {draft.status === 'draft' && (+ {draft.status === 'draft' && draft.sendVia !== 'review' && (<buttononClick={() => handleApprove(draft.id)}className="p-1 text-gray-400 hover:text-port-success transition-colors"@@ -123,7 +123,10 @@ export default function DraftsTab({ accounts }) {Review only</span>)}- {['draft', 'pending_review', 'failed'].includes(draft.status) && (+ {/* Review-only drafts never reach a 'sent' state (there's no send+ channel), so keep Delete available at any status — otherwise an+ approved iMessage/Signal draft would be stuck with no action. */}+ {(['draft', 'pending_review', 'failed'].includes(draft.status) || draft.sendVia === 'review') && (<buttononClick={() => requestDelete(draft.id)}className="p-1 text-gray-400 hover:text-port-error transition-colors"diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsxindex 92c2d2a334..a620aa1c46 100644--- a/client/src/pages/Tribe.jsx+++ b/client/src/pages/Tribe.jsx@@ -581,7 +581,10 @@ function OutreachQueue() {// null = still loading; [] = loaded-empty. Distinguishing them keeps the panel// from flashing an empty state before the first fetch resolves.const [threads, setThreads] = useState(null);- const [busyKey, setBusyKey] = useState(null);+ // A SET of in-flight conversation keys, not a single key — with one key, starting+ // a second generation re-enables the first thread's button and a re-click fires a+ // duplicate provider call + duplicate draft.+ const [busyKeys, setBusyKeys] = useState(() => new Set());const [drafts, setDrafts] = useState({});const [copiedKey, setCopiedKey] = useState(null);@@ -594,23 +597,24 @@ function OutreachQueue() {}, []);const generate = async (thread) => {- setBusyKey(thread.conversationKey);+ const key = thread.conversationKey;+ if (busyKeys.has(key) || drafts[key]) return; // already generating or done+ setBusyKeys((prev) => new Set(prev).add(key));const seed = {personId: thread.personId,source: thread.source,- accountId: thread.accountId,threadId: thread.threadId,chatGuid: thread.chatGuid,+ conversationId: thread.conversationId,handle: thread.handle,- replyToExternalId: thread.replyToExternalId,};const result = await api.generateTribeOutreachDraft(seed, { silent: true }).catch((err) => {toast.error(err.message || 'Could not generate a draft');return null;});- setBusyKey((prev) => (prev === thread.conversationKey ? null : prev));+ setBusyKeys((prev) => { const next = new Set(prev); next.delete(key); return next; });if (result?.draft) {- setDrafts((prev) => ({ ...prev, [thread.conversationKey]: result.draft }));+ setDrafts((prev) => ({ ...prev, [key]: result.draft }));toast.success(`Draft saved for ${thread.personName} — review before sending`);}};@@ -642,7 +646,7 @@ function OutreachQueue() {<div className="mt-3 grid gap-3">{threads.map((thread) => {const draft = drafts[thread.conversationKey];- const busy = busyKey === thread.conversationKey;+ const busy = busyKeys.has(thread.conversationKey);return (<div key={thread.conversationKey} className="rounded border border-port-border bg-port-bg p-3"><div className="flex flex-wrap items-center gap-2 text-xs text-gray-500">diff --git a/server/routes/tribe.js b/server/routes/tribe.jsindex 3ba165571e..7e0c21b41b 100644--- a/server/routes/tribe.js+++ b/server/routes/tribe.js@@ -65,11 +65,10 @@ const memoryLinkSchema = z.object({const outreachDraftSchema = z.object({personId: z.string().guid().nullable().optional(),source: z.string().max(60).nullable().optional(),- accountId: z.string().guid().nullable().optional(),threadId: z.string().max(500).nullable().optional(),chatGuid: z.string().max(500).nullable().optional(),+ conversationId: z.string().max(500).nullable().optional(),handle: z.string().max(320).nullable().optional(),- replyToExternalId: z.string().max(500).nullable().optional(),instructions: z.string().max(2000).optional().default(''),useVoice: z.boolean().optional(),});diff --git a/server/routes/tribe.test.js b/server/routes/tribe.test.jsindex f9a4932ce3..4b712c101b 100644--- a/server/routes/tribe.test.js+++ b/server/routes/tribe.test.js@@ -300,10 +300,10 @@ describe('Tribe Routes', () => {expect(emit).toHaveBeenCalledWith('messages:draft:created', { draftId: '44444444-4444-4444-8444-444444444444' });});- it('rejects an outreach draft request with a non-UUID accountId', async () => {+ it('rejects an outreach draft request with a non-UUID personId', async () => {const response = await request(app).post('/api/tribe/outreach/draft')- .send({ accountId: 'not-a-uuid' });+ .send({ personId: 'not-a-uuid' });expect(response.status).toBe(400);expect(tribeOutreach.generateOutreachDraft).not.toHaveBeenCalled();diff --git a/server/services/humanActivity.js b/server/services/humanActivity.jsindex 8ce42009ac..6f04e4822b 100644--- a/server/services/humanActivity.js+++ b/server/services/humanActivity.js@@ -351,7 +351,7 @@ async function insertActivityChunk(rows) {// lower, exclusive upper); `personId` matches a participant via the JSONB// containment operator. `chatGuid` / `handle` match iMessage-style metadata// pointers. Newest first, capped by `limit` (default 500, max 2000).-export async function listEvents({ from, to, source, kind, personId, chatGuid, handle, limit } = {}) {+export async function listEvents({ from, to, source, kind, personId, chatGuid, conversationId, threadId, handle, limit } = {}) {await ensureReady();const clauses = [];const params = [];@@ -367,6 +367,14 @@ export async function listEvents({ from, to, source, kind, personId, chatGuid, hparams.push(String(chatGuid));clauses.push(`metadata->>'chatGuid' = $${params.length}`);}+ if (conversationId != null && String(conversationId).length > 0) {+ params.push(String(conversationId));+ clauses.push(`metadata->>'conversationId' = $${params.length}`);+ }+ if (threadId != null && String(threadId).length > 0) {+ params.push(String(threadId));+ clauses.push(`metadata->>'threadId' = $${params.length}`);+ }if (handle != null && String(handle).length > 0) {params.push(String(handle));clauses.push(`metadata->>'handle' = $${params.length}`);diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.jsindex 8383cde3e4..99d922b7fb 100644--- a/server/services/proactiveAlerts.js+++ b/server/services/proactiveAlerts.js@@ -291,11 +291,10 @@ async function checkUnansweredTribeThreads() {metadata: {personId: t.personId,source: t.source,- accountId: t.accountId,threadId: t.threadId,chatGuid: t.chatGuid,+ conversationId: t.conversationId,handle: t.handle,- replyToExternalId: t.replyToExternalId,daysAgo: t.daysAgo,},};diff --git a/server/services/tribeOutreach.js b/server/services/tribeOutreach.jsindex e7481aa333..f8cd381746 100644--- a/server/services/tribeOutreach.js+++ b/server/services/tribeOutreach.js@@ -41,6 +41,14 @@ const MAX_GROUNDING_EVENTS = 12;const MESSAGE_KINDS = new Set(['message.sent', 'message.received']);+// 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']);+// 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@@ -66,11 +74,15 @@ function threadFields(inbound, eventCount, ageMs) {personName: inbound.personName || 'someone',ring: inbound.ring || null,source: inbound.source || null,- accountId: inbound.accountId || null,+ // The detected conversation key must round-trip to draft generation so the+ // reply is grounded in THIS conversation. chatGuid (iMessage) /+ // conversationId (Signal) / threadId (email) are the per-source keys; handle+ // is the counterpart. personId is NOT a usable key — message events don't+ // persist it on their participants (it's resolved at read time).threadId: m.threadId || null,chatGuid: m.chatGuid || null,+ conversationId: m.conversationId || null,handle: m.handle || null,- replyToExternalId: m.externalId || null,lastInboundAt: inbound.happenedAt,daysAgo: Math.floor(ageMs / DAY_MS),snippet: String(inbound.summary || inbound.title || '').trim(),@@ -161,33 +173,24 @@ export async function findUnansweredTribeThreads({const from = new Date(now - withinDays * DAY_MS).toISOString();// Two kind-filtered queries instead of one broad scan: the timeline is capped// at 2000 rows per query, so on a busy install a single unfiltered query could- // return 2000 non-message rows and drop every message event. Fetch inbound- // within the window; fetch outbound WITHOUT a `from` bound (2000 newest) so it- // doubles as the source-capability probe below — a source that has never- // recorded an outbound turn (e.g. email, whose sync ingests the inbox only and- // never emits `message.sent`) must not have its stale inbound reported as- // "unanswered" just because a reply is structurally invisible to the timeline.+ // return 2000 non-message rows and drop every message event.const [received, sent] = await Promise.all([listEvents({ from, kind: 'message.received', limit: 2000 }).catch(() => []),- listEvents({ kind: 'message.sent', limit: 2000 }).catch(() => []),+ listEvents({ from, kind: 'message.sent', limit: 2000 }).catch(() => []),]);- // Sources that demonstrably record outbound activity (two-way observable).- const outboundSources = new Set();- for (const ev of sent) if (ev.source) outboundSources.add(ev.source);-- // Keep every outbound turn — it only needs to cancel the unanswered flag for- // its conversation (grouped by chatGuid/conversationId/threadId).- const tagged = [...sent];+ // Keep every outbound turn from a two-way source — it only needs to cancel the+ // unanswered flag for its conversation (grouped by chatGuid/conversationId).+ const tagged = sent.filter((ev) => TWO_WAY_SOURCES.has(ev.source));for (const ev of received) {- // Only nudge for sources we can actually see replies on; otherwise every- // stale Tribe inbound would read as unanswered forever (finding: email).- if (!outboundSources.has(ev.source)) continue;- // Resolve the counterpart to a Tribe person (handle first, then any- // participant with a resolved personId). Drop inbound we can't tie to Tribe.+ // Only nudge for sources where a reply would actually be visible (chat).+ if (!TWO_WAY_SOURCES.has(ev.source)) continue;+ // Resolve the SENDER to a Tribe person — the event's handle, else the first+ // participant (message.from). NOT "any participant with a personId": a group+ // thread from an untracked sender to a Tribe recipient would otherwise be+ // misattributed to the recipient. Drop inbound we can't tie to a Tribe sender.const enriched = enrichActivityEvent(ev, ctx);- let personId = enriched.personId;- if (!personId) personId = (enriched.participants || []).find((p) => p.personId)?.personId || null;+ const personId = enriched.personId || enriched.participants?.[0]?.personId || null;if (!personId) continue;const ring = ringById.get(personId);if (!ring || ring === 'external') continue;@@ -202,11 +205,11 @@ export async function findUnansweredTribeThreads({return threads.slice(0, Math.max(0, limit));}-// Build a synthetic thread (buildThreadContext / generateReplyBody shape) from-// the conversation's own timeline events when no rich provider cache is available-// (iMessage/Signal, or an email thread pruned from cache). The message summaries-// are the actual message text (shortSummary-capped), so this still grounds the-// reply in the real conversation. `selfName` labels the user's own sent turns.+// Build a synthetic thread (buildThreadContext / generateReplyBody shape) from the+// conversation's own timeline events. The message summaries are the actual message+// text (shortSummary-capped), so this grounds the reply in the real conversation —+// including the user's own sent turns (labeled "You"), which is why the draft query+// keys on the conversation, not just the counterpart handle.function timelineThreadMessages(events, personName) {return (events || []).filter((ev) => MESSAGE_KINDS.has(ev.kind) && (ev.summary || ev.title))@@ -219,92 +222,54 @@ function timelineThreadMessages(events, personName) {}));}-function replySubject(subject) {- const s = String(subject || '').trim();- if (!s) return '';- return /^re:/i.test(s) ? s : `Re: ${s}`;-}-/**- * Generate a grounded outreach draft for one unanswered thread and file 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.+ * Generate a grounded outreach draft for one detected unanswered thread and file+ * 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.** @returns {Promise<{ draft, person: { id, name } | null }>}*/export async function generateOutreachDraft({personId = null,source = null,- accountId = null,- threadId = null,chatGuid = null,+ conversationId = null,+ threadId = null,handle = null,- replyToExternalId = null,instructions = '',useVoice,} = {}) {- const [- { getPerson },- { getAccount },- { getThread },- { listEvents },- { generateReplyBody },- { createDraft },- ] = await Promise.all([+ const [{ getPerson }, { listEvents }, { generateReplyBody }, { createDraft }] = await Promise.all([import('./tribe.js'),- import('./messageAccounts.js'),- import('./messageSync.js'),import('./humanActivity.js'),import('./messageEvaluator.js'),import('./messageDrafts.js'),]);const person = personId ? await getPerson(personId).catch(() => null) : null;- // accountId is optional: iMessage/Signal threads have no message account, so a- // real messageAccounts row exists only for email sources. Absent/unknown → the- // draft grounds off the timeline and stays review-only (no derived send channel).- const account = accountId ? await getAccount(accountId).catch(() => null) : null;- const selfEmail = String(account?.email || '').trim().toLowerCase();-- // Prefer the rich provider cache (full message bodies) when an email account +- // threadId are present; otherwise ground off the conversation's timeline events.- let cacheThread = [];- if (account && threadId) {- cacheThread = await getThread(accountId, threadId).catch(() => []);- }-- let replyTo = null;- let threadMessages = null;- if (cacheThread.length) {- // Reply to the EXACT detected inbound first (its externalId came from the- // Tribe-resolved timeline event). Only when that message isn't in the cache- // fall back to the newest non-self inbound — in a multi-participant thread the- // newest inbound may be from someone else entirely, so anchoring on the- // detected message keeps the draft addressed to the right person.- replyTo = (replyToExternalId ? cacheThread.find((m) => m.externalId === replyToExternalId) : null)- || [...cacheThread].reverse().find((m) => {- const fromEmail = String(m.from?.email || '').trim().toLowerCase();- return !(selfEmail && fromEmail === selfEmail);- })- || cacheThread[cacheThread.length - 1];- threadMessages = cacheThread;- } else {- // Timeline grounding: pull this conversation's message events. chatGuid is the- // most selective key; fall back to handle, then the person's whole history.- const convoEvents = await listEvents({- source: source || undefined,- chatGuid: chatGuid || undefined,- handle: chatGuid ? undefined : (handle || undefined),- personId: (chatGuid || handle) ? undefined : (personId || undefined),- limit: 200,- }).catch(() => []);- const msgs = timelineThreadMessages(convoEvents, person?.name);- threadMessages = msgs;- // Reply to the last inbound turn (the person's), else the newest turn.- replyTo = [...msgs].reverse().find((m) => m.from?.name !== 'You') || msgs[msgs.length - 1] || null;- }+ // Ground the reply in the actual conversation, pulled from the timeline by the+ // DETECTED conversation key — chatGuid (iMessage) / conversationId (Signal) /+ // threadId (email) / handle (counterpart). NOT personId: message events don't+ // persist it on their participants, so a personId query returns nothing. Pass+ // exactly the most-selective key present (listEvents ANDs its filters).+ const convoEvents = await listEvents({+ source: source || undefined,+ chatGuid: chatGuid || undefined,+ conversationId: chatGuid ? undefined : (conversationId || undefined),+ threadId: (chatGuid || conversationId) ? undefined : (threadId || undefined),+ handle: (chatGuid || conversationId || threadId) ? undefined : (handle || undefined),+ limit: 200,+ }).catch(() => []);+ const threadMessages = timelineThreadMessages(convoEvents, person?.name);+ // Reply to the last inbound turn (the person's), else the newest turn.+ const replyTo = [...threadMessages].reverse().find((m) => m.from?.name !== 'You')+ || threadMessages[threadMessages.length - 1]+ || null;if (!replyTo) {// No conversational grounding at all — refuse rather than fabricate context.throw new ServerError('No conversation history found to ground an outreach draft', { status: 404 });@@ -319,28 +284,24 @@ export async function generateOutreachDraft({throw new ServerError('Could not generate an outreach draft — check your reply provider in Messages > Config', { status: 502 });}- // Recipient: `to` is a string[] of addresses/handles (the shape every existing- // draft consumer expects — DraftsTab and the Gmail serializer both call- // `draft.to.join(', ')`). Prefer the detected sender's email, else the person's- // known email, else the conversation handle / phone for review-only channels.+ // Recipient: `to` is a string[] (the shape every draft consumer expects —+ // DraftsTab and the Gmail serializer both call `draft.to.join(', ')`). Chat+ // sources are review-only, so prefer the actual chat handle/phone over a generic+ // person email — the To must name the channel the conversation happened on.const to = [];- const recipient = replyTo.from?.email- || person?.emails?.[0]- || handle- || person?.phones?.[0];+ const recipient = handle || person?.phones?.[0] || person?.emails?.[0];if (recipient) to.push(recipient);const draft = await createDraft({- accountId: accountId || null,- replyToMessageId: replyTo.id || null,- threadId: threadId || replyTo.threadId || null,+ accountId: null,+ threadId: threadId || null,to,- subject: replySubject(replyTo.subject),+ subject: '',body,// Distinct provenance so the drafts list can badge Tribe-originated outreach.generatedBy: 'tribe-outreach',- // Only email accounts have a real send channel; leave others as review-only.- sendVia: account ? (account.type === 'gmail' ? 'api' : 'playwright') : 'review',+ // Chat sources have no programmatic send channel — review-only (never sent).+ sendVia: 'review',});console.log(`🤝 Outreach draft filed for ${person?.name || 'a Tribe contact'} (${source || 'timeline'})`);