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): live backfill progress in inbox settings (#4263)
Evan Hutnikaf233d9bfdf7
diff --git a/js/app/packages/app/component/settings/Email.tsx b/js/app/packages/app/component/settings/Email.tsxindex 53778fdbd8..fecd89845c 100644--- a/js/app/packages/app/component/settings/Email.tsx+++ b/js/app/packages/app/component/settings/Email.tsx@@ -12,11 +12,17 @@ import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';import ArrowsClockwiseIcon from '@phosphor-icons/core/regular/arrows-clockwise.svg?component-solid';import PlusIcon from '@phosphor-icons/core/regular/plus.svg?component-solid';import {+ type BackfillJob,+ BackfillJobStatus,type Link as EmailLink,SyncStatus,} from '@service-email/generated/schemas';import { useEmail, useUserId } from '@core/context/user';-import { createMemo, createSignal, For, Show } from 'solid-js';+import {+ getBackfillProgress,+ useBackfillJobsQuery,+} from '@queries/email/backfill';+import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';import {useAddInboxFlow,useEmailLinks,@@ -50,6 +56,25 @@ export function Email() {const emailActive = useEmailLinksStatus();const startAddInbox = useAddInboxFlow();+ // Fires when the Email settings open. Used only to surface the COMPLETED+ // state; in-progress state comes from the live connection-gateway store.+ const backfillJobsQuery = useBackfillJobsQuery();+ // Latest job per link. The query returns newest-first, so the first job seen+ // for a link_id is its latest — we key the settled label off the current job,+ // not any historical completed one (a later fail/cancel must not still read+ // as "complete").+ const latestBackfillByLinkId = createMemo(() => {+ const latest = new Map<string, BackfillJob>();+ for (const job of backfillJobsQuery.data?.jobs ?? []) {+ if (job.link_id && !latest.has(job.link_id)) {+ latest.set(job.link_id, job);+ }+ }+ return latest;+ });+ const hasCompletedBackfill = (linkId: string): boolean =>+ latestBackfillByLinkId().get(linkId)?.status === BackfillJobStatus.Complete;+const removeInboxMutation = useRemoveInboxMutation({onSuccess: () => toast.success('Inbox removed'),onError: () => toast.failure('Failed to remove inbox. Please try again.'),@@ -218,6 +243,7 @@ export function Email() {link={primary()}isPrimaryisOwn={primary().macro_id === userId()}+ hasCompletedBackfill={hasCompletedBackfill(primary().id)}resyncing={resyncingIds().has(primary().id)}onResync={() => handleResyncInbox(primary().id)}onReconnect={() => void startAddInbox()}@@ -243,6 +269,7 @@ export function Email() {link={link}isPrimary={false}isOwn={link.macro_id === userId()}+ hasCompletedBackfill={hasCompletedBackfill(link.id)}resyncing={resyncingIds().has(link.id)}onResync={() => handleResyncInbox(link.id)}onReconnect={() => void startAddInbox()}@@ -381,6 +408,30 @@ function syncStatusLabel(status: SyncStatus): string {.exhaustive();}+// Live backfill progress bar. `completed`/`total` are the connection-gateway+// counters; render the ratio rather than the raw counts since the priority pass+// can inflate both slightly above the real mailbox size.+function BackfillProgressBar(props: { completed: number; total: number }) {+ const percent = () =>+ props.total > 0+ ? Math.min(100, Math.round((props.completed / props.total) * 100))+ : 0;+ return (+ <div class="flex w-40 flex-col gap-1">+ <span class="flex items-center gap-1 text-xs text-ink-muted">+ <ArrowsClockwiseIcon class="size-3 animate-spin" />+ Syncing… {percent()}%+ </span>+ <div class="h-1 w-full overflow-hidden rounded-full bg-edge-muted">+ <div+ class="h-full rounded-full bg-ink transition-[width] duration-300"+ style={{ width: `${percent()}%` }}+ />+ </div>+ </div>+ );+}+function Chip(props: { label: string }) {return (<span class="shrink-0 rounded bg-edge-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-ink-muted">@@ -416,6 +467,7 @@ function InboxRow(props: {link: EmailLink;isPrimary: boolean;isOwn: boolean;+ hasCompletedBackfill: boolean;resyncing: boolean;onResync: () => void;onReconnect: () => void;@@ -435,28 +487,49 @@ function InboxRow(props: {<Chip label="Shared" /></Show></div>- <Show- when={- ENABLE_INBOX_SYNC_STATUS &&- props.link.sync_status !== SyncStatus.UP_TO_DATE- }- >- <span- class="flex items-center gap-1 text-xs"- classList={{- '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={ENABLE_INBOX_SYNC_STATUS}>+ <Switch+ fallback={+ <Show when={props.link.sync_status !== SyncStatus.UP_TO_DATE}>+ <span+ class="flex items-center gap-1 text-xs"+ classList={{+ '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}>+ <ArrowsClockwiseIcon class="size-3 animate-spin" />+ </Show>+ {syncStatusLabel(props.link.sync_status)}+ </span>+ </Show>+ }>- <Show when={props.link.sync_status === SyncStatus.SYNCING}>- <ArrowsClockwiseIcon class="size-3 animate-spin" />- </Show>- {syncStatusLabel(props.link.sync_status)}- </span>+ {/* Live backfill progress (connection gateway) wins over the coarse+ sync_status while a backfill is actively running. */}+ <Match when={getBackfillProgress(props.link.id)}>+ {(progress) => (+ <BackfillProgressBar+ completed={progress().completed}+ total={progress().total}+ />+ )}+ </Match>+ {/* Settled inbox with a completed backfill from the BE list. */}+ <Match+ when={+ props.link.sync_status === SyncStatus.UP_TO_DATE &&+ props.hasCompletedBackfill+ }+ >+ <span class="text-xs text-ink-muted">Initial sync complete</span>+ </Match>+ </Switch></Show></div><div class="flex items-center gap-2 shrink-0">diff --git a/js/app/packages/queries/email/backfill.ts b/js/app/packages/queries/email/backfill.tsnew file mode 100644index 0000000000..79ac9d11b9--- /dev/null+++ b/js/app/packages/queries/email/backfill.ts@@ -0,0 +1,87 @@+import { throwOnErr } from '@core/util/result';+import { queryClient } from '@queries/client';+import { emailClient } from '@service-email/client';+import { useQuery } from '@tanstack/solid-query';+import { createSignal } from 'solid-js';+import { emailKeys } from './keys';++/**+ * How far along a link's backfill is, as last reported by a `backfill_progress`+ * websocket event. `completed`/`total` mirror the backend's `completed_threads`+ * / `total_threads`. Both can read slightly above the real mailbox size — the+ * priority pass inflates them in lockstep — so prefer the ratio over the+ * absolute numbers when rendering.+ */+export type BackfillProgress = {+ completed: number;+ total: number;+};++/**+ * Ephemeral, in-memory store of per-link backfill progress, written by the+ * `backfill_progress` handler in `sync.ts` and read by the inbox sync UI. An+ * entry exists only while a link is actively backfilling; it's removed on+ * completion, failure, or link removal. Not persisted — on reload the coarse+ * `sync_status` from the links query takes over until the next event arrives.+ */+const [progressByLink, setProgressByLink] = createSignal<+ Map<string, BackfillProgress>+>(new Map());++/** Record the latest progress for a link, replacing any previous value. */+export function setBackfillProgress(+ linkId: string,+ progress: BackfillProgress+): void {+ setProgressByLink((prev) => {+ const next = new Map(prev);+ next.set(linkId, progress);+ return next;+ });+}++/** Drop a link's progress entry (on completion, failure, or link removal). */+export function clearBackfillProgress(linkId: string): void {+ setProgressByLink((prev) => {+ if (!prev.has(linkId)) return prev;+ const next = new Map(prev);+ next.delete(linkId);+ return next;+ });+}++/**+ * Current backfill progress for a link, or `undefined` if it isn't actively+ * backfilling. Call inside a reactive scope to track updates.+ */+export function getBackfillProgress(+ linkId: string+): BackfillProgress | undefined {+ return progressByLink().get(linkId);+}++/**+ * Lists every backfill job for the user. Fired when the email settings open, to+ * surface COMPLETED backfills. In-progress backfills are driven by the live+ * progress store above (connection-gateway events), not this query — its counts+ * can lag the live counters — so consumers should read this only for terminal+ * (e.g. completed) jobs.+ */+export function useBackfillJobsQuery() {+ return useQuery(() => ({+ queryKey: emailKeys.backfillJobs.queryKey,+ queryFn: async () =>+ throwOnErr(async () => await emailClient.listBackfillJobs()),+ }));+}++/**+ * Refetch the backfill jobs list. Call on terminal backfill events so the+ * settled "completed" state updates even while the email settings stay open+ * (the query otherwise only fires on mount).+ */+export function invalidateBackfillJobs() {+ queryClient.invalidateQueries({+ queryKey: emailKeys.backfillJobs.queryKey,+ });+}diff --git a/js/app/packages/queries/email/keys.ts b/js/app/packages/queries/email/keys.tsindex 95a44e73bc..b3d0eea4f4 100644--- a/js/app/packages/queries/email/keys.ts+++ b/js/app/packages/queries/email/keys.ts@@ -6,6 +6,7 @@ export const emailKeys = createQueryKeys('email', {labels: null,links: null,linksHealthProbe: null,+ backfillJobs: null,threads: null,thread: (threadId: string) => ({queryKey: [threadId],diff --git a/js/app/packages/queries/email/sync.ts b/js/app/packages/queries/email/sync.tsindex 6558a3f1c9..d47609e78c 100644--- a/js/app/packages/queries/email/sync.ts+++ b/js/app/packages/queries/email/sync.ts@@ -5,8 +5,14 @@ import {BackfillStatus,type RefreshEmailEvent,RefreshEmailEventOneOfOneoneEvent,+ RefreshEmailEventOneOfOnethreeEvent,} from '@service-email/generated/schemas';import { leadingAndTrailing, throttle } from '@solid-primitives/scheduled';+import {+ clearBackfillProgress,+ invalidateBackfillJobs,+ setBackfillProgress,+} from './backfill';import { invalidateEmailLinks } from './link';const BACKFILL_SOUP_REFRESH_INTERVAL = 5_000;@@ -31,15 +37,16 @@ function asRefreshEmailEvent(payload: unknown): RefreshEmailEvent | undefined {* Handles `refresh_email` websocket events. Steady-state mutations* (`upsert_message`, `update_labels`, `delete_message`) already invalidate soup* through the notification-driven path, and reacting to them again would- * double-refetch, so only `backfill`, `link_removed`, and `photo_synced` act- * here.+ * double-refetch, so only `backfill_progress`, `backfill`, `link_removed`, and+ * `photo_synced` act here.*- * Backfill produces no notifications, so this is its only refresh signal.- * `progress` refetches soup, throttled because the backend emits one event per- * batch of threads. `complete`/`failed` additionally refetch the links list so- * the inbox's `sync_status` settles out of `SYNCING`, and surface a toast.- * `photo_synced` refetches the links list so the inbox's derived `photo_url`- * lands once its self-contact photo finishes uploading.+ * Backfill produces no notifications, so these are its only refresh signals.+ * `backfill_progress` carries live progress: it refetches soup (throttled,+ * because the backend emits one event per batch of threads) and on `complete`+ * refetches the links list so the inbox's `sync_status` settles out of+ * `SYNCING`, with a toast. The legacy `backfill` event now only signals+ * failure. `photo_synced` refetches the links list so the inbox's derived+ * `photo_url` lands once its self-contact photo finishes uploading.*/export function handleRefreshEmail(payload: unknown): void {const event = asRefreshEmailEvent(payload);@@ -49,8 +56,10 @@ export function handleRefreshEmail(payload: unknown): void {// settle its links row. This is the only reliable signal that teardown is// done; refetching on the delete request itself races the cascade delete.if (event.event === 'link_removed') {+ clearBackfillProgress(event.link_id);invalidateAllSoup();invalidateEmailLinks();+ invalidateBackfillJobs();return;}@@ -61,23 +70,39 @@ export function handleRefreshEmail(payload: unknown): void {return;}- if (event.event !== 'backfill') return;- const { status } = event;-- if (status === BackfillStatus.failed) {- invalidateEmailLinks();- if (ENABLE_INBOX_SYNC_STATUS) {- toast.failure('Inbox sync failed');+ // Backfill failed — settle the links row out of `SYNCING` and surface it.+ // Progress and completion now arrive as `backfill_progress` instead.+ if (event.event === 'backfill') {+ if (event.status === BackfillStatus.failed) {+ clearBackfillProgress(event.link_id);+ invalidateEmailLinks();+ invalidateBackfillJobs();+ if (ENABLE_INBOX_SYNC_STATUS) {+ toast.failure('Inbox sync failed');+ }}return;}- throttledBackfillSoupRefresh();+ // Live backfill progress. Record `completed_threads`/`total_threads` for the+ // progress UI and keep soup fresh (throttled, one event per batch). On+ // completion, drop the progress entry and settle the links row out of+ // `SYNCING` with a toast.+ if (event.event === RefreshEmailEventOneOfOnethreeEvent.backfill_progress) {+ throttledBackfillSoupRefresh();- if (status === BackfillStatus.complete) {- invalidateEmailLinks();- if (ENABLE_INBOX_SYNC_STATUS) {- toast.success('Inbox synced');+ if (event.status === BackfillStatus.complete) {+ clearBackfillProgress(event.link_id);+ invalidateEmailLinks();+ invalidateBackfillJobs();+ if (ENABLE_INBOX_SYNC_STATUS) {+ toast.success('Inbox synced');+ }+ } else {+ setBackfillProgress(event.link_id, {+ completed: event.completed_threads,+ total: event.total_threads,+ });}}}diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.tsindex 37daeeb4da..b7b5f9ec0d 100644--- a/js/app/packages/service-clients/service-email/client.ts+++ b/js/app/packages/service-clients/service-email/client.ts@@ -15,6 +15,7 @@ import type {GetAttachmentDocumentIDResponse,GetAttachmentResponse,GetThreadResponse,+ ListBackfillJobsResponse,ListContactsResponse,ListEmailFiltersResponse,ListLabelsResponse,@@ -261,6 +262,14 @@ export const emailClient = {).map((result) => result);},+ async listBackfillJobs() {+ return (+ await emailFetch<ListBackfillJobsResponse>('/email/backfill/gmail', {+ method: 'GET',+ })+ ).map((result) => result);+ },+async deleteLink(args: { linkId: string }) {const { linkId } = args;return (diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.tsindex b4f0d77ea5..57644faecc 100644--- a/js/app/packages/service-clients/service-email/generated/client.ts+++ b/js/app/packages/service-clients/service-email/generated/client.ts@@ -30,6 +30,7 @@ import type {GetThreadResponse,InitResponse,InitUserParams,+ ListBackfillJobsResponse,ListBlockedResponse,ListContactsResponse,ListEmailFiltersResponse,@@ -194,6 +195,62 @@ export const getAttachmentDocumentId = async (} as getAttachmentDocumentIdResponse;};+/**+ * @summary List all backfill jobs for the authenticated user, across every link they+own. Scoped by the user's fusionauth id from the request context rather than+a single resolved link.+ */+export type listBackfillGmailResponse200 = {+ data: ListBackfillJobsResponse;+ status: 200;+};++export type listBackfillGmailResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type listBackfillGmailResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type listBackfillGmailResponseSuccess = listBackfillGmailResponse200 & {+ headers: Headers;+};+export type listBackfillGmailResponseError = (+ | listBackfillGmailResponse401+ | listBackfillGmailResponse500+) & {+ headers: Headers;+};++export type listBackfillGmailResponse =+ | listBackfillGmailResponseSuccess+ | listBackfillGmailResponseError;++export const getListBackfillGmailUrl = () => {+ return `/email/backfill/gmail`;+};++export const listBackfillGmail = async (+ options?: RequestInit+): Promise<listBackfillGmailResponse> => {+ const res = await fetch(getListBackfillGmailUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: listBackfillGmailResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as listBackfillGmailResponse;+};+/*** @summary Cancel a backfill job.*/diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.tsindex 18c85abcce..07e074dd0c 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts@@ -189,6 +189,7 @@ export * from './labelTypeProperty';export * from './link';export * from './linkPhotoUrl';export * from './linkSignature';+export * from './listBackfillJobsResponse';export * from './listBlockedResponse';export * from './listContactsResponse';export * from './listContactsResponseContacts';@@ -233,6 +234,8 @@ export * from './refreshEmailEventOneOfNine';export * from './refreshEmailEventOneOfNineEvent';export * from './refreshEmailEventOneOfOneone';export * from './refreshEmailEventOneOfOneoneEvent';+export * from './refreshEmailEventOneOfOnethree';+export * from './refreshEmailEventOneOfOnethreeEvent';export * from './refreshEmailEventOneOfSeven';export * from './refreshEmailEventOneOfSevenEvent';export * from './refreshEmailEventOneOfThree';diff --git a/js/app/packages/service-clients/service-email/generated/schemas/listBackfillJobsResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/listBackfillJobsResponse.tsnew file mode 100644index 0000000000..68c35fc31d--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/listBackfillJobsResponse.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { BackfillJob } from './backfillJob';++/**+ * The response returned from the list backfill jobs endpoint+ */+export interface ListBackfillJobsResponse {+ jobs: BackfillJob[];+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEvent.ts b/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEvent.tsindex 386dadb246..dd995b274c 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEvent.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEvent.ts@@ -8,6 +8,7 @@ import type { RefreshEmailEventOneOf } from './refreshEmailEventOneOf';import type { RefreshEmailEventOneOfFive } from './refreshEmailEventOneOfFive';import type { RefreshEmailEventOneOfNine } from './refreshEmailEventOneOfNine';import type { RefreshEmailEventOneOfOneone } from './refreshEmailEventOneOfOneone';+import type { RefreshEmailEventOneOfOnethree } from './refreshEmailEventOneOfOnethree';import type { RefreshEmailEventOneOfSeven } from './refreshEmailEventOneOfSeven';import type { RefreshEmailEventOneOfThree } from './refreshEmailEventOneOfThree';@@ -21,4 +22,5 @@ export type RefreshEmailEvent =| RefreshEmailEventOneOfFive| RefreshEmailEventOneOfSeven| RefreshEmailEventOneOfNine- | RefreshEmailEventOneOfOneone;+ | RefreshEmailEventOneOfOneone+ | RefreshEmailEventOneOfOnethree;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEventOneOfOnethree.ts b/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEventOneOfOnethree.tsnew file mode 100644index 0000000000..da05864d8f--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEventOneOfOnethree.ts@@ -0,0 +1,24 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++import type { BackfillStatus } from './backfillStatus';+import type { RefreshEmailEventOneOfOnethreeEvent } from './refreshEmailEventOneOfOnethreeEvent';++/**+ * Live backfill progress for `link_id`, for driving a progress indicator on+the frontend: `completed_threads` out of `total_threads`, plus `status`.+Counts reflect the Redis progress counters; the priority pass may bump+both above the raw mailbox size, but in lockstep, so the ratio holds.+Appended last so existing variants keep their generated TS names.+ */+export type RefreshEmailEventOneOfOnethree = {+ completed_threads: number;+ event: RefreshEmailEventOneOfOnethreeEvent;+ link_id: string;+ status: BackfillStatus;+ total_threads: number;+};diff --git a/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEventOneOfOnethreeEvent.ts b/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEventOneOfOnethreeEvent.tsnew file mode 100644index 0000000000..11c9785a59--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/refreshEmailEventOneOfOnethreeEvent.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++export type RefreshEmailEventOneOfOnethreeEvent =+ (typeof RefreshEmailEventOneOfOnethreeEvent)[keyof typeof RefreshEmailEventOneOfOnethreeEvent];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RefreshEmailEventOneOfOnethreeEvent = {+ backfill_progress: 'backfill_progress',+} as const;diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex 0aa4a1a3f5..dc5a1f19db 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -153,6 +153,43 @@}},"/email/backfill/gmail": {+ "get": {+ "tags": ["Init"],+ "summary": "List all backfill jobs for the authenticated user, across every link they\nown. Scoped by the user's fusionauth id from the request context rather than\na single resolved link.",+ "operationId": "list_backfill_gmail",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ListBackfillJobsResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },"delete": {"tags": ["Init"],"summary": "Cancel a backfill job.",@@ -4253,6 +4290,19 @@}}},+ "ListBackfillJobsResponse": {+ "type": "object",+ "description": "The response returned from the list backfill jobs endpoint",+ "required": ["jobs"],+ "properties": {+ "jobs": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BackfillJob"+ }+ }+ }+ },"ListBlockedResponse": {"type": "object","description": "Response containing list of blocked email addresses.",@@ -4717,6 +4767,38 @@"format": "uuid"}}+ },+ {+ "type": "object",+ "description": "Live backfill progress for `link_id`, for driving a progress indicator on\nthe frontend: `completed_threads` out of `total_threads`, plus `status`.\nCounts reflect the Redis progress counters; the priority pass may bump\nboth above the raw mailbox size, but in lockstep, so the ratio holds.\nAppended last so existing variants keep their generated TS names.",+ "required": [+ "link_id",+ "status",+ "completed_threads",+ "total_threads",+ "event"+ ],+ "properties": {+ "completed_threads": {+ "type": "integer",+ "format": "int32"+ },+ "event": {+ "type": "string",+ "enum": ["backfill_progress"]+ },+ "link_id": {+ "type": "string",+ "format": "uuid"+ },+ "status": {+ "$ref": "#/components/schemas/BackfillStatus"+ },+ "total_threads": {+ "type": "integer",+ "format": "int32"+ }+ }}],"description": "Payload for the `refresh_email` connection gateway event: identifies the\ninbox that changed and the kind of change."diff --git a/rust/cloud-storage/.sqlx/query-311d0f633b6a6a886d277868afc7c5b06f113e04f158ac20fadc093737c5567a.json b/rust/cloud-storage/.sqlx/query-311d0f633b6a6a886d277868afc7c5b06f113e04f158ac20fadc093737c5567a.jsonnew file mode 100644index 0000000000..45e12b4266--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-311d0f633b6a6a886d277868afc7c5b06f113e04f158ac20fadc093737c5567a.json@@ -0,0 +1,83 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE fusionauth_user_id = $1\n ORDER BY created_at DESC\n LIMIT 100\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "fusionauth_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "threads_requested_limit",+ "type_info": "Int4"+ },+ {+ "ordinal": 4,+ "name": "total_threads",+ "type_info": "Int4"+ },+ {+ "ordinal": 5,+ "name": "threads_retrieved_count",+ "type_info": "Int4"+ },+ {+ "ordinal": 6,+ "name": "status: db::backfill::BackfillJobStatus",+ "type_info": {+ "Custom": {+ "name": "email_backfill_job_status",+ "kind": {+ "Enum": [+ "Init",+ "InProgress",+ "Complete",+ "Cancelled",+ "Failed"+ ]+ }+ }+ }+ },+ {+ "ordinal": 7,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ false,+ true,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "311d0f633b6a6a886d277868afc7c5b06f113e04f158ac20fadc093737c5567a"+}diff --git a/rust/cloud-storage/email_db_client/src/backfill/job/get.rs b/rust/cloud-storage/email_db_client/src/backfill/job/get.rsindex 0d96d01ee4..26e58ec612 100644--- a/rust/cloud-storage/email_db_client/src/backfill/job/get.rs+++ b/rust/cloud-storage/email_db_client/src/backfill/job/get.rs@@ -164,5 +164,44 @@ pub async fn get_recent_jobs_by_fusionauth_user_id(Ok(jobs)}+/// Retrieves a user's most recent backfill jobs, newest first. Spans all of the+/// user's links and all statuses; `link_id` is intentionally not used so jobs+/// survive a link being deleted and recreated. Capped at 100 so frequent+/// resyncs can't grow the response unbounded — the settings UI only needs the+/// current per-link state, which the newest jobs cover.+#[tracing::instrument(skip(pool), err)]+pub async fn get_all_jobs_by_fusionauth_user_id(+ pool: &PgPool,+ fusionauth_user_id: &str,+) -> anyhow::Result<Vec<service::backfill::BackfillJob>> {+ let records = sqlx::query_as!(+ db::backfill::BackfillJob,+ r#"+ SELECT+ id,+ link_id,+ fusionauth_user_id,+ threads_requested_limit,+ total_threads,+ threads_retrieved_count,+ status as "status: db::backfill::BackfillJobStatus",+ created_at,+ updated_at+ FROM email_backfill_jobs+ WHERE fusionauth_user_id = $1+ ORDER BY created_at DESC+ LIMIT 100+ "#,+ fusionauth_user_id+ )+ .fetch_all(pool)+ .await?;++ // Convert all database records to service models+ let jobs = records.into_iter().map(Into::into).collect();++ Ok(jobs)+}+#[cfg(test)]mod test;diff --git a/rust/cloud-storage/email_db_client/src/backfill/job/get/test.rs b/rust/cloud-storage/email_db_client/src/backfill/job/get/test.rsindex 3541d3a238..17cdca6a19 100644--- a/rust/cloud-storage/email_db_client/src/backfill/job/get/test.rs+++ b/rust/cloud-storage/email_db_client/src/backfill/job/get/test.rs@@ -1,4 +1,4 @@-use super::get_recent_jobs_by_fusionauth_user_id;+use super::{get_all_jobs_by_fusionauth_user_id, get_recent_jobs_by_fusionauth_user_id};use macro_db_migrator::MACRO_DB_MIGRATIONS;use models_email::email::db::backfill::BackfillJobStatus as DbStatus;use models_email::email::service::backfill::BackfillJobStatus;@@ -49,3 +49,47 @@ async fn recent_jobs_excludes_terminal_and_old_and_other_users(Ok(())}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn all_jobs_returns_users_jobs_any_status_newest_first(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ const FUSION: &str = "fusion-all-jobs-user";+ const OTHER: &str = "fusion-other-user";++ // Unlike the recent query, every status counts and there's no time window.+ insert_job(&pool, FUSION, DbStatus::Complete, 3).await; // oldest+ insert_job(&pool, FUSION, DbStatus::InProgress, 2).await;+ insert_job(&pool, FUSION, DbStatus::Cancelled, 1).await;+ insert_job(&pool, FUSION, DbStatus::Failed, 0).await; // newest+ insert_job(&pool, FUSION, DbStatus::Init, 100).await; // well outside any 24h window+ // Different user → excluded.+ insert_job(&pool, OTHER, DbStatus::Complete, 1).await;++ let jobs = get_all_jobs_by_fusionauth_user_id(&pool, FUSION).await?;++ assert_eq!(jobs.len(), 5);+ assert!(jobs.iter().all(|j| j.fusionauth_user_id == FUSION));+ // Newest-first ordering.+ assert!(+ jobs.windows(2).all(|w| w[0].created_at >= w[1].created_at),+ "jobs should be ordered newest-first"+ );++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn all_jobs_caps_at_100(pool: Pool<Postgres>) -> anyhow::Result<()> {+ const FUSION: &str = "fusion-cap-user";++ for _ in 0..105 {+ insert_job(&pool, FUSION, DbStatus::Complete, 0).await;+ }++ let jobs = get_all_jobs_by_fusionauth_user_id(&pool, FUSION).await?;++ assert_eq!(jobs.len(), 100, "result should be capped at LIMIT 100");++ Ok(())+}diff --git a/rust/cloud-storage/email_service/src/api/email/backfill/get.rs b/rust/cloud-storage/email_service/src/api/email/backfill/get.rsindex a59258e548..f1ce11f77a 100644--- a/rust/cloud-storage/email_service/src/api/email/backfill/get.rs+++ b/rust/cloud-storage/email_service/src/api/email/backfill/get.rs@@ -130,3 +130,60 @@ impl IntoResponse for GetActiveBackfillError {.into_response()}}++/// The response returned from the list backfill jobs endpoint+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct ListBackfillJobsResponse {+ pub jobs: Vec<BackfillJob>,+}++/// List all backfill jobs for the authenticated user, across every link they+/// own. Scoped by the user's fusionauth id from the request context rather than+/// a single resolved link.+#[utoipa::path(+ get,+ tag = "Init",+ path = "/email/backfill/gmail",+ operation_id = "list_backfill_gmail",+ responses(+ (status = 200, body=ListBackfillJobsResponse),+ (status = 401, body=ErrorResponse),+ (status = 500, body=ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]+pub async fn list_handler(+ State(ctx): State<ApiContext>,+ user_context: Extension<UserContext>,+) -> Result<Response, ListBackfillJobsError> {+ let jobs = email_db_client::backfill::job::get::get_all_jobs_by_fusionauth_user_id(+ &ctx.db,+ &user_context.fusion_user_id,+ )+ .await+ .map_err(ListBackfillJobsError::QueryError)?;++ Ok(Json(ListBackfillJobsResponse { jobs }).into_response())+}++#[derive(Debug, Error, AsRefStr)]+pub enum ListBackfillJobsError {+ #[error("Failed to list backfill jobs from database")]+ QueryError(#[from] anyhow::Error),+}++impl IntoResponse for ListBackfillJobsError {+ fn into_response(self) -> Response {+ let status_code = match self {+ ListBackfillJobsError::QueryError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ (+ status_code,+ Json(ErrorResponse {+ message: self.to_string().into(),+ }),+ )+ .into_response()+ }+}diff --git a/rust/cloud-storage/email_service/src/api/email/backfill/mod.rs b/rust/cloud-storage/email_service/src/api/email/backfill/mod.rsindex 6d5bb5f0f8..3f5eeb2307 100644--- a/rust/cloud-storage/email_service/src/api/email/backfill/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/backfill/mod.rs@@ -7,12 +7,19 @@ use axum::routing::{delete, get};use crate::api::ApiContext;pub fn router(state: ApiContext) -> Router<ApiContext> {- Router::new()+ // Link-scoped routes: each resolves and attaches the caller's email link.+ let link_scoped = Router::new().route("/gmail", delete(cancel::handler)).route("/gmail/{id}", get(get::handler)).route("/gmail/active", get(get::active_handler)).layer(axum::middleware::from_fn_with_state(state.email_service,crate::api::middleware::link::attach_link_context,- ))+ ));++ // GET /gmail is the user-scoped collection: it lists jobs across all of the+ // user's links via the fusionauth id in the request context, so it must not+ // go through the link middleware. Merged onto the same /gmail path as DELETE+ // (different method, so no conflict).+ link_scoped.merge(Router::new().route("/gmail", get(get::list_handler)))}diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rsindex 9384b64934..2c41588ccc 100644--- a/rust/cloud-storage/email_service/src/api/swagger.rs+++ b/rust/cloud-storage/email_service/src/api/swagger.rs@@ -1,7 +1,9 @@use crate::api::email::attachments::get::GetAttachmentResponse;use crate::api::email::attachments::get_document_id::GetAttachmentDocumentIDResponse;use crate::api::email::backfill::cancel::CancelBackfillParams;-use crate::api::email::backfill::get::{GetActiveBackfillJobResponse, GetBackfillJobResponse};+use crate::api::email::backfill::get::{+ GetActiveBackfillJobResponse, GetBackfillJobResponse, ListBackfillJobsResponse,+};use crate::api::email::contacts::block_sender::BlockSenderRequest;use crate::api::email::contacts::list::ListContactsResponse;use crate::api::email::contacts::list_blocked::ListBlockedResponse;@@ -65,6 +67,7 @@ use utoipa::OpenApi;email::backfill::cancel::handler,email::backfill::get::handler,email::backfill::get::active_handler,+ email::backfill::get::list_handler,email::init::handler,inbound::axum::draft_router::create_draft_handler,email::drafts::delete::handler,@@ -110,6 +113,7 @@ use utoipa::OpenApi;CancelBackfillParams,GetBackfillJobResponse,GetActiveBackfillJobResponse,+ ListBackfillJobsResponse,BackfillJob,// Draft typesHexCreateDraftRequest,diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rsindex c9fde06859..f788a02ba0 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs@@ -17,8 +17,10 @@ use models_email::service::link::Link;use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use uuid::Uuid;-/// Emit a `refresh_email` event once per this many completed threads, plus-/// once at job completion, rather than per-thread.+/// Emit a `refresh_email` event once per this many completed threads, plus on+/// the first completed thread and at job completion, rather than per-thread.+/// The first-thread emit ensures backfills smaller than this interval still+/// surface a progress event before completing.const REFRESH_EMAIL_THREAD_INTERVAL: i32 = 50;/// called when a thread has completed processing. checks if it is the last thread to be processed@@ -40,17 +42,22 @@ pub async fn incr_completed_threads(})})?;- if progress.job_complete || progress.completed_threads % REFRESH_EMAIL_THREAD_INTERVAL == 0 {+ if progress.job_complete+ || progress.completed_threads == 1+ || progress.completed_threads % REFRESH_EMAIL_THREAD_INTERVAL == 0+ {cg_refresh_email(&ctx.connection_gateway_client,link.macro_id.as_ref(),- RefreshEmailEvent::Backfill {+ RefreshEmailEvent::BackfillProgress {link_id: link.id,status: if progress.job_complete {BackfillStatus::Complete} else {BackfillStatus::Progress},+ completed_threads: progress.completed_threads,+ total_threads: progress.total_threads,},).await;diff --git a/rust/cloud-storage/email_service/src/util/redis/backfill.rs b/rust/cloud-storage/email_service/src/util/redis/backfill.rsindex 7a71d8cab0..608c2d5685 100644--- a/rust/cloud-storage/email_service/src/util/redis/backfill.rs+++ b/rust/cloud-storage/email_service/src/util/redis/backfill.rs@@ -7,6 +7,10 @@ use uuid::Uuid;pub struct BackfillJobProgress {/// Number of threads completed so far, including this increment.pub completed_threads: i32,+ /// The job's target thread total — the denominator for progress. Reflects+ /// the Redis counter, which the priority pass may have bumped above the raw+ /// mailbox size; `completed_threads` is inflated to match, so the ratio holds.+ pub total_threads: i32,/// Whether every thread in the job has now been processed.pub job_complete: bool,}@@ -110,6 +114,7 @@ impl RedisClient {Ok(BackfillJobProgress {completed_threads,+ total_threads,job_complete,})}diff --git a/rust/cloud-storage/models_email/src/email/api/refresh.rs b/rust/cloud-storage/models_email/src/email/api/refresh.rsindex 5449b72e83..109af1d4c9 100644--- a/rust/cloud-storage/models_email/src/email/api/refresh.rs+++ b/rust/cloud-storage/models_email/src/email/api/refresh.rs@@ -35,4 +35,15 @@ pub enum RefreshEmailEvent {/// The self-contact photo for `link_id` finished uploading to static/// file storage, so the inbox's derived `photo_url` is now available.PhotoSynced { link_id: Uuid },+ /// Live backfill progress for `link_id`, for driving a progress indicator on+ /// the frontend: `completed_threads` out of `total_threads`, plus `status`.+ /// Counts reflect the Redis progress counters; the priority pass may bump+ /// both above the raw mailbox size, but in lockstep, so the ratio holds.+ /// Appended last so existing variants keep their generated TS names.+ BackfillProgress {+ link_id: Uuid,+ status: BackfillStatus,+ completed_threads: i32,+ total_threads: i32,+ },}