Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): dedup external mailboxes shared by multiple users (#3910)
gbirmanfdb99d019488
diff --git a/js/app/packages/app/component/EmailAuth.tsx b/js/app/packages/app/component/EmailAuth.tsxindex 13288ca509..1df104a70f 100644--- a/js/app/packages/app/component/EmailAuth.tsx+++ b/js/app/packages/app/component/EmailAuth.tsx@@ -7,7 +7,8 @@ import { useEmailLinks } from '@core/email-link';import { whenSettled } from '@core/util/whenSettled';import { invalidateAllAfterLogin } from '@queries/auth/user-info';import { useNavigate, useSearchParams } from '@solidjs/router';-import { onMount, Suspense } from 'solid-js';+import { Button, Dialog, Panel } from '@ui';+import { createSignal, onMount, Show, Suspense } from 'solid-js';type EmailAuthParams = {callbackPath: string;@@ -98,11 +99,47 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {const navigate = useNavigate();const [searchParams] = useSearchParams();const { query, initEmailLink } = useEmailLinks();+ const [conflict, setConflict] = createSignal<{+ linkId: string;+ emailAddress: string;+ ownerEmail: string;+ } | null>(null);const navigateToSuccess = () => {navigate(props.successPath, { replace: true });};+ const runInit = async (linkId: string, forceShare: boolean) => {+ await initEmailLink({ linkId, forceShare }).match(+ async () => {+ // Pull the newly-provisioned link into the cache before leaving the+ // callback so the inbox panel shows it immediately on return rather+ // than flashing a stale list until its own refetch lands.+ await query.refetch();+ toast.success('Inbox connected');+ navigateToSuccess();+ },+ (err) => {+ if (err.tag === 'AlreadyInitialized') {+ navigateToSuccess();+ return;+ }+ // The mailbox is already connected by someone else. Hold the callback open+ // and let the user confirm sharing it before retrying with forceShare.+ if (err.tag === 'SharedInboxConflict' && !forceShare) {+ setConflict({+ linkId,+ emailAddress: err.emailAddress,+ ownerEmail: err.ownerEmail,+ });+ return;+ }+ toast.failure('Failed to add inbox');+ navigateToSuccess();+ }+ );+ };+whenSettled(query,async () => {@@ -114,24 +151,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {return;}- await initEmailLink({ linkId }).match(- async () => {- // Pull the newly-provisioned link into the cache before leaving the- // callback so the inbox panel shows it immediately on return rather- // than flashing a stale list until its own refetch lands.- await query.refetch();- toast.success('Inbox connected');- navigateToSuccess();- },- (err) => {- if (err.tag === 'AlreadyInitialized') {- navigateToSuccess();- return;- }- toast.failure('Failed to add inbox');- navigateToSuccess();- }- );+ await runInit(linkId, false);},(error) => {toast.failure(error.message);@@ -139,7 +159,62 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {});- return <LoadingBlock />;+ return (+ <Show when={conflict()} fallback={<LoadingBlock />}>+ {(c) => (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open) {+ setConflict(null);+ navigateToSuccess();+ }+ }}+ position="center"+ class="w-120"+ >+ <Panel active depth={2} class="rounded-xl">+ <Panel.Header class="px-6">+ <Dialog.Title class="text-ink text-sm font-semibold">+ Share this inbox?+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="p-6 font-sans flex flex-col gap-3">+ <Dialog.Description class="text-ink-muted text-sm/tight font-normal">+ <span class="text-ink">{c().emailAddress}</span> is already+ connected by <span class="text-ink">{c().ownerEmail}</span>.+ Share it so you both manage one inbox instead of syncing a+ duplicate copy.+ </Dialog.Description>+ <div class="pt-3 justify-end items-center gap-3 inline-flex">+ <Button+ variant="base"+ depth={3}+ onClick={() => {+ setConflict(null);+ navigateToSuccess();+ }}+ >+ Cancel+ </Button>+ <Button+ variant="active"+ depth={3}+ onClick={() => {+ const linkId = c().linkId;+ setConflict(null);+ void runInit(linkId, true);+ }}+ >+ Share inbox+ </Button>+ </div>+ </Panel.Body>+ </Panel>+ </Dialog>+ )}+ </Show>+ );}function EmailSignUp(diff --git a/js/app/packages/core/email-link/index.ts b/js/app/packages/core/email-link/index.tsindex dd96dcaaf3..e163519b9f 100644--- a/js/app/packages/core/email-link/index.ts+++ b/js/app/packages/core/email-link/index.ts@@ -8,7 +8,7 @@ import { openEmailAuthPopup } from '@core/auth/email';import { invalidateUserInfo } from '@queries/auth/user-info';import { invalidateEmailLinks, useEmailLinksQuery } from '@queries/email/link';-import { emailClient } from '@service-email/client';+import { emailClient, SHARED_INBOX_CONFLICT_CODE } from '@service-email/client';import type {ListLinksResponse,ResyncResponse,@@ -38,8 +38,28 @@ export function useEmailLinksStatus() {type EmailInitError =/** The email link has already been initialized*/| { tag: 'AlreadyInitialized' }+ /** The mailbox is already connected by another user; confirm to share it. */+ | { tag: 'SharedInboxConflict'; emailAddress: string; ownerEmail: string }| { tag: 'FailedToInitialize'; message: string };+function parseSharedInboxConflict(message: string): {+ emailAddress: string;+ ownerEmail: string;+} {+ try {+ const parsed = JSON.parse(message) as {+ emailAddress?: string;+ existingOwnerEmail?: string;+ };+ return {+ emailAddress: parsed.emailAddress ?? '',+ ownerEmail: parsed.existingOwnerEmail ?? '',+ };+ } catch {+ return { emailAddress: '', ownerEmail: '' };+ }+}+/*** Calls email service to start syncing and initialize a new email link.*@@ -47,29 +67,39 @@ type EmailInitError =* read the `in_progress_user_link` row and provision a second `email_links` scoped to* that linked email. Omit for the first-time signup path.*+ * Pass `forceShare` to confirm promoting a mailbox another user already connected into+ * a shared inbox, after the user accepts the `SharedInboxConflict` prompt.+ ** @returns ok if syncing was started, err if syncing failed*/function initEmailLink(args?: {linkId?: string;+ forceShare?: boolean;}): ResultAsync<void, EmailInitError> {return ResultAsync.fromSafePromise(- emailClient.init({ linkId: args?.linkId })+ emailClient.init({ linkId: args?.linkId, forceShare: args?.forceShare })).andThen((initResult) => {if (initResult.isErr()) {+ const conflict = initResult.error.find(+ (e) => e.code === SHARED_INBOX_CONFLICT_CODE+ );+ if (conflict) {+ const conflictError: EmailInitError = {+ tag: 'SharedInboxConflict',+ ...parseSharedInboxConflict(conflict.message),+ };+ return err<void, EmailInitError>(conflictError);+ }const badRequestError = initResult.error.find(// TODO: this is cope but seems like error.code not being set correctly(e) => e.message.includes('400'));- return err(- badRequestError- ? { tag: 'AlreadyInitialized' as const }- : {- tag: 'FailedToInitialize' as const,- message: 'Failed to initialize',- }- );+ const error: EmailInitError = badRequestError+ ? { tag: 'AlreadyInitialized' }+ : { tag: 'FailedToInitialize', message: 'Failed to initialize' };+ return err<void, EmailInitError>(error);}- return okAsync(undefined);+ return okAsync<void, EmailInitError>(undefined);});}@@ -175,7 +205,7 @@ export function useEmailLinks() {return {query: query,isConnected: () => hasEmailLinks(query),- initEmailLink: (args?: { linkId?: string }) =>+ initEmailLink: (args?: { linkId?: string; forceShare?: boolean }) =>initEmailLink(args).map(startEmailPolling).map(invalidations),connect: () =>connectEmail()diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.tsindex f9133856d9..27d3b1fcc6 100644--- a/js/app/packages/service-clients/service-email/client.ts+++ b/js/app/packages/service-clients/service-email/client.ts@@ -22,6 +22,7 @@ import type {ResyncResponse,SendMessageRequest,SendMessageResponse,+ SharedInboxConflictResponse,UpdateLabelBatchRequest,UpdateLabelBatchResponse,UpdateThreadLabelRequest,@@ -62,16 +63,47 @@ function emailFetch<T extends ObjectLike = never>(return fetchWithToken<T>(`${emailHost}${url}`, init);}+/**+ * Error code `init` returns when the target mailbox is already connected by another+ * macro user. The caller confirms with the user, then retries with `forceShare`.+ */+export const SHARED_INBOX_CONFLICT_CODE = 'SHARED_INBOX_CONFLICT' as const;+export const emailClient = {- async init(args?: { linkId?: string }) {- const path = args?.linkId- ? `/email/init?link_id=${encodeURIComponent(args.linkId)}`- : '/email/init';- return (- await emailFetch<EmptyResponse>(path, {+ async init(args?: { linkId?: string; forceShare?: boolean }) {+ const params = new URLSearchParams();+ if (args?.linkId) params.set('link_id', args.linkId);+ if (args?.forceShare) params.set('force_share', 'true');+ const query = params.toString();+ const path = query ? `/email/init?${query}` : '/email/init';++ return fetchWithToken<EmptyResponse, typeof SHARED_INBOX_CONFLICT_CODE>(+ `${emailHost}${path}`,+ {method: 'POST',- })- ).map((result) => result);+ // A custom handler replaces safeFetch's default status mapping, so non-409+ // statuses fall back to the same HTTP_ERROR shape callers already branch on.+ errorResponseHandler: async (response) => {+ if (response.status === 409) {+ const body = (await response+ .json()+ .catch(() => null)) as SharedInboxConflictResponse | null;+ return {+ code: SHARED_INBOX_CONFLICT_CODE,+ // The caller formats the prompt; the fields it needs ride along as JSON.+ message: JSON.stringify({+ emailAddress: body?.email_address ?? '',+ existingOwnerEmail: body?.existing_owner_email ?? '',+ }),+ };+ }+ return {+ code: 'HTTP_ERROR',+ message: `HTTP error! status: ${response.status}`,+ };+ },+ }+ );},async getThread(args: {offset?: number;diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.tsindex 61eaea6f8d..5953eca7c3 100644--- a/js/app/packages/service-clients/service-email/generated/client.ts+++ b/js/app/packages/service-clients/service-email/generated/client.ts@@ -43,6 +43,7 @@ import type {ResyncResponse,SendMessageRequest,SendMessageResponse,+ SharedInboxConflictResponse,UnblockSenderRequest,UpdateLabelBatchRequest,UpdateLabelBatchResponse,@@ -1436,6 +1437,11 @@ export type initUserResponse401 = {status: 401;};+export type initUserResponse409 = {+ data: SharedInboxConflictResponse;+ status: 409;+};+export type initUserResponse500 = {data: ErrorResponse;status: 500;@@ -1447,6 +1453,7 @@ export type initUserResponseSuccess = initUserResponse200 & {export type initUserResponseError = (| initUserResponse400| initUserResponse401+ | initUserResponse409| initUserResponse500) & {headers: Headers;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.tsindex 1765357cca..0af8f97dc6 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts@@ -228,6 +228,7 @@ export * from './sendMessageRequest';export * from './sendMessageResponse';export * from './settings';export * from './settingsSignatureOnRepliesForwards';+export * from './sharedInboxConflictResponse';export * from './syncStatus';export * from './thread';export * from './threadLatestInboundMessageTs';diff --git a/js/app/packages/service-clients/service-email/generated/schemas/initUserParams.ts b/js/app/packages/service-clients/service-email/generated/schemas/initUserParams.tsindex 6ba2ba7388..c6cd36a62b 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/initUserParams.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/initUserParams.ts@@ -10,4 +10,8 @@ export type InitUserParams = {* **OPTIONAL**. The in_progress_user_link id from a /link/gmail flow.*/link_id?: string;+ /**+ * **OPTIONAL**. Confirms promoting a mailbox already connected by another user into a shared inbox.+ */+ force_share?: boolean;};diff --git a/js/app/packages/service-clients/service-email/generated/schemas/sharedInboxConflictResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/sharedInboxConflictResponse.tsnew file mode 100644index 0000000000..c2aecaf88b--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/sharedInboxConflictResponse.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Returned with a `409 Conflict` when a connect targets an external mailbox another+macro user has already connected. The client surfaces a confirmation; on confirm it+retries `/email/init` with `force_share=true` to promote the mailbox to a shared inbox.+ */+export interface SharedInboxConflictResponse {+ /** The mailbox address that is already connected. */+ email_address: string;+ /** The existing link that would be shared if the caller confirms. */+ existing_link_id: string;+ /** The email of the macro user who first connected the mailbox. */+ existing_owner_email: string;+}diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex 084fb47066..1f04f95320 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -1293,6 +1293,15 @@"type": "string","format": "uuid"}+ },+ {+ "name": "force_share",+ "in": "query",+ "description": "**OPTIONAL**. Confirms promoting a mailbox already connected by another user into a shared inbox.",+ "required": false,+ "schema": {+ "type": "boolean"+ }}],"responses": {@@ -1326,6 +1335,16 @@}}},+ "409": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SharedInboxConflictResponse"+ }+ }+ }+ },"500": {"description": "","content": {@@ -4600,6 +4619,30 @@}}},+ "SharedInboxConflictResponse": {+ "type": "object",+ "description": "Returned with a `409 Conflict` when a connect targets an external mailbox another\nmacro user has already connected. The client surfaces a confirmation; on confirm it\nretries `/email/init` with `force_share=true` to promote the mailbox to a shared inbox.",+ "required": [+ "email_address",+ "existing_owner_email",+ "existing_link_id"+ ],+ "properties": {+ "email_address": {+ "type": "string",+ "description": "The mailbox address that is already connected."+ },+ "existing_link_id": {+ "type": "string",+ "format": "uuid",+ "description": "The existing link that would be shared if the caller confirms."+ },+ "existing_owner_email": {+ "type": "string",+ "description": "The email of the macro user who first connected the mailbox."+ }+ }+ },"SyncStatus": {"type": "string","description": "Coarse sync state for an inbox, used to render a one-line hint in the\nmulti-inbox settings list. Derived from the link's `is_sync_active` flag and\nits most recent backfill job.",diff --git a/rust/cloud-storage/.sqlx/query-0f43991b34ee9e8bb85f7a8c87ed522daaa36ef9bb9e1eed4ccca12de09f44f0.json b/rust/cloud-storage/.sqlx/query-0f43991b34ee9e8bb85f7a8c87ed522daaa36ef9bb9e1eed4ccca12de09f44f0.jsonnew file mode 100644index 0000000000..b9e67bdaa7--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-0f43991b34ee9e8bb85f7a8c87ed522daaa36ef9bb9e1eed4ccca12de09f44f0.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE email_links\n SET macro_id = $1, updated_at = NOW()\n WHERE id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "0f43991b34ee9e8bb85f7a8c87ed522daaa36ef9bb9e1eed4ccca12de09f44f0"+}diff --git a/rust/cloud-storage/.sqlx/query-1511f43c28d30141885fec9cfbc87b855ec6f10241b3e74499f22aeef7f762bc.json b/rust/cloud-storage/.sqlx/query-1511f43c28d30141885fec9cfbc87b855ec6f10241b3e74499f22aeef7f762bc.jsonnew file mode 100644index 0000000000..3b87978453--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-1511f43c28d30141885fec9cfbc87b855ec6f10241b3e74499f22aeef7f762bc.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS(\n SELECT 1 FROM promoted_shared_mailboxes WHERE macro_id = $1\n ) AS \"exists!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "1511f43c28d30141885fec9cfbc87b855ec6f10241b3e74499f22aeef7f762bc"+}diff --git a/rust/cloud-storage/.sqlx/query-601165c041981d75e53661a10ffd67a55ae4e7f2cf8bdde6ad1c834196934cf4.json b/rust/cloud-storage/.sqlx/query-601165c041981d75e53661a10ffd67a55ae4e7f2cf8bdde6ad1c834196934cf4.jsonnew file mode 100644index 0000000000..684abe4cf8--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-601165c041981d75e53661a10ffd67a55ae4e7f2cf8bdde6ad1c834196934cf4.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM macro_user WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "601165c041981d75e53661a10ffd67a55ae4e7f2cf8bdde6ad1c834196934cf4"+}diff --git a/rust/cloud-storage/.sqlx/query-7725b1095e9fdc3e8879840bf3480aae302752bce224b1e69dcb3f2a9c1cef5b.json b/rust/cloud-storage/.sqlx/query-7725b1095e9fdc3e8879840bf3480aae302752bce224b1e69dcb3f2a9c1cef5b.jsonnew file mode 100644index 0000000000..56e0353361--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-7725b1095e9fdc3e8879840bf3480aae302752bce224b1e69dcb3f2a9c1cef5b.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO macro_user_email_verification (macro_user_id, email, is_verified)\n VALUES ($1, $2, true)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "7725b1095e9fdc3e8879840bf3480aae302752bce224b1e69dcb3f2a9c1cef5b"+}diff --git a/rust/cloud-storage/.sqlx/query-893d51b6860bdb3deaf125dcb831a29eb711f46fa9f28cf211136eb4361b87bc.json b/rust/cloud-storage/.sqlx/query-893d51b6860bdb3deaf125dcb831a29eb711f46fa9f28cf211136eb4361b87bc.jsonnew file mode 100644index 0000000000..52a73057e2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-893d51b6860bdb3deaf125dcb831a29eb711f46fa9f28cf211136eb4361b87bc.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO promoted_shared_mailboxes (macro_id)\n VALUES ($1)\n ON CONFLICT (macro_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "893d51b6860bdb3deaf125dcb831a29eb711f46fa9f28cf211136eb4361b87bc"+}diff --git a/rust/cloud-storage/.sqlx/query-abd0a7a3bc1e35bfd6b0acd25aed7149fa0e81809511939a420fe17f93ae7d6e.json b/rust/cloud-storage/.sqlx/query-abd0a7a3bc1e35bfd6b0acd25aed7149fa0e81809511939a420fe17f93ae7d6e.jsonnew file mode 100644index 0000000000..0ffccf643b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-abd0a7a3bc1e35bfd6b0acd25aed7149fa0e81809511939a420fe17f93ae7d6e.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"User\" (id, email, macro_user_id, \"organizationId\")\n VALUES ($1, $2, $3, $4)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid",+ "Int4"+ ]+ },+ "nullable": []+ },+ "hash": "abd0a7a3bc1e35bfd6b0acd25aed7149fa0e81809511939a420fe17f93ae7d6e"+}diff --git a/rust/cloud-storage/.sqlx/query-c11f23488f780d7d26380775088aee0d8c1c9cf7cb28867dbdd96b7004a5d259.json b/rust/cloud-storage/.sqlx/query-c11f23488f780d7d26380775088aee0d8c1c9cf7cb28867dbdd96b7004a5d259.jsonnew file mode 100644index 0000000000..dbdf277f15--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c11f23488f780d7d26380775088aee0d8c1c9cf7cb28867dbdd96b7004a5d259.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM \"User\"\n WHERE id = $1\n AND EXISTS (SELECT 1 FROM promoted_shared_mailboxes WHERE macro_id = $1)\n RETURNING macro_user_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "macro_user_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "c11f23488f780d7d26380775088aee0d8c1c9cf7cb28867dbdd96b7004a5d259"+}diff --git a/rust/cloud-storage/.sqlx/query-f3fe8a220414038b0f4ebd8fbf0a6842bf271ef6cb2e4de41b820113295ca18d.json b/rust/cloud-storage/.sqlx/query-f3fe8a220414038b0f4ebd8fbf0a6842bf271ef6cb2e4de41b820113295ca18d.jsonnew file mode 100644index 0000000000..a902d75da9--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-f3fe8a220414038b0f4ebd8fbf0a6842bf271ef6cb2e4de41b820113295ca18d.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO macro_user (id, username, email, stripe_customer_id)\n VALUES ($1, $2, $3, $4)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "f3fe8a220414038b0f4ebd8fbf0a6842bf271ef6cb2e4de41b820113295ca18d"+}diff --git a/rust/cloud-storage/email_db_client/src/links/get/test.rs b/rust/cloud-storage/email_db_client/src/links/get/test.rsindex 6027911416..da762d04e7 100644--- a/rust/cloud-storage/email_db_client/src/links/get/test.rs+++ b/rust/cloud-storage/email_db_client/src/links/get/test.rs@@ -1,5 +1,8 @@-use crate::links::get::{fetch_owned_link_for_message, fetch_owned_link_for_thread};+use crate::links::get::{+ fetch_link_by_email, fetch_owned_link_for_message, fetch_owned_link_for_thread,+};use macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_email::service::link::UserProvider;use sqlx::types::Uuid;use sqlx::{Pool, Postgres};@@ -157,3 +160,34 @@ async fn resolves_nothing_for_unrelated_caller(pool: Pool<Postgres>) -> anyhow::Ok(())}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_link_by_email_finds_link_owned_by_another_macro_user(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // A shared external mailbox connected by one macro user as a data-source link+ // (owner's macro_id, mailbox email). A second user connecting the same mailbox+ // discovers it across all macro_ids — the trigger for the 409 / shared-inbox promote.+ insert_user(&pool, CHILD, "[email protected]").await;+ let (link_id, _, _) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;++ let found = fetch_link_by_email(&pool, "[email protected]", UserProvider::Gmail).await?;+ assert_eq!(+ found.map(|l| (l.id, l.macro_id.as_ref().to_string())),+ Some((link_id, CHILD.to_string()))+ );++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_link_by_email_none_when_mailbox_unconnected(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // No link for this mailbox → connect takes the plain data-source path, no dedup.+ let found = fetch_link_by_email(&pool, "[email protected]", UserProvider::Gmail).await?;+ assert!(found.is_none());++ Ok(())+}diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rsindex ecf1999c1d..fe8ed45376 100644--- a/rust/cloud-storage/email_service/src/api/email/init.rs+++ b/rust/cloud-storage/email_service/src/api/email/init.rs@@ -46,6 +46,13 @@ pub enum InitError {#[error("Invalid input")]Parse(#[from] macro_user_id::error::ParseErr),++ #[error("Inbox is already connected by another user")]+ SharedInboxConflict {+ email_address: String,+ existing_owner_email: String,+ existing_link_id: Uuid,+ },}impl IntoResponse for InitError {@@ -58,12 +65,41 @@ impl IntoResponse for InitError {InitError::EnqueueError | InitError::DatabaseError(_) | InitError::GmailError(_) => {StatusCode::INTERNAL_SERVER_ERROR}+ InitError::SharedInboxConflict { .. } => StatusCode::CONFLICT,};- (status_code, self.to_string()).into_response()+ match self {+ InitError::SharedInboxConflict {+ email_address,+ existing_owner_email,+ existing_link_id,+ } => (+ status_code,+ Json(SharedInboxConflictResponse {+ email_address,+ existing_owner_email,+ existing_link_id,+ }),+ )+ .into_response(),+ other => (status_code, other.to_string()).into_response(),+ }}}+/// Returned with a `409 Conflict` when a connect targets an external mailbox another+/// macro user has already connected. The client surfaces a confirmation; on confirm it+/// retries `/email/init` with `force_share=true` to promote the mailbox to a shared inbox.+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct SharedInboxConflictResponse {+ /// The mailbox address that is already connected.+ pub email_address: String,+ /// The email of the macro user who first connected the mailbox.+ pub existing_owner_email: String,+ /// The existing link that would be shared if the caller confirms.+ pub existing_link_id: Uuid,+}+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]pub struct InitResponse {/// The email_links row id for the now-accessible inbox. For cross-user delegation@@ -82,6 +118,10 @@ pub struct InitParams {/// Optional link id from a `/link/gmail` flow. When set, init provisions the inbox/// for the email recorded on the in_progress_user_link row instead of the JWT email.link_id: Option<Uuid>,+ /// When set, a connect that collides with a mailbox already connected by another+ /// macro user promotes it to a shared inbox instead of returning a 409 conflict.+ #[serde(default)]+ force_share: bool,}/// Initialize email functionality for the user. Populates initial threads and enables inbox syncing.@@ -91,19 +131,24 @@ pub struct InitParams {path = "/email/init",params(("link_id" = Option<Uuid>, Query, description = "**OPTIONAL**. The in_progress_user_link id from a /link/gmail flow."),+ ("force_share" = Option<bool>, Query, description = "**OPTIONAL**. Confirms promoting a mailbox already connected by another user into a shared inbox."),),operation_id = "init_user",responses((status = 200, body=InitResponse),(status = 400, body=ErrorResponse),(status = 401, body=ErrorResponse),+ (status = 409, body=SharedInboxConflictResponse),(status = 500, body=ErrorResponse),))]#[tracing::instrument(skip(ctx, user_extractor), fields(user_id=user_extractor.user_context.user_id, fusionauth_user_id=user_extractor.user_context.fusion_user_id), err)]pub async fn handler(State(ctx): State<ApiContext>,- Query(InitParams { link_id }): Query<InitParams>,+ Query(InitParams {+ link_id,+ force_share,+ }): Query<InitParams>,user_extractor: MacroUserExtractor,) -> Result<Response, InitError> {let MacroUserExtractor {@@ -270,6 +315,75 @@ pub async fn handler(return Err(InitError::AlreadyInitialized);}+ // The linked email is not itself a macro user, but another macro user may+ // already have connected this exact mailbox as a data-source link. Connecting+ // it again would store and sync a second copy of the same mailbox. Instead,+ // promote the single existing link to a shared macro user so both connectors+ // delegate over one link. Promotion turns the mailbox into a shared user, so+ // it is gated behind an explicit `force_share` confirmation.+ if existing_owner.is_none()+ && let Some(existing_link) = email_db_client::links::get::fetch_link_by_email(+ &ctx.db,+ &linked_email,+ link::UserProvider::Gmail,+ )+ .await+ .context("Failed to look up existing link for shared-mailbox dedup")?+ && existing_link.macro_id.as_ref() != user_context.user_id.as_str()+ {+ if !force_share {+ return Err(InitError::SharedInboxConflict {+ email_address: linked_email.clone(),+ existing_owner_email: existing_link.macro_id.email_str().to_string(),+ existing_link_id: existing_link.id,+ });+ }++ let organization_id =+ macro_db_client::user::get_user_organization::get_user_organization(+ ctx.db.clone(),+ existing_link.macro_id.as_ref(),+ )+ .await+ .context("Failed to fetch organization for shared-inbox owner")?;++ let mut tx = ctx+ .db+ .begin()+ .await+ .context("Failed to begin shared-inbox promotion transaction")?;++ let promoted = macro_db_client::shared_inbox::promote_link_to_shared(+ &mut tx,+ existing_link.id,+ existing_link.macro_id.as_ref(),+ &user_context.user_id,+ &linked_email,+ organization_id,+ )+ .await+ .context("Failed to promote link to shared inbox")?;++ macro_db_client::in_progress_user_link::delete_in_progress_user_link(+ &mut *tx, &link_id,+ )+ .await+ .context("Failed to delete in_progress_user_link after shared-inbox promotion")?;++ tx.commit()+ .await+ .context("Failed to commit shared-inbox promotion transaction")?;++ return Ok((+ StatusCode::OK,+ Json(InitResponse {+ link_id: promoted.link_id,+ backfill_job_id: None,+ }),+ )+ .into_response());+ }+let gmail_token =fetch_gmail_token_for_email(&ctx, &user_context.fusion_user_id, &linked_email).await?;diff --git a/rust/cloud-storage/email_service/src/api/email/links/delete.rs b/rust/cloud-storage/email_service/src/api/email/links/delete.rsindex 8dbf52b70e..9f5aab727e 100644--- a/rust/cloud-storage/email_service/src/api/email/links/delete.rs+++ b/rust/cloud-storage/email_service/src/api/email/links/delete.rs@@ -59,6 +59,40 @@ pub async fn delete_link_handler().await.context("failed to delete delegation edge")?;++ // A promoted shared mailbox has no human owner — it lives only through its+ // delegation edges. When the last delegate leaves, tear the mailbox down so it+ // doesn't linger as an orphaned link + minted user that nobody can reach.+ let remaining = macro_db_client::macro_user_links::get_primaries_for_child(+ &ctx.db,+ link.macro_id.as_ref(),+ )+ .await+ .context("failed to count remaining shared-inbox delegates")?;++ if remaining.is_empty() {+ let mut conn = ctx+ .db+ .acquire()+ .await+ .context("failed to acquire connection")?;+ let is_promoted = macro_db_client::shared_inbox::is_promoted_shared_mailbox(+ &mut conn,+ link.macro_id.as_ref(),+ )+ .await+ .context("failed to check promoted shared mailbox")?;++ if is_promoted {+ ctx.sqs_client+ .enqueue_link_manager_notification(LinkManagerMessage::DeleteLink {+ link_id: link.id,+ deletion_reason: DeletionReason::ManuallyDisabled,+ })+ .await+ .context("failed to enqueue shared-inbox teardown")?;+ }+ }}}diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rsindex b9c6edd241..dba86a07ee 100644--- a/rust/cloud-storage/email_service/src/api/swagger.rs+++ b/rust/cloud-storage/email_service/src/api/swagger.rs@@ -12,7 +12,7 @@ use crate::api::email::drafts::add_attachment::{use crate::api::email::drafts::add_forwarded_attachment::{AddForwardedAttachmentRequest, AddForwardedAttachmentResponse,};-use crate::api::email::init::InitResponse;+use crate::api::email::init::{InitResponse, SharedInboxConflictResponse};use crate::api::email::labels::create::CreateLabelRequest;use crate::api::email::labels::create::CreateLabelResponse;use crate::api::email::links::list::ListLinksResponse;@@ -121,6 +121,7 @@ use utoipa::OpenApi;AddForwardedAttachmentResponse,// Init typesInitResponse,+ SharedInboxConflictResponse,// Label typesCreateLabelRequest,CreateLabelResponse,diff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rsindex 00324f3f5c..6e648d61d4 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs@@ -286,6 +286,25 @@ async fn handle_delete(}}+ // If the deleted link was a promoted shared mailbox, remove its minted macro user too+ // (this also cascades its delegation edges and the promoted-mailbox marker). No-op for+ // ordinary inboxes; best-effort, since the link and its data are already gone.+ match ctx.db.acquire().await {+ Ok(mut conn) => {+ if let Err(e) = macro_db_client::shared_inbox::delete_promoted_mailbox_user(+ &mut conn,+ link.macro_id.as_ref(),+ )+ .await+ {+ tracing::error!(error=?e, "Failed to delete minted user for promoted shared mailbox");+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "Failed to acquire connection for promoted mailbox cleanup");+ }+ }+tracing::info!("Successfully deleted link");Ok(())diff --git a/rust/cloud-storage/macro_db_client/migrations/20260609223922_promoted_shared_mailboxes.sql b/rust/cloud-storage/macro_db_client/migrations/20260609223922_promoted_shared_mailboxes.sqlnew file mode 100644index 0000000000..ba9e02ee91--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260609223922_promoted_shared_mailboxes.sql@@ -0,0 +1,8 @@+-- Marks macro_ids minted by shared-inbox promotion: a mailbox that several macro users+-- connected, with no human who logs in as it directly. Distinguishes these from real+-- accounts someone was delegated to (which a delegate leaving must NOT delete), so the+-- last delegate removing access can tear the mailbox down instead of orphaning it.+CREATE TABLE IF NOT EXISTS promoted_shared_mailboxes (+ macro_id TEXT NOT NULL PRIMARY KEY REFERENCES "User"("id") ON DELETE CASCADE,+ created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP+);diff --git a/rust/cloud-storage/macro_db_client/src/lib.rs b/rust/cloud-storage/macro_db_client/src/lib.rsindex b2498f7ab7..40225f8bb6 100644--- a/rust/cloud-storage/macro_db_client/src/lib.rs+++ b/rust/cloud-storage/macro_db_client/src/lib.rs@@ -34,6 +34,7 @@ pub mod projects;pub mod recents;pub mod share_on_mention;pub mod share_permission;+pub mod shared_inbox;#[cfg(feature = "team")]pub mod team;pub mod user;diff --git a/rust/cloud-storage/macro_db_client/src/shared_inbox.rs b/rust/cloud-storage/macro_db_client/src/shared_inbox.rsnew file mode 100644index 0000000000..82f62e3e62--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/shared_inbox.rs@@ -0,0 +1,170 @@+//! Promotes an externally-shared mailbox to its own macro user. When a second macro+//! user connects a mailbox that is not itself a macro account, the connect flow would+//! otherwise create a duplicate `email_links` row and sync the same mailbox twice.+//! Instead we mint a dedicated macro user for the mailbox, re-home the single existing+//! link onto it, and grant both connectors access via `macro_user_links` edges.++use sqlx::types::Uuid;++#[cfg(test)]+mod test;++/// Outcome of promoting a duplicated external mailbox to a shared macro user.+pub struct PromotedSharedInbox {+ /// The macro_id minted for the mailbox. The re-homed link and both edges point at it.+ pub mailbox_macro_id: String,+ /// The surviving (re-homed) `email_links` row — its id is unchanged, so the one+ /// synced copy and its history are preserved.+ pub link_id: Uuid,+}++/// Mints a dedicated macro user for `mailbox_email`, re-homes `existing_link_id` onto it,+/// and grants both the original owner and the new connector access via `macro_user_links`+/// edges. Because the minted macro_id embeds the mailbox email, the re-homed link's email+/// matches its macro_id — i.e. it is no longer an inbox-only secondary but a shared user.+///+/// Runs on a caller-provided connection so the mint, re-home, and edge inserts commit+/// atomically with the rest of the connect flow.+#[tracing::instrument(skip(conn), err)]+pub async fn promote_link_to_shared(+ conn: &mut sqlx::PgConnection,+ existing_link_id: Uuid,+ original_owner_macro_id: &str,+ new_connector_macro_id: &str,+ mailbox_email: &str,+ organization_id: Option<i32>,+) -> anyhow::Result<PromotedSharedInbox> {+ let mailbox_macro_id = format!("macro|{mailbox_email}");+ let fusionauth_user_id = macro_uuid::generate_uuid_v7();+ let stripe_customer_id = format!("cus_shared_{fusionauth_user_id}");++ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $4)+ "#,+ &fusionauth_user_id,+ &mailbox_macro_id,+ mailbox_email,+ stripe_customer_id,+ )+ .execute(&mut *conn)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO macro_user_email_verification (macro_user_id, email, is_verified)+ VALUES ($1, $2, true)+ "#,+ &fusionauth_user_id,+ mailbox_email,+ )+ .execute(&mut *conn)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "User" (id, email, macro_user_id, "organizationId")+ VALUES ($1, $2, $3, $4)+ "#,+ &mailbox_macro_id,+ mailbox_email,+ &fusionauth_user_id,+ organization_id,+ )+ .execute(&mut *conn)+ .await?;++ // Mark this macro_id as a promoted shared mailbox so teardown can distinguish it from a+ // real account: the last delegate removing access tears it down rather than orphaning it.+ sqlx::query!(+ r#"+ INSERT INTO promoted_shared_mailboxes (macro_id)+ VALUES ($1)+ ON CONFLICT (macro_id) DO NOTHING+ "#,+ &mailbox_macro_id,+ )+ .execute(&mut *conn)+ .await?;++ let rehomed = sqlx::query!(+ r#"+ UPDATE email_links+ SET macro_id = $1, updated_at = NOW()+ WHERE id = $2+ "#,+ &mailbox_macro_id,+ existing_link_id,+ )+ .execute(&mut *conn)+ .await?;++ // The link is read outside this transaction, so it may have been deleted before+ // re-homing. A zero-row update would otherwise commit a mailbox user and edges+ // with no inbox attached; abort so the caller's transaction rolls back instead.+ if rehomed.rows_affected() == 0 {+ anyhow::bail!("no email_links row {existing_link_id} to re-home; aborting promotion");+ }++ crate::macro_user_links::insert_edge(&mut *conn, original_owner_macro_id, &mailbox_macro_id)+ .await?;+ crate::macro_user_links::insert_edge(&mut *conn, new_connector_macro_id, &mailbox_macro_id)+ .await?;++ Ok(PromotedSharedInbox {+ mailbox_macro_id,+ link_id: existing_link_id,+ })+}++/// Whether `macro_id` is a mailbox minted by shared-inbox promotion (no human owner),+/// as opposed to a real account someone was delegated to.+#[tracing::instrument(skip(conn), err)]+pub async fn is_promoted_shared_mailbox(+ conn: &mut sqlx::PgConnection,+ macro_id: &str,+) -> anyhow::Result<bool> {+ let exists = sqlx::query_scalar!(+ r#"+ SELECT EXISTS(+ SELECT 1 FROM promoted_shared_mailboxes WHERE macro_id = $1+ ) AS "exists!"+ "#,+ macro_id,+ )+ .fetch_one(&mut *conn)+ .await?;++ Ok(exists)+}++/// Deletes the macro user minted for a promoted shared mailbox once its single link has+/// been torn down. Removing the `User` row cascades its `macro_user_links` edges and the+/// `promoted_shared_mailboxes` marker; the backing `macro_user` row is removed explicitly.+/// No-op when `macro_id` is not a promoted mailbox.+#[tracing::instrument(skip(conn), err)]+pub async fn delete_promoted_mailbox_user(+ conn: &mut sqlx::PgConnection,+ macro_id: &str,+) -> anyhow::Result<()> {+ let row = sqlx::query!(+ r#"+ DELETE FROM "User"+ WHERE id = $1+ AND EXISTS (SELECT 1 FROM promoted_shared_mailboxes WHERE macro_id = $1)+ RETURNING macro_user_id+ "#,+ macro_id,+ )+ .fetch_optional(&mut *conn)+ .await?;++ if let Some(row) = row {+ sqlx::query!(r#"DELETE FROM macro_user WHERE id = $1"#, row.macro_user_id)+ .execute(&mut *conn)+ .await?;+ }++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/src/shared_inbox/test.rs b/rust/cloud-storage/macro_db_client/src/shared_inbox/test.rsnew file mode 100644index 0000000000..8194e2b541--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/shared_inbox/test.rs@@ -0,0 +1,210 @@+use super::*;+use sqlx::{Pool, Postgres};++const OWNER: &str = "macro|[email protected]";+const CONNECTOR: &str = "macro|[email protected]";+const MAILBOX_EMAIL: &str = "[email protected]";++async fn insert_user(pool: &Pool<Postgres>, macro_id: &str, email: &str) {+ let macro_uuid = Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $4)"#,+ macro_uuid,+ macro_id,+ email,+ macro_id,+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,+ macro_id,+ email,+ macro_uuid,+ )+ .execute(pool)+ .await+ .unwrap();+}++/// A data-source link for `email` owned by `macro_id` (the first connector's own macro_id).+async fn insert_data_source_link(pool: &Pool<Postgres>, macro_id: &str, email: &str) -> Uuid {+ let link_id = Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)+ VALUES ($1, $2, $2, $3, 'GMAIL')"#,+ link_id,+ macro_id,+ email,+ )+ .execute(pool)+ .await+ .unwrap();+ link_id+}++#[sqlx::test]+async fn promote_dedups_to_single_link_with_two_edges(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, CONNECTOR, "[email protected]").await;+ let link_id = insert_data_source_link(&pool, OWNER, MAILBOX_EMAIL).await;++ let mut conn = pool.acquire().await?;+ let result =+ promote_link_to_shared(&mut conn, link_id, OWNER, CONNECTOR, MAILBOX_EMAIL, None).await?;++ let mailbox_macro_id = format!("macro|{MAILBOX_EMAIL}");+ assert_eq!(result.mailbox_macro_id, mailbox_macro_id);+ // The link survives in place — single synced copy, id unchanged.+ assert_eq!(result.link_id, link_id);++ // Exactly one link for the mailbox email, re-homed onto the mailbox macro_id.+ let links = sqlx::query!(+ r#"SELECT id, macro_id FROM email_links WHERE email_address = $1"#,+ MAILBOX_EMAIL+ )+ .fetch_all(&pool)+ .await?;+ assert_eq!(links.len(), 1, "must remain a single link");+ assert_eq!(links[0].id, link_id);+ assert_eq!(links[0].macro_id, mailbox_macro_id);++ // is_inbox_only is computed as `link.email != macro_id's email`. The minted macro_id+ // embeds the mailbox email, so the promoted mailbox is a real shared user, not inbox-only.+ let mailbox_user = sqlx::query!(+ r#"SELECT email FROM "User" WHERE id = $1"#,+ mailbox_macro_id+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(mailbox_user.email, MAILBOX_EMAIL);++ // Both the original owner and the new connector hold an edge to the mailbox.+ let mut primaries =+ crate::macro_user_links::get_primaries_for_child(&pool, &mailbox_macro_id).await?;+ primaries.sort();+ assert_eq!(primaries, vec![OWNER.to_string(), CONNECTOR.to_string()]);++ Ok(())+}++#[sqlx::test]+async fn promote_is_atomic_on_rollback(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, CONNECTOR, "[email protected]").await;+ let link_id = insert_data_source_link(&pool, OWNER, MAILBOX_EMAIL).await;++ let mut tx = pool.begin().await?;+ promote_link_to_shared(&mut tx, link_id, OWNER, CONNECTOR, MAILBOX_EMAIL, None).await?;+ // Drop the transaction without committing.+ drop(tx);++ // Nothing leaked: the link is still owned by the original connector and no mailbox user exists.+ let link = sqlx::query!(r#"SELECT macro_id FROM email_links WHERE id = $1"#, link_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(link.macro_id, OWNER);++ let mailbox_macro_id = format!("macro|{MAILBOX_EMAIL}");+ let mailbox_user = sqlx::query!(r#"SELECT id FROM "User" WHERE id = $1"#, mailbox_macro_id)+ .fetch_optional(&pool)+ .await?;+ assert!(mailbox_user.is_none(), "rolled-back mint must not persist");++ Ok(())+}++#[sqlx::test]+async fn promote_errors_when_link_missing(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, CONNECTOR, "[email protected]").await;++ // The link vanished between lookup and promotion (e.g. owner disconnected it).+ let missing_link_id = Uuid::new_v4();+ let mut tx = pool.begin().await?;+ let result = promote_link_to_shared(+ &mut tx,+ missing_link_id,+ OWNER,+ CONNECTOR,+ MAILBOX_EMAIL,+ None,+ )+ .await;+ drop(tx);+ assert!(+ result.is_err(),+ "promotion must fail when no link is re-homed"+ );++ // The aborted transaction left no phantom mailbox user behind.+ let mailbox_macro_id = format!("macro|{MAILBOX_EMAIL}");+ let mailbox_user = sqlx::query!(r#"SELECT id FROM "User" WHERE id = $1"#, mailbox_macro_id)+ .fetch_optional(&pool)+ .await?;+ assert!(+ mailbox_user.is_none(),+ "phantom mailbox user must not persist"+ );++ Ok(())+}++#[sqlx::test]+async fn promote_marks_mailbox_and_teardown_removes_everything(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, CONNECTOR, "[email protected]").await;+ let link_id = insert_data_source_link(&pool, OWNER, MAILBOX_EMAIL).await;++ let mut conn = pool.acquire().await?;+ promote_link_to_shared(&mut conn, link_id, OWNER, CONNECTOR, MAILBOX_EMAIL, None).await?;+ let mailbox_macro_id = format!("macro|{MAILBOX_EMAIL}");++ // Promotion marks the mailbox; a regular macro_id is not marked.+ assert!(is_promoted_shared_mailbox(&mut conn, &mailbox_macro_id).await?);+ assert!(!is_promoted_shared_mailbox(&mut conn, OWNER).await?);++ // Simulate the cascading link delete that precedes minted-user teardown, then tear down.+ sqlx::query!(r#"DELETE FROM email_links WHERE id = $1"#, link_id)+ .execute(&pool)+ .await?;+ delete_promoted_mailbox_user(&mut conn, &mailbox_macro_id).await?;++ // The minted User, its macro_user, the marker, and both edges are gone.+ let user = sqlx::query!(r#"SELECT id FROM "User" WHERE id = $1"#, mailbox_macro_id)+ .fetch_optional(&pool)+ .await?;+ assert!(user.is_none(), "minted mailbox User must be removed");+ assert!(!is_promoted_shared_mailbox(&mut conn, &mailbox_macro_id).await?);+ assert!(+ crate::macro_user_links::get_primaries_for_child(&pool, &mailbox_macro_id)+ .await?+ .is_empty(),+ "delegation edges must be cascaded away"+ );++ Ok(())+}++#[sqlx::test]+async fn delete_promoted_mailbox_user_is_noop_for_real_account(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // OWNER is a real account, not a promoted mailbox — teardown must never delete it.+ insert_user(&pool, OWNER, "[email protected]").await;++ let mut conn = pool.acquire().await?;+ delete_promoted_mailbox_user(&mut conn, OWNER).await?;++ let user = sqlx::query!(r#"SELECT id FROM "User" WHERE id = $1"#, OWNER)+ .fetch_optional(&pool)+ .await?;+ assert!(user.is_some(), "a real account must not be torn down");++ Ok(())+}