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 message identity in browser archive and delete (#8784)
[._.]/ Adam Eivye63c6d9782f3
diff --git a/client/src/components/messages/InboxTab.test.jsx b/client/src/components/messages/InboxTab.test.jsxindex b1747885d4..53174d018a 100644--- a/client/src/components/messages/InboxTab.test.jsx+++ b/client/src/components/messages/InboxTab.test.jsx@@ -312,3 +312,16 @@ describe('InboxTab triage tab bar (#7244)', () => {expect(allTab).toHaveAttribute('aria-selected', 'true');});});++it('retains the requested inbox row and displays the actionable identity conflict', async () => {+ const row = { id: 'requested', accountId: neverSyncedAccount.id, subject: 'Keep this message', from: { name: 'Example Sender' }, date: HOUR_AGO, source: 'gmail' };+ api.getMessageInbox.mockResolvedValue({ messages: [row], total: 1 });+ api.executeMessageAction.mockRejectedValueOnce(Object.assign(new Error('Sync the account and retry.'), { status: 409, code: 'MESSAGE_IDENTITY_CONFLICT' }));+ renderInbox([neverSyncedAccount]);+ expect(await screen.findByText(row.subject)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Delete', exact: true }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Sync the account and retry.'));+ expect(api.executeMessageAction).toHaveBeenCalledWith(row.accountId, row.id, 'delete', { silent: true });+ expect(screen.getByText(row.subject)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Delete', exact: true })).not.toBeDisabled();+});diff --git a/server/lib/README.md b/server/lib/README.mdindex f8fd201cd6..4ff5de8696 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -763,3 +763,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `messageLogError.js` | `messageLogError(error)` projects mailbox failures to allowlisted codes and HTTP error status, excluding provider text and credentials. || `launchVideoValidation.js` | `validateLaunchVideoAssets` checks frozen launch composition text, storyboard reading time, duration, and poster position before rendering. |++| `messageBrowserIdentity.js` | Shared Outlook row extraction and identity-safe browser action scripts; exact unique targets and confirmed row removal. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 54c826a875..29a9136d87 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -745,3 +745,5 @@ export * from './messageLogError.js';export * from './launchVideoValidation.js';export * from './styleSourcePrompt.js';++export * from './messageBrowserIdentity.js';diff --git a/server/lib/messageBrowserIdentity.js b/server/lib/messageBrowserIdentity.jsnew file mode 100644index 0000000000..73b2a2d284--- /dev/null+++ b/server/lib/messageBrowserIdentity.js@@ -0,0 +1,123 @@+/** DOM reader shared by Outlook ingestion and destructive browser actions.+ * Self-contained so it can be serialized into a CDP evaluation. */+export function readOutlookMessageRow(row) {+ const ariaLabel = row.getAttribute('aria-label') || '';+ const isUnread = !!row.querySelector('button[aria-label="Mark as read"]');+ const isPinned = !!row.querySelector('button[aria-label*="Unpin"]');+ const isFlagged = !!row.querySelector('button[aria-label*="Unflag"]');+ const isReplied = ariaLabel.includes('Replied');+ const hasMeetingInvite = !!row.querySelector('button[aria-label="RSVP"]');++ const avatarSpan = row.querySelector('div[aria-label="Select a conversation"] > span[aria-label]');+ const from = avatarSpan?.getAttribute('aria-label') || '';++ const checkbox = row.querySelector('div[aria-label="Select a conversation"]');+ const contentArea = checkbox?.parentElement?.nextElementSibling;+ const contentDivs = contentArea ? Array.from(contentArea.children) : [];++ let subject = '', date = '', preview = '', fromEmail = '';++ if (contentDivs.length >= 3) {+ const senderDiv = contentDivs[0];+ const emailSpan = senderDiv?.querySelector('span[title*="@"]');+ fromEmail = emailSpan?.getAttribute('title') || '';++ const subDateDiv = contentDivs[1];+ const spans = subDateDiv ? Array.from(subDateDiv.querySelectorAll('span')) : [];+ subject = spans[0]?.textContent?.trim() || '';+ const dateSpan = spans.find(s => s.getAttribute('title')?.match(/\d{4}/));+ date = dateSpan?.getAttribute('title') || spans[spans.length - 1]?.textContent?.trim() || '';++ preview = contentDivs[2]?.textContent?.trim() || '';+ } else if (contentDivs.length >= 1) {+ const allSpans = contentDivs[0]?.querySelectorAll('span[title]') || [];+ const spanArr = Array.from(allSpans);+ const emailSpan = spanArr.find(s => (s.getAttribute('title') || '').includes('@'));+ fromEmail = emailSpan?.getAttribute('title') || '';+ // In compact layout: first titled span is sender, second is subject+ const titledSpans = spanArr.filter(s => s.closest('[class]'));+ subject = titledSpans.length > 1 ? titledSpans[titledSpans.length - 1]?.textContent?.trim() || '' : '';+ // Fallback: find span whose text differs from sender name+ if (!subject) {+ subject = spanArr.find(s => s.textContent?.trim() && s.textContent.trim() !== from && !(s.getAttribute('title') || '').includes('@'))?.textContent?.trim() || '';+ }+ const dateMatch = ariaLabel.match(/(\d{1,2}\/\d{1,2}(?:\/\d{2,4})?)/);+ date = dateMatch?.[1] || '';+ }++ const providerRowId = row.getAttribute('data-itemid') || row.getAttribute('data-convid') || null;+ return { providerRowId, from, fromEmail, subject, date, preview, isUnread, isPinned, isFlagged, isReplied, hasMeetingInvite };+}++/** All values are serialized as JSON, never interpolated as executable text. */+export function buildMessageBrowserActionScript(provider, message, action) {+ const identity = {+ id: message.id,+ providerRowId: message.providerRowId || null,+ subject: message.subject,+ from: message.from,+ date: message.date+ };+ return `(${actOnMessageRow.toString()})(${JSON.stringify(provider)}, ${JSON.stringify(identity)}, ${JSON.stringify(action)}, ${readOutlookMessageRow.toString()})`;+}++// Runs entirely inside the provider page. No keyboard shortcuts or global bulk+// actions: those can act on a different focused message or an existing selection.+async function actOnMessageRow(provider, identity, action, readOutlookRow) {+ const conflict = () => ({ code: 'MESSAGE_IDENTITY_CONFLICT' });+ const list = document.querySelector(provider === 'outlook' ? '[role="listbox"]' : '[role="main"]');+ if (!list || !['archive', 'delete'].includes(action)) return conflict();+ const rowSelector = provider === 'outlook' ? '[role="option"]' : 'tr.zA';+ const rows = () => [...list.querySelectorAll(rowSelector)];+ function read(row) {+ if (provider === 'outlook') return readOutlookRow(row);+ const sender = row.querySelector('[email]');+ const dated = row.querySelector('td.xW [title]');+ const idNode = row.matches('[data-legacy-message-id], [data-legacy-thread-id]')+ ? row : row.querySelector('[data-legacy-message-id], [data-legacy-thread-id]');+ return {+ providerRowId: idNode?.getAttribute('data-legacy-message-id') || idNode?.getAttribute('data-legacy-thread-id') || null,+ subject: row.querySelector('.bog')?.textContent?.trim() || '',+ from: sender?.getAttribute('name') || sender?.textContent?.trim() || '',+ fromEmail: sender?.getAttribute('email') || '',+ date: dated?.getAttribute('title') || ''+ };+ }+ function matches(row) {+ const actual = read(row);+ if (identity.providerRowId) return actual.providerRowId === identity.providerRowId;+ // Legacy records must supply every identity dimension. Do not normalize+ // case, truncate subjects, or guess missing dates/senders.+ if (!identity.subject?.trim() || !identity.date || !(identity.from?.email || identity.from?.name)) return false;+ return actual.subject === identity.subject && actual.date === identity.date+ && (!identity.from.email || actual.fromEmail === identity.from.email)+ && (!identity.from.name || actual.from === identity.from.name);+ }+ // A virtualized/scrolling list cannot establish legacy uniqueness outside the+ // rendered window. A fresh sync may supply an ID; otherwise use the provider UI.+ if (!identity.providerRowId) {+ for (let node = list; node; node = node.parentElement) {+ if (node.scrollHeight > node.clientHeight) return conflict();+ }+ if (rows().some(row => Number(row.getAttribute('aria-setsize')) > rows().length)) return conflict();+ }+ const candidates = rows().filter(matches);+ if (candidates.length !== 1) return conflict();+ const target = candidates[0];+ const label = action === 'archive' ? 'Archive' : 'Delete';+ const controls = [...target.querySelectorAll('button, [role="button"]')].filter(button =>+ [button.getAttribute('aria-label'), button.getAttribute('data-tooltip'), button.getAttribute('title')].includes(label)+ && !button.disabled && button.getAttribute('aria-disabled') !== 'true');+ if (controls.length !== 1) return conflict();+ // Recheck immediately before the side effect, without an intervening await.+ if (!target.isConnected || !matches(target) || rows().filter(matches).length !== 1) return conflict();+ const url = location.href;+ controls[0].click();+ for (let attempt = 0; attempt < 20; attempt++) {+ await new Promise(resolve => setTimeout(resolve, 100));+ // Navigation or a missing list is not evidence that this message was removed.+ if (location.href !== url || !list.isConnected) return { code: 'MESSAGE_ACTION_UNCONFIRMED' };+ if (rows().filter(matches).length === 0) return { success: true, messageId: identity.id };+ }+ return { code: 'MESSAGE_ACTION_UNCONFIRMED' };+}diff --git a/server/routes/messages.test.js b/server/routes/messages.test.jsindex 26f819b7e7..b1df847ec5 100644--- a/server/routes/messages.test.js+++ b/server/routes/messages.test.js@@ -10,6 +10,9 @@ const observeError = () => {};beforeAll(() => errorEvents.on('error', observeError));afterAll(() => errorEvents.off('error', observeError));+vi.mock('../services/messageActions.js', () => ({ executeAction: vi.fn() }));+import { executeAction } from '../services/messageActions.js';+// Mock the servicesvi.mock('../services/messageAccounts.js', () => ({listAccounts: vi.fn(),@@ -817,3 +820,19 @@ describe('Messages Routes', () => {});});});++describe('message browser action conflict envelope', () => {+ it('preserves both IDs and returns a typed 409 without broadcasting a change', async () => {+ const app = express();+ const emit = vi.fn();+ app.set('io', { emit });+ app.use(express.json());+ app.use('/api/messages', messagesRoutes);+ executeAction.mockRejectedValueOnce(new ServerError('Sync the account and retry.', { status: 409, code: 'MESSAGE_IDENTITY_CONFLICT' }));+ const response = await request(app).post(`/api/messages/${VALID_UUID}/${VALID_UUID_2}/action`).send({ action: 'delete' });+ expect(executeAction).toHaveBeenCalledWith(VALID_UUID, VALID_UUID_2, 'delete');+ expect(response.status).toBe(409);+ expect(response.body).toMatchObject({ error: 'Sync the account and retry.', code: 'MESSAGE_IDENTITY_CONFLICT' });+ expect(emit).not.toHaveBeenCalledWith('messages:changed', expect.anything());+ });+});diff --git a/server/services/messageActions.js b/server/services/messageActions.jsindex ae4ca0a1be..6f7b7241b0 100644--- a/server/services/messageActions.js+++ b/server/services/messageActions.js@@ -1,37 +1,16 @@+import { ServerError } from '../lib/errorHandler.js';+import { buildMessageBrowserActionScript } from '../lib/messageBrowserIdentity.js';import { getAccount } from './messageAccounts.js';-import { getMessage } from './messageSync.js';+import { getMessage, removeMessageFromCache } from './messageSync.js';import { findOrOpenPage, getPages, isAuthPage, evaluateOnPage } from './messagePlaywrightSync.js';import { recordCorrection } from './messageTriageRules.js';-import { join } from 'path';-import { atomicWrite, ensureDir, PATHS, safeJSONParse, UUID_RE, tryReadFile } from '../lib/fileUtils.js';--const CACHE_DIR = join(PATHS.messages, 'cache');+import { UUID_RE } from '../lib/fileUtils.js';const PROVIDER_URLS = {outlook: 'https://outlook.office.com/mail/',gmail: 'https://mail.google.com/'};-async function loadCache(accountId) {- await ensureDir(CACHE_DIR);- const filePath = join(CACHE_DIR, `${accountId}.json`);- const content = await tryReadFile(filePath);- if (!content) return { syncCursor: null, messages: [] };- return safeJSONParse(content, { syncCursor: null, messages: [] }, { context: `messageCache:${accountId}` });-}--async function saveCache(accountId, cache) {- await ensureDir(CACHE_DIR);- const filePath = join(CACHE_DIR, `${accountId}.json`);- await atomicWrite(filePath, cache);-}--async function removeFromCache(accountId, messageId) {- const cache = await loadCache(accountId);- cache.messages = cache.messages.filter(m => m.id !== messageId);- await saveCache(accountId, cache);-}-/*** Wait for a provider page to be ready (past auth screens).* Auto-launches the tab if not open, then polls until auth completes or timeout.@@ -85,22 +64,19 @@ export async function executeAction(accountId, messageId, action) {// Gmail: use API directly instead of browser automationif (account.type === 'gmail' && message.apiId) {await executeGmailApiAction(message, action);- } else if (account.type === 'outlook') {+ } else if (account.type === 'outlook' || account.type === 'gmail') {const page = await ensureProviderPage(account.type);console.log(`📧 ${action} message ${message.id} via ${account.type} browser`);- await executeOutlookAction(page, message.subject || '', action);- } else if (account.type === 'gmail') {- // Fallback to browser if no apiId- const page = await ensureProviderPage(account.type);- console.log(`📧 ${action} message ${message.id} via gmail browser`);- const script = buildGmailActionScript((message.subject || '').replace(/'/g, "\\'").replace(/\n/g, ' '), action);- const result = await evaluateOnPage(page, script);- if (!result || result.error) {- if (result?.notInInbox) {- console.log(`📧 ${message.id} not found in inbox, cleaning up local cache`);- } else {- throw new Error(result?.error || `${action} failed`);- }+ const result = await evaluateOnPage(page, buildMessageBrowserActionScript(account.type, message, action));+ if (result?.code === 'MESSAGE_IDENTITY_CONFLICT') {+ throw new ServerError('Cannot uniquely identify this message in the browser. Sync the account and retry, or archive/delete it directly in your mail provider.', {+ status: 409, code: 'MESSAGE_IDENTITY_CONFLICT'+ });+ }+ if (result?.success !== true || result.messageId !== messageId) {+ throw new ServerError('The browser action could not be confirmed. Check your mail provider before retrying; the cached message has been kept.', {+ status: 409, code: 'MESSAGE_ACTION_UNCONFIRMED'+ });}} else {throw new Error(`${action} not supported for ${account.type}`);@@ -117,7 +93,7 @@ export async function executeAction(accountId, messageId, action) {}).catch(() => {});}- await removeFromCache(accountId, messageId);+ await removeMessageFromCache(accountId, messageId);console.log(`📧 ${action} complete for ${message.id}`);return { success: true, action, messageId };@@ -148,121 +124,3 @@ async function executeGmailApiAction(message, action) {console.log(`📧 Gmail API: archived ${message.id}`);}}--/**- * Execute archive/delete on Outlook via CDP: find+click message, then send key via protocol.- */-async function executeOutlookAction(page, subject, action) {- const { default: WebSocket } = await import('ws');-- // Step 1: Find and click the message row using evaluateOnPage- const selectScript = `(async () => {- const listbox = document.querySelector("[role='listbox']");- if (!listbox) return { notInInbox: true, error: 'No message list found' };- const target = ${JSON.stringify(subject)}.toLowerCase();- const scrollContainer = listbox.closest('[role="region"]') || listbox.parentElement;- function findMatch() {- for (const row of listbox.querySelectorAll('[role="option"]')) {- const text = (row.getAttribute('aria-label') || row.innerText || '').toLowerCase();- if (text.includes(target)) return row;- }- return null;- }- let matched = findMatch();- if (!matched && scrollContainer) {- for (let i = 0; i < 15; i++) {- scrollContainer.scrollBy(0, 600);- await new Promise(r => setTimeout(r, 300));- matched = findMatch();- if (matched) break;- }- }- if (!matched) return { notInInbox: true, error: 'Message not found in inbox view' };- matched.scrollIntoView({ block: 'center' });- await new Promise(r => setTimeout(r, 200));- matched.click();- await new Promise(r => setTimeout(r, 800));- return { selected: true };- })()`;-- const selectResult = await evaluateOnPage(page, selectScript);- if (!selectResult || selectResult.error) {- if (selectResult?.notInInbox) {- console.log(`📧 Message not found in inbox, cleaning up local cache`);- return;- }- throw new Error(selectResult?.error || 'Failed to select message');- }-- // Step 2: Send Delete key via CDP Input.dispatchKeyEvent (protocol level, not DOM)- const wsUrl = page.webSocketDebuggerUrl;- if (!wsUrl) throw new Error('No WebSocket URL for CDP');-- const keyCode = action === 'delete' ? 'Delete' : 'Backspace';- const nativeVirtualKeyCode = action === 'delete' ? 46 : 8;-- await new Promise((resolve, reject) => {- const ws = new WebSocket(wsUrl);- const timer = setTimeout(() => { ws.close(); reject(new Error('CDP key dispatch timed out')); }, 10000);- let msgId = 1;-- ws.on('open', () => {- // Send keyDown then keyUp- ws.send(JSON.stringify({- id: msgId++,- method: 'Input.dispatchKeyEvent',- params: { type: 'keyDown', key: keyCode, code: keyCode, nativeVirtualKeyCode, windowsVirtualKeyCode: nativeVirtualKeyCode }- }));- ws.send(JSON.stringify({- id: msgId++,- method: 'Input.dispatchKeyEvent',- params: { type: 'keyUp', key: keyCode, code: keyCode, nativeVirtualKeyCode, windowsVirtualKeyCode: nativeVirtualKeyCode }- }));- });-- let responses = 0;- ws.on('message', (data) => {- const msg = safeJSONParse(data.toString(), null, { context: 'cdp-key' });- if (msg?.id) responses++;- if (responses >= 2) { clearTimeout(timer); ws.close(); resolve(); }- });- ws.on('error', (e) => { clearTimeout(timer); ws.close(); reject(e); });- });-- // Step 3: Wait and verify message is gone- await new Promise(r => setTimeout(r, 1500));- const verifyScript = `(function() {- const listbox = document.querySelector("[role='listbox']");- if (!listbox) return { gone: true };- const target = ${JSON.stringify(subject)}.toLowerCase();- for (const row of listbox.querySelectorAll('[role="option"]')) {- const text = (row.getAttribute('aria-label') || row.innerText || '').toLowerCase();- if (text.includes(target)) return { gone: false };- }- return { gone: true };- })()`;- const verify = await evaluateOnPage(page, verifyScript);- if (verify && !verify.gone) {- throw new Error(`Message still in inbox after ${action} attempt — action may not have worked`);- }-}--function buildGmailActionScript(subject, action) {- const ariaLabel = action === 'archive' ? 'Archive' : 'Delete';- return `(async () => {- const rows = [...document.querySelectorAll('tr.zA, [role="row"]')];- const row = rows.find(r => r.textContent?.includes('${subject}'));- if (!row) return { error: 'Message not found in inbox view' };-- const checkbox = row.querySelector('[role="checkbox"], input[type="checkbox"]');- if (checkbox) checkbox.click();- await new Promise(r => setTimeout(r, 300));-- const btn = document.querySelector('[aria-label="${ariaLabel}"], [data-tooltip="${ariaLabel}"]');- if (!btn) return { error: '${ariaLabel} button not found' };-- btn.click();- await new Promise(r => setTimeout(r, 1000));- return { success: true };- })()`;-}diff --git a/server/services/messageActions.test.js b/server/services/messageActions.test.jsnew file mode 100644index 0000000000..5d2f458b75--- /dev/null+++ b/server/services/messageActions.test.js@@ -0,0 +1,92 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { runInNewContext } from 'node:vm';+const mocks = vi.hoisted(() => ({ account: vi.fn(), message: vi.fn(), evaluate: vi.fn(), write: vi.fn(), trash: vi.fn(), modify: vi.fn(), correction: vi.fn() }));+vi.mock('./messageAccounts.js', () => ({ getAccount: mocks.account }));+vi.mock('./messageSync.js', () => ({ getMessage: mocks.message, removeMessageFromCache: mocks.write }));+vi.mock('./messagePlaywrightSync.js', () => ({ findOrOpenPage: async () => ({}), getPages: async () => [], isAuthPage: () => false, evaluateOnPage: mocks.evaluate }));+vi.mock('./messageTriageRules.js', () => ({ recordCorrection: mocks.correction }));+vi.mock('./googleAuth.js', () => ({ getAuthenticatedClient: async () => ({}) }));+vi.mock('@googleapis/gmail', () => ({ gmail: () => ({ users: { messages: { trash: mocks.trash, modify: mocks.modify } } }) }));+import { executeAction } from './messageActions.js';+const accountId = '11111111-1111-1111-1111-111111111111';+const message = { id: 'requested', subject: 'Status update', from: { name: 'Example Sender', email: '[email protected]' }, date: '2026-09-26 10:30' };++// Execute the actual CDP script against a synthetic provider DOM, including the+// production field reader, click, and confirmation loop. No mailbox/network I/O.+function mailbox(records, { remove = true, scroll = false, missingControl = false } = {}) {+ const attr = values => ({ getAttribute: name => values[name] ?? null });+ const span = (text, title) => ({ ...attr({ title }), textContent: text });+ const list = { isConnected: true, parentElement: null, scrollHeight: scroll ? 100 : 0, clientHeight: 0 };+ const clicked = [];+ let visible;+ visible = records.map((record, index) => {+ const row = {+ ...attr({ 'data-itemid': record.providerRowId, 'data-legacy-message-id': record.providerRowId }),+ isConnected: true, matches: () => !!record.providerRowId,+ querySelector(selector) {+ if (selector === 'div[aria-label="Select a conversation"] > span[aria-label]') return attr({ 'aria-label': record.from?.name });+ if (selector === 'div[aria-label="Select a conversation"]') return { parentElement: { nextElementSibling: { children: [+ { querySelector: () => attr({ title: record.from?.email }) },+ { querySelectorAll: () => [span(record.subject), span(record.date, record.date)] }, span('Preview')+ ] } } };+ if (selector === '[email]') return { ...attr({ email: record.from?.email, name: record.from?.name }), textContent: record.from?.name };+ if (selector === 'td.xW [title]') return attr({ title: record.date });+ if (selector === '.bog') return span(record.subject);+ return null;+ },+ querySelectorAll: () => missingControl ? [] : ['Archive', 'Delete'].map(label => ({ ...attr({ 'aria-label': label }), click() { clicked.push({ index, label }); if (remove) visible = visible.filter(r => r !== row); } }))+ };+ return row;+ });+ list.querySelectorAll = () => visible;+ mocks.evaluate.mockImplementation((_page, script) => runInNewContext(script, {+ document: { querySelector: () => list }, location: { href: 'https://example.com/inbox' }, setTimeout: callback => callback()+ }));+ return clicked;+}+beforeEach(() => { vi.clearAllMocks(); mocks.message.mockResolvedValue({ ...message }); mocks.correction.mockResolvedValue(undefined); });+for (const provider of ['gmail', 'outlook']) describe(`${provider} browser identity`, () => {+ beforeEach(() => mocks.account.mockResolvedValue({ type: provider }));+ it('selects the stable ID despite duplicate blank subjects and removes only its cache record', async () => {+ mocks.message.mockResolvedValue({ ...message, subject: '', providerRowId: 'second' });+ const clicked = mailbox([{ ...message, subject: '', providerRowId: 'first' }, { ...message, subject: '', providerRowId: 'second' }]);+ expect(await executeAction(accountId, message.id, 'delete')).toMatchObject({ success: true, messageId: message.id });+ expect(clicked).toEqual([{ index: 1, label: 'Delete' }]);+ expect(mocks.write).toHaveBeenCalledWith(accountId, 'requested');+ });+ it('requires exact legacy identity instead of a subject substring or first row', async () => {+ const clicked = mailbox([{ ...message, subject: 'Re: Status update' }, { ...message, from: { ...message.from, email: '[email protected]' } }, message]);+ await executeAction(accountId, message.id, 'archive');+ expect(clicked).toEqual([{ index: 2, label: 'Archive' }]);+ });+ it.each(['duplicate', 'blank', 'missing-date', 'missing-sender', 'missing-id', 'virtualized'])('rejects %s identity without action or cache writes', async scenario => {+ const target = { ...message };+ if (scenario === 'blank') target.subject = '';+ if (scenario === 'missing-date') target.date = '';+ if (scenario === 'missing-sender') target.from = {};+ if (scenario === 'missing-id') target.providerRowId = 'absent';+ mocks.message.mockResolvedValue(target);+ const clicked = mailbox(scenario === 'duplicate' ? [target, target] : [message], { scroll: scenario === 'virtualized' });+ await expect(executeAction(accountId, message.id, 'delete')).rejects.toMatchObject({ status: 409, code: 'MESSAGE_IDENTITY_CONFLICT' });+ expect(clicked).toEqual([]); expect(mocks.write).not.toHaveBeenCalled(); expect(mocks.correction).not.toHaveBeenCalled();+ });+ it('keeps cache when the row remains or CDP returns no confirmation', async () => {+ mailbox([message], { remove: false });+ await expect(executeAction(accountId, message.id, 'archive')).rejects.toMatchObject({ code: 'MESSAGE_ACTION_UNCONFIRMED' });+ mocks.evaluate.mockResolvedValue(null);+ await expect(executeAction(accountId, message.id, 'archive')).rejects.toMatchObject({ code: 'MESSAGE_ACTION_UNCONFIRMED' });+ expect(mocks.write).not.toHaveBeenCalled();+ });+ it('never uses a global action when the target lacks its own control', async () => {+ const clicked = mailbox([message], { missingControl: true });+ await expect(executeAction(accountId, message.id, 'delete')).rejects.toMatchObject({ code: 'MESSAGE_IDENTITY_CONFLICT' });+ expect(clicked).toEqual([]);+ });+});+it('preserves Gmail API-by-ID archive and delete without browser calls', async () => {+ mocks.account.mockResolvedValue({ type: 'gmail' }); mocks.message.mockResolvedValue({ ...message, apiId: 'api-target' });+ await executeAction(accountId, message.id, 'delete'); await executeAction(accountId, message.id, 'archive');+ expect(mocks.trash).toHaveBeenCalledWith({ userId: 'me', id: 'api-target' });+ expect(mocks.modify).toHaveBeenCalledWith({ userId: 'me', id: 'api-target', requestBody: { removeLabelIds: ['INBOX'] } });+ expect(mocks.evaluate).not.toHaveBeenCalled();+});diff --git a/server/services/messageLogging.test.js b/server/services/messageLogging.test.jsindex 330f0e5e20..21d310f68c 100644--- a/server/services/messageLogging.test.js+++ b/server/services/messageLogging.test.js@@ -125,6 +125,7 @@ describe('mailbox operational log privacy', () => {const message = seedMessage(account);doubles.evaluate.mockResolvedValueOnce({ found: false, hasListbox: true });await refreshMessage(account.id, message.id);+ doubles.evaluate.mockResolvedValueOnce({ success: true, messageId: message.id });expect(await executeAction(account.id, message.id, 'archive')).toMatchObject({ success: true });expect(await getMessage(account.id, message.id)).toBeNull();expect(output()).toContain(message.id);@@ -141,6 +142,7 @@ describe('mailbox operational log privacy', () => {const message = seedMessage(account);delete message.apiId;doubles.files.set(join('/mock/messages/cache', account.id + '.json'), JSON.stringify({ messages: [message] }));+ doubles.evaluate.mockResolvedValueOnce({ success: true, messageId: message.id });expect(await executeAction(account.id, message.id, 'delete')).toMatchObject({ success: true });expect(doubles.modify).toHaveBeenCalledOnce();expect(doubles.trash).toHaveBeenCalledOnce();diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.jsindex 8cd99c40ea..1b35a5459f 100644--- a/server/services/messagePlaywrightSync.js+++ b/server/services/messagePlaywrightSync.js@@ -1,3 +1,4 @@+import { readOutlookMessageRow } from '../lib/messageBrowserIdentity.js';import { join } from 'path';import crypto from 'crypto';import { v4 as uuidv4 } from '../lib/uuid.js';@@ -104,6 +105,7 @@ export async function syncPlaywright(account, cache, io, options = {}) {const buildMessage = (msg, extId, overrides = {}) => ({id: uuidv4(),externalId: extId,+ providerRowId: msg.providerRowId || null,threadId: null,from: { name: msg.from || '', email: msg.fromEmail || '' },to: [], cc: [],@@ -143,7 +145,7 @@ export async function syncPlaywright(account, cache, io, options = {}) {// Click into conversation to get full body + threadif (account.type === 'outlook') {- const detail = await fetchOutlookConversationDetail(page, msg.subject, msg.from);+ const detail = await fetchOutlookConversationDetail(page, msg.subject, msg.from, msg.date, msg.providerRowId);if (detail && detail.length > 0) {detailsFetched++;const threadKey = `thread-${extId}`;@@ -187,32 +189,29 @@ export async function syncPlaywright(account, cache, io, options = {}) {* > h3[aria-label^="Cc:"] (cc)* Returns an array of { from, fromEmail, to, cc, date, body } for each message in the thread.*/-async function fetchOutlookConversationDetail(page, subject, sender) {- // Find and click the row by matching subject text (not index, since Outlook virtualizes the list)+async function fetchOutlookConversationDetail(page, subject, sender, date, providerRowId) {+ // Preserve the same provider row identity when loading detail from a virtualized list.const safeSubject = JSON.stringify(subject || '');const safeSender = JSON.stringify(sender || '');const clickResult = await evaluateOnPage(page, `(async function() {const listbox = document.querySelector("[role='listbox']");if (!listbox) return { found: false, hasListbox: false };- const targetSubject = ${safeSubject}.toLowerCase();- const targetSender = ${safeSender}.toLowerCase();+ const targetSubject = ${safeSubject};+ const targetSender = ${safeSender};+ const targetDate = ${JSON.stringify(date || '')};+ const targetId = ${JSON.stringify(providerRowId || null)};+ const readRow = ${readOutlookMessageRow.toString()};const scrollContainer = listbox.closest('[role="region"]') || listbox.parentElement;function findMatch() {- const rows = listbox.querySelectorAll('[role="option"]');- let fallback = null;- for (const row of rows) {- const label = (row.getAttribute('aria-label') || '').toLowerCase();- const text = (row.innerText || '').toLowerCase();- if (targetSubject && (label.includes(targetSubject) || text.includes(targetSubject))) {- if (!targetSender || label.includes(targetSender) || text.includes(targetSender)) {- return row;- }- if (!fallback) fallback = row;- }- }- return fallback;+ const matches = [...listbox.querySelectorAll('[role="option"]')].filter(row => {+ const data = readRow(row);+ if (targetId) return data.providerRowId === targetId;+ return targetSubject && targetSender && targetDate+ && data.subject === targetSubject && data.from === targetSender && data.date === targetDate;+ });+ return matches.length === 1 ? matches[0] : null;}// Check visible rows first, then scroll to find the message@@ -362,53 +361,7 @@ function buildExtractionScript(type, sels, mode = 'unread') {const maxScroll = ${maxScrolls};const unreadOnly = ${mode === 'unread'};- function extractRow(row) {- const ariaLabel = row.getAttribute('aria-label') || '';- const isUnread = !!row.querySelector('button[aria-label="Mark as read"]');- const isPinned = !!row.querySelector('button[aria-label*="Unpin"]');- const isFlagged = !!row.querySelector('button[aria-label*="Unflag"]');- const isReplied = ariaLabel.includes('Replied');- const hasMeetingInvite = !!row.querySelector('button[aria-label="RSVP"]');-- const avatarSpan = row.querySelector('div[aria-label="Select a conversation"] > span[aria-label]');- const from = avatarSpan?.getAttribute('aria-label') || '';-- const checkbox = row.querySelector('div[aria-label="Select a conversation"]');- const contentArea = checkbox?.parentElement?.nextElementSibling;- const contentDivs = contentArea ? Array.from(contentArea.children) : [];-- let subject = '', date = '', preview = '', fromEmail = '';-- if (contentDivs.length >= 3) {- const senderDiv = contentDivs[0];- const emailSpan = senderDiv?.querySelector('span[title*="@"]');- fromEmail = emailSpan?.getAttribute('title') || '';-- const subDateDiv = contentDivs[1];- const spans = subDateDiv ? Array.from(subDateDiv.querySelectorAll('span')) : [];- subject = spans[0]?.textContent?.trim() || '';- const dateSpan = spans.find(s => s.getAttribute('title')?.match(/\\d{4}/));- date = dateSpan?.getAttribute('title') || spans[spans.length - 1]?.textContent?.trim() || '';-- preview = contentDivs[2]?.textContent?.trim() || '';- } else if (contentDivs.length >= 1) {- const allSpans = contentDivs[0]?.querySelectorAll('span[title]') || [];- const spanArr = Array.from(allSpans);- const emailSpan = spanArr.find(s => (s.getAttribute('title') || '').includes('@'));- fromEmail = emailSpan?.getAttribute('title') || '';- // In compact layout: first titled span is sender, second is subject- const titledSpans = spanArr.filter(s => s.closest('[class]'));- subject = titledSpans.length > 1 ? titledSpans[titledSpans.length - 1]?.textContent?.trim() || '' : '';- // Fallback: find span whose text differs from sender name- if (!subject) {- subject = spanArr.find(s => s.textContent?.trim() && s.textContent.trim() !== from && !(s.getAttribute('title') || '').includes('@'))?.textContent?.trim() || '';- }- const dateMatch = ariaLabel.match(/(\\d{1,2}\\/\\d{1,2}(?:\\/\\d{2,4})?)/);- date = dateMatch?.[1] || '';- }-- return { from, fromEmail, subject, date, preview, isUnread, isPinned, isFlagged, isReplied, hasMeetingInvite };- }+ const extractRow = ${readOutlookMessageRow.toString()};function scrapeVisible() {const rows = listbox.querySelectorAll('[role="option"]');@@ -417,7 +370,7 @@ function buildExtractionScript(type, sels, mode = 'unread') {if (seen.size >= maxMsg) break;const data = extractRow(row);if (!data.from && !data.subject) continue;- const key = data.from + '|' + data.subject + '|' + data.date;+ const key = data.providerRowId || data.from + '|' + data.subject + '|' + data.date;if (seen.has(key)) continue;if (unreadOnly && !data.isUnread) continue;seen.set(key, data);@@ -491,7 +444,7 @@ export async function refreshMessageDetail(account, message) {}console.log(`📧 Refresh: clicking into ${message.id}`);- const detail = await fetchOutlookConversationDetail(page, message.subject, message.from?.name);+ const detail = await fetchOutlookConversationDetail(page, message.subject, message.from?.name, message.date, message.providerRowId);if (!detail) {console.log(`📧 Refresh: click/extraction failed for ${message.id}`);} else {diff --git a/server/services/messagePlaywrightSync.test.js b/server/services/messagePlaywrightSync.test.jsindex 92fe68eee2..326eeb3b33 100644--- a/server/services/messagePlaywrightSync.test.js+++ b/server/services/messagePlaywrightSync.test.js@@ -12,7 +12,7 @@ vi.mock('../lib/fileUtils.js', async () => {return { ...actual, tryReadFile };});-const { testSelectors } = await import('./messagePlaywrightSync.js');+const { testSelectors, syncPlaywright } = await import('./messagePlaywrightSync.js');const OPEN_PAGE = { url: 'https://outlook.office.com/mail/', webSocketDebuggerUrl: 'ws://x' };@@ -93,3 +93,14 @@ describe('testSelectors', () => {expect(result.results.messageRow.matches).toBe(0);});});++it('retains the ingested provider row ID when detail is unavailable', async () => {+ findOrOpenPage.mockResolvedValue(OPEN_PAGE);+ isAuthPage.mockReturnValue(false);+ tryReadFile.mockResolvedValue('{}');+ evaluateOnPage.mockReset();+ evaluateOnPage.mockResolvedValueOnce([{ providerRowId: 'stable-row', from: 'Example Sender', subject: 'Example subject', date: '2026-09-26' }]);+ evaluateOnPage.mockResolvedValue({ found: false });+ const result = await syncPlaywright({ id: 'example-account', type: 'outlook' }, { messages: [] });+ expect(result.messages).toEqual([expect.objectContaining({ providerRowId: 'stable-row', subject: 'Example subject' })]);+});diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 71d50f9922..3115d78fdf 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -119,6 +119,16 @@ export async function getMessages(options = {}) {return aggregatePagedMessages(caches, { search, unevaluatedOnly, messageIds, limit, offset });}+/** Remove only a confirmed action target, serialized with sync/refresh writes. */+export async function removeMessageFromCache(accountId, messageId) {+ if (!UUID_RE.test(accountId)) throw new Error('Invalid accountId');+ return queueAccountWrite(accountId, async () => {+ const cache = await loadCache(accountId);+ cache.messages = cache.messages.filter(message => message.id !== messageId);+ await saveCache(accountId, cache);+ });+}+export async function deleteCache(accountId) {if (!UUID_RE.test(accountId)) return;// Drain cache writers before erasing; a writer already in flight must not@@ -211,14 +221,21 @@ export async function syncAccount(accountId, io, options = {}) {const sendAsAliases = Array.isArray(providerResult) ? null : (providerResult?.sendAsAliases ?? null);// Deduplicate by externalId; update flags and body on existing messages- const existingMap = new Map(cache.messages.filter(m => m.externalId).map(m => [m.externalId, m]));+ const existingMap = new Map(cache.messages.filter(m => m.externalId).map(m => [m.providerRowId ? `${m.externalId}|${m.providerRowId}` : m.externalId, m]));const uniqueNew = [];for (const msg of newMessages) {- if (!msg.externalId || !existingMap.has(msg.externalId)) {+ const identityKey = msg.providerRowId ? `${msg.externalId}|${msg.providerRowId}` : msg.externalId;+ // Upgrade a legacy identity only when both sides are unique. Duplicate+ // summaries must never move an existing local ID to a different row.+ const legacy = msg.providerRowId && existingMap.get(msg.externalId);+ const canUpgrade = legacy && cache.messages.filter(m => m.externalId === msg.externalId).length === 1+ && newMessages.filter(m => m.externalId === msg.externalId).length === 1;+ const existing = existingMap.get(identityKey) || (canUpgrade ? legacy : null);+ if (!msg.externalId || !existing) {uniqueNew.push(msg);} else {- // Update flags on existing message- const existing = existingMap.get(msg.externalId);+ // Update flags and provider identity on existing message+ if (msg.providerRowId) existing.providerRowId = msg.providerRowId;if (msg.isUnread !== undefined) existing.isUnread = msg.isUnread;if (msg.isRead !== undefined) existing.isRead = msg.isRead;if (msg.isPinned !== undefined) existing.isPinned = msg.isPinned;diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.jsindex 697680755b..fecce30245 100644--- a/server/services/messageSync.test.js+++ b/server/services/messageSync.test.js@@ -100,7 +100,7 @@ vi.mock('./userTimezone.js', () => ({import { readdir, unlink } from 'fs/promises';import { tryReadFile as readFile, atomicWrite } from '../lib/fileUtils.js';-import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage, refreshMessages, updateMessageEvaluations, logMessageTouchpoints, aggregatePagedMessages } from './messageSync.js';+import { getMessages, getMessage, removeMessageFromCache, syncAccount, deleteCache, getSyncStatus, refreshMessage, refreshMessages, updateMessageEvaluations, logMessageTouchpoints, aggregatePagedMessages } from './messageSync.js';import { autoLogTouchpoints } from './tribe.js';import { getAccount, updateSyncStatus, markSentIngested } from './messageAccounts.js';import { syncGmail } from './messageGmailSync.js';@@ -531,6 +531,12 @@ describe('syncAccount', () => {expect(syncPlaywright).toHaveBeenCalled();});+ it('removes only the confirmed action target from the current cache', async () => {+ readFile.mockResolvedValue(JSON.stringify({ syncCursor: 'keep-cursor', messages: [{ id: 'target' }, { id: 'other' }] }));+ await removeMessageFromCache(VALID_UUID, 'target');+ expect(atomicWrite.mock.calls[0][1]).toEqual({ syncCursor: 'keep-cursor', messages: [{ id: 'other' }] });+ });+it('should deduplicate by externalId during sync', async () => {getAccount.mockResolvedValue({ id: VALID_UUID, name: 'Gmail', type: 'gmail', enabled: true });const existingCache = {@@ -554,6 +560,28 @@ describe('syncAccount', () => {expect(savedData.messages).toHaveLength(2);});+ it('keeps provider row identities separate when summary hashes collide', async () => {+ getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook', enabled: true });+ readFile.mockResolvedValue(JSON.stringify({ messages: [{ id: 'local-first', externalId: 'same-summary', providerRowId: 'first' }] }));+ syncPlaywright.mockResolvedValue({ status: 'success', messages: [+ { id: 'incoming-first', externalId: 'same-summary', providerRowId: 'first' },+ { id: 'incoming-second', externalId: 'same-summary', providerRowId: 'second' }+ ] });+ await syncAccount(VALID_UUID, mockIo);+ expect(atomicWrite.mock.calls[0][1].messages).toEqual([+ expect.objectContaining({ id: 'local-first', providerRowId: 'first' }),+ expect.objectContaining({ id: 'incoming-second', providerRowId: 'second' })+ ]);+ });++ it('upgrades a unique legacy cache entry with its ingested provider row ID', async () => {+ getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook', enabled: true });+ readFile.mockResolvedValue(JSON.stringify({ messages: [{ id: 'legacy-local', externalId: 'summary' }] }));+ syncPlaywright.mockResolvedValue({ status: 'success', messages: [{ id: 'new-local', externalId: 'summary', providerRowId: 'stable-row' }] });+ await syncAccount(VALID_UUID, mockIo);+ expect(atomicWrite.mock.calls[0][1].messages).toEqual([expect.objectContaining({ id: 'legacy-local', providerRowId: 'stable-row' })]);+ });+it('should keep messages without externalId (no dedup for those)', async () => {getAccount.mockResolvedValue({ id: VALID_UUID, name: 'Gmail', type: 'gmail', enabled: true });readFile.mockResolvedValue(JSON.stringify({ messages: [{ id: 'msg-1' }] }));