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): serialize draft writes, revalidate answered, chat prompt, fail-closed reads

[._.]/ Adam Eivy4f4ac78cbbe2
diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsx
index a7e7525515..e2c68bc8ad 100644
--- a/client/src/pages/Tribe.jsx
+++ b/client/src/pages/Tribe.jsx
@@ -610,7 +610,14 @@ function OutreachQueue() {
lastInboundAt: thread.lastInboundAt,
};
const result = await api.generateTribeOutreachDraft(seed, { silent: true }).catch((err) => {
- toast.error(err.message || 'Could not generate a draft');
+ // The thread may have been answered since the list loaded (409) — drop it
+ // rather than leave a stale nudge the user can re-click.
+ if (err?.status === 409 || err?.code === 'ALREADY_REPLIED') {
+ setThreads((prev) => (prev || []).filter((t) => t.conversationKey !== key));
+ toast.success(`Looks like you already replied to ${thread.personName}`);
+ } else {
+ toast.error(err.message || 'Could not generate a draft');
+ }
return null;
});
setBusyKeys((prev) => { const next = new Set(prev); next.delete(key); return next; });
diff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.js
index 846482e349..07668b7a39 100644
--- a/server/services/messageDrafts.js
+++ b/server/services/messageDrafts.js
@@ -2,9 +2,17 @@
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { atomicWrite, ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
const DRAFTS_FILE = join(PATHS.messages, 'drafts.json');
+// Serialize every read-modify-write of drafts.json onto a single tail so two
+// concurrent createDraft/updateDraft/delete calls can't read the same snapshot and
+// have one atomic rename clobber the other's just-persisted draft. This matters
+// now that Tribe outreach (#2158) permits several draft generations in flight at
+// once — each finishing LLM call lands its own createDraft.
+const queueWrite = createFileWriteQueue();
+
async function loadDrafts() {
await ensureDir(PATHS.messages);
const content = await tryReadFile(DRAFTS_FILE);
@@ -38,43 +46,47 @@ export async function getDraft(id) {
}
export async function createDraft(data) {
- const drafts = await loadDrafts();
- const draft = {
- id: uuidv4(),
- accountId: data.accountId,
- replyToMessageId: data.replyToMessageId || null,
- threadId: data.threadId || null,
- // Stable per-conversation key + the inbound timestamp it answers, for
- // provenance-scoped dedup (Tribe outreach, #2158) — null for ordinary drafts.
- conversationKey: data.conversationKey || null,
- lastInboundAt: data.lastInboundAt || null,
- to: data.to || [],
- cc: data.cc || [],
- subject: data.subject || '',
- body: data.body || '',
- status: 'draft',
- generatedBy: data.generatedBy || 'manual',
- sendVia: data.sendVia || 'api',
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString()
- };
- drafts.push(draft);
- await saveDrafts(drafts);
- console.log(`📝 Message draft created: "${draft.subject}" via ${draft.sendVia}`);
- return draft;
+ return queueWrite(async () => {
+ const drafts = await loadDrafts();
+ const draft = {
+ id: uuidv4(),
+ accountId: data.accountId,
+ replyToMessageId: data.replyToMessageId || null,
+ threadId: data.threadId || null,
+ // Stable per-conversation key + the inbound timestamp it answers, for
+ // provenance-scoped dedup (Tribe outreach, #2158) — null for ordinary drafts.
+ conversationKey: data.conversationKey || null,
+ lastInboundAt: data.lastInboundAt || null,
+ to: data.to || [],
+ cc: data.cc || [],
+ subject: data.subject || '',
+ body: data.body || '',
+ status: 'draft',
+ generatedBy: data.generatedBy || 'manual',
+ sendVia: data.sendVia || 'api',
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ };
+ drafts.push(draft);
+ await saveDrafts(drafts);
+ console.log(`📝 Message draft created: "${draft.subject}" via ${draft.sendVia}`);
+ return draft;
+ });
}
export async function updateDraft(id, updates) {
- const drafts = await loadDrafts();
- const idx = drafts.findIndex(d => d.id === id);
- if (idx === -1) return null;
- const allowed = ['to', 'cc', 'subject', 'body', 'status'];
- for (const key of allowed) {
- if (updates[key] !== undefined) drafts[idx][key] = updates[key];
- }
- drafts[idx].updatedAt = new Date().toISOString();
- await saveDrafts(drafts);
- return drafts[idx];
+ return queueWrite(async () => {
+ const drafts = await loadDrafts();
+ const idx = drafts.findIndex(d => d.id === id);
+ if (idx === -1) return null;
+ const allowed = ['to', 'cc', 'subject', 'body', 'status'];
+ for (const key of allowed) {
+ if (updates[key] !== undefined) drafts[idx][key] = updates[key];
+ }
+ drafts[idx].updatedAt = new Date().toISOString();
+ await saveDrafts(drafts);
+ return drafts[idx];
+ });
}
export async function approveDraft(id) {
@@ -82,20 +94,24 @@ export async function approveDraft(id) {
}
export async function deleteDraftsByAccountId(accountId) {
- const drafts = await loadDrafts();
- const remaining = drafts.filter(d => d.accountId !== accountId);
- if (remaining.length < drafts.length) {
- await saveDrafts(remaining);
- console.log(`🗑️ Deleted ${drafts.length - remaining.length} drafts for account ${accountId}`);
- }
+ return queueWrite(async () => {
+ const drafts = await loadDrafts();
+ const remaining = drafts.filter(d => d.accountId !== accountId);
+ if (remaining.length < drafts.length) {
+ await saveDrafts(remaining);
+ console.log(`🗑️ Deleted ${drafts.length - remaining.length} drafts for account ${accountId}`);
+ }
+ });
}
export async function deleteDraft(id) {
- const drafts = await loadDrafts();
- const idx = drafts.findIndex(d => d.id === id);
- if (idx === -1) return false;
- drafts.splice(idx, 1);
- await saveDrafts(drafts);
- console.log(`🗑️ Message draft deleted: ${id}`);
- return true;
+ return queueWrite(async () => {
+ const drafts = await loadDrafts();
+ const idx = drafts.findIndex(d => d.id === id);
+ if (idx === -1) return false;
+ drafts.splice(idx, 1);
+ await saveDrafts(drafts);
+ console.log(`🗑️ Message draft deleted: ${id}`);
+ return true;
+ });
}
diff --git a/server/services/messageEvaluator.js b/server/services/messageEvaluator.js
index af6c90a582..58d1e93e4e 100644
--- a/server/services/messageEvaluator.js
+++ b/server/services/messageEvaluator.js
@@ -192,14 +192,17 @@ ${formatted}
* @returns {{ body: string }}
*/
export async function generateReplyBody(message, instructions = '', options = {}) {
- const { useVoice, threadMessages } = options;
+ const { useVoice, threadMessages, templateOverride } = options;
const { provider, model, msgConfig } = await resolveProviderConfig('reply');
// Determine if voice mode is active (explicit param > settings default)
const shouldUseVoice = useVoice ?? msgConfig.voiceMode ?? false;
- // Build prompt from template
- let template = msgConfig.replyTemplate || 'Write a professional reply to this email.\n\nFrom: {{from}}\nSubject: {{subject}}\nBody:\n{{body}}';
+ // Build prompt from template. `templateOverride` lets a caller supply a
+ // channel-appropriate prompt (e.g. Tribe chat outreach, #2158) instead of the
+ // email-toned default or the user's email replyTemplate — a text message needs
+ // a casual, subject-less reply, not "Write a professional reply to this email."
+ let template = templateOverride || msgConfig.replyTemplate || 'Write a professional reply to this email.\n\nFrom: {{from}}\nSubject: {{subject}}\nBody:\n{{body}}';
// Sanitize untrusted email content to prevent prompt injection
const vars = {
from: sanitize(message.from?.name || message.from?.email || 'Unknown'),
diff --git a/server/services/tribeOutreach.js b/server/services/tribeOutreach.js
index 1852a37917..474df2dc05 100644
--- a/server/services/tribeOutreach.js
+++ b/server/services/tribeOutreach.js
@@ -49,6 +49,11 @@ const MESSAGE_KINDS = new Set(['message.sent', 'message.received']);
// per-account sent/replied ingestion exists — see #2796.
const TWO_WAY_SOURCES = new Set(['imessage', 'signal']);
+// Channel-appropriate reply prompt for chat outreach — generateReplyBody's default
+// template is email-toned ("Write a professional reply to this email"), which reads
+// wrong for a text message. {{from}}/{{body}} are substituted by generateReplyBody.
+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.\n\nFrom: {{from}}\nTheir message:\n{{body}}';
+
// 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
@@ -178,14 +183,18 @@ export async function findUnansweredTribeThreads({
// mark a thread answered.
const received = [];
const sent = [];
- await Promise.all([...TWO_WAY_SOURCES].map(async (src) => {
- const [r, s] = await Promise.all([
- listEvents({ from, source: src, kind: 'message.received', limit: 2000 }).catch(() => []),
- listEvents({ from, source: src, kind: 'message.sent', limit: 2000 }).catch(() => []),
- ]);
- received.push(...r);
- sent.push(...s);
- }));
+ await Promise.all([...TWO_WAY_SOURCES].map((src) =>
+ // Fail CLOSED per source: if EITHER direction's query fails, drop this source's
+ // turns entirely. Substituting [] for only the failed direction would leave
+ // received without its sent counterpart, making every inbound look unanswered
+ // and emitting false nudges — the function's contract is to stay quiet on a
+ // read failure, not to nudge on half the data.
+ Promise.all([
+ listEvents({ from, source: src, kind: 'message.received', limit: 2000 }),
+ listEvents({ from, source: src, kind: 'message.sent', limit: 2000 }),
+ ]).then(([r, s]) => { received.push(...r); sent.push(...s); })
+ .catch(() => { /* partial read → drop this source to avoid false nudges */ })
+ ));
// Every outbound turn just needs to cancel the unanswered flag for its
// conversation (grouped by chatGuid/conversationId).
@@ -311,13 +320,28 @@ export async function generateOutreachDraft({
// No conversational grounding at all — refuse rather than fabricate context.
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.
+ const anchorT = Date.parse(anchorEv.happenedAt);
+ const alreadyReplied = sorted.some((ev) => ev.kind === 'message.sent' && Date.parse(ev.happenedAt) > anchorT);
+ if (alreadyReplied) {
+ throw new ServerError('You have already replied to this conversation', { status: 409, code: 'ALREADY_REPLIED' });
+ }
+
// Grounding context: the last N turns, but always keep the anchor in-window.
const windowEvents = sorted.slice(-MAX_GROUNDING_EVENTS);
if (!windowEvents.includes(anchorEv)) windowEvents.unshift(anchorEv);
const threadMessages = windowEvents.map((ev) => eventToMessage(ev, person?.name));
const replyTo = eventToMessage(anchorEv, person?.name);
- const aiResult = await generateReplyBody(replyTo, instructions, { useVoice, threadMessages }).catch((err) => {
+ const aiResult = await generateReplyBody(replyTo, instructions, {
+ useVoice,
+ threadMessages,
+ templateOverride: OUTREACH_CHAT_TEMPLATE,
+ }).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.js
index e38fa78e7b..cb23032a67 100644
--- a/server/services/tribeOutreach.test.js
+++ b/server/services/tribeOutreach.test.js
@@ -209,6 +209,29 @@ describe('generateOutreachDraft', () => {
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?' },
+ { kind: 'message.sent', happenedAt: '2026-07-16T00:00:00.000Z', summary: 'yes!' },
+ ]);
+ await expect(generateOutreachDraft({
+ personId: 'p1', source: 'imessage', chatGuid: 'chat-1', lastInboundAt: '2026-07-15T00:00:00.000Z',
+ })).rejects.toMatchObject({ status: 409 });
+ expect(generateReplyBody).not.toHaveBeenCalled();
+ expect(createDraft).not.toHaveBeenCalled();
+ });
+
+ 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' },
+ ]);
+ await generateOutreachDraft({ personId: 'p1', source: 'imessage', chatGuid: 'chat-1' });
+ const [, , opts] = generateReplyBody.mock.calls[0];
+ expect(opts.templateOverride).toMatch(/text message/i);
+ expect(opts.templateOverride).toMatch(/casual/i);
+ expect(opts.templateOverride).not.toMatch(/professional reply to this email/i);
+ });
+
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([