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: preserve mailbox account changes during concurrent sync (#8527)
[._.]/ Adam Eivyffc1ac7f387b
diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.jsindex c3fbdfb0ab..ea088e2c20 100644--- a/server/services/messageAccounts.js+++ b/server/services/messageAccounts.js@@ -2,9 +2,12 @@ import { noteReadinessChanged } from './readinessNotify.js';import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { ensureDir, PATHS, safeJSONParse, tryReadFile, atomicWrite } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { isPlainObject } from '../lib/objects.js';const ACCOUNTS_FILE = join(PATHS.messages, 'accounts.json');+// All account IDs share this file, including sync metadata writes.+const queueAccountWrite = createFileWriteQueue();async function loadAccounts() {await ensureDir(PATHS.messages);@@ -31,60 +34,66 @@ export async function getAccount(id) {}export async function createAccount(data) {- const accounts = await loadAccounts();- const id = uuidv4();- accounts[id] = {- id,- name: data.name,- type: data.type, // gmail, outlook, teams- provider: data.type === 'gmail' ? 'api' : 'playwright',- email: data.email || '',- enabled: true,- syncConfig: {- maxAge: data.syncConfig?.maxAge || '30d',- maxMessages: data.syncConfig?.maxMessages || 500,- syncInterval: data.syncConfig?.syncInterval || 300000,- // Ingest sent mail into the human-activity timeline as `message.sent` events- // so Tribe-outreach reply detection can see a thread as answered (#2796).- // Only Gmail has a sent-fetch path today; default it on there, off elsewhere.- // Absent (existing accounts) is treated as on for Gmail by the readers, so a- // migration isn't needed — this only makes new accounts' stored state explicit.- ingestSent: data.syncConfig?.ingestSent ?? (data.type === 'gmail')- },- // Gmail send-as alias addresses (#2831), refreshed on each sync. Owner addresses- // beyond the primary `email`; used to exclude the owner from received-message- // participants so a 1:1 email delivered to an alias isn't misread as a group thread.- // Additive/back-compat: existing accounts lack the key and readers treat absent as [].- sendAsAliases: [],- lastSyncAt: null,- lastSyncStatus: null,- createdAt: new Date().toISOString()- };- await saveAccounts(accounts);- console.log(`📧 Message account created: ${data.name} (${data.type})`);- return accounts[id];+ return queueAccountWrite(async () => {+ const accounts = await loadAccounts();+ const id = uuidv4();+ accounts[id] = {+ id,+ name: data.name,+ type: data.type, // gmail, outlook, teams+ provider: data.type === 'gmail' ? 'api' : 'playwright',+ email: data.email || '',+ enabled: true,+ syncConfig: {+ maxAge: data.syncConfig?.maxAge || '30d',+ maxMessages: data.syncConfig?.maxMessages || 500,+ syncInterval: data.syncConfig?.syncInterval || 300000,+ // Ingest sent mail into the human-activity timeline as `message.sent` events+ // so Tribe-outreach reply detection can see a thread as answered (#2796).+ // Only Gmail has a sent-fetch path today; default it on there, off elsewhere.+ // Absent (existing accounts) is treated as on for Gmail by the readers, so a+ // migration isn't needed — this only makes new accounts' stored state explicit.+ ingestSent: data.syncConfig?.ingestSent ?? (data.type === 'gmail')+ },+ // Gmail send-as alias addresses (#2831), refreshed on each sync. Owner addresses+ // beyond the primary `email`; used to exclude the owner from received-message+ // participants so a 1:1 email delivered to an alias isn't misread as a group thread.+ // Additive/back-compat: existing accounts lack the key and readers treat absent as [].+ sendAsAliases: [],+ lastSyncAt: null,+ lastSyncStatus: null,+ createdAt: new Date().toISOString()+ };+ await saveAccounts(accounts);+ console.log(`📧 Message account created: ${data.name} (${data.type})`);+ return accounts[id];+ });}export async function updateAccount(id, updates) {- const accounts = await loadAccounts();- if (!accounts[id]) return null;- const { name, email, enabled, syncConfig } = updates;- if (name !== undefined) accounts[id].name = name;- if (email !== undefined) accounts[id].email = email;- if (enabled !== undefined) accounts[id].enabled = enabled;- if (syncConfig) accounts[id].syncConfig = { ...accounts[id].syncConfig, ...syncConfig };- accounts[id].updatedAt = new Date().toISOString();- await saveAccounts(accounts);- return accounts[id];+ return queueAccountWrite(async () => {+ const accounts = await loadAccounts();+ if (!accounts[id]) return null;+ const { name, email, enabled, syncConfig } = updates;+ if (name !== undefined) accounts[id].name = name;+ if (email !== undefined) accounts[id].email = email;+ if (enabled !== undefined) accounts[id].enabled = enabled;+ if (syncConfig) accounts[id].syncConfig = { ...accounts[id].syncConfig, ...syncConfig };+ accounts[id].updatedAt = new Date().toISOString();+ await saveAccounts(accounts);+ return accounts[id];+ });}export async function deleteAccount(id) {- const accounts = await loadAccounts();- if (!accounts[id]) return false;- delete accounts[id];- await saveAccounts(accounts);- console.log(`🗑️ Message account deleted: ${id}`);- return true;+ return queueAccountWrite(async () => {+ const accounts = await loadAccounts();+ if (!accounts[id]) return false;+ delete accounts[id];+ await saveAccounts(accounts);+ console.log(`🗑️ Message account deleted: ${id}`);+ return true;+ });}// Persist the account's Gmail send-as aliases (#2831), refreshed opportunistically on@@ -92,22 +101,26 @@ export async function deleteAccount(id) {// `messageActivityCandidates` to exclude ALL owner addresses (not just the primary)// from received-message participants. Lowercased + deduped; absent → [] for readers.export async function updateSendAsAliases(id, aliases = []) {- const accounts = await loadAccounts();- if (!accounts[id]) return null;- accounts[id].sendAsAliases = Array.isArray(aliases)- ? [...new Set(aliases.map((a) => String(a || '').trim().toLowerCase()).filter(Boolean))]- : [];- await saveAccounts(accounts);- return accounts[id];+ return queueAccountWrite(async () => {+ const accounts = await loadAccounts();+ if (!accounts[id]) return null;+ accounts[id].sendAsAliases = Array.isArray(aliases)+ ? [...new Set(aliases.map((a) => String(a || '').trim().toLowerCase()).filter(Boolean))]+ : [];+ await saveAccounts(accounts);+ return accounts[id];+ });}export async function updateSyncStatus(id, status) {- const accounts = await loadAccounts();- if (!accounts[id]) return null;- accounts[id].lastSyncAt = new Date().toISOString();- accounts[id].lastSyncStatus = status;- await saveAccounts(accounts);- return accounts[id];+ return queueAccountWrite(async () => {+ const accounts = await loadAccounts();+ if (!accounts[id]) return null;+ accounts[id].lastSyncAt = new Date().toISOString();+ accounts[id].lastSyncStatus = status;+ await saveAccounts(accounts);+ return accounts[id];+ });}// Stamp the reply-detection watermark (#2796): the last time this account@@ -121,10 +134,12 @@ export async function updateSyncStatus(id, status) {// reply evidence — `sentCoveragePartial:true` drops it from the two-way set for// the scan (fail closed). A later full sync clears it back to false.export async function markSentIngested(id, { at = new Date().toISOString(), partial = false } = {}) {- const accounts = await loadAccounts();- if (!accounts[id]) return null;- accounts[id].sentIngestedAt = at;- accounts[id].sentCoveragePartial = partial;- await saveAccounts(accounts);- return accounts[id];+ return queueAccountWrite(async () => {+ const accounts = await loadAccounts();+ if (!accounts[id]) return null;+ accounts[id].sentIngestedAt = at;+ accounts[id].sentCoveragePartial = partial;+ await saveAccounts(accounts);+ return accounts[id];+ });}diff --git a/server/services/messageAccounts.test.js b/server/services/messageAccounts.test.jsindex 44b63f334f..2ea35bf17e 100644--- a/server/services/messageAccounts.test.js+++ b/server/services/messageAccounts.test.js@@ -6,19 +6,42 @@ import { makePathsProxy } from '../lib/mockPathsDataRoot.js';const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'message-accounts-test-'));-vi.mock('../lib/fileUtils.js', async (importOriginal) =>- makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...makePathsProxy(actual, { dataRoot: TEST_DATA_ROOT }),+ atomicWrite: vi.fn(actual.atomicWrite)+ };+});vi.mock('../lib/uuid.js', () => ({v4: vi.fn().mockReturnValue('msg-uuid-5678'),}));const messageAccounts = await import('./messageAccounts.js');+const { atomicWrite } = await import('../lib/fileUtils.js');+const { atomicWrite: persist } = await vi.importActual('../lib/fileUtils.js');+const { v4: uuid } = await import('../lib/uuid.js');++// Pause persistence after its read so competing service calls overlap deterministically.+function holdNextWrite({ fail = false } = {}) {+ const entered = Promise.withResolvers();+ const release = Promise.withResolvers();+ atomicWrite.mockImplementationOnce(async (...args) => {+ entered.resolve();+ await release.promise;+ if (fail) throw new Error('synthetic persistence failure');+ return persist(...args);+ });+ return { entered: entered.promise, release: release.resolve };+}afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));describe('messageAccounts', () => {beforeEach(() => {+ atomicWrite.mockReset().mockImplementation(persist);+ uuid.mockReset().mockReturnValue('msg-uuid-5678');rmSync(TEST_DATA_ROOT, { recursive: true, force: true });mkdirSync(TEST_DATA_ROOT, { recursive: true });});@@ -101,4 +124,68 @@ describe('messageAccounts', () => {expect(result).toBeNull();});});+ describe('concurrent persistence', () => {+ it.each(['same account', 'different accounts'])('preserves edits and sync status for %s', async (scope) => {+ uuid.mockReturnValueOnce('account-a').mockReturnValueOnce('account-b');+ await messageAccounts.createAccount({ name: 'Account A', type: 'gmail' });+ await messageAccounts.createAccount({ name: 'Account B', type: 'gmail' });+ const barrier = holdNextWrite();+ const edit = messageAccounts.updateAccount('account-a', { enabled: false });+ await barrier.entered;+ const statusId = scope === 'same account' ? 'account-a' : 'account-b';+ const status = messageAccounts.updateSyncStatus(statusId, 'success');+ barrier.release();+ await Promise.all([edit, status]);+ expect(await messageAccounts.getAccount('account-a')).toMatchObject({ enabled: false });+ expect(await messageAccounts.getAccount(statusId)).toMatchObject({ lastSyncStatus: 'success' });+ });++ it('does not resurrect a deleted account through queued sync metadata writes', async () => {+ const account = await messageAccounts.createAccount({ name: 'Account A', type: 'gmail' });+ const barrier = holdNextWrite();+ const deletion = messageAccounts.deleteAccount(account.id);+ await barrier.entered;+ const metadata = [+ messageAccounts.updateSyncStatus(account.id, 'success'),+ messageAccounts.updateSendAsAliases(account.id, ['[email protected]']),+ messageAccounts.markSentIngested(account.id)+ ];+ barrier.release();+ expect(await deletion).toBe(true);+ expect(await Promise.all(metadata)).toEqual([null, null, null]);+ expect(await messageAccounts.listAccounts()).toEqual([]);+ });++ it('preserves concurrent creates and subsequent alias and coverage changes', async () => {+ uuid.mockReturnValueOnce('account-a').mockReturnValueOnce('account-b');+ const barrier = holdNextWrite();+ const first = messageAccounts.createAccount({ name: 'Account A', type: 'gmail' });+ await barrier.entered;+ const second = messageAccounts.createAccount({ name: 'Account B', type: 'gmail' });+ const aliases = messageAccounts.updateSendAsAliases('account-a', [' [email protected] ']);+ const watermark = messageAccounts.markSentIngested('account-b', { at: '2026-01-01T00:00:00.000Z', partial: true });+ barrier.release();+ await Promise.all([first, second, aliases, watermark]);+ expect(await messageAccounts.listAccounts()).toEqual([+ expect.objectContaining({ id: 'account-a', sendAsAliases: ['[email protected]'] }),+ expect.objectContaining({ id: 'account-b', sentIngestedAt: '2026-01-01T00:00:00.000Z', sentCoveragePartial: true })+ ]);+ });++ it('rejects a failed save and lets a queued write use the last persisted state', async () => {+ const account = await messageAccounts.createAccount({ name: 'Account A', type: 'gmail' });+ const barrier = holdNextWrite({ fail: true });+ const edit = messageAccounts.updateAccount(account.id, { enabled: false });+ const rejected = expect(edit).rejects.toThrow('synthetic persistence failure');+ await barrier.entered;+ const status = messageAccounts.updateSyncStatus(account.id, 'success');+ barrier.release();+ await rejected;+ await status;+ expect(await messageAccounts.getAccount(account.id)).toMatchObject({+ enabled: true, lastSyncStatus: 'success'+ });+ });+ });+});