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): per-inbox management in multi-inbox settings (#3661)
gbirman02a01e326d12
diff --git a/js/app/packages/app/component/settings/Account.tsx b/js/app/packages/app/component/settings/Account.tsxindex b973ae59f3..331d1dd35d 100644--- a/js/app/packages/app/component/settings/Account.tsx+++ b/js/app/packages/app/component/settings/Account.tsx@@ -6,7 +6,7 @@ import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { toast } from '@core/component/Toast/Toast';import { staticFileIdEndpoint } from '@core/constant/servers';import { createStaticFile } from '@core/util/create';-import { Dialog, Button, Panel } from '@ui';+import { Dialog, Button, Panel, Tooltip } from '@ui';import {blockNameToFileExtensions,blockNameToMimeTypes,@@ -16,6 +16,7 @@ import {DEV_MODE_ENV,ENABLE_AUTO_UPDATE_UI,ENABLE_EMAIL,+ ENABLE_INBOX_RESYNC,ENABLE_MULTI_INBOX,ENABLE_PROFILE_PICTURES,ENABLE_NEW_PRICING_OVERRIDE,@@ -29,13 +30,21 @@ import {} from '@core/signal/profilePicture';import IconUpload from '@phosphor-icons/core/regular/upload-simple.svg?component-solid';import SignOutIcon from '@phosphor-icons/core/regular/sign-out.svg?component-solid';+import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';+import ArrowsClockwiseIcon from '@phosphor-icons/core/regular/arrows-clockwise.svg?component-solid';+import PlusIcon from '@phosphor-icons/core/regular/plus.svg?component-solid';import { authServiceClient } from '@service-auth/client';+import type {+ Link as EmailLink,+ SyncStatus,+} from '@service-email/generated/schemas';import { useEmail, useLicenseStatus, useUserId } from '@core/context/user';import {createEffect,createMemo,createResource,createSignal,+ For,type JSX,Match,Show,@@ -125,7 +134,32 @@ export function Account() {const [showDeleteModal, setShowDeleteModal] = createSignal<boolean>(false);const [showDeleteConfirmModal, setShowDeleteConfirmModal] = createSignal<boolean>(false);- const { disconnect: disconnectEmail } = useEmailLinks();+ const {+ query: emailLinksQuery,+ disconnect: disconnectEmail,+ removeInbox,+ resyncInbox,+ } = useEmailLinks();+ const [removeTarget, setRemoveTarget] = createSignal<{+ id: string;+ email: string;+ isOwn: boolean;+ } | null>(null);+ const [resyncingIds, setResyncingIds] = createSignal<ReadonlySet<string>>(+ new Set()+ );++ // The primary inbox is the one matching the account email; it sorts to the top+ // and is labelled. Everything else (other own inboxes + delegated/shared) follows.+ const inboxes = createMemo(() => {+ const links = emailLinksQuery.data?.links ?? [];+ const primaryEmail = email()?.toLowerCase();+ const primary = links.find(+ (link) => link.email_address.toLowerCase() === primaryEmail+ );+ const others = links.filter((link) => link !== primary);+ return { primary, others };+ });const userTeamsQuery = useUserTeamsQuery();const ownedTeam = createMemo(() => {@@ -162,6 +196,39 @@ export function Account() {}};+ const handleResyncInbox = async (linkId: string) => {+ setResyncingIds((prev) => new Set(prev).add(linkId));+ await resyncInbox(linkId).match(+ (res) => {+ toast.success(+ res.already_in_progress ? 'Sync already in progress' : 'Re-sync started'+ );+ },+ () => toast.failure('Failed to start re-sync')+ );+ setResyncingIds((prev) => {+ const next = new Set(prev);+ next.delete(linkId);+ return next;+ });+ };++ const handleRemoveInbox = async () => {+ const target = removeTarget();+ if (!target) return;+ setRemoveTarget(null);+ await removeInbox(target.id).match(+ () => {+ toast.success(+ target.isOwn+ ? 'Inbox removed — clearing its data, this may take a moment.'+ : 'Inbox removed.'+ );+ },+ () => toast.failure('Failed to remove inbox. Please try again.')+ );+ };+const [githubLinkExists, { refetch: refetchGithubLink }] = createResource(async () => {const response = await authServiceClient.checkLinkExists({ idp_name: 'github' });return response.isOk() ? response.value.link_exists : false;@@ -339,31 +406,25 @@ export function Account() {<BundleUpdateRow /></Show>- <Show when={ENABLE_EMAIL && (!emailActive() || DEV_MODE_ENV)}>+ <Show+ when={+ ENABLE_EMAIL &&+ !ENABLE_MULTI_INBOX &&+ (!emailActive() || DEV_MODE_ENV)+ }+ ><Row label="Email"><Showwhen={!emailActive()}fallback={- <div class="flex items-center gap-2">- <Show when={ENABLE_MULTI_INBOX}>- <Button- variant="base"- size="sm"- depth={3}- onClick={handleAddInbox}- >- Add Inbox- </Button>- </Show>- <Button- variant="base"- size="sm"- depth={3}- onClick={() => setShowEmailModal(true)}- >- Disable- </Button>- </div>+ <Button+ variant="base"+ size="sm"+ depth={3}+ onClick={() => setShowEmailModal(true)}+ >+ Disable+ </Button>}><Show when={!showEnableEmailModal()}>@@ -380,6 +441,92 @@ export function Account() {</Row></Show>+ <Show when={ENABLE_EMAIL && ENABLE_MULTI_INBOX}>+ <div class="bg-surface">+ <div class="flex items-center justify-between h-15.25 px-6">+ <div class="text-sm">Inboxes</div>+ <Show+ when={!emailLinksQuery.isLoading}+ fallback={+ <span class="text-sm text-ink-muted">Loading…</span>+ }+ >+ <Show+ when={emailActive()}+ fallback={+ <Show when={!showEnableEmailModal()}>+ <Button+ variant="base"+ size="sm"+ depth={3}+ onClick={() => setShowEnableEmailModal(true)}+ >+ Enable+ </Button>+ </Show>+ }+ >+ <Tooltip label="Add inbox">+ <Button+ variant="base"+ size="sm"+ depth={3}+ onClick={handleAddInbox}+ aria-label="Add inbox"+ >+ <PlusIcon class="size-4" />+ </Button>+ </Tooltip>+ </Show>+ </Show>+ </div>+ <Show when={emailActive()}>+ <Show when={inboxes().primary}>+ {(primary) => (+ <InboxRow+ link={primary()}+ isPrimary+ isOwn={primary().macro_id === userId()}+ resyncing={resyncingIds().has(primary().id)}+ onResync={() => handleResyncInbox(primary().id)}+ onRemove={() =>+ setRemoveTarget({+ id: primary().id,+ email: primary().email_address,+ isOwn: primary().macro_id === userId(),+ })+ }+ />+ )}+ </Show>+ <Show when={!inboxes().primary && email()}>+ <DisabledPrimaryRow+ email={email() ?? ''}+ onEnable={() => setShowEnableEmailModal(true)}+ />+ </Show>+ <For each={inboxes().others}>+ {(link) => (+ <InboxRow+ link={link}+ isPrimary={false}+ isOwn={link.macro_id === userId()}+ resyncing={resyncingIds().has(link.id)}+ onResync={() => handleResyncInbox(link.id)}+ onRemove={() =>+ setRemoveTarget({+ id: link.id,+ email: link.email_address,+ isOwn: link.macro_id === userId(),+ })+ }+ />+ )}+ </For>+ </Show>+ </div>+ </Show>+<Row label="GitHub"><Showwhen={!githubLinkExists.loading}@@ -492,6 +639,56 @@ export function Account() {</div></Show>+ <Dialog+ open={removeTarget() !== null}+ onOpenChange={(open) => {+ if (!open) setRemoveTarget(null);+ }}+ 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">+ Remove 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">+ <Show+ when={removeTarget()?.isOwn}+ fallback={+ <>+ Remove access to{' '}+ <span class="text-ink">{removeTarget()?.email}</span>?+ The inbox and its data stay with its owner.+ </>+ }+ >++ Remove{' '}+ <span class="text-ink">{removeTarget()?.email}</span>?+ This clears all of its email data from Macro and cannot be+ undone.++ </Show>+ </Dialog.Description>+ <div class="pt-3 justify-end items-center gap-3 inline-flex">+ <Button+ variant="base"+ depth={3}+ onClick={() => setRemoveTarget(null)}+ >+ Cancel+ </Button>+ <Button variant="danger" depth={3} onClick={handleRemoveInbox}>+ Remove+ </Button>+ </div>+ </Panel.Body>+ </Panel>+ </Dialog>+<Show when={isNativeMobilePlatform()}><div class="border-t border-edge pt-4"><Button variant="danger" depth={3} onClick={() => setShowDeleteModal(true)}>@@ -574,6 +771,113 @@ function Row(props: { label: string; children?: any }) {);}+function syncStatusLabel(status: SyncStatus): string {+ switch (status) {+ case 'SYNCING':+ return 'Syncing…';+ case 'UP_TO_DATE':+ return 'Up to date';+ case 'ERROR':+ return 'Error — re-sync';+ case 'INACTIVE':+ return 'Disabled';+ }+}++function Chip(props: { label: string }) {+ return (+ <span class="shrink-0 rounded bg-edge-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-ink-muted">+ {props.label}+ </span>+ );+}++// Placeholder shown when the account's primary inbox has been removed but other+// inboxes remain. It is not a real link — re-enabling re-runs the Gmail enable+// flow, which re-links and backfills.+function DisabledPrimaryRow(props: { email: string; onEnable: () => void }) {+ return (+ <div class="bg-surface flex items-center justify-between gap-3 h-15.25 px-6">+ <div class="min-w-0 flex flex-col gap-0.5">+ <div class="flex items-center gap-2 min-w-0">+ <span class="ph-no-capture text-sm truncate text-ink-muted">+ {props.email}+ </span>+ <Chip label="Primary" />+ <Chip label="Disabled" />+ </div>+ <span class="text-xs text-ink-muted">Sync disabled</span>+ </div>+ <Button variant="base" size="sm" depth={3} onClick={props.onEnable}>+ Enable+ </Button>+ </div>+ );+}++function InboxRow(props: {+ link: EmailLink;+ isPrimary: boolean;+ isOwn: boolean;+ resyncing: boolean;+ onResync: () => void;+ onRemove: () => void;+}) {+ return (+ <div class="bg-surface flex items-center justify-between gap-3 h-15.25 px-6">+ <div class="min-w-0 flex flex-col gap-0.5">+ <div class="flex items-center gap-2 min-w-0">+ <span class="ph-no-capture text-sm truncate">+ {props.link.email_address}+ </span>+ <Show when={props.isPrimary}>+ <Chip label="Primary" />+ </Show>+ <Show when={!props.isPrimary && !props.isOwn}>+ <Chip label="Shared" />+ </Show>+ </div>+ <span+ class="text-xs"+ classList={{+ 'text-failure': props.link.sync_status === 'ERROR',+ 'text-ink-muted': props.link.sync_status !== 'ERROR',+ }}+ >+ {syncStatusLabel(props.link.sync_status)}+ </span>+ </div>+ <div class="flex items-center gap-2 shrink-0">+ <Show when={ENABLE_INBOX_RESYNC}>+ <Tooltip label="Force sync">+ <Button+ variant="base"+ size="sm"+ depth={3}+ disabled={props.resyncing || props.link.sync_status === 'SYNCING'}+ onClick={props.onResync}+ aria-label={`Force sync ${props.link.email_address}`}+ >+ <ArrowsClockwiseIcon class="size-4" />+ </Button>+ </Tooltip>+ </Show>+ <Tooltip label="Remove inbox">+ <Button+ variant="base"+ size="sm"+ depth={3}+ onClick={props.onRemove}+ aria-label={`Remove ${props.link.email_address}`}+ >+ <XIcon class="size-4" />+ </Button>+ </Tooltip>+ </div>+ </div>+ );+}+function NameInput(props: {value?: string;placeholder?: string;diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.tsindex e7972fde3e..9086be632f 100644--- a/js/app/packages/core/constant/featureFlags.ts+++ b/js/app/packages/core/constant/featureFlags.ts@@ -241,6 +241,11 @@ export const ENABLE_MULTI_INBOX = resolveFeatureFlag(DEV_MODE_ENV);+export const ENABLE_INBOX_RESYNC = resolveFeatureFlag(+ 'ENABLE_INBOX_RESYNC',+ false+);+const _ENABLE_TASKS_TABS = resolveFeatureFlag('ENABLE_TASKS_TABS', true);export const ENABLE_EMAIL_SHARING = resolveFeatureFlag(diff --git a/js/app/packages/core/email-link/index.ts b/js/app/packages/core/email-link/index.tsindex 863191f185..fa9598e20d 100644--- a/js/app/packages/core/email-link/index.ts+++ b/js/app/packages/core/email-link/index.ts@@ -9,7 +9,10 @@ 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 type { ListLinksResponse } from '@service-email/generated/schemas';+import type {+ ListLinksResponse,+ ResyncResponse,+} from '@service-email/generated/schemas';import type { UseQueryResult } from '@tanstack/solid-query';import { err, okAsync, ResultAsync } from 'neverthrow';import { createMemo, createSignal } from 'solid-js';@@ -113,6 +116,36 @@ function disconnectEmail(): ResultAsync<void, 'failed-to-disconnect'> {);}+/**+ * Removes a linked inbox. For an owned inbox the backend cascades the full+ * teardown; for a delegated inbox it only drops the delegation edge.+ *+ * @returns ok if the inbox was removed, err if it failed+ */+function removeInbox(linkId: string): ResultAsync<void, 'failed-to-remove'> {+ return ResultAsync.fromSafePromise(+ emailClient.deleteLink({ linkId })+ ).andThen((response) =>+ response.isErr() ? err('failed-to-remove') : okAsync(void 0)+ );+}++/**+ * Enqueues a fresh backfill for a linked inbox. Idempotent on the backend: a+ * no-op when a backfill is already in progress.+ *+ * @returns ok with the resync response, err if it failed+ */+function resyncInbox(+ linkId: string+): ResultAsync<ResyncResponse, 'failed-to-resync'> {+ return ResultAsync.fromSafePromise(+ emailClient.resyncLink({ linkId })+ ).andThen((response) =>+ response.isErr() ? err('failed-to-resync') : okAsync(response.value)+ );+}+/*** Connects to the email service and authenticates with email permissions.*@@ -164,6 +197,9 @@ export function useEmailLinks() {.map(startEmailPolling).andTee(invalidations),disconnect: () => disconnectEmail().andTee(invalidations),+ removeInbox: (linkId: string) => removeInbox(linkId).andTee(invalidations),+ resyncInbox: (linkId: string) =>+ resyncInbox(linkId).andTee(() => invalidateEmailLinks()),invalidate: () => invalidateEmailLinks(),refetchInterval: emailRefetchInterval,};diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.tsindex 7ccfeba92e..86f2e5cd23 100644--- a/js/app/packages/service-clients/service-email/client.ts+++ b/js/app/packages/service-clients/service-email/client.ts@@ -19,6 +19,7 @@ import type {ListEmailFiltersResponse,ListLabelsResponse,ListLinksResponse,+ ResyncResponse,SendMessageRequest,SendMessageResponse,UpdateLabelBatchRequest,@@ -211,6 +212,30 @@ export const emailClient = {).map((result) => result);},+ async deleteLink(args: { linkId: string }) {+ const { linkId } = args;+ return (+ await emailFetch<EmptyResponse>(+ `/email/links/${encodeURIComponent(linkId)}`,+ {+ method: 'DELETE',+ }+ )+ ).map((result) => result);+ },++ async resyncLink(args: { linkId: string }) {+ const { linkId } = args;+ return (+ await emailFetch<ResyncResponse>(+ `/email/links/${encodeURIComponent(linkId)}/resync`,+ {+ method: 'POST',+ }+ )+ ).map((result) => result);+ },+async listContacts() {return (await emailFetch<ListContactsResponse>('/email/contacts', {diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.tsindex e019fde301..4d0959647d 100644--- a/js/app/packages/service-clients/service-email/generated/client.ts+++ b/js/app/packages/service-clients/service-email/generated/client.ts@@ -40,6 +40,7 @@ import type {PatchSettingsRequest,PatchSettingsResponse,PreviewsInboxCursorParams,+ ResyncResponse,SendMessageRequest,SendMessageResponse,UnblockSenderRequest,@@ -1753,6 +1754,145 @@ export const listLinks = async (} as listLinksResponse;};+/**+ * For an inbox the caller owns this enqueues a full cascade teardown+(`LinkManagerMessage::DeleteLink`). For an inbox reached via delegation it+only drops the `macro_user_links` edge, leaving the owner's data intact.+ * @summary Removes a linked inbox.+ */+export type deleteLinkResponse204 = {+ data: EmptyResponse;+ status: 204;+};++export type deleteLinkResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type deleteLinkResponse403 = {+ data: ErrorResponse;+ status: 403;+};++export type deleteLinkResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type deleteLinkResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type deleteLinkResponseSuccess = deleteLinkResponse204 & {+ headers: Headers;+};+export type deleteLinkResponseError = (+ | deleteLinkResponse401+ | deleteLinkResponse403+ | deleteLinkResponse404+ | deleteLinkResponse500+) & {+ headers: Headers;+};++export type deleteLinkResponse =+ | deleteLinkResponseSuccess+ | deleteLinkResponseError;++export const getDeleteLinkUrl = (linkId: string) => {+ return `/email/links/${linkId}`;+};++export const deleteLink = async (+ linkId: string,+ options?: RequestInit+): Promise<deleteLinkResponse> => {+ const res = await fetch(getDeleteLinkUrl(linkId), {+ ...options,+ method: 'DELETE',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: deleteLinkResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as deleteLinkResponse;+};++/**+ * Idempotent: if a backfill is already `Init`/`InProgress` for the inbox this is+a no-op and returns that job.+ * @summary Re-syncs a linked inbox by enqueuing a fresh backfill.+ */+export type resyncLinkResponse200 = {+ data: ResyncResponse;+ status: 200;+};++export type resyncLinkResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type resyncLinkResponse403 = {+ data: ErrorResponse;+ status: 403;+};++export type resyncLinkResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type resyncLinkResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type resyncLinkResponseSuccess = resyncLinkResponse200 & {+ headers: Headers;+};+export type resyncLinkResponseError = (+ | resyncLinkResponse401+ | resyncLinkResponse403+ | resyncLinkResponse404+ | resyncLinkResponse500+) & {+ headers: Headers;+};++export type resyncLinkResponse =+ | resyncLinkResponseSuccess+ | resyncLinkResponseError;++export const getResyncLinkUrl = (linkId: string) => {+ return `/email/links/${linkId}/resync`;+};++export const resyncLink = async (+ linkId: string,+ options?: RequestInit+): Promise<resyncLinkResponse> => {+ const res = await fetch(getResyncLinkUrl(linkId), {+ ...options,+ method: 'POST',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: resyncLinkResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as resyncLinkResponse;+};+/*** @summary Send a message.*/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 0bc64427b4..4bfa012e37 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@@ -222,10 +222,12 @@ export * from './patchSettingsResponse';export * from './previewsInboxCursorParams';export * from './previewView';export * from './previewViewStandardLabel';+export * from './resyncResponse';export * from './sendMessageRequest';export * from './sendMessageResponse';export * from './settings';export * from './settingsSignatureOnRepliesForwards';+export * from './syncStatus';export * from './thread';export * from './threadLatestInboundMessageTs';export * from './threadLatestNonSpamMessageTs';diff --git a/js/app/packages/service-clients/service-email/generated/schemas/link.ts b/js/app/packages/service-clients/service-email/generated/schemas/link.tsindex b205fa5832..aa22e6d985 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/link.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/link.ts@@ -7,6 +7,7 @@import type { LinkSignature } from './linkSignature';import type { Settings } from './settings';+import type { SyncStatus } from './syncStatus';import type { UserProvider } from './userProvider';export interface Link {@@ -19,5 +20,6 @@ export interface Link {provider: UserProvider;settings: Settings;signature?: LinkSignature;+ sync_status: SyncStatus;updated_at: string;}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/resyncResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/resyncResponse.tsnew file mode 100644index 0000000000..3ec9044f97--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/resyncResponse.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The response returned from the resync endpoint.+ */+export interface ResyncResponse {+ /** True when a backfill was already running and this call was a no-op. */+ already_in_progress: boolean;+ /** The backfill job driving the (re-)sync. Either the freshly enqueued job or+the one already in progress. */+ backfill_job_id: string;+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/syncStatus.ts b/js/app/packages/service-clients/service-email/generated/schemas/syncStatus.tsnew file mode 100644index 0000000000..8665715a7e--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/syncStatus.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Coarse sync state for an inbox, used to render a one-line hint in the+multi-inbox settings list. Derived from the link's `is_sync_active` flag and+its most recent backfill job.+ */+export type SyncStatus = (typeof SyncStatus)[keyof typeof SyncStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const SyncStatus = {+ SYNCING: 'SYNCING',+ UP_TO_DATE: 'UP_TO_DATE',+ ERROR: 'ERROR',+ INACTIVE: 'INACTIVE',+} as const;diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex 142f47ac4d..49441748c1 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -1586,6 +1586,150 @@}}},+ "/email/links/{link_id}": {+ "delete": {+ "tags": ["Links"],+ "summary": "Removes a linked inbox.",+ "description": "For an inbox the caller owns this enqueues a full cascade teardown\n(`LinkManagerMessage::DeleteLink`). For an inbox reached via delegation it\nonly drops the `macro_user_links` edge, leaving the owner's data intact.",+ "operationId": "delete_link",+ "parameters": [+ {+ "name": "link_id",+ "in": "path",+ "description": "Inbox link ID.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EmptyResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/email/links/{link_id}/resync": {+ "post": {+ "tags": ["Links"],+ "summary": "Re-syncs a linked inbox by enqueuing a fresh backfill.",+ "description": "Idempotent: if a backfill is already `Init`/`InProgress` for the inbox this is\na no-op and returns that job.",+ "operationId": "resync_link",+ "parameters": [+ {+ "name": "link_id",+ "in": "path",+ "description": "Inbox link ID.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ResyncResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/email/messages": {"post": {"tags": ["Messages"],@@ -3993,6 +4137,7 @@"email_address","provider","is_sync_active",+ "sync_status","settings","created_at","updated_at"@@ -4027,6 +4172,9 @@"signature": {"type": ["string", "null"]},+ "sync_status": {+ "$ref": "#/components/schemas/SyncStatus"+ },"updated_at": {"type": "string","format": "date-time"@@ -4403,6 +4551,22 @@"other"]},+ "ResyncResponse": {+ "type": "object",+ "description": "The response returned from the resync endpoint.",+ "required": ["backfill_job_id", "already_in_progress"],+ "properties": {+ "already_in_progress": {+ "type": "boolean",+ "description": "True when a backfill was already running and this call was a no-op."+ },+ "backfill_job_id": {+ "type": "string",+ "format": "uuid",+ "description": "The backfill job driving the (re-)sync. Either the freshly enqueued job or\nthe one already in progress."+ }+ }+ },"SendMessageRequest": {"type": "object","description": "Request body for sending a message (backward-compatible with `{ message: MessageToSend }`).",@@ -4433,6 +4597,11 @@}}},+ "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.",+ "enum": ["SYNCING", "UP_TO_DATE", "ERROR", "INACTIVE"]+ },"Thread": {"type": "object","required": [diff --git a/rust/cloud-storage/.sqlx/query-56187151cc2545db5e5b43235d9aa3a88303c3508b7218179e27812e3cad7ec2.json b/rust/cloud-storage/.sqlx/query-56187151cc2545db5e5b43235d9aa3a88303c3508b7218179e27812e3cad7ec2.jsonnew file mode 100644index 0000000000..985e7caf0e--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-56187151cc2545db5e5b43235d9aa3a88303c3508b7218179e27812e3cad7ec2.json@@ -0,0 +1,83 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE link_id = $1\n ORDER BY created_at DESC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "fusionauth_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "threads_requested_limit",+ "type_info": "Int4"+ },+ {+ "ordinal": 4,+ "name": "total_threads",+ "type_info": "Int4"+ },+ {+ "ordinal": 5,+ "name": "threads_retrieved_count",+ "type_info": "Int4"+ },+ {+ "ordinal": 6,+ "name": "status: db::backfill::BackfillJobStatus",+ "type_info": {+ "Custom": {+ "name": "email_backfill_job_status",+ "kind": {+ "Enum": [+ "Init",+ "InProgress",+ "Complete",+ "Cancelled",+ "Failed"+ ]+ }+ }+ }+ },+ {+ "ordinal": 7,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true,+ false,+ true,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "56187151cc2545db5e5b43235d9aa3a88303c3508b7218179e27812e3cad7ec2"+}diff --git a/rust/cloud-storage/.sqlx/query-6dde3a5ced431932d021e43180e45071efd36c3088dab4feada6254bc1aa41f2.json b/rust/cloud-storage/.sqlx/query-6dde3a5ced431932d021e43180e45071efd36c3088dab4feada6254bc1aa41f2.jsonnew file mode 100644index 0000000000..b996369a66--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6dde3a5ced431932d021e43180e45071efd36c3088dab4feada6254bc1aa41f2.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS(\n SELECT 1\n FROM macro_user_links\n WHERE primary_macro_id = $1\n AND child_macro_id = $2\n ) AS \"exists!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "6dde3a5ced431932d021e43180e45071efd36c3088dab4feada6254bc1aa41f2"+}diff --git a/rust/cloud-storage/.sqlx/query-e82b920450ded09debcd219dbe7a34dbde810b6b60c8d8a0854ee49ac57a7c02.json b/rust/cloud-storage/.sqlx/query-e82b920450ded09debcd219dbe7a34dbde810b6b60c8d8a0854ee49ac57a7c02.jsonnew file mode 100644index 0000000000..4913744755--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-e82b920450ded09debcd219dbe7a34dbde810b6b60c8d8a0854ee49ac57a7c02.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM macro_user_links\n WHERE child_macro_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "e82b920450ded09debcd219dbe7a34dbde810b6b60c8d8a0854ee49ac57a7c02"+}diff --git a/rust/cloud-storage/email_db_client/src/backfill/job/get.rs b/rust/cloud-storage/email_db_client/src/backfill/job/get.rsindex 580123b94d..73c3bee550 100644--- a/rust/cloud-storage/email_db_client/src/backfill/job/get.rs+++ b/rust/cloud-storage/email_db_client/src/backfill/job/get.rs@@ -93,6 +93,39 @@ pub async fn get_active_backfill_job(Ok(record.map(Into::into))}+/// Retrieves the most recent backfill job for a link, regardless of status.+/// Used to derive the inbox sync hint shown in multi-inbox settings.+#[tracing::instrument(skip(pool), err)]+pub async fn get_latest_backfill_job_by_link_id(+ pool: &PgPool,+ link_id: Uuid,+) -> anyhow::Result<Option<service::backfill::BackfillJob>> {+ let record = sqlx::query_as!(+ db::backfill::BackfillJob,+ r#"+ SELECT+ id,+ link_id,+ fusionauth_user_id,+ threads_requested_limit,+ total_threads,+ threads_retrieved_count,+ status as "status: db::backfill::BackfillJobStatus",+ created_at,+ updated_at+ FROM email_backfill_jobs+ WHERE link_id = $1+ ORDER BY created_at DESC+ LIMIT 1+ "#,+ link_id+ )+ .fetch_optional(pool)+ .await?;++ Ok(record.map(Into::into))+}+/// Retrieves all backfill jobs created in the last 24 hours for a given macro ID#[tracing::instrument(skip(pool), err)]pub async fn get_recent_jobs_by_fusionauth_user_id(diff --git a/rust/cloud-storage/email_service/src/api/email/links/access.rs b/rust/cloud-storage/email_service/src/api/email/links/access.rsnew file mode 100644index 0000000000..4c8a42faa7--- /dev/null+++ b/rust/cloud-storage/email_service/src/api/email/links/access.rs@@ -0,0 +1,85 @@+use crate::api::context::ApiContext;+use axum::http::StatusCode;+use axum::response::{IntoResponse, Json, Response};+use model::response::ErrorResponse;+use models_email::service::link::Link;+use thiserror::Error;+use uuid::Uuid;++/// How a caller is allowed to act on an inbox.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum InboxAccess {+ /// The caller owns the inbox (`link.macro_id == caller`).+ Own,+ /// The caller reaches the inbox through a `macro_user_links` edge.+ Delegated,+}++/// Error shared by the per-inbox action handlers (delete, resync). Carries+/// `Display` so handlers can be instrumented with `err`.+#[derive(Debug, Error)]+pub enum InboxActionError {+ #[error("inbox not found")]+ NotFound,++ #[error("not authorized for this inbox")]+ Forbidden,++ #[error(transparent)]+ Internal(#[from] anyhow::Error),+}++impl IntoResponse for InboxActionError {+ fn into_response(self) -> Response {+ let status = match &self {+ InboxActionError::NotFound => StatusCode::NOT_FOUND,+ InboxActionError::Forbidden => StatusCode::FORBIDDEN,+ InboxActionError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ let message = match &self {+ InboxActionError::Internal(_) => "internal error".to_string(),+ other => other.to_string(),+ };++ (+ status,+ Json(ErrorResponse {+ message: message.into(),+ }),+ )+ .into_response()+ }+}++/// Resolves the link by id and authorizes the caller against it.+///+/// Returns the link together with how the caller may act on it: [`InboxActionError::NotFound`]+/// when the link does not exist and [`InboxActionError::Forbidden`] when the caller+/// has neither ownership nor a delegation edge.+pub async fn authorize_inbox_access(+ ctx: &ApiContext,+ caller_macro_id: &str,+ link_id: Uuid,+) -> Result<(Link, InboxAccess), InboxActionError> {+ let link = email_db_client::links::get::fetch_link_by_id(&ctx.db, link_id)+ .await?+ .ok_or(InboxActionError::NotFound)?;++ if link.macro_id.as_ref() == caller_macro_id {+ return Ok((link, InboxAccess::Own));+ }++ let delegated = macro_db_client::macro_user_links::edge_exists(+ &ctx.db,+ caller_macro_id,+ link.macro_id.as_ref(),+ )+ .await?;++ if delegated {+ Ok((link, InboxAccess::Delegated))+ } else {+ Err(InboxActionError::Forbidden)+ }+}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.rsnew file mode 100644index 0000000000..8dbf52b70e--- /dev/null+++ b/rust/cloud-storage/email_service/src/api/email/links/delete.rs@@ -0,0 +1,66 @@+use crate::api::context::ApiContext;+use crate::api::email::links::access::{InboxAccess, InboxActionError, authorize_inbox_access};+use anyhow::Context;+use axum::Extension;+use axum::extract::{Path, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use model::response::{EmptyResponse, ErrorResponse};+use model::user::UserContext;+use models_email::email::service::pubsub::{DeletionReason, LinkManagerMessage};+use uuid::Uuid;++/// Removes a linked inbox.+///+/// For an inbox the caller owns this enqueues a full cascade teardown+/// (`LinkManagerMessage::DeleteLink`). For an inbox reached via delegation it+/// only drops the `macro_user_links` edge, leaving the owner's data intact.+#[utoipa::path(+ delete,+ tag = "Links",+ path = "/email/links/{link_id}",+ operation_id = "delete_link",+ params(+ ("link_id" = Uuid, Path, description = "Inbox link ID."),+ ),+ responses(+ (status = 204, body=EmptyResponse),+ (status = 401, body=ErrorResponse),+ (status = 403, body=ErrorResponse),+ (status = 404, body=ErrorResponse),+ (status = 500, body=ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]+pub async fn delete_link_handler(+ State(ctx): State<ApiContext>,+ user_context: Extension<UserContext>,+ Path(link_id): Path<Uuid>,+) -> Result<Response, InboxActionError> {+ let (link, access) = authorize_inbox_access(&ctx, &user_context.user_id, link_id).await?;++ match access {+ InboxAccess::Own => {+ let message = LinkManagerMessage::DeleteLink {+ link_id: link.id,+ deletion_reason: DeletionReason::ManuallyDisabled,+ };++ ctx.sqs_client+ .enqueue_link_manager_notification(message)+ .await+ .context("failed to enqueue delete notification")?;+ }+ InboxAccess::Delegated => {+ macro_db_client::macro_user_links::delete_edge(+ &ctx.db,+ &user_context.user_id,+ link.macro_id.as_ref(),+ )+ .await+ .context("failed to delete delegation edge")?;+ }+ }++ Ok(StatusCode::NO_CONTENT.into_response())+}diff --git a/rust/cloud-storage/email_service/src/api/email/links/list.rs b/rust/cloud-storage/email_service/src/api/email/links/list.rsindex 8faf18b0ac..390a20d7ee 100644--- a/rust/cloud-storage/email_service/src/api/email/links/list.rs+++ b/rust/cloud-storage/email_service/src/api/email/links/list.rs@@ -82,6 +82,17 @@ pub async fn list_links_handler(.await.map_err(ListLinksError::DatabaseError)?;+ let latest_job =+ email_db_client::backfill::job::get::get_latest_backfill_job_by_link_id(+ &ctx.db, link.id,+ )+ .await+ .map_err(ListLinksError::DatabaseError)?;+ let sync_status = api::link::SyncStatus::derive(+ link.is_sync_active,+ latest_job.map(|job| job.status),+ );+let signature = if query_params.include_signature {let access_token = fetch_gmail_access_token_from_link(&link,@@ -103,6 +114,7 @@ pub async fn list_links_handler(link,signature,api::settings::Settings::from(settings),+ sync_status,))}});diff --git a/rust/cloud-storage/email_service/src/api/email/links/mod.rs b/rust/cloud-storage/email_service/src/api/email/links/mod.rsindex a79059d7f7..6eb4469850 100644--- a/rust/cloud-storage/email_service/src/api/email/links/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/links/mod.rs@@ -1,9 +1,15 @@+pub(crate) mod access;+pub(crate) mod delete;pub(crate) mod list;+pub(crate) mod resync;use crate::api::ApiContext;use axum::Router;-use axum::routing::get;+use axum::routing::{delete, get, post};pub fn router() -> Router<ApiContext> {- Router::new().route("/", get(list::list_links_handler))+ Router::new()+ .route("/", get(list::list_links_handler))+ .route("/{link_id}", delete(delete::delete_link_handler))+ .route("/{link_id}/resync", post(resync::resync_link_handler))}diff --git a/rust/cloud-storage/email_service/src/api/email/links/resync.rs b/rust/cloud-storage/email_service/src/api/email/links/resync.rsnew file mode 100644index 0000000000..26250ce059--- /dev/null+++ b/rust/cloud-storage/email_service/src/api/email/links/resync.rs@@ -0,0 +1,105 @@+use crate::api::context::ApiContext;+use crate::api::email::links::access::{InboxActionError, authorize_inbox_access};+use anyhow::Context;+use axum::Extension;+use axum::extract::{Path, State};+use axum::response::{IntoResponse, Json, Response};+use model::response::ErrorResponse;+use model::user::UserContext;+use models_email::email::service::backfill::{+ BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, InitPayload, JobScopedPayload,+};+use utoipa::ToSchema;+use uuid::Uuid;++/// The response returned from the resync endpoint.+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct ResyncResponse {+ /// The backfill job driving the (re-)sync. Either the freshly enqueued job or+ /// the one already in progress.+ pub backfill_job_id: Uuid,+ /// True when a backfill was already running and this call was a no-op.+ pub already_in_progress: bool,+}++/// Re-syncs a linked inbox by enqueuing a fresh backfill.+///+/// Idempotent: if a backfill is already `Init`/`InProgress` for the inbox this is+/// a no-op and returns that job.+#[utoipa::path(+ post,+ tag = "Links",+ path = "/email/links/{link_id}/resync",+ operation_id = "resync_link",+ params(+ ("link_id" = Uuid, Path, description = "Inbox link ID."),+ ),+ responses(+ (status = 200, body=ResyncResponse),+ (status = 401, body=ErrorResponse),+ (status = 403, body=ErrorResponse),+ (status = 404, body=ErrorResponse),+ (status = 500, body=ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]+pub async fn resync_link_handler(+ State(ctx): State<ApiContext>,+ user_context: Extension<UserContext>,+ Path(link_id): Path<Uuid>,+) -> Result<Response, InboxActionError> {+ let (link, _access) = authorize_inbox_access(&ctx, &user_context.user_id, link_id).await?;++ if let Some(active) =+ email_db_client::backfill::job::get::get_active_backfill_job(&ctx.db, link.id)+ .await+ .context("failed to check active backfill job")?+ {+ return Ok(Json(ResyncResponse {+ backfill_job_id: active.id,+ already_in_progress: true,+ })+ .into_response());+ }++ let backfill_job = email_db_client::backfill::job::insert::create_backfill_job(+ &ctx.db,+ link.id,+ link.fusionauth_user_id.as_str(),+ None,+ )+ .await+ .context("failed to create backfill job")?;++ let ps_message = BackfillPubsubMessage {+ backfill_operation: BackfillOperation::Init(JobScopedPayload {+ link_id: link.id,+ job_id: backfill_job.id,+ payload: InitPayload {},+ }),+ };++ if let Err(e) = ctx+ .sqs_client+ .enqueue_email_backfill_message(ps_message)+ .await+ {+ if let Err(update_err) = email_db_client::backfill::job::update::update_backfill_job_status(+ &ctx.db,+ backfill_job.id,+ BackfillJobStatus::Failed,+ )+ .await+ {+ tracing::error!(error=?update_err, backfill_id=%backfill_job.id, "failed to mark backfill job failed");+ }++ return Err(e.context("failed to enqueue backfill message").into());+ }++ Ok(Json(ResyncResponse {+ backfill_job_id: backfill_job.id,+ already_in_progress: false,+ })+ .into_response())+}diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rsindex 8c8dad468f..b9c6edd241 100644--- a/rust/cloud-storage/email_service/src/api/swagger.rs+++ b/rust/cloud-storage/email_service/src/api/swagger.rs@@ -16,6 +16,7 @@ use crate::api::email::init::InitResponse;use crate::api::email::labels::create::CreateLabelRequest;use crate::api::email::labels::create::CreateLabelResponse;use crate::api::email::links::list::ListLinksResponse;+use crate::api::email::links::resync::ResyncResponse;use crate::api::email::messages::labels::{UpdateLabelBatchRequest, UpdateLabelBatchResponse};use crate::api::email::settings::patch::{PatchSettingsRequest, PatchSettingsResponse};use crate::api::email::threads::archived::ArchiveThreadRequest;@@ -39,6 +40,7 @@ use ::email::inbound::axum::thread_project_router::{UpdateThreadProjectRequest, UpdateThreadProjectResponse,};use model::response::EmptyResponse;+use models_email::api::link::SyncStatus;use models_email::api::settings::Settings;use models_email::email::service;use models_email::email::service::address::ContactInfoWithInteraction;@@ -84,6 +86,8 @@ use utoipa::OpenApi;inbound::axum::get_thread_router::get_thread_handler,inbound::axum::thread_project_router::update_thread_project_handler,email::links::list::list_links_handler,+ email::links::delete::delete_link_handler,+ email::links::resync::resync_link_handler,email::labels::create::handler,email::labels::delete::handler,inbound::axum::list_labels_router::list_labels_handler,@@ -148,6 +152,8 @@ use utoipa::OpenApi;// Link typesListLinksResponse,Link,+ SyncStatus,+ ResyncResponse,Settings,// Contact typesListContactsResponse,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 a8da34302c..3cbeded2e2 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@@ -263,6 +263,30 @@ async fn handle_delete(tracing::error!(error=?e, link_id=?link.id, "Failed to set deleted_at on email link history");}+ // If this was the owner's last inbox, prune any delegation edges pointing at+ // them so grantees don't retain dangling references. A delegation edge grants+ // access to all of the owner's inboxes, so only clean up once none remain.+ // Best-effort: leftover edges are harmless (they resolve to nothing).+ match email_db_client::links::get::fetch_link_by_macro_id(&ctx.db, link.macro_id.as_ref()).await+ {+ Ok(None) => {+ if let Err(e) = macro_db_client::macro_user_links::delete_edges_for_child(+ &ctx.db,+ link.macro_id.as_ref(),+ )+ .await+ {+ tracing::error!(error=?e, "Failed to prune delegation edges after deleting owner's last inbox");+ }+ }+ Ok(Some(_)) => {+ tracing::debug!("Owner has remaining inboxes; keeping delegation edges");+ }+ Err(e) => {+ tracing::error!(error=?e, "Failed to check remaining inboxes for delegation edge cleanup");+ }+ }+tracing::info!("Successfully deleted link");Ok(())diff --git a/rust/cloud-storage/macro_db_client/src/macro_user_links.rs b/rust/cloud-storage/macro_db_client/src/macro_user_links.rsindex b5f3a9d20f..a922d2bfd4 100644--- a/rust/cloud-storage/macro_db_client/src/macro_user_links.rs+++ b/rust/cloud-storage/macro_db_client/src/macro_user_links.rs@@ -52,6 +52,53 @@ pub async fn delete_edge(Ok(())}+/// Removes every edge granting access to `child_macro_id`'s inboxes. Used when a+/// macro user's last inbox is torn down so dangling delegation edges don't linger.+/// Returns the number of edges removed.+#[tracing::instrument(skip(db), err)]+pub async fn delete_edges_for_child(+ db: &Pool<Postgres>,+ child_macro_id: &str,+) -> anyhow::Result<u64> {+ let result = sqlx::query!(+ r#"+ DELETE FROM macro_user_links+ WHERE child_macro_id = $1+ "#,+ child_macro_id,+ )+ .execute(db)+ .await?;++ Ok(result.rows_affected())+}++/// Returns whether the edge `(primary, child)` exists. Used to authorize a+/// primary macro user acting on an inbox delegated to them.+#[tracing::instrument(skip(db), err)]+pub async fn edge_exists(+ db: &Pool<Postgres>,+ primary_macro_id: &str,+ child_macro_id: &str,+) -> anyhow::Result<bool> {+ let exists = sqlx::query_scalar!(+ r#"+ SELECT EXISTS(+ SELECT 1+ FROM macro_user_links+ WHERE primary_macro_id = $1+ AND child_macro_id = $2+ ) AS "exists!"+ "#,+ primary_macro_id,+ child_macro_id,+ )+ .fetch_one(db)+ .await?;++ Ok(exists)+}+/// Returns the `child_macro_id`s the given primary delegates from./// Used by email-service to union linked inboxes with the user's own.#[tracing::instrument(skip(db), err)]diff --git a/rust/cloud-storage/macro_db_client/src/macro_user_links/test.rs b/rust/cloud-storage/macro_db_client/src/macro_user_links/test.rsindex 34ff486616..223e034838 100644--- a/rust/cloud-storage/macro_db_client/src/macro_user_links/test.rs+++ b/rust/cloud-storage/macro_db_client/src/macro_user_links/test.rs@@ -75,6 +75,48 @@ async fn delete_edge_removes_row(pool: Pool<Postgres>) -> anyhow::Result<()> {Ok(())}+#[sqlx::test]+async fn edge_exists_reflects_delegation(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, "macro|[email protected]").await?;+ insert_user(&pool, "macro|[email protected]").await?;++ assert!(!edge_exists(&pool, "macro|[email protected]", "macro|[email protected]").await?);++ insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;+ assert!(edge_exists(&pool, "macro|[email protected]", "macro|[email protected]").await?);++ // Direction matters: the reverse edge must not exist.+ assert!(!edge_exists(&pool, "macro|[email protected]", "macro|[email protected]").await?);++ delete_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;+ assert!(!edge_exists(&pool, "macro|[email protected]", "macro|[email protected]").await?);++ Ok(())+}++#[sqlx::test]+async fn delete_edges_for_child_removes_all_grants(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, "macro|[email protected]").await?;+ insert_user(&pool, "macro|[email protected]").await?;+ insert_user(&pool, "macro|[email protected]").await?;+ insert_user(&pool, "macro|[email protected]").await?;++ // Two primaries delegate from the same owner, plus an unrelated edge.+ insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;+ insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;+ insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;++ let removed = delete_edges_for_child(&pool, "macro|[email protected]").await?;+ assert_eq!(removed, 2);++ assert!(!edge_exists(&pool, "macro|[email protected]", "macro|[email protected]").await?);+ assert!(!edge_exists(&pool, "macro|[email protected]", "macro|[email protected]").await?);+ // The unrelated edge is untouched.+ assert!(edge_exists(&pool, "macro|[email protected]", "macro|[email protected]").await?);++ Ok(())+}+#[sqlx::test]async fn self_referential_edge_rejected(pool: Pool<Postgres>) -> anyhow::Result<()> {insert_user(&pool, "macro|[email protected]").await?;diff --git a/rust/cloud-storage/models_email/src/email/api/link.rs b/rust/cloud-storage/models_email/src/email/api/link.rsindex 9993bdd0b9..103c5c7f50 100644--- a/rust/cloud-storage/models_email/src/email/api/link.rs+++ b/rust/cloud-storage/models_email/src/email/api/link.rs@@ -1,11 +1,44 @@use crate::api::settings::Settings;use crate::service;+use crate::service::backfill::BackfillJobStatus;use chrono::{DateTime, Utc};use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};use serde::{Deserialize, Serialize};use utoipa::ToSchema;use uuid::Uuid;+/// Coarse sync state for an inbox, used to render a one-line hint in the+/// multi-inbox settings list. Derived from the link's `is_sync_active` flag and+/// its most recent backfill job.+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, ToSchema)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum SyncStatus {+ /// A backfill is queued or running.+ Syncing,+ /// The inbox finished backfilling and is actively syncing.+ UpToDate,+ /// The most recent backfill failed; the user can re-sync to recover.+ Error,+ /// Syncing has been turned off for this inbox.+ Inactive,+}++impl SyncStatus {+ /// Derives the sync status from the link's active flag and the status of its+ /// most recent backfill job (if any).+ pub fn derive(is_sync_active: bool, latest_job_status: Option<BackfillJobStatus>) -> Self {+ if !is_sync_active {+ return SyncStatus::Inactive;+ }++ match latest_job_status {+ Some(BackfillJobStatus::Init | BackfillJobStatus::InProgress) => SyncStatus::Syncing,+ Some(BackfillJobStatus::Failed | BackfillJobStatus::Cancelled) => SyncStatus::Error,+ Some(BackfillJobStatus::Complete) | None => SyncStatus::UpToDate,+ }+ }+}+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, ToSchema)]#[serde(rename_all = "UPPERCASE")]pub enum UserProvider {@@ -44,6 +77,7 @@ pub struct Link {pub email_address: EmailStr<'static>,pub provider: UserProvider,pub is_sync_active: bool,+ pub sync_status: SyncStatus,pub signature: Option<String>,pub settings: Settings,pub created_at: DateTime<Utc>,@@ -51,7 +85,12 @@ pub struct Link {}impl Link {- pub fn new(source: service::link::Link, signature: Option<String>, settings: Settings) -> Self {+ pub fn new(+ source: service::link::Link,+ signature: Option<String>,+ settings: Settings,+ sync_status: SyncStatus,+ ) -> Self {Link {id: source.id,macro_id: source.macro_id,@@ -59,6 +98,7 @@ impl Link {email_address: source.email_address,provider: UserProvider::from(source.provider),is_sync_active: source.is_sync_active,+ sync_status,signature,settings,created_at: source.created_at,