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: prevent overlapping requests from sending a draft twice (#8785)
[._.]/ Adam Eivya37eaad8a8d7
diff --git a/client/src/components/messages/DraftsTab.jsx b/client/src/components/messages/DraftsTab.jsxindex 7f83cee4bd..5c297b2601 100644--- a/client/src/components/messages/DraftsTab.jsx+++ b/client/src/components/messages/DraftsTab.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useRef } from 'react';import { FileText, Trash2, Send, Check, RefreshCw, Copy } from 'lucide-react';import toast from '../ui/Toast';import * as api from '../../services/api';@@ -9,6 +9,8 @@ import { copyToClipboard } from '../../lib/clipboard.js';export default function DraftsTab({ accounts }) {const [drafts, setDrafts] = useState([]);const [loading, setLoading] = useState(true);+ const sendingRef = useRef(new Set());+ const [sendingIds, setSendingIds] = useState(new Set());const [copiedId, setCopiedId] = useState(null);const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();@@ -40,7 +42,13 @@ export default function DraftsTab({ accounts }) {};const handleSend = async (id) => {- const result = await api.sendMessageDraft(id).catch(() => null);+ if (sendingRef.current.has(id)) return;+ sendingRef.current.add(id);+ setSendingIds(new Set(sendingRef.current));+ const result = await api.sendMessageDraft(id).catch(() => null).finally(() => {+ sendingRef.current.delete(id);+ setSendingIds(new Set(sendingRef.current));+ });if (!result || result.success === false) return;setDrafts(prev => prev.map(d => d.id === id ? { ...d, status: 'sent' } : d));toast.success('Message sent');@@ -125,9 +133,11 @@ export default function DraftsTab({ accounts }) {onClick={() => handleSend(draft.id)}className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-400 hover:text-port-accent transition-colors"title="Send" aria-label="Send"+ disabled={sendingIds.has(draft.id)}+ aria-busy={sendingIds.has(draft.id)}data-voice-guard="confirm">- <Send size={16} />+ {sendingIds.has(draft.id) ? <RefreshCw size={16} className="animate-spin" /> : <Send size={16} />}</button>)}{draft.sendVia === 'review' && (diff --git a/client/src/components/messages/DraftsTab.test.jsx b/client/src/components/messages/DraftsTab.test.jsxindex 13091fcaa1..e011194e85 100644--- a/client/src/components/messages/DraftsTab.test.jsx+++ b/client/src/components/messages/DraftsTab.test.jsx@@ -1,13 +1,15 @@-import { render, screen } from '@testing-library/react';-import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent, act, waitFor } from '@testing-library/react';+import { describe, it, expect, vi, beforeEach } from 'vitest';import DraftsTab from './DraftsTab.jsx';import { buildIndex } from '../../services/domIndex.js';vi.mock('../../services/api', () => ({getMessageDrafts: vi.fn(),+ sendMessageDraft: vi.fn(),}));import * as api from '../../services/api';+beforeEach(() => vi.clearAllMocks());// jsdom doesn't do layout, so domIndex's isVisible() geometry checks would// drop every element — same stub domIndex.test.jsx uses.@@ -47,3 +49,30 @@ describe('DraftsTab — voice confirmation annotation on Send (#5907)', () => {expect(entry.guard).toBe('confirm');});});+++describe('DraftsTab pending sends', () => {+ it('immediately disables only the sending draft and clears pending on failure', async () => {+ api.getMessageDrafts.mockResolvedValue([+ { id: 'd1', status: 'approved', sendVia: 'api', subject: 'First' },+ { id: 'd2', status: 'approved', sendVia: 'api', subject: 'Second' }+ ]);+ let rejectSend;+ api.sendMessageDraft.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectSend = reject; }));+ render(<DraftsTab accounts={[]} />);+ const [first, second] = await screen.findAllByRole('button', { name: 'Send' });+ fireEvent.click(first);+ fireEvent.click(first);+ expect(first).toBeDisabled();+ expect(first).toHaveAttribute('aria-busy', 'true');+ expect(second).toBeEnabled();+ expect(api.sendMessageDraft).toHaveBeenCalledTimes(1);+ await act(async () => { rejectSend(new Error('Example send failure')); });+ await waitFor(() => expect(first).toBeEnabled());+ api.sendMessageDraft.mockResolvedValueOnce({ success: true });+ fireEvent.click(first);+ await waitFor(() => expect(screen.getAllByRole('button', { name: 'Send' })).toHaveLength(1));+ expect(screen.getByText('sent')).toBeInTheDocument();+ expect(api.getMessageDrafts).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/routes/messages.test.js b/server/routes/messages.test.jsindex b1df847ec5..4b72fe9a23 100644--- a/server/routes/messages.test.js+++ b/server/routes/messages.test.js@@ -560,16 +560,29 @@ describe('Messages Routes', () => {expect(response.status).toBe(404);});- it('should return 400 for non-not-found errors', async () => {- messageSender.sendDraft.mockResolvedValue({ success: false, status: 400, code: 'INVALID_STATUS', error: 'Draft not approved' });+ it('should return a typed 409 for an ineligible send', async () => {+ messageSender.sendDraft.mockResolvedValue({ success: false, status: 409, code: 'DRAFT_STATE_CONFLICT', error: 'Draft not approved' });const response = await request(app).post(`/api/messages/drafts/${DRAFT_UUID}/send`);- expect(response.status).toBe(400);+ expect(response.status).toBe(409);expect(response.body.error).toBe('Draft not approved');+ expect(response.body.code).toBe('DRAFT_STATE_CONFLICT');});});+ it.each([+ ['post', '/approve', 'approveDraft'],+ ['put', '', 'updateDraft'],+ ['post', '/send', 'sendDraft']+ ])('returns the conflict envelope from %s drafts/:id%s', async (method, suffix, service) => {+ const owner = service === 'sendDraft' ? messageSender : messageDrafts;+ owner[service].mockRejectedValueOnce(new ServerError('Draft state conflict', { status: 409, code: 'DRAFT_STATE_CONFLICT' }));+ const response = await request(app)[method](`/api/messages/drafts/${DRAFT_UUID}${suffix}`).send({});+ expect(response.status).toBe(409);+ expect(response.body).toMatchObject({ error: 'Draft state conflict', code: 'DRAFT_STATE_CONFLICT' });+ });+describe('DELETE /api/messages/drafts/:id', () => {it('should delete a draft', async () => {messageDrafts.deleteDraft.mockResolvedValue(true);diff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.jsindex 1d30f1fafb..fe4acf8578 100644--- a/server/services/messageDrafts.js+++ b/server/services/messageDrafts.js@@ -2,6 +2,7 @@import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { atomicWrite, ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';const DRAFTS_FILE = join(PATHS.messages, 'drafts.json');@@ -79,6 +80,9 @@ 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)) {+ 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'];for (const key of allowed) {if (updates[key] !== undefined) drafts[idx][key] = updates[key];@@ -89,6 +93,38 @@ export async function updateDraft(id, updates) {});}+// The eligibility check and transition share the same queue as every draft edit.+// Provider I/O happens after this promise resolves, never while holding the queue.+export async function claimDraftForSend(id) {+ 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 (draft.status !== 'approved') {+ throw new ServerError('Draft must be approved and not already sending or sent', { status: 409, code: 'DRAFT_STATE_CONFLICT' });+ }+ draft.status = 'sending';+ draft.updatedAt = new Date().toISOString();+ await saveDrafts(drafts);+ return draft;+ });+}++export async function finishDraftSend(id, success) {+ return queueWrite(async () => {+ const drafts = await loadDrafts();+ const draft = drafts.find(d => d.id === id);+ if (!draft) return null;+ if (draft.status !== 'sending') {+ throw new ServerError('Draft is not sending', { status: 409, code: 'DRAFT_STATE_CONFLICT' });+ }+ draft.status = success ? 'sent' : 'failed';+ draft.updatedAt = new Date().toISOString();+ await saveDrafts(drafts);+ return draft;+ });+}+export async function approveDraft(id) {return updateDraft(id, { status: 'approved' });}diff --git a/server/services/messageLogging.test.js b/server/services/messageLogging.test.jsindex 21d310f68c..8ea0a6a0e4 100644--- a/server/services/messageLogging.test.js+++ b/server/services/messageLogging.test.js@@ -85,10 +85,11 @@ describe('mailbox operational log privacy', () => {expect((await getDraft(draft.id)).status).toBe('sent');expect((await getDraft(draft.id)).body).toBe(PRIVATE.body);- await updateDraft(draft.id, { status: 'approved' });+ const failedDraft = await createDraft({ ...PRIVATE, to: [PRIVATE.email], accountId: account.id });+ await updateDraft(failedDraft.id, { status: 'approved' });doubles.send.mockRejectedValueOnce(failure());- expect(await sendDraft(draft.id)).toMatchObject({ success: false, code: 'GMAIL_SEND_FAILED' });- expect((await getDraft(draft.id)).status).toBe('failed');+ expect(await sendDraft(failedDraft.id)).toMatchObject({ success: false, code: 'GMAIL_SEND_FAILED' });+ expect((await getDraft(failedDraft.id)).status).toBe('failed');expect(output()).toContain(draft.id);expect(output()).toContain(account.id);expect(output()).toContain('HTTP 403');diff --git a/server/services/messageSender.js b/server/services/messageSender.jsindex 0474083242..9f79d29355 100644--- a/server/services/messageSender.js+++ b/server/services/messageSender.js@@ -1,5 +1,5 @@import { messageLogError } from '../lib/messageLogError.js';-import { getDraft, updateDraft } from './messageDrafts.js';+import { getDraft, claimDraftForSend, finishDraftSend } from './messageDrafts.js';import { getAccount } from './messageAccounts.js';const ACCOUNT_TYPE_TO_SEND_VIA = {@@ -9,9 +9,9 @@ const ACCOUNT_TYPE_TO_SEND_VIA = {};export async function sendDraft(draftId, io) {- const draft = await getDraft(draftId);+ let draft = await getDraft(draftId);if (!draft) return { success: false, status: 404, code: 'DRAFT_NOT_FOUND', error: 'Draft not found' };- if (draft.status !== 'approved') return { success: false, status: 400, code: 'INVALID_STATUS', error: `Draft status is "${draft.status}", must be "approved"` };+ if (draft.status !== 'approved') return { success: false, status: 409, code: 'DRAFT_STATE_CONFLICT', error: `Draft status is "${draft.status}", must be "approved"` };const account = await getAccount(draft.accountId);if (!account) return { success: false, status: 404, code: 'ACCOUNT_NOT_FOUND', error: 'Account not found' };@@ -21,7 +21,7 @@ export async function sendDraft(draftId, io) {return { success: false, status: 400, code: 'SEND_VIA_MISMATCH', error: `sendVia "${draft.sendVia}" does not match account type "${account.type}" (expected "${expectedSendVia}")` };}- await updateDraft(draftId, { status: 'sending' });+ draft = await claimDraftForSend(draftId);console.log(`📧 Sending draft ${draft.id} via ${draft.sendVia}`);const dispatch = async () => {@@ -39,12 +39,12 @@ export async function sendDraft(draftId, io) {});if (result?.success) {- await updateDraft(draftId, { status: 'sent' });+ await finishDraftSend(draftId, true);io?.emit('messages:draft:sent', { draftId });io?.emit('messages:changed', {});console.log(`📧 Draft sent successfully: ${draft.id}`);} else {- await updateDraft(draftId, { status: 'failed' }).catch(err => console.warn(`⚠️ Failed to mark draft as failed: ${messageLogError(err)}`));+ 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 };diff --git a/server/services/messageSender.test.js b/server/services/messageSender.test.jsnew file mode 100644index 0000000000..ef6665011f--- /dev/null+++ b/server/services/messageSender.test.js@@ -0,0 +1,138 @@+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()+}));+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)); },+ safeJSONParse: JSON.parse+}));+vi.mock('./messageAccounts.js', () => ({ getAccount: doubles.getAccount }));+vi.mock('./messageGmailSync.js', () => ({ sendGmail: doubles.sendGmail }));+vi.mock('./messagePlaywrightSync.js', () => ({ sendPlaywright: doubles.sendPlaywright }));++import { sendDraft } from './messageSender.js';+import { getDraft, approveDraft, updateDraft } from './messageDrafts.js';++function barrier() {+ let resolve;+ const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+}++function seed(...drafts) {+ doubles.files.set(join('/mock/messages', 'drafts.json'), JSON.stringify(drafts.map(draft => ({+ accountId: 'account-1', status: 'approved', sendVia: 'api', body: 'Example message', ...draft+ }))));+}++beforeEach(() => {+ vi.resetAllMocks();+ doubles.files.clear();+ doubles.getAccount.mockResolvedValue({ id: 'account-1', type: 'gmail' });+ doubles.sendGmail.mockResolvedValue({ success: true });+ doubles.sendPlaywright.mockResolvedValue({ success: true });+});++describe('draft send workflow', () => {+ it('claims once after overlapping reads and prevents edits from reopening the send', async () => {+ seed({ id: 'draft-1' });+ const bothRead = barrier();+ const dispatchStarted = barrier();+ const releaseDispatch = barrier();+ let reads = 0;+ doubles.getAccount.mockImplementation(async () => {+ if (++reads === 2) bothRead.resolve();+ await bothRead.promise;+ return { id: 'account-1', type: 'gmail' };+ });+ doubles.sendGmail.mockImplementation(async () => {+ dispatchStarted.resolve();+ await releaseDispatch.promise;+ return { success: true };+ });++ const sends = Promise.allSettled([sendDraft('draft-1'), sendDraft('draft-1')]);+ await dispatchStarted.promise;+ 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 });+ releaseDispatch.resolve();+ const results = await sends;+ expect(results.filter(result => result.status === 'fulfilled')).toEqual([{ status: 'fulfilled', value: { success: true } }]);+ expect(results.find(result => result.status === 'rejected').reason).toMatchObject({ status: 409, code: 'DRAFT_STATE_CONFLICT' });+ expect(doubles.sendGmail).toHaveBeenCalledTimes(1);+ expect((await getDraft('draft-1')).status).toBe('sent');+ await expect(approveDraft('draft-1')).rejects.toMatchObject({ status: 409 });+ await expect(updateDraft('draft-1', { status: 'approved' })).rejects.toMatchObject({ status: 409 });+ expect(await sendDraft('draft-1')).toMatchObject({ success: false, status: 409, code: 'DRAFT_STATE_CONFLICT' });+ expect(doubles.sendGmail).toHaveBeenCalledTimes(1);+ });++ it('lets another draft complete while one provider dispatch is blocked', async () => {+ seed({ id: 'draft-1' }, { id: 'draft-2' });+ const dispatchStarted = barrier();+ const releaseDispatch = barrier();+ doubles.sendGmail.mockImplementation(async (_account, draft) => {+ if (draft.id === 'draft-1') {+ dispatchStarted.resolve();+ await releaseDispatch.promise;+ }+ return { success: true };+ });+ const first = sendDraft('draft-1');+ await dispatchStarted.promise;+ expect(await sendDraft('draft-2')).toEqual({ success: true });+ expect((await getDraft('draft-2')).status).toBe('sent');+ releaseDispatch.resolve();+ await first;+ expect(doubles.sendGmail).toHaveBeenCalledTimes(2);+ });++ it.each(['returned', 'thrown'])('persists a %s dispatch failure and permits explicit reapproval', async kind => {+ seed({ id: 'draft-1', sendVia: 'playwright' });+ doubles.getAccount.mockResolvedValue({ id: 'account-1', type: 'outlook' });+ if (kind === 'thrown') doubles.sendPlaywright.mockRejectedValueOnce(new Error('Example transport failure'));+ else doubles.sendPlaywright.mockResolvedValueOnce({ success: false, status: 502, code: 'SEND_FAILED', error: 'Example transport failure' });+ expect(await sendDraft('draft-1')).toMatchObject({ success: false, code: 'SEND_FAILED' });+ expect((await getDraft('draft-1')).status).toBe('failed');+ expect(await sendDraft('draft-1')).toMatchObject({ status: 409 });+ await approveDraft('draft-1');+ expect(await sendDraft('draft-1')).toEqual({ success: true });+ expect((await getDraft('draft-1')).status).toBe('sent');+ });++ it('rechecks eligibility after account lookup and dispatches only the claimed snapshot', async () => {+ seed({ id: 'draft-1' });+ doubles.getAccount.mockImplementationOnce(async () => {+ await updateDraft('draft-1', { status: 'draft' });+ return { id: 'account-1', type: 'gmail' };+ });+ await expect(sendDraft('draft-1')).rejects.toMatchObject({ status: 409 });+ expect(doubles.sendGmail).not.toHaveBeenCalled();+ await approveDraft('draft-1');+ doubles.getAccount.mockImplementationOnce(async () => {+ await updateDraft('draft-1', { body: 'Latest approved content' });+ return { id: 'account-1', type: 'gmail' };+ });+ await sendDraft('draft-1');+ expect(doubles.sendGmail).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ body: 'Latest approved content', status: 'sending' }));+ });++ it('leaves validation failures unsent and does not call a provider', async () => {+ seed({ id: 'unapproved', status: 'draft' }, { id: 'missing-account' }, { id: 'mismatch', sendVia: 'playwright' });+ expect(await sendDraft('absent')).toMatchObject({ status: 404, code: 'DRAFT_NOT_FOUND' });+ expect(await sendDraft('unapproved')).toMatchObject({ status: 409, code: 'DRAFT_STATE_CONFLICT' });+ doubles.getAccount.mockResolvedValueOnce(null);+ expect(await sendDraft('missing-account')).toMatchObject({ code: 'ACCOUNT_NOT_FOUND' });+ expect(await sendDraft('mismatch')).toMatchObject({ code: 'SEND_VIA_MISMATCH' });+ expect((await getDraft('missing-account')).status).toBe('approved');+ expect((await getDraft('mismatch')).status).toBe('approved');+ expect(doubles.sendGmail).not.toHaveBeenCalled();+ expect(doubles.sendPlaywright).not.toHaveBeenCalled();+ });+});