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
feat: deliver approved Outlook and Teams drafts through the signed-in browser tab (#9967)
[._.]/ Adam Eivy636f1d9a14c5
diff --git a/client/src/components/messages/DraftsTab.jsx b/client/src/components/messages/DraftsTab.jsxindex 345fe65e83..00b99f3503 100644--- a/client/src/components/messages/DraftsTab.jsx+++ b/client/src/components/messages/DraftsTab.jsx@@ -32,9 +32,9 @@ function DeliveryReconciliation({ draft, onReconciled }) {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.+ Delivery is unknown because this send was interrupted or the provider never+ confirmed it. 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"@@ -103,7 +103,12 @@ export default function DraftsTab({ accounts }) {sendingRef.current.delete(id);setSendingIds(new Set(sendingRef.current));});- if (!result || result.success === false) return;+ if (!result || result.success === false) {+ // The server has already moved the draft out of "approved" — to failed, or to+ // delivery unknown when the provider never confirmed — so show that state now.+ if (!result) fetchDrafts();+ return;+ }setDrafts(prev => prev.map(d => d.id === id ? { ...d, status: 'sent' } : d));toast.success('Message sent');};@@ -123,8 +128,7 @@ export default function DraftsTab({ accounts }) {};const isCopyOnly = draft => draft.sendVia === 'review' ||- accounts.find(account => account.id === draft.accountId)?.canSend === false ||- draft.sendVia === 'playwright';+ accounts.find(account => account.id === draft.accountId)?.canSend === false;const statusColors = {draft: 'bg-gray-700 text-gray-300',diff --git a/client/src/components/messages/DraftsTab.test.jsx b/client/src/components/messages/DraftsTab.test.jsxindex 9cb73f06b3..8e538f8bf8 100644--- a/client/src/components/messages/DraftsTab.test.jsx+++ b/client/src/components/messages/DraftsTab.test.jsx@@ -75,7 +75,8 @@ describe('DraftsTab pending sends', () => {fireEvent.click(first);await waitFor(() => expect(screen.getAllByRole('button', { name: 'Send' })).toHaveLength(1));expect(screen.getByText('sent')).toBeInTheDocument();- expect(api.getMessageDrafts).toHaveBeenCalledTimes(1);+ // The initial load plus the one reload after the failed send; the successful retry applies its response locally.+ expect(api.getMessageDrafts).toHaveBeenCalledTimes(2);});});@@ -133,6 +134,34 @@ describe('DraftsTab interrupted delivery', () => {});describe('DraftsTab send capabilities', () => {+ it('offers approval and send for browser-delivered accounts the server reports as sendable', async () => {+ api.getMessageDrafts.mockResolvedValue([+ { id: 'outlook-draft', status: 'draft', accountId: 'outlook', sendVia: 'playwright', body: 'Outlook text' },+ { id: 'teams-draft', status: 'approved', accountId: 'teams', sendVia: 'playwright', body: 'Teams text' }+ ]);+ render(<DraftsTab accounts={[+ { id: 'outlook', name: 'Outlook', canSend: true },+ { id: 'teams', name: 'Teams', canSend: true }+ ]} />);+ expect(await screen.findByRole('button', { name: 'Approve' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Send' })).toBeInTheDocument();+ expect(screen.queryByText(/Sending from this account isn't supported yet/)).not.toBeInTheDocument();+ });++ it('reloads drafts after a failed send so a provider-unconfirmed draft shows its reconciliation state', async () => {+ api.getMessageDrafts.mockResolvedValueOnce([+ { id: 'd1', status: 'approved', accountId: 'outlook', sendVia: 'playwright', body: 'Outlook text' }+ ]);+ api.getMessageDrafts.mockResolvedValueOnce([+ { id: 'd1', status: 'delivery_unknown', accountId: 'outlook', sendVia: 'playwright', sendAttemptId: 'attempt-1', body: 'Outlook text' }+ ]);+ api.sendMessageDraft.mockRejectedValueOnce(new Error('Example provider did not confirm delivery'));+ render(<DraftsTab accounts={[{ id: 'outlook', name: 'Outlook', canSend: true }]} />);+ fireEvent.click(await screen.findByRole('button', { name: 'Send' }));+ expect(await screen.findByText(/the provider never\s+confirmed it/)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Send' })).not.toBeInTheDocument();+ });+it('offers copy instead of approval/send for Outlook and Teams while Gmail still sends', async () => {api.getMessageDrafts.mockResolvedValue([{ id: 'outlook-draft', status: 'draft', accountId: 'outlook', sendVia: 'playwright', body: 'Outlook text' },diff --git a/client/src/components/privacy/PrivacyBrokersTab.test.jsx b/client/src/components/privacy/PrivacyBrokersTab.test.jsxindex 724ee17683..c2676421d3 100644--- a/client/src/components/privacy/PrivacyBrokersTab.test.jsx+++ b/client/src/components/privacy/PrivacyBrokersTab.test.jsx@@ -60,11 +60,11 @@ const renderTab = (props = {}) => render(<MemoryRouter initialEntries={['/privacdescribe('PrivacyBrokersTab', () => {it('shows the missing send account next action after an opt-out pass', async () => {const toast = (await import('../ui/Toast')).default;- apiMod.runPrivacyOptOut.mockResolvedValueOnce({ submitted: [], skipped: 1, nextActions: ['Connect a Gmail account to send opt-out emails'] });+ apiMod.runPrivacyOptOut.mockResolvedValueOnce({ submitted: [], skipped: 1, nextActions: ['Connect a Gmail or Outlook account to send opt-out emails'] });renderTab();await screen.findByText('Spokeo');fireEvent.click(screen.getByRole('button', { name: /Run opt-out pass/i }));- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Connect a Gmail account to send opt-out emails'));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Connect a Gmail or Outlook account to send opt-out emails'));});beforeEach(() => {diff --git a/docs/README.md b/docs/README.mdindex e1a24b0eec..fa05bc8240 100644--- a/docs/README.md+++ b/docs/README.md@@ -64,7 +64,7 @@ Knowledge: [brain-system](./features/brain-system.md) · [untrusted messages andCreate: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [Eidoverse Worlds integration](./features/eidoverse.md) · [Eidoverse music-video renderer](./EIDOVERSE_VIDEO.md) · [OpenWorld historical reference](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md) · [video-render-batches](./features/video-render-batches.md) · [video-upscale](./features/video-upscale.md)-Comms & voice: [beeper](./features/beeper.md) · [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md) ([Jev feasibility](./research/2026-09-30-jev-voice-feasibility.md))+Comms & voice: [beeper](./features/beeper.md) · [messages-browser-send](./features/messages-browser-send.md) · [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md) ([Jev feasibility](./research/2026-09-30-jev-voice-feasibility.md))## Point-in-time recordsdiff --git a/docs/features/messages-browser-send.md b/docs/features/messages-browser-send.mdnew file mode 100644index 0000000000..197e6725b3--- /dev/null+++ b/docs/features/messages-browser-send.md@@ -0,0 +1,51 @@+# Outlook and Teams draft delivery++Approved drafts for Outlook and Teams accounts are delivered by driving the web UI in the PortOS browser tab you are already signed into. Gmail still sends through its API. This page is the contract for the browser path; the code is `server/lib/messageBrowserCompose.js` (pure planning, scripts and judging) and `sendPlaywright` in `server/services/messagePlaywrightSync.js` (the I/O).++## Live validation status++**Not validated against a real mailbox or Teams tenant.** The selector defaults in `COMPOSE_SELECTOR_DEFAULTS` are best-effort descriptions of the providers' current web UIs, written without access to a controlled test account. The in-page scripts were exercised against a synthetic DOM and the orchestration against scripted browser results, which proves the logic and the failure handling but not that Outlook or Teams still match the selectors.++The design makes an unvalidated selector fail safe rather than send wrongly:++- a control that does not match stops the send **before** the click (`PROVIDER_CONTROL_MISSING`, nothing sent, draft may be re-approved);+- an acknowledgement signal that does not match leaves the delivery **unconfirmed** (`DELIVERY_UNKNOWN`), which routes to the existing reconciliation flow instead of reporting success.++Until someone validates a send against a controlled account, expect some sends to end as "delivery unknown" even though they went through. To validate: open Outlook or Teams in the PortOS browser, send a draft to an address you control, and adjust the selector keys (below) until it reports confirmed.++## Guarantees++1. **Approval is preserved on refusals.** Whether a draft can be delivered at all, to whom, and which message it replies to is decided before the draft is claimed (`planDelivery`, called from `sendDraft`). The reply target is looked up in the draft's **own** account cache, so a draft cannot answer another account's thread.+2. **Exactly one submit click.** Every phase before the click (identity probe, open compose, fill, verify) is side-effect free. The send runs under a per-provider lock so two drafts never interleave in one tab.+3. **Success needs a positive provider signal.** After the click, a delivery is confirmed only when the compose surface closed **and** a fresh acknowledgement appeared: new live-region text matching `sendAckPattern` for Outlook, or the sent message rendered in the conversation for Teams. Anything else — a lost connection, a timeout, a closed window with no acknowledgement — is `delivery_unknown`.+4. **Ambiguity is never retried.** `delivery_unknown` is the same state a crash during a send leaves. The draft cannot be re-sent or re-approved until you check Sent Items or the conversation and record the outcome (Drafts → Confirm sent / Confirm not sent). A provider refusal with the compose window still open is a definite failure (`PROVIDER_REFUSED`).+5. **Recipients are verified, not assumed.** Before the click the page's recipients must equal the approved ones exactly — no extras, none missing — and the typed text must read back. A Teams recipient must resolve to a picker entry that names the exact address.+6. **Account identity.** One tab is one signed-in identity. A visible identity that is not the account's is refused. When several enabled accounts share a provider, an identity the page does not reveal is also refused, so a draft cannot leave from the wrong mailbox.++Not supported: reply-all, attachments, Teams channels and meetings, and Cc on an Outlook reply (a reply goes to the recipients Outlook prefilled, and any difference from the approved list is refused). Cc on a Teams chat is refused up front. A new Outlook message needs a subject; a reply keeps the subject Outlook wrote.++## Failure codes++| Code | Meaning | Draft after |+| --- | --- | --- |+| `PROVIDER_TAB_UNAVAILABLE` | No signed-in tab open, or it did not respond | `failed` (re-approvable) |+| `PROVIDER_LOGIN_REQUIRED` | The tab is on a sign-in page | `failed` |+| `PROVIDER_CONTROL_MISSING` | A compose control no longer matches a selector | `failed` |+| `PROVIDER_COMPOSE_BUSY` | A compose window is already open in the tab | `failed` |+| `RECIPIENT_MISMATCH` / `RECIPIENT_UNRESOLVED` | The page's recipients differ from the approved ones | `failed` |+| `ACCOUNT_IDENTITY_MISMATCH` / `ACCOUNT_IDENTITY_UNVERIFIED` | The tab may be a different account | `failed` |+| `PROVIDER_REFUSED` | The provider rejected the message after Send | `failed` |+| `DELIVERY_UNKNOWN` | Send was clicked; no confirmation | `delivery_unknown` (reconcile) |+| `DRAFT_NOT_DELIVERABLE`, `REPLY_TARGET_NOT_FOUND`, `THREAD_MISMATCH` | Refused before claiming | `approved` (unchanged) |++## Overriding selectors++`data/messages/selectors.json` is keyed by provider (`outlook`, `teams`). Any key in `COMPOSE_SELECTOR_DEFAULTS` may be overridden there, plus `sendAckPattern` and `sendRefusalPattern` (case-insensitive regex source). Unknown keys and invalid patterns are ignored. The existing selector test (Messages → selectors) counts matches for every key in the file, so a compose key that only exists while a compose window is open will read as unmatched on an idle page.++## Privacy email lanes++The privacy opt-out and "update my records" email drafts use `pickEmailSenderAccount` (`server/lib/messageTransport.js`): an enabled, sendable, email-capable account, preferring a provider API (Gmail) over browser automation, and each draft carries that account's real `sendVia`. A Teams chat reaches a person, not a mailbox, so it is never chosen.++## Security posture++The automation uses only the browser the instance already runs and the sign-in you established; nothing is exposed beyond the private network, and no credential is read, stored or sent. Recipient addresses are not written to logs.diff --git a/server/lib/README.md b/server/lib/README.mdindex c2724dbf51..ae28fd4e65 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -794,6 +794,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. |+| `messageBrowserCompose.js` | Confirmed Outlook/Teams draft delivery through the authenticated browser tab, as pure helpers: `planDelivery` (deliverability + intended recipients/thread, run BEFORE a draft is claimed), `buildComposePhaseScript` (probe/open/fill/submit/discard CDP scripts, args as JSON), `classifySendOutcome` (confirmed only on a closed compose surface plus a fresh provider signal; anything else after the single submit click is `unknown`), `recipientsMatch`, `checkAccountIdentity`, and overridable `COMPOSE_SELECTOR_DEFAULTS`/`resolveComposeConfig`. Defaults are unvalidated against a live mailbox. |+| `messageTransport.js` | `MESSAGE_ACCOUNT_TRANSPORT` — the one table of what each message-account type delivers (`sendVia`, email-capable): `sendViaForAccountType`, `accountTypeCanSend`, and `pickEmailSenderAccount` (privacy email lanes prefer an API transport, never pick a Teams chat). || `defaultRequestBody.js` | Express middleware that defaults an undefined `req.body` (Express 5 leaves it unset for body-less requests) to `{}` so handlers do not crash with a TypeError 500. || `databaseAuthority.js` | `createDatabaseAuthority(dataDir?)` durably records which backend a verified cutover released admission to and which it retired; `assertDatabasePoolAuthority(pool)` refuses a process whose pool still names the retired source (enforced at boot and on every pooled operation). |diff --git a/server/lib/index.js b/server/lib/index.jsindex cfc2e53f67..2e76949081 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -774,6 +774,8 @@ export * from './launchVideoValidation.js';export * from './styleSourcePrompt.js';export * from './messageBrowserIdentity.js';+export * from './messageBrowserCompose.js';+export * from './messageTransport.js';export * from './databaseAuthority.js';diff --git a/server/lib/messageBrowserCompose.js b/server/lib/messageBrowserCompose.jsnew file mode 100644index 0000000000..9742023c18--- /dev/null+++ b/server/lib/messageBrowserCompose.js@@ -0,0 +1,474 @@+// Confirmed draft delivery through the authenticated Outlook / Teams browser tab.+//+// Everything here is pure: it plans a delivery, builds the scripts the CDP page+// evaluates, and judges what the page reported. The I/O (finding the tab, running+// each phase, serializing sends) lives in `services/messagePlaywrightSync.js`.+//+// A browser submit has no idempotency key, so the contract is asymmetric:+// - every phase BEFORE the single submit click is side-effect free (a failure+// there is a definite "not sent" and the draft may be re-approved), and+// - once the click has happened, anything short of a positive provider signal+// is "delivery unknown" — never success, never an automatic retry.+import { readOutlookMessageRow } from './messageBrowserIdentity.js';++// Best-effort defaults for each provider's web UI. They are NOT validated against+// a live mailbox in this repository — the DOM changes without notice — so every+// key can be overridden per provider in the Messages selectors file+// (`data/messages/selectors.json`). A selector that stops matching degrades to a+// definite "control missing" failure before anything is sent.+export const COMPOSE_SELECTOR_DEFAULTS = Object.freeze({+ outlook: Object.freeze({+ accountIdentity: '#O365_MainLink_Me, button[aria-label^="Account manager"]',+ newMail: 'button[aria-label="New mail"]',+ replyButton: 'button[aria-label="Reply"]',+ composeBody: '[role="textbox"][aria-label="Message body"]',+ composeSend: 'button[aria-label="Send"]',+ composeDiscard: 'button[aria-label="Discard"]',+ composeSubject: 'input[aria-label="Add a subject"]',+ toField: '[aria-label="To"]',+ ccField: '[aria-label="Cc"]',+ showCc: 'button[aria-label="Cc"]'+ }),+ teams: Object.freeze({+ accountIdentity: 'button[aria-label^="Your profile"], [data-tid="me-control-avatar"]',+ newChat: 'button[aria-label="New chat"]',+ recipientInput: 'input[aria-label^="To"]',+ recipientSuggestion: '[role="option"]',+ composeBox: '[role="textbox"][aria-label^="Type a"]',+ composeSend: 'button[aria-label="Send"]',+ sentMessage: '[data-tid="chat-pane-message"]'+ })+});++// What the page says when a send went through / was refused. Matched against NEW+// live-region text only (anything already on screen before the click is ignored).+export const SEND_ACK_PATTERN = '(^|\\b)(message sent|your message (was|has been) sent|sent successfully)\\b';+export const SEND_REFUSAL_PATTERN = "couldn.?t send|could not send|failed to send|unable to send|didn.?t send|wasn.?t sent|not sent|try again";++export const SUBMIT_OBSERVE_MS = 20000;+// Must outlast the in-page observation window or a slow-but-successful send reads as a lost connection.+export const SUBMIT_EVALUATE_TIMEOUT_MS = SUBMIT_OBSERVE_MS + 10000;++/** Merge the stored per-provider overrides over the defaults. Unknown keys are ignored. */+export function resolveComposeConfig(provider, stored) {+ const defaults = COMPOSE_SELECTOR_DEFAULTS[provider];+ if (!defaults) return null;+ const override = key => (typeof stored?.[key] === 'string' && stored[key].trim() ? stored[key].trim() : null);+ const validPattern = key => {+ const candidate = override(key);+ if (!candidate) return null;+ try { new RegExp(candidate, 'i'); return candidate; } catch { return null; }+ };+ const sels = Object.fromEntries(Object.entries(defaults).map(([key, value]) => [key, override(key) ?? value]));+ return {+ sels,+ ackPattern: validPattern('sendAckPattern') ?? SEND_ACK_PATTERN,+ refusalPattern: validPattern('sendRefusalPattern') ?? SEND_REFUSAL_PATTERN+ };+}++const EMAIL_RE = /^[^\s<>@,;"]+@[^\s<>@,;"]+\.[^\s<>@,;"]+$/;++/** `Alice <[email protected]>` / `[email protected]` → lowercase address, else null. */+function normalizeEmail(value) {+ if (typeof value !== 'string') return null;+ const angle = value.match(/<([^<>]+)>\s*$/);+ const candidate = (angle ? angle[1] : value).trim().toLowerCase();+ return EMAIL_RE.test(candidate) ? candidate : null;+}++const asList = value => (Array.isArray(value) ? value : value ? [value] : []);+const unique = list => [...new Set(list)];++/**+ * Decide whether a browser-send draft can be delivered at all, and to whom —+ * BEFORE the draft is claimed, so a refusal leaves its approval intact.+ * `replyTarget` is the cached message the draft answers, already scoped to the+ * draft's own account by the caller. Returns `{ ok: true, plan }` or+ * `{ ok: false, status, code, error }`.+ */+export function planDelivery(accountType, draft, replyTarget = null) {+ const refuse = (status, code, error) => ({ ok: false, status, code, error });+ const isTeams = accountType === 'teams';+ if (!COMPOSE_SELECTOR_DEFAULTS[accountType]) {+ return refuse(501, 'SEND_NOT_SUPPORTED', "Sending from this account isn't supported yet — copy the draft");+ }+ const body = typeof draft.body === 'string' ? draft.body : '';+ if (!body.trim()) return refuse(400, 'DRAFT_NOT_DELIVERABLE', 'Draft has no message body');++ const to = asList(draft.to).map(normalizeEmail);+ const cc = asList(draft.cc).map(normalizeEmail);+ if (to.includes(null) || cc.includes(null)) {+ return refuse(400, 'DRAFT_NOT_DELIVERABLE', 'Recipients must be plain email addresses');+ }++ const isReply = Boolean(draft.replyToMessageId);+ if (isReply) {+ if (!replyTarget) return refuse(409, 'REPLY_TARGET_NOT_FOUND', 'The message this draft replies to is no longer in this account — sync and retry');+ if (draft.threadId && replyTarget.threadId && draft.threadId !== replyTarget.threadId) {+ return refuse(409, 'THREAD_MISMATCH', 'This draft does not belong to the thread of the message it replies to');+ }+ // Outlook replies are located by the provider's row id; a title match is a guess about whose mail to answer.+ if (!isTeams && !replyTarget.providerRowId) {+ return refuse(409, 'REPLY_TARGET_UNIDENTIFIABLE', 'This message has no provider identity yet — sync the account and retry');+ }+ }++ // An explicit recipient list wins; a bare reply answers the sender it was written for.+ const answered = isReply ? normalizeEmail(replyTarget.from?.email) : null;+ const recipients = unique(to.length ? to : answered ? [answered] : []);+ if (!recipients.length) return refuse(400, 'DRAFT_NOT_DELIVERABLE', 'Add a recipient email address before sending');+ if (isTeams && cc.length) return refuse(400, 'DRAFT_NOT_DELIVERABLE', 'Teams chats have no Cc — remove the Cc recipients');++ // A new Outlook message without a subject raises a confirmation dialog, which is+ // one more ambiguous step; a reply keeps the subject the provider already wrote.+ const subject = typeof draft.subject === 'string' ? draft.subject.trim() : '';+ if (!isTeams && !isReply && !subject) return refuse(400, 'DRAFT_NOT_DELIVERABLE', 'Add a subject before sending');++ return {+ ok: true,+ plan: {+ to: recipients,+ cc: unique(cc),+ subject,+ body,+ reply: isReply && !isTeams+ ? { providerRowId: replyTarget.providerRowId, subject: replyTarget.subject || '', from: replyTarget.from?.name || '' }+ : null+ }+ };+}++const sameSet = (a, b) => a.length === b.length && a.every(item => b.includes(item));++/** The recipients the page shows must be exactly the planned ones — no extras, none missing. */+export function recipientsMatch(plan, shown) {+ const to = unique(asList(shown?.to).map(normalizeEmail).filter(Boolean));+ const cc = unique(asList(shown?.cc).map(normalizeEmail).filter(Boolean));+ return sameSet(to, plan.to) && sameSet(cc, plan.cc);+}++/**+ * One tab serves one signed-in identity, but several accounts of a type can exist.+ * A visible identity that is not this account's is a definite refusal; an identity+ * the page does not reveal is only acceptable when no other account could be the+ * one signed in (`required` = more than one enabled account of this type).+ */+export function checkAccountIdentity({ expected, observed, required }) {+ const want = normalizeEmail(expected);+ const seen = asList(observed?.emails).map(normalizeEmail).filter(Boolean);+ if (want && seen.length) {+ return seen.includes(want) ? { ok: true } : { ok: false, code: 'ACCOUNT_IDENTITY_MISMATCH' };+ }+ return required ? { ok: false, code: 'ACCOUNT_IDENTITY_UNVERIFIED' } : { ok: true };+}++/**+ * Judge what the submit phase reported. `observed` is the page's return value, or+ * null when the evaluation was lost (timeout, closed socket, in-page exception) —+ * which cannot be told apart from "the click already happened".+ * not_sent — the page explicitly says it never clicked submit+ * confirmed — the compose surface closed AND a fresh provider signal appeared+ * refused — the provider rejected it and the compose surface is still open+ * unknown — everything else after a click+ */+export function classifySendOutcome(observed) {+ if (!observed || typeof observed !== 'object') return { outcome: 'unknown' };+ if (observed.submitClicked === false) {+ return { outcome: 'not_sent', code: observed.code || 'CONTROL_MISSING', control: observed.control };+ }+ if (observed.submitClicked !== true) return { outcome: 'unknown' };+ if (observed.refusalSeen === true && observed.composeClosed !== true) return { outcome: 'refused' };+ if (observed.ackSeen === true && observed.composeClosed === true && observed.refusalSeen !== true) {+ return { outcome: 'confirmed' };+ }+ return { outcome: 'unknown' };+}++export const COMPOSE_PROVIDER_LABEL = Object.freeze({ outlook: 'Outlook', teams: 'Teams' });++/** Map a pre-submit in-page failure to the structured failure the sender returns. */+export function describeComposeFailure(provider, failure) {+ const label = COMPOSE_PROVIDER_LABEL[provider] || provider;+ // A lost evaluation (no result at all) says nothing about which control failed.+ if (!failure) return { status: 502, code: 'PROVIDER_TAB_UNAVAILABLE', error: `The ${label} tab did not respond — nothing was sent` };+ const code = failure.code;+ if (code === 'COMPOSE_BUSY') {+ return { status: 409, code: 'PROVIDER_COMPOSE_BUSY', error: `A ${label} compose window is already open in the browser — send or close it, then retry` };+ }+ if (code === 'REPLY_TARGET_UNLOCATED') {+ return { status: 409, code: 'REPLY_TARGET_UNLOCATED', error: `The original message is not visible in the open ${label} mailbox — open its folder, sync, and retry` };+ }+ if (code === 'RECIPIENT_UNRESOLVED') {+ return { status: 409, code: 'RECIPIENT_UNRESOLVED', error: `${label} could not resolve every recipient — nothing was sent` };+ }+ if (code === 'RECIPIENT_MISMATCH') {+ return { status: 409, code: 'RECIPIENT_MISMATCH', error: `${label} recipients do not match the approved draft — nothing was sent` };+ }+ if (code === 'CONTENT_MISMATCH') {+ return { status: 502, code: 'PROVIDER_CONTENT_MISMATCH', error: `${label} did not accept the approved text — nothing was sent` };+ }+ const control = failure.control ? ` (${failure.control})` : '';+ return { status: 502, code: 'PROVIDER_CONTROL_MISSING', error: `The ${label} page is missing a compose control${control} — update the Messages selectors; nothing was sent` };+}++// ── In-page code ────────────────────────────────────────────────────────────+// Each function below is serialized with toString() and evaluated inside the+// provider tab, so it must not close over module scope: every dependency arrives+// as an argument (`args` is JSON, never interpolated as executable text).++function pageHelpers() {+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));+ const visible = el => Boolean(el) && el.isConnected && el.getClientRects().length > 0;+ const usable = el => visible(el) && !el.disabled && el.getAttribute('aria-disabled') !== 'true';+ // Exactly one usable match or nothing: an ambiguous control is never guessed at.+ const only = (scope, selector) => {+ const hits = [...scope.querySelectorAll(selector)].filter(usable);+ return hits.length === 1 ? hits[0] : null;+ };+ const waitFor = async (probe, timeoutMs = 10000) => {+ const end = Date.now() + timeoutMs;+ while (Date.now() < end) {+ const value = probe();+ if (value) return value;+ await sleep(150);+ }+ return null;+ };+ const norm = text => String(text || '').replace(/\s+/g, ' ').trim();+ const labelOf = el => [el.getAttribute('aria-label'), el.getAttribute('title'), el.innerText].filter(Boolean).join(' ');+ const emailsIn = scope => {+ const found = new Set();+ if (!scope) return [];+ const scan = text => {+ for (const match of String(text || '').match(/[^\s<>@,;"()]+@[^\s<>@,;"()]+\.[^\s<>@,;"()]+/g) || []) found.add(match.toLowerCase());+ };+ for (const el of [scope, ...scope.querySelectorAll('*')]) {+ scan(el.getAttribute('title'));+ scan(el.getAttribute('aria-label'));+ scan(el.getAttribute('data-email'));+ }+ scan(scope.innerText);+ return [...found];+ };+ const typeInto = (el, text) => {+ el.focus();+ document.execCommand('insertText', false, text);+ };+ const tagged = token => document.querySelector('[data-portos-send-token="' + token + '"]');+ return { sleep, visible, usable, only, waitFor, norm, labelOf, emailsIn, typeInto, tagged };+}++// Identity of whoever the tab is signed in as — read-only, runs before anything is touched.+async function probeIdentityInPage(args, h) {+ const el = document.querySelector(args.sels.accountIdentity);+ return { found: Boolean(el), emails: el ? h.emailsIn(el) : [] };+}++async function openComposeInPage(args, h, readRow) {+ const { provider, sels, token } = args;+ if (provider === 'outlook') {+ if (document.querySelector(sels.composeBody)) return { code: 'COMPOSE_BUSY' };+ if (args.reply) {+ const listbox = document.querySelector("[role='listbox']");+ if (!listbox || !args.reply.providerRowId) return { code: 'REPLY_TARGET_UNLOCATED' };+ const matches = () => [...listbox.querySelectorAll('[role="option"]')]+ .filter(row => readRow(row).providerRowId === args.reply.providerRowId);+ const scroller = listbox.closest('[role="region"]') || listbox.parentElement;+ let found = matches();+ for (let step = 0; step < 30 && found.length === 0 && scroller; step++) {+ scroller.scrollBy(0, 600);+ await h.sleep(300);+ found = matches();+ }+ if (found.length !== 1) return { code: 'REPLY_TARGET_UNLOCATED' };+ found[0].scrollIntoView({ block: 'center' });+ found[0].click();+ const reply = await h.waitFor(() => h.only(document, sels.replyButton));+ if (!reply) return { code: 'CONTROL_MISSING', control: 'replyButton' };+ reply.click();+ } else {+ const newMail = h.only(document, sels.newMail);+ if (!newMail) return { code: 'CONTROL_MISSING', control: 'newMail' };+ newMail.click();+ }+ const body = await h.waitFor(() => document.querySelector(sels.composeBody));+ if (!body) return { code: 'COMPOSE_NOT_OPENED' };+ // The compose surface is the nearest ancestor of the body that also holds Send.+ let root = body.parentElement;+ while (root && !root.querySelector(sels.composeSend)) root = root.parentElement;+ if (!root) return { code: 'CONTROL_MISSING', control: 'composeSend' };+ root.setAttribute('data-portos-send-token', token);+ return { ok: true };+ }++ // Teams: a new chat addressed by email, never the currently focused conversation.+ const existing = document.querySelector(sels.composeBox);+ if (existing && h.norm(existing.innerText)) return { code: 'COMPOSE_BUSY' };+ const newChat = h.only(document, sels.newChat);+ if (!newChat) return { code: 'CONTROL_MISSING', control: 'newChat' };+ newChat.click();+ const input = await h.waitFor(() => h.only(document, sels.recipientInput));+ if (!input) return { code: 'CONTROL_MISSING', control: 'recipientInput' };+ const resolved = [];+ for (const address of args.to) {+ h.typeInto(input, address);+ const option = await h.waitFor(() => {+ const hits = [...document.querySelectorAll(sels.recipientSuggestion)]+ .filter(el => h.visible(el) && h.labelOf(el).toLowerCase().includes(address));+ return hits.length === 1 ? hits[0] : null;+ }, 6000);+ if (!option) return { code: 'RECIPIENT_UNRESOLVED' };+ option.click();+ resolved.push(address);+ await h.sleep(300);+ }+ const box = await h.waitFor(() => h.only(document, sels.composeBox));+ if (!box) return { code: 'CONTROL_MISSING', control: 'composeBox' };+ box.setAttribute('data-portos-send-token', token);+ return { ok: true, resolved };+}++async function fillComposeInPage(args, h) {+ const { provider, sels, token } = args;+ const root = h.tagged(token);+ if (!root) return { code: 'COMPOSE_LOST' };+ const insertAtStart = (editor, text) => {+ editor.focus();+ const range = document.createRange();+ range.setStart(editor, 0);+ range.collapse(true);+ const selection = window.getSelection();+ selection.removeAllRanges();+ selection.addRange(range);+ document.execCommand('insertText', false, text);+ };++ if (provider === 'teams') {+ insertAtStart(root, args.body);+ return { ok: true, bodyOk: h.norm(root.innerText).includes(h.norm(args.body)) };+ }++ const fieldInput = field => field.matches('input, [contenteditable="true"], [role="textbox"]')+ ? field : field.querySelector('input, [contenteditable="true"], [role="textbox"]');+ const addRecipients = async (selector, addresses) => {+ if (!addresses.length) return true;+ const field = root.querySelector(selector);+ const input = field && fieldInput(field);+ if (!input) return false;+ for (const address of addresses) {+ h.typeInto(input, address + ';');+ await h.sleep(250);+ }+ return true;+ };++ let subjectOk = true;+ if (!args.reply) {+ if (args.cc.length && !root.querySelector(sels.ccField)) {+ h.only(root, sels.showCc)?.click();+ await h.sleep(300);+ }+ if (!(await addRecipients(sels.toField, args.to))) return { code: 'CONTROL_MISSING', control: 'toField' };+ if (!(await addRecipients(sels.ccField, args.cc))) return { code: 'CONTROL_MISSING', control: 'ccField' };+ const subject = h.only(root, sels.composeSubject);+ if (!subject) return { code: 'CONTROL_MISSING', control: 'composeSubject' };+ subject.focus();+ subject.select?.();+ document.execCommand('insertText', false, args.subject);+ subjectOk = subject.value === args.subject;+ }++ const editor = root.querySelector(sels.composeBody);+ if (!editor) return { code: 'CONTROL_MISSING', control: 'composeBody' };+ insertAtStart(editor, args.body);+ return {+ ok: true,+ subjectOk,+ bodyOk: h.norm(editor.innerText).includes(h.norm(args.body)),+ to: h.emailsIn(root.querySelector(sels.toField)),+ cc: h.emailsIn(root.querySelector(sels.ccField))+ };+}++// The ONE place a message can leave. It clicks Send at most once and never throws+// after the click: whatever it saw is reported, and the caller judges it.+async function submitComposeInPage(args, h) {+ const { provider, sels, token } = args;+ const root = h.tagged(token);+ if (!root) return { submitClicked: false, code: 'COMPOSE_LOST' };+ const send = h.only(provider === 'teams' ? document : root, sels.composeSend);+ if (!send) return { submitClicked: false, code: 'CONTROL_MISSING', control: 'composeSend' };++ const ack = new RegExp(args.ackPattern, 'i');+ const refusal = new RegExp(args.refusalPattern, 'i');+ const liveTexts = () => [...document.querySelectorAll('[role="status"], [role="alert"], [aria-live="polite"], [aria-live="assertive"]')]+ .map(el => h.norm(el.innerText)).filter(Boolean);+ const textsBefore = new Set(liveTexts());+ const chatMessages = () => (provider === 'teams' ? [...document.querySelectorAll(sels.sentMessage)] : []);+ const messagesBefore = new Set(chatMessages());+ const needle = h.norm(args.body).slice(0, 120);++ send.click();+ const observed = { submitClicked: true, composeClosed: false, ackSeen: false, refusalSeen: false };+ try {+ const end = Date.now() + args.timeoutMs;+ while (Date.now() < end) {+ await h.sleep(200);+ const fresh = liveTexts().filter(text => !textsBefore.has(text));+ if (fresh.some(text => refusal.test(text))) observed.refusalSeen = true;+ if (provider === 'teams') {+ // Teams acknowledges by rendering our own message in the thread.+ const mine = chatMessages().filter(el => !messagesBefore.has(el) && h.norm(el.innerText).includes(needle));+ if (mine.length) observed.ackSeen = true;+ if (mine.some(el => refusal.test(h.norm(el.innerText)))) observed.refusalSeen = true;+ observed.composeClosed = !root.isConnected || h.norm(root.innerText) === '';+ } else {+ observed.composeClosed = !root.isConnected;+ if (fresh.some(text => ack.test(text))) observed.ackSeen = true;+ }+ if (observed.refusalSeen || (observed.ackSeen && observed.composeClosed)) break;+ }+ } catch {+ // Observation only — the click already happened, so report what was seen.+ }+ return observed;+}++// Only ever runs BEFORE the click: removes our own tagged compose surface.+async function discardComposeInPage(args, h) {+ const { provider, sels, token } = args;+ const root = h.tagged(token);+ if (!root) return { discarded: false };+ if (provider === 'teams') {+ root.focus();+ document.execCommand('selectAll');+ document.execCommand('delete');+ return { discarded: true };+ }+ const discard = h.only(root, sels.composeDiscard);+ if (!discard) return { discarded: false };+ discard.click();+ await h.sleep(500);+ const confirm = [...document.querySelectorAll('[role="dialog"] button, [role="alertdialog"] button')]+ .find(button => /^discard$/i.test(h.norm(button.innerText || button.getAttribute('aria-label'))));+ confirm?.click();+ return { discarded: true };+}++const PHASES = {+ probe: probeIdentityInPage,+ open: openComposeInPage,+ fill: fillComposeInPage,+ submit: submitComposeInPage,+ discard: discardComposeInPage+};++export const COMPOSE_PHASES = Object.freeze(Object.keys(PHASES));++/** Source for one CDP evaluation. `args` is serialized as JSON, never interpolated as code. */+export function buildComposePhaseScript(phase, args) {+ const run = PHASES[phase];+ if (!run) throw new Error(`Unknown compose phase: ${phase}`);+ return `(${run.toString()})(${JSON.stringify({ ...args, phase })}, (${pageHelpers.toString()})(), ${readOutlookMessageRow.toString()})`;+}diff --git a/server/lib/messageBrowserCompose.test.js b/server/lib/messageBrowserCompose.test.jsnew file mode 100644index 0000000000..706c367c8f--- /dev/null+++ b/server/lib/messageBrowserCompose.test.js@@ -0,0 +1,120 @@+import vm from 'node:vm';+import { describe, expect, it } from 'vitest';+import {+ COMPOSE_PHASES, COMPOSE_SELECTOR_DEFAULTS, SEND_ACK_PATTERN, SEND_REFUSAL_PATTERN, buildComposePhaseScript,+ checkAccountIdentity, classifySendOutcome, planDelivery, recipientsMatch, resolveComposeConfig+} from './messageBrowserCompose.js';++// The single click that cannot be undone: only a positive provider signal is success.+describe('classifySendOutcome', () => {+ const clicked = (seen = {}) => ({ submitClicked: true, composeClosed: false, ackSeen: false, refusalSeen: false, ...seen });++ it.each([+ ['a closed compose surface plus a fresh acknowledgement', clicked({ composeClosed: true, ackSeen: true }), 'confirmed'],+ ['an acknowledgement while the compose surface is still open', clicked({ ackSeen: true }), 'unknown'],+ ['a closed compose surface with no acknowledgement', clicked({ composeClosed: true }), 'unknown'],+ ['an acknowledgement contradicted by a refusal', clicked({ composeClosed: true, ackSeen: true, refusalSeen: true }), 'unknown'],+ ['a refusal with the compose surface still open', clicked({ refusalSeen: true }), 'refused'],+ ['nothing observed after the click', clicked(), 'unknown'],+ ['a lost evaluation (timeout, closed socket, in-page throw)', null, 'unknown'],+ ['a non-object result', 'ok', 'unknown'],+ ['a result that never says whether it clicked', { composeClosed: true, ackSeen: true }, 'unknown'],+ ['an explicit refusal to click', { submitClicked: false, code: 'CONTROL_MISSING', control: 'composeSend' }, 'not_sent']+ ])('%s → %s', (_label, observed, outcome) => {+ expect(classifySendOutcome(observed).outcome).toBe(outcome);+ });++ it('never reports success without an explicit true for every signal', () => {+ for (const ackSeen of [undefined, 'yes', 1]) {+ expect(classifySendOutcome(clicked({ composeClosed: true, ackSeen })).outcome).not.toBe('confirmed');+ }+ });+});++describe('planDelivery', () => {+ const draft = (overrides = {}) => ({ body: 'Example body', to: ['[email protected]'], subject: 'Example subject', ...overrides });+ const target = (overrides = {}) => ({ id: 'msg-1', threadId: 'thread-1', providerRowId: 'row-1', subject: 'Re', from: { name: 'Bob Example', email: '[email protected]' }, ...overrides });++ it('plans an explicit recipient list, normalizing display-name forms', () => {+ const { plan } = planDelivery('outlook', draft({ to: ['Alice <[email protected]>', '[email protected]'], cc: ['[email protected]'] }));+ expect(plan).toMatchObject({ to: ['[email protected]'], cc: ['[email protected]'], subject: 'Example subject', reply: null });+ });++ it('answers the sender of the message a bare reply was written for, and locates it by provider row id', () => {+ const planned = planDelivery('outlook', draft({ to: [], replyToMessageId: 'msg-1', threadId: 'thread-1' }), target());+ expect(planned.plan).toMatchObject({ to: ['[email protected]'], reply: { providerRowId: 'row-1' } });+ });++ it.each([+ ['an empty body', 'outlook', { body: ' ' }, null, 'DRAFT_NOT_DELIVERABLE'],+ ['no recipient at all', 'outlook', { to: [] }, null, 'DRAFT_NOT_DELIVERABLE'],+ ['a bare reply whose sender has no email', 'outlook', { to: [], replyToMessageId: 'msg-1' }, target({ from: { name: 'Bob' } }), 'DRAFT_NOT_DELIVERABLE'],+ ['a new Outlook message without a subject', 'outlook', { subject: ' ' }, null, 'DRAFT_NOT_DELIVERABLE'],+ ['Cc on a Teams chat', 'teams', { cc: ['[email protected]'] }, null, 'DRAFT_NOT_DELIVERABLE'],+ ['a reply with no target', 'outlook', { replyToMessageId: 'msg-1' }, null, 'REPLY_TARGET_NOT_FOUND'],+ ['an Outlook reply whose target has no provider row id', 'outlook', { replyToMessageId: 'msg-1' }, target({ providerRowId: null }), 'REPLY_TARGET_UNIDENTIFIABLE'],+ ['a thread that is not the target\'s thread', 'teams', { replyToMessageId: 'msg-1', threadId: 'thread-2' }, target(), 'THREAD_MISMATCH'],+ ['an account type with no browser transport', 'gmail', {}, null, 'SEND_NOT_SUPPORTED']+ ])('refuses %s', (_label, type, overrides, replyTarget, code) => {+ expect(planDelivery(type, draft(overrides), replyTarget)).toMatchObject({ ok: false, code });+ });++ it('plans a Teams reply by the explicit recipient and needs no subject or row id', () => {+ const planned = planDelivery('teams', draft({ subject: '', replyToMessageId: 'msg-1' }), target({ providerRowId: null }));+ expect(planned).toMatchObject({ ok: true, plan: { to: ['[email protected]'], reply: null } });+ });+});++describe('what the page may show before the click', () => {+ const plan = { to: ['[email protected]'], cc: ['[email protected]'] };++ it('requires exactly the planned recipients — no extras, none missing', () => {+ expect(recipientsMatch(plan, { to: ['[email protected]'], cc: ['[email protected]'] })).toBe(true);+ expect(recipientsMatch(plan, { to: ['[email protected]', '[email protected]'], cc: ['[email protected]'] })).toBe(false);+ expect(recipientsMatch(plan, { to: ['[email protected]'], cc: [] })).toBe(false);+ expect(recipientsMatch(plan, undefined)).toBe(false);+ });++ it('refuses a visible identity that is not the account\'s and an unverifiable one when another account could be signed in', () => {+ expect(checkAccountIdentity({ expected: '[email protected]', observed: { emails: ['[email protected]'] }, required: false })).toMatchObject({ ok: false, code: 'ACCOUNT_IDENTITY_MISMATCH' });+ expect(checkAccountIdentity({ expected: '[email protected]', observed: { emails: ['[email protected]'] }, required: true })).toEqual({ ok: true });+ expect(checkAccountIdentity({ expected: '[email protected]', observed: { emails: [] }, required: true })).toMatchObject({ ok: false, code: 'ACCOUNT_IDENTITY_UNVERIFIED' });+ expect(checkAccountIdentity({ expected: '', observed: { emails: [] }, required: true })).toMatchObject({ ok: false, code: 'ACCOUNT_IDENTITY_UNVERIFIED' });+ expect(checkAccountIdentity({ expected: '[email protected]', observed: { emails: [] }, required: false })).toEqual({ ok: true });+ });+});++describe('resolveComposeConfig', () => {+ it('layers stored overrides over the defaults and ignores unknown keys and bad patterns', () => {+ const config = resolveComposeConfig('outlook', {+ composeSend: ' button.send ', messageRow: 'ignored', sendAckPattern: 'delivered', sendRefusalPattern: '(unclosed'+ });+ expect(config.sels.composeSend).toBe('button.send');+ expect(config.sels.newMail).toBe(COMPOSE_SELECTOR_DEFAULTS.outlook.newMail);+ expect(config.sels).not.toHaveProperty('messageRow');+ expect(config.ackPattern).toBe('delivered');+ expect(config.refusalPattern).toBe(SEND_REFUSAL_PATTERN);+ expect(resolveComposeConfig('outlook', undefined).ackPattern).toBe(SEND_ACK_PATTERN);+ expect(resolveComposeConfig('gmail', {})).toBeNull();+ });+});++// The scripts run inside the provider tab, so a syntax error or an argument that+// escapes its JSON literal would only show up against a real mailbox.+describe('buildComposePhaseScript', () => {+ const args = { sels: COMPOSE_SELECTOR_DEFAULTS.outlook, token: 'attempt-1', to: ['[email protected]'], cc: [], subject: 'Example', body: 'Example body', reply: null, ackPattern: SEND_ACK_PATTERN, refusalPattern: SEND_REFUSAL_PATTERN, timeoutMs: 1000 };++ it.each(['outlook', 'teams'].flatMap(provider => COMPOSE_PHASES.map(phase => [provider, phase])))('%s %s compiles', (provider, phase) => {+ const script = buildComposePhaseScript(phase, { ...args, provider, sels: COMPOSE_SELECTOR_DEFAULTS[provider] });+ expect(() => new vm.Script(script)).not.toThrow();+ expect(script).toContain(`"phase":"${phase}"`);+ });++ it('carries hostile text only as a JSON string, never as code', () => {+ const body = `"); globalThis.pwned = true; ("${String.fromCharCode(0x2028)}</script>`; // U+2028 must stay inside the JSON literal+ const script = buildComposePhaseScript('fill', { ...args, provider: 'outlook', body });+ expect(() => new vm.Script(script)).not.toThrow();+ expect(script).toContain(JSON.stringify(body).slice(1, -1));+ expect(() => buildComposePhaseScript('send-now', args)).toThrow(/Unknown compose phase/);+ });+});diff --git a/server/lib/messageTransport.js b/server/lib/messageTransport.jsnew file mode 100644index 0000000000..4280df8502--- /dev/null+++ b/server/lib/messageTransport.js@@ -0,0 +1,33 @@+// One table for what each message-account type can deliver and over which+// transport. Account capability, draft `sendVia`, the sender's mismatch guard and+// the privacy email lanes all read this, so "Outlook can send" is declared once.+//+// `email` marks accounts that can deliver to an arbitrary email address. A Teams+// chat reaches a person, not a mailbox, so it is sendable but never an email lane.+export const MESSAGE_ACCOUNT_TRANSPORT = Object.freeze({+ gmail: Object.freeze({ sendVia: 'api', email: true }),+ outlook: Object.freeze({ sendVia: 'playwright', email: true }),+ teams: Object.freeze({ sendVia: 'playwright', email: false })+});++export function sendViaForAccountType(type) {+ return MESSAGE_ACCOUNT_TRANSPORT[type]?.sendVia ?? null;+}++export function accountTypeCanSend(type) {+ return sendViaForAccountType(type) !== null;+}++/**+ * The account an email-shaped workflow (privacy opt-out / update requests) should+ * draft from: enabled, able to send, and able to reach an email address. A+ * provider API transport is preferred over browser automation because it returns+ * a definite result; otherwise the first match in the caller's order wins.+ * Accounts arrive from `listAccounts()` (derived `canSend`), which stays the+ * gate: an account without `canSend: true` is never picked.+ */+export function pickEmailSenderAccount(accounts = []) {+ const eligible = accounts.filter(account =>+ account.enabled !== false && account.canSend === true && MESSAGE_ACCOUNT_TRANSPORT[account.type]?.email === true);+ return eligible.find(account => sendViaForAccountType(account.type) === 'api') ?? eligible[0] ?? null;+}diff --git a/server/lib/messageTransport.test.js b/server/lib/messageTransport.test.jsnew file mode 100644index 0000000000..d80b61f4b7--- /dev/null+++ b/server/lib/messageTransport.test.js@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';+import { accountTypeCanSend, pickEmailSenderAccount, sendViaForAccountType } from './messageTransport.js';++describe('message account transports', () => {+ it('declares one transport per implemented account type and none for anything else', () => {+ expect(['gmail', 'outlook', 'teams'].map(sendViaForAccountType)).toEqual(['api', 'playwright', 'playwright']);+ expect(['gmail', 'outlook', 'teams'].every(accountTypeCanSend)).toBe(true);+ expect([sendViaForAccountType('signal'), accountTypeCanSend('signal'), accountTypeCanSend(undefined)]).toEqual([null, false, false]);+ });++ describe('pickEmailSenderAccount', () => {+ const account = (type, extra = {}) => ({ id: type, type, canSend: true, enabled: true, ...extra });++ it('prefers an API transport, never chooses a Teams chat, and honors the derived gate', () => {+ expect(pickEmailSenderAccount([account('outlook'), account('gmail')]).type).toBe('gmail');+ expect(pickEmailSenderAccount([account('teams'), account('outlook')]).type).toBe('outlook');+ expect(pickEmailSenderAccount([account('teams')])).toBeNull();+ expect(pickEmailSenderAccount([account('gmail', { canSend: false }), account('outlook', { enabled: false })])).toBeNull();+ expect(pickEmailSenderAccount([account('outlook', { canSend: undefined })])).toBeNull();+ expect(pickEmailSenderAccount()).toBeNull();+ });+ });+});diff --git a/server/routes/messages.js b/server/routes/messages.jsindex 29b62848c7..09e0a1e777 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -4,6 +4,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { UUID_RE } from '../lib/fileUtils.js';+import { sendViaForAccountType } from '../lib/messageTransport.js';import * as messageAccounts from '../services/messageAccounts.js';import * as messageSync from '../services/messageSync.js';import * as messageDrafts from '../services/messageDrafts.js';@@ -207,7 +208,7 @@ router.post('/drafts', asyncHandler(async (req, res) => {const data = validateRequest(createDraftSchema, req.body);const account = await messageAccounts.getAccount(data.accountId);if (!account) throw new ServerError('Account not found', { status: 404 });- const derivedSendVia = account.type === 'gmail' ? 'api' : 'playwright';+ const derivedSendVia = sendViaForAccountType(account.type) ?? 'playwright';if (data.sendVia && data.sendVia !== derivedSendVia) {throw new ServerError(`sendVia "${data.sendVia}" conflicts with account type "${account.type}" (expected "${derivedSendVia}")`, { status: 400 });}@@ -251,7 +252,7 @@ router.post('/drafts/generate', asyncHandler(async (req, res) => {subject: '',body: replyBody,generatedBy: 'ai',- sendVia: account.type === 'gmail' ? 'api' : 'playwright'+ sendVia: sendViaForAccountType(account.type) ?? 'playwright'});req.app.get('io')?.emit('messages:draft:created', { draftId: draft.id });res.status(201).json(draft);diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.jsindex 77620e912b..a9e2fce5a6 100644--- a/server/routes/privacy.test.js+++ b/server/routes/privacy.test.js@@ -506,7 +506,7 @@ describe('POST /api/privacy/optout', () => {optOutService.runOptOutPass.mockImplementationOnce(actual.runOptOutPass);const res = await request(makeApp()).post('/api/privacy/optout').send({ runVerification: false });expect(res.status).toBe(200);- expect(res.body).toMatchObject({ submitted: [], skipped: 1, nextActions: ['Connect a Gmail account to send opt-out emails'] });+ expect(res.body).toMatchObject({ submitted: [], skipped: 1, nextActions: ['Connect a Gmail or Outlook account to send opt-out emails'] });expect(brokers.transitionCase).not.toHaveBeenCalled();expect(drafts.createDraft).not.toHaveBeenCalled();expect(drafts.approveDraft).not.toHaveBeenCalled();diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.jsindex 0364e03242..a35af0a76b 100644--- a/server/services/messageAccounts.js+++ b/server/services/messageAccounts.js@@ -4,6 +4,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { isPlainObject } from '../lib/objects.js';+import { accountTypeCanSend, sendViaForAccountType } from '../lib/messageTransport.js';const ACCOUNTS_FILE = join(PATHS.messages, 'accounts.json');// All account IDs share this file, including sync metadata writes.@@ -22,14 +23,18 @@ async function saveAccounts(accounts) {noteReadinessChanged();}+// `canSend` is derived from the transport table, never stored: it flips with the+// code that implements a provider's send, not with data an install carries.+const withDerivedCapabilities = account => ({ ...account, canSend: accountTypeCanSend(account.type) });+export async function listAccounts() {const accounts = await loadAccounts();- return Object.values(accounts).map(account => ({ ...account, canSend: account.type === 'gmail' })).sort((a, b) => a.name.localeCompare(b.name));+ return Object.values(accounts).map(withDerivedCapabilities).sort((a, b) => a.name.localeCompare(b.name));}export async function getAccount(id) {const accounts = await loadAccounts();- return accounts[id] ? { ...accounts[id], canSend: accounts[id].type === 'gmail' } : null;+ return accounts[id] ? withDerivedCapabilities(accounts[id]) : null;}export async function createAccount(data) {@@ -40,7 +45,7 @@ export async function createAccount(data) {id,name: data.name,type: data.type, // gmail, outlook, teams- provider: data.type === 'gmail' ? 'api' : 'playwright',+ provider: sendViaForAccountType(data.type) ?? 'playwright',email: data.email || '',enabled: true,syncConfig: {diff --git a/server/services/messageAccounts.test.js b/server/services/messageAccounts.test.jsindex 554d9dedd0..73c8a6fbe0 100644--- a/server/services/messageAccounts.test.js+++ b/server/services/messageAccounts.test.js@@ -46,8 +46,9 @@ describe('messageAccounts', () => {uuid.mockReturnValueOnce('teams-id');await messageAccounts.createAccount({ name: 'Teams', type: 'teams' });expect((await messageAccounts.listAccounts()).map(({ type, canSend }) => ({ type, canSend }))).toEqual([- { type: 'gmail', canSend: true }, { type: 'outlook', canSend: false }, { type: 'teams', canSend: false }+ { type: 'gmail', canSend: true }, { type: 'outlook', canSend: true }, { type: 'teams', canSend: true }]);+ expect(await messageAccounts.getAccount('teams-id')).toMatchObject({ type: 'teams', canSend: true, provider: 'playwright' });});beforeEach(() => {diff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.jsindex 5aabea553e..41d70aaaf2 100644--- a/server/services/messageDrafts.js+++ b/server/services/messageDrafts.js@@ -146,7 +146,10 @@ export async function claimDraftForSend(id) {});}-export async function finishDraftSend(id, attemptId, success) {+// `outcome` is true (delivered), false (definitely not delivered, may be re-approved)+// or 'delivery_unknown' (the transport cannot say — same state a crash leaves, and+// it likewise needs a human to check the mailbox before the draft can move again).+export async function finishDraftSend(id, attemptId, outcome) {return queueWrite(async () => {const drafts = await loadDrafts();const draft = drafts.find(d => d.id === id);@@ -154,7 +157,7 @@ export async function finishDraftSend(id, attemptId, success) {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.status = outcome === 'delivery_unknown' ? 'delivery_unknown' : outcome === true ? 'sent' : 'failed';draft.updatedAt = new Date().toISOString();const attempt = draft.sendAttempts.find(a => a.id === attemptId);attempt.outcome = draft.status;diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.jsindex 1b35a5459f..27e064013c 100644--- a/server/services/messagePlaywrightSync.js+++ b/server/services/messagePlaywrightSync.js@@ -4,6 +4,12 @@ import crypto from 'crypto';import { v4 as uuidv4 } from '../lib/uuid.js';import { ensureDir, PATHS, safeJSONParse, tryReadFile, atomicWrite } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';+import { createMutex } from '../lib/asyncMutex.js';+import { messageLogError } from '../lib/messageLogError.js';+import {+ COMPOSE_PROVIDER_LABEL, SUBMIT_EVALUATE_TIMEOUT_MS, SUBMIT_OBSERVE_MS, buildComposePhaseScript, checkAccountIdentity, classifySendOutcome,+ describeComposeFailure, planDelivery, recipientsMatch, resolveComposeConfig+} from '../lib/messageBrowserCompose.js';import { findOrOpenPage, listCdpPages, isAuthPage, evaluateOnPage } from './browserService.js';// Compat re-exports — older consumers and test mocks import these from here@@ -453,12 +459,115 @@ export async function refreshMessageDetail(account, message) {return detail;}+const SEND_PAGE_MATCH = { outlook: 'outlook.office.com/mail', teams: 'teams.microsoft.com' };++// One browser tab per provider, so two sends to the same provider must not+// interleave their compose steps. Claimed drafts of different providers still run in parallel.+const sendLocks = { outlook: createMutex(), teams: createMutex() };++// A send never opens a tab: a freshly opened one cannot be signed in, and the+// sign-in state the user already established is exactly what authorizes the send.+async function findExistingProviderPage(provider) {+ const pages = await getPages().catch(() => []);+ return pages.find(page => (!page.type || page.type === 'page') && page.url?.includes(SEND_PAGE_MATCH[provider])) ?? null;+}++const notSent = (status, code, error) => ({ success: false, status, code, error });++const deliveryUnknown = label => ({+ success: false,+ deliveryUnknown: true,+ status: 502,+ code: 'DELIVERY_UNKNOWN',+ error: `${label} did not confirm delivery and it may already have been sent. Check ${label === 'Teams' ? 'the conversation' : 'Sent Items'}, then record the outcome. PortOS will not resend it.`+});+/**- * Send message via Playwright browser automation+ * Deliver an approved draft through the provider's web UI. Every phase before the+ * single submit click is side-effect free and fails as a definite "not sent"; after+ * the click, only a positive provider acknowledgement is success and anything else+ * is `deliveryUnknown` — never retried here (see `lib/messageBrowserCompose.js`).*/-export async function sendPlaywright(account, draft) {- console.log(`📧 Playwright send for account ${account.id} (${account.type}) — automation pending`);- return { success: false, error: 'Playwright send not yet implemented', status: 501, code: 'NOT_IMPLEMENTED' };+async function deliverViaBrowser(account, draft, { replyTarget, requireIdentity }, markSubmitting) {+ const provider = account.type;+ const label = COMPOSE_PROVIDER_LABEL[provider];+ const planned = planDelivery(provider, draft, replyTarget);+ if (!planned.ok) return notSent(planned.status, planned.code, planned.error);+ const { plan } = planned;++ const page = await findExistingProviderPage(provider);+ if (!page) return notSent(409, 'PROVIDER_TAB_UNAVAILABLE', `No ${label} tab is open in the PortOS browser — open ${label}, sign in, and retry`);+ if (!page.webSocketDebuggerUrl) return notSent(502, 'PROVIDER_TAB_UNAVAILABLE', `Cannot connect to the ${label} tab`);+ if (isAuthPage(page)) return notSent(409, 'PROVIDER_LOGIN_REQUIRED', `Login required — sign into ${label} and retry`);++ const config = resolveComposeConfig(provider, (await getSelectors())[provider]);+ const token = draft.sendAttemptId || uuidv4();+ const run = (phase, extra = {}, options) =>+ evaluateOnPage(page, buildComposePhaseScript(phase, { provider, sels: config.sels, token, ...extra }), options);+ // Only used before the click: removes our own compose surface, best effort.+ const abort = async failure => {+ await run('discard').catch(() => null);+ return { success: false, ...describeComposeFailure(provider, failure) };+ };++ const identity = await run('probe');+ if (!identity) return notSent(502, 'PROVIDER_TAB_UNAVAILABLE', `The ${label} tab did not respond`);+ const who = checkAccountIdentity({ expected: account.email, observed: identity, required: requireIdentity });+ if (!who.ok) {+ return notSent(409, who.code, who.code === 'ACCOUNT_IDENTITY_MISMATCH'+ ? `The ${label} tab is signed in as a different account — sign into this account and retry`+ : `Several ${label} accounts exist and the browser tab does not show which one is signed in, so sending is blocked to keep it from going out of the wrong mailbox`);+ }++ const opened = await run('open', { to: plan.to, reply: plan.reply });+ if (opened?.ok !== true) return abort(opened);+ if (provider === 'teams' && !recipientsMatch(plan, { to: opened.resolved, cc: [] })) return abort({ code: 'RECIPIENT_MISMATCH' });++ const filled = await run('fill', { to: plan.to, cc: plan.cc, subject: plan.subject, body: plan.body, reply: plan.reply });+ if (filled?.ok !== true) return abort(filled);+ if (provider === 'outlook' && !recipientsMatch(plan, filled)) return abort({ code: 'RECIPIENT_MISMATCH' });+ if (filled.bodyOk !== true || filled.subjectOk === false) return abort({ code: 'CONTENT_MISMATCH' });++ markSubmitting(); // from here a throw can no longer prove nothing was sent+ const observed = await run('submit', {+ body: plan.body, ackPattern: config.ackPattern, refusalPattern: config.refusalPattern, timeoutMs: SUBMIT_OBSERVE_MS+ }, { timeout: SUBMIT_EVALUATE_TIMEOUT_MS });+ const verdict = classifySendOutcome(observed);+ if (verdict.outcome === 'confirmed') {+ console.log(`📧 ${label} send confirmed: draft ${draft.id}`);+ return { success: true, confirmed: true };+ }+ if (verdict.outcome === 'not_sent') return abort(verdict);+ if (verdict.outcome === 'refused') {+ return notSent(502, 'PROVIDER_REFUSED', `${label} refused the message. Close its compose window, fix the problem, and approve the draft again`);+ }+ console.warn(`⚠️ ${label} delivery unconfirmed: draft ${draft.id}`);+ return deliveryUnknown(label);+}++/**+ * Send an approved draft via the provider's web UI (Outlook / Teams).+ * `replyTarget` is the cached message the draft answers, resolved within the+ * draft's own account by the sender; `requireIdentity` is set when more than one+ * enabled account shares this provider's single browser sign-in.+ */+export async function sendPlaywright(account, draft, options) {+ const { replyTarget = null, requireIdentity = false } = options ?? {};+ const label = COMPOSE_PROVIDER_LABEL[account.type];+ if (!label) return notSent(501, 'SEND_NOT_SUPPORTED', "Sending from this account isn't supported yet — copy the draft");+ return sendLocks[account.type](async () => {+ let submitting = false;+ return deliverViaBrowser(account, draft, { replyTarget, requireIdentity }, () => { submitting = true; }).catch(error => {+ // A throw before the click is a definite failure; once Send may have been+ // clicked the same throw cannot prove the message stayed in the mailbox.+ if (submitting) {+ console.warn(`⚠️ ${label} delivery unconfirmed after error: draft ${draft.id}: ${messageLogError(error)}`);+ return deliveryUnknown(label);+ }+ console.error(`❌ ${label} send failed before submit: draft ${draft.id}: ${messageLogError(error)}`);+ return notSent(502, 'SEND_FAILED', `${label} send failed before anything was submitted — nothing was sent`);+ });+ });}/**diff --git a/server/services/messagePlaywrightSync.test.js b/server/services/messagePlaywrightSync.test.jsindex 326eeb3b33..1be8bc8dbc 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, syncPlaywright } = await import('./messagePlaywrightSync.js');+const { testSelectors, syncPlaywright, sendPlaywright } = await import('./messagePlaywrightSync.js');const OPEN_PAGE = { url: 'https://outlook.office.com/mail/', webSocketDebuggerUrl: 'ws://x' };@@ -104,3 +104,186 @@ it('retains the ingested provider row ID when detail is unavailable', async () =const result = await syncPlaywright({ id: 'example-account', type: 'outlook' }, { messages: [] });expect(result.messages).toEqual([expect.objectContaining({ providerRowId: 'stable-row', subject: 'Example subject' })]);});++// Browser-delivered drafts. evaluateOnPage is scripted per compose phase, so the+// whole success / failure / ambiguity matrix runs with no mailbox and no recipient.+describe('sendPlaywright', () => {+ const OUTLOOK_PAGE = { id: 'page-1', type: 'page', url: 'https://outlook.office.com/mail/', webSocketDebuggerUrl: 'ws://page' };+ const TEAMS_PAGE = { id: 'page-2', type: 'page', url: 'https://teams.microsoft.com/v2/', webSocketDebuggerUrl: 'ws://teams' };+ const outlook = { id: 'acct-1', type: 'outlook', email: '[email protected]' };+ const teams = { id: 'acct-2', type: 'teams', email: '' };+ const draft = (overrides = {}) => ({ id: 'draft-1', sendAttemptId: 'attempt-1', body: 'Example body', to: ['[email protected]'], cc: [], subject: 'Example subject', ...overrides });+ const CONFIRMED = { submitClicked: true, composeClosed: true, ackSeen: true, refusalSeen: false };++ const phaseOf = script => script.match(/"phase":"(\w+)"/)?.[1];+ const phasesRun = () => evaluateOnPage.mock.calls.map(([, script]) => phaseOf(script));+ const scriptBrowser = (overrides = {}) => {+ const phases = {+ probe: { found: true, emails: [] },+ open: { ok: true },+ fill: { ok: true, subjectOk: true, bodyOk: true, to: ['[email protected]'], cc: [] },+ submit: CONFIRMED,+ discard: { discarded: true },+ ...overrides+ };+ evaluateOnPage.mockImplementation(async (_page, script, options) => {+ const value = phases[phaseOf(script)];+ return typeof value === 'function' ? value(script, options) : value;+ });+ };++ beforeEach(() => {+ findOrOpenPage.mockReset();+ isAuthPage.mockReset().mockReturnValue(false);+ evaluateOnPage.mockReset();+ tryReadFile.mockReset().mockResolvedValue(null);+ // A service-worker target for the same host must never be mistaken for the page.+ listCdpPages.mockReset().mockResolvedValue([{ type: 'service_worker', url: 'https://outlook.office.com/mail/sw.js', webSocketDebuggerUrl: 'ws://sw' }, OUTLOOK_PAGE, TEAMS_PAGE]);+ scriptBrowser();+ });++ it('confirms an Outlook send only after one pass through probe, open, fill and a single submit', async () => {+ expect(await sendPlaywright(outlook, draft())).toEqual({ success: true, confirmed: true });+ expect(phasesRun()).toEqual(['probe', 'open', 'fill', 'submit']);+ expect(evaluateOnPage.mock.calls.every(([page]) => page === OUTLOOK_PAGE)).toBe(true);+ expect(findOrOpenPage).not.toHaveBeenCalled();+ const [, submitScript, options] = evaluateOnPage.mock.calls.at(-1);+ expect(submitScript).toContain('"body":"Example body"');+ expect(options.timeout).toBeGreaterThan(20000);+ });++ it('answers a cached Outlook message by its provider row id and sends to its sender', async () => {+ scriptBrowser({ fill: { ok: true, subjectOk: true, bodyOk: true, to: ['[email protected]'], cc: [] } });+ const replyTarget = { providerRowId: 'row-1', subject: 'Example', from: { name: 'Bob Example', email: '[email protected]' } };+ const result = await sendPlaywright(outlook, draft({ to: [], replyToMessageId: 'msg-1' }), { replyTarget });+ expect(result).toEqual({ success: true, confirmed: true });+ const openScript = evaluateOnPage.mock.calls.find(([, script]) => phaseOf(script) === 'open')[1];+ expect(openScript).toContain('"providerRowId":"row-1"');+ expect(openScript).toContain('"to":["[email protected]"]');+ });++ it('delivers a Teams chat to the resolved recipient on the Teams tab', async () => {+ scriptBrowser({ open: { ok: true, resolved: ['[email protected]'] }, fill: { ok: true, bodyOk: true } });+ expect(await sendPlaywright(teams, draft({ subject: '' }))).toEqual({ success: true, confirmed: true });+ expect(evaluateOnPage.mock.calls.every(([page]) => page === TEAMS_PAGE)).toBe(true);+ });++ describe('before anything is submitted', () => {+ it.each([+ ['no tab for the provider is open', () => listCdpPages.mockResolvedValue([]), 'PROVIDER_TAB_UNAVAILABLE', []],+ ['the tab has no debugger connection', () => listCdpPages.mockResolvedValue([{ ...OUTLOOK_PAGE, webSocketDebuggerUrl: undefined }]), 'PROVIDER_TAB_UNAVAILABLE', []],+ ['the login has expired', () => isAuthPage.mockReturnValue(true), 'PROVIDER_LOGIN_REQUIRED', []],+ ['the tab never answers the identity probe', () => scriptBrowser({ probe: null }), 'PROVIDER_TAB_UNAVAILABLE', ['probe']],+ ['the tab is signed in as someone else', () => scriptBrowser({ probe: { found: true, emails: ['[email protected]'] } }), 'ACCOUNT_IDENTITY_MISMATCH', ['probe']]+ ])('%s: fails without opening a compose window', async (_label, arrange, code, ran) => {+ arrange();+ expect(await sendPlaywright(outlook, draft())).toMatchObject({ success: false, code });+ expect(phasesRun()).toEqual(ran);+ });++ it('blocks an unverifiable sign-in when several accounts share the provider', async () => {+ expect(await sendPlaywright(outlook, draft(), { requireIdentity: true })).toMatchObject({ success: false, status: 409, code: 'ACCOUNT_IDENTITY_UNVERIFIED' });+ expect(phasesRun()).toEqual(['probe']);+ scriptBrowser({ probe: { found: true, emails: ['[email protected]'] } });+ expect(await sendPlaywright(outlook, draft(), { requireIdentity: true })).toMatchObject({ success: true });+ });++ it.each([+ ['a compose control is missing', { open: { code: 'CONTROL_MISSING', control: 'newMail' } }, 'PROVIDER_CONTROL_MISSING'],+ ['a compose window is already in use', { open: { code: 'COMPOSE_BUSY' } }, 'PROVIDER_COMPOSE_BUSY'],+ ['the page stops answering while opening', { open: null }, 'PROVIDER_TAB_UNAVAILABLE'],+ ['the shown recipients differ from the approved ones', { fill: { ok: true, subjectOk: true, bodyOk: true, to: ['[email protected]', '[email protected]'], cc: [] } }, 'RECIPIENT_MISMATCH'],+ ['the typed text did not take', { fill: { ok: true, subjectOk: true, bodyOk: false, to: ['[email protected]'], cc: [] } }, 'PROVIDER_CONTENT_MISMATCH']+ ])('%s: removes its own compose window and never reaches submit', async (_label, overrides, code) => {+ scriptBrowser(overrides);+ expect(await sendPlaywright(outlook, draft())).toMatchObject({ success: false, code });+ expect(phasesRun()).not.toContain('submit');+ expect(phasesRun().at(-1)).toBe('discard');+ });++ it('refuses a Teams recipient the picker did not resolve to exactly the planned address', async () => {+ scriptBrowser({ open: { ok: true, resolved: ['[email protected]'] } });+ expect(await sendPlaywright(teams, draft({ subject: '' }))).toMatchObject({ success: false, code: 'RECIPIENT_MISMATCH' });+ expect(phasesRun()).not.toContain('submit');+ });++ it('reports a throw before the click as a definite failure', async () => {+ evaluateOnPage.mockImplementation(async (_page, script) => {+ if (phaseOf(script) === 'open') throw new Error('Example socket failure');+ return { found: true, emails: [] };+ });+ expect(await sendPlaywright(outlook, draft())).toMatchObject({ success: false, status: 502, code: 'SEND_FAILED' });+ expect(phasesRun()).not.toContain('submit');+ });++ it('stops at a deliverability problem before touching the browser', async () => {+ expect(await sendPlaywright(outlook, draft({ to: [] }))).toMatchObject({ success: false, code: 'DRAFT_NOT_DELIVERABLE' });+ expect(evaluateOnPage).not.toHaveBeenCalled();+ expect(await sendPlaywright({ id: 'acct-3', type: 'gmail' }, draft())).toMatchObject({ success: false, status: 501, code: 'SEND_NOT_SUPPORTED' });+ });+ });++ describe('after the single submit click', () => {+ const lastPhases = () => phasesRun().slice(-2);++ it.each([+ ['the evaluation is lost', null],+ ['the compose window closed but nothing acknowledged it', { ...CONFIRMED, ackSeen: false }],+ ['the acknowledgement arrived while the window stayed open', { ...CONFIRMED, composeClosed: false }],+ ['the page reported an acknowledgement and a refusal', { ...CONFIRMED, refusalSeen: true }]+ ])('%s: reports unknown delivery, never discards, never retries', async (_label, submit) => {+ scriptBrowser({ submit });+ expect(await sendPlaywright(outlook, draft())).toMatchObject({ success: false, deliveryUnknown: true, status: 502, code: 'DELIVERY_UNKNOWN' });+ expect(phasesRun().filter(phase => phase === 'submit')).toHaveLength(1);+ expect(phasesRun()).not.toContain('discard');+ expect(lastPhases()).toEqual(['fill', 'submit']);+ });++ it('reports a provider refusal as a definite failure and leaves the compose window for the user', async () => {+ scriptBrowser({ submit: { submitClicked: true, composeClosed: false, ackSeen: false, refusalSeen: true } });+ expect(await sendPlaywright(outlook, draft())).toMatchObject({ success: false, status: 502, code: 'PROVIDER_REFUSED' });+ expect(phasesRun()).not.toContain('discard');+ });++ it('treats a missing Send control as not sent and clears the compose window', async () => {+ scriptBrowser({ submit: { submitClicked: false, code: 'CONTROL_MISSING', control: 'composeSend' } });+ expect(await sendPlaywright(outlook, draft())).toMatchObject({ success: false, code: 'PROVIDER_CONTROL_MISSING' });+ expect(lastPhases()).toEqual(['submit', 'discard']);+ });++ it('reports a throw while submitting as unknown delivery, because the click may have happened', async () => {+ evaluateOnPage.mockImplementation(async (_page, script) => {+ if (phaseOf(script) === 'submit') throw new Error('Example socket failure');+ return { probe: { found: true, emails: [] }, open: { ok: true }, fill: { ok: true, subjectOk: true, bodyOk: true, to: ['[email protected]'], cc: [] } }[phaseOf(script)];+ });+ expect(await sendPlaywright(outlook, draft())).toMatchObject({ success: false, deliveryUnknown: true, code: 'DELIVERY_UNKNOWN' });+ expect(phasesRun()).not.toContain('discard');+ });+ });++ it('serializes sends through one provider tab but lets another provider proceed', async () => {+ const gate = Promise.withResolvers();+ const flush = () => new Promise(resolve => setImmediate(resolve));+ let submits = 0;+ scriptBrowser({+ submit: async () => {+ if (++submits === 1) await gate.promise;+ return CONFIRMED;+ },+ open: { ok: true, resolved: ['[email protected]'] },+ fill: { ok: true, subjectOk: true, bodyOk: true, to: ['[email protected]'], cc: [] }+ });+ const first = sendPlaywright(outlook, draft());+ await vi.waitFor(() => expect(submits).toBe(1));+ const second = sendPlaywright(outlook, draft({ id: 'draft-2', sendAttemptId: 'attempt-2' }));+ const otherProvider = await sendPlaywright(teams, draft({ id: 'draft-3', sendAttemptId: 'attempt-3', subject: '' }));+ await flush();+ expect(otherProvider).toMatchObject({ success: true });+ expect(phasesRun().filter(phase => phase === 'probe')).toHaveLength(2); // first Outlook + the Teams send+ gate.resolve();+ expect(await first).toMatchObject({ success: true });+ expect(await second).toMatchObject({ success: true });+ expect(phasesRun().filter(phase => phase === 'probe')).toHaveLength(3);+ expect(submits).toBe(3);+ });+});diff --git a/server/services/messageSender.js b/server/services/messageSender.jsindex ab98c1bb44..c8b8df8777 100644--- a/server/services/messageSender.js+++ b/server/services/messageSender.js@@ -1,12 +1,25 @@import { messageLogError } from '../lib/messageLogError.js';+import { sendViaForAccountType } from '../lib/messageTransport.js';+import { planDelivery } from '../lib/messageBrowserCompose.js';import { getDraft, claimDraftForSend, finishDraftSend, releaseDraftSend } from './messageDrafts.js';-import { getAccount } from './messageAccounts.js';+import { getAccount, listAccounts } from './messageAccounts.js';-const ACCOUNT_TYPE_TO_SEND_VIA = {- gmail: 'api',- outlook: 'playwright',- teams: 'playwright'-};+// Everything a browser delivery needs that can be refused WITHOUT consuming the+// draft's approval: whether it can be delivered at all and to whom, the message it+// answers (looked up in the draft's OWN account cache, so a draft can never answer+// another account's thread), and whether the shared browser sign-in could be a+// different account of the same type.+async function prepareBrowserDelivery(account, draft) {+ let replyTarget = null;+ if (draft.replyToMessageId) {+ const { getMessage } = await import('./messageSync.js');+ replyTarget = await getMessage(account.id, draft.replyToMessageId);+ }+ const planned = planDelivery(account.type, draft, replyTarget);+ if (!planned.ok) return { refusal: { success: false, status: planned.status, code: planned.code, error: planned.error } };+ const sameType = (await listAccounts()).filter(other => other.type === account.type && other.enabled !== false);+ return { delivery: { replyTarget, requireIdentity: sameType.length > 1 } };+}export async function sendDraft(draftId, io) {let draft = await getDraft(draftId);@@ -22,11 +35,18 @@ export async function sendDraft(draftId, io) {return { success: false, status: 501, code: 'SEND_NOT_SUPPORTED', error: "Sending from this account isn't supported yet — copy the draft" };}- const expectedSendVia = ACCOUNT_TYPE_TO_SEND_VIA[account.type];+ const expectedSendVia = sendViaForAccountType(account.type);if (draft.sendVia !== expectedSendVia) {return { success: false, status: 400, code: 'SEND_VIA_MISMATCH', error: `sendVia "${draft.sendVia}" does not match account type "${account.type}" (expected "${expectedSendVia}")` };}+ let delivery = null;+ if (draft.sendVia === 'playwright') {+ const prepared = await prepareBrowserDelivery(account, draft);+ if (prepared.refusal) return prepared.refusal;+ delivery = prepared.delivery;+ }+draft = await claimDraftForSend(draftId);console.log(`📧 Sending draft ${draft.id} via ${draft.sendVia}`);@@ -36,7 +56,7 @@ export async function sendDraft(draftId, io) {return sendGmail(account, draft);}const { sendPlaywright } = await import('./messagePlaywrightSync.js');- return sendPlaywright(account, draft);+ return sendPlaywright(account, draft, delivery);};const complete = async () => {@@ -50,6 +70,13 @@ export async function sendDraft(draftId, io) {io?.emit('messages:draft:sent', { draftId });io?.emit('messages:changed', {});console.log(`📧 Draft sent successfully: ${draft.id}`);+ } else if (result?.deliveryUnknown) {+ // The transport cannot say whether it left. Park the draft in the same+ // human-reconciled state a crash leaves — never `failed`, which can be re-approved and resent.+ await finishDraftSend(draftId, draft.sendAttemptId, 'delivery_unknown').catch(err => console.warn(`⚠️ Failed to mark draft delivery unknown: ${messageLogError(err)}`));+ io?.emit('messages:changed', {});+ console.warn(`⚠️ Draft delivery unconfirmed: ${draft.id} awaits reconciliation`);+ return { success: false, status: result.status ?? 502, code: 'DELIVERY_UNKNOWN', error: result.error };} 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';diff --git a/server/services/messageSender.test.js b/server/services/messageSender.test.jsindex 4eb8430b9b..e1bc363739 100644--- a/server/services/messageSender.test.js+++ b/server/services/messageSender.test.js@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { join } from 'path';const doubles = vi.hoisted(() => ({- files: new Map(), failTerminal: false, getAccount: vi.fn(), sendGmail: vi.fn(), sendPlaywright: vi.fn()+ files: new Map(), failTerminal: false, getAccount: vi.fn(), listAccounts: vi.fn(), getMessage: vi.fn(), sendGmail: vi.fn(), sendPlaywright: vi.fn()}));vi.mock('../lib/fileUtils.js', () => ({PATHS: { messages: '/mock/messages' },@@ -14,7 +14,8 @@ vi.mock('../lib/fileUtils.js', () => ({},safeJSONParse: JSON.parse}));-vi.mock('./messageAccounts.js', () => ({ getAccount: doubles.getAccount }));+vi.mock('./messageAccounts.js', () => ({ getAccount: doubles.getAccount, listAccounts: doubles.listAccounts }));+vi.mock('./messageSync.js', () => ({ getMessage: doubles.getMessage }));vi.mock('./messageGmailSync.js', () => ({ sendGmail: doubles.sendGmail }));vi.mock('./messagePlaywrightSync.js', () => ({ sendPlaywright: doubles.sendPlaywright }));@@ -38,6 +39,8 @@ beforeEach(() => {doubles.files.clear();doubles.failTerminal = false;doubles.getAccount.mockResolvedValue({ id: 'account-1', type: 'gmail' });+ doubles.listAccounts.mockResolvedValue([{ id: 'account-1', type: 'gmail' }]);+ doubles.getMessage.mockResolvedValue(null);doubles.sendGmail.mockResolvedValue({ success: true });doubles.sendPlaywright.mockResolvedValue({ success: true });});@@ -112,8 +115,9 @@ describe('draft send workflow', () => {});it.each(['returned', 'thrown'])('persists a %s dispatch failure and permits explicit reapproval', async kind => {- seed({ id: 'draft-1', sendVia: 'playwright' });+ seed({ id: 'draft-1', sendVia: 'playwright', to: ['[email protected]'], subject: 'Example subject' });doubles.getAccount.mockResolvedValue({ id: 'account-1', type: 'outlook' });+ doubles.listAccounts.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' });@@ -155,6 +159,79 @@ describe('draft send workflow', () => {});});+const OUTLOOK = { id: 'account-1', type: 'outlook', enabled: true };+const browserDraft = (overrides = {}) => ({ sendVia: 'playwright', to: ['[email protected]'], subject: 'Example subject', ...overrides });+const cachedMessage = (overrides = {}) => ({+ id: 'msg-1', threadId: 'thread-1', providerRowId: 'row-1', subject: 'Example', from: { name: 'Bob Example', email: '[email protected]' }, ...overrides+});++describe('browser draft delivery', () => {+ beforeEach(() => {+ doubles.getAccount.mockResolvedValue(OUTLOOK);+ doubles.listAccounts.mockResolvedValue([OUTLOOK]);+ });++ it('dispatches an approved draft once and returns the provider confirmation', async () => {+ seed({ id: 'draft-1', ...browserDraft() });+ doubles.sendPlaywright.mockResolvedValueOnce({ success: true, confirmed: true });+ expect(await sendDraft('draft-1')).toEqual({ success: true, confirmed: true });+ expect((await getDraft('draft-1')).status).toBe('sent');+ expect(doubles.sendPlaywright).toHaveBeenCalledWith(OUTLOOK, expect.objectContaining({ id: 'draft-1', status: 'sending' }), { replyTarget: null, requireIdentity: false });+ expect(await sendDraft('draft-1')).toMatchObject({ status: 409 });+ expect(doubles.sendPlaywright).toHaveBeenCalledTimes(1);+ });++ it('resolves the reply target inside the draft\'s own account only', async () => {+ seed({ id: 'reply', replyToMessageId: 'msg-1', threadId: 'thread-1', ...browserDraft({ to: [] }) });+ doubles.getMessage.mockResolvedValueOnce(cachedMessage());+ expect(await sendDraft('reply')).toEqual({ success: true });+ expect(doubles.getMessage).toHaveBeenCalledWith('account-1', 'msg-1');+ expect(doubles.sendPlaywright).toHaveBeenCalledWith(OUTLOOK, expect.anything(), expect.objectContaining({ replyTarget: expect.objectContaining({ id: 'msg-1', providerRowId: 'row-1' }) }));+ });++ it.each([+ ['a reply target that belongs to another account', { replyToMessageId: 'msg-1' }, null, 'REPLY_TARGET_NOT_FOUND'],+ ['a reply whose thread differs from its target', { replyToMessageId: 'msg-1', threadId: 'thread-2' }, cachedMessage(), 'THREAD_MISMATCH'],+ ['a draft with no recipient', { to: [] }, null, 'DRAFT_NOT_DELIVERABLE'],+ ['a recipient that is not an email address', { to: ['Alice'] }, null, 'DRAFT_NOT_DELIVERABLE']+ ])('refuses %s without consuming approval or touching the provider', async (_label, overrides, target, code) => {+ seed({ id: 'draft-1', ...browserDraft(overrides) });+ doubles.getMessage.mockResolvedValue(target);+ expect(await sendDraft('draft-1')).toMatchObject({ success: false, code });+ expect((await getDraft('draft-1')).status).toBe('approved');+ expect(doubles.sendPlaywright).not.toHaveBeenCalled();+ });++ it('flags a shared browser sign-in when several accounts of the provider are enabled', async () => {+ seed({ id: 'draft-1', ...browserDraft() });+ doubles.listAccounts.mockResolvedValue([OUTLOOK, { id: 'account-2', type: 'outlook', enabled: true }, { id: 'account-3', type: 'gmail' }]);+ await sendDraft('draft-1');+ expect(doubles.sendPlaywright).toHaveBeenCalledWith(OUTLOOK, expect.anything(), { replyTarget: null, requireIdentity: true });+ });++ it('parks an unconfirmed delivery for reconciliation instead of a re-approvable failure', async () => {+ seed({ id: 'draft-1', ...browserDraft() });+ const io = { emit: vi.fn() };+ doubles.sendPlaywright.mockResolvedValueOnce({ success: false, deliveryUnknown: true, status: 502, code: 'DELIVERY_UNKNOWN', error: 'Example unconfirmed' });+ expect(await sendDraft('draft-1', io)).toEqual({ success: false, status: 502, code: 'DELIVERY_UNKNOWN', error: 'Example unconfirmed' });+ const unknown = await getDraft('draft-1');+ expect(unknown.status).toBe('delivery_unknown');+ expect(unknown.sendAttempts).toEqual([expect.objectContaining({ id: unknown.sendAttemptId, outcome: 'delivery_unknown', finishedAt: expect.any(String) })]);+ expect(io.emit).toHaveBeenCalledWith('messages:changed', {});+ expect(io.emit).not.toHaveBeenCalledWith('messages:draft:sent', expect.anything());++ // Neither a second send nor a re-approval can duplicate it; only a mailbox-checked reconciliation reopens it.+ expect(await sendDraft('draft-1')).toMatchObject({ status: 409 });+ await expect(approveDraft('draft-1')).rejects.toMatchObject({ status: 409 });+ expect(doubles.sendPlaywright).toHaveBeenCalledTimes(1);+ await reconcileDraftSend('draft-1', { attemptId: unknown.sendAttemptId, outcome: 'not_sent' });+ await approveDraft('draft-1');+ doubles.sendPlaywright.mockResolvedValueOnce({ success: true, confirmed: true });+ expect(await sendDraft('draft-1')).toMatchObject({ success: true });+ expect(doubles.sendPlaywright).toHaveBeenCalledTimes(2);+ });+});+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();diff --git a/server/services/privacyChanges.js b/server/services/privacyChanges.jsindex 16a033ec92..69d79434d9 100644--- a/server/services/privacyChanges.js+++ b/server/services/privacyChanges.js@@ -32,6 +32,7 @@ import { getOrg } from './privacyOrgs.js';import { resolveSubjectId } from './privacySubjects.js';import { listAccounts } from './messageAccounts.js';import { createDraft } from './messageDrafts.js';+import { pickEmailSenderAccount, sendViaForAccountType } from '../lib/messageTransport.js';const EVENT_COLUMNS = `id, subject_id, vault_record_id, replacement_record_id, kind, declared_at, note`;@@ -342,8 +343,8 @@ export async function draftUpdateEmail(eventId, orgId) {if (!to) throw new ServerError('Organization has no contact email', { status: 400, code: 'ORG_EMAIL_MISSING' });const accounts = await listAccounts();- const account = accounts.find((a) => a.canSend && a.enabled !== false);- if (!account) throw new ServerError('Connect a Gmail account to send update emails', { status: 400, code: 'NO_MESSAGE_ACCOUNT' });+ const account = pickEmailSenderAccount(accounts);+ if (!account) throw new ServerError('Connect a Gmail or Outlook account to send update emails', { status: 400, code: 'NO_MESSAGE_ACCOUNT' });const oldRecord = await getVaultRecord(event.vaultRecordId);const newReveal = await revealValue(event.replacementRecordId);@@ -362,7 +363,7 @@ export async function draftUpdateEmail(eventId, orgId) {subject,body,generatedBy: 'privacy-change',- sendVia: 'api',+ sendVia: sendViaForAccountType(account.type),});console.log(`📧 Drafted privacy update email for org ${orgId} (change ${eventId}, draft ${draft.id})`);return { draftId: draft.id, status: draft.status };diff --git a/server/services/privacyChanges.test.js b/server/services/privacyChanges.test.jsindex b56e832e8e..6bf2b48744 100644--- a/server/services/privacyChanges.test.js+++ b/server/services/privacyChanges.test.js@@ -43,6 +43,7 @@ const {const privacyVault = await import('./privacyVault.js');const privacyOrgs = await import('./privacyOrgs.js');const messageAccounts = await import('./messageAccounts.js');+const messageDrafts = await import('./messageDrafts.js');beforeEach(() => {queryMock.mockReset();@@ -278,6 +279,21 @@ describe('draftUpdateEmail', () => {expect(privacyVault.revealValue).not.toHaveBeenCalled();});+ it('drafts over the chosen account\'s real transport and never from a Teams chat', async () => {+ queryMock.mockImplementation(async (sql) => {+ if (/FROM privacy_change_events WHERE id/.test(sql)) return { rows: [eventRow()] };+ throw new Error(`unexpected query: ${sql}`);+ });+ messageAccounts.listAccounts.mockResolvedValueOnce([+ { id: 'teams-1', type: 'teams', canSend: true, name: 'Chat' },+ { id: 'outlook-1', type: 'outlook', canSend: true, name: 'Work' }+ ]);+ await draftUpdateEmail('ev1', 'o1');+ expect(messageDrafts.createDraft).toHaveBeenLastCalledWith(expect.objectContaining({ accountId: 'outlook-1', sendVia: 'playwright' }));+ messageAccounts.listAccounts.mockResolvedValueOnce([{ id: 'teams-1', type: 'teams', canSend: true, name: 'Chat' }]);+ await expect(draftUpdateEmail('ev1', 'o1')).rejects.toMatchObject({ code: 'NO_MESSAGE_ACCOUNT' });+ });+it('creates an UNAPPROVED draft (status draft) to the org contact email', async () => {queryMock.mockImplementation(async (sql) => {if (/FROM privacy_change_events WHERE id/.test(sql)) return { rows: [eventRow()] };diff --git a/server/services/privacyOptOut.db.test.js b/server/services/privacyOptOut.db.test.jsindex 19fcb476cc..4364cc7110 100644--- a/server/services/privacyOptOut.db.test.js+++ b/server/services/privacyOptOut.db.test.js@@ -100,7 +100,7 @@ describe.skipIf(!runDb)('privacy opt-out engine DB round-trip', () => {draftApprover: async () => { throw new Error('Unsupported account must not approve'); },sender: async () => { throw new Error('Unsupported account must not send'); },});- expect(res).toMatchObject({ outcome: 'account_required', nextAction: 'Connect a Gmail account to send opt-out emails' });+ expect(res).toMatchObject({ outcome: 'account_required', nextAction: 'Connect a Gmail or Outlook account to send opt-out emails' });expect(drafts).toHaveLength(draftCount);expect((await brokers.getCaseForBroker(emailBrokerId)).state).toBe('found');});diff --git a/server/services/privacyOptOut.js b/server/services/privacyOptOut.jsindex f541bc2596..60c21ec7c9 100644--- a/server/services/privacyOptOut.js+++ b/server/services/privacyOptOut.js@@ -51,6 +51,7 @@ import {import { listScanEligibleValues } from './privacyVault.js';import { buildSearchVectors, probeBroker } from './privacyScan.js';import { createDraft, approveDraft } from './messageDrafts.js';+import { pickEmailSenderAccount, sendViaForAccountType } from '../lib/messageTransport.js';import { listAccounts } from './messageAccounts.js';import { getMessages } from './messageSync.js';import { getSettings } from './settings.js';@@ -332,10 +333,10 @@ export async function emailLane(broker, kase, {return { caseId: kase.id, lane: 'email', outcome: 'human_task_queued' };}const accounts = await accountsProvider();- const account = accounts.find((a) => a.canSend && a.enabled !== false);+ const account = pickEmailSenderAccount(accounts);if (!account) {return { caseId: kase.id, lane: 'email', outcome: 'account_required',- nextAction: 'Connect a Gmail account to send opt-out emails' };+ nextAction: 'Connect a Gmail or Outlook account to send opt-out emails' };}const { subject, body, templateName } = await renderOptOutEmail({ broker, payload, disclosedFields, listingUrls, now });const draft = await draftCreator({@@ -344,7 +345,7 @@ export async function emailLane(broker, kase, {subject,body,generatedBy: 'privacy-optout',- sendVia: 'api',+ sendVia: sendViaForAccountType(account.type), // the account's real transport, not an assumed Gmail API});await transitionCase(kase.id, 'optout_in_progress', { channel: 'email', disclosedFields, evidence: { lane: 'email', to, template: templateName, draftId: draft.id, disclosed: disclosedFields }, now });diff --git a/server/services/privacyOptOut.test.js b/server/services/privacyOptOut.test.jsindex 92746a455f..49e90d1979 100644--- a/server/services/privacyOptOut.test.js+++ b/server/services/privacyOptOut.test.js@@ -217,6 +217,19 @@ describe('emailLane', () => {expect(sender).toHaveBeenCalledWith('draft-1');expect(res.sent).toBe(true);});+ it.each([+ ['an Outlook account drafts over the browser transport', [{ id: 'outlook-1', type: 'outlook', canSend: true }], 'outlook-1', 'playwright'],+ ['Gmail is preferred over a browser-delivered account', [{ id: 'outlook-1', type: 'outlook', canSend: true }, { id: 'gmail-1', type: 'gmail', canSend: true }], 'gmail-1', 'api']+ ])('%s', async (_label, accounts, accountId, sendVia) => {+ await emailLane(broker, { id: 'c1' }, { disclosedFields: ['full_name', 'email'], payload, accountsProvider: async () => accounts });+ expect(createDraft).toHaveBeenCalledWith(expect.objectContaining({ accountId, sendVia }));+ });+ it('never drafts a broker email from a Teams chat', async () => {+ createDraft.mockClear();+ const res = await emailLane(broker, { id: 'c1' }, { disclosedFields: ['full_name', 'email'], payload, accountsProvider: async () => [{ id: 'teams-1', type: 'teams', canSend: true }] });+ expect(res).toMatchObject({ outcome: 'account_required' });+ expect(createDraft).not.toHaveBeenCalled();+ });it('queues a human task when the broker has no email', async () => {const res = await emailLane({ id: 'x', optout: {} }, { id: 'c1' }, { disclosedFields: ['full_name'], payload });expect(res.outcome).toBe('human_task_queued');