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): coalesce concurrent generation, revalidate before reuse, stale anchor, per-conversation deep-link
[._.]/ Adam Eivy5e298c8ec4f7
diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsxindex cec99ffcc4..a4537b9409 100644--- a/client/src/pages/Tribe.jsx+++ b/client/src/pages/Tribe.jsx@@ -589,10 +589,11 @@ function OutreachQueue() {const [copiedKey, setCopiedKey] = useState(null);const [highlightKey, setHighlightKey] = useState(null);const rowRefs = useRef({});- // A proactive alert deep-links here as ?outreach=<personId> — scroll to and- // highlight that person's thread so clicking one of several alerts lands on it.+ // A proactive alert deep-links here as ?outreach=<conversationKey> — scroll to and+ // highlight that exact thread so clicking one of several alerts lands on it (keyed+ // by conversation, since one person can have multiple unanswered threads).const [searchParams] = useSearchParams();- const outreachPersonId = searchParams.get('outreach');+ const outreachKey = searchParams.get('outreach');useEffect(() => {let cancelled = false;@@ -603,15 +604,15 @@ function OutreachQueue() {}, []);useEffect(() => {- if (!outreachPersonId || !Array.isArray(threads)) return;- const target = threads.find((t) => t.personId === outreachPersonId);+ if (!outreachKey || !Array.isArray(threads)) return;+ const target = threads.find((t) => t.conversationKey === outreachKey);if (!target) return;const el = rowRefs.current[target.conversationKey];if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });setHighlightKey(target.conversationKey);const timer = setTimeout(() => setHighlightKey((prev) => (prev === target.conversationKey ? null : prev)), 2500);return () => clearTimeout(timer);- }, [outreachPersonId, threads]);+ }, [outreachKey, threads]);const generate = async (thread) => {const key = thread.conversationKey;diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.jsindex e900d4f295..d8670b18ea 100644--- a/server/services/proactiveAlerts.js+++ b/server/services/proactiveAlerts.js@@ -287,9 +287,10 @@ async function checkUnansweredTribeThreads() {severity: t.daysAgo >= 7 ? 'high' : 'medium',title: `Unanswered: ${t.personName}`,detail: `You never replied to ${snippet} (${ago(t.daysAgo)})`,- // Deep-link to the specific outreach item (person) so clicking one of several- // alerts scrolls to and highlights the right thread, not just the Care Queue.- link: `/tribe?tab=care&outreach=${encodeURIComponent(t.personId)}`,+ // Deep-link to the specific outreach item by CONVERSATION (not person — one+ // person can have several unanswered threads, e.g. iMessage + Signal), so+ // clicking one of several alerts scrolls to and highlights the right thread.+ link: `/tribe?tab=care&outreach=${encodeURIComponent(t.conversationKey)}`,metadata: {personId: t.personId,source: t.source,diff --git a/server/services/tribeOutreach.js b/server/services/tribeOutreach.jsindex cfea6691b1..1018a927cc 100644--- a/server/services/tribeOutreach.js+++ b/server/services/tribeOutreach.js@@ -251,6 +251,12 @@ function eventToMessage(ev, personName) {};}+// Per-(conversation, inbound) in-flight guard so two concurrent requests for the+// same thread (two tabs, a retry) don't each fire a paid LLM call before either+// files its draft — the file-write queue serializes the writes, not the+// lookup→generate→create span. The second caller awaits the first's result.+const inflightOutreach = new Map();+/*** 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@@ -262,7 +268,22 @@ function eventToMessage(ev, personName) {** @returns {Promise<{ draft, person: { id, name } | null }>}*/-export async function generateOutreachDraft({+export async function generateOutreachDraft(params = {}) {+ const conversationKey = params.chatGuid || params.conversationId || params.threadId || params.handle || null;+ // No key to guard on (validated away at the route, but defensive) → run directly.+ if (!conversationKey) return generateOutreachDraftImpl(params);+ const guardKey = `${conversationKey}::${params.lastInboundAt || ''}`;+ const pending = inflightOutreach.get(guardKey);+ if (pending) return pending;+ const promise = generateOutreachDraftImpl(params);+ inflightOutreach.set(guardKey, promise);+ promise.finally(() => {+ if (inflightOutreach.get(guardKey) === promise) inflightOutreach.delete(guardKey);+ }).catch(() => {}); // finally's own rejection is irrelevant; callers see `promise`+ return promise;+}++async function generateOutreachDraftImpl({personId = null,source = null,chatGuid = null,@@ -283,24 +304,6 @@ export async function generateOutreachDraft({const person = personId ? await getPerson(personId).catch(() => null) : null;const conversationKey = chatGuid || conversationId || threadId || handle || null;- // Idempotency: a Tribe-outreach draft is a paid LLM call. Detection doesn't- // clear when a draft is filed (the inbound is still the last turn), so the same- // thread resurfaces after a page reload / tab remount. Reuse an existing un-sent- // draft for this conversation — but ONLY when it targets the SAME detected inbound- // (`lastInboundAt`): once the contact sends a newer message, that draft is stale- // and a fresh reply must be generated, not the old one returned forever (review-- // only drafts never reach 'sent').- if (conversationKey) {- const existing = (await listDrafts().catch(() => []))- .find((d) => d.generatedBy === 'tribe-outreach'- && d.conversationKey === conversationKey- && d.lastInboundAt === lastInboundAt- && d.status !== 'sent');- if (existing) {- return { draft: existing, person: person ? { id: person.id, name: person.name } : null, reused: true };- }- }-// 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@@ -333,15 +336,36 @@ export async function generateOutreachDraft({throw new ServerError('No conversation history found to ground an outreach draft', { status: 404 });}- // Revalidate against fresh timeline state: the Care Queue fetched once, so the- // user may have replied (a newer sync recorded a `message.sent`) between then and- // this click. Don't spend a paid LLM call drafting a reply to an already-answered- // thread — bail with a clear signal the client can surface instead.+ // Revalidate against fresh timeline state BEFORE any reuse or generation: the+ // Care Queue fetched once, so between then and this click the user may have+ // replied (a newer `message.sent`) OR the contact may have sent a follow-up (a+ // newer `message.received`). Either makes the detected anchor stale — bail with a+ // clear signal so we don't reply to the wrong (old) turn or an answered thread.+ // Doing this before the draft-reuse lookup means a since-answered thread returns+ // 409 even when an obsolete un-sent draft is still on file.const anchorT = Date.parse(anchorEv.happenedAt);- const alreadyReplied = sorted.some((ev) => ev.kind === 'message.sent' && Date.parse(ev.happenedAt) > anchorT);- if (alreadyReplied) {+ if (sorted.some((ev) => ev.kind === 'message.sent' && Date.parse(ev.happenedAt) > anchorT)) {throw new ServerError('You have already replied to this conversation', { status: 409, code: 'ALREADY_REPLIED' });}+ if (lastInboundAt && sorted.some((ev) => ev.kind === 'message.received' && Date.parse(ev.happenedAt) > anchorT)) {+ throw new ServerError('A newer message arrived — reload to draft a reply to the latest one', { status: 409, code: 'STALE_INBOUND' });+ }++ // Idempotency: a Tribe-outreach draft is a paid LLM call, and detection doesn't+ // clear when a draft is filed (the inbound is still the last turn), so the same+ // thread resurfaces after a reload / tab remount. Reuse an existing un-sent draft+ // for the SAME conversation + inbound instead of regenerating. (A newer inbound+ // has a different lastInboundAt and was already rejected above as stale.)+ if (conversationKey) {+ const existing = (await listDrafts().catch(() => []))+ .find((d) => d.generatedBy === 'tribe-outreach'+ && d.conversationKey === conversationKey+ && d.lastInboundAt === lastInboundAt+ && d.status !== 'sent');+ if (existing) {+ return { draft: existing, person: person ? { id: person.id, name: person.name } : null, reused: true };+ }+ }// Grounding context: the last N turns, but always keep the anchor in-window.const windowEvents = sorted.slice(-MAX_GROUNDING_EVENTS);diff --git a/server/services/tribeOutreach.test.js b/server/services/tribeOutreach.test.jsindex cb23032a67..1b7905bb35 100644--- a/server/services/tribeOutreach.test.js+++ b/server/services/tribeOutreach.test.js@@ -158,6 +158,11 @@ describe('generateOutreachDraft', () => {generateReplyBody.mockResolvedValue({ body: 'Hey Alex — sorry for the delay!' });createDraft.mockImplementation(async (d) => ({ id: 'draft-new', status: 'draft', ...d }));listDrafts.mockResolvedValue([]);+ // Default timeline: a single inbound matching the tests' lastInboundAt, so the+ // pre-generation freshness read (now runs before reuse) finds a fresh anchor.+ listEvents.mockResolvedValue([+ { kind: 'message.received', happenedAt: '2026-07-15T00:00:00.000Z', summary: 'hi' },+ ]);});it('reuses an existing un-sent outreach draft for the same conversation + inbound (no duplicate LLM call)', async () => {@@ -171,6 +176,16 @@ describe('generateOutreachDraft', () => {expect(createDraft).not.toHaveBeenCalled();});+ it('anchors the reply to the detected inbound even with older turns present', async () => {+ listEvents.mockResolvedValue([+ { kind: 'message.sent', happenedAt: '2026-07-10T00:00:00.000Z', summary: 'an older reply of mine' },+ { kind: 'message.received', happenedAt: '2026-07-15T00:00:00.000Z', summary: 'the detected one' },+ ]);+ await generateOutreachDraft({ personId: 'p1', source: 'imessage', chatGuid: 'chat-1', lastInboundAt: '2026-07-15T00:00:00.000Z' });+ const [replyTo] = generateReplyBody.mock.calls[0];+ expect(replyTo.bodyText).toBe('the detected one');+ });+it('does NOT reuse a draft for a stale inbound — a newer message generates a fresh draft', async () => {listDrafts.mockResolvedValue([{ id: 'draft-old', generatedBy: 'tribe-outreach', conversationKey: 'chat-1', lastInboundAt: '2026-07-15T00:00:00.000Z', status: 'draft', body: 'earlier' },@@ -196,19 +211,6 @@ describe('generateOutreachDraft', () => {expect(createDraft).toHaveBeenCalledWith(expect.objectContaining({ conversationKey: 'chat-1', sendVia: 'review' }));});- it('anchors the reply to the detected inbound timestamp, not the newest turn', async () => {- listEvents.mockResolvedValue([- { kind: 'message.received', happenedAt: '2026-07-15T00:00:00.000Z', summary: 'the one we detected' },- { kind: 'message.received', happenedAt: '2026-07-16T00:00:00.000Z', summary: 'a later turn from someone else' },- ]);- await generateOutreachDraft({- personId: 'p1', source: 'imessage', chatGuid: 'chat-1',- lastInboundAt: '2026-07-15T00:00:00.000Z',- });- const [replyTo] = generateReplyBody.mock.calls[0];- expect(replyTo.bodyText).toBe('the one we detected');- });-it('refuses (409) when a reply was sent after the detected inbound', async () => {listEvents.mockResolvedValue([{ kind: 'message.received', happenedAt: '2026-07-15T00:00:00.000Z', summary: 'you around?' },@@ -221,6 +223,28 @@ describe('generateOutreachDraft', () => {expect(createDraft).not.toHaveBeenCalled();});+ it('refuses (409 STALE_INBOUND) when a newer inbound arrived after the detected one', async () => {+ listEvents.mockResolvedValue([+ { kind: 'message.received', happenedAt: '2026-07-15T00:00:00.000Z', summary: 'the detected one' },+ { kind: 'message.received', happenedAt: '2026-07-18T00:00:00.000Z', summary: 'a newer follow-up' },+ ]);+ await expect(generateOutreachDraft({+ personId: 'p1', source: 'imessage', chatGuid: 'chat-1', lastInboundAt: '2026-07-15T00:00:00.000Z',+ })).rejects.toMatchObject({ status: 409, code: 'STALE_INBOUND' });+ expect(generateReplyBody).not.toHaveBeenCalled();+ });++ it('coalesces two concurrent generations for the same thread into one LLM call', async () => {+ listEvents.mockResolvedValue([+ { kind: 'message.received', happenedAt: '2026-07-15T00:00:00.000Z', summary: 'hi' },+ ]);+ const seed = { personId: 'p1', source: 'imessage', chatGuid: 'chat-1', lastInboundAt: '2026-07-15T00:00:00.000Z' };+ const [a, b] = await Promise.all([generateOutreachDraft(seed), generateOutreachDraft(seed)]);+ expect(generateReplyBody).toHaveBeenCalledTimes(1);+ expect(createDraft).toHaveBeenCalledTimes(1);+ expect(a.draft).toBe(b.draft);+ });+it('uses a chat-appropriate reply template, not the email default', async () => {listEvents.mockResolvedValue([{ kind: 'message.received', happenedAt: '2026-07-15T00:00:00.000Z', summary: 'hey' },