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-link sync-health tracking and reconnect surfacing (#4086)
gbirman7ac5ac895748
diff --git a/js/app/packages/app/component/GmailReauthenticationPrompt.tsx b/js/app/packages/app/component/GmailReauthenticationPrompt.tsxindex ac7b8ab9b5..f04e027d19 100644--- a/js/app/packages/app/component/GmailReauthenticationPrompt.tsx+++ b/js/app/packages/app/component/GmailReauthenticationPrompt.tsx@@ -1,65 +1,90 @@-import { emailAuthUrl } from '@core/auth/email';import { toast } from '@core/component/Toast/Toast';-import { authServiceClient } from '@service-auth/client';-import { onMount } from 'solid-js';+import { useAddInboxFlow } from '@core/email-link';+import { useEmailLinksQuery } from '@queries/email/link';+import { createEffect, onCleanup } from 'solid-js';-let gmailReauthenticationToastId: number | undefined;--function clearGmailReauthenticationToastState(): void {- gmailReauthenticationToastId = undefined;-}+/**+ * Surfaces a per-inbox "Reconnect Gmail" prompt for every linked inbox whose grant+ * has died, driven by `needs_reauth` from the (already polled) links list. Because+ * the links list includes delegated/shared inboxes, a shared inbox's prompt fans+ * out to every sharer automatically. Replaces the old mount-once, primary-only+ * `/link/gmail/status` check.+ */+export function GmailReauthenticationPrompt() {+ const linksQuery = useEmailLinksQuery();+ const startAddInbox = useAddInboxFlow();-function handleGmailReauthenticationToastAction(): void {- if (gmailReauthenticationToastId !== undefined) {- toast.dismiss(gmailReauthenticationToastId);- }- clearGmailReauthenticationToastState();+ // One persistent toast per broken inbox, keyed by link id.+ const toastIds = new Map<string, number>();+ // Inboxes the user dismissed this session; not re-prompted until they recover.+ const dismissed = new Set<string>();- window.location.href = emailAuthUrl({- returnPath: `${window.location.pathname}${window.location.search}${window.location.hash}`,- });-}+ const dismissToast = (linkId: string) => {+ const id = toastIds.get(linkId);+ if (id !== undefined) {+ toast.dismiss(id);+ toastIds.delete(linkId);+ }+ };-function showGmailReauthenticationToast(): void {- if (gmailReauthenticationToastId !== undefined) return;+ createEffect(() => {+ const links = linksQuery.data?.links ?? [];+ const needingReauth = new Set(+ links.filter((link) => link.needs_reauth).map((link) => link.id)+ );- gmailReauthenticationToastId = toast.custom(- {- title: 'Reconnect Gmail',- content(): string {- return 'Your Gmail authorization has expired. Reconnect Gmail to restore email sync.';- },- actions: [- {- label: 'Reconnect',- onClick: handleGmailReauthenticationToastAction,- },- ],- },- {- persistent: true,- onDismiss: clearGmailReauthenticationToastState,+ // Clear toasts and dismissals for inboxes that recovered or were removed, so a+ // later failure can prompt again.+ for (const linkId of [...toastIds.keys()]) {+ if (!needingReauth.has(linkId)) dismissToast(linkId);+ }+ for (const linkId of [...dismissed]) {+ if (!needingReauth.has(linkId)) dismissed.delete(linkId);}- );-}-async function checkGmailReauthenticationStatus(): Promise<void> {- const response = await authServiceClient.checkGmailLinkStatus();+ for (const link of links) {+ if (+ !link.needs_reauth ||+ toastIds.has(link.id) ||+ dismissed.has(link.id)+ ) {+ continue;+ }- const needsReauthentication = response.isOk()- ? response.value.reauthentication_required- : response.error.some(- (error) => error.code === 'REAUTHENTICATION_REQUIRED'+ const linkId = link.id;+ const id = toast.custom(+ {+ title: 'Reconnect Gmail',+ content(): string {+ return `Sync stopped for ${link.email_address}. Reconnect to restore email sync.`;+ },+ actions: [+ {+ label: 'Reconnect',+ onClick: () => {+ // Suppress re-prompting until the inbox recovers; on native the page+ // stays mounted while the OAuth flow runs.+ dismissed.add(linkId);+ dismissToast(linkId);+ void startAddInbox();+ },+ },+ ],+ },+ {+ persistent: true,+ onDismiss: () => {+ toastIds.delete(linkId);+ dismissed.add(linkId);+ },+ });+ toastIds.set(linkId, id);+ }+ });- if (needsReauthentication) {- showGmailReauthenticationToast();- }-}--export function GmailReauthenticationPrompt() {- onMount(() => {- void checkGmailReauthenticationStatus();+ onCleanup(() => {+ for (const linkId of [...toastIds.keys()]) dismissToast(linkId);});return null;diff --git a/js/app/packages/app/component/settings/Email.tsx b/js/app/packages/app/component/settings/Email.tsxindex a00a5cd9d3..ffe636de40 100644--- a/js/app/packages/app/component/settings/Email.tsx+++ b/js/app/packages/app/component/settings/Email.tsx@@ -17,7 +17,11 @@ import {} from '@service-email/generated/schemas';import { useEmail, useUserId } from '@core/context/user';import { createMemo, createSignal, For, Show } from 'solid-js';-import { useEmailLinks, useEmailLinksStatus } from '@core/email-link';+import {+ useAddInboxFlow,+ useEmailLinks,+ useEmailLinksStatus,+} from '@core/email-link';import {AddInboxDialog,openAddInboxDialog,@@ -45,6 +49,7 @@ export function Email() {resyncInbox,} = useEmailLinks();const emailActive = useEmailLinksStatus();+ const startAddInbox = useAddInboxFlow();const removeInboxMutation = useRemoveInboxMutation({onSuccess: () => toast.success('Inbox removed'),@@ -230,6 +235,7 @@ export function Email() {isOwn={primary().macro_id === userId()}resyncing={resyncingIds().has(primary().id)}onResync={() => handleResyncInbox(primary().id)}+ onReconnect={() => void startAddInbox()}onRemove={() =>setRemoveTarget({id: primary().id,@@ -254,6 +260,7 @@ export function Email() {isOwn={link.macro_id === userId()}resyncing={resyncingIds().has(link.id)}onResync={() => handleResyncInbox(link.id)}+ onReconnect={() => void startAddInbox()}onRemove={() =>setRemoveTarget({id: link.id,@@ -364,6 +371,7 @@ function syncStatusLabel(status: SyncStatus): string {.with(SyncStatus.SYNCING, () => 'Syncing…').with(SyncStatus.UP_TO_DATE, () => 'Up to date').with(SyncStatus.ERROR, () => 'Error — re-sync')+ .with(SyncStatus.NEEDS_REAUTH, () => 'Reconnect to resume sync').with(SyncStatus.INACTIVE, () => 'Disabled').exhaustive();}@@ -405,6 +413,7 @@ function InboxRow(props: {isOwn: boolean;resyncing: boolean;onResync: () => void;+ onReconnect: () => void;onRemove: () => void;}) {return (@@ -430,8 +439,12 @@ function InboxRow(props: {<spanclass="flex items-center gap-1 text-xs"classList={{- 'text-failure': props.link.sync_status === SyncStatus.ERROR,- 'text-ink-muted': props.link.sync_status !== SyncStatus.ERROR,+ 'text-failure':+ props.link.sync_status === SyncStatus.ERROR ||+ props.link.sync_status === SyncStatus.NEEDS_REAUTH,+ 'text-ink-muted':+ props.link.sync_status !== SyncStatus.ERROR &&+ props.link.sync_status !== SyncStatus.NEEDS_REAUTH,}}><Show when={props.link.sync_status === SyncStatus.SYNCING}>@@ -442,6 +455,22 @@ function InboxRow(props: {</Show></div><div class="flex items-center gap-2 shrink-0">+ <Show+ when={+ ENABLE_INBOX_SYNC_STATUS &&+ props.link.sync_status === SyncStatus.NEEDS_REAUTH+ }+ >+ <Button+ variant="active"+ size="sm"+ depth={3}+ onClick={props.onReconnect}+ aria-label={`Reconnect ${props.link.email_address}`}+ >+ Reconnect+ </Button>+ </Show><Show when={ENABLE_INBOX_RESYNC}><Tooltip label="Force sync"><Buttondiff --git a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.tsindex 13dd84b25c..05f75c3f44 100644--- a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts+++ b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts@@ -41,6 +41,7 @@ export function getActionVerb(type: NotificationType): string {.with('github_pr_mention', () => 'mentioned you on a pull request').with('github_pr_review', () => 'reviewed your pull request').with('call-started', () => 'started a call')+ .with('inbox_reauth_required', () => 'needs reconnection').exhaustive();}@@ -79,6 +80,7 @@ export function getTypeNoun(type: NotificationType, count: number): string {.with('github_pr_mention', () => (count === 1 ? 'mention' : 'mentions')).with('github_pr_review', () => (count === 1 ? 'review' : 'reviews')).with('call-started', () => (count === 1 ? 'call' : 'calls'))+ .with('inbox_reauth_required', () => (count === 1 ? 'inbox' : 'inboxes')).exhaustive();}diff --git a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx b/js/app/packages/entity/src/extractors-notification/notification-icon.tsxindex 34b1c9798f..09e8102518 100644--- a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx+++ b/js/app/packages/entity/src/extractors-notification/notification-icon.tsx@@ -52,6 +52,7 @@ function getNotificationIcon(() => GithubIcon).with('call-started', () => PhoneIcon)+ .with('inbox_reauth_required', () => EnvelopeIcon).exhaustive();}diff --git a/js/app/packages/entity/src/utils/notification.ts b/js/app/packages/entity/src/utils/notification.tsindex 5074c7ceee..d1d01aa605 100644--- a/js/app/packages/entity/src/utils/notification.ts+++ b/js/app/packages/entity/src/utils/notification.ts@@ -137,6 +137,7 @@ export function getNotificationActionText(n: Notification): string {.with('github_pr_mention', () => 'mentioned').with('github_pr_review', () => 'reviewed').with('call-started', () => 'called')+ .with('inbox_reauth_required', () => 'needs reconnection').exhaustive();}@@ -197,6 +198,7 @@ export function extractMessageContent(notification: Notification): string {.with({ tag: 'channel_invite' }, () => '').with({ tag: 'invite_to_team' }, () => '').with({ tag: 'call-started' }, (m) => m.content.channel_name ?? '')+ .with({ tag: 'inbox_reauth_required' }, (m) => m.content.emailAddress || '').exhaustive();}diff --git a/js/app/packages/notifications/notification-metadata.ts b/js/app/packages/notifications/notification-metadata.tsindex f5c3514580..13a67f630b 100644--- a/js/app/packages/notifications/notification-metadata.ts+++ b/js/app/packages/notifications/notification-metadata.ts@@ -34,6 +34,7 @@ export function getNotificationAction(n: UnifiedNotification): string {.with('github_pr_comment', () => 'commented on').with('github_pr_mention', () => 'mentioned you in').with('github_pr_review', () => 'reviewed')+ .with('inbox_reauth_required', () => 'needs reconnection').exhaustive();}@@ -64,6 +65,7 @@ export function getNotificationTargetName(.with({ tag: 'ai_response' }, () => undefined).with({ tag: 'channel_message_reply' }, () => undefined).with({ tag: 'new_email' }, () => undefined)+ .with({ tag: 'inbox_reauth_required' }, () => undefined).exhaustive();}@@ -105,6 +107,7 @@ export function getNotificationContent().with({ tag: 'channel_invite' }, () => undefined).with({ tag: 'invite_to_team' }, () => undefined)+ .with({ tag: 'inbox_reauth_required' }, (m) => m.content.emailAddress).exhaustive();}@@ -133,5 +136,6 @@ export function shouldShowNotificationTarget(n: UnifiedNotification): boolean {.with({ tag: 'commented_on_document' }, () => true).with({ tag: 'channel_invite' }, () => true).with({ tag: 'invite_to_team' }, () => true)+ .with({ tag: 'inbox_reauth_required' }, () => false).exhaustive();}diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.tsindex 7246ebe9ba..2ea2b0640d 100644--- a/js/app/packages/notifications/notification-navigation.ts+++ b/js/app/packages/notifications/notification-navigation.ts@@ -315,6 +315,7 @@ function getSupportedHandler(params,});})+ .with('inbox_reauth_required', () => null).exhaustive();}diff --git a/js/app/packages/notifications/notification-preview.ts b/js/app/packages/notifications/notification-preview.tsindex 1b93b035ac..711a8c0b15 100644--- a/js/app/packages/notifications/notification-preview.ts+++ b/js/app/packages/notifications/notification-preview.ts@@ -20,4 +20,5 @@ export const NOTIFICATION_LABEL_BY_TYPE: Record<NotificationType, string> = {github_pr_mention: 'MENTION',github_pr_review: 'REVIEW','call-started': 'CALL',+ inbox_reauth_required: 'EMAIL',} as const;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 6028b9de7b..525d0e8375 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@@ -18,6 +18,9 @@ export interface Link {is_primary: boolean;is_sync_active: boolean;macro_id: string;+ /** Whether the link's Google grant needs to be reconnected. Drives the+per-inbox reconnect prompt independently of the sync-status badge. */+ needs_reauth: boolean;/** The inbox's own profile photo (its self-contact's SFS photo), if synced. */photo_url?: LinkPhotoUrl;provider: UserProvider;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.tsindex 8665715a7e..9095c865e8 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/syncStatus.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/syncStatus.ts@@ -7,8 +7,8 @@/*** 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.+multi-inbox settings list. Derived from the link's `is_sync_active` flag, its+reauth health, and its most recent backfill job.*/export type SyncStatus = (typeof SyncStatus)[keyof typeof SyncStatus];@@ -17,5 +17,6 @@ export const SyncStatus = {SYNCING: 'SYNCING',UP_TO_DATE: 'UP_TO_DATE',ERROR: 'ERROR',+ NEEDS_REAUTH: 'NEEDS_REAUTH',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 ba2e89381d..f1cf3ce7ca 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -4157,6 +4157,7 @@"provider","is_sync_active","sync_status",+ "needs_reauth","settings","is_primary","created_at",@@ -4186,6 +4187,10 @@"macro_id": {"type": "string"},+ "needs_reauth": {+ "type": "boolean",+ "description": "Whether the link's Google grant needs to be reconnected. Drives the\nper-inbox reconnect prompt independently of the sync-status badge."+ },"photo_url": {"type": ["string", "null"],"description": "The inbox's own profile photo (its self-contact's SFS photo), if synced."@@ -4748,8 +4753,8 @@},"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"]+ "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, its\nreauth health, and its most recent backfill job.",+ "enum": ["SYNCING", "UP_TO_DATE", "ERROR", "NEEDS_REAUTH", "INACTIVE"]},"Thread": {"type": "object",diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/inboxReauthRequiredMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/inboxReauthRequiredMetadata.tsnew file mode 100644index 0000000000..542d134ca2--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/inboxReauthRequiredMetadata.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Metadata for a notification that a linked inbox's grant has died and the+inbox must be reconnected. Fanned out to the inbox owner and every delegate,+since any of them holding the Google grant can restore sync.+ */+export interface InboxReauthRequiredMetadata {+ /** The address of the inbox that needs to be reconnected. */+ emailAddress: string;+}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.tsindex 09388c9b75..6fc2ee3352 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts@@ -95,6 +95,7 @@ export * from './githubReviewRequested';export * from './githubReviewRequestedAllOf';export * from './githubReviewRequestedAllOfRequestedReviewerGithubLogin';export * from './githubReviewRequestedAllOfRequestedReviewerGithubUserId';+export * from './inboxReauthRequiredMetadata';export * from './inviteToTeamMetadata';export * from './inviteToTeamMetadataRole';export * from './inviteToTeamMetadataSenderProfilePictureUrl';@@ -133,6 +134,8 @@ export * from './notifEventOneOfThreefive';export * from './notifEventOneOfThreefiveTag';export * from './notifEventOneOfThreeone';export * from './notifEventOneOfThreeoneTag';+export * from './notifEventOneOfThreeseven';+export * from './notifEventOneOfThreesevenTag';export * from './notifEventOneOfThreeTag';export * from './notifEventOneOfThreethree';export * from './notifEventOneOfThreethreeTag';diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.tsindex df641102a9..b04b54319c 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts@@ -16,6 +16,7 @@ import type { NotifEventOneOfSeven } from './notifEventOneOfSeven';import type { NotifEventOneOfThree } from './notifEventOneOfThree';import type { NotifEventOneOfThreefive } from './notifEventOneOfThreefive';import type { NotifEventOneOfThreeone } from './notifEventOneOfThreeone';+import type { NotifEventOneOfThreeseven } from './notifEventOneOfThreeseven';import type { NotifEventOneOfThreethree } from './notifEventOneOfThreethree';import type { NotifEventOneOfTwofive } from './notifEventOneOfTwofive';import type { NotifEventOneOfTwonine } from './notifEventOneOfTwonine';@@ -49,4 +50,5 @@ export type NotifEvent =| NotifEventOneOfTwonine| NotifEventOneOfThreeone| NotifEventOneOfThreethree- | NotifEventOneOfThreefive;+ | NotifEventOneOfThreefive+ | NotifEventOneOfThreeseven;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenine.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenine.tsindex 0613bd3424..3ef7c4f28e 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenine.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenine.ts@@ -4,14 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { InviteToTeamMetadata } from './inviteToTeamMetadata';+import type { InboxReauthRequiredMetadata } from './inboxReauthRequiredMetadata';import type { NotifEventOneOfOnenineTag } from './notifEventOneOfOnenineTag';/**- * A user was invited to a team.+ * A linked inbox's grant died and must be reconnected.*/export type NotifEventOneOfOnenine = {- /** A user was invited to a team. */- content: InviteToTeamMetadata;+ /** A linked inbox's grant died and must be reconnected. */+ content: InboxReauthRequiredMetadata;tag: NotifEventOneOfOnenineTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenineTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenineTag.tsindex e09a7ddd47..e41ba845d4 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenineTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenineTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfOnenineTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfOnenineTag = {- invite_to_team: 'invite_to_team',+ inbox_reauth_required: 'inbox_reauth_required',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreefive.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreefive.tsindex 255a149e29..01f67b7f1b 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreefive.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreefive.ts@@ -4,14 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrReview } from './githubPrReview';+import type { GithubPrMention } from './githubPrMention';import type { NotifEventOneOfThreefiveTag } from './notifEventOneOfThreefiveTag';/**- * A review was submitted on the user's GitHub pull request.+ * The user was mentioned on a GitHub pull request.*/export type NotifEventOneOfThreefive = {- /** A review was submitted on the user's GitHub pull request. */- content: GithubPrReview;+ /** The user was mentioned on a GitHub pull request. */+ content: GithubPrMention;tag: NotifEventOneOfThreefiveTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreefiveTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreefiveTag.tsindex 7299adb547..619cb0f93d 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreefiveTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreefiveTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfThreefiveTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfThreefiveTag = {- github_pr_review: 'github_pr_review',+ github_pr_mention: 'github_pr_mention',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeone.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeone.tsindex 4ad56ee64e..085632a135 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeone.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeone.ts@@ -4,14 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrComment } from './githubPrComment';+import type { GithubReviewRequested } from './githubReviewRequested';import type { NotifEventOneOfThreeoneTag } from './notifEventOneOfThreeoneTag';/**- * A GitHub pull request was commented on.+ * The user's review was requested on a GitHub pull request.*/export type NotifEventOneOfThreeone = {- /** A GitHub pull request was commented on. */- content: GithubPrComment;+ /** The user's review was requested on a GitHub pull request. */+ content: GithubReviewRequested;tag: NotifEventOneOfThreeoneTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeoneTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeoneTag.tsindex 9e15a9b28f..96a671da8a 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeoneTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeoneTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfThreeoneTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfThreeoneTag = {- github_pr_comment: 'github_pr_comment',+ github_review_requested: 'github_review_requested',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeseven.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeseven.tsnew file mode 100644index 0000000000..27c9e0da8b--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeseven.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { GithubPrReview } from './githubPrReview';+import type { NotifEventOneOfThreesevenTag } from './notifEventOneOfThreesevenTag';++/**+ * A review was submitted on the user's GitHub pull request.+ */+export type NotifEventOneOfThreeseven = {+ /** A review was submitted on the user's GitHub pull request. */+ content: GithubPrReview;+ tag: NotifEventOneOfThreesevenTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreesevenTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreesevenTag.tsnew file mode 100644index 0000000000..1c9bc6bd40--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreesevenTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfThreesevenTag =+ (typeof NotifEventOneOfThreesevenTag)[keyof typeof NotifEventOneOfThreesevenTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfThreesevenTag = {+ github_pr_review: 'github_pr_review',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreethree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreethree.tsindex e59d1b5deb..c120361b96 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreethree.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreethree.ts@@ -4,14 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrMention } from './githubPrMention';+import type { GithubPrComment } from './githubPrComment';import type { NotifEventOneOfThreethreeTag } from './notifEventOneOfThreethreeTag';/**- * The user was mentioned on a GitHub pull request.+ * A GitHub pull request was commented on.*/export type NotifEventOneOfThreethree = {- /** The user was mentioned on a GitHub pull request. */- content: GithubPrMention;+ /** A GitHub pull request was commented on. */+ content: GithubPrComment;tag: NotifEventOneOfThreethreeTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreethreeTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreethreeTag.tsindex a622eb81a9..6a17ad6df1 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreethreeTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreethreeTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfThreethreeTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfThreethreeTag = {- github_pr_mention: 'github_pr_mention',+ github_pr_comment: 'github_pr_comment',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofive.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofive.tsindex 85e779a63e..b027f731fc 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofive.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofive.ts@@ -4,20 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrStatusChanged } from './githubPrStatusChanged';+import type { AiResponseMetadata } from './aiResponseMetadata';import type { NotifEventOneOfTwofiveTag } from './notifEventOneOfTwofiveTag';/**- * A GitHub pull request changed lifecycle state.--The `github_pr_event` alias keeps rows and queue messages persisted-before the rename deserializable.+ * An AI assistant responded to a chat.*/export type NotifEventOneOfTwofive = {- /** A GitHub pull request changed lifecycle state.--The `github_pr_event` alias keeps rows and queue messages persisted-before the rename deserializable. */- content: GithubPrStatusChanged;+ /** An AI assistant responded to a chat. */+ content: AiResponseMetadata;tag: NotifEventOneOfTwofiveTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofiveTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofiveTag.tsindex 70863e176f..b78286bcb6 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofiveTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofiveTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfTwofiveTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfTwofiveTag = {- github_pr_status_changed: 'github_pr_status_changed',+ ai_response: 'ai_response',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwonine.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwonine.tsindex d60b749701..701a8926a7 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwonine.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwonine.ts@@ -4,14 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubReviewRequested } from './githubReviewRequested';+import type { GithubPrCheckRun } from './githubPrCheckRun';import type { NotifEventOneOfTwonineTag } from './notifEventOneOfTwonineTag';/**- * The user's review was requested on a GitHub pull request.+ * A GitHub pull request check run completed.*/export type NotifEventOneOfTwonine = {- /** The user's review was requested on a GitHub pull request. */- content: GithubReviewRequested;+ /** A GitHub pull request check run completed. */+ content: GithubPrCheckRun;tag: NotifEventOneOfTwonineTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwonineTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwonineTag.tsindex 7bf8b23007..dabc28ebb4 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwonineTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwonineTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfTwonineTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfTwonineTag = {- github_review_requested: 'github_review_requested',+ github_pr_check_run: 'github_pr_check_run',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwoone.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwoone.tsindex 56bbb11dd1..b84a9432ed 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwoone.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwoone.ts@@ -4,15 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-+import type { InviteToTeamMetadata } from './inviteToTeamMetadata';import type { NotifEventOneOfTwooneTag } from './notifEventOneOfTwooneTag';-import type { TaskAssignedMetadata } from './taskAssignedMetadata';/**- * A user was assigned to a task.+ * A user was invited to a team.*/export type NotifEventOneOfTwoone = {- /** A user was assigned to a task. */- content: TaskAssignedMetadata;+ /** A user was invited to a team. */+ content: InviteToTeamMetadata;tag: NotifEventOneOfTwooneTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwooneTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwooneTag.tsindex 18d9834fe4..9e63689b83 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwooneTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwooneTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfTwooneTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfTwooneTag = {- task_assigned: 'task_assigned',+ invite_to_team: 'invite_to_team',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwoseven.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwoseven.tsindex 241401619e..9811a860ce 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwoseven.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwoseven.ts@@ -4,14 +4,20 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrCheckRun } from './githubPrCheckRun';+import type { GithubPrStatusChanged } from './githubPrStatusChanged';import type { NotifEventOneOfTwosevenTag } from './notifEventOneOfTwosevenTag';/**- * A GitHub pull request check run completed.+ * A GitHub pull request changed lifecycle state.++The `github_pr_event` alias keeps rows and queue messages persisted+before the rename deserializable.*/export type NotifEventOneOfTwoseven = {- /** A GitHub pull request check run completed. */- content: GithubPrCheckRun;+ /** A GitHub pull request changed lifecycle state.++The `github_pr_event` alias keeps rows and queue messages persisted+before the rename deserializable. */+ content: GithubPrStatusChanged;tag: NotifEventOneOfTwosevenTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwosevenTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwosevenTag.tsindex 9eb3f2a036..0e4d656709 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwosevenTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwosevenTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfTwosevenTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfTwosevenTag = {- github_pr_check_run: 'github_pr_check_run',+ github_pr_status_changed: 'github_pr_status_changed',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwothree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwothree.tsindex 2db48b7871..35ccbdb4cb 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwothree.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwothree.ts@@ -4,14 +4,15 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { AiResponseMetadata } from './aiResponseMetadata';+import type { NotifEventOneOfTwothreeTag } from './notifEventOneOfTwothreeTag';+import type { TaskAssignedMetadata } from './taskAssignedMetadata';/**- * An AI assistant responded to a chat.+ * A user was assigned to a task.*/export type NotifEventOneOfTwothree = {- /** An AI assistant responded to a chat. */- content: AiResponseMetadata;+ /** A user was assigned to a task. */+ content: TaskAssignedMetadata;tag: NotifEventOneOfTwothreeTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwothreeTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwothreeTag.tsindex c9c9a5ae4c..c1c0444fa5 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwothreeTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwothreeTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfTwothreeTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfTwothreeTag = {- ai_response: 'ai_response',+ task_assigned: 'task_assigned',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/zod.ts b/js/app/packages/service-clients/service-notification/generated/zod.tsindex 073dcb8148..9c3b481e83 100644--- a/js/app/packages/service-clients/service-notification/generated/zod.ts+++ b/js/app/packages/service-clients/service-notification/generated/zod.ts@@ -547,6 +547,24 @@ export const listTypedNotificationsResponse = zodtag: zod.enum(['new_email']),}).describe('A new email has been sent to the user.'),+ zod+ .object({+ content: zod+ .object({+ emailAddress: zod+ .string()+ .describe(+ 'The address of the inbox that needs to be reconnected.'+ ),+ })+ .describe(+ "Metadata for a notification that a linked inbox's grant has died and the\ninbox must be reconnected. Fanned out to the inbox owner and every delegate,\nsince any of them holding the Google grant can restore sync."+ ),+ tag: zod.enum(['inbox_reauth_required']),+ })+ .describe(+ "A linked inbox's grant died and must be reconnected."+ ),zod.object({content: zod@@ -1764,6 +1782,24 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zodtag: zod.enum(['new_email']),}).describe('A new email has been sent to the user.'),+ zod+ .object({+ content: zod+ .object({+ emailAddress: zod+ .string()+ .describe(+ 'The address of the inbox that needs to be reconnected.'+ ),+ })+ .describe(+ "Metadata for a notification that a linked inbox's grant has died and the\ninbox must be reconnected. Fanned out to the inbox owner and every delegate,\nsince any of them holding the Google grant can restore sync."+ ),+ tag: zod.enum(['inbox_reauth_required']),+ })+ .describe(+ "A linked inbox's grant died and must be reconnected."+ ),zod.object({content: zod@@ -2975,6 +3011,24 @@ export const getTypedNotificationsByEventItemIdResponse = zodtag: zod.enum(['new_email']),}).describe('A new email has been sent to the user.'),+ zod+ .object({+ content: zod+ .object({+ emailAddress: zod+ .string()+ .describe(+ 'The address of the inbox that needs to be reconnected.'+ ),+ })+ .describe(+ "Metadata for a notification that a linked inbox's grant has died and the\ninbox must be reconnected. Fanned out to the inbox owner and every delegate,\nsince any of them holding the Google grant can restore sync."+ ),+ tag: zod.enum(['inbox_reauth_required']),+ })+ .describe(+ "A linked inbox's grant died and must be reconnected."+ ),zod.object({content: zod@@ -4171,6 +4225,22 @@ export const getTypedNotificationByIdResponse = zodtag: zod.enum(['new_email']),}).describe('A new email has been sent to the user.'),+ zod+ .object({+ content: zod+ .object({+ emailAddress: zod+ .string()+ .describe(+ 'The address of the inbox that needs to be reconnected.'+ ),+ })+ .describe(+ "Metadata for a notification that a linked inbox's grant has died and the\ninbox must be reconnected. Fanned out to the inbox owner and every delegate,\nsince any of them holding the Google grant can restore sync."+ ),+ tag: zod.enum(['inbox_reauth_required']),+ })+ .describe("A linked inbox's grant died and must be reconnected."),zod.object({content: zoddiff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex 4c8bd4b034..2cc31bdba3 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -1849,6 +1849,17 @@],"description": "Metadata for a notification that the user's review was requested on a GitHub pull request."},+ "InboxReauthRequiredMetadata": {+ "type": "object",+ "description": "Metadata for a notification that a linked inbox's grant has died and the\ninbox must be reconnected. Fanned out to the inbox owner and every delegate,\nsince any of them holding the Google grant can restore sync.",+ "required": ["emailAddress"],+ "properties": {+ "emailAddress": {+ "type": "string",+ "description": "The address of the inbox that needs to be reconnected."+ }+ }+ },"InviteToTeamMetadata": {"type": "object","description": "Metadata for when a user is invited to a team.",@@ -2134,6 +2145,21 @@}}},+ {+ "type": "object",+ "description": "A linked inbox's grant died and must be reconnected.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "$ref": "#/components/schemas/InboxReauthRequiredMetadata",+ "description": "A linked inbox's grant died and must be reconnected."+ },+ "tag": {+ "type": "string",+ "enum": ["inbox_reauth_required"]+ }+ }+ },{"type": "object","description": "A user was invited to a team.",diff --git a/rust/cloud-storage/.sqlx/query-484391893f69c9fce4d47c7daeb46dca050ac95aa1f247654f6a3820f78552ee.json b/rust/cloud-storage/.sqlx/query-12773a1767f52f123fb158a571543301a22033075690452539815c071d5a2f4c.jsonsimilarity index 74%rename from rust/cloud-storage/.sqlx/query-484391893f69c9fce4d47c7daeb46dca050ac95aa1f247654f6a3820f78552ee.jsonrename to rust/cloud-storage/.sqlx/query-12773a1767f52f123fb158a571543301a22033075690452539815c071d5a2f4c.jsonindex 5d325343bf..246703ceff 100644--- a/rust/cloud-storage/.sqlx/query-484391893f69c9fce4d47c7daeb46dca050ac95aa1f247654f6a3820f78552ee.json+++ b/rust/cloud-storage/.sqlx/query-12773a1767f52f123fb158a571543301a22033075690452539815c071d5a2f4c.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, fusionauth_user_id, macro_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, created_at, updated_at\n FROM email_links\n WHERE fusionauth_user_id = $1\n ORDER BY created_at DESC\n ",+ "query": "\n SELECT id, fusionauth_user_id, macro_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_at\n FROM email_links\n WHERE fusionauth_user_id = $1\n ORDER BY created_at DESC\n ","describe": {"columns": [{@@ -49,11 +49,21 @@},{"ordinal": 7,+ "name": "needs_reauth",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "last_sync_error_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 10,"name": "updated_at","type_info": "Timestamptz"}@@ -72,8 +82,10 @@false,false,false,+ true,+ false,false]},- "hash": "484391893f69c9fce4d47c7daeb46dca050ac95aa1f247654f6a3820f78552ee"+ "hash": "12773a1767f52f123fb158a571543301a22033075690452539815c071d5a2f4c"}diff --git a/rust/cloud-storage/.sqlx/query-1936337bcd93ae86730b7d49554e872c3c2abfad492c08f7cd1c015a89526aa7.json b/rust/cloud-storage/.sqlx/query-1936337bcd93ae86730b7d49554e872c3c2abfad492c08f7cd1c015a89526aa7.jsonnew file mode 100644index 0000000000..c76f7ed134--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-1936337bcd93ae86730b7d49554e872c3c2abfad492c08f7cd1c015a89526aa7.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH prev AS (\n SELECT needs_reauth FROM email_links WHERE id = $1 FOR UPDATE\n )\n UPDATE email_links e\n SET needs_reauth = true,\n last_sync_error_at = NOW(),\n updated_at = NOW()\n FROM prev\n WHERE e.id = $1\n RETURNING (NOT prev.needs_reauth) AS \"did_transition!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "did_transition!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "1936337bcd93ae86730b7d49554e872c3c2abfad492c08f7cd1c015a89526aa7"+}diff --git a/rust/cloud-storage/.sqlx/query-575c7ee9e44a430e30f7ac9ec9f7adc80032fa0cd70a608529ce33c27a124c5f.json b/rust/cloud-storage/.sqlx/query-575c7ee9e44a430e30f7ac9ec9f7adc80032fa0cd70a608529ce33c27a124c5f.jsonnew file mode 100644index 0000000000..572944e96b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-575c7ee9e44a430e30f7ac9ec9f7adc80032fa0cd70a608529ce33c27a124c5f.json@@ -0,0 +1,91 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id as \"id!\", macro_id as \"macro_id!\",\n fusionauth_user_id as \"fusionauth_user_id!\",\n email_address as \"email_address!\",\n provider as \"provider!: _\",\n is_sync_active as \"is_sync_active!\",\n is_primary as \"is_primary!\",\n needs_reauth as \"needs_reauth!\",\n last_sync_error_at,\n created_at as \"created_at!\",\n updated_at as \"updated_at!\"\n FROM (\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,\n el.last_sync_error_at, el.created_at, el.updated_at\n FROM email_links el\n WHERE el.macro_id = $1\n UNION\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,\n el.last_sync_error_at, el.created_at, el.updated_at\n FROM email_links el\n JOIN macro_user_links mul ON el.id = mul.link_id\n WHERE mul.primary_macro_id = $1\n ) AS combined\n ORDER BY created_at DESC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "macro_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "fusionauth_user_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "email_address!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 4,+ "name": "provider!: _",+ "type_info": {+ "Custom": {+ "name": "email_user_provider_enum",+ "kind": {+ "Enum": [+ "GMAIL"+ ]+ }+ }+ }+ },+ {+ "ordinal": 5,+ "name": "is_sync_active!",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "is_primary!",+ "type_info": "Bool"+ },+ {+ "ordinal": 7,+ "name": "needs_reauth!",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "last_sync_error_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "created_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "updated_at!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null+ ]+ },+ "hash": "575c7ee9e44a430e30f7ac9ec9f7adc80032fa0cd70a608529ce33c27a124c5f"+}diff --git a/rust/cloud-storage/.sqlx/query-3438cbfd6a3d2354c38bfb1eda314caaf7a8f149d1b20385ab990f4c32c406fe.json b/rust/cloud-storage/.sqlx/query-74e2214e68d34a0c65aab38926518e3c0b8905a79eeb38ed7f84258b00a1b991.jsonsimilarity index 70%rename from rust/cloud-storage/.sqlx/query-3438cbfd6a3d2354c38bfb1eda314caaf7a8f149d1b20385ab990f4c32c406fe.jsonrename to rust/cloud-storage/.sqlx/query-74e2214e68d34a0c65aab38926518e3c0b8905a79eeb38ed7f84258b00a1b991.jsonindex 0bf8574453..e84c3d95cc 100644--- a/rust/cloud-storage/.sqlx/query-3438cbfd6a3d2354c38bfb1eda314caaf7a8f149d1b20385ab990f4c32c406fe.json+++ b/rust/cloud-storage/.sqlx/query-74e2214e68d34a0c65aab38926518e3c0b8905a79eeb38ed7f84258b00a1b991.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (fusionauth_user_id, email_address, provider) \n DO UPDATE SET \n is_sync_active = EXCLUDED.is_sync_active,\n updated_at = NOW()\n RETURNING id, is_primary\n ",+ "query": "\n INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (fusionauth_user_id, email_address, provider)\n DO UPDATE SET\n is_sync_active = EXCLUDED.is_sync_active,\n needs_reauth = false,\n last_sync_error_at = NULL,\n updated_at = NOW()\n RETURNING id, is_primary\n ","describe": {"columns": [{@@ -38,5 +38,5 @@false]},- "hash": "3438cbfd6a3d2354c38bfb1eda314caaf7a8f149d1b20385ab990f4c32c406fe"+ "hash": "74e2214e68d34a0c65aab38926518e3c0b8905a79eeb38ed7f84258b00a1b991"}diff --git a/rust/cloud-storage/.sqlx/query-11dd667e0b2f95f4d43191cc1ad971ce1816b260b7e8b529f1a39f284fecc9c7.json b/rust/cloud-storage/.sqlx/query-863c1f8f59612d776ce83a444d00c12b3f5bae7996b24d60d0cca35327a91243.jsonsimilarity index 76%rename from rust/cloud-storage/.sqlx/query-11dd667e0b2f95f4d43191cc1ad971ce1816b260b7e8b529f1a39f284fecc9c7.jsonrename to rust/cloud-storage/.sqlx/query-863c1f8f59612d776ce83a444d00c12b3f5bae7996b24d60d0cca35327a91243.jsonindex f06d3a25ec..7147dd7ba6 100644--- a/rust/cloud-storage/.sqlx/query-11dd667e0b2f95f4d43191cc1ad971ce1816b260b7e8b529f1a39f284fecc9c7.json+++ b/rust/cloud-storage/.sqlx/query-863c1f8f59612d776ce83a444d00c12b3f5bae7996b24d60d0cca35327a91243.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, created_at, updated_at\n FROM email_links\n WHERE id = $1\n ",+ "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_at\n FROM email_links\n WHERE id = $1\n ","describe": {"columns": [{@@ -49,11 +49,21 @@},{"ordinal": 7,+ "name": "needs_reauth",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "last_sync_error_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 10,"name": "updated_at","type_info": "Timestamptz"}@@ -72,8 +82,10 @@false,false,false,+ true,+ false,false]},- "hash": "11dd667e0b2f95f4d43191cc1ad971ce1816b260b7e8b529f1a39f284fecc9c7"+ "hash": "863c1f8f59612d776ce83a444d00c12b3f5bae7996b24d60d0cca35327a91243"}diff --git a/rust/cloud-storage/.sqlx/query-8c27c21ce4b8a231459f68a1ecfd08a56170c1fb420a4f09ed2d997664081cb7.json b/rust/cloud-storage/.sqlx/query-b7286b5c7483bde7946d25e62e0afed919e8cc8dc0347b824f4372b9325e33f3.jsonsimilarity index 77%rename from rust/cloud-storage/.sqlx/query-8c27c21ce4b8a231459f68a1ecfd08a56170c1fb420a4f09ed2d997664081cb7.jsonrename to rust/cloud-storage/.sqlx/query-b7286b5c7483bde7946d25e62e0afed919e8cc8dc0347b824f4372b9325e33f3.jsonindex c0d914f931..e1377a0aa4 100644--- a/rust/cloud-storage/.sqlx/query-8c27c21ce4b8a231459f68a1ecfd08a56170c1fb420a4f09ed2d997664081cb7.json+++ b/rust/cloud-storage/.sqlx/query-b7286b5c7483bde7946d25e62e0afed919e8cc8dc0347b824f4372b9325e33f3.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, created_at, updated_at\n FROM email_links\n WHERE email_address = $1 AND provider = $2\n LIMIT 1\n ",+ "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_at\n FROM email_links\n WHERE email_address = $1 AND provider = $2\n LIMIT 1\n ","describe": {"columns": [{@@ -49,11 +49,21 @@},{"ordinal": 7,+ "name": "needs_reauth",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "last_sync_error_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 10,"name": "updated_at","type_info": "Timestamptz"}@@ -82,8 +92,10 @@false,false,false,+ true,+ false,false]},- "hash": "8c27c21ce4b8a231459f68a1ecfd08a56170c1fb420a4f09ed2d997664081cb7"+ "hash": "b7286b5c7483bde7946d25e62e0afed919e8cc8dc0347b824f4372b9325e33f3"}diff --git a/rust/cloud-storage/.sqlx/query-bb63e2806040952a060af94ba8a9806cf6c1124a09e8dd64d3acea4f0d196e8f.json b/rust/cloud-storage/.sqlx/query-bb63e2806040952a060af94ba8a9806cf6c1124a09e8dd64d3acea4f0d196e8f.jsonnew file mode 100644index 0000000000..5ed1ed528f--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-bb63e2806040952a060af94ba8a9806cf6c1124a09e8dd64d3acea4f0d196e8f.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE email_links\n SET needs_reauth = false,\n last_sync_error_at = NULL,\n updated_at = NOW()\n WHERE id = $1 AND needs_reauth = true\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "bb63e2806040952a060af94ba8a9806cf6c1124a09e8dd64d3acea4f0d196e8f"+}diff --git a/rust/cloud-storage/.sqlx/query-d1eba683c01a615159db5a2aba7090ecb587e9c53c9875c1bc84b582be547ca1.json b/rust/cloud-storage/.sqlx/query-d1727232ae9c4554c9f16e3e2bca090b6bfc494b78a0431c7c6bfeb417d58c04.jsonsimilarity index 65%rename from rust/cloud-storage/.sqlx/query-d1eba683c01a615159db5a2aba7090ecb587e9c53c9875c1bc84b582be547ca1.jsonrename to rust/cloud-storage/.sqlx/query-d1727232ae9c4554c9f16e3e2bca090b6bfc494b78a0431c7c6bfeb417d58c04.jsonindex f9b7015405..5540a56b05 100644--- a/rust/cloud-storage/.sqlx/query-d1eba683c01a615159db5a2aba7090ecb587e9c53c9875c1bc84b582be547ca1.json+++ b/rust/cloud-storage/.sqlx/query-d1727232ae9c4554c9f16e3e2bca090b6bfc494b78a0431c7c6bfeb417d58c04.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as \"provider: _\",\n l.is_sync_active, l.is_primary, l.created_at, l.updated_at\n FROM email_messages m\n JOIN email_links l ON l.id = m.link_id\n WHERE m.id = $1\n AND (\n l.macro_id = $2\n OR EXISTS (\n SELECT 1 FROM macro_user_links mul\n WHERE mul.link_id = l.id AND mul.primary_macro_id = $2\n )\n )\n ",+ "query": "\n SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as \"provider: _\",\n l.is_sync_active, l.is_primary, l.needs_reauth, l.last_sync_error_at,\n l.created_at, l.updated_at\n FROM email_threads t\n JOIN email_links l ON l.id = t.link_id\n WHERE t.id = $1\n AND (\n l.macro_id = $2\n OR EXISTS (\n SELECT 1 FROM macro_user_links mul\n WHERE mul.link_id = l.id AND mul.primary_macro_id = $2\n )\n )\n ","describe": {"columns": [{@@ -49,11 +49,21 @@},{"ordinal": 7,+ "name": "needs_reauth",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "last_sync_error_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 10,"name": "updated_at","type_info": "Timestamptz"}@@ -73,8 +83,10 @@false,false,false,+ true,+ false,false]},- "hash": "d1eba683c01a615159db5a2aba7090ecb587e9c53c9875c1bc84b582be547ca1"+ "hash": "d1727232ae9c4554c9f16e3e2bca090b6bfc494b78a0431c7c6bfeb417d58c04"}diff --git a/rust/cloud-storage/.sqlx/query-e04e6950cd34a8c41a9d7f8388083fde87ad65f6ac3fa1616007d9ff5027777c.json b/rust/cloud-storage/.sqlx/query-e04e6950cd34a8c41a9d7f8388083fde87ad65f6ac3fa1616007d9ff5027777c.jsonnew file mode 100644index 0000000000..91dec3970c--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-e04e6950cd34a8c41a9d7f8388083fde87ad65f6ac3fa1616007d9ff5027777c.json@@ -0,0 +1,92 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as \"provider: _\",\n l.is_sync_active, l.is_primary, l.needs_reauth, l.last_sync_error_at,\n l.created_at, l.updated_at\n FROM email_messages m\n JOIN email_links l ON l.id = m.link_id\n WHERE m.id = $1\n AND (\n l.macro_id = $2\n OR EXISTS (\n SELECT 1 FROM macro_user_links mul\n WHERE mul.link_id = l.id AND mul.primary_macro_id = $2\n )\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "macro_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "fusionauth_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "email_address",+ "type_info": "Varchar"+ },+ {+ "ordinal": 4,+ "name": "provider: _",+ "type_info": {+ "Custom": {+ "name": "email_user_provider_enum",+ "kind": {+ "Enum": [+ "GMAIL"+ ]+ }+ }+ }+ },+ {+ "ordinal": 5,+ "name": "is_sync_active",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "is_primary",+ "type_info": "Bool"+ },+ {+ "ordinal": 7,+ "name": "needs_reauth",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "last_sync_error_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "e04e6950cd34a8c41a9d7f8388083fde87ad65f6ac3fa1616007d9ff5027777c"+}diff --git a/rust/cloud-storage/.sqlx/query-08d035b4ba64e5c981db5899f59dd65c406184ebcfe92ee3fecd979dc7da2f3f.json b/rust/cloud-storage/.sqlx/query-f0e338160444a468d336d95163818842921bc1da4baace8e4b8658dbc71aa1a0.jsonsimilarity index 74%rename from rust/cloud-storage/.sqlx/query-08d035b4ba64e5c981db5899f59dd65c406184ebcfe92ee3fecd979dc7da2f3f.jsonrename to rust/cloud-storage/.sqlx/query-f0e338160444a468d336d95163818842921bc1da4baace8e4b8658dbc71aa1a0.jsonindex fb114d4c60..c02e013c73 100644--- a/rust/cloud-storage/.sqlx/query-08d035b4ba64e5c981db5899f59dd65c406184ebcfe92ee3fecd979dc7da2f3f.json+++ b/rust/cloud-storage/.sqlx/query-f0e338160444a468d336d95163818842921bc1da4baace8e4b8658dbc71aa1a0.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, created_at, updated_at \n FROM email_links\n WHERE macro_id = $1\n ORDER BY created_at DESC\n LIMIT 1\n ",+ "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_at\n FROM email_links\n WHERE macro_id = $1\n ORDER BY created_at DESC\n LIMIT 1\n ","describe": {"columns": [{@@ -49,11 +49,21 @@},{"ordinal": 7,+ "name": "needs_reauth",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "last_sync_error_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 10,"name": "updated_at","type_info": "Timestamptz"}@@ -72,8 +82,10 @@false,false,false,+ true,+ false,false]},- "hash": "08d035b4ba64e5c981db5899f59dd65c406184ebcfe92ee3fecd979dc7da2f3f"+ "hash": "f0e338160444a468d336d95163818842921bc1da4baace8e4b8658dbc71aa1a0"}diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rsindex d134f1c195..4955de75a1 100644--- a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs@@ -102,11 +102,26 @@ async fn link_user({Ok(()) => {}Err(FusionAuthClientError::IdentityProviderLinkAlreadyExists) => {- tracing::info!(- fusion_user_id = %idp_link_owner,- linked_email = %user_info_email,- "idp link already exists, skipping creation"- );+ // The link already exists but its stored refresh token may be dead (this+ // is the reconnect path). A plain `link_user` no-ops and leaves the dead+ // token in place, so swap in the freshly minted token. With no fresh token+ // (Google withheld a refresh token) there is nothing to swap, so leave the+ // existing grant untouched.+ if token_response.refresh_token.is_empty() {+ tracing::info!(+ fusion_user_id = %idp_link_owner,+ "idp link already exists and no fresh refresh token returned, leaving existing grant"+ );+ } else {+ relink_with_fresh_token(+ ctx,+ identity_provider_id,+ &idp_link_owner,+ &user_info_email,+ &token_response.refresh_token,+ )+ .await?;+ }}Err(e) => {return Err((@@ -130,6 +145,103 @@ async fn link_user(Ok(())}+/// Replaces a stale Google grant on an existing IdP link with a freshly minted+/// refresh token. Used on reconnect, when the mailbox's FusionAuth link already+/// exists but its stored token has gone dead — a plain `link_user` no-ops and+/// leaves the dead token in place.+///+/// A Google identity binds to exactly one FusionAuth user, so the grant is swapped+/// by unlinking the old link and re-linking with the new token, rolling back to the+/// old token if the re-link fails. A shared mailbox's grant lives on a deactivated+/// stub user; links are only created against active users, so the stub is+/// reactivated for the swap and returned to its prior state afterward (a human's own+/// active account is left active). Idempotent when the stored token already matches.+async fn relink_with_fresh_token(+ ctx: &ApiContext,+ identity_provider_id: &str,+ idp_link_owner: &str,+ email: &str,+ fresh_refresh_token: &str,+) -> Result<(), (StatusCode, String)> {+ let server_error = |message: String| (StatusCode::INTERNAL_SERVER_ERROR, message);+ let auth = &ctx.auth_client;++ let existing_links = auth+ .get_links(idp_link_owner, Some(identity_provider_id.to_string()))+ .await+ .map_err(|e| server_error(format!("unable to read existing links {e}")))?;++ let Some(existing) = existing_links.into_iter().find(|l| l.display_name == email) else {+ // Owner resolution and the already-exists error disagree about where the+ // link lives; there is nothing to relink on this user.+ tracing::warn!(+ fusion_user_id = %idp_link_owner,+ "relink: no existing grant found for mailbox on resolved owner, skipping"+ );+ return Ok(());+ };++ if existing.token == fresh_refresh_token {+ // Stored token already current; nothing to do.+ return Ok(());+ }++ let sub = existing.identity_provider_user_id;+ let stale_token = existing.token;++ let was_active = auth+ .get_user_active(idp_link_owner)+ .await+ .map_err(|e| server_error(format!("unable to read user active state {e}")))?;++ if !was_active {+ auth.reactivate_user(idp_link_owner)+ .await+ .map_err(|e| server_error(format!("unable to reactivate user for relink {e}")))?;+ }++ let link_with = |token: &str| LinkUserRequest {+ identity_provider_link: IdentityProviderLink {+ display_name: Cow::Owned(email.to_string()),+ identity_provider_id: Cow::Borrowed(identity_provider_id),+ identity_provider_user_id: Cow::Borrowed(&sub),+ user_id: Cow::Borrowed(idp_link_owner),+ token: Cow::Owned(token.to_string()),+ },+ };++ // Swap the grant, capturing the outcome so the stub is re-deactivated below on+ // every path — including an unlink failure — rather than leaking an active stub.+ let swap_result: Result<(), (StatusCode, String)> = async {+ auth.unlink_user(idp_link_owner, identity_provider_id, &sub)+ .await+ .map_err(|e| server_error(format!("unable to unlink stale grant {e}")))?;++ let link_result = auth.link_user(link_with(fresh_refresh_token)).await;++ if let Err(e) = &link_result {+ tracing::error!(error=?e, "relink: failed to attach fresh grant, rolling back to stale token");+ if let Err(rollback) = auth.link_user(link_with(&stale_token)).await {+ tracing::error!(error=?rollback, "relink: rollback re-link also failed, grant is detached");+ }+ }++ link_result.map_err(|e| server_error(format!("unable to attach fresh grant {e}")))+ }+ .await;++ // Restore the stub's deactivated state on every path; a human's own account was+ // active and is left as-is. Best-effort (logged) so a deactivation blip can't fail+ // a reconnect whose grant swap already succeeded.+ if !was_active && let Err(e) = auth.deactivate_user(idp_link_owner).await {+ tracing::error!(error=?e, %idp_link_owner, "relink: failed to re-deactivate stub after relink");+ }++ swap_result?;++ Ok(())+}+pub(in crate::api::oauth2) async fn handler(ctx: &ApiContext,cookies: Cookies,diff --git a/rust/cloud-storage/email_db_client/src/links/get.rs b/rust/cloud-storage/email_db_client/src/links/get.rsindex a09d861dd4..ce16884d56 100644--- a/rust/cloud-storage/email_db_client/src/links/get.rs+++ b/rust/cloud-storage/email_db_client/src/links/get.rs@@ -24,7 +24,7 @@ pub async fn fetch_link_by_email(DbLink,r#"SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",- is_sync_active, is_primary, created_at, updated_at+ is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_atFROM email_linksWHERE email_address = $1 AND provider = $2LIMIT 1@@ -52,7 +52,7 @@ pub async fn fetch_link_by_macro_id(DbLink,r#"SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",- is_sync_active, is_primary, created_at, updated_at+ is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_atFROM email_linksWHERE macro_id = $1ORDER BY created_at DESC@@ -89,16 +89,20 @@ pub async fn fetch_inboxes_for_macro_id(provider as "provider!: _",is_sync_active as "is_sync_active!",is_primary as "is_primary!",+ needs_reauth as "needs_reauth!",+ last_sync_error_at,created_at as "created_at!",updated_at as "updated_at!"FROM (SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,- el.provider, el.is_sync_active, el.is_primary, el.created_at, el.updated_at+ el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,+ el.last_sync_error_at, el.created_at, el.updated_atFROM email_links elWHERE el.macro_id = $1UNIONSELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,- el.provider, el.is_sync_active, el.is_primary, el.created_at, el.updated_at+ el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,+ el.last_sync_error_at, el.created_at, el.updated_atFROM email_links elJOIN macro_user_links mul ON el.id = mul.link_idWHERE mul.primary_macro_id = $1@@ -132,7 +136,7 @@ pub async fn fetch_links_by_fusionauth_user_id(DbLink,r#"SELECT id, fusionauth_user_id, macro_id, email_address, provider as "provider: _",- is_sync_active, is_primary, created_at, updated_at+ is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_atFROM email_linksWHERE fusionauth_user_id = $1ORDER BY created_at DESC@@ -167,7 +171,8 @@ pub async fn fetch_owned_link_for_thread(DbLink,r#"SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as "provider: _",- l.is_sync_active, l.is_primary, l.created_at, l.updated_at+ l.is_sync_active, l.is_primary, l.needs_reauth, l.last_sync_error_at,+ l.created_at, l.updated_atFROM email_threads tJOIN email_links l ON l.id = t.link_idWHERE t.id = $1@@ -200,7 +205,8 @@ pub async fn fetch_owned_link_for_message(DbLink,r#"SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as "provider: _",- l.is_sync_active, l.is_primary, l.created_at, l.updated_at+ l.is_sync_active, l.is_primary, l.needs_reauth, l.last_sync_error_at,+ l.created_at, l.updated_atFROM email_messages mJOIN email_links l ON l.id = m.link_idWHERE m.id = $1@@ -229,7 +235,7 @@ pub async fn fetch_link_by_id(pool: &PgPool, link_id: Uuid) -> anyhow::Result<OpDbLink,r#"SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",- is_sync_active, is_primary, created_at, updated_at+ is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_atFROM email_linksWHERE id = $1"#,diff --git a/rust/cloud-storage/email_db_client/src/links/insert.rs b/rust/cloud-storage/email_db_client/src/links/insert.rsindex 504c2c5166..2c5e9cc472 100644--- a/rust/cloud-storage/email_db_client/src/links/insert.rs+++ b/rust/cloud-storage/email_db_client/src/links/insert.rs@@ -33,6 +33,8 @@ pub async fn upsert_link(provider,is_sync_active,is_primary: _,+ needs_reauth: _,+ last_sync_error_at: _,created_at,updated_at,} = service_link;@@ -44,9 +46,11 @@ pub async fn upsert_link(r#"INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active)VALUES ($1, $2, $3, $4, $5, $6)- ON CONFLICT (fusionauth_user_id, email_address, provider)- DO UPDATE SET+ ON CONFLICT (fusionauth_user_id, email_address, provider)+ DO UPDATE SETis_sync_active = EXCLUDED.is_sync_active,+ needs_reauth = false,+ last_sync_error_at = NULL,updated_at = NOW()RETURNING id, is_primary"#,@@ -68,6 +72,8 @@ pub async fn upsert_link(provider,is_sync_active,is_primary: result.is_primary,+ needs_reauth: false,+ last_sync_error_at: None,created_at,updated_at,};diff --git a/rust/cloud-storage/email_db_client/src/links/insert/test.rs b/rust/cloud-storage/email_db_client/src/links/insert/test.rsindex 0a6b2bc4e8..82c654f0c8 100644--- a/rust/cloud-storage/email_db_client/src/links/insert/test.rs+++ b/rust/cloud-storage/email_db_client/src/links/insert/test.rs@@ -25,6 +25,8 @@ async fn upsert_link_in_transaction_persists_divergent_ids(provider: UserProvider::Gmail,is_sync_active: true,is_primary: true,+ needs_reauth: false,+ last_sync_error_at: None,created_at: Default::default(),updated_at: Default::default(),};diff --git a/rust/cloud-storage/email_db_client/src/links/types.rs b/rust/cloud-storage/email_db_client/src/links/types.rsindex 53fbe0af99..5657d8eb8f 100644--- a/rust/cloud-storage/email_db_client/src/links/types.rs+++ b/rust/cloud-storage/email_db_client/src/links/types.rs@@ -28,6 +28,8 @@ pub struct DbLink {pub provider: DbUserProvider,pub is_sync_active: bool,pub is_primary: bool,+ pub needs_reauth: bool,+ pub last_sync_error_at: Option<DateTime<Utc>>,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,}@@ -49,6 +51,8 @@ impl From<models_email::email::service::link::Link> for DbLink {},is_sync_active: service_link.is_sync_active,is_primary: service_link.is_primary,+ needs_reauth: service_link.needs_reauth,+ last_sync_error_at: service_link.last_sync_error_at,created_at: service_link.created_at,updated_at: service_link.updated_at,}@@ -67,6 +71,8 @@ impl TryFrom<DbLink> for models_email::email::service::link::Link {provider,is_sync_active,is_primary,+ needs_reauth,+ last_sync_error_at,created_at,updated_at,} = value;@@ -80,6 +86,8 @@ impl TryFrom<DbLink> for models_email::email::service::link::Link {},is_sync_active,is_primary,+ needs_reauth,+ last_sync_error_at,created_at,updated_at,})diff --git a/rust/cloud-storage/email_db_client/src/links/update.rs b/rust/cloud-storage/email_db_client/src/links/update.rsindex 8f8a355f76..3b7b5b3dc2 100644--- a/rust/cloud-storage/email_db_client/src/links/update.rs+++ b/rust/cloud-storage/email_db_client/src/links/update.rs@@ -1,6 +1,9 @@use sqlx::PgPool;use sqlx::types::Uuid;+#[cfg(test)]+mod test;+/// Re-homes a link's `fusionauth_user_id`. Used after a shared mailbox's Google grant is/// relocated onto a dedicated FusionAuth user so token resolution follows it there.#[tracing::instrument(skip(pool), err)]@@ -28,6 +31,53 @@ pub async fn update_link_fusionauth_user_id(Ok(())}+/// Marks a link as needing reauth and records when the failure was observed.+/// Returns `true` only when this call flipped the link from healthy to+/// needs-reauth, letting callers fire a one-time notification on that edge.+/// Returns `false` when it was already flagged or no such link exists.+#[tracing::instrument(skip(pool), err)]+pub async fn set_link_needs_reauth(pool: &PgPool, link_id: Uuid) -> anyhow::Result<bool> {+ let row = sqlx::query!(+ r#"+ WITH prev AS (+ SELECT needs_reauth FROM email_links WHERE id = $1 FOR UPDATE+ )+ UPDATE email_links e+ SET needs_reauth = true,+ last_sync_error_at = NOW(),+ updated_at = NOW()+ FROM prev+ WHERE e.id = $1+ RETURNING (NOT prev.needs_reauth) AS "did_transition!"+ "#,+ link_id,+ )+ .fetch_optional(pool)+ .await?;++ Ok(matches!(row, Some(r) if r.did_transition))+}++/// Clears a link's reauth flag once its token is healthy again. A no-op when the+/// flag isn't set, so it is cheap to call on every successful token fetch.+#[tracing::instrument(skip(pool), err)]+pub async fn clear_link_needs_reauth(pool: &PgPool, link_id: Uuid) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ UPDATE email_links+ SET needs_reauth = false,+ last_sync_error_at = NULL,+ updated_at = NOW()+ WHERE id = $1 AND needs_reauth = true+ "#,+ link_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}+/// Updates the sync active status for a link by its ID./// Also updates the updated_at timestamp to the current time.#[tracing::instrument(skip(pool), err)]diff --git a/rust/cloud-storage/email_db_client/src/links/update/test.rs b/rust/cloud-storage/email_db_client/src/links/update/test.rsnew file mode 100644index 0000000000..1e6db677d3--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/links/update/test.rs@@ -0,0 +1,67 @@+use super::*;+use crate::links::get::fetch_link_by_id;+use crate::links::insert::upsert_link;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::email::EmailStr;+use macro_user_id::user_id::MacroUserIdStr;+use models_email::email::service::link::{Link, UserProvider};+use sqlx::{Pool, Postgres};++async fn insert_test_link(pool: &Pool<Postgres>, email: &str) -> anyhow::Result<Uuid> {+ let link = Link {+ id: macro_uuid::generate_uuid_v7(),+ macro_id: MacroUserIdStr::try_from(format!("macro|{email}"))?,+ fusionauth_user_id: "22222222-2222-2222-2222-222222222222".to_string(),+ email_address: EmailStr::try_from(email.to_string())?,+ provider: UserProvider::Gmail,+ is_sync_active: true,+ is_primary: true,+ needs_reauth: false,+ last_sync_error_at: None,+ created_at: Default::default(),+ updated_at: Default::default(),+ };+ let mut conn = pool.acquire().await?;+ let inserted = upsert_link(&mut conn, link).await?;+ Ok(inserted.id)+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_needs_reauth_is_edge_triggered(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let id = insert_test_link(&pool, "[email protected]").await?;++ // First failure flips the flag and reports the transition.+ assert!(set_link_needs_reauth(&pool, id).await?);++ let link = fetch_link_by_id(&pool, id).await?.expect("link exists");+ assert!(link.needs_reauth);+ assert!(link.last_sync_error_at.is_some());++ // A repeat failure does not re-report the transition (so it won't re-notify).+ assert!(!set_link_needs_reauth(&pool, id).await?);++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn clear_needs_reauth_resets_health(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let id = insert_test_link(&pool, "[email protected]").await?;++ set_link_needs_reauth(&pool, id).await?;+ clear_link_needs_reauth(&pool, id).await?;++ let link = fetch_link_by_id(&pool, id).await?.expect("link exists");+ assert!(!link.needs_reauth);+ assert!(link.last_sync_error_at.is_none());++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_needs_reauth_on_missing_link_is_not_a_transition(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let missing = macro_uuid::generate_uuid_v7();+ assert!(!set_link_needs_reauth(&pool, missing).await?);+ 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 1a18d3e600..6ed3582d49 100644--- a/rust/cloud-storage/email_service/src/api/email/init.rs+++ b/rust/cloud-storage/email_service/src/api/email/init.rs@@ -737,6 +737,8 @@ async fn enable_gmail_sync_for(provider: link::UserProvider::Gmail,is_sync_active: true,is_primary,+ needs_reauth: false,+ last_sync_error_at: None,created_at: Default::default(),updated_at: Default::default(),};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 2375a0a5c6..b54e22e5dc 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@@ -90,6 +90,7 @@ pub async fn list_links_handler(.map_err(ListLinksError::DatabaseError)?;let sync_status = api::link::SyncStatus::derive(link.is_sync_active,+ link.needs_reauth,latest_job.map(|job| job.status),);diff --git a/rust/cloud-storage/email_service/src/api/middleware/link.rs b/rust/cloud-storage/email_service/src/api/middleware/link.rsindex de112cbecc..28049aca78 100644--- a/rust/cloud-storage/email_service/src/api/middleware/link.rs+++ b/rust/cloud-storage/email_service/src/api/middleware/link.rs@@ -31,6 +31,10 @@ pub(in crate::api) async fn attach_link_context<U: EmailService>(provider,is_sync_active: link.is_sync_active,is_primary: link.is_primary,+ // Health fields aren't part of the request-scoped link context the hex+ // extractor resolves; they're only read from the persisted link.+ needs_reauth: false,+ last_sync_error_at: None,created_at: link.created_at,updated_at: link.updated_at,});diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rsindex 678d61113d..d19884dcce 100644--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs@@ -470,6 +470,7 @@ async fn main() -> anyhow::Result<()> {let sqs_client_link_manager = sqs_client.clone();let crm_service_link_manager = crm_service.clone();let connection_gateway_client_link_manager = connection_gateway_client.clone();+ let notification_ingress_service_link_manager = notification_ingress_service.clone();// daily link_manager operations for user contacts and inbox subscriptionstokio::spawn(async move {email_service::pubsub::link_manager::worker::run_worker(@@ -481,6 +482,7 @@ async fn main() -> anyhow::Result<()> {sqs_client_link_manager,crm_service_link_manager,connection_gateway_client_link_manager,+ notification_ingress_service_link_manager,).await;});diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rsindex a3b7fe449a..c6dbaa1e4b 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs@@ -4,7 +4,7 @@ use crate::pubsub::backfill::{populate_crm_for_user, update_metadata,};use crate::pubsub::context::PubSubContext;-use crate::util::gmail::auth::fetch_token_or_delete_on_revocation;+use crate::util::gmail::auth::fetch_token_or_mark_reauth;use anyhow::Context;use models_email::email::service::backfill::{BackfillJob, BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, JobScopedPayload,@@ -218,8 +218,9 @@ async fn fetch_job_context<P>(return Ok(None);};- let access_token = fetch_token_or_delete_on_revocation(+ let access_token = fetch_token_or_mark_reauth(&link,+ &ctx.db,&ctx.redis_client,&ctx.auth_service_client,&ctx.sqs_client,diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/process.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/process.rsindex 0f144532bc..8b2d03de57 100644--- a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/process.rs@@ -115,8 +115,9 @@ pub async fn fetch_gmail_token(ctx: &GmailOpsContext,link: &Link,) -> Result<String, ProcessingError> {- let gmail_access_token = crate::util::gmail::auth::fetch_token_or_delete_on_revocation(+ let gmail_access_token = crate::util::gmail::auth::fetch_token_or_mark_reauth(link,+ &ctx.db,&ctx.redis_client,&ctx.auth_service_client,&ctx.sqs_client,diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rsindex fa402b5d1d..8f171cd1b3 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs@@ -4,7 +4,9 @@ use crate::pubsub::inbox_sync::operations::shared::notify_search;use crate::pubsub::inbox_sync::process;use crate::pubsub::inbox_sync::process::check_gmail_rate_limit_inbox_sync;use crate::pubsub::util::cg_refresh_email;-use crate::pubsub::util::{CrmContactRecipient, enqueue_populate_crm_contacts};+use crate::pubsub::util::{+ CrmContactRecipient, build_notification_recipients, enqueue_populate_crm_contacts,+};use crate::util::process_pre_insert::{process_message_pre_insert, process_threads_pre_insert};use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};use contacts::domain::ports::ContactsIngress;@@ -611,30 +613,6 @@ async fn send_notifications(Ok(())}-fn build_notification_recipients(- owner: &MacroUserIdStr<'static>,- primaries: Vec<String>,-) -> HashSet<MacroUserIdStr<'static>> {- let mut recipient_ids = HashSet::from([owner.clone()]);-- for primary in primaries {- match MacroUserIdStr::try_from(primary) {- Ok(id) => {- recipient_ids.insert(id);- }- Err(e) => {- tracing::warn!(- error=?e,- inbox_owner=%owner,- "skipping delegated primary that failed to parse as a macro user id"- );- }- }- }-- recipient_ids-}-// filter out messages we don't want to send notifications for#[tracing::instrument(skip(ctx, link))]async fn filter_notifiable_message(diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rsindex fdb14f6d4e..64e4e5e3c4 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs@@ -129,8 +129,9 @@ pub async fn fetch_pubsub_gmail_token(ctx: &PubSubContext,link: &Link,) -> result::Result<String, ProcessingError> {- let gmail_access_token = crate::util::gmail::auth::fetch_token_or_delete_on_revocation(+ let gmail_access_token = crate::util::gmail::auth::fetch_token_or_mark_reauth(link,+ &ctx.db,&ctx.redis_client,&ctx.auth_service_client,&ctx.sqs_client,diff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/context.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/context.rsindex 8186fa9b41..ac4658c3d3 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/context.rs@@ -1,10 +1,11 @@-use crate::pubsub::context::CrmServiceType;+use crate::pubsub::context::{CrmServiceType, NotificationIngressType};use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;use gmail_client::GmailClient;use sqlx::PgPool;use sqs_client::SQS;+use std::sync::Arc;#[derive(Clone)]pub struct LinkManagerContext {@@ -16,4 +17,5 @@ pub struct LinkManagerContext {pub sqs_client: SQS,pub crm_service: CrmServiceType,pub connection_gateway_client: ConnectionGatewayClient,+ pub notification_ingress_service: Arc<NotificationIngressType>,}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 9c1de009f6..c70854cbc6 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@@ -1,15 +1,20 @@use crate::pubsub::link_manager::context::LinkManagerContext;-use crate::pubsub::util::cg_refresh_email;+use crate::pubsub::util::{build_notification_recipients, cg_refresh_email};use crate::util::gmail::auth::{- fetch_gmail_access_token_from_link, fetch_token_or_delete_on_revocation, is_forbidden_error,+ fetch_gmail_access_token_from_link, fetch_token_or_mark_reauth, is_forbidden_error,+ is_reauth_required_error,};use crate::util::sync_contacts::sync_contacts;use anyhow::{Context, anyhow};use crm::domain::service::CrmService;+use model_entity::EntityType;+use model_notifications::InboxReauthRequiredMetadata;use models_email::api::refresh::RefreshEmailEvent;use models_email::email::service::pubsub::{DeletionReason, LinkManagerMessage};use models_email::service::cache::TokenCacheKey;use models_email::service::link::{Link, UserProvider};+use notification::domain::models::SendNotificationRequestBuilder;+use notification::domain::service::NotificationIngress;use sqs_client::search::SearchQueueMessage;use sqs_client::search::email::EmailLinkMessage;use sqs_worker::cleanup_message;@@ -26,14 +31,41 @@ pub async fn process_message(let link = get_link_or_skip(&ctx, message, link_id).await?;let Some(link) = link else { return Ok(()) };- let gmail_access_token = fetch_token_or_delete_on_revocation(+ match fetch_token_or_mark_reauth(&link,+ &ctx.db,&ctx.redis_client,&ctx.auth_service_client,&ctx.sqs_client,)- .await?;- handle_refresh(&ctx, &link, &gmail_access_token).await?;+ .await+ {+ Ok(gmail_access_token) => {+ handle_refresh(&ctx, &link, &gmail_access_token).await?;+ }+ // The grant is gone. There is nothing to refresh until the user+ // reconnects, so drop the message rather than retrying a fetch that+ // cannot succeed — but only once the reauth flag is actually+ // persisted, otherwise retry so the health signal isn't lost when the+ // mark write itself failed.+ Err(e) if is_reauth_required_error(&e) => {+ let persisted = email_db_client::links::get::fetch_link_by_id(&ctx.db, link.id)+ .await+ .context("Failed to verify needs_reauth state after token fetch failure")?+ .is_some_and(|l| l.needs_reauth);++ if !persisted {+ return Err(e.context("reauth required but needs_reauth not persisted"));+ }+ }+ Err(e) => return Err(e),+ }+ }+ LinkManagerMessage::NotifyReauthRequired { link_id } => {+ let link = get_link_or_skip(&ctx, message, link_id).await?;+ let Some(link) = link else { return Ok(()) };++ handle_notify_reauth_required(&ctx, &link).await?;}LinkManagerMessage::DeleteLink {link_id,@@ -137,6 +169,43 @@ async fn handle_refresh(Ok(())}+/// Notifies the inbox owner and every delegate that the link's grant has died and+/// the inbox must be reconnected. Reuses the new-mail recipient computation so a+/// shared inbox reaches everyone who could hold the Google grant.+#[tracing::instrument(skip(ctx), fields(link = ?link), err)]+async fn handle_notify_reauth_required(+ ctx: &LinkManagerContext,+ link: &Link,+) -> anyhow::Result<()> {+ let primaries = macro_db_client::macro_user_links::get_primaries_for_link(+ &ctx.db,+ link.macro_id.as_ref(),+ link.id,+ )+ .await+ .context("Failed to fetch delegated primaries for reauth notification")?;++ let recipient_ids = build_notification_recipients(&link.macro_id, primaries);++ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::User.with_entity_string(link.macro_id.to_string()),+ notification: InboxReauthRequiredMetadata {+ email_address: link.email_address.0.as_ref().to_string(),+ },+ sender_id: None,+ recipient_ids,+ }+ .into_request()+ .with_conn_gateway();++ ctx.notification_ingress_service+ .send_notification(request)+ .await+ .map_err(|e| anyhow!("failed to send reauth notification: {e}"))?;++ Ok(())+}+/// Fetches all links for a user and deletes each one via the existing delete handler.#[tracing::instrument(skip(ctx), err)]async fn handle_delete_all_user_links(diff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/worker.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/worker.rsindex e95962b025..1cd92ee572 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/worker.rs@@ -1,4 +1,4 @@-use crate::pubsub::context::CrmServiceType;+use crate::pubsub::context::{CrmServiceType, NotificationIngressType};use crate::pubsub::link_manager::context::LinkManagerContext;use crate::pubsub::link_manager::process;use crate::util::redis::RedisClient;@@ -7,6 +7,7 @@ use connection_gateway_client::client::ConnectionGatewayClient;use futures::StreamExt;use sqlx::PgPool;use sqs_client::SQS;+use std::sync::Arc;/// method that ingests sqs messages and calls the process function for each#[allow(clippy::too_many_arguments)]@@ -19,6 +20,7 @@ pub async fn run_worker(sqs_client: SQS,crm_service: CrmServiceType,connection_gateway_client: ConnectionGatewayClient,+ notification_ingress_service: Arc<NotificationIngressType>,) {let ctx = LinkManagerContext {db,@@ -29,6 +31,7 @@ pub async fn run_worker(sqs_client,crm_service,connection_gateway_client,+ notification_ingress_service,};loop {let worker_result = tokio::spawn({diff --git a/rust/cloud-storage/email_service/src/pubsub/util.rs b/rust/cloud-storage/email_service/src/pubsub/util.rsindex 928ec6a017..f70d581e54 100644--- a/rust/cloud-storage/email_service/src/pubsub/util.rs+++ b/rust/cloud-storage/email_service/src/pubsub/util.rs@@ -3,8 +3,12 @@ use crate::util::redis::RedisClient;use crate::util::redis::rate_limit::RateLimitArgs;use chrono::{DateTime, Utc};use connection_gateway_client::client::ConnectionGatewayClient;+use macro_user_id::user_id::MacroUserIdStr;/// shared utils across different pubsub workersuse models_email::api::refresh::RefreshEmailEvent;++#[cfg(test)]+mod test;use models_email::email::service::backfill::{BackfillOperation, BackfillPubsubMessage, DepopulateCrmContactPayload, LinkScopedPayload,PopulateCrmContactPayload,@@ -14,6 +18,34 @@ use models_email::gmail::operations::GmailApiOperation;use std::collections::HashSet;use uuid::Uuid;+/// The macro users to notify about a link's inbox: its owner plus every primary+/// delegated to read it. Shared by the new-mail and reauth notification paths so+/// both fan out to the same recipients. Delegated primaries that fail to parse as+/// a macro user id are skipped.+pub fn build_notification_recipients(+ owner: &MacroUserIdStr<'static>,+ primaries: Vec<String>,+) -> HashSet<MacroUserIdStr<'static>> {+ let mut recipient_ids = HashSet::from([owner.clone()]);++ for primary in primaries {+ match MacroUserIdStr::try_from(primary) {+ Ok(id) => {+ recipient_ids.insert(id);+ }+ Err(e) => {+ tracing::warn!(+ error=?e,+ inbox_owner=%owner,+ "skipping delegated primary that failed to parse as a macro user id"+ );+ }+ }+ }++ recipient_ids+}+/// One recipient tuple `(email, name, first_at, last_at)` fed into/// [`enqueue_populate_crm_contacts`]. Per-message paths use the same/// timestamp for both endpoints; the historical seed passes thediff --git a/rust/cloud-storage/email_service/src/pubsub/util/test.rs b/rust/cloud-storage/email_service/src/pubsub/util/test.rsnew file mode 100644index 0000000000..0b589e66ed--- /dev/null+++ b/rust/cloud-storage/email_service/src/pubsub/util/test.rs@@ -0,0 +1,45 @@+use super::build_notification_recipients;+use macro_user_id::user_id::MacroUserIdStr;++fn id(s: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(s.to_string()).expect("valid macro user id")+}++#[test]+fn fans_out_to_owner_and_every_delegated_primary() {+ let owner = id("macro|[email protected]");+ let primaries = vec![+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ ];++ let recipients = build_notification_recipients(&owner, primaries);++ assert_eq!(recipients.len(), 3);+ assert!(recipients.contains(&owner));+ assert!(recipients.contains(&id("macro|[email protected]")));+ assert!(recipients.contains(&id("macro|[email protected]")));+}++#[test]+fn owner_only_when_no_delegates() {+ let owner = id("macro|[email protected]");+ let recipients = build_notification_recipients(&owner, vec![]);+ assert_eq!(recipients.len(), 1);+ assert!(recipients.contains(&owner));+}++#[test]+fn skips_primaries_that_fail_to_parse() {+ let owner = id("macro|[email protected]");+ let primaries = vec![+ "not-a-macro-id".to_string(),+ "macro|[email protected]".to_string(),+ ];++ let recipients = build_notification_recipients(&owner, primaries);++ assert_eq!(recipients.len(), 2);+ assert!(recipients.contains(&owner));+ assert!(recipients.contains(&id("macro|[email protected]")));+}diff --git a/rust/cloud-storage/email_service/src/util/gmail/auth.rs b/rust/cloud-storage/email_service/src/util/gmail/auth.rsindex edc38dd314..5c5cc42966 100644--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs@@ -16,35 +16,58 @@ use models_email::gmail::inbox_sync::KeyMap;use sqs_client::SQS;use std::sync::Arc;-/// Fetches Gmail access token from link and triggers link deletion if access was revoked.-/// This should be used by pubsub handlers where we want to automatically clean up revoked links.-/// API handlers should use `fetch_gmail_access_token_from_link` directly instead.-#[tracing::instrument(skip(redis_client, auth_service_client, sqs_client))]-pub async fn fetch_token_or_delete_on_revocation(+/// Fetches a Gmail access token for a link and records its sync health as a side+/// effect: clears the link's reauth flag on success, and on a revoked or missing+/// grant marks the link as needing reauth (and enqueues a one-time fan-out+/// notification on the first such transition). Other, transient failures are+/// returned unchanged without touching health state.+///+/// Pubsub handlers should use this so a dead grant surfaces for reconnect instead+/// of stalling silently. API handlers should use `fetch_gmail_access_token_from_link`.+#[tracing::instrument(skip(db, redis_client, auth_service_client, sqs_client))]+pub async fn fetch_token_or_mark_reauth(link: &Link,+ db: &sqlx::PgPool,redis_client: &RedisClient,auth_service_client: &AuthServiceClient,sqs_client: &SQS,) -> anyhow::Result<String> {match fetch_gmail_access_token_from_link(link, redis_client, auth_service_client).await {- Ok(token) => Ok(token),- Err(e) if is_forbidden_error(&e) => {+ Ok(token) => {+ email_db_client::links::update::clear_link_needs_reauth(db, link.id)+ .await+ .inspect_err(|e| {+ tracing::warn!(error=?e, link_id=%link.id, "Failed to clear needs_reauth after successful token fetch");+ })+ .ok();+ Ok(token)+ }+ Err(e) if is_reauth_required_error(&e) => {tracing::warn!(link_id = %link.id,fusionauth_user_id = %link.fusionauth_user_id,- "User revoked access to Gmail - enqueueing link deletion"+ "Gmail grant no longer yields a token - marking link as needing reauth");- sqs_client- .enqueue_link_manager_notification(LinkManagerMessage::DeleteLink {- link_id: link.id,- deletion_reason: models_email::email::service::pubsub::DeletionReason::AccessRevoked,- })- .await- .inspect_err(|e| {- tracing::error!(error=?e, link_id=%link.id, "Failed to enqueue link deletion after detecting revoked access");- })- .ok();+ match email_db_client::links::update::set_link_needs_reauth(db, link.id).await {+ // Only the transition into needs-reauth fans out a notification, so a+ // link that keeps failing every cycle notifies its sharers just once.+ Ok(true) => {+ sqs_client+ .enqueue_link_manager_notification(+ LinkManagerMessage::NotifyReauthRequired { link_id: link.id },+ )+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, link_id=%link.id, "Failed to enqueue reauth notification");+ })+ .ok();+ }+ Ok(false) => {}+ Err(e) => {+ tracing::error!(error=?e, link_id=%link.id, "Failed to mark link as needing reauth");+ }+ }Err(e)}@@ -52,7 +75,7 @@ pub async fn fetch_token_or_delete_on_revocation(}}-/// Checks if an error chain contains a Forbidden error from the auth service+/// Checks if an error chain contains a Forbidden error from the auth service.pub(crate) fn is_forbidden_error(e: &anyhow::Error) -> bool {e.chain().any(|cause| {cause@@ -62,6 +85,23 @@ pub(crate) fn is_forbidden_error(e: &anyhow::Error) -> bool {})}+/// Whether a token-fetch error means the link's grant is gone (revoked, or the+/// underlying IdP link is missing) and the user must reconnect — as opposed to a+/// transient failure that should be retried without flagging the link.+pub fn is_reauth_required_error(e: &anyhow::Error) -> bool {+ e.chain().any(|cause| {+ cause+ .downcast_ref::<AuthServiceClientError>()+ .map(|e| {+ matches!(+ e,+ AuthServiceClientError::Forbidden | AuthServiceClientError::NotFound+ )+ })+ .unwrap_or(false)+ })+}+/// Creates a cache key using a link, then fetches access token. Returns error if access token can't/// be fetched.pub async fn fetch_gmail_access_token_from_link(diff --git a/rust/cloud-storage/macro_db_client/migrations/20260615180337_add_email_links_reauth_health.sql b/rust/cloud-storage/macro_db_client/migrations/20260615180337_add_email_links_reauth_health.sqlnew file mode 100644index 0000000000..647f75c526--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260615180337_add_email_links_reauth_health.sql@@ -0,0 +1,6 @@+-- Per-link sync health. `needs_reauth` is set when a link's Google grant stops+-- yielding a token (revoked / missing) and cleared on the next successful token+-- fetch; `last_sync_error_at` records when the failure was last observed.+ALTER TABLE email_links+ ADD COLUMN needs_reauth boolean NOT NULL DEFAULT false,+ ADD COLUMN last_sync_error_at timestamptz;diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rsindex 2bd6924977..5419dfe73c 100644--- a/rust/cloud-storage/model_notifications/src/lib.rs+++ b/rust/cloud-storage/model_notifications/src/lib.rs@@ -15,9 +15,10 @@ pub use metadata::{DocumentMentionMetadata, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment,GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention,GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState,- GithubPrStatusChanged, GithubReviewRequested, InviteToTeamMetadata, ItemSharedMetadata,- MentionedInDocumentCommentMetadata, NewEmailMetadata, NotificationDocumentSubType,- NotificationTitle, RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata,+ GithubPrStatusChanged, GithubReviewRequested, InboxReauthRequiredMetadata,+ InviteToTeamMetadata, ItemSharedMetadata, MentionedInDocumentCommentMetadata, NewEmailMetadata,+ NotificationDocumentSubType, NotificationTitle, RepliedToDocumentCommentThreadMetadata,+ TaskAssignedMetadata,};pub use unsubscribe::UserUnsubscribe;#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]@@ -195,6 +196,9 @@ define_notif_event!(/// A new email has been sent to the user.NewEmail(NewEmailMetadata),+ /// A linked inbox's grant died and must be reconnected.+ InboxReauthRequired(InboxReauthRequiredMetadata),+/// A user was invited to a team.InviteToTeam(InviteToTeamMetadata),@@ -253,6 +257,7 @@ impl NotificationTitle for NotifEvent {channel_reply_metadata.format_title(sender_id)}NotifEvent::NewEmail(new_email_metadata) => new_email_metadata.format_title(sender_id),+ NotifEvent::InboxReauthRequired(m) => m.format_title(sender_id),NotifEvent::InviteToTeam(_) => Err(report!("not implemented")),NotifEvent::TaskAssigned(task_assigned_metadata) => {task_assigned_metadata.format_title(sender_id)@@ -305,6 +310,7 @@ impl NotificationTitle for NotifEvent {channel_reply_metadata.format_body(sender_id)}NotifEvent::NewEmail(new_email_metadata) => new_email_metadata.format_body(sender_id),+ NotifEvent::InboxReauthRequired(m) => m.format_body(sender_id),NotifEvent::InviteToTeam(_) => Err(report!("not implemented")),NotifEvent::TaskAssigned(task_assigned_metadata) => {task_assigned_metadata.format_body(sender_id)diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rsindex 3608de1cdd..d7b6fb193c 100644--- a/rust/cloud-storage/model_notifications/src/metadata.rs+++ b/rust/cloud-storage/model_notifications/src/metadata.rs@@ -682,6 +682,40 @@ pub struct NewEmailMetadata {pub snippet: String,}+/// Metadata for a notification that a linked inbox's grant has died and the+/// inbox must be reconnected. Fanned out to the inbox owner and every delegate,+/// since any of them holding the Google grant can restore sync.+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct InboxReauthRequiredMetadata {+ /// The address of the inbox that needs to be reconnected.+ #[serde(alias = "email_address")]+ pub email_address: String,+}++impl notification::domain::models::Notification for InboxReauthRequiredMetadata {+ const TYPE_NAME: &'static str = "inbox_reauth_required";+}++impl NotificationTitle for InboxReauthRequiredMetadata {+ fn format_title(+ &self,+ _sender_id: Option<MacroUserIdStr<'_>>,+ ) -> Result<String, rootcause::Report> {+ Ok(format!("Reconnect {}", self.email_address))+ }++ fn format_body(+ &self,+ _sender_id: Option<MacroUserIdStr<'_>>,+ ) -> Result<String, rootcause::Report> {+ Ok(+ "Sync stopped because the Google connection expired. Reconnect to restore it."+ .to_string(),+ )+ }+}+impl notification::domain::models::Notification for NewEmailMetadata {const TYPE_NAME: &'static str = "new_email";}diff --git a/rust/cloud-storage/models_email/src/email/api/link.rs b/rust/cloud-storage/models_email/src/email/api/link.rsindex 79207c0254..46c1ea2a39 100644--- a/rust/cloud-storage/models_email/src/email/api/link.rs+++ b/rust/cloud-storage/models_email/src/email/api/link.rs@@ -7,9 +7,12 @@ use serde::{Deserialize, Serialize};use utoipa::ToSchema;use uuid::Uuid;+#[cfg(test)]+mod test;+/// 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.+/// multi-inbox settings list. Derived from the link's `is_sync_active` flag, its+/// reauth health, and its most recent backfill job.#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, ToSchema)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]pub enum SyncStatus {@@ -19,18 +22,30 @@ pub enum SyncStatus {UpToDate,/// The most recent backfill failed; the user can re-sync to recover.Error,+ /// The link's Google grant has stopped working; the user must reconnect.+ NeedsReauth,/// 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 {+ /// Derives the sync status from the link's active flag, its reauth health,+ /// and the status of its most recent backfill job (if any). A dead grant+ /// takes precedence over backfill state because no sync can proceed until+ /// the user reconnects.+ pub fn derive(+ is_sync_active: bool,+ needs_reauth: bool,+ latest_job_status: Option<BackfillJobStatus>,+ ) -> Self {if !is_sync_active {return SyncStatus::Inactive;}+ if needs_reauth {+ return SyncStatus::NeedsReauth;+ }+match latest_job_status {Some(BackfillJobStatus::Init | BackfillJobStatus::InProgress) => SyncStatus::Syncing,Some(BackfillJobStatus::Failed | BackfillJobStatus::Cancelled) => SyncStatus::Error,@@ -80,6 +95,9 @@ pub struct Link {pub provider: UserProvider,pub is_sync_active: bool,pub sync_status: SyncStatus,+ /// Whether the link's Google grant needs to be reconnected. Drives the+ /// per-inbox reconnect prompt independently of the sync-status badge.+ pub needs_reauth: bool,pub signature: Option<String>,pub settings: Settings,pub is_primary: bool,@@ -104,6 +122,7 @@ impl Link {provider: UserProvider::from(source.provider),is_sync_active: source.is_sync_active,sync_status,+ needs_reauth: source.needs_reauth,signature,settings,is_primary: source.is_primary,diff --git a/rust/cloud-storage/models_email/src/email/api/link/test.rs b/rust/cloud-storage/models_email/src/email/api/link/test.rsnew file mode 100644index 0000000000..16be2122db--- /dev/null+++ b/rust/cloud-storage/models_email/src/email/api/link/test.rs@@ -0,0 +1,48 @@+use super::*;++#[test]+fn inactive_link_is_inactive_regardless_of_reauth() {+ assert_eq!(SyncStatus::derive(false, false, None), SyncStatus::Inactive);+ assert_eq!(SyncStatus::derive(false, true, None), SyncStatus::Inactive);+}++#[test]+fn needs_reauth_takes_precedence_over_backfill_state() {+ assert_eq!(+ SyncStatus::derive(true, true, None),+ SyncStatus::NeedsReauth+ );+ assert_eq!(+ SyncStatus::derive(true, true, Some(BackfillJobStatus::InProgress)),+ SyncStatus::NeedsReauth+ );+ assert_eq!(+ SyncStatus::derive(true, true, Some(BackfillJobStatus::Complete)),+ SyncStatus::NeedsReauth+ );+}++#[test]+fn healthy_link_derives_from_backfill_state() {+ assert_eq!(SyncStatus::derive(true, false, None), SyncStatus::UpToDate);+ assert_eq!(+ SyncStatus::derive(true, false, Some(BackfillJobStatus::Complete)),+ SyncStatus::UpToDate+ );+ assert_eq!(+ SyncStatus::derive(true, false, Some(BackfillJobStatus::Init)),+ SyncStatus::Syncing+ );+ assert_eq!(+ SyncStatus::derive(true, false, Some(BackfillJobStatus::InProgress)),+ SyncStatus::Syncing+ );+ assert_eq!(+ SyncStatus::derive(true, false, Some(BackfillJobStatus::Failed)),+ SyncStatus::Error+ );+ assert_eq!(+ SyncStatus::derive(true, false, Some(BackfillJobStatus::Cancelled)),+ SyncStatus::Error+ );+}diff --git a/rust/cloud-storage/models_email/src/email/service/link.rs b/rust/cloud-storage/models_email/src/email/service/link.rsindex a7cfe3e336..2fd88a4190 100644--- a/rust/cloud-storage/models_email/src/email/service/link.rs+++ b/rust/cloud-storage/models_email/src/email/service/link.rs@@ -15,6 +15,11 @@ pub struct Link {pub provider: UserProvider,pub is_sync_active: bool,pub is_primary: bool,+ /// Set when the link's Google grant stops yielding a token (revoked or+ /// missing); cleared on the next successful token fetch.+ pub needs_reauth: bool,+ /// When the most recent token failure was observed, if any.+ pub last_sync_error_at: Option<DateTime<Utc>>,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,}diff --git a/rust/cloud-storage/models_email/src/email/service/pubsub.rs b/rust/cloud-storage/models_email/src/email/service/pubsub.rsindex 772cd56119..599fe4035c 100644--- a/rust/cloud-storage/models_email/src/email/service/pubsub.rs+++ b/rust/cloud-storage/models_email/src/email/service/pubsub.rs@@ -75,6 +75,10 @@ pub enum LinkManagerMessage {},/// Delete all links for a user, identified by fusionauth_user_id.DeleteUser { fusionauth_user_id: String },+ /// Notify everyone who can act on a link (its owner and any delegates) that+ /// its grant has gone dead and the inbox needs to be reconnected. Enqueued+ /// once, on the edge where a link first transitions into needs-reauth.+ NotifyReauthRequired { link_id: Uuid },}/// The message we send from the email_scheduled_handler lambda to the service via SQS to triggerdiff --git a/rust/cloud-storage/seed_cli/src/entity/email/mod.rs b/rust/cloud-storage/seed_cli/src/entity/email/mod.rsindex 08988ffee1..fd8a7f2caf 100644--- a/rust/cloud-storage/seed_cli/src/entity/email/mod.rs+++ b/rust/cloud-storage/seed_cli/src/entity/email/mod.rs@@ -438,6 +438,8 @@ async fn seed(args: SeedArgs, ctx: SeedCliContext) -> anyhow::Result<()> {provider: seed_data.provider,is_sync_active: true,is_primary,+ needs_reauth: false,+ last_sync_error_at: None,created_at: now,updated_at: now,};