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

fix: make mailbox deletion failures visible and retryable (#8647)

[._.]/ Adam Eivy5c91887363b3
diff --git a/client/src/components/messages/ConfigTab.test.jsx b/client/src/components/messages/ConfigTab.test.jsx
index d949d6185c..14a8589271 100644
--- a/client/src/components/messages/ConfigTab.test.jsx
+++ b/client/src/components/messages/ConfigTab.test.jsx
@@ -3,6 +3,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
const api = vi.hoisted(() => ({
+ deleteMessageAccount: vi.fn(),
getGoogleAuthStatus: vi.fn(),
getGoogleAuthUrl: vi.fn(),
getSettings: vi.fn(),
@@ -39,10 +40,10 @@ const gmailAccount = {
syncConfig: { ingestSent: true },
};
-function renderConfig() {
+function renderConfig(setAccounts = vi.fn()) {
return render(
<MemoryRouter initialEntries={['/messages/config']}>
- <ConfigTab accounts={[gmailAccount]} setAccounts={vi.fn()} />
+ <ConfigTab accounts={[gmailAccount]} setAccounts={setAccounts} />
</MemoryRouter>,
);
}
@@ -106,3 +107,27 @@ describe('Messages Gmail OAuth setup', () => {
expect(screen.getByRole('button', { name: 'Pending authorization' })).toBeInTheDocument();
});
});
+
+
+describe('Messages account deletion', () => {
+ it('retains the account without a success toast on cleanup failure, then allows retry', async () => {
+ api.getGoogleAuthStatus.mockResolvedValue({ hasCredentials: true, hasTokens: true });
+ api.deleteMessageAccount.mockRejectedValueOnce(new Error('Cleanup failed')).mockResolvedValueOnce(undefined);
+ const setAccounts = vi.fn();
+ renderConfig(setAccounts);
+ await screen.findByRole('button', { name: 'Enabled' });
+
+ fireEvent.click(screen.getByTitle('Delete account'));
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }));
+ await waitFor(() => expect(api.deleteMessageAccount).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(screen.getByTitle('Delete account')).not.toBeDisabled());
+ expect(setAccounts).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(screen.getByText('Personal')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByTitle('Delete account'));
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }));
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Account deleted'));
+ expect(setAccounts.mock.calls[0][0]([gmailAccount])).toEqual([]);
+ });
+});
diff --git a/server/routes/messages.cleanup.test.js b/server/routes/messages.cleanup.test.js
new file mode 100644
index 0000000000..06076550ce
--- /dev/null
+++ b/server/routes/messages.cleanup.test.js
@@ -0,0 +1,111 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import { request } from '../lib/testHelper.js';
+import { errorEvents } from '../lib/errorHandler.js';
+
+const tempRoot = mkdtempSync(join(tmpdir(), 'messages-cleanup-test-'));
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...makePathsProxy(actual, { dataRoot: tempRoot }),
+ atomicWrite: vi.fn(actual.atomicWrite)
+ };
+});
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, unlink: vi.fn(actual.unlink) };
+});
+vi.mock('../services/readinessNotify.js', () => ({ noteReadinessChanged: vi.fn() }));
+vi.mock('../services/messageEvaluator.js', () => ({ evaluateMessages: vi.fn(), generateReplyBody: vi.fn() }));
+vi.mock('../services/messageSender.js', () => ({ sendDraft: vi.fn() }));
+vi.mock('../services/messagePlaywrightSync.js', () => ({
+ getSelectors: vi.fn(), updateSelectors: vi.fn(), testSelectors: vi.fn(), launchProvider: vi.fn()
+}));
+vi.mock('../services/messageActions.js', () => ({ executeAction: vi.fn() }));
+vi.mock('../services/messageTriageRules.js', () => ({ listRules: vi.fn(), deleteRule: vi.fn() }));
+vi.mock('../services/messageTokenExtractor.js', () => ({
+ getToken: vi.fn(), getTokenStatus: vi.fn(), testApi: vi.fn(), clearTokenCache: vi.fn()
+}));
+
+const { atomicWrite, PATHS } = await import('../lib/fileUtils.js');
+const { atomicWrite: persist } = await vi.importActual('../lib/fileUtils.js');
+const { unlink } = await import('fs/promises');
+const { unlink: remove } = await vi.importActual('fs/promises');
+const accounts = await import('../services/messageAccounts.js');
+const drafts = await import('../services/messageDrafts.js');
+const sync = await import('../services/messageSync.js');
+const { default: routes } = await import('./messages.js');
+
+const io = { emit: vi.fn() };
+const app = express();
+app.use(express.json());
+app.set('io', io);
+app.use('/api/messages', routes);
+const observeError = () => {};
+beforeAll(() => errorEvents.on('error', observeError));
+afterAll(() => {
+ errorEvents.off('error', observeError);
+ rmSync(tempRoot, { recursive: true, force: true });
+});
+beforeEach(() => {
+ rmSync(tempRoot, { recursive: true, force: true });
+ atomicWrite.mockReset().mockImplementation(persist);
+ unlink.mockReset().mockImplementation(remove);
+ io.emit.mockClear();
+});
+
+async function seedMailbox() {
+ const account = await accounts.createAccount({ name: 'Example mailbox', type: 'gmail' });
+ await persist(join(PATHS.messages, 'cache', `${account.id}.json`), {
+ messages: [{ id: 'example-message', subject: 'Example subject', bodyText: 'Example mail', date: '2026-01-01' }]
+ });
+ await drafts.createDraft({ accountId: account.id, to: ['[email protected]'], body: 'Example draft' });
+ return account.id;
+}
+
+describe('mailbox deletion cleanup with isolated persisted stores', () => {
+ it.each(['cache unlink', 'draft persistence'])('keeps a disabled account retryable after %s fails', async (failure) => {
+ const id = await seedMailbox();
+ const storageError = Object.assign(new Error('Synthetic cleanup failure'), { code: 'EACCES' });
+ if (failure === 'cache unlink') {
+ unlink.mockRejectedValueOnce(storageError);
+ } else {
+ atomicWrite.mockImplementation(async (path, ...args) => {
+ if (path === join(PATHS.messages, 'drafts.json')) throw storageError;
+ return persist(path, ...args);
+ });
+ }
+
+ const failed = await request(app).delete(`/api/messages/accounts/${id}`);
+ expect(failed.status).toBe(500);
+ expect(await accounts.getAccount(id)).toMatchObject({ id, enabled: false });
+ expect(await drafts.listDrafts({ accountId: id })).toHaveLength(1);
+ expect((await sync.getMessages()).total).toBe(failure === 'cache unlink' ? 1 : 0);
+ expect(io.emit).toHaveBeenCalledWith('error:occurred', expect.objectContaining({ status: 500 }));
+ expect(io.emit).not.toHaveBeenCalledWith('messages:changed', expect.anything());
+ expect(await sync.syncAccount(id)).toMatchObject({ error: 'Account is disabled' });
+
+ atomicWrite.mockImplementation(persist);
+ const retried = await request(app).delete(`/api/messages/accounts/${id}`);
+ expect(retried.status).toBe(204);
+ expect(await accounts.getAccount(id)).toBeNull();
+ expect(await sync.getMessages()).toEqual({ messages: [], total: 0 });
+ expect(await drafts.listDrafts()).toEqual([]);
+ expect(io.emit).toHaveBeenCalledWith('messages:changed', {});
+ });
+
+ it('erases historical orphan stores and treats repeated deletion as a successful no-op', async () => {
+ const id = await seedMailbox();
+ await accounts.deleteAccount(id);
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const response = await request(app).delete(`/api/messages/accounts/${id}`);
+ expect(response.status).toBe(204);
+ expect(await sync.getMessages()).toEqual({ messages: [], total: 0 });
+ expect(await drafts.listDrafts()).toEqual([]);
+ }
+ });
+});
diff --git a/server/routes/messages.js b/server/routes/messages.js
index 909db6decc..05dde339b9 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -112,11 +112,12 @@ router.delete('/accounts/:id', asyncHandler(async (req, res) => {
if (!UUID_RE.test(req.params.id)) {
throw new ServerError('Invalid account ID format', { status: 400 });
}
- const deleted = await messageAccounts.deleteAccount(req.params.id);
- if (!deleted) throw new ServerError('Account not found', { status: 404 });
- // Clean up related data
- await messageSync.deleteCache(req.params.id).catch(() => {});
- await messageDrafts.deleteDraftsByAccountId(req.params.id).catch(() => {});
+ // Stop scheduled ingestion, retaining the account for retry if cleanup fails.
+ // Missing accounts still need cleanup: older deletions may have left orphans.
+ await messageAccounts.updateAccount(req.params.id, { enabled: false });
+ await messageSync.deleteCache(req.params.id);
+ await messageDrafts.deleteDraftsByAccountId(req.params.id);
+ await messageAccounts.deleteAccount(req.params.id);
req.app.get('io')?.emit('messages:changed', {});
res.status(204).send();
}));
diff --git a/server/routes/messages.test.js b/server/routes/messages.test.js
index d215680f04..9265befa74 100644
--- a/server/routes/messages.test.js
+++ b/server/routes/messages.test.js
@@ -197,13 +197,15 @@ describe('Messages Routes', () => {
expect(response.body.error).toBe('Invalid account ID format');
});
- it('should return 404 if account not found', async () => {
+ it('cleans up historical orphan data even when the account is absent', async () => {
+ messageAccounts.updateAccount.mockResolvedValue(null);
messageAccounts.deleteAccount.mockResolvedValue(false);
const response = await request(app).delete(`/api/messages/accounts/${VALID_UUID}`);
- expect(response.status).toBe(404);
- expect(response.body.error).toBe('Account not found');
+ expect(response.status).toBe(204);
+ expect(messageSync.deleteCache).toHaveBeenCalledWith(VALID_UUID);
+ expect(messageDrafts.deleteDraftsByAccountId).toHaveBeenCalledWith(VALID_UUID);
});
});
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 783de144e9..65f800259c 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -118,18 +118,16 @@ export async function getMessages(options = {}) {
export async function deleteCache(accountId) {
if (!UUID_RE.test(accountId)) return;
- const { unlink } = await import('fs/promises');
- const filePath = join(CACHE_DIR, `${accountId}.json`);
- try {
- await unlink(filePath);
+ // Drain cache writers before erasing; a writer already in flight must not
+ // recreate the file after deletion reports success.
+ return queueAccountWrite(accountId, async () => {
+ const { unlink } = await import('fs/promises');
+ const filePath = join(CACHE_DIR, `${accountId}.json`);
+ await unlink(filePath).catch(err => {
+ if (err.code !== 'ENOENT') throw err;
+ });
console.log(`🗑️ Message cache deleted for account ${accountId}`);
- } catch (err) {
- if (err.code === 'ENOENT') {
- console.log(`🗑️ No message cache to delete for account ${accountId}`);
- } else {
- console.error(`❌ Failed to delete message cache for account ${accountId}: ${err.message}`);
- }
- }
+ });
}
export async function getMessage(accountId, messageId) {
@@ -164,6 +162,11 @@ export async function syncAccount(accountId, io, options = {}) {
console.log(`📧 Starting ${mode} sync for ${account.name} (${account.type})`);
const providerSync = async () => {
+ // The initial read may predate queued deletion. Recheck under the cache
+ // queue before a stale sync can write after cleanup.
+ const currentAccount = await getAccount(accountId);
+ if (!currentAccount) return { error: 'Account not found' };
+ if (!currentAccount.enabled) return { error: 'Account is disabled', status: 400 };
const cache = await loadCache(accountId);
let providerResult;
if (account.type === 'gmail') {
diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.js
index 770bea9598..49191273b6 100644
--- a/server/services/messageSync.test.js
+++ b/server/services/messageSync.test.js
@@ -382,6 +382,48 @@ describe('deleteCache', () => {
expect(unlink).toHaveBeenCalledWith(expect.stringContaining(`${VALID_UUID}.json`));
});
+ it('waits for an in-flight cache writer before erasing its result', async () => {
+ const entered = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ let stored = { messages: [{ id: 'msg-1' }] };
+ readFile.mockImplementation(async () => stored ? JSON.stringify(stored) : null);
+ readdir.mockResolvedValue([`${VALID_UUID}.json`]);
+ atomicWrite.mockImplementationOnce(async (_path, data) => {
+ entered.resolve();
+ await release.promise;
+ stored = data;
+ });
+ unlink.mockImplementationOnce(async () => { stored = null; });
+
+ const writer = updateMessageEvaluations({ 'msg-1': { score: 9 } });
+ await entered.promise;
+ const cleanup = deleteCache(VALID_UUID);
+ expect(stored).not.toBeNull();
+ release.resolve();
+ await Promise.all([writer, cleanup]);
+ expect(stored).toBeNull();
+ expect(await getMessages({ accountId: VALID_UUID })).toEqual({ messages: [], total: 0 });
+ });
+
+ it('rejects a sync with a stale enabled-account read after cleanup', async () => {
+ const entered = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ getAccount.mockImplementationOnce(async () => {
+ entered.resolve();
+ await release.promise;
+ return { id: VALID_UUID, name: 'Example', type: 'gmail', enabled: true };
+ }).mockResolvedValue(null);
+ unlink.mockResolvedValue();
+ const syncing = syncAccount(VALID_UUID);
+ await entered.promise;
+ await deleteCache(VALID_UUID);
+ release.resolve();
+
+ expect(await syncing).toEqual({ error: 'Account not found' });
+ expect(syncGmail).not.toHaveBeenCalled();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
it('should silently skip invalid accountId', async () => {
await deleteCache('not-a-uuid');
expect(unlink).not.toHaveBeenCalled();