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

address review (codex): anchor group-chat drafts + idempotent generation + review-only copy

[._.]/ Adam Eivybc485e3999d5
diff --git a/client/src/components/messages/DraftsTab.jsx b/client/src/components/messages/DraftsTab.jsx
index 7e7da15be3..6aeccf17b3 100644
--- a/client/src/components/messages/DraftsTab.jsx
+++ b/client/src/components/messages/DraftsTab.jsx
@@ -1,15 +1,24 @@
import { useState, useEffect, useCallback } from 'react';
-import { FileText, Trash2, Send, Check, RefreshCw } from 'lucide-react';
+import { FileText, Trash2, Send, Check, RefreshCw, Copy } from 'lucide-react';
import toast from '../ui/Toast';
import * as api from '../../services/api';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
+import { copyToClipboard } from '../../lib/clipboard.js';
export default function DraftsTab({ accounts }) {
const [drafts, setDrafts] = useState([]);
const [loading, setLoading] = useState(true);
+ const [copiedId, setCopiedId] = useState(null);
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
+ const handleCopy = async (draft) => {
+ const ok = await copyToClipboard(draft.body || '');
+ if (!ok) { toast.error('Could not copy to clipboard'); return; }
+ setCopiedId(draft.id);
+ setTimeout(() => setCopiedId((prev) => (prev === draft.id ? null : prev)), 1500);
+ };
+
const fetchDrafts = useCallback(async () => {
setLoading(true);
const data = await api.getMessageDrafts().catch(() => []);
@@ -119,9 +128,19 @@ export default function DraftsTab({ accounts }) {
</button>
)}
{draft.sendVia === 'review' && (
- <span className="text-xs text-gray-500" title="No programmatic send — copy and send from your messaging app">
- Review only
- </span>
+ <>
+ <span className="text-xs text-gray-500" title="No programmatic send — copy and send from your messaging app">
+ Review only
+ </span>
+ <button
+ onClick={() => handleCopy(draft)}
+ className="p-1 text-gray-400 hover:text-port-accent transition-colors"
+ title="Copy message"
+ aria-label="Copy message"
+ >
+ {copiedId === draft.id ? <Check size={16} /> : <Copy size={16} />}
+ </button>
+ </>
)}
{/* Review-only drafts never reach a 'sent' state (there's no send
channel), so keep Delete available at any status — otherwise an
@@ -141,7 +160,9 @@ export default function DraftsTab({ accounts }) {
{draft.to?.length > 0 && (
<div className="text-xs text-gray-500">To: {draft.to.join(', ')}</div>
)}
- <div className="text-sm text-gray-400 whitespace-pre-wrap line-clamp-3">
+ {/* Review-only drafts are sent by hand, so show the full body (not
+ clamped) — it's the text the user copies into their messaging app. */}
+ <div className={`text-sm text-gray-400 whitespace-pre-wrap ${draft.sendVia === 'review' ? '' : 'line-clamp-3'}`}>
{draft.body}
</div>
{isConfirming(draft.id) && (
diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsx
index a620aa1c46..e4eeba3b7e 100644
--- a/client/src/pages/Tribe.jsx
+++ b/client/src/pages/Tribe.jsx
@@ -607,6 +607,7 @@ function OutreachQueue() {
chatGuid: thread.chatGuid,
conversationId: thread.conversationId,
handle: thread.handle,
+ lastInboundAt: thread.lastInboundAt,
};
const result = await api.generateTribeOutreachDraft(seed, { silent: true }).catch((err) => {
toast.error(err.message || 'Could not generate a draft');
diff --git a/server/routes/tribe.js b/server/routes/tribe.js
index 7e0c21b41b..574691e047 100644
--- a/server/routes/tribe.js
+++ b/server/routes/tribe.js
@@ -69,6 +69,7 @@ const outreachDraftSchema = z.object({
chatGuid: z.string().max(500).nullable().optional(),
conversationId: z.string().max(500).nullable().optional(),
handle: z.string().max(320).nullable().optional(),
+ lastInboundAt: z.string().datetime().nullable().optional(),
instructions: z.string().max(2000).optional().default(''),
useVoice: z.boolean().optional(),
});
diff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.js
index 83afa57bd7..4b36e7ca59 100644
--- a/server/services/messageDrafts.js
+++ b/server/services/messageDrafts.js
@@ -44,6 +44,9 @@ export async function createDraft(data) {
accountId: data.accountId,
replyToMessageId: data.replyToMessageId || null,
threadId: data.threadId || null,
+ // Stable per-conversation key for provenance-scoped dedup (Tribe outreach,
+ // #2158) — null for ordinary drafts.
+ conversationKey: data.conversationKey || null,
to: data.to || [],
cc: data.cc || [],
subject: data.subject || '',
diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.js
index 99d922b7fb..97c6cdfb19 100644
--- a/server/services/proactiveAlerts.js
+++ b/server/services/proactiveAlerts.js
@@ -295,6 +295,7 @@ async function checkUnansweredTribeThreads() {
chatGuid: t.chatGuid,
conversationId: t.conversationId,
handle: t.handle,
+ lastInboundAt: t.lastInboundAt,
daysAgo: t.daysAgo,
},
};
diff --git a/server/services/tribeOutreach.js b/server/services/tribeOutreach.js
index f8cd381746..0ff4526917 100644
--- a/server/services/tribeOutreach.js
+++ b/server/services/tribeOutreach.js
@@ -185,12 +185,15 @@ export async function findUnansweredTribeThreads({
for (const ev of received) {
// 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.
+ // Resolve the SENDER to a Tribe person via the event's counterpart handle
+ // ONLY. For iMessage/Signal a received event's `metadata.handle` IS the
+ // sender, which is what `enrichActivityEvent` resolves. Do NOT fall back to
+ // participants[]: iMessage builds it from every chat member in unspecified
+ // order, so a group message from an untracked sender to a Tribe member would
+ // be misattributed to that member — a false "unanswered" nudge for someone
+ // who never wrote. An unresolved sender is skipped, not guessed.
const enriched = enrichActivityEvent(ev, ctx);
- const personId = enriched.personId || enriched.participants?.[0]?.personId || null;
+ const personId = enriched.personId || null;
if (!personId) continue;
const ring = ringById.get(personId);
if (!ring || ring === 'external') continue;
@@ -240,10 +243,11 @@ export async function generateOutreachDraft({
conversationId = null,
threadId = null,
handle = null,
+ lastInboundAt = null,
instructions = '',
useVoice,
} = {}) {
- const [{ getPerson }, { listEvents }, { generateReplyBody }, { createDraft }] = await Promise.all([
+ const [{ getPerson }, { listEvents }, { generateReplyBody }, { createDraft, listDrafts }] = await Promise.all([
import('./tribe.js'),
import('./humanActivity.js'),
import('./messageEvaluator.js'),
@@ -251,6 +255,20 @@ 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. If an un-sent outreach
+ // draft already exists for this conversation, return it instead of generating —
+ // otherwise a second click bills the provider again and files a duplicate.
+ if (conversationKey) {
+ const existing = (await listDrafts().catch(() => []))
+ .find((d) => d.generatedBy === 'tribe-outreach' && d.conversationKey === conversationKey && 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) /
@@ -266,8 +284,14 @@ export async function generateOutreachDraft({
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')
+ // Anchor to the EXACT detected inbound (by its timestamp) — a group chat's
+ // chatGuid loads every member's turns, so "newest inbound from anyone" could
+ // reply to a different member who spoke after the Tribe person. Fall back to the
+ // newest inbound, then the newest turn, only when the anchor isn't found.
+ const replyTo = (lastInboundAt
+ ? threadMessages.find((m) => m.from?.name !== 'You' && m.date === lastInboundAt)
+ : null)
+ || [...threadMessages].reverse().find((m) => m.from?.name !== 'You')
|| threadMessages[threadMessages.length - 1]
|| null;
if (!replyTo) {
@@ -300,6 +324,8 @@ export async function generateOutreachDraft({
body,
// Distinct provenance so the drafts list can badge Tribe-originated outreach.
generatedBy: 'tribe-outreach',
+ // Stable per-conversation key so a repeat request reuses this draft (above).
+ conversationKey,
// Chat sources have no programmatic send channel — review-only (never sent).
sendVia: 'review',
});
diff --git a/server/services/tribeOutreach.test.js b/server/services/tribeOutreach.test.js
index 63d010ffdc..c02c165b08 100644
--- a/server/services/tribeOutreach.test.js
+++ b/server/services/tribeOutreach.test.js
@@ -1,6 +1,19 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { groupUnansweredThreads } from './tribeOutreach.js';
+import { groupUnansweredThreads, generateOutreachDraft } from './tribeOutreach.js';
+
+// generateOutreachDraft dynamically imports these — mock them so the draft-side
+// logic (idempotent reuse, anchoring the reply to the detected inbound) is
+// testable without a DB or a live LLM.
+vi.mock('./tribe.js', () => ({ getPerson: vi.fn() }));
+vi.mock('./humanActivity.js', () => ({ listEvents: vi.fn() }));
+vi.mock('./messageEvaluator.js', () => ({ generateReplyBody: vi.fn() }));
+vi.mock('./messageDrafts.js', () => ({ createDraft: vi.fn(), listDrafts: vi.fn() }));
+
+import { getPerson } from './tribe.js';
+import { listEvents } from './humanActivity.js';
+import { generateReplyBody } from './messageEvaluator.js';
+import { createDraft, listDrafts } from './messageDrafts.js';
// `groupUnansweredThreads` is the pure detection core — no DB, no LLM. These
// tests pin the "unanswered inbound from a Tribe person, within the actionable
@@ -137,3 +150,59 @@ describe('groupUnansweredThreads', () => {
expect(out).toHaveLength(0);
});
});
+
+describe('generateOutreachDraft', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getPerson.mockResolvedValue({ id: 'p1', name: 'Alex', phones: ['+15550001'], emails: [] });
+ generateReplyBody.mockResolvedValue({ body: 'Hey Alex — sorry for the delay!' });
+ createDraft.mockImplementation(async (d) => ({ id: 'draft-new', status: 'draft', ...d }));
+ listDrafts.mockResolvedValue([]);
+ });
+
+ it('reuses an existing un-sent outreach draft for the same conversation (no duplicate LLM call)', async () => {
+ listDrafts.mockResolvedValue([
+ { id: 'draft-old', generatedBy: 'tribe-outreach', conversationKey: 'chat-1', status: 'draft', body: 'earlier' },
+ ]);
+ const result = await generateOutreachDraft({ personId: 'p1', source: 'imessage', chatGuid: 'chat-1' });
+ expect(result.reused).toBe(true);
+ expect(result.draft.id).toBe('draft-old');
+ expect(generateReplyBody).not.toHaveBeenCalled();
+ expect(createDraft).not.toHaveBeenCalled();
+ });
+
+ it('does not reuse an already-sent draft — generates a fresh one', async () => {
+ listDrafts.mockResolvedValue([
+ { id: 'draft-sent', generatedBy: 'tribe-outreach', conversationKey: 'chat-1', status: 'sent', body: 'sent' },
+ ]);
+ listEvents.mockResolvedValue([
+ { kind: 'message.received', happenedAt: '2026-07-15T00:00:00.000Z', summary: 'you around?' },
+ ]);
+ const result = await generateOutreachDraft({ personId: 'p1', source: 'imessage', chatGuid: 'chat-1' });
+ expect(result.reused).toBeUndefined();
+ expect(generateReplyBody).toHaveBeenCalled();
+ 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('prefers the chat handle over a person email in the review-only recipient', async () => {
+ getPerson.mockResolvedValue({ id: 'p1', name: 'Alex', phones: [], emails: ['[email protected]'] });
+ listEvents.mockResolvedValue([
+ { kind: 'message.received', happenedAt: '2026-07-15T00:00:00.000Z', summary: 'hi' },
+ ]);
+ await generateOutreachDraft({ personId: 'p1', source: 'imessage', chatGuid: 'chat-1', handle: '+15559999' });
+ expect(createDraft).toHaveBeenCalledWith(expect.objectContaining({ to: ['+15559999'] }));
+ });
+});