Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(calendar): restore access and clarify sync progress (#7398)

gbirman74a85637595e
diff --git a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx b/apps/web/src/features/auth/CalendarPermissionPrompt.tsx
index e1d9f149fa..9e40eb8aba 100644
--- a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx
+++ b/apps/web/src/features/auth/CalendarPermissionPrompt.tsx
@@ -14,11 +14,11 @@ import { useEmailLinksQuery } from '@queries/email/link';
* grant to the existing link, which kicks off the calendar backfill.
*
* 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. 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.
+ * stack. Reconnecting restores previously enabled calendar access too; an
+ * inbox that never enabled calendar can still opt in through this prompt.
+ * Inboxes whose calendar the user turned off are also skipped — 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
@@ -58,7 +58,10 @@ export function CalendarPermissionPrompt() {
// Suppress re-prompting until the grant upgrades; on native the
// page stays mounted while the OAuth flow runs.
dismiss();
- startAddInbox({ scopes: 'calendar' });
+ void startAddInbox({
+ scopes: 'calendar',
+ emailAddress: link.email_address,
+ });
},
},
],
diff --git a/apps/web/src/features/auth/EmailAuth.test.tsx b/apps/web/src/features/auth/EmailAuth.test.tsx
new file mode 100644
index 0000000000..c5531e0909
--- /dev/null
+++ b/apps/web/src/features/auth/EmailAuth.test.tsx
@@ -0,0 +1,169 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { errAsync, okAsync, ResultAsync } from 'neverthrow';
+import type { JSX } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ init: vi.fn(),
+ refetch: vi.fn(),
+ failure: vi.fn(),
+ success: vi.fn(),
+ linkId: 'oauth-link',
+ restore: vi.fn(),
+}));
+vi.mock('@solidjs/router', () => ({
+ useNavigate: () => mocks.navigate,
+ useSearchParams: () => [{ link_id: mocks.linkId }],
+}));
+vi.mock('@core/email-link', () => ({
+ useEmailLinks: () => ({
+ query: { isSuccess: false, isError: false, refetch: mocks.refetch },
+ initEmailLink: mocks.init,
+ }),
+}));
+vi.mock('@core/auth', () => ({ updateUserAuth: vi.fn() }));
+vi.mock('@core/auth/email', () => ({ redirectToEmailAuth: vi.fn() }));
+vi.mock('@core/auth/login-events', () => ({ publishLoginSuccess: vi.fn() }));
+vi.mock('@app/lib/analytics/analytics-context', () => ({
+ useAnalytics: () => ({ pageView: vi.fn() }),
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { success: mocks.success, failure: mocks.failure },
+}));
+vi.mock('@core/constant/SettingsState', () => ({
+ restoreSettingsReturnTo: vi.fn(),
+}));
+vi.mock('@core/email-link/return-layout', () => ({
+ consumeInboxLinkReturn: mocks.restore,
+}));
+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
+ isNativeMobilePlatform: () => false,
+}));
+vi.mock('@queries/auth/user-info', () => ({
+ invalidateAllAfterLogin: vi.fn(),
+ useUserInfoQuery: () => ({ data: { tutorialComplete: true } }),
+}));
+vi.mock('@app/features/setup/flow/useOnboardingV4Flag', () => ({
+ useOnboardingV4Flag: () => () => ({ enabled: false }),
+}));
+vi.mock('@ui', () => ({
+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props} />
+ ),
+}));
+vi.mock('@app/features/inbox/ShareInboxConflictDialog', () => ({
+ ShareInboxConflictDialog: (props: {
+ onShare: () => void;
+ onCancel: () => void;
+ }) => (
+ <div>
+ <button onClick={props.onShare}>Share inbox</button>
+ <button onClick={props.onCancel}>Cancel share</button>
+ </div>
+ ),
+}));
+
+import { makeEmailAuthComponents } from './EmailAuth';
+
+const { EmailLinkCallback } = makeEmailAuthComponents({
+ callbackPath: '/signup-callback',
+ linkCallbackPath: '/inbox-link-callback',
+ successPath: '/',
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.linkId = 'oauth-link';
+ mocks.refetch.mockResolvedValue({});
+ mocks.restore.mockReturnValue({ url: '/calendar/week' });
+ mocks.init.mockReturnValue(okAsync(undefined));
+});
+afterEach(cleanup);
+
+describe('inbox consent callback', () => {
+ it('applies the grant without waiting for the old inbox query, then restores the calendar', async () => {
+ render(() => <EmailLinkCallback />);
+ await waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith('/calendar/week', {
+ replace: true,
+ })
+ );
+ expect(mocks.init).toHaveBeenCalledExactlyOnceWith({
+ linkId: 'oauth-link',
+ forceShare: false,
+ });
+ expect(mocks.refetch).toHaveBeenCalledOnce();
+ });
+
+ it('explains pending work and lets the user return without a later redirect', async () => {
+ let finish!: () => void;
+ mocks.init.mockReturnValue(
+ ResultAsync.fromSafePromise(
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ })
+ )
+ );
+ const mounted = render(() => <EmailLinkCallback />);
+ expect(
+ await screen.findByText('Finishing account connection…')
+ ).toBeTruthy();
+ await fireEvent.click(screen.getByRole('button', { name: 'Back to app' }));
+ expect(mocks.navigate).toHaveBeenCalledOnce();
+ mounted.unmount();
+ finish();
+ await waitFor(() => expect(mocks.refetch).toHaveBeenCalledOnce());
+ expect(mocks.navigate).toHaveBeenCalledOnce();
+ });
+
+ it('leaves the callback and explains an unexpected request failure', async () => {
+ mocks.init.mockImplementationOnce(() => {
+ throw new Error('network failed');
+ });
+ render(() => <EmailLinkCallback />);
+ await waitFor(() => expect(mocks.failure).toHaveBeenCalledOnce());
+ expect(mocks.navigate).toHaveBeenCalledWith('/calendar/week', {
+ replace: true,
+ });
+ });
+
+ it('reports declined permissions without getting stuck', async () => {
+ mocks.init.mockReturnValue(errAsync({ tag: 'NoGmailGrant' }));
+ render(() => <EmailLinkCallback />);
+ await waitFor(() =>
+ expect(mocks.failure).toHaveBeenCalledWith(
+ expect.stringContaining('Gmail access was not granted')
+ )
+ );
+ expect(mocks.navigate).toHaveBeenCalledOnce();
+ });
+
+ it('still holds the callback for a shared-inbox confirmation', async () => {
+ mocks.init.mockReturnValueOnce(
+ errAsync({
+ tag: 'SharedInboxConflict',
+ emailAddress: '[email protected]',
+ ownerEmail: '[email protected]',
+ })
+ );
+ render(() => <EmailLinkCallback />);
+ await fireEvent.click(
+ await screen.findByRole('button', { name: 'Share inbox' })
+ );
+ await waitFor(() =>
+ expect(mocks.init).toHaveBeenLastCalledWith({
+ linkId: 'oauth-link',
+ forceShare: true,
+ })
+ );
+ await waitFor(() => expect(mocks.navigate).toHaveBeenCalledOnce());
+ });
+});
diff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsx
index 9e402e7985..54ce341dc5 100644
--- a/apps/web/src/features/auth/EmailAuth.tsx
+++ b/apps/web/src/features/auth/EmailAuth.tsx
@@ -13,12 +13,14 @@ import { consumeInboxLinkReturn } from '@core/email-link/return-layout';
import { isMobile } from '@core/mobile/isMobile';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { whenSettled } from '@core/util/whenSettled';
+import SpinnerIcon from '@phosphor/spinner-gap.svg';
import {
invalidateAllAfterLogin,
useUserInfoQuery,
} from '@queries/auth/user-info';
import { useNavigate, useSearchParams } from '@solidjs/router';
-import { createSignal, onMount, Show, Suspense } from 'solid-js';
+import { Button } from '@ui';
+import { createSignal, onCleanup, onMount, Show, Suspense } from 'solid-js';
type EmailAuthParams = {
callbackPath: string;
@@ -121,6 +123,10 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { query, initEmailLink } = useEmailLinks();
+ let disposed = false;
+ onCleanup(() => {
+ disposed = true;
+ });
const [conflict, setConflict] = createSignal<{
linkId: string;
emailAddress: string;
@@ -150,6 +156,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
// form-factor default — the list view on mobile, where the desktop settings
// split doesn't exist and the toast is the confirmation.
const navigateAfterLink = (linkId: string) => {
+ if (disposed) return;
// A first-run user connected this inbox from the onboarding flow:
// return straight to it. Landing in mail settings would mount the app
// shell mid-onboarding just for NewOnboardingRedirect to bounce back.
@@ -171,65 +178,101 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
};
const runInit = async (linkId: string, forceShare: boolean) => {
- await initEmailLink({ linkId, forceShare }).match(
- async () => {
- // Pull the newly-provisioned link into the cache before leaving the
- // callback so the inbox panel shows it immediately on return rather
- // than flashing a stale list until its own refetch lands.
- await query.refetch();
- toast.success('Account connected');
- navigateAfterLink(linkId);
- },
- async (err) => {
- if (err.tag === 'AlreadyInitialized') {
+ try {
+ await initEmailLink({ linkId, forceShare }).match(
+ async () => {
+ // Pull the newly-provisioned link into the cache before leaving the
+ // callback so the inbox panel shows it immediately on return rather
+ // than flashing a stale list until its own refetch lands.
await query.refetch();
+ toast.success('Account connected');
navigateAfterLink(linkId);
- return;
- }
- // The mailbox is already connected by someone else. Hold the callback open
- // and let the user confirm sharing it before retrying with forceShare.
- if (err.tag === 'SharedInboxConflict' && !forceShare) {
- setConflict({
- linkId,
- emailAddress: err.emailAddress,
- ownerEmail: err.ownerEmail,
- });
- return;
- }
- if (err.tag === 'NoGmailGrant') {
- toast.failure(
- 'Gmail access was not granted. Please allow all requested permissions and try again.'
- );
+ },
+ async (err) => {
+ if (err.tag === 'AlreadyInitialized') {
+ await query.refetch();
+ navigateAfterLink(linkId);
+ return;
+ }
+ // The mailbox is already connected by someone else. Hold the callback open
+ // and let the user confirm sharing it before retrying with forceShare.
+ if (err.tag === 'SharedInboxConflict' && !forceShare) {
+ setConflict({
+ linkId,
+ emailAddress: err.emailAddress,
+ ownerEmail: err.ownerEmail,
+ });
+ return;
+ }
+ if (err.tag === 'NoGmailGrant') {
+ toast.failure(
+ 'Gmail access was not granted. Please allow all requested permissions and try again.'
+ );
+ navigateAfterLink(linkId);
+ return;
+ }
+ toast.failure('Failed to add inbox');
navigateAfterLink(linkId);
- return;
}
- toast.failure('Failed to add inbox');
- navigateAfterLink(linkId);
- }
- );
+ );
+ } catch {
+ if (disposed) return;
+ toast.failure(
+ 'Failed to finish connecting your account. Please try again from Settings.'
+ );
+ navigateAfterLink(linkId);
+ }
};
- whenSettled(
- query,
- async () => {
- const linkId =
- typeof searchParams.link_id === 'string' ? searchParams.link_id : null;
- if (!linkId) {
- toast.failure('Missing link id in callback URL');
- navigateToSuccess();
- return;
- }
-
- await runInit(linkId, false);
- },
- (error) => {
- toast.failure(error.message);
+ // Completing consent does not depend on the old inbox list loading first.
+ // A paused or slow query must not prevent the new grant from being applied.
+ onMount(() => {
+ const linkId =
+ typeof searchParams.link_id === 'string' ? searchParams.link_id : null;
+ if (!linkId) {
+ toast.failure('Missing link id in callback URL');
navigateToSuccess();
+ return;
}
- );
+
+ void runInit(linkId, false);
+ });
return (
- <Show when={conflict()} fallback={<LoadingBlock />}>
+ <Show
+ when={conflict()}
+ fallback={
+ <div class="flex size-full items-center justify-center p-6">
+ <div
+ role="status"
+ class="flex max-w-sm flex-col items-center gap-3 text-center"
+ >
+ <SpinnerIcon class="size-6 animate-spin motion-reduce:animate-none text-accent" />
+ <h1 class="text-sm font-semibold text-ink">
+ Finishing account connection…
+ </h1>
+ <p class="text-sm text-ink-muted">
+ We’re applying your Google permissions. Calendar events may take a
+ few minutes to sync after you return.
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ const linkId =
+ typeof searchParams.link_id === 'string'
+ ? searchParams.link_id
+ : undefined;
+ if (linkId) navigateAfterLink(linkId);
+ else navigateToSuccess();
+ }}
+ >
+ Back to app
+ </Button>
+ </div>
+ </div>
+ }
+ >
{(c) => (
<ShareInboxConflictDialog
open
diff --git a/apps/web/src/features/auth/GmailReauthenticationPrompt.tsx b/apps/web/src/features/auth/GmailReauthenticationPrompt.tsx
index de233ceeaa..e757a2e39e 100644
--- a/apps/web/src/features/auth/GmailReauthenticationPrompt.tsx
+++ b/apps/web/src/features/auth/GmailReauthenticationPrompt.tsx
@@ -1,5 +1,6 @@
import { useKeyedPersistentToasts } from '@core/component/Toast/useKeyedPersistentToasts';
import { useAddInboxFlow } from '@core/email-link';
+import { reconnectScopes } from '@core/email-link/consent';
import {
useEmailLinksQuery,
useInboxHealthProbeQuery,
@@ -25,9 +26,12 @@ export function GmailReauthenticationPrompt() {
(linksQuery.data?.links ?? []).filter((link) => link.needs_reauth),
key: (link) => link.id,
toast: (link, dismiss) => ({
- title: 'Reconnect Gmail',
+ title:
+ reconnectScopes(link) === 'gmail_and_calendar'
+ ? 'Reconnect email and calendar'
+ : 'Reconnect Gmail',
content(): string {
- return `Sync stopped for ${link.email_address}. Reconnect to restore email sync.`;
+ return `Sync stopped for ${link.email_address}. Reconnect to restore ${reconnectScopes(link) === 'gmail_and_calendar' ? 'email and calendar' : 'email'} sync.`;
},
actions: [
{
@@ -36,7 +40,10 @@ export function GmailReauthenticationPrompt() {
// Suppress re-prompting until the inbox recovers; on native the page
// stays mounted while the OAuth flow runs.
dismiss();
- startAddInbox();
+ void startAddInbox({
+ scopes: reconnectScopes(link),
+ emailAddress: link.email_address,
+ });
},
},
],
diff --git a/apps/web/src/features/calendar-view/components/Page.tsx b/apps/web/src/features/calendar-view/components/Page.tsx
index 522cd3c5dd..de623d6e89 100644
--- a/apps/web/src/features/calendar-view/components/Page.tsx
+++ b/apps/web/src/features/calendar-view/components/Page.tsx
@@ -35,7 +35,6 @@ import { toast } from '@core/component/Toast/Toast';
import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';
import { isMobile } from '@core/mobile/isMobile';
import type { DateSelectArg, DatesSetArg } from '@fullcalendar/core';
-import SpinnerIcon from '@phosphor/spinner-gap.svg';
import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
import { useUpdateCalendarEventMutation } from '@queries/calendar/mutations';
import {
@@ -149,14 +148,6 @@ function CalendarPageDataStatus(props: {
!props.data.occurrencesQuery.isError &&
(props.changingView || props.data.isLoading());
- const showBlockingState = () => {
- if (isRangeUnavailable()) return false;
- if (props.data.occurrencesQuery.isError) return true;
- if (showLoading()) return false;
-
- return props.data.isSyncing() && props.data.events().length === 0;
- };
-
return (
<>
<CalendarLoadingSkeleton
@@ -166,52 +157,27 @@ function CalendarPageDataStatus(props: {
disabled={isRangeUnavailable() || props.data.occurrencesQuery.isError}
onBlockingChange={props.onLoadingBlockingChange}
/>
- <Show when={showBlockingState()}>
+ <Show when={!isRangeUnavailable() && props.data.occurrencesQuery.isError}>
<div
class="absolute inset-0 z-20 flex items-center justify-center rounded-xl bg-surface/90 p-6 text-center"
aria-live="polite"
>
- <Show
- when={!props.data.occurrencesQuery.isError}
- fallback={
- <div class="flex max-w-sm flex-col items-center gap-3">
- <div class="text-sm font-semibold text-ink">
- Calendar unavailable
- </div>
- <p class="text-xs text-ink-muted">
- We couldn’t load your calendar events. Try again.
- </p>
- <Button
- variant="accent"
- size="sm"
- label="Retry loading calendar"
- onClick={() => void props.data.occurrencesQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- }
- >
- <div class="flex items-center gap-2 text-xs text-ink-muted">
- <SpinnerIcon class="size-4 animate-spin" />
- <span>Syncing calendar…</span>
+ <div class="flex max-w-sm flex-col items-center gap-3">
+ <div class="text-sm font-semibold text-ink">
+ Calendar unavailable
</div>
- </Show>
- </div>
- </Show>
-
- <Show
- when={
- !isRangeUnavailable() &&
- !showLoading() &&
- !showBlockingState() &&
- props.data.isSyncing() &&
- props.data.events().length > 0
- }
- >
- <div class="absolute right-2 bottom-2 z-10 flex items-center gap-1.5 rounded-full border border-edge-muted bg-surface px-2.5 py-1 text-xs text-ink-muted shadow-menu">
- <SpinnerIcon class="size-3 animate-spin" />
- Syncing
+ <p class="text-xs text-ink-muted">
+ We couldn’t load your calendar events. Try again.
+ </p>
+ <Button
+ variant="accent"
+ size="sm"
+ label="Retry loading calendar"
+ onClick={() => void props.data.occurrencesQuery.refetch()}
+ >
+ Retry
+ </Button>
+ </div>
</div>
</Show>
</>
diff --git a/apps/web/src/features/calendar-view/components/SetupStatus.tsx b/apps/web/src/features/calendar-view/components/SetupStatus.tsx
index 01f37abe5e..12affdc597 100644
--- a/apps/web/src/features/calendar-view/components/SetupStatus.tsx
+++ b/apps/web/src/features/calendar-view/components/SetupStatus.tsx
@@ -85,7 +85,13 @@ export function SetupStatus() {
// alone. Connecting and reconnecting need the mailbox scopes alongside it.
const startSetup = () => {
const state = setupState();
+ const links = linksQuery.isSuccess ? linksQuery.data.links : [];
+ const link =
+ state === 'reauth'
+ ? links.find((link) => link.needs_reauth)
+ : links.find((link) => link.needs_calendar_permission);
void startAddInbox({
+ emailAddress: link?.email_address,
scopes:
state === 'permission' || state === 'disabled'
? 'calendar'
diff --git a/apps/web/src/features/calendar-view/components/SyncStatus.tsx b/apps/web/src/features/calendar-view/components/SyncStatus.tsx
new file mode 100644
index 0000000000..1518118de8
--- /dev/null
+++ b/apps/web/src/features/calendar-view/components/SyncStatus.tsx
@@ -0,0 +1,25 @@
+import SpinnerIcon from '@phosphor/spinner-gap.svg';
+import { Show } from 'solid-js';
+
+/** Keep backfill progress visible while events arrive and the grid is usable. */
+export function SyncStatus(props: { syncing: boolean }) {
+ return (
+ <Show when={props.syncing}>
+ <div
+ role="status"
+ class="flex shrink-0 items-center gap-3 border-b border-edge-muted bg-surface px-4 py-3"
+ >
+ <SpinnerIcon class="size-4 shrink-0 animate-spin motion-reduce:animate-none text-accent" />
+ <div class="flex min-w-0 flex-col gap-0.5">
+ <span class="text-sm font-medium text-ink">
+ Syncing your calendar…
+ </span>
+ <span class="text-xs text-ink-muted">
+ Events are still being imported from Google. They’ll appear
+ automatically. You can keep using Macro.
+ </span>
+ </div>
+ </div>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/calendar-view/components/Workspace.tsx b/apps/web/src/features/calendar-view/components/Workspace.tsx
index 7d6e908d01..feb3701024 100644
--- a/apps/web/src/features/calendar-view/components/Workspace.tsx
+++ b/apps/web/src/features/calendar-view/components/Workspace.tsx
@@ -35,6 +35,7 @@ import { Header } from './Header';
import { Page } from './Page';
import { SelectedEventDetails } from './SelectedEventDetails';
import { SetupStatus } from './SetupStatus';
+import { SyncStatus } from './SyncStatus';
const CALENDAR_SWIPE_EDGE_INSET = 40;
@@ -73,6 +74,9 @@ function CalendarPages() {
return (
<Layer depth={2}>
<div class="flex min-w-0 min-h-0 flex-1 flex-col">
+ <SyncStatus
+ syncing={calendarPager.activeData()?.isSyncing() ?? false}
+ />
<RangeUnavailableBanner
class={isMobile() ? 'order-last' : undefined}
fullWidth={isMobile()}
diff --git a/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx b/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx
index 60dade536d..54ce8cb186 100644
--- a/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx
+++ b/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx
@@ -111,7 +111,16 @@ function createCalendarSettingsControls(isNarrow: () => boolean) {
calendarView.closeEventDetails();
match(account.action)
.with('enable', () => {
- startAddInbox({ scopes: 'calendar' });
+ void startAddInbox({
+ scopes: account.consentScopes,
+ emailAddress: account.emailAddress,
+ });
+ })
+ .with('reconnect', () => {
+ void startAddInbox({
+ scopes: account.consentScopes,
+ emailAddress: account.emailAddress,
+ });
})
.with('turnOff', () => {
setTurnOffTarget({
@@ -294,11 +303,15 @@ function DesktopCalendarSettings(props: {
<span
class="shrink-0 text-xs font-medium"
classList={{
- 'text-accent': account.action === 'enable',
+ 'text-accent': account.action !== 'turnOff',
'text-failure': account.action === 'turnOff',
}}
>
- {account.action === 'enable' ? 'Enable' : 'Turn off'}
+ {match(account.action)
+ .with('enable', () => 'Enable')
+ .with('reconnect', () => 'Reconnect')
+ .with('turnOff', () => 'Turn off')
+ .exhaustive()}
</span>
</Dropdown.Item>
)}
@@ -488,11 +501,15 @@ function MobileCalendarSettings(props: {
<span
class="shrink-0 text-xs font-medium"
classList={{
- 'text-accent': account.action === 'enable',
+ 'text-accent': account.action !== 'turnOff',
'text-failure': account.action === 'turnOff',
}}
>
- {account.action === 'enable' ? 'Enable' : 'Turn off'}
+ {match(account.action)
+ .with('enable', () => 'Enable')
+ .with('reconnect', () => 'Reconnect')
+ .with('turnOff', () => 'Turn off')
+ .exhaustive()}
</span>
</MobileDrawer.Item>
)}
diff --git a/apps/web/src/features/calendar/components/TurnOffCalendarDialog.tsx b/apps/web/src/features/calendar/components/TurnOffCalendarDialog.tsx
index a2afaed91a..81d3e93846 100644
--- a/apps/web/src/features/calendar/components/TurnOffCalendarDialog.tsx
+++ b/apps/web/src/features/calendar/components/TurnOffCalendarDialog.tsx
@@ -1,6 +1,7 @@
import { toast } from '@core/component/Toast/Toast';
import { useDisableCalendarMutation } from '@queries/email/link';
import { Button, Dialog, Panel } from '@ui';
+import { Show } from 'solid-js';
/** The inbox a turn-off confirmation is about. */
export interface TurnOffCalendarTarget {
@@ -20,15 +21,17 @@ export function TurnOffCalendarDialog(props: {
onClose: () => void;
}) {
const disableCalendar = useDisableCalendarMutation({
- onSuccess: () => toast.success('Calendar turned off'),
+ onSuccess: () => {
+ toast.success('Calendar turned off');
+ props.onClose();
+ },
onError: () =>
toast.failure('Failed to turn off calendar. Please try again.'),
});
const confirm = () => {
const target = props.target;
- if (!target) return;
- props.onClose();
+ if (!target || disableCalendar.isPending) return;
disableCalendar.mutate(target.linkId);
};
@@ -36,7 +39,7 @@ export function TurnOffCalendarDialog(props: {
<Dialog
open={props.target !== null}
onOpenChange={(open) => {
- if (!open) props.onClose();
+ if (!open && !disableCalendar.isPending) props.onClose();
}}
position="center"
class="w-120"
@@ -55,12 +58,27 @@ export function TurnOffCalendarDialog(props: {
Google Calendar is untouched and email keeps syncing, but turning
calendar back on means granting access again.
</Dialog.Description>
+ <Show when={disableCalendar.isPending}>
+ <p role="status" class="text-sm text-ink-muted">
+ Turning off calendar and removing synced events…
+ </p>
+ </Show>
<div class="pt-3 justify-end items-center gap-3 inline-flex">
- <Button variant="ghost" depth={3} onClick={props.onClose}>
+ <Button
+ variant="ghost"
+ depth={3}
+ onClick={props.onClose}
+ disabled={disableCalendar.isPending}
+ >
Cancel
</Button>
- <Button variant="strong" depth={3} onClick={confirm}>
- Turn off
+ <Button
+ variant="strong"
+ depth={3}
+ onClick={confirm}
+ disabled={disableCalendar.isPending}
+ >
+ {disableCalendar.isPending ? 'Turning off…' : 'Turn off'}
</Button>
</div>
</Panel.Body>
diff --git a/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx b/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx
index cd8c14fa09..f08ea8d644 100644
--- a/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx
+++ b/apps/web/src/features/calendar/components/composer/EventPropertyPills.tsx
@@ -622,7 +622,7 @@ export function EventComposerRecurrencePill(
export interface EventComposerCalendarPillProps {
options: EventEditorCalendarOption[];
- value: EventEditorCalendarOption;
+ value: EventEditorCalendarOption | undefined;
onChange: (calendarId: string) => void;
disabled?: boolean;
readOnly?: boolean;
@@ -634,6 +634,7 @@ export function EventComposerCalendarPill(
) {
return (
<Select<EventEditorCalendarOption>
+ placeholder="Choose calendar"
options={props.options}
value={props.value}
onChange={(option) => {
diff --git a/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.test.ts b/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.test.ts
index 1068106e6c..9db7192256 100644
--- a/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.test.ts
+++ b/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.test.ts
@@ -1,5 +1,5 @@
import { format } from 'date-fns';
-import { createRoot } from 'solid-js';
+import { createRoot, createSignal } from 'solid-js';
import { afterEach, describe, expect, it } from 'vitest';
import {
type CreateCalendarEventFormControllerOptions,
@@ -45,7 +45,10 @@ afterEach(() => {
function controllerFor(
initialValue: Partial<EventEditorInitialValues>,
options?: Partial<
- Pick<CreateCalendarEventFormControllerOptions, 'isEdit' | 'calendarOptions'>
+ Pick<
+ CreateCalendarEventFormControllerOptions,
+ 'isEdit' | 'calendarOptions' | 'defaultCalendarId'
+ >
>
) {
return createRoot((dispose) => {
@@ -64,6 +67,48 @@ function controllerFor(
});
}
+describe('calendar account selection', () => {
+ it('waits for the primary account instead of silently using another inbox', () => {
+ const [primary, setPrimary] = createSignal<string>();
+ const controller = controllerFor(
+ { title: 'Customer demo', ...timedRange(24) },
+ { defaultCalendarId: primary }
+ );
+ expect(controller.effectiveCalendarId()).toBeUndefined();
+ expect(controller.selectedCalendarOption()).toBeUndefined();
+ expect(controller.canSave()).toBe(false);
+ expect(controller.submitValues()).toBeUndefined();
+ setPrimary('calendar-1');
+ expect(controller.canSave()).toBe(true);
+ expect(controller.submitValues()?.calendarId).toBe('calendar-1');
+ });
+
+ it('allows an explicitly selected alternate calendar while primary is unavailable', () => {
+ const controller = controllerFor(
+ { title: 'Customer demo', ...timedRange(24) },
+ { defaultCalendarId: () => undefined }
+ );
+ controller.setField('calendarId', 'calendar-1');
+ expect(controller.canSave()).toBe(true);
+ expect(controller.submitValues()?.calendarId).toBe('calendar-1');
+ });
+
+ it('does not switch to another account when the proposed calendar disappears', () => {
+ const controller = controllerFor(
+ {
+ title: 'Customer demo',
+ ...timedRange(24),
+ calendarId: 'missing-work-calendar',
+ },
+ { defaultCalendarId: () => 'calendar-1' }
+ );
+ expect(controller.effectiveCalendarId()).toBe('missing-work-calendar');
+ expect(controller.selectedCalendarOption()).toBeUndefined();
+ expect(controller.canSave()).toBe(false);
+ expect(controller.submitValues()).toBeUndefined();
+ });
+});
+
describe('recurrence submission', () => {
const originalRule =
'RRULE:FREQ=WEEKLY;WKST=SU;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR';
diff --git a/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.ts b/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.ts
index 8453ce9388..fa4418acf1 100644
--- a/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.ts
+++ b/apps/web/src/features/calendar/components/composer/create-calendar-event-form-controller.ts
@@ -105,6 +105,8 @@ export interface CreateCalendarEventFormControllerOptions {
/** Editing a saved event, whose initial guests already hold an invitation. */
isEdit?: boolean;
calendarOptions: Accessor<EventEditorCalendarOption[]>;
+ /** Override the default account; undefined means wait for it or choose explicitly. */
+ defaultCalendarId?: Accessor<string | undefined>;
guestOptions: Accessor<EventEditorGuestOption[]>;
recurrenceTimeZone?: string;
onChange?: (value: EventEditorInitialValues) => void;
@@ -174,25 +176,27 @@ export function createCalendarEventFormController(
const availableCalendarOptions = () =>
restrictsCalendars() ? primaryCalendarOptions() : options.calendarOptions();
+ const defaultCalendarId = () =>
+ options.defaultCalendarId
+ ? options.defaultCalendarId()
+ : availableCalendarOptions()[0]?.id;
const effectiveCalendarId = () => {
const chosen = state().calendarId;
if (!restrictsCalendars()) {
- return chosen ?? options.calendarOptions()[0]?.id;
+ return chosen ?? defaultCalendarId();
}
// The restriction also steers a selection made before it applied.
const available = availableCalendarOptions();
return (
- available.find((option) => option.id === chosen)?.id ?? available[0]?.id
+ available.find((option) => option.id === chosen)?.id ??
+ defaultCalendarId()
);
};
const calendarOptionFor = (calendarId: string | undefined) =>
options
.calendarOptions()
- .find(
- (option) =>
- option.id === (calendarId ?? options.calendarOptions()[0]?.id)
- ) ?? options.calendarOptions()[0];
+ .find((option) => option.id === (calendarId ?? defaultCalendarId()));
const selectedCalendarOption = () => calendarOptionFor(effectiveCalendarId());
@@ -304,7 +308,7 @@ export function createCalendarEventFormController(
start: initialValue().start,
end: initialValue().end,
recurrenceLines: initialValue().recurrenceLines,
- calendarId: initialValue().calendarId ?? options.calendarOptions()[0]?.id,
+ calendarId: initialValue().calendarId ?? defaultCalendarId(),
guestEmails: blanks ? [] : initialGuestEmails(),
location: blanks ? '' : initialValue().location,
description: blanks ? '' : initialValue().description,
@@ -447,9 +451,16 @@ export function createCalendarEventFormController(
};
};
+ const canSave = () =>
+ recurrence.canSave() &&
+ (!options.defaultCalendarId ||
+ availableCalendarOptions().some(
+ (option) => option.id === effectiveCalendarId()
+ ));
+
const submitValues = (): EventEditorSubmitValues | undefined => {
const time = recurrence.eventTime();
- if (!time || !recurrence.canSave()) return undefined;
+ if (!time || !canSave()) return undefined;
const current = state();
const reminders = reminderUpdate();
const outOfOffice = submittedOutOfOffice();
@@ -531,7 +542,7 @@ export function createCalendarEventFormController(
dateRangeError: recurrence.dateRangeError,
pastEventWarning,
eventTime: recurrence.eventTime,
- canSave: recurrence.canSave,
+ canSave,
snapshot,
isDirty,
submitValues,
diff --git a/apps/web/src/features/calendar/hooks/use-calendar-accounts.test.ts b/apps/web/src/features/calendar/hooks/use-calendar-accounts.test.ts
index 71ac5461d6..dfa54fd8ca 100644
--- a/apps/web/src/features/calendar/hooks/use-calendar-accounts.test.ts
+++ b/apps/web/src/features/calendar/hooks/use-calendar-accounts.test.ts
@@ -15,16 +15,35 @@ const link = (id: string, overrides: Partial<EmailLink> = {}): EmailLink =>
}) as unknown as EmailLink;
describe('toCalendarAccounts', () => {
+ it('offers reconnect when an expired Google grant still has stored calendar scopes', () => {
+ expect(
+ toCalendarAccounts([link('a', { needs_reauth: true })], 'macro|self')[0]
+ ).toMatchObject({
+ action: 'reconnect',
+ consentScopes: 'gmail_and_calendar',
+ });
+ });
+
it('offers turn-off for an inbox that already has calendar', () => {
expect(toCalendarAccounts([link('a')], 'macro|self')).toEqual([
- { linkId: 'a', emailAddress: '[email protected]', action: 'turnOff' },
+ {
+ linkId: 'a',
+ emailAddress: '[email protected]',
+ action: 'turnOff',
+ consentScopes: 'calendar',
+ },
]);
});
it('offers enable for an inbox missing calendar permission', () => {
const links = [link('a', { needs_calendar_permission: true })];
expect(toCalendarAccounts(links, 'macro|self')).toEqual([
- { linkId: 'a', emailAddress: '[email protected]', action: 'enable' },
+ {
+ linkId: 'a',
+ emailAddress: '[email protected]',
+ action: 'enable',
+ consentScopes: 'calendar',
+ },
]);
});
@@ -35,6 +54,23 @@ describe('toCalendarAccounts', () => {
expect(toCalendarAccounts(links, 'macro|self')[0]?.action).toBe('enable');
});
+ it.each([false, true])(
+ 'explicitly enables calendar when a revoked inbox has calendar_disabled=%s',
+ (disabled) => {
+ const links = [
+ link('a', {
+ needs_reauth: true,
+ needs_calendar_permission: true,
+ calendar_disabled: disabled,
+ }),
+ ];
+ expect(toCalendarAccounts(links, 'macro|self')[0]).toMatchObject({
+ action: 'enable',
+ consentScopes: 'gmail_and_calendar',
+ });
+ }
+ );
+
it('offers enable — not turn-off — for a legacy inbox with stale data', () => {
const links = [
link('a', { needs_calendar_permission: true, has_calendar_data: true }),
@@ -56,7 +92,12 @@ describe('toCalendarAccounts', () => {
it('drops delegated inboxes the viewer does not own', () => {
const links = [link('own'), link('shared', { macro_id: 'macro|other' })];
expect(toCalendarAccounts(links, 'macro|self')).toEqual([
- { linkId: 'own', emailAddress: '[email protected]', action: 'turnOff' },
+ {
+ linkId: 'own',
+ emailAddress: '[email protected]',
+ action: 'turnOff',
+ consentScopes: 'calendar',
+ },
]);
});
diff --git a/apps/web/src/features/calendar/hooks/use-calendar-accounts.ts b/apps/web/src/features/calendar/hooks/use-calendar-accounts.ts
index 948cc18a8f..c87cea0960 100644
--- a/apps/web/src/features/calendar/hooks/use-calendar-accounts.ts
+++ b/apps/web/src/features/calendar/hooks/use-calendar-accounts.ts
@@ -1,25 +1,29 @@
import { useUserId } from '@core/context/user';
+import { calendarConsentScopes } from '@core/email-link/consent';
import { useEmailLinksQuery } from '@queries/email/link';
+import type { ConsentScopes } from '@service-auth/client';
import type { Link as EmailLink } from '@service-email/generated/schemas';
import { createMemo } from 'solid-js';
/** The one calendar action a connected account offers from the calendar view. */
-type CalendarAccountAction = 'enable' | 'turnOff';
+type CalendarAccountAction = 'enable' | 'reconnect' | 'turnOff';
/** A viewer-owned inbox rendered as a manageable calendar account. */
export interface CalendarAccount {
linkId: string;
emailAddress: string;
action: CalendarAccountAction;
+ consentScopes: ConsentScopes;
}
/**
* Classifies the viewer's own inboxes into one calendar action each. An inbox
- * whose Google grant is missing calendar access — never granted, declined, or
- * turned off — offers `enable`; one that already has it offers `turnOff`. A
- * legacy inbox that still has data but no longer satisfies the capability check
- * also reads as `enable`: re-granting resumes it, and removing the stale data
- * stays available from connection settings.
+ * whose enabled calendar grant has expired offers `reconnect`. Missing calendar
+ * access — never granted, declined, or turned off — offers `enable`, including
+ * when the mailbox also needs reconnection; one that already
+ * has it offers `turnOff`. A legacy inbox that still has data but no longer
+ * satisfies the capability check also reads as `enable`: re-granting resumes
+ * it, and removing the stale data stays available from connection settings.
*
* Delegated inboxes are dropped: the viewer reads the owner's calendar but must
* not enable or delete the owner's calendar from here. The viewer's primary
@@ -35,7 +39,12 @@ export function toCalendarAccounts(
.map((link) => ({
linkId: link.id,
emailAddress: link.email_address,
- action: link.needs_calendar_permission ? 'enable' : 'turnOff',
+ consentScopes: calendarConsentScopes(link),
+ action: link.needs_calendar_permission
+ ? 'enable'
+ : link.needs_reauth
+ ? 'reconnect'
+ : 'turnOff',
}));
}
diff --git a/apps/web/src/features/settings/Email.tsx b/apps/web/src/features/settings/Email.tsx
index 04a59300fa..d6c9f77e1f 100644
--- a/apps/web/src/features/settings/Email.tsx
+++ b/apps/web/src/features/settings/Email.tsx
@@ -18,6 +18,10 @@ import {
useEmailLinks,
useEmailLinksStatus,
} from '@core/email-link';
+import {
+ calendarConsentScopes,
+ reconnectScopes,
+} from '@core/email-link/consent';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import GmailIcon from '@icon/mcp-gmail.svg';
import ArrowsClockwiseIcon from '@phosphor-icons/core/regular/arrows-clockwise.svg?component-solid';
@@ -183,9 +187,17 @@ export function EmailCard() {
hasCompletedBackfill={hasCompletedBackfill(primary().id)}
resyncing={resyncingIds().has(primary().id)}
onResync={() => handleResyncInbox(primary().id)}
- onReconnect={() => void startAddInbox()}
+ onReconnect={() =>
+ void startAddInbox({
+ scopes: reconnectScopes(primary()),
+ emailAddress: primary().email_address,
+ })
+ }
onEnableCalendar={() =>
- void startAddInbox({ scopes: 'calendar' })
+ void startAddInbox({
+ scopes: calendarConsentScopes(primary()),
+ emailAddress: primary().email_address,
+ })
}
onRemove={() =>
setRemoveTarget({
@@ -218,9 +230,17 @@ export function EmailCard() {
hasCompletedBackfill={hasCompletedBackfill(link.id)}
resyncing={resyncingIds().has(link.id)}
onResync={() => handleResyncInbox(link.id)}
- onReconnect={() => void startAddInbox()}
+ onReconnect={() =>
+ void startAddInbox({
+ scopes: reconnectScopes(link),
+ emailAddress: link.email_address,
+ })
+ }
onEnableCalendar={() =>
- void startAddInbox({ scopes: 'calendar' })
+ void startAddInbox({
+ scopes: calendarConsentScopes(link),
+ emailAddress: link.email_address,
+ })
}
onRemove={() =>
setRemoveTarget({
@@ -513,12 +533,7 @@ function InboxRow(props: {
</Button>
</Tooltip>
</Show>
- <Show
- when={
- ENABLE_INBOX_SYNC_STATUS &&
- props.link.sync_status === SyncStatus.NEEDS_REAUTH
- }
- >
+ <Show when={props.link.needs_reauth}>
<Button
variant="accent"
size="sm"
@@ -529,10 +544,8 @@ function InboxRow(props: {
Reconnect
</Button>
</Show>
- {/* 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. */}
+ {/* Explicitly enabling calendar also restores mailbox access when
+ the Google grant has expired. */}
<Show
when={calendarUiEnabled() && props.link.needs_calendar_permission}
>
diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsx
new file mode 100644
index 0000000000..0522706eb7
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsx
@@ -0,0 +1,246 @@
+import type { EventFormProps } from '@app/features/calendar/components/composer/EventForm';
+import type { VisibleCalendar } from '@queries/calendar/calendars';
+import type { CreateCalendarEvent } from '@service-cognition/generated/tools/types';
+import type { Link } from '@service-email/generated/schemas';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { For, type JSX } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ calendars: [] as VisibleCalendar[],
+ links: [] as Link[],
+ calendarError: false,
+ linksError: false,
+ refetchCalendars: vi.fn(),
+ refetchLinks: vi.fn(),
+ startAddInbox: vi.fn(),
+ execute: vi.fn(),
+}));
+vi.mock('@queries/calendar/calendars', () => ({
+ useVisibleCalendarsQuery: () => ({
+ isSuccess: !mocks.calendarError,
+ isError: mocks.calendarError,
+ data: mocks.calendars,
+ refetch: mocks.refetchCalendars,
+ }),
+}));
+vi.mock('@queries/email/link', () => ({
+ useEmailLinksQuery: () => ({
+ isSuccess: !mocks.linksError,
+ isError: mocks.linksError,
+ data: { links: mocks.links },
+ refetch: mocks.refetchLinks,
+ }),
+}));
+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'macro|self' }));
+vi.mock('@core/email-link', () => ({
+ useAddInboxFlow: () => mocks.startAddInbox,
+}));
+vi.mock('@core/user', () => ({
+ useContacts: () => () => [],
+ recipientEntityMapper: () => (value: unknown) => value,
+}));
+vi.mock('@ui', () => ({
+ Layer: (props: { children: JSX.Element }) => props.children,
+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props} />
+ ),
+}));
+vi.mock('./EventPreview', () => ({ CalendarToolEventPreview: () => null }));
+vi.mock('@app/features/calendar/components/composer/EventForm', () => ({
+ EventForm: (props: EventFormProps) => (
+ <>
+ <select
+ aria-label="Calendar"
+ value={props.controller.effectiveCalendarId() ?? ''}
+ onChange={(event) =>
+ props.controller.setField('calendarId', event.currentTarget.value)
+ }
+ >
+ <option value="">Choose calendar</option>
+ <For each={props.controller.calendarOptions()}>
+ {(option) => <option value={option.id}>{option.label}</option>}
+ </For>
+ </select>
+ <button
+ disabled={
+ !props.controller.canSave() || props.disabled || props.pending
+ }
+ onClick={() => {
+ const values = props.controller.submitValues();
+ if (values) props.onSubmit(values);
+ }}
+ >
+ Create event
+ </button>
+ </>
+ ),
+}));
+
+import { CalendarDraftComposer } from './DraftComposer';
+
+const link = (id: string, overrides: Partial<Link> = {}): Link =>
+ ({
+ id,
+ macro_id: 'macro|self',
+ email_address: `${id}@example.com`,
+ is_primary: id === 'work',
+ needs_reauth: false,
+ needs_calendar_permission: false,
+ calendar_disabled: false,
+ ...overrides,
+ }) as Link;
+const calendar = (id: string): VisibleCalendar => ({
+ id: `${id}-calendar`,
+ emailLinkId: id,
+ emailAddress: `${id}@example.com`,
+ name: id,
+ isPrimary: true,
+ isWritable: true,
+ isSubscription: false,
+ defaultReminders: [],
+});
+
+function showDraft(calendarId?: string) {
+ const draft = {
+ title: 'Customer demo',
+ calendarId,
+ time: {
+ kind: 'timed',
+ startsAt: '2030-01-01T12:00:00Z',
+ endsAt: '2030-01-01T13:00:00Z',
+ },
+ } as CreateCalendarEvent;
+ return render(() => (
+ <CalendarDraftComposer
+ initialData={draft}
+ previewKey="test"
+ showPreview={false}
+ sink={{
+ canAct: () => true,
+ lockedNotice: () => undefined,
+ onExecute: mocks.execute,
+ onReject: async () => true,
+ }}
+ />
+ ));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.execute.mockResolvedValue(true);
+ mocks.startAddInbox.mockResolvedValue(undefined);
+ mocks.calendarError = false;
+ mocks.linksError = false;
+ mocks.links = [link('personal'), link('work')];
+ mocks.calendars = [calendar('personal'), calendar('work')];
+});
+afterEach(cleanup);
+
+describe('AI calendar draft account selection', () => {
+ it.each([
+ { calendarError: true, linksError: false },
+ { calendarError: false, linksError: true },
+ { calendarError: true, linksError: true },
+ ])(
+ 'offers retry instead of consent for failed queries: %j',
+ async (errors) => {
+ Object.assign(mocks, errors);
+ showDraft();
+ expect(screen.getByText('Could not load your calendars.')).not.toBeNull();
+ expect(screen.queryByText(/Wait for it to sync/)).toBeNull();
+ expect(
+ screen.queryByRole('button', {
+ name: /Connect calendar|Reconnect calendar/,
+ })
+ ).toBeNull();
+ expect(
+ screen.getByRole('button', { name: 'Create event' })
+ ).toHaveProperty('disabled', true);
+ await fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
+ expect(mocks.refetchCalendars).toHaveBeenCalledTimes(
+ Number(errors.calendarError)
+ );
+ expect(mocks.refetchLinks).toHaveBeenCalledTimes(
+ Number(errors.linksError)
+ );
+ expect(mocks.startAddInbox).not.toHaveBeenCalled();
+ }
+ );
+
+ it('defaults to the primary inbox even when a personal calendar is listed first', async () => {
+ showDraft();
+ await fireEvent.click(screen.getByRole('button', { name: 'Create event' }));
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ calendarId: 'work-calendar' })
+ );
+ });
+
+ it('requires a choice while the primary calendar is backfilling', async () => {
+ mocks.calendars = [calendar('personal')];
+ showDraft();
+ const submit = screen.getByRole('button', { name: 'Create event' });
+ expect(submit).toHaveProperty('disabled', true);
+ expect(screen.getByText(/Wait for it to sync/)).not.toBeNull();
+ await fireEvent.change(screen.getByRole('combobox'), {
+ target: { value: 'personal-calendar' },
+ });
+ expect(submit).toHaveProperty('disabled', false);
+ await fireEvent.click(submit);
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ calendarId: 'personal-calendar' })
+ );
+ });
+
+ it('rejects a cached writable calendar whose Google grant expired and reconnects the right account', async () => {
+ mocks.links = [link('personal'), link('work', { needs_reauth: true })];
+ showDraft('work-calendar');
+ expect(screen.getByRole('button', { name: 'Create event' })).toHaveProperty(
+ 'disabled',
+ true
+ );
+ expect(screen.queryByRole('option', { name: 'work' })).toBeNull();
+ await fireEvent.click(
+ screen.getByRole('button', { name: 'Reconnect calendar' })
+ );
+ expect(mocks.startAddInbox).toHaveBeenCalledExactlyOnceWith({
+ scopes: 'gmail_and_calendar',
+ emailAddress: '[email protected]',
+ });
+ expect(mocks.execute).not.toHaveBeenCalled();
+ });
+
+ it('does not replace a deleted requested calendar with the primary calendar', () => {
+ showDraft('deleted-calendar');
+ expect(screen.getByRole('button', { name: 'Create event' })).toHaveProperty(
+ 'disabled',
+ true
+ );
+ expect(
+ screen.getByText(/requested calendar is unavailable/)
+ ).not.toBeNull();
+ expect(
+ screen.getByRole('button', { name: 'Connect calendar' })
+ ).not.toBeNull();
+ });
+
+ it.each([false, true])(
+ 'does not reconnect the primary inbox for a removed calendar account (primary expired: %s)',
+ async (needsReauth) => {
+ mocks.links = [link('work', { needs_reauth: needsReauth })];
+ showDraft('personal-calendar');
+ expect(
+ screen.getByRole('button', { name: 'Create event' })
+ ).toHaveProperty('disabled', true);
+ expect(
+ screen.queryByRole('button', { name: 'Reconnect calendar' })
+ ).toBeNull();
+ await fireEvent.click(
+ screen.getByRole('button', { name: 'Connect calendar' })
+ );
+ expect(mocks.startAddInbox).toHaveBeenCalledExactlyOnceWith({
+ scopes: 'gmail_and_calendar',
+ });
+ }
+ );
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx
index 2d10965e08..abcb059537 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx
@@ -16,10 +16,14 @@ import {
calendarDisplayLabel,
spansMultipleInboxes,
} from '@app/features/calendar/utils/calendar-label';
+import { useUserId } from '@core/context/user';
+import { useAddInboxFlow } from '@core/email-link';
+import { calendarConsentScopes } from '@core/email-link/consent';
import { recipientEntityMapper, useContacts } from '@core/user';
import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
+import { useEmailLinksQuery } from '@queries/email/link';
import type { CreateCalendarEvent } from '@service-cognition/generated/tools/types';
-import { Layer } from '@ui';
+import { Button, Layer } from '@ui';
import {
createMemo,
createSignal,
@@ -85,6 +89,32 @@ function CalendarDraftComposerFallback() {
function CalendarDraftComposerContent(props: CalendarDraftComposerProps) {
const calendarsQuery = useVisibleCalendarsQuery();
+ const linksQuery = useEmailLinksQuery();
+ const userId = useUserId();
+ const startAddInbox = useAddInboxFlow();
+ const calendars = () => (calendarsQuery.isSuccess ? calendarsQuery.data : []);
+ const links = () => (linksQuery.isSuccess ? linksQuery.data.links : []);
+ const loadingCalendars = () =>
+ calendarsQuery.isPending || linksQuery.isPending;
+ const calendarLoadFailed = () => calendarsQuery.isError || linksQuery.isError;
+ const retryCalendarData = () => {
+ if (calendarsQuery.isError) void calendarsQuery.refetch();
+ if (linksQuery.isError) void linksQuery.refetch();
+ };
+ const primaryInbox = () =>
+ links().find((link) => link.macro_id === userId() && link.is_primary);
+ const primaryNeedsAccess = () =>
+ primaryInbox()?.needs_reauth || primaryInbox()?.needs_calendar_permission;
+ const requestedInbox = () => {
+ if (!props.initialData.calendarId) return primaryInbox();
+ const calendar = calendars().find(
+ (calendar) => calendar.id === props.initialData.calendarId
+ );
+ return links().find((link) => link.id === calendar?.emailLinkId);
+ };
+ const requestedNeedsAccess = () =>
+ requestedInbox()?.needs_reauth ||
+ requestedInbox()?.needs_calendar_permission;
const contacts = useContacts();
const [operation, setOperation] = createSignal<'create' | 'reject'>();
let finalized = false;
@@ -95,8 +125,16 @@ function CalendarDraftComposerContent(props: CalendarDraftComposerProps) {
const guestOptions = createMemo(() =>
contacts().map(recipientEntityMapper('user'))
);
- const writableCalendars = createMemo(
- () => calendarsQuery.data?.filter((calendar) => calendar.isWritable) ?? []
+ const writableCalendars = createMemo(() =>
+ calendars().filter((calendar) => {
+ const link = links().find((link) => link.id === calendar.emailLinkId);
+ return (
+ calendar.isWritable &&
+ link &&
+ !link.needs_reauth &&
+ !link.needs_calendar_permission
+ );
+ })
);
const calendarsSpanInboxes = () => spansMultipleInboxes(writableCalendars());
const calendarOptions = createMemo(() =>
@@ -112,6 +150,13 @@ function CalendarDraftComposerContent(props: CalendarDraftComposerProps) {
const controller = createCalendarEventFormController({
initialValue: createCalendarEventToEditorInitialValues(props.initialData),
calendarOptions,
+ defaultCalendarId: () =>
+ primaryNeedsAccess()
+ ? undefined
+ : writableCalendars().find(
+ (calendar) =>
+ calendar.emailLinkId === primaryInbox()?.id && calendar.isPrimary
+ )?.id,
guestOptions,
recurrenceTimeZone:
props.initialData.time.kind === 'timed'
@@ -162,6 +207,67 @@ function CalendarDraftComposerContent(props: CalendarDraftComposerProps) {
<p class="text-xs text-ink-extra-muted/60">{notice()}</p>
)}
</Show>
+ <Show when={!controller.selectedCalendarOption()}>
+ <div
+ role="status"
+ class="flex flex-wrap items-center gap-2 text-sm text-ink-muted"
+ >
+ <Show
+ when={!calendarLoadFailed()}
+ fallback={
+ <>
+ <span>Could not load your calendars.</span>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={retryCalendarData}
+ >
+ Try again
+ </Button>
+ </>
+ }
+ >
+ <Show
+ when={!loadingCalendars()}
+ fallback="Loading your calendars…"
+ >
+ <span>
+ The requested calendar is unavailable.{' '}
+ {requestedNeedsAccess()
+ ? 'Reconnect it or choose another calendar.'
+ : 'Wait for it to sync or choose another calendar.'}
+ </span>
+ <Show when={requestedNeedsAccess() && requestedInbox()}>
+ {(link) => (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ void startAddInbox({
+ scopes: calendarConsentScopes(link()),
+ emailAddress: link().email_address,
+ })
+ }
+ >
+ Reconnect calendar
+ </Button>
+ )}
+ </Show>
+ <Show when={!requestedInbox()}>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ void startAddInbox({ scopes: 'gmail_and_calendar' })
+ }
+ >
+ Connect calendar
+ </Button>
+ </Show>
+ </Show>
+ </Show>
+ </div>
+ </Show>
<EventForm
controller={controller}
macroCallsEnabled={false}
diff --git a/apps/web/src/lib/core/email-link/consent.test.ts b/apps/web/src/lib/core/email-link/consent.test.ts
new file mode 100644
index 0000000000..b57cb2343d
--- /dev/null
+++ b/apps/web/src/lib/core/email-link/consent.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+import {
+ calendarConsentScopes,
+ inboxAuthorizationUrl,
+ reconnectScopes,
+} from './consent';
+
+const connectedCalendar = {
+ needs_reauth: true,
+ needs_calendar_permission: false,
+ calendar_disabled: false,
+ has_calendar_data: true,
+};
+
+describe('Google reconnect consent', () => {
+ it('restores calendar with Gmail after a grant expires', () => {
+ expect(reconnectScopes(connectedCalendar)).toBe('gmail_and_calendar');
+ expect(
+ reconnectScopes({ ...connectedCalendar, needs_calendar_permission: true })
+ ).toBe('gmail_and_calendar');
+ });
+
+ it('does not enable calendar during an email reconnect after an opt-out', () => {
+ expect(
+ reconnectScopes({ ...connectedCalendar, calendar_disabled: true })
+ ).toBe('gmail');
+ });
+
+ it('does not request calendar for an inbox that has never enabled it', () => {
+ expect(
+ reconnectScopes({
+ ...connectedCalendar,
+ needs_calendar_permission: true,
+ has_calendar_data: false,
+ })
+ ).toBe('gmail');
+ });
+
+ it('repairs revoked email access when explicitly enabling calendar', () => {
+ expect(calendarConsentScopes({ needs_reauth: true })).toBe(
+ 'gmail_and_calendar'
+ );
+ expect(calendarConsentScopes({ needs_reauth: false })).toBe('calendar');
+ });
+
+ it('preselects the requested inbox without replacing OAuth state or scopes', () => {
+ const initial =
+ 'https://accounts.google.com/o/oauth2/v2/auth?state=original&scope=calendar';
+ const url = new URL(
+ inboxAuthorizationUrl(initial, '[email protected]')
+ );
+ expect(url.searchParams.get('login_hint')).toBe(
+ );
+ expect(url.searchParams.get('state')).toBe('original');
+ expect(url.searchParams.get('scope')).toBe('calendar');
+ expect(inboxAuthorizationUrl(initial)).toBe(initial);
+ });
+});
diff --git a/apps/web/src/lib/core/email-link/consent.ts b/apps/web/src/lib/core/email-link/consent.ts
new file mode 100644
index 0000000000..e71c482395
--- /dev/null
+++ b/apps/web/src/lib/core/email-link/consent.ts
@@ -0,0 +1,36 @@
+import type { ConsentScopes } from '@service-auth/client';
+import type { Link } from '@service-email/generated/schemas';
+
+type CalendarAccess = Pick<
+ Link,
+ | 'needs_reauth'
+ | 'needs_calendar_permission'
+ | 'calendar_disabled'
+ | 'has_calendar_data'
+>;
+
+/** Repair the capabilities an inbox used before its Google grant expired. */
+export function reconnectScopes(link: CalendarAccess): ConsentScopes {
+ return !link.calendar_disabled &&
+ (!link.needs_calendar_permission || link.has_calendar_data)
+ ? 'gmail_and_calendar'
+ : 'gmail';
+}
+
+/** A revoked mailbox needs email permission as well as calendar permission. */
+export function calendarConsentScopes(
+ link: Pick<Link, 'needs_reauth'>
+): ConsentScopes {
+ return link.needs_reauth ? 'gmail_and_calendar' : 'calendar';
+}
+
+/** Preselect the account named by the reconnect/enable action at Google. */
+export function inboxAuthorizationUrl(
+ url: string,
+ emailAddress?: string
+): string {
+ if (!emailAddress) return url;
+ const authorizationUrl = new URL(url);
+ authorizationUrl.searchParams.set('login_hint', emailAddress);
+ return authorizationUrl.toString();
+}
diff --git a/apps/web/src/lib/core/email-link/index.ts b/apps/web/src/lib/core/email-link/index.ts
index da4a174146..116cdafd65 100644
--- a/apps/web/src/lib/core/email-link/index.ts
+++ b/apps/web/src/lib/core/email-link/index.ts
@@ -21,6 +21,7 @@ import type {
import type { UseQueryResult } from '@tanstack/solid-query';
import { err, okAsync, ResultAsync } from 'neverthrow';
import { createMemo, createSignal } from 'solid-js';
+import { inboxAuthorizationUrl } from './consent';
import { rememberInboxLinkReturn } from './return-layout';
import { requestShareInboxConfirmation } from './share-conflict';
@@ -217,10 +218,10 @@ const TOO_MANY_PENDING_LINKS_MESSAGE =
* navigates the browser to the OAuth consent page. The callback returns to
* `/inbox-link-callback`, which provisions the new link.
*
- * `scopes` selects which permissions the consent screen asks for. Only calendar
- * entry points may request calendar access, and they pass `calendar` for an
- * inbox that is already connected so the user isn't shown mailbox permissions
- * they have already granted.
+ * `scopes` selects which permissions the consent screen asks for. Calendar
+ * entry points and reconnects of previously enabled calendars request calendar
+ * access. A healthy mailbox upgrade passes `calendar`; a revoked account needs
+ * `gmail_and_calendar` to restore both capabilities.
*
* On native mobile OAuth runs in a platform authentication browser via
* the Tauri auth plugin (the app never navigates away), and the link is
@@ -261,7 +262,10 @@ export function useAddInboxFlow() {
);
};
- const startNativeFlow = async (scopes: ConsentScopes) => {
+ const startNativeFlow = async (
+ scopes: ConsentScopes,
+ emailAddress?: string
+ ) => {
const session = createNativeAuthSession('inbox-link-callback');
const result = await initGmailLink.mutateAsync({
originalUrl: session.callbackUrl,
@@ -280,7 +284,9 @@ export function useAddInboxFlow() {
return;
}
- const auth = await session.authenticate(result.value.authorization_url);
+ const auth = await session.authenticate(
+ inboxAuthorizationUrl(result.value.authorization_url, emailAddress)
+ );
if (!auth.success) {
if (auth.error !== 'User canceled login') {
toast.failure('Failed to add inbox');
@@ -291,10 +297,13 @@ export function useAddInboxFlow() {
await completeNativeLink(result.value.link_id, false);
};
- return async (options?: { scopes?: ConsentScopes }) => {
+ return async (options?: {
+ scopes?: ConsentScopes;
+ emailAddress?: string;
+ }) => {
const scopes = options?.scopes ?? 'gmail';
if (isNativeMobilePlatform()) {
- await startNativeFlow(scopes);
+ await startNativeFlow(scopes, options?.emailAddress);
return;
}
@@ -310,7 +319,10 @@ export function useAddInboxFlow() {
rememberInboxLinkReturn(result.value.link_id, {
url: `${toBaseRelative(window.location.pathname)}${window.location.search}${window.location.hash}`,
});
- window.location.href = result.value.authorization_url;
+ window.location.href = inboxAuthorizationUrl(
+ result.value.authorization_url,
+ options?.emailAddress
+ );
} else if (isPaymentRequired(result.error)) {
showPaywall(PaywallKey.MULTI_INBOX);
} else if (isTooManyPendingLinks(result.error)) {
diff --git a/apps/web/src/lib/queries/auth/gmail-link.ts b/apps/web/src/lib/queries/auth/gmail-link.ts
index d2cc475503..f655936827 100644
--- a/apps/web/src/lib/queries/auth/gmail-link.ts
+++ b/apps/web/src/lib/queries/auth/gmail-link.ts
@@ -5,8 +5,8 @@ import { useMutation } from '@tanstack/solid-query';
* Mutation that asks auth-service for the Google OAuth authorization URL for
* adding a Gmail inbox to the already-authenticated user. Callers consume the
* `authorization_url` and navigate the browser to it. `scopes` selects which
- * permissions the consent screen asks for; only calendar entry points may
- * request calendar access.
+ * permissions the consent screen asks for. Calendar entry points and reconnects
+ * of inboxes that already used calendar request calendar access.
*/
export function useInitGmailLink() {
return useMutation(() => ({
diff --git a/apps/web/src/lib/queries/email/link.test.tsx b/apps/web/src/lib/queries/email/link.test.tsx
index e3bfccf3bc..395eaab2c8 100644
--- a/apps/web/src/lib/queries/email/link.test.tsx
+++ b/apps/web/src/lib/queries/email/link.test.tsx
@@ -98,6 +98,36 @@ beforeEach(() => {
});
describe('useDisableCalendarMutation', () => {
+ it('does not offer re-enable while the server is still deleting calendar data', async () => {
+ let finish!: (value: Ok<Record<string, never>, never>) => void;
+ disableLinkCalendarMock.mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ const disable = mountEmailMutation(
+ useDisableCalendarMutation,
+ testQueryClient
+ );
+ const pending = disable.mutateAsync('inbox-a');
+ await vi.waitFor(() =>
+ expect(disableLinkCalendarMock).toHaveBeenCalledOnce()
+ );
+ expect(disable.isPending).toBe(true);
+ expect(cachedLink('inbox-a')).toMatchObject({
+ calendar_disabled: false,
+ needs_calendar_permission: false,
+ has_calendar_data: true,
+ });
+ finish(ok({}));
+ await pending;
+ expect(cachedLink('inbox-a')).toMatchObject({
+ calendar_disabled: true,
+ needs_calendar_permission: true,
+ has_calendar_data: false,
+ });
+ });
+
it('marks only the target inbox as deliberately calendar-less', async () => {
disableLinkCalendarMock.mockResolvedValue(ok({}));
const disable = mountEmailMutation(
@@ -123,7 +153,7 @@ describe('useDisableCalendarMutation', () => {
expect(invalidateCalendarViewsMock).toHaveBeenCalledTimes(1);
});
- it('restores the previous links when the request fails', async () => {
+ it('keeps the previous links when the request fails', async () => {
disableLinkCalendarMock.mockResolvedValue(
err([{ code: 'HTTP_ERROR' as const, message: 'nope' }])
);
diff --git a/apps/web/src/lib/queries/email/link.ts b/apps/web/src/lib/queries/email/link.ts
index 9f6d120824..c3df5d5ca7 100644
--- a/apps/web/src/lib/queries/email/link.ts
+++ b/apps/web/src/lib/queries/email/link.ts
@@ -121,23 +121,13 @@ export function invalidateEmailLinks() {
});
}
-type DisableCalendarContext = {
- previousLinks: ListLinksResponse | undefined;
-};
-type DisableCalendarCallbacks = MutationCallbacks<
- void,
- Error,
- string,
- DisableCalendarContext
->;
+type DisableCalendarCallbacks = MutationCallbacks<void, Error, string>;
/**
* 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 and drops
- * `has_calendar_data`, which is what swaps the settings row back to "Enable
- * calendar", retires the turn-off control, and keeps the enable prompt quiet.
- * The emptied calendar caches are refetched.
+ * drops the calendar scopes from its Google grant. Publish the disabled state
+ * only after deletion finishes: offering Enable while deletion holds the
+ * inbox's grant lock makes the consent callback wait behind that deletion.
*/
export function useDisableCalendarMutation(
callbacks?: DisableCalendarCallbacks
@@ -147,17 +137,13 @@ export function useDisableCalendarMutation(
await throwOnErr(() => emailClient.disableLinkCalendar({ linkId }));
},
- ...withCallbacks<void, Error, string, DisableCalendarContext>(
+ ...withCallbacks<void, Error, string>(
{
- onMutate: async (linkId) => {
+ onSuccess: async (_data, linkId) => {
await queryClient.cancelQueries({
queryKey: emailKeys.links.queryKey,
});
- const previousLinks = queryClient.getQueryData<ListLinksResponse>(
- emailKeys.links.queryKey
- );
-
queryClient.setQueryData<ListLinksResponse>(
emailKeys.links.queryKey,
(old) =>
@@ -176,22 +162,9 @@ export function useDisableCalendarMutation(
}
);
- return { previousLinks };
- },
-
- onSuccess: () => {
invalidateEmailLinks();
invalidateCalendarViews();
},
-
- onError: (_error, _linkId, context) => {
- if (context?.previousLinks) {
- queryClient.setQueryData(
- emailKeys.links.queryKey,
- context.previousLinks
- );
- }
- },
},
callbacks
),
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index d2e44c3330..be5c9d748d 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -831,10 +831,9 @@ export const authServiceClient = {
* After Google consent, the user is redirected back to `originalUrl` with `?link_id=<uuid>`
* appended; the frontend then calls `emailClient.init({ linkId })` to provision the inbox.
*
- * `scopes` selects which permissions the consent screen asks for. Only
- * calendar entry points may request calendar access, and an inbox that is
- * already connected should ask for `calendar` alone so the user isn't
- * re-consenting to mailbox access they have already granted.
+ * `scopes` selects which permissions the consent screen asks for. A healthy
+ * mailbox adding calendar requests `calendar`; reconnecting an account that
+ * used calendar requests `gmail_and_calendar` to repair both capabilities.
*/
async initGmailLink(
originalUrl?: string,
diff --git a/crates/macro_db_client/migrations/20261002191525_calendar_event_source_reference_indexes.sql b/crates/macro_db_client/migrations/20261002191525_calendar_event_source_reference_indexes.sql
new file mode 100644
index 0000000000..0faeba1bc6
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261002191525_calendar_event_source_reference_indexes.sql
@@ -0,0 +1,8 @@
+-- no-transaction
+
+-- Deleting a calendar source sets this reference to NULL. Without an index,
+-- disconnecting an account scans all events once for every deleted source,
+-- holding the inbox's grant lock and blocking a concurrent reconnect.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS calendar_events_content_source_idx
+ ON calendar_events (content_source_id)
+ WHERE content_source_id IS NOT NULL;
diff --git a/crates/macro_db_client/migrations/20261002191555_calendar_event_schedule_source_index.sql b/crates/macro_db_client/migrations/20261002191555_calendar_event_schedule_source_index.sql
new file mode 100644
index 0000000000..3d83d6b145
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261002191555_calendar_event_schedule_source_index.sql
@@ -0,0 +1,7 @@
+-- no-transaction
+
+-- The schedule reference has the same ON DELETE SET NULL cost as the content
+-- reference. Keep concurrent index builds in separate SQLx migrations.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS calendar_events_schedule_source_idx
+ ON calendar_events (schedule_source_id)
+ WHERE schedule_source_id IS NOT NULL;
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 9f0f1648d9..b74ab3004e 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1083,7 +1083,10 @@ Quick loads skip the skeletons. Real events lay out underneath during the brief
minimum display, then fade in as the skeletons fade out. Changing period during a
load carries feedback into the new cells without restarting the appearance delay.
Background refreshes retain current events without skeletons or a transient loading
-pill. Provider sync and errors still show their own states. Verify delayed occurrence
+pill. Provider backfill shows a persistent `Syncing your calendar…` banner above the
+grid, explaining that events will appear automatically and Macro remains usable.
+The banner stays visible as partial results arrive and disappears when sync finishes.
+Errors retain the separate retry state. Verify delayed occurrence
responses: switch Month/Week/Day rapidly and navigate without blanking the grid.
Confirm mixed event shapes, stable positions, clean handoff, and an uncovered Retry.
Reduced-motion mode disables pulses and transitions. The page stays busy until the
@@ -1294,10 +1297,26 @@ Working locations (such as `Office` or `Home`) stay on the calendar grid but are
excluded from Upcoming events, including both all-day and hourly locations.
Events require connecting a Google account (`Connect calendar`). The
`Calendar settings` (gear) menu has an `Accounts`
-section listing each connected account with a per-account `Enable` (grant calendar) or
-`Turn off` action, plus `Connect another account` to connect a new Google account
+section listing each connected account with a per-account `Enable` (grant calendar),
+`Reconnect` (expired Google authorization), or `Turn off` action, plus
+`Connect another account` to connect a new Google account
(email + calendar).
+`Turn off` keeps its confirmation open with `Turning off…` until removal finishes;
+re-enabling is not offered while the old calendar is still being deleted. Reconnecting
+an inbox that used calendar requests email and calendar together, while an explicit
+calendar opt-out remains off during an email-only reconnect. Per-inbox actions
+preselect that Google account. The consent callback explains that it is finishing
+the connection, provides `Back to app`, and restores the previous layout on completion.
+It applies the grant even if the old inbox list is still loading.
+
+An AI event draft defaults to the primary inbox's primary calendar. If that calendar
+is disconnected or still syncing, the draft offers reconnection or an explicit
+calendar choice and disables submission until a usable calendar is selected. It
+does not silently send the invitation from another connected inbox.
+Failed calendar or account queries show `Could not load your calendars.` with
+`Try again`, rather than offering consent or presenting the failure as backfill.
+
`New event` opens the compact composer with All day in the date/time fields.
The meeting-link selector lists `Macro call`, `Google Meet`, then `No meeting link`
for new events, defaulting to `Macro call` when quick calls are enabled. Keeping