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
fix: reconcile interrupted message sends before allowing retries (#8793)
[._.]/ Adam Eivyb17d631f9f1b
diff --git a/client/src/components/messages/DraftsTab.jsx b/client/src/components/messages/DraftsTab.jsxindex 5c297b2601..a9964f841a 100644--- a/client/src/components/messages/DraftsTab.jsx+++ b/client/src/components/messages/DraftsTab.jsx@@ -6,6 +6,60 @@ import InlineConfirmRow from '../ui/InlineConfirmRow';import { useConfirmDelete } from '../../hooks/useConfirmDelete';import { copyToClipboard } from '../../lib/clipboard.js';+function DeliveryReconciliation({ draft, onReconciled }) {+ const [checkedMailbox, setCheckedMailbox] = useState(false);+ const [pending, setPending] = useState(false);+ const pendingRef = useRef(false);+ const [error, setError] = useState(null);++ const reconcile = async (outcome) => {+ if (!checkedMailbox || pendingRef.current) return;+ pendingRef.current = true;+ setPending(true);+ setError(null);+ const result = await api.reconcileMessageDraft(draft.id, {+ attemptId: draft.sendAttemptId, outcome+ }, { silent: true }).catch(err => {+ setError(err.message || 'Could not record delivery. Refresh the draft and try again.');+ return null;+ }).finally(() => {+ pendingRef.current = false;+ setPending(false);+ });+ if (result) onReconciled(result);+ };++ return (+ <div className="rounded border border-port-warning/40 p-3 space-y-3 text-sm">+ <p className="text-port-warning">+ Delivery is unknown because this send was interrupted. It may already have+ reached the recipient. Check your sent mailbox or conversation before recording+ the outcome. PortOS will not resend it automatically.+ </p>+ <label className="flex items-start gap-2" htmlFor={`checked-mailbox-${draft.id}`}>+ <input id={`checked-mailbox-${draft.id}`} type="checkbox"+ checked={checkedMailbox} disabled={pending}+ onChange={event => setCheckedMailbox(event.target.checked)} />+ I checked the mailbox or conversation and can confirm the delivery outcome.+ </label>+ <div className="flex flex-wrap gap-2">+ <button disabled={!checkedMailbox || pending} aria-busy={pending}+ data-voice-guard="confirm" onClick={() => reconcile('sent')}+ className="min-h-[44px] px-3 rounded bg-port-success/20 text-port-success disabled:opacity-50">+ Confirm sent+ </button>+ <button disabled={!checkedMailbox || pending} aria-busy={pending}+ data-voice-guard="confirm" onClick={() => reconcile('not_sent')}+ className="min-h-[44px] px-3 rounded bg-port-warning/20 text-port-warning disabled:opacity-50">+ Confirm not sent+ </button>+ </div>+ <p className="text-gray-400">Confirmed sent is final. Confirmed not sent restores a draft that needs fresh approval before sending.</p>+ {error && <p role="alert" className="text-port-error">{error}</p>}+ </div>+ );+}+export default function DraftsTab({ accounts }) {const [drafts, setDrafts] = useState([]);const [loading, setLoading] = useState(true);@@ -73,6 +127,7 @@ export default function DraftsTab({ accounts }) {pending_review: 'bg-port-warning/20 text-port-warning',approved: 'bg-port-success/20 text-port-success',sending: 'bg-port-accent/20 text-port-accent',+ delivery_unknown: 'bg-port-warning/20 text-port-warning',sent: 'bg-port-success/20 text-port-success',failed: 'bg-port-error/20 text-port-error'};@@ -107,7 +162,7 @@ export default function DraftsTab({ accounts }) {<div className="flex items-center justify-between"><div className="flex items-center gap-2"><span className={`px-2 py-0.5 rounded text-xs ${statusColors[draft.status] || ''}`}>- {draft.status}+ {draft.status === 'delivery_unknown' ? 'Delivery unknown' : draft.status}</span><span className="text-xs text-gray-500">{getAccountName(draft.accountId)}</span>{draft.generatedBy === 'ai' && (@@ -178,6 +233,12 @@ export default function DraftsTab({ accounts }) {<div className={`text-sm text-gray-400 whitespace-pre-wrap ${draft.sendVia === 'review' ? '' : 'line-clamp-3'}`}>{draft.body}</div>+ {draft.status === 'delivery_unknown' && (+ <DeliveryReconciliation key={draft.sendAttemptId} draft={draft}+ onReconciled={updated => setDrafts(prev => prev.map(d =>+ d.id === updated.id && d.sendAttemptId === updated.sendAttemptId ? updated : d+ ))} />+ )}{isConfirming(draft.id) && (<InlineConfirmRowquestion="Delete this draft? This cannot be undone."diff --git a/client/src/components/messages/DraftsTab.test.jsx b/client/src/components/messages/DraftsTab.test.jsxindex e011194e85..99c24fd50b 100644--- a/client/src/components/messages/DraftsTab.test.jsx+++ b/client/src/components/messages/DraftsTab.test.jsx@@ -6,6 +6,8 @@ import { buildIndex } from '../../services/domIndex.js';vi.mock('../../services/api', () => ({getMessageDrafts: vi.fn(),sendMessageDraft: vi.fn(),+ reconcileMessageDraft: vi.fn(),+ approveMessageDraft: vi.fn(),}));import * as api from '../../services/api';@@ -76,3 +78,56 @@ describe('DraftsTab pending sends', () => {expect(api.getMessageDrafts).toHaveBeenCalledTimes(1);});});++describe('DraftsTab interrupted delivery', () => {+ const unknown = {+ id: 'd1', status: 'delivery_unknown', sendVia: 'api',+ sendAttemptId: 'attempt-1', subject: 'Example interrupted message', body: 'Example body'+ };++ it('requires a mailbox check, records nondelivery once, and requires fresh approval', async () => {+ api.getMessageDrafts.mockResolvedValue([unknown]);+ let finish;+ api.reconcileMessageDraft.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ render(<DraftsTab accounts={[]} />);+ const confirmNotSent = await screen.findByRole('button', { name: 'Confirm not sent' });+ expect(screen.getByText(/It may already have reached the recipient/)).toBeInTheDocument();+ expect(confirmNotSent).toBeDisabled();+ expect(screen.queryByRole('button', { name: 'Send' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('checkbox'));+ fireEvent.click(confirmNotSent);+ fireEvent.click(confirmNotSent);+ expect(confirmNotSent).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Confirm sent' })).toBeDisabled();+ expect(api.reconcileMessageDraft).toHaveBeenCalledTimes(1);+ expect(api.reconcileMessageDraft).toHaveBeenCalledWith('d1', {+ attemptId: 'attempt-1', outcome: 'not_sent'+ }, { silent: true });+ await act(async () => finish({ ...unknown, status: 'draft' }));+ expect(screen.queryByText('Delivery unknown')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Send' })).not.toBeInTheDocument();+ api.approveMessageDraft.mockResolvedValueOnce({ ...unknown, status: 'approved' });+ fireEvent.click(screen.getByRole('button', { name: 'Approve' }));+ expect(await screen.findByRole('button', { name: 'Send' })).toBeEnabled();+ expect(api.sendMessageDraft).not.toHaveBeenCalled();+ expect(api.getMessageDrafts).toHaveBeenCalledTimes(1);+ });++ it('keeps uncertainty visible on conflict and makes confirmed delivery terminal', async () => {+ api.getMessageDrafts.mockResolvedValue([unknown]);+ api.reconcileMessageDraft.mockRejectedValueOnce(new Error('Draft state conflict'));+ render(<DraftsTab accounts={[]} />);+ await screen.findByText('Delivery unknown');+ fireEvent.click(screen.getByRole('checkbox'));+ fireEvent.click(screen.getByRole('button', { name: 'Confirm sent' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('Draft state conflict');+ expect(screen.getByText('Delivery unknown')).toBeInTheDocument();+ api.reconcileMessageDraft.mockResolvedValueOnce({ ...unknown, status: 'sent' });+ fireEvent.click(screen.getByRole('button', { name: 'Confirm sent' }));+ expect(await screen.findByText('sent')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Send' })).not.toBeInTheDocument();+ expect(api.sendMessageDraft).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/apiMessages.js b/client/src/services/apiMessages.jsindex fc0bb1fe2b..89140a2d8f 100644--- a/client/src/services/apiMessages.js+++ b/client/src/services/apiMessages.js@@ -32,6 +32,9 @@ export const createMessageDraft = (data) => request('/messages/drafts', { methodexport const generateMessageDraft = (data) => request('/messages/drafts/generate', { method: 'POST', body: JSON.stringify(data) });export const updateMessageDraft = (id, data) => request(`/messages/drafts/${id}`, { method: 'PUT', body: JSON.stringify(data) });export const approveMessageDraft = (id) => request(`/messages/drafts/${id}/approve`, { method: 'POST' });+export const reconcileMessageDraft = (id, data, options = {}) => request(`/messages/drafts/${id}/reconcile`, {+ method: 'POST', body: JSON.stringify(data), ...options+});export const sendMessageDraft = (id) => request(`/messages/drafts/${id}/send`, { method: 'POST' });export const deleteMessageDraft = (id) => request(`/messages/drafts/${id}`, { method: 'DELETE' });export const getMessageSelectors = () => request('/messages/selectors');diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 00da7df334..3473a775f2 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -186,6 +186,18 @@ Each file→Postgres migrator parks its source aside (`<domain>.imported`, per-r---+### Existing Messages draft send state++Messages retains its existing machine-local `data/messages/drafts.json` store.+Migration 415 adds send-attempt identity and a history capped at 20 attempts per+draft, including interruption and operator reconciliation timestamps. It preserves+draft content and states; startup recovery then marks abandoned sends as+`delivery_unknown` without contacting a provider. Unknown delivery cannot be+edited, deleted, approved, or sent until the operator checks their mailbox and+records sent or not sent. Confirmed nondelivery returns to an unapproved draft.+These fields stay with the existing draft backup and never federate; this change+adds no new store or seed.+## PostgreSQL is required — `MEMORY_BACKEND=file` is test-onlyPortOS treats **PostgreSQL as a mandatory install/runtime dependency** for every install and every federated peer machine (decision: [ADR — PostgreSQL as the Primary Datastore](./decisions/2026-06-07-postgres-as-primary-datastore.md)). Run it as either:diff --git a/scripts/migrations/415-message-draft-send-attempts.js b/scripts/migrations/415-message-draft-send-attempts.jsnew file mode 100644index 0000000000..c0647cd6a8--- /dev/null+++ b/scripts/migrations/415-message-draft-send-attempts.js@@ -0,0 +1,27 @@+/**+ * Add machine-local send audit fields without changing content or deciding+ * delivery. Boot recovery marks orphaned sending attempts delivery_unknown.+ */+import { join } from 'path';+import { writeJsonAtomic } from './_lib.js';+import { readJSONFileStrict } from '../../server/lib/fileUtils.js';++export default {+ async up({ rootDir }) {+ const file = join(rootDir, 'data', 'messages', 'drafts.json');+ const { ok, value: drafts } = await readJSONFileStrict(file, null, { logError: false });+ if (ok && drafts === null) return { updated: 0 };+ if (!ok || !Array.isArray(drafts) || drafts.some(d => !d || typeof d !== 'object' || Array.isArray(d))) {+ throw new Error('Invalid message drafts snapshot; preserving original data');+ }+ let updated = 0;+ for (const draft of drafts) {+ if (Object.hasOwn(draft, 'sendAttempts') && Object.hasOwn(draft, 'sendAttemptId')) continue;+ draft.sendAttempts ??= [];+ draft.sendAttemptId ??= null;+ updated++;+ }+ if (updated) await writeJsonAtomic(file, drafts);+ return { updated };+ }+};diff --git a/scripts/migrations/415-message-draft-send-attempts.test.js b/scripts/migrations/415-message-draft-send-attempts.test.jsnew file mode 100644index 0000000000..1bae6ffc7b--- /dev/null+++ b/scripts/migrations/415-message-draft-send-attempts.test.js@@ -0,0 +1,26 @@+import { afterEach, expect, it } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './415-message-draft-send-attempts.js';++let rootDir;+afterEach(async () => { if (rootDir) await rm(rootDir, { recursive: true, force: true }); });++it('preserves legacy draft content and states, existing attempt history, and invalid snapshots', async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'message-attempt-migration-'));+ expect(await migration.up({ rootDir })).toEqual({ updated: 0 });+ await mkdir(join(rootDir, 'data', 'messages'), { recursive: true });+ const file = join(rootDir, 'data', 'messages', 'drafts.json');+ const legacy = { id: 'example-draft', status: 'sending', body: 'Invented message', futureField: true };+ const current = { id: 'other-draft', status: 'sent', sendAttemptId: 'example-attempt', sendAttempts: [{ id: 'example-attempt', outcome: 'sent' }] };+ await writeFile(file, JSON.stringify([legacy, current]));+ expect(await migration.up({ rootDir })).toEqual({ updated: 1 });+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual([{ ...legacy, sendAttemptId: null, sendAttempts: [] }, current]);+ expect(await migration.up({ rootDir })).toEqual({ updated: 0 });+ for (const invalid of ['{invalid', '{}', '[null]']) {+ await writeFile(file, invalid);+ await expect(migration.up({ rootDir })).rejects.toThrow('Invalid message drafts snapshot');+ expect(await readFile(file, 'utf8')).toBe(invalid);+ }+});diff --git a/server/routes/messages.js b/server/routes/messages.jsindex e31f032611..29b62848c7 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -71,6 +71,11 @@ const updateDraftSchema = z.object({status: z.enum(['draft', 'pending_review', 'approved']).optional()});+const reconcileDraftSchema = z.object({+ attemptId: z.string().guid(),+ outcome: z.enum(['sent', 'not_sent'])+});+const generateDraftSchema = z.object({accountId: z.string().guid(),replyToMessageId: z.string().nullish(),@@ -271,6 +276,16 @@ router.post('/drafts/:id/approve', asyncHandler(async (req, res) => {res.json(draft);}));+router.post('/drafts/:id/reconcile', asyncHandler(async (req, res) => {+ if (!UUID_RE.test(req.params.id)) {+ throw new ServerError('Invalid draft ID format', { status: 400 });+ }+ const data = validateRequest(reconcileDraftSchema, req.body);+ const draft = await messageDrafts.reconcileDraftSend(req.params.id, data);+ req.app.get('io')?.emit('messages:changed', {});+ res.json(draft);+}));+router.post('/drafts/:id/send', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.id)) {throw new ServerError('Invalid draft ID format', { status: 400 });diff --git a/server/routes/messages.test.js b/server/routes/messages.test.jsindex 4b72fe9a23..4e18c2d645 100644--- a/server/routes/messages.test.js+++ b/server/routes/messages.test.js@@ -40,6 +40,7 @@ vi.mock('../services/messageDrafts.js', () => ({createDraft: vi.fn(),updateDraft: vi.fn(),approveDraft: vi.fn(),+ reconcileDraftSend: vi.fn(),deleteDraft: vi.fn(),deleteDraftsByAccountId: vi.fn()}));@@ -542,6 +543,30 @@ describe('Messages Routes', () => {});});+ describe('POST /api/messages/drafts/:id/reconcile', () => {+ it('validates the mailbox outcome and attempt identity, returns the updated draft, and emits only invalidation', async () => {+ const emit = vi.fn();+ app.set('io', { emit });+ const updated = { id: DRAFT_UUID, status: 'draft', sendAttemptId: DRAFT_UUID_2 };+ messageDrafts.reconcileDraftSend.mockResolvedValue(updated);+ const data = { attemptId: DRAFT_UUID_2, outcome: 'not_sent' };+ const response = await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/reconcile`).send(data);+ expect(response.status).toBe(200);+ expect(response.body).toEqual(updated);+ expect(messageDrafts.reconcileDraftSend).toHaveBeenCalledWith(DRAFT_UUID, data);+ expect(emit).toHaveBeenCalledWith('messages:changed', {});+ messageDrafts.reconcileDraftSend.mockClear();+ for (const invalid of [{ outcome: 'not_sent' }, { attemptId: DRAFT_UUID_2, outcome: 'retry' }]) {+ expect((await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/reconcile`).send(invalid)).status).toBe(400);+ }+ expect(messageDrafts.reconcileDraftSend).not.toHaveBeenCalled();+ messageDrafts.reconcileDraftSend.mockRejectedValueOnce(new ServerError('Draft state conflict', { status: 409, code: 'DRAFT_STATE_CONFLICT' }));+ const conflict = await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/reconcile`).send(data);+ expect(conflict.status).toBe(409);+ expect(conflict.body.code).toBe('DRAFT_STATE_CONFLICT');+ });+ });+describe('POST /api/messages/drafts/:id/send', () => {it('should send a draft', async () => {messageSender.sendDraft.mockResolvedValue({ success: true });diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 6daf4a5142..fb72834e25 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -255,7 +255,12 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// import.meta.url-derived path so a server booted from inside a CoS agent// worktree still resolves to the real install; runMigrations also skips a// worktree-rooted path as a backstop (#1947).- applyDataMigrations: () => runMigrations({ rootDir: resolveInstallRoot(join(serverDir, '..')) }),+ applyDataMigrations: async () => {+ await runMigrations({ rootDir: resolveInstallRoot(join(serverDir, '..')) });+ // Local recovery only: no mail, browser, or LLM provider calls.+ const { initializeMessageDrafts } = await import('./messageDrafts.js');+ await initializeMessageDrafts();+ },// usage.js and migration 304 both update usage.json. Initialize the service// only after migrations finish so their whole-file writes cannot race anddiff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.jsindex a9ab078c11..5aabea553e 100644--- a/server/services/messageDrafts.js+++ b/server/services/messageDrafts.js@@ -13,21 +13,49 @@ const DRAFTS_FILE = join(PATHS.messages, 'drafts.json');// now that Tribe outreach (#2158) permits several draft generations in flight at// once — each finishing LLM call lands its own createDraft.const queueWrite = createFileWriteQueue();+const activeAttempts = new Map();+const MAX_SEND_ATTEMPTS = 20;+// Called only under queueWrite. A persisted send with no live dispatcher is+// ambiguous even if it never reached the transport. Never retry it at boot.async function loadDrafts() {await ensureDir(PATHS.messages);const content = await tryReadFile(DRAFTS_FILE);if (!content) return [];const parsed = safeJSONParse(content, [], { context: 'messageDrafts' });- return Array.isArray(parsed) ? parsed : [];+ const drafts = Array.isArray(parsed) ? parsed : [];+ let recovered = false;+ for (const draft of drafts) {+ if (draft.status !== 'sending' || activeAttempts.has(draft.id)) continue;+ const now = new Date().toISOString();+ draft.sendAttemptId ||= uuidv4();+ draft.sendAttempts = (draft.sendAttempts || []).slice(-MAX_SEND_ATTEMPTS);+ let attempt = draft.sendAttempts.find(a => a.id === draft.sendAttemptId);+ if (!attempt) {+ attempt = { id: draft.sendAttemptId, startedAt: draft.updatedAt || null };+ draft.sendAttempts = [...draft.sendAttempts, attempt].slice(-MAX_SEND_ATTEMPTS);+ }+ attempt.outcome = 'delivery_unknown';+ attempt.interruptedAt = now;+ draft.status = 'delivery_unknown';+ draft.updatedAt = now;+ recovered = true;+ }+ if (recovered) await saveDrafts(drafts);+ return drafts;}async function saveDrafts(drafts) {await atomicWrite(DRAFTS_FILE, drafts);}+// Boot and request-time recovery share the same queue and active-attempt guard.+export async function initializeMessageDrafts() {+ await queueWrite(loadDrafts);+}+export async function listDrafts(filters = {}) {- let drafts = await loadDrafts();+ let drafts = await queueWrite(loadDrafts);if (filters.accountId) drafts = drafts.filter(d => d.accountId === filters.accountId);if (filters.status) {// `status` accepts a single value or an array (OR filter), so callers like@@ -42,7 +70,7 @@ export async function listDrafts(filters = {}) {}export async function getDraft(id) {- const drafts = await loadDrafts();+ const drafts = await queueWrite(loadDrafts);return drafts.find(d => d.id === id) || null;}@@ -63,6 +91,8 @@ export async function createDraft(data) {subject: data.subject || '',body: data.body || '',status: 'draft',+ sendAttemptId: null,+ sendAttempts: [],generatedBy: data.generatedBy || 'manual',sendVia: data.sendVia || 'api',createdAt: new Date().toISOString(),@@ -80,7 +110,7 @@ export async function updateDraft(id, updates) {const drafts = await loadDrafts();const idx = drafts.findIndex(d => d.id === id);if (idx === -1) return null;- if (['sending', 'sent'].includes(drafts[idx].status) || ['sending', 'sent', 'failed'].includes(updates.status)) {+ if (['sending', 'delivery_unknown', 'sent'].includes(drafts[idx].status) || ['sending', 'delivery_unknown', 'sent', 'failed'].includes(updates.status)) {throw new ServerError('Draft cannot be edited in its current send state', { status: 409, code: 'DRAFT_STATE_CONFLICT' });}const allowed = ['to', 'cc', 'subject', 'body', 'status'];@@ -106,21 +136,57 @@ export async function claimDraftForSend(id) {// Keep uncertain delivery blocked after a crash; never silently retry it.draft.status = 'sending';draft.updatedAt = new Date().toISOString();+ draft.sendAttemptId = uuidv4();+ draft.sendAttempts = [...(draft.sendAttempts || []), {+ id: draft.sendAttemptId, startedAt: draft.updatedAt, outcome: 'sending'+ }].slice(-MAX_SEND_ATTEMPTS);await saveDrafts(drafts);+ activeAttempts.set(id, draft.sendAttemptId);return draft;});}-export async function finishDraftSend(id, success) {+export async function finishDraftSend(id, attemptId, success) {return queueWrite(async () => {const drafts = await loadDrafts();const draft = drafts.find(d => d.id === id);if (!draft) return null;- if (draft.status !== 'sending') {+ if (draft.status !== 'sending' || draft.sendAttemptId !== attemptId || activeAttempts.get(id) !== attemptId) {throw new ServerError('Draft is not sending', { status: 409, code: 'DRAFT_STATE_CONFLICT' });}draft.status = success ? 'sent' : 'failed';draft.updatedAt = new Date().toISOString();+ const attempt = draft.sendAttempts.find(a => a.id === attemptId);+ attempt.outcome = draft.status;+ attempt.finishedAt = draft.updatedAt;+ await saveDrafts(drafts);+ return draft;+ });+}++// Only the dispatcher releases its own lease, after all transport I/O settles.+// A failed terminal write remains sending on disk and is recovered on next read.+export function releaseDraftSend(id, attemptId) {+ if (activeAttempts.get(id) === attemptId) activeAttempts.delete(id);+}++export async function reconcileDraftSend(id, { attemptId, outcome }) {+ return queueWrite(async () => {+ const drafts = await loadDrafts();+ const draft = drafts.find(d => d.id === id);+ if (!draft) throw new ServerError('Draft not found', { status: 404, code: 'DRAFT_NOT_FOUND' });+ if (activeAttempts.has(id) || draft.status !== 'delivery_unknown' || draft.sendAttemptId !== attemptId) {+ throw new ServerError('Draft delivery cannot be reconciled in its current state', { status: 409, code: 'DRAFT_STATE_CONFLICT' });+ }+ if (!['sent', 'not_sent'].includes(outcome)) {+ throw new ServerError('Confirm sent or not sent after checking your mailbox', { status: 400 });+ }+ const now = new Date().toISOString();+ const attempt = draft.sendAttempts.find(a => a.id === attemptId);+ attempt.reconciliation = outcome;+ attempt.reconciledAt = now;+ draft.status = outcome === 'sent' ? 'sent' : 'draft';+ draft.updatedAt = now;await saveDrafts(drafts);return draft;});@@ -133,8 +199,8 @@ export async function approveDraft(id) {export async function deleteDraftsByAccountId(accountId) {return queueWrite(async () => {const drafts = await loadDrafts();- if (drafts.some(d => d.accountId === accountId && d.status === 'sending')) {- throw new ServerError('Account has a draft being sent', { status: 409, code: 'DRAFT_STATE_CONFLICT' });+ if (drafts.some(d => d.accountId === accountId && ['sending', 'delivery_unknown'].includes(d.status))) {+ throw new ServerError('Account has a draft sending or awaiting delivery reconciliation', { status: 409, code: 'DRAFT_STATE_CONFLICT' });}const remaining = drafts.filter(d => d.accountId !== accountId);if (remaining.length < drafts.length) {@@ -149,8 +215,8 @@ export async function deleteDraft(id) {const drafts = await loadDrafts();const idx = drafts.findIndex(d => d.id === id);if (idx === -1) return false;- if (drafts[idx].status === 'sending') {- throw new ServerError('Draft is being sent', { status: 409, code: 'DRAFT_STATE_CONFLICT' });+ if (['sending', 'delivery_unknown'].includes(drafts[idx].status)) {+ throw new ServerError('Draft is sending or awaiting delivery reconciliation', { status: 409, code: 'DRAFT_STATE_CONFLICT' });}drafts.splice(idx, 1);await saveDrafts(drafts);diff --git a/server/services/messageSender.js b/server/services/messageSender.jsindex 138744c44d..955621a741 100644--- a/server/services/messageSender.js+++ b/server/services/messageSender.js@@ -1,5 +1,5 @@import { messageLogError } from '../lib/messageLogError.js';-import { getDraft, claimDraftForSend, finishDraftSend } from './messageDrafts.js';+import { getDraft, claimDraftForSend, finishDraftSend, releaseDraftSend } from './messageDrafts.js';import { getAccount } from './messageAccounts.js';const ACCOUNT_TYPE_TO_SEND_VIA = {@@ -35,22 +35,25 @@ export async function sendDraft(draftId, io) {return sendPlaywright(account, draft);};- const result = await dispatch().catch(async (error) => {- console.error(`📧 Draft send threw for ${draft.id}: ${messageLogError(error)}`);- return { success: false, status: 502, code: 'SEND_FAILED', error: error.message };- });-- if (result?.success) {- await finishDraftSend(draftId, true);- io?.emit('messages:draft:sent', { draftId });- io?.emit('messages:changed', {});- console.log(`📧 Draft sent successfully: ${draft.id}`);- } else {- await finishDraftSend(draftId, false).catch(err => console.warn(`⚠️ Failed to mark draft as failed: ${messageLogError(err)}`));- const errorMsg = result?.error ?? 'Unknown error sending draft';- console.error(`📧 Draft send failed: ${messageLogError(result)}`);- return { success: false, status: result?.status ?? 500, code: result?.code ?? 'SEND_FAILED', error: errorMsg };- }+ const complete = async () => {+ const result = await dispatch().catch(async (error) => {+ console.error(`📧 Draft send threw for ${draft.id}: ${messageLogError(error)}`);+ return { success: false, status: 502, code: 'SEND_FAILED', error: error.message };+ });++ if (result?.success) {+ await finishDraftSend(draftId, draft.sendAttemptId, true);+ io?.emit('messages:draft:sent', { draftId });+ io?.emit('messages:changed', {});+ console.log(`📧 Draft sent successfully: ${draft.id}`);+ } else {+ await finishDraftSend(draftId, draft.sendAttemptId, false).catch(err => console.warn(`⚠️ Failed to mark draft as failed: ${messageLogError(err)}`));+ const errorMsg = result?.error ?? 'Unknown error sending draft';+ console.error(`📧 Draft send failed: ${messageLogError(result)}`);+ return { success: false, status: result?.status ?? 500, code: result?.code ?? 'SEND_FAILED', error: errorMsg };+ }- return result;+ return result;+ };+ return complete().finally(() => releaseDraftSend(draftId, draft.sendAttemptId));}diff --git a/server/services/messageSender.test.js b/server/services/messageSender.test.jsindex 5947de5761..27833900f3 100644--- a/server/services/messageSender.test.js+++ b/server/services/messageSender.test.js@@ -2,13 +2,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { join } from 'path';const doubles = vi.hoisted(() => ({- files: new Map(), getAccount: vi.fn(), sendGmail: vi.fn(), sendPlaywright: vi.fn()+ files: new Map(), failTerminal: false, getAccount: vi.fn(), sendGmail: vi.fn(), sendPlaywright: vi.fn()}));vi.mock('../lib/fileUtils.js', () => ({PATHS: { messages: '/mock/messages' },ensureDir: async () => {},tryReadFile: async path => doubles.files.get(path) ?? null,- atomicWrite: async (path, data) => { doubles.files.set(path, JSON.stringify(data)); },+ atomicWrite: async (path, data) => {+ if (doubles.failTerminal && data.some(d => d.status === 'sent')) throw new Error('Example disk failure');+ doubles.files.set(path, JSON.stringify(data));+ },safeJSONParse: JSON.parse}));vi.mock('./messageAccounts.js', () => ({ getAccount: doubles.getAccount }));@@ -16,7 +19,7 @@ vi.mock('./messageGmailSync.js', () => ({ sendGmail: doubles.sendGmail }));vi.mock('./messagePlaywrightSync.js', () => ({ sendPlaywright: doubles.sendPlaywright }));import { sendDraft } from './messageSender.js';-import { getDraft, approveDraft, updateDraft, deleteDraft, deleteDraftsByAccountId } from './messageDrafts.js';+import { getDraft, approveDraft, updateDraft, deleteDraft, deleteDraftsByAccountId, initializeMessageDrafts, reconcileDraftSend } from './messageDrafts.js';function barrier() {let resolve;@@ -33,6 +36,7 @@ function seed(...drafts) {beforeEach(() => {vi.resetAllMocks();doubles.files.clear();+ doubles.failTerminal = false;doubles.getAccount.mockResolvedValue({ id: 'account-1', type: 'gmail' });doubles.sendGmail.mockResolvedValue({ success: true });doubles.sendPlaywright.mockResolvedValue({ success: true });@@ -58,6 +62,10 @@ describe('draft send workflow', () => {const sends = Promise.allSettled([sendDraft('draft-1'), sendDraft('draft-1')]);await dispatchStarted.promise;+ const active = await getDraft('draft-1');+ expect(active.status).toBe('sending');+ await initializeMessageDrafts();+ await expect(reconcileDraftSend('draft-1', { attemptId: active.sendAttemptId, outcome: 'not_sent' })).rejects.toMatchObject({ status: 409 });expect((await getDraft('draft-1')).status).toBe('sending');await expect(approveDraft('draft-1')).rejects.toMatchObject({ status: 409, code: 'DRAFT_STATE_CONFLICT' });await expect(updateDraft('draft-1', { status: 'draft', body: 'Changed' })).rejects.toMatchObject({ status: 409 });@@ -138,3 +146,76 @@ describe('draft send workflow', () => {expect(doubles.sendPlaywright).not.toHaveBeenCalled();});});++describe('interrupted send reconciliation', () => {+ it.each(['before dispatch', 'after external success'])('recovers a restart %s without dispatching and fences reconciliation by attempt', async point => {+ vi.resetModules();+ const original = await import('./messageDrafts.js');+ seed({ id: 'draft-1' });+ if (point === 'before dispatch') {+ await original.claimDraftForSend('draft-1');+ } else {+ const sender = await import('./messageSender.js');+ doubles.failTerminal = true;+ await expect(sender.sendDraft('draft-1')).rejects.toThrow('Example disk failure');+ doubles.failTerminal = false;+ expect(doubles.sendGmail).toHaveBeenCalledTimes(1);+ }+ const dispatchCount = doubles.sendGmail.mock.calls.length;+ vi.resetModules(); // a new process has no active dispatch leases+ const restarted = await import('./messageDrafts.js');+ const sender = await import('./messageSender.js');+ await restarted.initializeMessageDrafts();+ const unknown = await restarted.getDraft('draft-1');+ expect(unknown.status).toBe('delivery_unknown');+ expect(unknown.sendAttempts).toEqual([expect.objectContaining({+ id: unknown.sendAttemptId, outcome: 'delivery_unknown', interruptedAt: expect.any(String)+ })]);+ await restarted.initializeMessageDrafts();+ expect(await restarted.getDraft('draft-1')).toEqual(unknown);+ await expect(restarted.approveDraft('draft-1')).rejects.toMatchObject({ status: 409 });+ await expect(restarted.updateDraft('draft-1', { status: 'draft', body: 'Changed' })).rejects.toMatchObject({ status: 409 });+ await expect(restarted.deleteDraft('draft-1')).rejects.toMatchObject({ status: 409 });+ await expect(restarted.deleteDraftsByAccountId('account-1')).rejects.toMatchObject({ status: 409 });+ expect(await sender.sendDraft('draft-1')).toMatchObject({ status: 409 });+ expect(doubles.sendGmail).toHaveBeenCalledTimes(dispatchCount);+ expect(doubles.sendPlaywright).not.toHaveBeenCalled();++ await expect(restarted.reconcileDraftSend('draft-1', { attemptId: 'stale', outcome: 'not_sent' })).rejects.toMatchObject({ status: 409 });+ const outcome = point === 'before dispatch' ? 'not_sent' : 'sent';+ const reconciled = await restarted.reconcileDraftSend('draft-1', { attemptId: unknown.sendAttemptId, outcome });+ expect(reconciled.status).toBe(outcome === 'sent' ? 'sent' : 'draft');+ expect(reconciled.sendAttempts[0]).toMatchObject({ reconciliation: outcome, reconciledAt: expect.any(String) });+ expect(await sender.sendDraft('draft-1')).toMatchObject({ status: 409 });+ await expect(restarted.reconcileDraftSend('draft-1', { attemptId: unknown.sendAttemptId, outcome })).rejects.toMatchObject({ status: 409 });+ if (outcome === 'sent') {+ await expect(restarted.approveDraft('draft-1')).rejects.toMatchObject({ status: 409 });+ } else {+ await restarted.updateDraft('draft-1', { body: 'Updated after mailbox check' });+ await restarted.approveDraft('draft-1');+ expect(await sender.sendDraft('draft-1')).toEqual({ success: true });+ const sent = await restarted.getDraft('draft-1');+ expect(sent.sendAttemptId).not.toBe(unknown.sendAttemptId);+ expect(sent.sendAttempts).toHaveLength(2);+ await expect(restarted.finishDraftSend('draft-1', unknown.sendAttemptId, true)).rejects.toMatchObject({ status: 409 });+ }+ });++ it('recovers legacy sends and bounds retained attempt history', async () => {+ vi.resetModules();+ const drafts = await import('./messageDrafts.js');+ seed({ id: 'legacy', status: 'sending' }, {+ id: 'retry', sendAttempts: Array.from({ length: 25 }, (_, i) => ({ id: `old-${i}`, outcome: 'failed' }))+ });+ await drafts.initializeMessageDrafts();+ const legacy = await drafts.getDraft('legacy');+ expect(legacy).toMatchObject({ status: 'delivery_unknown', body: 'Example message' });+ expect(legacy.sendAttempts).toHaveLength(1);+ expect(legacy.sendAttempts[0].id).toBe(legacy.sendAttemptId);+ const attempt = await drafts.claimDraftForSend('retry');+ expect(attempt.sendAttempts).toHaveLength(20);+ expect(attempt.sendAttempts.at(-1).id).toBe(attempt.sendAttemptId);+ expect(doubles.sendGmail).not.toHaveBeenCalled();+ expect(doubles.sendPlaywright).not.toHaveBeenCalled();+ });+});