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(calendar): turn calendar off per inbox (#5693)
gbirmaneb82cb63aa22
diff --git a/.sqlx/query-2121f66406c52de0e5153405c7313fc90d26ba7a35e6e8efa8376ae630af8c75.json b/.sqlx/query-2121f66406c52de0e5153405c7313fc90d26ba7a35e6e8efa8376ae630af8c75.jsonnew file mode 100644index 0000000000..c13d80c340--- /dev/null+++ b/.sqlx/query-2121f66406c52de0e5153405c7313fc90d26ba7a35e6e8efa8376ae630af8c75.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE email_link_google_scopes\n SET calendar_disabled_at = NULL,\n updated_at = now()\n WHERE link_id = $1 AND calendar_disabled_at IS NOT NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "2121f66406c52de0e5153405c7313fc90d26ba7a35e6e8efa8376ae630af8c75"+}diff --git a/.sqlx/query-4143a43174d786e98370acde7c522ad38749cef96f8768d9bdff0386d4700c10.json b/.sqlx/query-4143a43174d786e98370acde7c522ad38749cef96f8768d9bdff0386d4700c10.jsonnew file mode 100644index 0000000000..9ab236ea63--- /dev/null+++ b/.sqlx/query-4143a43174d786e98370acde7c522ad38749cef96f8768d9bdff0386d4700c10.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n c.watch_channel_id AS \"channel_id!\",\n c.watch_resource_id AS \"resource_id!\"\n FROM calendars c\n JOIN calendar_accounts a ON a.id = c.account_id\n WHERE a.email_link_id = $1\n AND c.watch_channel_id IS NOT NULL\n AND c.watch_resource_id IS NOT NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "channel_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "resource_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true,+ true+ ]+ },+ "hash": "4143a43174d786e98370acde7c522ad38749cef96f8768d9bdff0386d4700c10"+}diff --git a/.sqlx/query-46c30f92473c3d7f9785b5253f38a7e8051bd4306d1ab4c3a953e03034fa6e38.json b/.sqlx/query-46c30f92473c3d7f9785b5253f38a7e8051bd4306d1ab4c3a953e03034fa6e38.jsonnew file mode 100644index 0000000000..1c189975d7--- /dev/null+++ b/.sqlx/query-46c30f92473c3d7f9785b5253f38a7e8051bd4306d1ab4c3a953e03034fa6e38.json@@ -0,0 +1,41 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n l.fusionauth_user_id,\n l.email_address::text AS \"email_address!\",\n l.provider::text AS \"provider!\",\n COALESCE(g.granted_scopes, '{}') AS \"granted_scopes!\"\n FROM email_links l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n WHERE l.id = $1 AND l.macro_id = $2\n FOR UPDATE OF l\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "fusionauth_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "email_address!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "provider!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "granted_scopes!",+ "type_info": "TextArray"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ null,+ null,+ null+ ]+ },+ "hash": "46c30f92473c3d7f9785b5253f38a7e8051bd4306d1ab4c3a953e03034fa6e38"+}diff --git a/.sqlx/query-8653d05ff7b1784299919ce6125845ae22c8daebb69b3b62041646c39fb08f90.json b/.sqlx/query-8653d05ff7b1784299919ce6125845ae22c8daebb69b3b62041646c39fb08f90.jsonnew file mode 100644index 0000000000..d13007a6b2--- /dev/null+++ b/.sqlx/query-8653d05ff7b1784299919ce6125845ae22c8daebb69b3b62041646c39fb08f90.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_link_google_scopes (\n link_id, granted_scopes, grant_version, calendar_disabled_at\n )\n VALUES ($1, $2, 1, now())\n ON CONFLICT (link_id) DO UPDATE\n SET granted_scopes = EXCLUDED.granted_scopes,\n grant_version = email_link_google_scopes.grant_version + 1,\n calendar_disabled_at = now(),\n updated_at = now()\n RETURNING grant_version AS \"grant_version!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "grant_version!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "8653d05ff7b1784299919ce6125845ae22c8daebb69b3b62041646c39fb08f90"+}diff --git a/.sqlx/query-91343113c1f5bb42291d27bb2f2b16ab9b43f63f768ea3dbc7d61c16452a9a92.json b/.sqlx/query-9a1dd88fd623f93c9b0d94a10790bd5f860a2bd671301790e406843c18e29bcc.jsonsimilarity index 68%rename from .sqlx/query-91343113c1f5bb42291d27bb2f2b16ab9b43f63f768ea3dbc7d61c16452a9a92.jsonrename to .sqlx/query-9a1dd88fd623f93c9b0d94a10790bd5f860a2bd671301790e406843c18e29bcc.jsonindex a99290a150..728c435121 100644--- a/.sqlx/query-91343113c1f5bb42291d27bb2f2b16ab9b43f63f768ea3dbc7d61c16452a9a92.json+++ b/.sqlx/query-9a1dd88fd623f93c9b0d94a10790bd5f860a2bd671301790e406843c18e29bcc.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT l.id as \"id!\", l.macro_id as \"macro_id!\",\n l.fusionauth_user_id as \"fusionauth_user_id!\",\n l.email_address as \"email_address!\",\n l.provider as \"provider!: _\",\n l.is_sync_active as \"is_sync_active!\",\n l.is_primary as \"is_primary!\",\n l.needs_reauth as \"needs_reauth!\",\n l.last_sync_error_at,\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n s.signature_on_replies_forwards as \"signature_on_replies_forwards?\",\n s.signature,\n bj.status as \"latest_backfill_status?: _\",\n c.sfs_photo_url as \"photo_url?\",\n COALESCE(g.granted_scopes, '{}') AS \"google_granted_scopes!\"\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 ) l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n LEFT JOIN email_settings s ON s.link_id = l.id\n LEFT JOIN LATERAL (\n SELECT status FROM email_backfill_jobs\n WHERE link_id = l.id\n ORDER BY created_at DESC\n LIMIT 1\n ) bj ON true\n LEFT JOIN email_contacts c\n ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)\n ORDER BY l.created_at DESC\n ",+ "query": "\n SELECT l.id as \"id!\", l.macro_id as \"macro_id!\",\n l.fusionauth_user_id as \"fusionauth_user_id!\",\n l.email_address as \"email_address!\",\n l.provider as \"provider!: _\",\n l.is_sync_active as \"is_sync_active!\",\n l.is_primary as \"is_primary!\",\n l.needs_reauth as \"needs_reauth!\",\n l.last_sync_error_at,\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n s.signature_on_replies_forwards as \"signature_on_replies_forwards?\",\n s.signature,\n bj.status as \"latest_backfill_status?: _\",\n c.sfs_photo_url as \"photo_url?\",\n COALESCE(g.granted_scopes, '{}') AS \"google_granted_scopes!\",\n (g.calendar_disabled_at IS NOT NULL) AS \"calendar_disabled!\"\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 ) l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n LEFT JOIN email_settings s ON s.link_id = l.id\n LEFT JOIN LATERAL (\n SELECT status FROM email_backfill_jobs\n WHERE link_id = l.id\n ORDER BY created_at DESC\n LIMIT 1\n ) bj ON true\n LEFT JOIN email_contacts c\n ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)\n ORDER BY l.created_at DESC\n ","describe": {"columns": [{@@ -104,6 +104,11 @@"ordinal": 15,"name": "google_granted_scopes!","type_info": "TextArray"+ },+ {+ "ordinal": 16,+ "name": "calendar_disabled!",+ "type_info": "Bool"}],"parameters": {@@ -127,8 +132,9 @@true,false,true,+ null,null]},- "hash": "91343113c1f5bb42291d27bb2f2b16ab9b43f63f768ea3dbc7d61c16452a9a92"+ "hash": "9a1dd88fd623f93c9b0d94a10790bd5f860a2bd671301790e406843c18e29bcc"}diff --git a/.sqlx/query-d46629520beb24f9ce40480fbaf29efe6e0a14d9d508f5697ccdb70fe42a0488.json b/.sqlx/query-a270aa55700c21f86559761d5ef84611251ba4170197dd3a27d488da5050204d.jsonsimilarity index 66%rename from .sqlx/query-d46629520beb24f9ce40480fbaf29efe6e0a14d9d508f5697ccdb70fe42a0488.jsonrename to .sqlx/query-a270aa55700c21f86559761d5ef84611251ba4170197dd3a27d488da5050204d.jsonindex 8373aa1728..1e9780ceff 100644--- a/.sqlx/query-d46629520beb24f9ce40480fbaf29efe6e0a14d9d508f5697ccdb70fe42a0488.json+++ b/.sqlx/query-a270aa55700c21f86559761d5ef84611251ba4170197dd3a27d488da5050204d.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n l.macro_id,\n l.email_address::text AS \"email_address!\",\n COALESCE(g.granted_scopes, '{}') AS \"granted_scopes!\",\n COALESCE(g.grant_version, 0) AS \"grant_version!\"\n FROM email_links l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n WHERE l.id = $1\n FOR UPDATE OF l\n ",+ "query": "\n SELECT\n l.macro_id,\n l.email_address::text AS \"email_address!\",\n COALESCE(g.granted_scopes, '{}') AS \"granted_scopes!\",\n COALESCE(g.grant_version, 0) AS \"grant_version!\",\n g.calendar_disabled_at\n FROM email_links l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n WHERE l.id = $1\n FOR UPDATE OF l\n ","describe": {"columns": [{@@ -22,6 +22,11 @@"ordinal": 3,"name": "grant_version!","type_info": "Int8"+ },+ {+ "ordinal": 4,+ "name": "calendar_disabled_at",+ "type_info": "Timestamptz"}],"parameters": {@@ -33,8 +38,9 @@false,null,null,- null+ null,+ true]},- "hash": "d46629520beb24f9ce40480fbaf29efe6e0a14d9d508f5697ccdb70fe42a0488"+ "hash": "a270aa55700c21f86559761d5ef84611251ba4170197dd3a27d488da5050204d"}diff --git a/.sqlx/query-aa7c405262b7782ebf1de1d6f08e0ccc0fb2e81ba4620537d75cdac9a31a3a7a.json b/.sqlx/query-aa7c405262b7782ebf1de1d6f08e0ccc0fb2e81ba4620537d75cdac9a31a3a7a.jsonnew file mode 100644index 0000000000..c739674eea--- /dev/null+++ b/.sqlx/query-aa7c405262b7782ebf1de1d6f08e0ccc0fb2e81ba4620537d75cdac9a31a3a7a.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM calendar_accounts WHERE email_link_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "aa7c405262b7782ebf1de1d6f08e0ccc0fb2e81ba4620537d75cdac9a31a3a7a"+}diff --git a/.sqlx/query-1c26edf29d47ee2ca10b21f5ce7ffe278ba07f69aa005d64c3a7c51a57b7242b.json b/.sqlx/query-d2d763c3bd44e383c60265785052c8414dc58578f76bda5b1380e9f05efcd998.jsonsimilarity index 53%rename from .sqlx/query-1c26edf29d47ee2ca10b21f5ce7ffe278ba07f69aa005d64c3a7c51a57b7242b.jsonrename to .sqlx/query-d2d763c3bd44e383c60265785052c8414dc58578f76bda5b1380e9f05efcd998.jsonindex b3fe176e4a..9335255e0e 100644--- a/.sqlx/query-1c26edf29d47ee2ca10b21f5ce7ffe278ba07f69aa005d64c3a7c51a57b7242b.json+++ b/.sqlx/query-d2d763c3bd44e383c60265785052c8414dc58578f76bda5b1380e9f05efcd998.json@@ -1,16 +1,17 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO email_link_google_scopes (link_id, granted_scopes, grant_version)\n VALUES ($1, $2, $3)\n ON CONFLICT (link_id) DO UPDATE\n SET granted_scopes = EXCLUDED.granted_scopes,\n grant_version = EXCLUDED.grant_version,\n updated_at = now()\n ",+ "query": "\n INSERT INTO email_link_google_scopes (link_id, granted_scopes, grant_version)\n VALUES ($1, $2, $3)\n ON CONFLICT (link_id) DO UPDATE\n SET granted_scopes = EXCLUDED.granted_scopes,\n grant_version = EXCLUDED.grant_version,\n calendar_disabled_at = CASE\n WHEN $4 THEN NULL\n ELSE email_link_google_scopes.calendar_disabled_at\n END,\n updated_at = now()\n ","describe": {"columns": [],"parameters": {"Left": ["Uuid","TextArray",- "Int8"+ "Int8",+ "Bool"]},"nullable": []},- "hash": "1c26edf29d47ee2ca10b21f5ce7ffe278ba07f69aa005d64c3a7c51a57b7242b"+ "hash": "d2d763c3bd44e383c60265785052c8414dc58578f76bda5b1380e9f05efcd998"}diff --git a/.sqlx/query-ddd88eef7f2461c8dfb8b442d6f11b66fc309a5eceb026ac874be21aed13c1b8.json b/.sqlx/query-ddd88eef7f2461c8dfb8b442d6f11b66fc309a5eceb026ac874be21aed13c1b8.jsonnew file mode 100644index 0000000000..4982a742da--- /dev/null+++ b/.sqlx/query-ddd88eef7f2461c8dfb8b442d6f11b66fc309a5eceb026ac874be21aed13c1b8.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM calendar_event_reminder_deliveries d\n WHERE d.event_id = ANY($1)\n AND NOT EXISTS (\n SELECT 1 FROM calendar_events e WHERE e.id = d.event_id\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "ddd88eef7f2461c8dfb8b442d6f11b66fc309a5eceb026ac874be21aed13c1b8"+}diff --git a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx b/apps/web/src/features/auth/CalendarPermissionPrompt.tsxindex c626ca3a37..56aa2316c7 100644--- a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx+++ b/apps/web/src/features/auth/CalendarPermissionPrompt.tsx@@ -15,7 +15,10 @@ import { useEmailLinksQuery } from '@queries/email/link';** Inboxes that also need a full reconnect are skipped so the two prompts don't* stack. Reconnecting restores the mailbox without calendar access, which- * leaves `needs_calendar_permission` set and brings this prompt back.+ * leaves `needs_calendar_permission` set and brings this prompt back. So are+ * inboxes whose calendar the user turned off — that reads as missing calendar+ * permission too, and nagging someone to re-enable what they just removed is+ * the one thing this prompt must never do.** Closing the prompt sticks across reloads. Nothing is broken while calendar* is off, so re-asking every load is just nagging — Settings › Email keeps a@@ -31,7 +34,10 @@ export function CalendarPermissionPrompt() {items: () =>calendarUiEnabled() && promptAllowed()? (linksQuery.data?.links ?? []).filter(- (link) => link.needs_calendar_permission && !link.needs_reauth+ (link) =>+ link.needs_calendar_permission &&+ !link.needs_reauth &&+ !link.calendar_disabled): [],key: (link) => link.id,diff --git a/apps/web/src/features/calendar/CalendarSettingsDropdown.tsx b/apps/web/src/features/calendar/CalendarSettingsDropdown.tsxindex 30987e3e53..0e6e64c231 100644--- a/apps/web/src/features/calendar/CalendarSettingsDropdown.tsx+++ b/apps/web/src/features/calendar/CalendarSettingsDropdown.tsx@@ -9,6 +9,11 @@ import { createMemo, createSignal, For, Show } from 'solid-js';import { MobileCalendarPeriodControls } from './CalendarPeriodSelector';import { useCalendarView } from './CalendarViewContext';import type { CalendarTimeFormat, CalendarWeekStart } from './events/types';+import {+ TurnOffCalendarDialog,+ type TurnOffCalendarTarget,+ useCalendarConnectedInboxes,+} from './TurnOffCalendarDialog';const WEEK_START_OPTIONS: Array<{value: CalendarWeekStart;@@ -29,6 +34,9 @@ const TIME_FORMAT_OPTIONS: Array<{function createCalendarSettingsControls() {const calendarView = useCalendarView();const sidePanel = useSidePanel();+ const connectedInboxes = useCalendarConnectedInboxes();+ const [turnOffTarget, setTurnOffTarget] =+ createSignal<TurnOffCalendarTarget | null>(null);const showCalendarVisibility = () =>(sidePanel?.isNarrow() ?? false) && calendarView.sources().length > 1;@@ -67,6 +75,25 @@ function createCalendarSettingsControls() {calendarView.setTimeFormat(timeFormat);};+ // Only ever the viewer's own connected inboxes, so a delegate can never turn+ // off (and delete) the owner's calendar from here. The address is shown only+ // when more than one inbox could be meant.+ const turnOffItems = createMemo(() => {+ const inboxes = connectedInboxes();+ return inboxes.map((link) => ({+ target: { linkId: link.id, emailAddress: link.email_address },+ label:+ inboxes.length > 1+ ? `Turn off calendar for ${link.email_address}`+ : 'Turn off calendar',+ }));+ });++ const startTurnOff = (target: TurnOffCalendarTarget) => {+ calendarView.closeEventDetails();+ setTurnOffTarget(target);+ };+return {calendarView,showCalendarVisibility,@@ -76,6 +103,10 @@ function createCalendarSettingsControls() {changeShowWeekends,changeWeekStartsOn,changeTimeFormat,+ turnOffItems,+ turnOffTarget,+ startTurnOff,+ clearTurnOffTarget: () => setTurnOffTarget(null),};}@@ -205,6 +236,23 @@ function DesktopCalendarSettings(props: {</Dropdown.SubContent></Dropdown.Sub></Dropdown.Group>++ <Show when={controls.turnOffItems().length > 0}>+ <Dropdown.Group>+ <Dropdown.GroupLabel>Calendar access</Dropdown.GroupLabel>+ <For each={controls.turnOffItems()}>+ {(item) => (+ <Dropdown.Item+ closeOnSelect+ class="text-failure"+ onSelect={() => controls.startTurnOff(item.target)}+ >+ <span class="min-w-0 flex-1 truncate">{item.label}</span>+ </Dropdown.Item>+ )}+ </For>+ </Dropdown.Group>+ </Show></Dropdown.Content></Dropdown>);@@ -312,7 +360,7 @@ function MobileCalendarSettings(props: { controls: CalendarSettingsControls }) {</MobileDrawer.Section><MobileDrawer.Label class="pt-4">Time format</MobileDrawer.Label>- <MobileDrawer.Section class="mb-3 flex shrink-0 flex-col">+ <MobileDrawer.Section class="flex shrink-0 flex-col"><For each={TIME_FORMAT_OPTIONS}>{(option) => (<button@@ -336,22 +384,55 @@ function MobileCalendarSettings(props: { controls: CalendarSettingsControls }) {)}</For></MobileDrawer.Section>++ <Show when={controls.turnOffItems().length > 0}>+ <MobileDrawer.Label class="pt-4">+ Calendar access+ </MobileDrawer.Label>+ <MobileDrawer.Section class="mb-3 flex shrink-0 flex-col">+ <For each={controls.turnOffItems()}>+ {(item) => (+ <button+ type="button"+ class={DRAWER_ROW_CLASS}+ onClick={() => {+ setOpen(false);+ controls.startTurnOff(item.target);+ }}+ >+ <span class="min-w-0 flex-1 truncate text-failure">+ {item.label}+ </span>+ </button>+ )}+ </For>+ </MobileDrawer.Section>+ </Show></MobileDrawer.Content></MobileDrawer.Portal></MobileDrawer>);}-/** Responsive calendar display settings menu. */+/**+ * Responsive calendar display settings menu. The turn-off confirmation lives+ * outside the menu so it survives the menu closing on select.+ */export function CalendarSettingsDropdown() {const controls = createCalendarSettingsControls();return (- <Show- when={isMobile()}- fallback={<DesktopCalendarSettings controls={controls} />}- >- <MobileCalendarSettings controls={controls} />- </Show>+ <>+ <Show+ when={isMobile()}+ fallback={<DesktopCalendarSettings controls={controls} />}+ >+ <MobileCalendarSettings controls={controls} />+ </Show>+ <TurnOffCalendarDialog+ target={controls.turnOffTarget()}+ onClose={controls.clearTurnOffTarget}+ />+ </>);}diff --git a/apps/web/src/features/calendar/CalendarSetupStatus.tsx b/apps/web/src/features/calendar/CalendarSetupStatus.tsxindex e5b26b10bb..221585fa19 100644--- a/apps/web/src/features/calendar/CalendarSetupStatus.tsx+++ b/apps/web/src/features/calendar/CalendarSetupStatus.tsx@@ -16,6 +16,11 @@ const SETUP_MESSAGES = {description: 'Grant calendar access to show your events in Macro.',action: 'Grant access',},+ disabled: {+ title: 'Calendar is off',+ description: 'Grant calendar access again to show your events in Macro.',+ action: 'Turn on',+ },reauth: {title: 'Reconnect calendar',description: 'Reconnect your Google account to resume calendar sync.',@@ -36,7 +41,7 @@ export function CalendarSetupStatus() {// or delegated inbox can leave events visible without a working calendar// connection belonging to the current user.const setupState = createMemo<- 'connect' | 'permission' | 'reauth' | undefined+ 'connect' | 'permission' | 'reauth' | 'disabled' | undefined>(() => {const activeData = calendarPager.activeData();const range = activeData?.range();@@ -58,7 +63,13 @@ export function CalendarSetupStatus() {if (hasAvailableCalendar) return undefined;if (links.some((link) => link.needs_reauth)) return 'reauth';if (links.some((link) => link.needs_calendar_permission)) {- return 'permission';+ // A calendar the user turned off is not a missing upgrade; say so, and+ // still offer the way back since they came to the calendar view.+ return links.every(+ (link) => !link.needs_calendar_permission || link.calendar_disabled+ )+ ? 'disabled'+ : 'permission';}return 'connect';@@ -68,12 +79,18 @@ export function CalendarSetupStatus() {() => SETUP_MESSAGES[setupState() ?? 'connect']);- // Only the permission state has a working mailbox already; connecting and- // reconnecting both need the mailbox scopes alongside calendar.- const startSetup = () =>+ // The permission and disabled states both sit on a working mailbox —+ // turning calendar off leaves Gmail untouched — so they ask for calendar+ // alone. Connecting and reconnecting need the mailbox scopes alongside it.+ const startSetup = () => {+ const state = setupState();void startAddInbox({- scopes: setupState() === 'permission' ? 'calendar' : 'gmail_and_calendar',+ scopes:+ state === 'permission' || state === 'disabled'+ ? 'calendar'+ : 'gmail_and_calendar',});+ };return (<Show when={setupState() !== undefined}>diff --git a/apps/web/src/features/calendar/TurnOffCalendarDialog.test.tsx b/apps/web/src/features/calendar/TurnOffCalendarDialog.test.tsxnew file mode 100644index 0000000000..3688838513--- /dev/null+++ b/apps/web/src/features/calendar/TurnOffCalendarDialog.test.tsx@@ -0,0 +1,85 @@+/**+ * @vitest-environment jsdom+ */++import { render, screen } from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { ok } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { TurnOffCalendarDialog } from './TurnOffCalendarDialog';++const disableLinkCalendarMock = vi.hoisted(() => vi.fn());++vi.mock('@service-email/client', () => ({+ emailClient: { disableLinkCalendar: disableLinkCalendarMock },+}));++vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: vi.fn(), failure: vi.fn() },+}));++vi.mock('@core/context/user', () => ({ useUserId: () => () => 'macro|self' }));+vi.mock('@queries/calendar/sync', () => ({+ invalidateCalendarViews: vi.fn(),+}));+vi.mock('@queries/auth/user-info', () => ({ invalidateUserInfo: vi.fn() }));+vi.mock('@queries/soup/normalized-cache', () => ({+ invalidateAllSoup: vi.fn(),+}));++let testQueryClient: QueryClient;++vi.mock('@queries/client', () => ({+ get queryClient() {+ return testQueryClient;+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+ testQueryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+});++function renderDialog(onClose = vi.fn()) {+ render(() => (+ <QueryClientProvider client={testQueryClient}>+ <TurnOffCalendarDialog+ target={{ linkId: 'inbox-a', emailAddress: '[email protected]' }}+ onClose={onClose}+ />+ </QueryClientProvider>+ ));+ return onClose;+}++describe('TurnOffCalendarDialog', () => {+ it('names the inbox it is about', () => {+ renderDialog();++ expect(screen.getByText('[email protected]')).toBeTruthy();+ });++ it('turns calendar off for the confirmed inbox and closes', async () => {+ disableLinkCalendarMock.mockResolvedValue(ok({}));+ const onClose = renderDialog();++ screen.getByRole('button', { name: 'Turn off' }).click();+ await vi.waitFor(() =>+ expect(disableLinkCalendarMock).toHaveBeenCalledWith({+ linkId: 'inbox-a',+ })+ );+ expect(onClose).toHaveBeenCalled();+ });++ it('leaves the calendar alone when cancelled', () => {+ const onClose = renderDialog();++ screen.getByRole('button', { name: 'Cancel' }).click();++ expect(disableLinkCalendarMock).not.toHaveBeenCalled();+ expect(onClose).toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/calendar/TurnOffCalendarDialog.tsx b/apps/web/src/features/calendar/TurnOffCalendarDialog.tsxnew file mode 100644index 0000000000..9f278d2915--- /dev/null+++ b/apps/web/src/features/calendar/TurnOffCalendarDialog.tsx@@ -0,0 +1,94 @@+import { toast } from '@core/component/Toast/Toast';+import { useUserId } from '@core/context/user';+import {+ useDisableCalendarMutation,+ useEmailLinksQuery,+} from '@queries/email/link';+import type { Link as EmailLink } from '@service-email/generated/schemas';+import { Button, Dialog, Panel } from '@ui';+import { createMemo } from 'solid-js';++/** The inbox a turn-off confirmation is about. */+export interface TurnOffCalendarTarget {+ linkId: string;+ emailAddress: string;+}++/**+ * The viewer's own inboxes that currently have calendar access, in the order+ * the links list returns them. Delegated inboxes are excluded: the viewer can+ * read the owner's calendar but must not be able to delete the owner's data.+ *+ * An inbox needing reauth still counts — its events are still in Macro, so+ * turning calendar off is still the way to remove them.+ */+export function useCalendarConnectedInboxes() {+ const linksQuery = useEmailLinksQuery();+ const userId = useUserId();+ return createMemo<EmailLink[]>(() =>+ (linksQuery.data?.links ?? []).filter(+ (link) => link.macro_id === userId() && !link.needs_calendar_permission+ )+ );+}++/**+ * Confirms turning calendar off for one inbox and runs the disable. Shared by+ * the connected-accounts settings row and the calendar view's settings menu so+ * both entry points remove the same thing and describe it the same way.+ *+ * Rendered with a `null` target while closed; callers hold the target signal.+ */+export function TurnOffCalendarDialog(props: {+ target: TurnOffCalendarTarget | null;+ onClose: () => void;+}) {+ const disableCalendar = useDisableCalendarMutation({+ onSuccess: () => toast.success('Calendar turned off'),+ onError: () =>+ toast.failure('Failed to turn off calendar. Please try again.'),+ });++ const confirm = () => {+ const target = props.target;+ if (!target) return;+ props.onClose();+ disableCalendar.mutate(target.linkId);+ };++ return (+ <Dialog+ open={props.target !== null}+ onOpenChange={(open) => {+ if (!open) props.onClose();+ }}+ position="center"+ class="w-120"+ >+ <Panel depth={2} class="rounded-xl">+ <Panel.Header class="px-6">+ <Dialog.Title class="text-ink text-sm font-semibold">+ Turn off calendar+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="p-6 font-sans flex flex-col gap-3">+ <Dialog.Description class="text-ink-muted text-sm/tight font-normal">+ Turn off calendar for{' '}+ <span class="text-ink">{props.target?.emailAddress}</span>? Macro+ deletes its copy of these events and gives up calendar access. Your+ Google Calendar is untouched and email keeps syncing, but turning+ calendar back on means granting access again.+ </Dialog.Description>+ <div class="pt-3 justify-end items-center gap-3 inline-flex">+ <Button variant="base" depth={3} onClick={props.onClose}>+ Cancel+ </Button>+ <Button variant="danger" depth={3} onClick={confirm}>+ Turn off+ </Button>+ </div>+ </Panel.Body>+ </Panel>+ </Dialog>+ );+}diff --git a/apps/web/src/features/settings/Email.tsx b/apps/web/src/features/settings/Email.tsxindex 601d7b2cd5..610bcc0f6e 100644--- a/apps/web/src/features/settings/Email.tsx+++ b/apps/web/src/features/settings/Email.tsx@@ -1,3 +1,7 @@+import {+ TurnOffCalendarDialog,+ type TurnOffCalendarTarget,+} from '@app/features/calendar/TurnOffCalendarDialog';import { useCalendarUiFlag } from '@app/features/calendar/use-calendar-ui-flag';import { openAddInboxDialog } from '@app/features/inbox/AddInboxDialog';import { useFeatureFlag } from '@app/lib/analytics/posthog';@@ -17,6 +21,7 @@ import {} from '@core/email-link';import GmailIcon from '@icon/mcp-gmail.svg';import ArrowsClockwiseIcon from '@phosphor-icons/core/regular/arrows-clockwise.svg?component-solid';+import CalendarSlashIcon from '@phosphor-icons/core/regular/calendar-slash.svg?component-solid';import PlusIcon from '@phosphor-icons/core/regular/plus.svg?component-solid';import SignatureIcon from '@phosphor-icons/core/regular/signature.svg?component-solid';import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';@@ -93,6 +98,8 @@ export function EmailCard() {email: string;isOwn: boolean;} | null>(null);+ const [turnOffCalendarTarget, setTurnOffCalendarTarget] =+ createSignal<TurnOffCalendarTarget | null>(null);const [resyncingIds, setResyncingIds] = createSignal<ReadonlySet<string>>(new Set());@@ -189,6 +196,12 @@ export function EmailCard() {isOwn: primary().macro_id === userId(),})}+ onTurnOffCalendar={() =>+ setTurnOffCalendarTarget({+ linkId: primary().id,+ emailAddress: primary().email_address,+ })+ }/>)}</Show>@@ -218,6 +231,12 @@ export function EmailCard() {isOwn: link.macro_id === userId(),})}+ onTurnOffCalendar={() =>+ setTurnOffCalendarTarget({+ linkId: link.id,+ emailAddress: link.email_address,+ })+ }/>)}</For>@@ -242,6 +261,11 @@ export function EmailCard() {</Show></SettingsCard>+ <TurnOffCalendarDialog+ target={turnOffCalendarTarget()}+ onClose={() => setTurnOffCalendarTarget(null)}+ />+<Dialogopen={removeTarget() !== null}onOpenChange={(open) => {@@ -392,6 +416,7 @@ function InboxRow(props: {onReconnect: () => void;onEnableCalendar: () => void;onRemove: () => void;+ onTurnOffCalendar: () => void;}) {const emailSignaturesFlag = useFeatureFlag(ENABLE_EMAIL_SIGNATURES_FLAG, {enabledOverride: ENABLE_EMAIL_SIGNATURES_OVERRIDE,@@ -488,15 +513,12 @@ function InboxRow(props: {Reconnect</Button></Show>- {/* A link that needs a full reconnect gets calendar access on the- pass after it: Reconnect restores the mailbox, then this button- appears to add the calendar scope. */}+ {/* Its own consent flow, since Reconnect asks for the Gmail scopes+ only. Shown alongside Reconnect rather than after it: this+ request is a superset, so one consent repairs a dead grant and+ enables calendar, sparing a full revoke two round trips. */}<Show- when={- calendarUiEnabled() &&- props.link.needs_calendar_permission &&- props.link.sync_status !== SyncStatus.NEEDS_REAUTH- }+ when={calendarUiEnabled() && props.link.needs_calendar_permission}><Buttonvariant="active"@@ -508,6 +530,27 @@ function InboxRow(props: {Enable calendar</Button></Show>+ {/* Only the owner sees this: turning calendar off deletes the+ inbox's calendar data, which a delegate must not do. */}+ <Show+ when={+ calendarUiEnabled() &&+ props.isOwn &&+ !props.link.needs_calendar_permission+ }+ >+ <Tooltip label="Turn off calendar">+ <Button+ variant="base"+ size="icon-sm"+ depth={3}+ onClick={props.onTurnOffCalendar}+ aria-label={`Turn off calendar for ${props.link.email_address}`}+ >+ <CalendarSlashIcon class="size-4" />+ </Button>+ </Tooltip>+ </Show><Show when={ENABLE_INBOX_RESYNC}><Tooltip label="Force sync"><Buttondiff --git a/apps/web/src/lib/queries/calendar/sync.ts b/apps/web/src/lib/queries/calendar/sync.tsindex fcdc77de5a..b037654240 100644--- a/apps/web/src/lib/queries/calendar/sync.ts+++ b/apps/web/src/lib/queries/calendar/sync.ts@@ -2,6 +2,18 @@ import { queryClient } from '@queries/client';import { calendarKeys } from './keys';import { invalidateCalendarOccurrences } from './occurrences';+/**+ * Refetches everything the calendar UI reads: every mounted occurrence+ * viewport and the calendar list, which also carries per-calendar colors and+ * names.+ */+export function invalidateCalendarViews(): void {+ invalidateCalendarOccurrences();+ queryClient.invalidateQueries({+ queryKey: calendarKeys.visibleCalendars.queryKey,+ });+}+/*** Handles `refresh_calendar` websocket events: a sync run committed* provider-side changes for one of the viewer's (owned or delegated)@@ -20,8 +32,5 @@ export function handleRefreshCalendar(payload: unknown): void {: undefined;if (event?.event !== 'synced' || typeof event.link_id !== 'string') return;- invalidateCalendarOccurrences();- queryClient.invalidateQueries({- queryKey: calendarKeys.visibleCalendars.queryKey,- });+ invalidateCalendarViews();}diff --git a/apps/web/src/lib/queries/email/link.test.tsx b/apps/web/src/lib/queries/email/link.test.tsxnew file mode 100644index 0000000000..49afce9057--- /dev/null+++ b/apps/web/src/lib/queries/email/link.test.tsx@@ -0,0 +1,119 @@+import type { Link as EmailLink } from '@service-email/generated/schemas';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import type { JSX } from 'solid-js';+import { render } from 'solid-js/web';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { emailKeys } from './keys';+import { useDisableCalendarMutation } from './link';++const disableLinkCalendarMock = vi.hoisted(() => vi.fn());+const invalidateCalendarViewsMock = vi.hoisted(() => vi.fn());++vi.mock('@service-email/client', () => ({+ emailClient: { disableLinkCalendar: disableLinkCalendarMock },+}));++vi.mock('@queries/calendar/sync', () => ({+ invalidateCalendarViews: invalidateCalendarViewsMock,+}));++vi.mock('@queries/auth/user-info', () => ({ invalidateUserInfo: vi.fn() }));+vi.mock('@queries/soup/normalized-cache', () => ({+ invalidateAllSoup: vi.fn(),+}));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'macro|self' }));++let testQueryClient: QueryClient;++vi.mock('../client', () => ({+ get queryClient() {+ return testQueryClient;+ },+}));++const link = (id: string): EmailLink =>+ ({+ id,+ macro_id: 'macro|self',+ email_address: `${id}@example.com`,+ needs_calendar_permission: false,+ calendar_disabled: false,+ }) as unknown as EmailLink;++const cachedLinks = () =>+ testQueryClient.getQueryData<{ links: EmailLink[] }>(emailKeys.links.queryKey)+ ?.links ?? [];++const cachedLink = (id: string) => cachedLinks().find((it) => it.id === id);++let dispose: (() => void) | undefined;++function renderHook<T>(factory: () => T): T {+ let hook!: T;+ dispose = render(+ () => (+ <QueryClientProvider client={testQueryClient}>+ {(() => {+ hook = factory();+ return null as unknown as JSX.Element;+ })()}+ </QueryClientProvider>+ ),+ document.body+ );+ return hook;+}++beforeEach(() => {+ vi.clearAllMocks();+ testQueryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ testQueryClient.setQueryData(emailKeys.links.queryKey, {+ links: [link('inbox-a'), link('inbox-b')],+ });+});++afterEach(() => {+ dispose?.();+ dispose = undefined;+ testQueryClient.clear();+});++describe('useDisableCalendarMutation', () => {+ it('marks only the target inbox as deliberately calendar-less', async () => {+ disableLinkCalendarMock.mockResolvedValue(ok({}));+ const disable = renderHook(() => useDisableCalendarMutation());++ await disable.mutateAsync('inbox-a');++ expect(cachedLink('inbox-a')).toMatchObject({+ calendar_disabled: true,+ needs_calendar_permission: true,+ });+ expect(cachedLink('inbox-b')).toMatchObject({+ calendar_disabled: false,+ needs_calendar_permission: false,+ });+ expect(disableLinkCalendarMock).toHaveBeenCalledWith({+ linkId: 'inbox-a',+ });+ expect(invalidateCalendarViewsMock).toHaveBeenCalledTimes(1);+ });++ it('restores the previous links when the request fails', async () => {+ disableLinkCalendarMock.mockResolvedValue(+ err([{ code: 'HTTP_ERROR' as const, message: 'nope' }])+ );+ const disable = renderHook(() => useDisableCalendarMutation());++ await expect(disable.mutateAsync('inbox-a')).rejects.toThrow();++ expect(cachedLink('inbox-a')).toMatchObject({+ calendar_disabled: false,+ needs_calendar_permission: false,+ });+ expect(invalidateCalendarViewsMock).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/queries/email/link.ts b/apps/web/src/lib/queries/email/link.tsindex 62f7566fb1..b8b3d4e109 100644--- a/apps/web/src/lib/queries/email/link.ts+++ b/apps/web/src/lib/queries/email/link.ts@@ -1,6 +1,7 @@import { useUserId } from '@core/context/user';import { throwOnErr } from '@core/util/result';import { invalidateUserInfo } from '@queries/auth/user-info';+import { invalidateCalendarViews } from '@queries/calendar/sync';import { queryClient } from '@queries/client';import { invalidateAllSoup } from '@queries/soup/normalized-cache';import { emailClient } from '@service-email/client';@@ -104,6 +105,81 @@ export function invalidateEmailLinks() {});}+type DisableCalendarContext = {+ previousLinks: ListLinksResponse | undefined;+};+type DisableCalendarCallbacks = MutationCallbacks<+ void,+ Error,+ string,+ DisableCalendarContext+>;++/**+ * Turns calendar off for one inbox: the backend deletes its calendar data and+ * drops the calendar scopes from its Google grant. The cached link flips to+ * `calendar_disabled` + `needs_calendar_permission` right away, which is what+ * swaps the settings row back to "Enable calendar" and keeps the enable prompt+ * quiet, and the emptied calendar caches are refetched.+ */+export function useDisableCalendarMutation(+ callbacks?: DisableCalendarCallbacks+) {+ return useMutation(() => ({+ mutationFn: async (linkId: string) => {+ await throwOnErr(() => emailClient.disableLinkCalendar({ linkId }));+ },++ ...withCallbacks<void, Error, string, DisableCalendarContext>(+ {+ onMutate: async (linkId) => {+ await queryClient.cancelQueries({+ queryKey: emailKeys.links.queryKey,+ });++ const previousLinks = queryClient.getQueryData<ListLinksResponse>(+ emailKeys.links.queryKey+ );++ queryClient.setQueryData<ListLinksResponse>(+ emailKeys.links.queryKey,+ (old) =>+ old && {+ ...old,+ links: old.links.map((link) =>+ link.id === linkId+ ? {+ ...link,+ calendar_disabled: true,+ needs_calendar_permission: true,+ }+ : link+ ),+ }+ );++ return { previousLinks };+ },++ onSuccess: () => {+ invalidateEmailLinks();+ invalidateCalendarViews();+ },++ onError: (_error, _linkId, context) => {+ if (context?.previousLinks) {+ queryClient.setQueryData(+ emailKeys.links.queryKey,+ context.previousLinks+ );+ }+ },+ },+ callbacks+ ),+ }));+}+type RemoveInboxContext = { previousLinks: ListLinksResponse | undefined };type RemoveInboxCallbacks = MutationCallbacks<void,diff --git a/apps/web/src/lib/service-clients/service-email/client.ts b/apps/web/src/lib/service-clients/service-email/client.tsindex 2cdc9cc9cd..97043a57f4 100644--- a/apps/web/src/lib/service-clients/service-email/client.ts+++ b/apps/web/src/lib/service-clients/service-email/client.ts@@ -384,6 +384,24 @@ export const emailClient = {).map((result) => result);},+ /**+ * Turns calendar off for one connected inbox: its calendar data is removed+ * and the calendar scopes leave its Google grant, so the inbox comes back as+ * needing calendar permission until the user grants it again. Gmail sync is+ * unaffected.+ */+ async disableLinkCalendar(args: { linkId: string }) {+ const { linkId } = args;+ return (+ await emailFetch<EmptyResponse>(+ `/email/links/${encodeURIComponent(linkId)}/calendar`,+ {+ method: 'DELETE',+ }+ )+ ).map((result) => result);+ },+async resyncLink(args: { linkId: string }) {const { linkId } = args;return (diff --git a/apps/web/src/lib/service-clients/service-email/generated/client.ts b/apps/web/src/lib/service-clients/service-email/generated/client.tsindex 1c8812d668..e70e8b61a2 100644--- a/apps/web/src/lib/service-clients/service-email/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/client.ts@@ -2384,6 +2384,83 @@ export const deleteLink = async (} as deleteLinkResponse;};+/**+ * Removes the inbox's calendar data, drops the calendar scopes from its+recorded Google grant, and closes its push channels, so the inbox reads as+calendar-less until the user runs the calendar consent flow again. Gmail+sync is untouched.++Only the inbox's owner may do this: a delegate can see the owner's calendar+but must not be able to delete the owner's data.+ * @summary Turns calendar off for a connected inbox.+ */+export type disableLinkCalendarResponse204 = {+ data: EmptyResponse;+ status: 204;+};++export type disableLinkCalendarResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type disableLinkCalendarResponse403 = {+ data: ErrorResponse;+ status: 403;+};++export type disableLinkCalendarResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type disableLinkCalendarResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type disableLinkCalendarResponseSuccess =+ disableLinkCalendarResponse204 & {+ headers: Headers;+ };+export type disableLinkCalendarResponseError = (+ | disableLinkCalendarResponse401+ | disableLinkCalendarResponse403+ | disableLinkCalendarResponse404+ | disableLinkCalendarResponse500+) & {+ headers: Headers;+};++export type disableLinkCalendarResponse =+ | disableLinkCalendarResponseSuccess+ | disableLinkCalendarResponseError;++export const getDisableLinkCalendarUrl = (linkId: string) => {+ return `/email/links/${linkId}/calendar`;+};++export const disableLinkCalendar = async (+ linkId: string,+ options?: RequestInit+): Promise<disableLinkCalendarResponse> => {+ const res = await fetch(getDisableLinkCalendarUrl(linkId), {+ ...options,+ method: 'DELETE',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: disableLinkCalendarResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as disableLinkCalendarResponse;+};+/*** Idempotent: if a backfill is already `Init`/`InProgress` for the inbox this isa no-op and returns that job.diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/link.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/link.tsindex 3e25a68e61..1fb47bd8d3 100644--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/link.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/link.ts@@ -10,6 +10,11 @@ import type { SyncStatus } from './syncStatus';import type { UserProvider } from './userProvider';export interface Link {+ /** Whether the user turned calendar off for this inbox, which also removed+its calendar data. `needs_calendar_permission` is true either way, so+this is what separates "never granted" from "deliberately off" —+unprompted calendar nags must stay quiet for the latter. */+ calendar_disabled: boolean;created_at: string;email_address: string;fusionauth_user_id: string;diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.jsonindex 399c38e008..da8f30ac33 100644--- a/apps/web/src/lib/service-clients/service-email/openapi.json+++ b/apps/web/src/lib/service-clients/service-email/openapi.json@@ -2198,6 +2198,78 @@}}},+ "/email/links/{link_id}/calendar": {+ "delete": {+ "tags": ["Links"],+ "summary": "Turns calendar off for a connected inbox.",+ "description": "Removes the inbox's calendar data, drops the calendar scopes from its\nrecorded Google grant, and closes its push channels, so the inbox reads as\ncalendar-less until the user runs the calendar consent flow again. Gmail\nsync is untouched.\n\nOnly the inbox's owner may do this: a delegate can see the owner's calendar\nbut must not be able to delete the owner's data.",+ "operationId": "disable_link_calendar",+ "parameters": [+ {+ "name": "link_id",+ "in": "path",+ "description": "Inbox link ID.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EmptyResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/email/links/{link_id}/resync": {"post": {"tags": ["Links"],@@ -5151,12 +5223,17 @@"sync_status","needs_reauth","needs_calendar_permission",+ "calendar_disabled","settings","is_primary","created_at","updated_at"],"properties": {+ "calendar_disabled": {+ "type": "boolean",+ "description": "Whether the user turned calendar off for this inbox, which also removed\nits calendar data. `needs_calendar_permission` is true either way, so\nthis is what separates \"never granted\" from \"deliberately off\" —\nunprompted calendar nags must stay quiet for the latter."+ },"created_at": {"type": "string","format": "date-time"diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rsindex 621fd60001..49f1dd2115 100644--- a/crates/calendar_events/src/domain/models.rs+++ b/crates/calendar_events/src/domain/models.rs@@ -19,6 +19,15 @@ pub const GOOGLE_CALENDAR_LIST_SCOPE: &str =pub const GOOGLE_CALENDAR_SCOPES: [&str; 2] =[GOOGLE_CALENDAR_EVENTS_SCOPE, GOOGLE_CALENDAR_LIST_SCOPE];+/// The single broad scope Macro requested before narrowing to the two above.+/// Google keeps a granted scope for the life of the grant, so inboxes connected+/// before the narrowing still report it; it is what [`GoogleScopeSet::without_calendar`]+/// must strip beyond the two scopes Macro requests today. It deliberately does+/// not count towards the capability: an inbox reports it without Macro having+/// asked for calendar in this era, so the user re-grants through the normal+/// prompt (or drops it entirely by removing Macro's access at Google).+pub const GOOGLE_CALENDAR_FULL_SCOPE: &str = "https://www.googleapis.com/auth/calendar";+/// Build the space-delimited calendar scope fragment for an OAuth authorization URL.pub fn google_calendar_scope_parameter() -> String {GOOGLE_CALENDAR_SCOPES.join(" ")@@ -60,6 +69,54 @@ impl GoogleScopeSet {.iter().all(|scope| self.contains(scope))}++ /// Return the same grant without any Google Calendar scope, leaving the+ /// Gmail capability untouched. Every calendar scope is dropped, not just+ /// the two Macro requests, so a grant that carries a broader calendar+ /// scope cannot keep the capability alive.+ pub fn without_calendar(self) -> Self {+ Self(+ self.0+ .into_iter()+ .filter(|scope| !scope.starts_with(GOOGLE_CALENDAR_SCOPE_PREFIX))+ .collect(),+ )+ }+}++/// Every Google Calendar scope shares this prefix.+const GOOGLE_CALENDAR_SCOPE_PREFIX: &str = "https://www.googleapis.com/auth/calendar";++/// Why a Google grant is being recorded, which decides how it interacts with a+/// standing calendar opt-out.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CalendarGrantIntent {+ /// The consent flow explicitly asked for calendar access, so the user is+ /// (re-)enabling the capability: clear any standing opt-out.+ CalendarRequested,+ /// Calendar scopes, if any are present, only rode along from an earlier+ /// grant (`include_granted_scopes=true`) or a token-discovery probe. A+ /// standing opt-out keeps calendar off and the scopes are not recorded.+ Incidental,+}++/// A watch channel that must be closed at Google after its calendar is gone.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CalendarWatchRelease {+ /// Channel identifier Macro opened the watch with.+ pub channel_id: String,+ /// Provider-assigned resource identifier for the watched calendar.+ pub resource_id: String,+}++/// What a completed calendar disconnect leaves for the caller to finish at the+/// provider. Local state is already gone by the time this is returned.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct DisconnectedGoogleCalendar {+ /// Token identity of the disconnected inbox, for closing its channels.+ pub token_identity: CalendarLinkTokenIdentity,+ /// Push channels that were open when the calendar was removed.+ pub watch_channels: Vec<CalendarWatchRelease>,}/// The mutually exclusive time shape of a calendar event.diff --git a/crates/calendar_events/src/domain/mutations.rs b/crates/calendar_events/src/domain/mutations.rsindex 32034aeb26..d03c713a6c 100644--- a/crates/calendar_events/src/domain/mutations.rs+++ b/crates/calendar_events/src/domain/mutations.rs@@ -12,8 +12,9 @@ use uuid::Uuid;use super::{models::{AttendeeResponseStatus, CalendarEvent, CalendarEventDraft, CalendarEventMutationTarget,- CalendarEventPatch, CalendarEventUpsert, EventReminders, EventTime, OccurrenceRange,- REMINDER_METHOD_EMAIL, REMINDER_METHOD_POPUP, REMINDER_MINUTES_MAX, REMINDER_OVERRIDES_MAX,+ CalendarEventPatch, CalendarEventUpsert, DisconnectedGoogleCalendar, EventReminders,+ EventTime, OccurrenceRange, REMINDER_METHOD_EMAIL, REMINDER_METHOD_POPUP,+ REMINDER_MINUTES_MAX, REMINDER_OVERRIDES_MAX,},ports::{CalendarAccessTokenProvider, CalendarDeletionScope, CalendarEventWrite,@@ -285,6 +286,23 @@ where.await.map_err(internal)}++ #[tracing::instrument(skip(self, requester_id), err)]+ async fn disconnect_calendar(+ &self,+ requester_id: &str,+ email_link_id: Uuid,+ ) -> Result<(), CalendarMutationError> {+ let disconnected = self+ .repository+ .disconnect_google_calendar(requester_id, email_link_id)+ .await+ .map_err(internal)?+ .ok_or(CalendarMutationError::NotFound)?;+ self.release_watch_channels(email_link_id, &disconnected)+ .await;+ Ok(())+ }}impl<R, G, T> CalendarMutationServiceImpl<R, G, T>@@ -293,6 +311,54 @@ whereG: GoogleCalendarMutationProvider,T: CalendarAccessTokenProvider,{+ /// Close the push channels a disconnected calendar left open. Best-effort:+ /// the local calendars are already gone, so a notification that still+ /// arrives resolves to no watch target and is dropped. Stopping the+ /// channels only spares Google the retries until they expire.+ async fn release_watch_channels(+ &self,+ email_link_id: Uuid,+ disconnected: &DisconnectedGoogleCalendar,+ ) {+ if disconnected.watch_channels.is_empty() {+ return;+ }+ let access_token = match self+ .tokens+ .fetch_access_token(&disconnected.token_identity)+ .await+ {+ Ok(token) => token,+ Err(error) => {+ tracing::warn!(+ error=?error,+ email_link_id=%email_link_id,+ "no token to close the disconnected calendar's push channels"+ );+ return;+ }+ };+ for channel in &disconnected.watch_channels {+ self.provider+ .stop_watch_channel(+ &access_token,+ email_link_id,+ &channel.channel_id,+ &channel.resource_id,+ )+ .await+ .inspect_err(|error| {+ tracing::warn!(+ error=?error,+ email_link_id=%email_link_id,+ channel_id=%channel.channel_id,+ "failed to close a disconnected calendar's push channel"+ );+ })+ .ok();+ }+ }+/// Best-effort cleanup when the provider reports the event gone: the/// regular sync converges the projection either way.async fn retire_gone_source(&self, target: &CalendarEventMutationTarget) {diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex a82b3351b5..33f65f7ab0 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -2,9 +2,10 @@ use super::*;use crate::domain::models::{AppliedGoogleGrant, CalendarAttendeeInput, CalendarBackfillJobKey, CalendarCreationTarget,CalendarEventSource, CalendarLinkTokenIdentity, CalendarOccurrence, CalendarOccurrenceCursor,- CalendarSyncStatus, ConferenceChange, EventStatus, EventTransparency, EventVisibility,- GoogleCalendarSyncSnapshot, GoogleCalendarTarget, GoogleEventSource, GoogleWatchChannel,- ProviderCalendar, StoredGoogleCalendar,+ CalendarSyncStatus, CalendarWatchRelease, ConferenceChange, DisconnectedGoogleCalendar,+ EventStatus, EventTransparency, EventVisibility, GoogleCalendarSyncSnapshot,+ GoogleCalendarTarget, GoogleEventSource, GoogleWatchChannel, ProviderCalendar,+ StoredGoogleCalendar,};use chrono::{Duration, TimeZone};use std::sync::{Arc, Mutex};@@ -119,6 +120,8 @@ struct FakeRepo {persisted_event_id: Option<Uuid>,upserts: Arc<Mutex<Vec<CalendarEventUpsert>>>,removed_sources: Arc<Mutex<Vec<(Uuid, Uuid, String)>>>,+ disconnected: Option<DisconnectedGoogleCalendar>,+ disconnect_requests: Arc<Mutex<Vec<(String, Uuid)>>>,}impl CalendarRepository for FakeRepo {@@ -126,10 +129,23 @@ impl CalendarRepository for FakeRepo {&self,_email_link_id: Uuid,_scopes: crate::domain::models::GoogleScopeSet,+ _intent: crate::domain::models::CalendarGrantIntent,) -> Result<AppliedGoogleGrant, rootcause::Report> {unreachable!()}+ async fn disconnect_google_calendar(+ &self,+ requester_id: &str,+ email_link_id: Uuid,+ ) -> Result<Option<DisconnectedGoogleCalendar>, rootcause::Report> {+ self.disconnect_requests+ .lock()+ .unwrap()+ .push((requester_id.to_string(), email_link_id));+ Ok(self.disconnected.clone())+ }+async fn upsert_event(&self, write: CalendarEventWrite) -> Result<Uuid, rootcause::Report> {let CalendarEventWrite::UserMutation(upsert) = write else {panic!("mutations must persist through the UserMutation authority");@@ -333,6 +349,23 @@ impl GoogleCalendarMutationProvider for FakeProvider {Ok(())}+ async fn stop_watch_channel(+ &self,+ _access_token: &str,+ _email_link_id: Uuid,+ channel_id: &str,+ resource_id: &str,+ ) -> Result<(), GoogleProviderError> {+ self.calls+ .lock()+ .unwrap()+ .push(format!("stop:{channel_id}:{resource_id}"));+ if let Some(error) = self.fail() {+ return Err(error);+ }+ Ok(())+ }+async fn delete_event_instance(&self,_access_token: &str,@@ -864,3 +897,91 @@ async fn conference_changes_reach_the_provider_for_any_conference() {assert_eq!(calls.lock().unwrap().as_slice(), ["update:master-id"]);}}++fn disconnected(channels: &[(&str, &str)]) -> DisconnectedGoogleCalendar {+ DisconnectedGoogleCalendar {+ token_identity: token_identity(),+ watch_channels: channels+ .iter()+ .map(|(channel_id, resource_id)| CalendarWatchRelease {+ channel_id: (*channel_id).to_string(),+ resource_id: (*resource_id).to_string(),+ })+ .collect(),+ }+}++#[tokio::test]+async fn disconnecting_calendar_closes_every_open_watch_channel() {+ let link_id = Uuid::now_v7();+ let repo = FakeRepo {+ disconnected: Some(disconnected(&[+ ("channel-a", "resource-a"),+ ("channel-b", "resource-b"),+ ])),+ ..FakeRepo::default()+ };+ let requests = repo.disconnect_requests.clone();+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();++ service(repo, provider, FakeTokens::ok())+ .disconnect_calendar("macro|user", link_id)+ .await+ .unwrap();++ assert_eq!(+ requests.lock().unwrap().as_slice(),+ [("macro|user".to_string(), link_id)]+ );+ assert_eq!(+ calls.lock().unwrap().as_slice(),+ [+ "stop:channel-a:resource-a".to_string(),+ "stop:channel-b:resource-b".to_string()+ ]+ );+}++/// The local removal has already committed by the time channels are closed, so+/// a provider or token failure must not report the disconnect as failed — the+/// stale channel resolves to no watch target and expires on its own.+#[tokio::test]+async fn disconnecting_calendar_survives_a_provider_that_cannot_close_channels() {+ let repo = FakeRepo {+ disconnected: Some(disconnected(&[("channel-a", "resource-a")])),+ ..FakeRepo::default()+ };+ let provider = FakeProvider::new(FakeProviderBehavior::Fail(+ GoogleProviderErrorKind::Transient,+ ));+ assert!(+ service(repo.clone(), provider, FakeTokens::ok())+ .disconnect_calendar("macro|user", Uuid::now_v7())+ .await+ .is_ok()+ );++ let unreachable_token = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = unreachable_token.calls.clone();+ assert!(+ service(repo, unreachable_token, FakeTokens::reauth())+ .disconnect_calendar("macro|user", Uuid::now_v7())+ .await+ .is_ok()+ );+ assert!(calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn disconnecting_an_inbox_the_requester_does_not_own_is_not_found() {+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();+ assert!(matches!(+ service(FakeRepo::default(), provider, FakeTokens::ok())+ .disconnect_calendar("macro|other", Uuid::now_v7())+ .await,+ Err(CalendarMutationError::NotFound)+ ));+ assert!(calls.lock().unwrap().is_empty());+}diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 1bcc31b042..6f1f60e792 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -10,9 +10,10 @@ use super::models::{AppliedGoogleGrant, AttendeeResponseStatus, CalendarBackfillClaim,CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJobKey,CalendarCreationTarget, CalendarEvent, CalendarEventDraft, CalendarEventMutationTarget,- CalendarEventPatch, CalendarEventUpsert, CalendarLinkTokenIdentity, CalendarOccurrence,- CalendarOccurrenceCursor, CalendarReminderDeliveryOutcome, CalendarReminderDispatchMessage,- CalendarReminderFiring, CalendarReminderSweepSummary, CalendarSyncStatus, DueCalendarReminder,+ CalendarEventPatch, CalendarEventUpsert, CalendarGrantIntent, CalendarLinkTokenIdentity,+ CalendarOccurrence, CalendarOccurrenceCursor, CalendarReminderDeliveryOutcome,+ CalendarReminderDispatchMessage, CalendarReminderFiring, CalendarReminderSweepSummary,+ CalendarSyncStatus, DisconnectedGoogleCalendar, DueCalendarReminder,GoogleCalendarSyncSnapshot, GoogleCalendarTarget, GoogleEventSyncBatch, GoogleScopeSet,GoogleSyncPlan, GoogleWatchChannel, GoogleWatchConfig, OccurrenceRange, ProviderCalendar,StoredGoogleCalendar, VisibleCalendar,@@ -176,6 +177,16 @@ pub trait GoogleCalendarMutationProvider: Send + Sync + 'static {response: AttendeeResponseStatus,scope: &CalendarRsvpScope,) -> impl Future<Output = Result<GoogleRsvpOutcome, GoogleProviderError>> + Send;++ /// Close a push notification channel. A channel Google no longer knows+ /// about is success, since the goal is only that it stops delivering.+ fn stop_watch_channel(+ &self,+ access_token: &str,+ email_link_id: Uuid,+ channel_id: &str,+ resource_id: &str,+ ) -> impl Future<Output = Result<(), GoogleProviderError>> + Send;}/// How much of a recurring series a deletion removes.@@ -256,12 +267,28 @@ pub trait CalendarOccurrenceService: Send + Sync + 'static {pub trait CalendarRepository: Send + Sync + 'static {/// Apply the actual scopes returned by Google and atomically schedule any/// newly unlocked historical work.+ ///+ /// `intent` decides how the grant meets a standing calendar opt-out: an+ /// explicit calendar request clears it, anything else is filtered through+ /// it so calendar scopes that merely rode along stay unrecorded.fn apply_google_grant(&self,email_link_id: Uuid,scopes: GoogleScopeSet,+ intent: CalendarGrantIntent,) -> impl Future<Output = Result<AppliedGoogleGrant, Report>> + Send;+ /// Turn the calendar capability off for an inbox the requester owns:+ /// remove its calendar data, drop the calendar scopes from the recorded+ /// grant, and stamp the opt-out that keeps a later incidental re-grant+ /// from resurrecting it. Returns `None` when the requester owns no such+ /// inbox, and the still-open push channels otherwise.+ fn disconnect_google_calendar(+ &self,+ requester_id: &str,+ email_link_id: Uuid,+ ) -> impl Future<Output = Result<Option<DisconnectedGoogleCalendar>, Report>> + Send;+/// Upsert an event through an explicit, source-matched ingestion authority.fn upsert_event(&self,@@ -421,6 +448,15 @@ pub trait CalendarMutationService: Send + Sync + 'static {response: AttendeeResponseStatus,scope: CalendarRsvpScope,) -> impl Future<Output = Result<CalendarEvent, CalendarMutationError>> + Send;++ /// Turn calendar off for one of the requester's own connected inboxes:+ /// its calendar data is removed, the calendar scopes leave the recorded+ /// grant, and its push channels are closed at Google.+ fn disconnect_calendar(+ &self,+ requester_id: &str,+ email_link_id: Uuid,+ ) -> impl Future<Output = Result<(), CalendarMutationError>> + Send;}/// Use-case failures surfaced by calendar mutations.diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex b387944602..f1a9fbfc2b 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -9,8 +9,8 @@ use super::{models::{AppliedGoogleGrant, CalendarBackfillClaim, CalendarBackfillFailureDisposition,CalendarBackfillFailureOutcome, CalendarBackfillJobKey, CalendarEventUpsert,- CalendarOccurrenceCursor, GoogleBackfillRunReport, GoogleCalendarSyncSnapshot,- GoogleScopeSet, OccurrenceRange,+ CalendarGrantIntent, CalendarOccurrenceCursor, GoogleBackfillRunReport,+ GoogleCalendarSyncSnapshot, GoogleScopeSet, OccurrenceRange,},ports::{CalendarBackfillRepository, CalendarEventWrite, CalendarOccurrenceService,@@ -55,15 +55,18 @@ where/// Apply an OAuth grant using actual scopes returned by Google.////// The repository owns the transaction that increments the grant version- /// and inserts the two idempotent backfill jobs.+ /// and inserts the two idempotent backfill jobs. `intent` states whether+ /// the consent flow behind this grant explicitly asked for calendar+ /// access, which is what clears a standing calendar opt-out.#[tracing::instrument(skip(self, scopes), err)]pub async fn apply_google_grant(&self,email_link_id: Uuid,scopes: GoogleScopeSet,+ intent: CalendarGrantIntent,) -> Result<AppliedGoogleGrant, Report> {self.repository- .apply_google_grant(email_link_id, scopes)+ .apply_google_grant(email_link_id, scopes, intent).await}diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex 8fde39474b..dbb8d53756 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -4,10 +4,11 @@ use crate::domain::{AttendeeResponseStatus, CalendarAttendee, CalendarBackfillClaim,CalendarBackfillFailureDisposition, CalendarBackfillJobKey, CalendarCreationTarget,CalendarEvent, CalendarEventMutationTarget, CalendarEventSource, CalendarOccurrence,- CalendarSyncStatus, EventReminders, EventStatus, EventTime, EventTransparency,- EventVisibility, GOOGLE_CALENDAR_SCOPES, GoogleBackfillRunReport,- GoogleCalendarSyncSnapshot, GoogleEventSource, GoogleEventSyncBatch, GoogleWatchChannel,- GoogleWatchConfig, ProviderCalendar, StoredGoogleCalendar,+ CalendarSyncStatus, DisconnectedGoogleCalendar, EventReminders, EventStatus, EventTime,+ EventTransparency, EventVisibility, GOOGLE_CALENDAR_FULL_SCOPE, GOOGLE_CALENDAR_SCOPES,+ GoogleBackfillRunReport, GoogleCalendarSyncSnapshot, GoogleEventSource,+ GoogleEventSyncBatch, GoogleWatchChannel, GoogleWatchConfig, ProviderCalendar,+ StoredGoogleCalendar,},ports::{CalendarBackfillRepository, CalendarEventWrite, CalendarRepository, GoogleCalendarProvider,@@ -28,10 +29,19 @@ impl CalendarRepository for FakeRepo {&self,_email_link_id: Uuid,_scopes: GoogleScopeSet,+ _intent: CalendarGrantIntent,) -> Result<AppliedGoogleGrant, Report> {unreachable!()}+ async fn disconnect_google_calendar(+ &self,+ _requester_id: &str,+ _email_link_id: Uuid,+ ) -> Result<Option<DisconnectedGoogleCalendar>, Report> {+ unreachable!()+ }+async fn upsert_event(&self, write: CalendarEventWrite) -> Result<Uuid, Report> {let upsert = match write {CalendarEventWrite::GoogleBackfill { upsert, .. }@@ -248,13 +258,33 @@ fn complete_scope_capability_requires_every_requested_scope() {}}+/// An inbox connected before Macro narrowed its request reports only the broad+/// scope. It deliberately does not read as the capability — the user re-grants+/// through the normal prompt, which records the scopes Macro asks for today.#[test]fn broad_calendar_grant_no_longer_reads_as_the_capability() {- let broad = GoogleScopeSet::parse("https://www.googleapis.com/auth/calendar");+ let broad = GoogleScopeSet::parse(GOOGLE_CALENDAR_FULL_SCOPE);assert!(!broad.has_calendar_capability());}+/// Google re-issues an earlier broad grant alongside the narrow scopes it now+/// grants, so turning calendar off has to strip the broad one too or the+/// capability survives its own removal.+#[test]+fn turning_calendar_off_strips_a_re_issued_broad_scope() {+ let reissued = GoogleScopeSet::parse(&format!(+ "https://www.googleapis.com/auth/gmail.modify {GOOGLE_CALENDAR_FULL_SCOPE} {}",+ GOOGLE_CALENDAR_SCOPES.join(" ")+ ));+ assert!(reissued.has_calendar_capability());++ let stripped = reissued.without_calendar();+ assert!(!stripped.has_calendar_capability());+ assert!(!stripped.contains(GOOGLE_CALENDAR_FULL_SCOPE));+ assert!(stripped.contains("https://www.googleapis.com/auth/gmail.modify"));+}+#[derive(Clone)]struct FakeGoogleProvider;diff --git a/crates/calendar_events/src/outbound/google.rs b/crates/calendar_events/src/outbound/google.rsindex 8176ecf129..20609921f9 100644--- a/crates/calendar_events/src/outbound/google.rs+++ b/crates/calendar_events/src/outbound/google.rs@@ -1136,6 +1136,35 @@ impl<G: GoogleRequestGate> GoogleCalendarMutationProvider for GoogleCalendarClie}}}++ #[tracing::instrument(skip(self, access_token), err)]+ async fn stop_watch_channel(+ &self,+ access_token: &str,+ email_link_id: Uuid,+ channel_id: &str,+ resource_id: &str,+ ) -> Result<(), GoogleProviderError> {+ self.gate.acquire(email_link_id).await?;+ let response = self+ .client+ .post(format!("{GOOGLE_CALENDAR_API}/channels/stop"))+ .bearer_auth(access_token)+ .json(&serde_json::json!({+ "id": channel_id,+ "resourceId": resource_id,+ }))+ .send()+ .await+ .map_err(provider_transport_error)?;+ let status = response.status();+ // A channel Google has already forgotten is as stopped as it gets.+ if status.is_success() || status == StatusCode::NOT_FOUND || status == StatusCode::GONE {+ return Ok(());+ }+ let body = response.text().await.map_err(provider_transport_error)?;+ Err(provider_response_error(status, &body))+ }}/// Outcome of writing the connected account's response to one provider event.diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsindex e281963613..8ff3ce88d4 100644--- a/crates/calendar_events/src/outbound/pg.rs+++ b/crates/calendar_events/src/outbound/pg.rs@@ -15,12 +15,12 @@ use crate::domain::{CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJob,CalendarBackfillJobKey, CalendarBackfillKind, CalendarCreationTarget, CalendarEvent,CalendarEventMutationTarget, CalendarEventOverride, CalendarEventSource,- CalendarEventUpsert, CalendarLinkTokenIdentity, CalendarOccurrence,- CalendarOccurrenceCursor, CalendarReminderFiring, CalendarSyncStatus, ConferenceProvider,- DueCalendarReminder, EventReminderOverride, EventReminders, EventStart, EventStatus,- EventTime, EventTransparency, EventVisibility, GOOGLE_CALENDAR_SCOPES,- GoogleCalendarSyncSnapshot, GoogleScopeSet, GoogleWatchChannel, OccurrenceRange,- ProviderCalendar, StoredGoogleCalendar, VisibleCalendar,+ CalendarEventUpsert, CalendarGrantIntent, CalendarLinkTokenIdentity, CalendarOccurrence,+ CalendarOccurrenceCursor, CalendarReminderFiring, CalendarSyncStatus, CalendarWatchRelease,+ ConferenceProvider, DisconnectedGoogleCalendar, DueCalendarReminder, EventReminderOverride,+ EventReminders, EventStart, EventStatus, EventTime, EventTransparency, EventVisibility,+ GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleScopeSet, GoogleWatchChannel,+ OccurrenceRange, ProviderCalendar, StoredGoogleCalendar, VisibleCalendar,},ports::{CalendarBackfillRepository, CalendarEventWrite, CalendarReminderDispatchRepo,@@ -231,7 +231,8 @@ impl PgCalendarRepository {l.macro_id,l.email_address::text AS "email_address!",COALESCE(g.granted_scopes, '{}') AS "granted_scopes!",- COALESCE(g.grant_version, 0) AS "grant_version!"+ COALESCE(g.grant_version, 0) AS "grant_version!",+ g.calendar_disabled_atFROM email_links lLEFT JOIN email_link_google_scopes g ON g.link_id = l.idWHERE l.id = $1@@ -254,6 +255,7 @@ struct GrantRow {email_address: String,granted_scopes: Vec<String>,grant_version: i64,+ calendar_disabled_at: Option<DateTime<Utc>>,}struct StoredCalendarRow {@@ -350,6 +352,7 @@ impl CalendarRepository for PgCalendarRepository {&self,email_link_id: Uuid,scopes: GoogleScopeSet,+ intent: CalendarGrantIntent,) -> Result<AppliedGoogleGrant, Report> {let mut tx = self.pool.begin().await.map_err(report)?;// The email_links row remains the grant serialization point. Every@@ -361,7 +364,8 @@ impl CalendarRepository for PgCalendarRepository {l.macro_id,l.email_address::text AS "email_address!",COALESCE(g.granted_scopes, '{}') AS "granted_scopes!",- COALESCE(g.grant_version, 0) AS "grant_version!"+ COALESCE(g.grant_version, 0) AS "grant_version!",+ g.calendar_disabled_atFROM email_links lLEFT JOIN email_link_google_scopes g ON g.link_id = l.idWHERE l.id = $1@@ -373,10 +377,25 @@ impl CalendarRepository for PgCalendarRepository {.await.map_err(report)?;+ // The user's own opt-out outranks whatever Google reports. Consent+ // requests carry `include_granted_scopes=true`, so a plain Gmail+ // reconnect hands back the calendar scopes of an earlier grant; only a+ // flow that explicitly asked for calendar counts as re-enabling it.+ let clear_opt_out = matches!(intent, CalendarGrantIntent::CalendarRequested);+ let calendar_opted_out = row.calendar_disabled_at.is_some() && !clear_opt_out;+ let scopes = if calendar_opted_out {+ scopes.without_calendar()+ } else {+ scopes+ };+let old_scopes = GoogleScopeSet::from_scopes(row.granted_scopes);let had_calendar_capability = old_scopes.has_calendar_capability();let changed = old_scopes != scopes;if !changed {+ if clear_opt_out {+ clear_calendar_opt_out_tx(&mut tx, email_link_id).await?;+ }let jobs = if scopes.has_calendar_capability() {retry_failed_backfills_tx(&mut tx, email_link_id, row.grant_version).await?} else {@@ -399,11 +418,16 @@ impl CalendarRepository for PgCalendarRepository {ON CONFLICT (link_id) DO UPDATESET granted_scopes = EXCLUDED.granted_scopes,grant_version = EXCLUDED.grant_version,+ calendar_disabled_at = CASE+ WHEN $4 THEN NULL+ ELSE email_link_google_scopes.calendar_disabled_at+ END,updated_at = now()"#,email_link_id,&granted_scopes,grant_version,+ clear_opt_out,).execute(&mut *tx).await@@ -474,6 +498,111 @@ impl CalendarRepository for PgCalendarRepository {})}+ #[tracing::instrument(skip(self, requester_id), err)]+ async fn disconnect_google_calendar(+ &self,+ requester_id: &str,+ email_link_id: Uuid,+ ) -> Result<Option<DisconnectedGoogleCalendar>, Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ // Same serialization point and lock order as grant application, so a+ // consent landing concurrently either precedes or follows this removal.+ // Only the inbox's owner may disconnect it: a delegate reads the+ // owner's calendar and must not be able to delete the owner's data.+ let row = sqlx::query!(+ r#"+ SELECT+ l.fusionauth_user_id,+ l.email_address::text AS "email_address!",+ l.provider::text AS "provider!",+ COALESCE(g.granted_scopes, '{}') AS "granted_scopes!"+ FROM email_links l+ LEFT JOIN email_link_google_scopes g ON g.link_id = l.id+ WHERE l.id = $1 AND l.macro_id = $2+ FOR UPDATE OF l+ "#,+ email_link_id,+ requester_id,+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(report)?;+ let Some(row) = row else {+ return Ok(None);+ };++ // Read the open channels before the calendars go away; the caller+ // closes them at Google once the local removal has committed.+ let watch_channels = sqlx::query!(+ r#"+ SELECT+ c.watch_channel_id AS "channel_id!",+ c.watch_resource_id AS "resource_id!"+ FROM calendars c+ JOIN calendar_accounts a ON a.id = c.account_id+ WHERE a.email_link_id = $1+ AND c.watch_channel_id IS NOT NULL+ AND c.watch_resource_id IS NOT NULL+ "#,+ email_link_id,+ )+ .fetch_all(&mut *tx)+ .await+ .map_err(report)?+ .into_iter()+ .map(|row| CalendarWatchRelease {+ channel_id: row.channel_id,+ resource_id: row.resource_id,+ })+ .collect();++ let granted_scopes = GoogleScopeSet::from_scopes(row.granted_scopes)+ .without_calendar()+ .into_vec();+ let grant_version = sqlx::query_scalar!(+ r#"+ INSERT INTO email_link_google_scopes (+ link_id, granted_scopes, grant_version, calendar_disabled_at+ )+ VALUES ($1, $2, 1, now())+ ON CONFLICT (link_id) DO UPDATE+ SET granted_scopes = EXCLUDED.granted_scopes,+ grant_version = email_link_google_scopes.grant_version + 1,+ calendar_disabled_at = now(),+ updated_at = now()+ RETURNING grant_version AS "grant_version!"+ "#,+ email_link_id,+ &granted_scopes,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(report)?;++ // Fence anything mid-flight against the superseded grant, then tear+ // the local projection down and drop the account itself, which+ // cascades its calendars and backfill jobs.+ invalidate_stale_google_jobs_tx(&mut tx, email_link_id, grant_version).await?;+ disable_google_calendar_capability_tx(&mut tx, email_link_id).await?;+ sqlx::query!(+ "DELETE FROM calendar_accounts WHERE email_link_id = $1",+ email_link_id,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;++ tx.commit().await.map_err(report)?;+ Ok(Some(DisconnectedGoogleCalendar {+ token_identity: CalendarLinkTokenIdentity {+ fusionauth_user_id: row.fusionauth_user_id,+ email_address: row.email_address,+ provider: row.provider,+ },+ watch_channels,+ }))+ }+#[tracing::instrument(skip(self, write), err)]async fn upsert_event(&self, write: CalendarEventWrite) -> Result<Uuid, Report> {let mut tx = self.pool.begin().await.map_err(report)?;@@ -1926,6 +2055,25 @@ async fn invalidate_stale_google_jobs_tx(Ok(())}+async fn clear_calendar_opt_out_tx(+ tx: &mut Transaction<'_, Postgres>,+ email_link_id: Uuid,+) -> Result<(), Report> {+ sqlx::query!(+ r#"+ UPDATE email_link_google_scopes+ SET calendar_disabled_at = NULL,+ updated_at = now()+ WHERE link_id = $1 AND calendar_disabled_at IS NOT NULL+ "#,+ email_link_id,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ Ok(())+}+async fn disable_google_calendar_capability_tx(tx: &mut Transaction<'_, Postgres>,email_link_id: Uuid,@@ -1982,9 +2130,26 @@ async fn disable_google_calendar_capability_tx(.fetch_all(&mut **tx).await.map_err(report)?;- for event_id in affected_event_ids {- restore_best_source_or_delete(tx, event_id).await?;+ for event_id in &affected_event_ids {+ restore_best_source_or_delete(tx, *event_id).await?;}++ // Reminder delivery claims are deliberately not foreign-keyed to+ // occurrences, so an event that lost its last source takes its claims with+ // it here rather than leaving them behind forever.+ sqlx::query!(+ r#"+ DELETE FROM calendar_event_reminder_deliveries d+ WHERE d.event_id = ANY($1)+ AND NOT EXISTS (+ SELECT 1 FROM calendar_events e WHERE e.id = d.event_id+ )+ "#,+ &affected_event_ids,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;Ok(())}diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsindex c1d711f986..6dd4163173 100644--- a/crates/calendar_events/src/outbound/pg/test.rs+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -214,7 +214,11 @@ async fn applying_grant_recreates_missing_side_table_state_from_version_zero(poo.unwrap();let grant = PgCalendarRepository::new(pool.clone())- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();assert!(grant.changed);@@ -253,6 +257,7 @@ async fn calendar_capability_transition_schedules_once_and_failed_jobs_can_retry.apply_google_grant(link_id,GoogleScopeSet::parse("https://www.googleapis.com/auth/gmail.modify"),+ CalendarGrantIntent::CalendarRequested,).await.unwrap();@@ -260,14 +265,22 @@ async fn calendar_capability_transition_schedules_once_and_failed_jobs_can_retryassert!(partial.jobs.is_empty());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();assert!(enabled.changed);assert_eq!(enabled.jobs.len(), 1);let duplicate = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();assert!(!duplicate.changed);@@ -290,7 +303,11 @@ async fn calendar_capability_transition_schedules_once_and_failed_jobs_can_retry.unwrap();let retried = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();assert!(!retried.changed);@@ -321,7 +338,11 @@ async fn removing_calendar_scope_disables_sources_and_fences_the_running_job(poolet link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();let google_job = enabled@@ -389,6 +410,7 @@ async fn removing_calendar_scope_disables_sources_and_fences_the_running_job(poo.apply_google_grant(link_id,GoogleScopeSet::parse("https://www.googleapis.com/auth/gmail.modify"),+ CalendarGrantIntent::CalendarRequested,).await.unwrap();@@ -428,7 +450,11 @@ async fn removing_calendar_scope_disables_sources_and_fences_the_running_job(poo));let reenabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();assert_eq!(reenabled.jobs.len(), 1);@@ -450,7 +476,11 @@ async fn completed_google_job_is_rearmed_and_reuses_calendar_sync_state(pool: Pglet link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();let google_job = enabled@@ -607,9 +637,13 @@ async fn canonical_precedence_uses_the_selected_source_clock(pool: PgPool) {let later_clock = source_clock + Duration::hours(3);let winning_clock = source_clock + Duration::hours(2);- repo.apply_google_grant(link_id, complete_grant())- .await- .unwrap();+ repo.apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();let provider = provider_ids(&repo, link_id).await;let mut first = timed_upsert(@@ -658,7 +692,11 @@ async fn fenced_google_snapshot_removes_deleted_events_and_calendars(pool: PgPoolet link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();let account_id = repo.upsert_google_account(link_id).await.unwrap();@@ -782,7 +820,11 @@ async fn expired_google_worker_cannot_resurrect_reconciled_provider_data(pool: Plet link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();let account_id = repo.upsert_google_account(link_id).await.unwrap();@@ -929,7 +971,11 @@ async fn google_snapshot_deletion_removes_an_event_without_a_surviving_source(polet link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();let (account_id, calendar_id) = provider_ids(&repo, link_id).await;@@ -1005,7 +1051,11 @@ async fn incremental_cancellation_tombstones_retire_sources_without_a_snapshot(plet link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();let (account_id, calendar_id) = provider_ids(&repo, link_id).await;@@ -1363,7 +1413,11 @@ async fn watch_channels_round_trip_from_recording_to_targeted_rearm(pool: PgPoollet link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();let account_id = repo.upsert_google_account(link_id).await.unwrap();@@ -1495,9 +1549,13 @@ async fn sync_status_reflects_visible_account_ingestion_state(pool: PgPool) {);let link_id = insert_link(&pool, owner_id).await;- repo.apply_google_grant(link_id, complete_grant())- .await- .unwrap();+ repo.apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();let account_id = repo.upsert_google_account(link_id).await.unwrap();assert_eq!(repo.sync_status(owner_id).await.unwrap(),@@ -1522,9 +1580,13 @@ async fn unchanged_google_projection_skips_the_write_path(pool: PgPool) {let owner_id = "macro|[email protected]";let link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());- repo.apply_google_grant(link_id, complete_grant())- .await- .unwrap();+ repo.apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();let account_id = repo.upsert_google_account(link_id).await.unwrap();let calendar_id = repo.upsert_calendar_fixture(@@ -1776,7 +1838,11 @@ async fn stale_google_source_projection_cannot_resurface_during_reconciliation(plet link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();let account_id = repo.upsert_google_account(link_id).await.unwrap();@@ -2037,7 +2103,11 @@ async fn calendar_permission_failure_does_not_mark_the_gmail_link_for_reauth(poolet link_id = insert_link(&pool, owner_id).await;let repo = PgCalendarRepository::new(pool.clone());let enabled = repo- .apply_google_grant(link_id, complete_grant())+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ ).await.unwrap();let job = enabled@@ -2142,9 +2212,13 @@ async fn unclaimed_permanent_google_failure_marks_account_error(pool: PgPool) {}async fn grant_and_provider_ids(repo: &PgCalendarRepository, link_id: Uuid) -> (Uuid, Uuid) {- repo.apply_google_grant(link_id, complete_grant())- .await- .unwrap();+ repo.apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();provider_ids(repo, link_id).await}@@ -2926,3 +3000,288 @@ async fn conference_provider_round_trips_through_persistence(pool: PgPool) {Some(ConferenceProvider::GoogleMeet));}++/// A grant that also carries Gmail, so a disconnect can be shown to take the+/// calendar scopes and nothing else.+fn gmail_and_calendar_grant() -> GoogleScopeSet {+ GoogleScopeSet::parse(&format!(+ "https://www.googleapis.com/auth/gmail.modify {}",+ GOOGLE_CALENDAR_SCOPES.join(" ")+ ))+}++/// Bring one inbox's calendar fully to life: account, calendar, open push+/// channel, and a synced event with an outstanding reminder delivery claim.+async fn connected_calendar(+ pool: &PgPool,+ repo: &PgCalendarRepository,+ owner_id: &str,+ link_id: Uuid,+) -> (Uuid, Uuid, Uuid, Uuid) {+ let enabled = repo+ .apply_google_grant(+ link_id,+ gmail_and_calendar_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();+ let job = enabled+ .jobs+ .iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let account_id = job.account_id.unwrap();+ let key = CalendarBackfillJobKey {+ job_id: job.id,+ email_link_id: link_id,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("Google job should be claimable");+ };+ let calendar_id = repo+ .upsert_google_calendar(+ key,+ lease_token,+ account_id,+ ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ default_reminders: Vec::new(),+ },+ )+ .await+ .unwrap()+ .id;+ let channel_id = Uuid::new_v4();+ repo.record_watch_channel(+ key,+ lease_token,+ account_id,+ calendar_id,+ GoogleWatchChannel {+ channel_id,+ resource_id: "resource-1".to_string(),+ expires_at: (Utc::now() + Duration::days(6)).trunc_subsecs(6),+ },+ )+ .await+ .unwrap();+ let event_id = repo+ .upsert_event(CalendarEventWrite::GoogleBackfill {+ key,+ lease_token,+ upsert: timed_upsert(+ owner_id,+ link_id,+ (account_id, calendar_id),+ "[email protected]",+ "Removed by disconnect",+ 1,+ ),+ })+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO calendar_event_reminder_deliveries (+ id, event_id, occurrence_key, minutes_before, fire_at+ )+ VALUES ($1, $2, 'key', 10, now())+ "#,+ Uuid::now_v7(),+ event_id,+ )+ .execute(pool)+ .await+ .unwrap();+ (account_id, calendar_id, event_id, channel_id)+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn disconnecting_calendar_removes_the_data_and_records_the_opt_out(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, _calendar_id, event_id, channel_id) =+ connected_calendar(&pool, &repo, owner_id, link_id).await;++ let disconnected = repo+ .disconnect_google_calendar(owner_id, link_id)+ .await+ .unwrap()+ .expect("the owner's inbox is disconnectable");++ assert_eq!(+ disconnected.watch_channels,+ vec![CalendarWatchRelease {+ channel_id: channel_id.to_string(),+ resource_id: "resource-1".to_string(),+ }]+ );+ assert_eq!(disconnected.token_identity.fusionauth_user_id, owner_id);+ assert_eq!(disconnected.token_identity.provider, "GMAIL");++ let remaining = sqlx::query!(+ r#"+ SELECT+ (SELECT count(*) FROM calendar_accounts WHERE email_link_id = $1) AS "accounts!",+ (SELECT count(*) FROM calendars WHERE account_id = $2) AS "calendars!",+ (SELECT count(*) FROM calendar_events WHERE source_link_id = $1) AS "events!",+ (SELECT count(*) FROM calendar_event_sources WHERE source_link_id = $1) AS "sources!",+ (SELECT count(*) FROM calendar_event_occurrences WHERE event_id = $3) AS "occurrences!",+ (SELECT count(*) FROM calendar_event_reminder_deliveries WHERE event_id = $3) AS "deliveries!",+ (SELECT count(*) FROM calendar_backfill_jobs WHERE email_link_id = $1) AS "jobs!"+ "#,+ link_id,+ account_id,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(remaining.accounts, 0);+ assert_eq!(remaining.calendars, 0);+ assert_eq!(remaining.events, 0);+ assert_eq!(remaining.sources, 0);+ assert_eq!(remaining.occurrences, 0);+ assert_eq!(remaining.deliveries, 0);+ assert_eq!(remaining.jobs, 0);++ // A notification for the closed channel no longer resolves to the inbox.+ assert_eq!(+ repo.find_watch_target(&channel_id.to_string(), "resource-1")+ .await+ .unwrap(),+ None+ );++ let grant = sqlx::query!(+ r#"+ SELECT+ granted_scopes,+ grant_version,+ (calendar_disabled_at IS NOT NULL) AS "opted_out!"+ FROM email_link_google_scopes+ WHERE link_id = $1+ "#,+ link_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(+ GoogleScopeSet::from_scopes(grant.granted_scopes),+ GoogleScopeSet::parse("https://www.googleapis.com/auth/gmail.modify"),+ "Gmail keeps working; only the calendar scopes leave the grant"+ );+ assert_eq!(grant.grant_version, 2);+ assert!(grant.opted_out);+}++/// Consent requests carry `include_granted_scopes=true`, so a later Gmail-only+/// connect reports the calendar scopes Google still holds. That must not+/// resurrect calendar; only a flow that asked for calendar turns it back on.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_reissued_grant_keeps_calendar_off_until_it_is_requested_again(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ connected_calendar(&pool, &repo, owner_id, link_id).await;+ repo.disconnect_google_calendar(owner_id, link_id)+ .await+ .unwrap()+ .unwrap();++ let incidental = repo+ .apply_google_grant(+ link_id,+ gmail_and_calendar_grant(),+ CalendarGrantIntent::Incidental,+ )+ .await+ .unwrap();+ assert!(!incidental.changed);+ assert!(incidental.jobs.is_empty());+ let held = sqlx::query!(+ r#"+ SELECT granted_scopes, (calendar_disabled_at IS NOT NULL) AS "opted_out!"+ FROM email_link_google_scopes WHERE link_id = $1+ "#,+ link_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert!(+ !GoogleScopeSet::from_scopes(held.granted_scopes).has_calendar_capability(),+ "a scope that merely rode along must not be recorded"+ );+ assert!(held.opted_out);+ assert_eq!(+ sqlx::query_scalar!(+ "SELECT count(*) AS \"count!\" FROM calendar_accounts WHERE email_link_id = $1",+ link_id+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ 0+ );++ let requested = repo+ .apply_google_grant(+ link_id,+ gmail_and_calendar_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();+ assert!(requested.changed);+ assert_eq!(requested.jobs.len(), 1);+ let restored = sqlx::query!(+ r#"+ SELECT granted_scopes, (calendar_disabled_at IS NOT NULL) AS "opted_out!"+ FROM email_link_google_scopes WHERE link_id = $1+ "#,+ link_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert!(GoogleScopeSet::from_scopes(restored.granted_scopes).has_calendar_capability());+ assert!(!restored.opted_out);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn only_the_owner_can_disconnect_an_inbox_calendar(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ connected_calendar(&pool, &repo, owner_id, link_id).await;++ assert!(+ repo.disconnect_google_calendar("macro|[email protected]", link_id)+ .await+ .unwrap()+ .is_none()+ );+ assert_eq!(+ sqlx::query_scalar!(+ "SELECT count(*) AS \"count!\" FROM calendar_accounts WHERE email_link_id = $1",+ link_id+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ 1+ );+}diff --git a/crates/email_db_client/src/links/get.rs b/crates/email_db_client/src/links/get.rsindex 00b0636b55..4af94afaa9 100644--- a/crates/email_db_client/src/links/get.rs+++ b/crates/email_db_client/src/links/get.rs@@ -176,6 +176,10 @@ pub struct InboxDetails {/// The Google OAuth scopes recorded for the link's grant. An empty vector/// represents either an absent grant-state row or the initial version-0 state.pub google_granted_scopes: Vec<String>,+ /// Whether the user turned the calendar capability off for this inbox.+ /// Distinguishes a deliberate opt-out from a grant that never carried the+ /// calendar scopes, which read identically from the scopes alone.+ pub calendar_disabled: bool,}struct DbInboxDetailsRow {@@ -194,6 +198,7 @@ struct DbInboxDetailsRow {signature: Option<String>,latest_backfill_status: Option<db::backfill::BackfillJobStatus>,google_granted_scopes: Vec<String>,+ calendar_disabled: bool,photo_url: Option<String>,}@@ -225,7 +230,8 @@ pub async fn fetch_inbox_details_for_macro_id(s.signature,bj.status as "latest_backfill_status?: _",c.sfs_photo_url as "photo_url?",- COALESCE(g.granted_scopes, '{}') AS "google_granted_scopes!"+ COALESCE(g.granted_scopes, '{}') AS "google_granted_scopes!",+ (g.calendar_disabled_at IS NOT NULL) AS "calendar_disabled!"FROM (SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,@@ -284,6 +290,7 @@ pub async fn fetch_inbox_details_for_macro_id(latest_backfill_status: row.latest_backfill_status.map(Into::into),photo_url: row.photo_url,google_granted_scopes: row.google_granted_scopes,+ calendar_disabled: row.calendar_disabled,})}).collect()diff --git a/crates/email_db_client/src/links/get/test.rs b/crates/email_db_client/src/links/get/test.rsindex c201093548..1d868613e2 100644--- a/crates/email_db_client/src/links/get/test.rs+++ b/crates/email_db_client/src/links/get/test.rs@@ -370,6 +370,20 @@ async fn fetch_inbox_details_reads_google_scopes_from_side_table(let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;assert_eq!(details.len(), 1);assert_eq!(details[0].google_granted_scopes, granted_scopes);+ assert!(!details[0].calendar_disabled);++ sqlx::query!(+ "UPDATE email_link_google_scopes SET calendar_disabled_at = now() WHERE link_id = $1",+ link_id,+ )+ .execute(&pool)+ .await?;++ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;+ assert!(+ details[0].calendar_disabled,+ "an opted-out inbox reads as deliberately disabled, not merely ungranted"+ );sqlx::query!("DELETE FROM email_link_google_scopes WHERE link_id = $1",@@ -381,6 +395,7 @@ async fn fetch_inbox_details_reads_google_scopes_from_side_table(let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;assert_eq!(details.len(), 1);assert!(details[0].google_granted_scopes.is_empty());+ assert!(!details[0].calendar_disabled);Ok(())}diff --git a/crates/macro_db_client/migrations/20260817153144_calendar_disabled_opt_out.sql b/crates/macro_db_client/migrations/20260817153144_calendar_disabled_opt_out.sqlnew file mode 100644index 0000000000..c9ce56786c--- /dev/null+++ b/crates/macro_db_client/migrations/20260817153144_calendar_disabled_opt_out.sql@@ -0,0 +1,11 @@+-- An explicit user opt-out of the calendar capability, recorded when the user+-- turns calendar off from settings or the calendar view.+--+-- Google has no per-scope revocation: dropping the calendar scopes from the+-- recorded grant is what stops Macro using them, but the authorization request+-- carries `include_granted_scopes=true`, so any later Gmail consent would hand+-- the calendar scopes back and silently resurrect sync. This stamp fences that+-- path — while it is set, an incidental re-grant keeps calendar off, and only a+-- consent flow that explicitly asked for calendar clears it.+ALTER TABLE email_link_google_scopes+ ADD COLUMN calendar_disabled_at timestamptz;diff --git a/crates/models_email/src/email/api/link.rs b/crates/models_email/src/email/api/link.rsindex 52cb33d91c..3eb8d27a7c 100644--- a/crates/models_email/src/email/api/link.rs+++ b/crates/models_email/src/email/api/link.rs@@ -103,6 +103,11 @@ pub struct Link {/// grants where the user declined it); drives the per-inbox calendar/// upgrade prompt. Re-running the connect flow records the new grant.pub needs_calendar_permission: bool,+ /// Whether the user turned calendar off for this inbox, which also removed+ /// its calendar data. `needs_calendar_permission` is true either way, so+ /// this is what separates "never granted" from "deliberately off" —+ /// unprompted calendar nags must stay quiet for the latter.+ pub calendar_disabled: bool,pub settings: Settings,pub is_primary: bool,pub created_at: DateTime<Utc>,@@ -116,6 +121,7 @@ impl Link {sync_status: SyncStatus,photo_url: Option<String>,needs_calendar_permission: bool,+ calendar_disabled: bool,) -> Self {Link {id: source.id,@@ -128,6 +134,7 @@ impl Link {sync_status,needs_reauth: source.needs_reauth,needs_calendar_permission,+ calendar_disabled,settings,is_primary: source.is_primary,created_at: source.created_at,diff --git a/packages/sdk/generated/email/index.ts b/packages/sdk/generated/email/index.tsindex adf9aa054c..e7b1964acf 100644--- a/packages/sdk/generated/email/index.ts+++ b/packages/sdk/generated/email/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, Attachment, AttachmentDraft, AttachmentForwarded, AttendeeResponseStatus, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CalendarAttendee, CalendarAttendeeInputBody, CalendarDeletionScopeParam, CalendarEvent, CalendarMutationApiError, CalendarMutationErrorCode, CalendarRsvpScopeParam, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, ConferenceChange, ConferenceProvider, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmptyResponse, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventVisibility, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, Message, MessageListVisibility, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RefreshCalendarEvent, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadPreviewCursor, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadSummary, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value, VisibleCalendar } from './types.gen';+export type { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, Attachment, AttachmentDraft, AttachmentForwarded, AttendeeResponseStatus, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CalendarAttendee, CalendarAttendeeInputBody, CalendarDeletionScopeParam, CalendarEvent, CalendarMutationApiError, CalendarMutationErrorCode, CalendarRsvpScopeParam, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, ConferenceChange, ConferenceProvider, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarError, DisableLinkCalendarErrors, DisableLinkCalendarResponse, DisableLinkCalendarResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmptyResponse, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventVisibility, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, Message, MessageListVisibility, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RefreshCalendarEvent, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadPreviewCursor, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadSummary, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value, VisibleCalendar } from './types.gen';diff --git a/packages/sdk/generated/email/sdk.gen.ts b/packages/sdk/generated/email/sdk.gen.tsindex 69966d4219..292f66b65b 100644--- a/packages/sdk/generated/email/sdk.gen.ts+++ b/packages/sdk/generated/email/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddDraftAttachmentData, AddDraftAttachmentErrors, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentErrors, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelErrors, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponses, ArchiveThreadData, ArchiveThreadErrors, ArchiveThreadResponses, BlockSenderData, BlockSenderErrors, BlockSenderResponses, CancelBackfillGmailData, CancelBackfillGmailErrors, CancelBackfillGmailResponses, CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, CreateDraftData, CreateDraftErrors, CreateDraftResponses, CreateLabelData, CreateLabelErrors, CreateLabelResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, DeleteDraftData, DeleteDraftErrors, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterErrors, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelErrors, DeleteLabelResponses, DeleteLinkData, DeleteLinkErrors, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftErrors, DeleteScheduledDraftResponses, DisableSyncData, DisableSyncErrors, DisableSyncResponses, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponses, GetAttachmentErrors, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailErrors, GetBackfillGmailResponses, GetMessageData, GetMessageErrors, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchErrors, GetMessagesBatchResponses, GetScheduledMessagesData, GetScheduledMessagesErrors, GetScheduledMessagesResponses, GetThreadData, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponses, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksErrors, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponses, InitUserData, InitUserErrors, InitUserResponses, ListBackfillGmailData, ListBackfillGmailErrors, ListBackfillGmailResponses, ListBlockedSendersData, ListBlockedSendersErrors, ListBlockedSendersResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, ListContactsData, ListContactsErrors, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersErrors, ListEmailFiltersResponses, ListLabelsData, ListLabelsErrors, ListLabelsResponses, ListLinksData, ListLinksErrors, ListLinksResponses, PatchSettingsData, PatchSettingsErrors, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorErrors, PreviewsInboxCursorResponses, RemoveDraftAttachmentData, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkErrors, ResyncLinkResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, SendMessageData, SendMessageErrors, SendMessageResponses, ThreadSeenData, ThreadSeenErrors, ThreadSeenResponses, UnblockSenderData, UnblockSenderErrors, UnblockSenderResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses, UpdateThreadProjectData, UpdateThreadProjectErrors, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterErrors, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageErrors, UpsertScheduledMessageResponses } from './types.gen';+import type { AddDraftAttachmentData, AddDraftAttachmentErrors, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentErrors, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelErrors, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponses, ArchiveThreadData, ArchiveThreadErrors, ArchiveThreadResponses, BlockSenderData, BlockSenderErrors, BlockSenderResponses, CancelBackfillGmailData, CancelBackfillGmailErrors, CancelBackfillGmailResponses, CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, CreateDraftData, CreateDraftErrors, CreateDraftResponses, CreateLabelData, CreateLabelErrors, CreateLabelResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, DeleteDraftData, DeleteDraftErrors, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterErrors, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelErrors, DeleteLabelResponses, DeleteLinkData, DeleteLinkErrors, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftErrors, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarErrors, DisableLinkCalendarResponses, DisableSyncData, DisableSyncErrors, DisableSyncResponses, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponses, GetAttachmentErrors, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailErrors, GetBackfillGmailResponses, GetMessageData, GetMessageErrors, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchErrors, GetMessagesBatchResponses, GetScheduledMessagesData, GetScheduledMessagesErrors, GetScheduledMessagesResponses, GetThreadData, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponses, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksErrors, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponses, InitUserData, InitUserErrors, InitUserResponses, ListBackfillGmailData, ListBackfillGmailErrors, ListBackfillGmailResponses, ListBlockedSendersData, ListBlockedSendersErrors, ListBlockedSendersResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, ListContactsData, ListContactsErrors, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersErrors, ListEmailFiltersResponses, ListLabelsData, ListLabelsErrors, ListLabelsResponses, ListLinksData, ListLinksErrors, ListLinksResponses, PatchSettingsData, PatchSettingsErrors, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorErrors, PreviewsInboxCursorResponses, RemoveDraftAttachmentData, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkErrors, ResyncLinkResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, SendMessageData, SendMessageErrors, SendMessageResponses, ThreadSeenData, ThreadSeenErrors, ThreadSeenResponses, UnblockSenderData, UnblockSenderErrors, UnblockSenderResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses, UpdateThreadProjectData, UpdateThreadProjectErrors, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterErrors, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageErrors, UpsertScheduledMessageResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -396,6 +396,21 @@ export class Sdk extends HeyApiClient {return (options.client ?? this.client).delete<DeleteLinkResponses, DeleteLinkErrors, ThrowOnError>({ url: '/email/links/{link_id}', ...options });}+ /**+ * Turns calendar off for a connected inbox.+ *+ * Removes the inbox's calendar data, drops the calendar scopes from its+ * recorded Google grant, and closes its push channels, so the inbox reads as+ * calendar-less until the user runs the calendar consent flow again. Gmail+ * sync is untouched.+ *+ * Only the inbox's owner may do this: a delegate can see the owner's calendar+ * but must not be able to delete the owner's data.+ */+ public disableLinkCalendar<ThrowOnError extends boolean = false>(options: Options<DisableLinkCalendarData, ThrowOnError>): RequestResult<DisableLinkCalendarResponses, DisableLinkCalendarErrors, ThrowOnError> {+ return (options.client ?? this.client).delete<DisableLinkCalendarResponses, DisableLinkCalendarErrors, ThrowOnError>({ url: '/email/links/{link_id}/calendar', ...options });+ }+/*** Re-syncs a linked inbox by enqueuing a fresh backfill.*diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.tsindex 4a8044c791..67bbda49ba 100644--- a/packages/sdk/generated/email/types.gen.ts+++ b/packages/sdk/generated/email/types.gen.ts@@ -1043,6 +1043,13 @@ export type LabelListVisibility = 'LabelShow' | 'LabelShowIfUnread' | 'LabelHideexport type LabelType = 'System' | 'User';export type Link = {+ /**+ * Whether the user turned calendar off for this inbox, which also removed+ * its calendar data. `needs_calendar_permission` is true either way, so+ * this is what separates "never granted" from "deliberately off" —+ * unprompted calendar nags must stay quiet for the latter.+ */+ calendar_disabled: boolean;created_at: string;email_address: string;fusionauth_user_id: string;@@ -2495,6 +2502,33 @@ export type DeleteLinkResponses = {export type DeleteLinkResponse = DeleteLinkResponses[keyof DeleteLinkResponses];+export type DisableLinkCalendarData = {+ body?: never;+ path: {+ /**+ * Inbox link ID.+ */+ link_id: string;+ };+ query?: never;+ url: '/email/links/{link_id}/calendar';+};++export type DisableLinkCalendarErrors = {+ 401: ErrorResponse;+ 403: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type DisableLinkCalendarError = DisableLinkCalendarErrors[keyof DisableLinkCalendarErrors];++export type DisableLinkCalendarResponses = {+ 204: EmptyResponse;+};++export type DisableLinkCalendarResponse = DisableLinkCalendarResponses[keyof DisableLinkCalendarResponses];+export type ResyncLinkData = {body?: never;path: {diff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.jsonindex 399c38e008..da8f30ac33 100644--- a/packages/sdk/specs/email.json+++ b/packages/sdk/specs/email.json@@ -2198,6 +2198,78 @@}}},+ "/email/links/{link_id}/calendar": {+ "delete": {+ "tags": ["Links"],+ "summary": "Turns calendar off for a connected inbox.",+ "description": "Removes the inbox's calendar data, drops the calendar scopes from its\nrecorded Google grant, and closes its push channels, so the inbox reads as\ncalendar-less until the user runs the calendar consent flow again. Gmail\nsync is untouched.\n\nOnly the inbox's owner may do this: a delegate can see the owner's calendar\nbut must not be able to delete the owner's data.",+ "operationId": "disable_link_calendar",+ "parameters": [+ {+ "name": "link_id",+ "in": "path",+ "description": "Inbox link ID.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EmptyResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/email/links/{link_id}/resync": {"post": {"tags": ["Links"],@@ -5151,12 +5223,17 @@"sync_status","needs_reauth","needs_calendar_permission",+ "calendar_disabled","settings","is_primary","created_at","updated_at"],"properties": {+ "calendar_disabled": {+ "type": "boolean",+ "description": "Whether the user turned calendar off for this inbox, which also removed\nits calendar data. `needs_calendar_permission` is true either way, so\nthis is what separates \"never granted\" from \"deliberately off\" —\nunprompted calendar nags must stay quiet for the latter."+ },"created_at": {"type": "string","format": "date-time"diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 875f1fdd60..d279257a47 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -145,6 +145,7 @@ export const contactsBacklog =export const emailExcluded = ['cancelBackfillGmail','deleteLink',+ 'disableLinkCalendar','disableSync','getBackfillGmail','getBackfillGmailActive',diff --git a/services/email_service/src/api/email/init.rs b/services/email_service/src/api/email/init.rsindex 82fc9a2759..43b94e63bc 100644--- a/services/email_service/src/api/email/init.rs+++ b/services/email_service/src/api/email/init.rs@@ -7,7 +7,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};-use calendar_events::domain::models::GoogleScopeSet;+use calendar_events::domain::models::{CalendarGrantIntent, GoogleScopeSet};use email::domain::events::{EmailMacroEvent, LinkConnectedMetadata};use email::domain::models::UserProvider;use email::domain::ports::EmailRepo;@@ -15,6 +15,7 @@ use email::outbound::EmailPgRepo;use email_api_client::domain::models::{EmailApiError, TokenFreshness};use email_service::pubsub::publish_email_event;use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};+use macro_db_client::in_progress_user_link::InProgressUserLink;use macro_user_id::email::EmailStr;use macro_user_id::user_id::MacroUserIdStr;use model::response::ErrorResponse;@@ -252,7 +253,7 @@ async fn init_user() -> Result<Response, InitError> {let macro_user_id = authorization.authorization.user.macro_user_id.clone();let user_context = authorization.authorization.user.user_context.clone();- let mut completed_google_grant: Option<Vec<String>> = None;+ let mut completed_google_grant: Option<CompletedGoogleGrant> = None;tracing::info!(user_id = %user_context.user_id, ?link_id, "Init called");let pg_repo = EmailPgRepo::new(ctx.db.clone());@@ -262,7 +263,8 @@ async fn init_user(macro_db_client::in_progress_user_link::get_in_progress_user_link(&ctx.db, &link_id).await.context("Failed to fetch in_progress_user_link")?;- completed_google_grant = Some(in_progress.granted_google_scopes.clone());+ let completed_grant = CompletedGoogleGrant::from_in_progress(&in_progress);+ completed_google_grant = Some(completed_grant.clone());if in_progress.macro_user_id.to_string() != user_context.fusion_user_id {return Err(InitError::BadRequest(@@ -333,13 +335,8 @@ async fn init_user(.await.context("Failed to commit graph delegation transaction")?;- apply_and_consume_calendar_grant(- &ctx,- child_link.id,- link_id,- &in_progress.granted_google_scopes,- )- .await?;+ apply_and_consume_calendar_grant(&ctx, child_link.id, link_id, &completed_grant)+ .await?;return Ok((StatusCode::OK,@@ -420,7 +417,7 @@ async fn init_user(&ctx,existing_link.id,link_id,- &in_progress.granted_google_scopes,+ &completed_grant,).await?;tracing::info!(@@ -542,13 +539,8 @@ async fn init_user(}}- apply_and_consume_calendar_grant(- &ctx,- promoted.link_id,- link_id,- &in_progress.granted_google_scopes,- )- .await?;+ apply_and_consume_calendar_grant(&ctx, promoted.link_id, link_id, &completed_grant)+ .await?;return Ok((StatusCode::OK,@@ -633,8 +625,8 @@ async fn init_user((link, email)};- if let (Some(scopes), Some(link_id)) = (completed_google_grant.as_deref(), link_id) {- apply_and_consume_calendar_grant(&ctx, link.id, link_id, scopes).await?;+ if let (Some(grant), Some(link_id)) = (completed_google_grant.as_ref(), link_id) {+ apply_and_consume_calendar_grant(&ctx, link.id, link_id, grant).await?;} else if completed_google_grant.is_none() {apply_grant_discovered_from_token(&ctx, &link).await;}@@ -788,7 +780,12 @@ async fn apply_grant_discovered_from_token(ctx: &ApiContext, link: &link::Link)};match fetch_token_scopes(token.expose_secret()).await {Ok(scopes) => {- apply_calendar_grant(ctx.calendar_service.as_ref(), link.id, &scopes)+ apply_calendar_grant(+ ctx.calendar_service.as_ref(),+ link.id,+ &scopes,+ CalendarGrantIntent::Incidental,+ ).await.inspect_err(|error| {tracing::warn!(error = ?error, link_id = %link.id, "failed to apply discovered Google grant");@@ -831,15 +828,45 @@ async fn fetch_token_scopes(access_token: &str) -> anyhow::Result<Vec<String>> {.collect())}+/// The Google grant a completed link flow carries back, with what the consent+/// request asked for — the grant alone cannot say whether calendar scopes were+/// wanted or merely re-issued.+#[derive(Clone)]+struct CompletedGoogleGrant {+ intent: CalendarGrantIntent,+ granted_scopes: Vec<String>,+}++impl CompletedGoogleGrant {+ /// Only a consent request that asked for calendar counts as the user+ /// enabling it. Requests carry `include_granted_scopes=true`, so a plain+ /// Gmail reconnect hands calendar scopes back from an earlier grant, and+ /// that must not undo a deliberate opt-out.+ fn from_in_progress(in_progress: &InProgressUserLink) -> Self {+ let requested =+ GoogleScopeSet::from_scopes(in_progress.requested_google_scopes.iter().cloned());+ Self {+ intent: if requested.has_calendar_capability() {+ CalendarGrantIntent::CalendarRequested+ } else {+ CalendarGrantIntent::Incidental+ },+ granted_scopes: in_progress.granted_google_scopes.clone(),+ }+ }+}+async fn apply_calendar_grant(calendar_service: &CalendarGrantService,email_link_id: Uuid,granted_scopes: &[String],+ intent: CalendarGrantIntent,) -> Result<calendar_events::domain::models::AppliedGoogleGrant, InitError> {calendar_service.apply_google_grant(email_link_id,GoogleScopeSet::from_scopes(granted_scopes.iter().cloned()),+ intent,).await.map_err(|error| {@@ -853,16 +880,35 @@ async fn apply_and_consume_calendar_grant(ctx: &ApiContext,email_link_id: Uuid,in_progress_link_id: Uuid,- granted_scopes: &[String],+ grant: &CompletedGoogleGrant,) -> Result<calendar_events::domain::models::AppliedGoogleGrant, InitError> {- let applied =- apply_calendar_grant(ctx.calendar_service.as_ref(), email_link_id, granted_scopes).await?;+ let applied = apply_calendar_grant(+ ctx.calendar_service.as_ref(),+ email_link_id,+ &grant.granted_scopes,+ grant.intent,+ )+ .await?;macro_db_client::in_progress_user_link::delete_in_progress_user_link(&ctx.db,&in_progress_link_id,).await.context("Failed to consume applied Google grant")?;++ // Reaching here means consent completed for this inbox's mailbox and its+ // refresh token was just replaced, so any reauth flag is stale. Links+ // provisioned by this flow are upserted with the flag already clear; an+ // inbox that merely reconnected is not, and would keep asking to reconnect+ // until something happened to fetch a token. Best-effort: a stale badge is+ // a worse outcome to trade a failed reconnect for.+ email_db_client::links::update::clear_link_needs_reauth(&ctx.db, email_link_id)+ .await+ .inspect_err(|error| {+ tracing::warn!(error = ?error, link_id = %email_link_id, "failed to clear the reauth flag after a completed consent");+ })+ .ok();+Ok(applied)}diff --git a/services/email_service/src/api/email/init/test.rs b/services/email_service/src/api/email/init/test.rsindex 53904fac93..48964182d8 100644--- a/services/email_service/src/api/email/init/test.rs+++ b/services/email_service/src/api/email/init/test.rs@@ -143,3 +143,33 @@ fn only_shared_inbox_conflict_keeps_the_in_progress_link() {);}}++/// The grant alone cannot say whether the user wanted calendar: consent+/// requests carry `include_granted_scopes=true`, so Google re-issues the+/// calendar scopes of an earlier grant on a plain Gmail reconnect. Only what+/// the request asked for decides.+#[test]+fn calendar_intent_follows_the_consent_request_not_the_grant() {+ let calendar_scopes = calendar_events::domain::models::GOOGLE_CALENDAR_SCOPES+ .map(str::to_owned)+ .to_vec();+ let gmail_scope = "https://www.googleapis.com/auth/gmail.modify".to_owned();+ let in_progress = |requested: Vec<String>| InProgressUserLink {+ macro_user_id: Uuid::now_v7(),+ linked_email: None,+ requested_google_scopes: requested,+ granted_google_scopes: [vec![gmail_scope.clone()], calendar_scopes.clone()].concat(),+ };++ assert!(matches!(+ CompletedGoogleGrant::from_in_progress(&in_progress(vec![gmail_scope.clone()])).intent,+ CalendarGrantIntent::Incidental+ ));+ assert!(matches!(+ CompletedGoogleGrant::from_in_progress(&in_progress(+ [vec![gmail_scope.clone()], calendar_scopes.clone()].concat()+ ))+ .intent,+ CalendarGrantIntent::CalendarRequested+ ));+}diff --git a/services/email_service/src/api/email/links/calendar.rs b/services/email_service/src/api/email/links/calendar.rsnew file mode 100644index 0000000000..75b5e830a8--- /dev/null+++ b/services/email_service/src/api/email/links/calendar.rs@@ -0,0 +1,59 @@+use crate::api::context::{ApiContext, AuthorizationService};+use crate::api::email::links::access::{InboxAccess, InboxActionError, authorize_inbox_access};+use axum::extract::{Path, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use calendar_events::domain::ports::{CalendarMutationError, CalendarMutationService};+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};+use model::response::{EmptyResponse, ErrorResponse};+use uuid::Uuid;++/// Turns calendar off for a connected inbox.+///+/// Removes the inbox's calendar data, drops the calendar scopes from its+/// recorded Google grant, and closes its push channels, so the inbox reads as+/// calendar-less until the user runs the calendar consent flow again. Gmail+/// sync is untouched.+///+/// Only the inbox's owner may do this: a delegate can see the owner's calendar+/// but must not be able to delete the owner's data.+#[utoipa::path(+ delete,+ tag = "Links",+ path = "/email/links/{link_id}/calendar",+ operation_id = "disable_link_calendar",+ params(+ ("link_id" = Uuid, Path, description = "Inbox link ID."),+ ),+ responses(+ (status = 204, body=EmptyResponse),+ (status = 401, body=ErrorResponse),+ (status = 403, body=ErrorResponse),+ (status = 404, body=ErrorResponse),+ (status = 500, body=ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id), err)]+pub async fn disable_link_calendar_handler(+ State(ctx): State<ApiContext>,+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,+ Path(link_id): Path<Uuid>,+) -> Result<Response, InboxActionError> {+ let macro_user_id = &authorization.authorization.user.macro_user_id;+ let (_, access) = authorize_inbox_access(&ctx, macro_user_id.as_ref(), link_id).await?;+ if access == InboxAccess::Delegated {+ return Err(InboxActionError::Forbidden);+ }++ ctx.calendar_mutation_service+ .disconnect_calendar(macro_user_id.as_ref(), link_id)+ .await+ .map_err(|error| match error {+ CalendarMutationError::NotFound => InboxActionError::NotFound,+ error => InboxActionError::Internal(anyhow::anyhow!(+ "failed to disconnect the inbox calendar: {error:?}"+ )),+ })?;++ Ok(StatusCode::NO_CONTENT.into_response())+}diff --git a/services/email_service/src/api/email/links/list.rs b/services/email_service/src/api/email/links/list.rsindex 6b6a40d3cc..4817976fb0 100644--- a/services/email_service/src/api/email/links/list.rs+++ b/services/email_service/src/api/email/links/list.rs@@ -78,6 +78,7 @@ pub async fn list_links_handler(sync_status,inbox.photo_url,needs_calendar_permission,+ inbox.calendar_disabled,)}).collect();diff --git a/services/email_service/src/api/email/links/mod.rs b/services/email_service/src/api/email/links/mod.rsindex c29eeff4a2..a958362bb8 100644--- a/services/email_service/src/api/email/links/mod.rs+++ b/services/email_service/src/api/email/links/mod.rs@@ -1,4 +1,5 @@pub(crate) mod access;+pub(crate) mod calendar;pub(crate) mod delete;pub(crate) mod health_check;pub(crate) mod list;@@ -13,5 +14,9 @@ pub fn router() -> Router<ApiContext> {.route("/", get(list::list_links_handler)).route("/health-check", post(health_check::health_check_handler)).route("/{link_id}", delete(delete::delete_link_handler))+ .route(+ "/{link_id}/calendar",+ delete(calendar::disable_link_calendar_handler),+ ).route("/{link_id}/resync", post(resync::resync_link_handler))}diff --git a/services/email_service/src/api/swagger.rs b/services/email_service/src/api/swagger.rsindex c73486b856..f4992238f8 100644--- a/services/email_service/src/api/swagger.rs+++ b/services/email_service/src/api/swagger.rs@@ -92,6 +92,7 @@ use utoipa::OpenApi;email::links::list::list_links_handler,email::links::health_check::health_check_handler,email::links::delete::delete_link_handler,+ email::links::calendar::disable_link_calendar_handler,email::links::resync::resync_link_handler,email::labels::create::handler,email::labels::delete::handler,