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
fix(calendar): make the enable-calendar prompt usable on mobile (#5407)
gbirmaneca3c89b8482
diff --git a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx b/apps/web/src/features/auth/CalendarPermissionPrompt.tsxindex ae30f3a5a0..c626ca3a37 100644--- a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx+++ b/apps/web/src/features/auth/CalendarPermissionPrompt.tsx@@ -17,9 +17,9 @@ import { useEmailLinksQuery } from '@queries/email/link';* stack. Reconnecting restores the mailbox without calendar access, which* leaves `needs_calendar_permission` set and brings this prompt back.*- * Gated per form factor: `enable-calendar-prompt-web` on desktop/web and- * `enable-calendar-prompt-mobile` on phones, where the toast layout can't- * present it without stranding the user. See `useCalendarPromptAllowed`.+ * 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+ * per-inbox "Enable calendar" button for whenever the user wants it.*/export function CalendarPermissionPrompt() {const calendarUiEnabled = useCalendarUiFlag();@@ -35,6 +35,11 @@ export function CalendarPermissionPrompt() {): [],key: (link) => link.id,+ persistKey: 'macro:calendar-prompt:dismissed',+ // Until the flag resolves and the links land, the empty list above means+ // "don't know yet", not "no inbox needs this" — stored dismissals must+ // survive that window.+ itemsLoaded: () => calendarUiEnabled() && linksQuery.isSuccess,toast: (link, dismiss) => ({title: 'Enable calendar',content(): string {diff --git a/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx b/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsxindex 990a6d0434..4840204ae8 100644--- a/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx+++ b/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx@@ -111,6 +111,9 @@ describe('GithubReauthenticationPrompt', () => {const cleanup = renderPrompt();await flushPromises();await getReconnectAction().onClick();+ // The action fires the OAuth kickoff without awaiting it; let the+ // redirect land before asserting on it.+ await flushPromises();const options = mocks.toastCustom.mock.calls[0]?.[1] as ToastOptions;diff --git a/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx b/apps/web/src/features/auth/GithubReauthenticationPrompt.tsxindex 9e447653c1..6c16dfe3c1 100644--- a/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx+++ b/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx@@ -1,19 +1,19 @@import { toast } from '@core/component/Toast/Toast';+import { useKeyedPersistentToasts } from '@core/component/Toast/useKeyedPersistentToasts';import { authServiceClient } from '@service-auth/client';-import { onMount } from 'solid-js';+import { createSignal, onMount } from 'solid-js';-let githubReauthenticationToastId: number | undefined;--function clearGithubReauthenticationToastState(): void {- githubReauthenticationToastId = undefined;+async function checkGithubReauthenticationStatus(): Promise<boolean> {+ const response = await authServiceClient.checkGithubLinkStatus();+ return response.isOk()+ ? response.value.reauthentication_required+ : response.error.some(+ (error) => error.code === 'REAUTHENTICATION_REQUIRED'+ );}-async function handleGithubReauthenticationToastAction(): Promise<void> {- if (githubReauthenticationToastId !== undefined) {- toast.dismiss(githubReauthenticationToastId);- }- clearGithubReauthenticationToastState();-+/** Kick off the OAuth flow; on success the browser navigates away. */+async function startGithubReauthentication(): Promise<void> {const result = await authServiceClient.reauthenticateGithub(window.location.href);@@ -26,11 +26,23 @@ async function handleGithubReauthenticationToastAction(): Promise<void> {window.location.href = result.value;}-function showGithubReauthenticationToast(): void {- if (githubReauthenticationToastId !== undefined) return;+/**+ * Surfaces a "Reconnect GitHub" prompt when the GitHub grant has expired,+ * probed once on mount. Shares the capped prompt region with the other auth+ * prompts, so it takes its turn instead of stacking on them.+ */+export function GithubReauthenticationPrompt() {+ const [needsReauth, setNeedsReauth] = createSignal(false);- githubReauthenticationToastId = toast.custom(- {+ onMount(() => {+ void checkGithubReauthenticationStatus().then(setNeedsReauth);+ });++ useKeyedPersistentToasts({+ // One GitHub grant per user, so the set is empty or this one fixed key.+ items: () => (needsReauth() ? ['github'] : []),+ key: (item) => item,+ toast: (_item, dismiss) => ({title: 'Reconnect GitHub',content(): string {return 'Your GitHub authorization has expired. Reconnect GitHub to restore pull request details.';@@ -38,34 +50,15 @@ function showGithubReauthenticationToast(): void {actions: [{label: 'Reconnect',- onClick: handleGithubReauthenticationToastAction,+ onClick: () => {+ // Suppress re-prompting while the OAuth flow runs; success+ // navigates the page away entirely.+ dismiss();+ void startGithubReauthentication();+ },},],- },- {- persistent: true,- onDismiss: clearGithubReauthenticationToastState,- }- );-}--async function checkGithubReauthenticationStatus(): Promise<void> {- const response = await authServiceClient.checkGithubLinkStatus();-- const needsReauthentication = response.isOk()- ? response.value.reauthentication_required- : response.error.some(- (error) => error.code === 'REAUTHENTICATION_REQUIRED'- );-- if (needsReauthentication) {- showGithubReauthenticationToast();- }-}--export function GithubReauthenticationPrompt() {- onMount(() => {- void checkGithubReauthenticationStatus();+ }),});return null;diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex b4facea271..a27fbe78ea 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -368,6 +368,7 @@ body.tauri-ios {--animate-dialog-fullscreen-open: dialog-fullscreen-open 160ms cubic-bezier(0.16, 1, 0.3, 1);--animate-typing-dot: typing-dot 1s infinite;--animate-swipe-out: swipeOut 100ms ease-out;+ --animate-swipe-out-left: swipeOutLeft 100ms ease-out;--animate-indeterminate-bar: indeterminate-bar 1.1s ease-in-out infinite;/* Z-index scale — the single source of truth for stacking. Classes come@@ -571,6 +572,13 @@ body.tauri-ios {to { transform: translateX(calc(100% + 16px)) ; }}+@keyframes swipeOutLeft {+ from { transform: translateX(var(--kb-toast-swipe-end-x)); }+ /* Fade as well as slide: the mobile region is centered, so a leftward exit+ can travel over page content instead of off-screen (e.g. on a tablet). */+ to { transform: translateX(calc(-100% - 16px)); opacity: 0; }+}+@keyframes menu-open {from {opacity: 0;diff --git a/apps/web/src/lib/core/component/Toast/Toast.tsx b/apps/web/src/lib/core/component/Toast/Toast.tsxindex 2d191b2ad7..8ebea58b11 100644--- a/apps/web/src/lib/core/component/Toast/Toast.tsx+++ b/apps/web/src/lib/core/component/Toast/Toast.tsx@@ -192,6 +192,29 @@ function dismissActiveToast(region: string): boolean {return true;}+/**+ * Hand the region's single visible slot to a new toast, and report whether it+ * displaced one (so the newcomer can skip its entrance animation).+ *+ * Persistent toasts opt out of the slot entirely: they are prompts the user is+ * expected to answer, so a passing "Copied" must not tear one down, and a+ * prompt appearing must not swallow a result the user is still reading. They+ * stack in the region instead, and leave only when dismissed.+ */+function replaceActiveToast(region: string, persistent?: boolean): boolean {+ if (persistent) return false;+ return dismissActiveToast(region);+}++function trackActiveToast(+ region: string,+ toastId: number,+ persistent?: boolean+): void {+ if (persistent) return;+ setActiveToastId(region, toastId);+}+function clearTrackedToast(region: string, toastId: number): void {if (getActiveToastId(region) === toastId) {setActiveToastId(region, undefined);@@ -251,8 +274,8 @@ function ActionButtons(props: { actions: ToastAction[]; mobile?: boolean }) {<Buttonsize={props.mobile ? 'sm' : 'md'}onClick={action.onClick}- variant={props.mobile ? 'ghost' : 'base'}- class={cn('px-2 py-1', props.mobile && 'text-panel text-xs')}+ variant="base"+ class="px-2 py-1 bg-lift"depth={3}><Show when={action.icon}>@@ -287,7 +310,7 @@ function ToastBodyWrapper(props: {</Surface>}>- <div class="island relative w-[90vw] p-2 rounded-xl bg-toast">+ <div class="island relative w-full p-2 rounded-xl bg-toast">{props.children}</div></Show>@@ -382,7 +405,10 @@ function ToastContent(props: {class={cn(`relative overflow-visible pointer-events-autotransition-[transform,opacity] duration-100 ease-in data-closed:opacity-0 data-[swipe=move]:translate-x-(--kb-toast-swipe-move-x)- data-[swipe=cancel]:translate-x-0 data-[swipe=cancel]:ease-out data-[swipe=cancel]:duration-200 data-[swipe=end]:animate-swipe-out`,+ data-[swipe=move]:transition-none+ data-[swipe=cancel]:translate-x-0 data-[swipe=cancel]:ease-out data-[swipe=cancel]:duration-200+ data-[swipe=end]:data-[swipe-direction=right]:animate-swipe-out+ data-[swipe=end]:data-[swipe-direction=left]:animate-swipe-out-left`,!props.skipOpenAnimation && 'data-opened:animate-slide-in',props.mobile && 'w-full')}@@ -408,46 +434,69 @@ function ToastContent(props: {{/* ── Custom layout ── */}<Match when={props.custom}>- {(customConfig) => (- <>- <div class="flex items-center gap-2 justify-between">- <Show when={customConfig().icon && !props.mobile}>- {(_) => {- const icon = customConfig().icon!;- return (- <div class="size-5 flex shrink-0 justify-center items-center rounded-full p-0.75">- <Dynamic component={icon} />- </div>- );- }}- </Show>- <Toast.Title- class={cn(- 'font-semibold grow shrink truncate text-left',- props.mobile ? 'text-xs' : 'text-ink'- )}- >- {customConfig().title}- </Toast.Title>- <Show when={customConfig().actions?.length}>- <ActionButtons- actions={customConfig().actions!}- mobile={props.mobile}- />+ {(customConfig) => {+ // A persistent prompt on mobile can't borrow the transient+ // one-line treatment: with the body and close button stripped it+ // reduces to a bare title that never goes away. Give it the full+ // card — description, close button, and its actions on their own+ // row so the tap targets aren't fighting a truncated title.+ const stacked = () => Boolean(props.mobile && props.persistent);+ const showContent = () =>+ Boolean(customConfig().content) && (!props.mobile || stacked());+ return (+ <>+ <div class="flex items-center gap-2 justify-between">+ <Show when={customConfig().icon && !props.mobile}>+ {(_) => {+ const icon = customConfig().icon!;+ return (+ <div class="size-5 flex shrink-0 justify-center items-center rounded-full p-0.75">+ <Dynamic component={icon} />+ </div>+ );+ }}+ </Show>+ <Toast.Title+ class={cn(+ 'font-semibold grow shrink truncate text-left flex items-center',+ props.mobile ? 'text-xs' : 'text-ink',+ stacked() && 'text-sm'+ )}+ >+ {customConfig().title}+ </Toast.Title>+ <Show when={customConfig().actions?.length && !stacked()}>+ <ActionButtons+ actions={customConfig().actions!}+ mobile={props.mobile}+ />+ </Show>+ <Show when={!props.mobile || props.persistent}>+ <Toast.CloseButton>+ <Button variant="ghost" size="icon-sm">+ <XIcon />+ </Button>+ </Toast.CloseButton>+ </Show>+ </div>+ <Show when={showContent()}>+ <div+ class={cn(+ 'my-2',+ props.mobile && 'text-xs text-ink-muted'+ )}+ >+ {customConfig().content?.()}+ </div></Show>- <Show when={!props.mobile}>- <Toast.CloseButton>- <Button variant="ghost" size="icon-sm">- <XIcon />- </Button>- </Toast.CloseButton>+ <Show when={stacked() && customConfig().actions?.length}>+ <div class="flex justify-end gap-2">+ <ActionButtons actions={customConfig().actions!} mobile />+ </div></Show>- </div>- <Show when={customConfig().content && !props.mobile}>- <div class="my-2 ml-7">{customConfig().content?.()}</div>- </Show>- </>- )}+ </>+ );+ }}</Match>{/* ── Standard layout ── */}@@ -664,7 +713,7 @@ function embed(const useMobile = isMobile();const region =options?.region ?? (useMobile ? 'mobile-toast-region' : 'toast-region');- const skipOpenAnimation = dismissActiveToast(region);+ const skipOpenAnimation = replaceActiveToast(region, options?.persistent);const toastId = toaster.show((props) => (<ToastContent@@ -679,7 +728,7 @@ function embed(),{ region });- setActiveToastId(region, toastId);+ trackActiveToast(region, toastId, options?.persistent);return toastId;}@@ -702,7 +751,7 @@ function custom(const useMobile = isMobile();const region =options?.region ?? (useMobile ? 'mobile-toast-region' : 'toast-region');- const skipOpenAnimation = dismissActiveToast(region);+ const skipOpenAnimation = replaceActiveToast(region, options?.persistent);const toastId = toaster.show((props) => (<ToastContent@@ -720,7 +769,7 @@ function custom(),{ region });- setActiveToastId(region, toastId);+ trackActiveToast(region, toastId, options?.persistent);return toastId;}diff --git a/apps/web/src/lib/core/component/Toast/ToastRegion.tsx b/apps/web/src/lib/core/component/Toast/ToastRegion.tsxindex 2af57df86d..335b041675 100644--- a/apps/web/src/lib/core/component/Toast/ToastRegion.tsx+++ b/apps/web/src/lib/core/component/Toast/ToastRegion.tsx@@ -4,36 +4,66 @@ import { Portal } from 'solid-js/web';export function ToastRegion() {return (<Portal>- <div class="fixed bottom-2 right-2 m-0 list-none outline-none pointer-events-none z-toast-region">+ {/*+ Desktop stack, bottom-right. Persistent prompts get their own region+ capped at one visible card.+ */}+ <div class="fixed bottom-2 right-2 m-0 p-2 sm:p-4 list-none outline-none pointer-events-none z-toast-region flex flex-col items-end gap-2">+ <Toast.Region+ regionId="prompt-region"+ duration={Infinity}+ limit={1}+ pauseOnInteraction={false}+ swipeDirection="right"+ >+ <Toast.List class="flex flex-col gap-2" />+ </Toast.Region><Toast.RegionregionId="toast-region"duration={Infinity}pauseOnInteraction={false}+ swipeDirection="right">- <Toast.List class="absolute bottom-0 right-0 flex flex-col p-2 sm:p-4 gap-2" />+ <Toast.List class="flex flex-col gap-2" /></Toast.Region>- <Toast.Region regionId="stable-toast" duration={Infinity}>- <Toast.List class="absolute bottom-0 right-0 flex flex-col p-2 sm:p-4 gap-2" />+ <Toast.Region+ regionId="stable-toast"+ duration={Infinity}+ swipeDirection="right"+ >+ <Toast.List class="flex flex-col gap-2" /></Toast.Region></div>{/*- Mobile-only region: centered above the mobile dock. Only one toast is- ever visible — Toast.tsx dismisses the previous mobile toast as soon- as a new one is shown, so no stacking is needed here.+ Mobile-only stack: centered above the mobile dock. At most one+ transient toast is visible — Toast.tsx dismisses the previous one as+ soon as a new one is shown. Persistent prompts live in their own+ region above that slot, capped at one visible card with the rest+ queued until it is answered.*/}<div- class="fixed left-1/2 -translate-x-1/2 w-full max-w-[420px] px-(--mobile-chrome-gutter) pointer-events-none z-toast-region"+ class="fixed left-1/2 -translate-x-1/2 w-full max-w-[420px] px-(--mobile-chrome-gutter) pointer-events-none z-toast-region flex flex-col gap-2"style={{bottom: 'calc(var(--mobile-content-inset-bottom, 0px) + 12px)',}}>+ <Toast.Region+ regionId="mobile-prompt-region"+ duration={Infinity}+ limit={1}+ pauseOnInteraction={false}+ swipeDirection="left"+ >+ <Toast.List class="flex flex-col gap-2" />+ </Toast.Region><Toast.RegionregionId="mobile-toast-region"duration={Infinity}pauseOnInteraction={false}+ swipeDirection="left">- <Toast.List class="flex flex-col" />+ <Toast.List class="flex flex-col gap-2" /></Toast.Region></div></Portal>diff --git a/apps/web/src/lib/core/component/Toast/useKeyedPersistentToasts.test.ts b/apps/web/src/lib/core/component/Toast/useKeyedPersistentToasts.test.tsindex 16989cf89d..8019fcf0f6 100644--- a/apps/web/src/lib/core/component/Toast/useKeyedPersistentToasts.test.ts+++ b/apps/web/src/lib/core/component/Toast/useKeyedPersistentToasts.test.ts@@ -2,7 +2,7 @@* @vitest-environment jsdom*/-import { createRoot, createSignal } from 'solid-js';+import { batch, createRoot, createSignal } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({@@ -21,41 +21,69 @@ import { useKeyedPersistentToasts } from './useKeyedPersistentToasts';type Item = { id: string; label: string };-type ToastOptions = { persistent?: boolean; onDismiss?: () => void };+type ToastOptions = {+ persistent?: boolean;+ region?: string;+ onDismiss?: () => void;+};++function toastOptionsAt(index: number): ToastOptions {+ return mocks.toastCustom.mock.calls[index]?.[1] as ToastOptions;+}function lastToastOptions(): ToastOptions {return mocks.toastCustom.mock.calls.at(-1)?.[1] as ToastOptions;}+const PERSIST_KEY = 'macro:test-prompt:dismissed';++function persistedKeys(): string[] {+ return JSON.parse(localStorage.getItem(PERSIST_KEY) ?? '[]');+}+describe('useKeyedPersistentToasts', () => {let nextToastId: number;beforeEach(() => {nextToastId = 1;mocks.toastCustom.mockImplementation(() => nextToastId++);+ localStorage.clear();});afterEach(() => {vi.clearAllMocks();});- function mount(initial: Item[]) {+ function mount(+ initial: Item[],+ options?: {+ persistKey?: string;+ itemsLoaded?: boolean;+ }+ ) {let setItems!: (items: Item[]) => void;+ let setLoaded!: (loaded: boolean) => void;let dispose!: () => void;createRoot((d) => {dispose = d;const [items, set] = createSignal(initial);+ const [loaded, setLoadedSignal] = createSignal(+ options?.itemsLoaded ?? true+ );setItems = set;+ setLoaded = setLoadedSignal;useKeyedPersistentToasts<Item>({items,key: (item) => item.id,+ persistKey: options?.persistKey,+ itemsLoaded: loaded,toast: (item, dismiss) => ({title: item.label,actions: [{ label: 'Go', onClick: dismiss }],}),});});- return { setItems, dispose };+ return { setItems, setLoaded, dispose };}it('shows one persistent toast per item and no duplicates on re-run', () => {@@ -74,6 +102,18 @@ describe('useKeyedPersistentToasts', () => {dispose();});+ it('routes every prompt to the capped prompt region', () => {+ // The region's `limit` is what caps and queues prompts, so toasts are+ // created eagerly and must all target it. jsdom reports non-mobile.+ const { dispose } = mount([+ { id: 'a', label: 'A' },+ { id: 'b', label: 'B' },+ ]);+ expect(toastOptionsAt(0).region).toBe('prompt-region');+ expect(toastOptionsAt(1).region).toBe('prompt-region');+ dispose();+ });+it('dismisses the toast when its item leaves the set', () => {const { setItems, dispose } = mount([{ id: 'a', label: 'A' }]);setItems([]);@@ -112,6 +152,32 @@ describe('useKeyedPersistentToasts', () => {dispose();});+ it('records nothing when a teardown unmounts synchronously inside dismiss', () => {+ // Kobalte removes a programmatically-dismissed toast from the region in+ // the same synchronous update, so its onDismiss fires inside+ // toast.dismiss — that unmount must not read as a user close.+ const optionsById = new Map<number, ToastOptions>();+ mocks.toastCustom.mockImplementation((_config, options) => {+ const id = nextToastId++;+ optionsById.set(id, options as ToastOptions);+ return id;+ });+ mocks.toastDismiss.mockImplementation((id: number) => {+ optionsById.get(id)?.onDismiss?.();+ });++ const item = { id: 'a', label: 'A' };+ const { setItems, dispose } = mount([item], { persistKey: PERSIST_KEY });+ setItems([]);+ expect(persistedKeys()).toEqual([]);++ setItems([{ ...item }]);+ // The teardown was ours, so the returning item prompts again.+ expect(mocks.toastCustom).toHaveBeenCalledTimes(2);+ dispose();+ mocks.toastDismiss.mockImplementation(() => undefined);+ });+it('dismisses all live toasts on owner cleanup', () => {const { dispose } = mount([{ id: 'a', label: 'A' },@@ -121,4 +187,130 @@ describe('useKeyedPersistentToasts', () => {expect(mocks.toastDismiss).toHaveBeenCalledWith(1);expect(mocks.toastDismiss).toHaveBeenCalledWith(2);});++ it('re-prompts a returning item when its unmount lands after it left', () => {+ const item = { id: 'a', label: 'A' };+ const { setItems, dispose } = mount([item]);+ const unmount = toastOptionsAt(0).onDismiss!;++ setItems([]);+ // The toast element unmounts on its exit animation, i.e. after the item+ // has already been forgotten.+ unmount();+ setItems([{ ...item }]);++ expect(mocks.toastCustom).toHaveBeenCalledTimes(2);+ dispose();+ });++ it('does not touch storage without a persistKey', () => {+ const { dispose } = mount([{ id: 'a', label: 'A' }]);+ lastToastOptions().onDismiss?.();+ expect(localStorage.length).toBe(0);+ dispose();+ });++ describe('with persistKey', () => {+ it('remembers a close across mounts', () => {+ const item = { id: 'a', label: 'A' };+ const first = mount([item], { persistKey: PERSIST_KEY });+ lastToastOptions().onDismiss?.();+ expect(persistedKeys()).toEqual(['a']);+ first.dispose();++ const second = mount([item], { persistKey: PERSIST_KEY });+ expect(mocks.toastCustom).toHaveBeenCalledTimes(1);+ second.dispose();+ });++ it('re-prompts next mount when the action was taken instead of closed', () => {+ const item = { id: 'a', label: 'A' };+ const first = mount([item], { persistKey: PERSIST_KEY });+ const config = mocks.toastCustom.mock.calls[0][0] as {+ actions: { onClick: () => void }[];+ };+ config.actions[0].onClick();+ toastOptionsAt(0).onDismiss?.();+ expect(persistedKeys()).toEqual([]);+ first.dispose();++ // The flow may not have landed the grant — keep the prompt available.+ const second = mount([item], { persistKey: PERSIST_KEY });+ expect(mocks.toastCustom).toHaveBeenCalledTimes(2);+ second.dispose();+ });++ it('does not record a dismissal when the owner is disposed', () => {+ const item = { id: 'a', label: 'A' };+ const { dispose } = mount([item], { persistKey: PERSIST_KEY });+ dispose();+ toastOptionsAt(0).onDismiss?.();+ expect(persistedKeys()).toEqual([]);+ });++ it('forgets a stored dismissal once the item leaves the set', () => {+ const item = { id: 'a', label: 'A' };+ const { setItems, dispose } = mount([item], { persistKey: PERSIST_KEY });+ lastToastOptions().onDismiss?.();+ expect(persistedKeys()).toEqual(['a']);++ setItems([]);+ expect(persistedKeys()).toEqual([]);+ dispose();+ });++ it('keeps stored dismissals while the item set is still loading', () => {+ const item = { id: 'a', label: 'A' };+ const first = mount([item], { persistKey: PERSIST_KEY });+ lastToastOptions().onDismiss?.();+ expect(persistedKeys()).toEqual(['a']);+ first.dispose();++ // How a page load starts: query hasn't answered, so the list is empty.+ const second = mount([], {+ persistKey: PERSIST_KEY,+ itemsLoaded: false,+ });+ expect(persistedKeys()).toEqual(['a']);++ // Links land, still needing calendar — the stored "no" holds. Data and+ // success flip together, so the empty list is never seen as loaded.+ batch(() => {+ second.setItems([item]);+ second.setLoaded(true);+ });+ expect(mocks.toastCustom).toHaveBeenCalledTimes(1);+ expect(persistedKeys()).toEqual(['a']);+ second.dispose();+ });++ it('ignores malformed stored state', () => {+ localStorage.setItem(PERSIST_KEY, '{"nope":true}');+ const { dispose } = mount([{ id: 'a', label: 'A' }], {+ persistKey: PERSIST_KEY,+ });+ expect(mocks.toastCustom).toHaveBeenCalledTimes(1);+ dispose();+ });+ });++ it('lets a stale unmount retract only its own toast', () => {+ const item = { id: 'a', label: 'A' };+ const { setItems, dispose } = mount([item]);+ const staleUnmount = toastOptionsAt(0).onDismiss!;++ // Item leaves and returns inside the first toast's exit animation, so the+ // key already belongs to a replacement by the time #1 finally unmounts.+ setItems([]);+ setItems([{ ...item }]);+ expect(mocks.toastCustom).toHaveBeenCalledTimes(2);++ staleUnmount();++ // The replacement is still tracked, so no duplicate is created for it and+ // the stale teardown is not mistaken for a user dismissal.+ setItems([{ ...item, label: 'A2' }]);+ expect(mocks.toastCustom).toHaveBeenCalledTimes(2);+ dispose();+ });});diff --git a/apps/web/src/lib/core/component/Toast/useKeyedPersistentToasts.ts b/apps/web/src/lib/core/component/Toast/useKeyedPersistentToasts.tsindex ee52b7ec9a..e36e9165c5 100644--- a/apps/web/src/lib/core/component/Toast/useKeyedPersistentToasts.ts+++ b/apps/web/src/lib/core/component/Toast/useKeyedPersistentToasts.ts@@ -1,31 +1,110 @@+import { isMobile } from '@core/mobile/isMobile';import { type Accessor, createEffect, onCleanup } from 'solid-js';import { type CustomToastConfig, toast } from './Toast';+function readDismissed(storageKey: string): string[] {+ if (typeof localStorage === 'undefined') return [];+ try {+ const parsed: unknown = JSON.parse(+ localStorage.getItem(storageKey) ?? '[]'+ );+ if (!Array.isArray(parsed)) return [];+ return parsed.filter((key): key is string => typeof key === 'string');+ } catch {+ return [];+ }+}++function writeDismissed(storageKey: string, keys: Iterable<string>): void {+ if (typeof localStorage === 'undefined') return;+ try {+ localStorage.setItem(storageKey, JSON.stringify([...keys]));+ } catch {+ // Storage may be unavailable or full. In-memory dismissal still works.+ }+}+/*** Keep exactly one persistent toast alive per keyed item in a reactive set.*- * When an item leaves the set its toast is dismissed and its session dismissal- * is forgotten, so a later reappearance prompts again. A user-dismissed key is+ * When an item leaves the set its toast is dismissed and its dismissal is+ * forgotten, so a later reappearance prompts again. A user-dismissed key is* not re-prompted while the item remains in the set. All live toasts are* dismissed on owner cleanup.** The factory receives a `dismiss` handle for action handlers that should* close the toast and suppress re-prompting for the session (e.g. after* kicking off a flow that will eventually remove the item from the set).+ *+ * Every toast is created eagerly into the layout's prompt region, whose+ * `limit` shows one prompt at a time and queues the rest in creation order —+ * unrelated prompt hooks take turns instead of stacking, with mount order+ * deciding who goes first. `persistKey` carries closes across reloads — see+ * below.*/export function useKeyedPersistentToasts<T>(options: {items: Accessor<readonly T[]>;key: (item: T) => string;toast: (item: T, dismiss: () => void) => CustomToastConfig;+ /**+ * localStorage key under which explicit user dismissals are remembered+ * across reloads. Set it for advisory prompts, where re-asking on every+ * load is nagging and the action stays reachable elsewhere (e.g.+ * settings). Leave it unset for prompts that must keep re-surfacing until+ * resolved, like a dead inbox grant.+ *+ * Only a close counts: taking the action, or the toast being torn down+ * for us, still re-prompts next session if the item is still there.+ */+ persistKey?: string;+ /**+ * Whether `items` currently reflects real server state rather than a+ * query that has not answered yet. Both look like an empty list from in+ * here, and treating "still loading" as "the item is gone" would forget+ * dismissals the moment the app starts. Defaults to true, which is right+ * for a set that is synchronously derived.+ */+ itemsLoaded?: Accessor<boolean>;}): void {- const toastIds = new Map<string, number>();+ /**+ * A shown toast. Tracked by object identity rather than by key alone: a+ * toast unmounts at the end of its exit animation, by which point the key+ * may already belong to a replacement, and the departing toast must not+ * retract or answer for it.+ */+ type LiveToast = { id: number };++ const live = new Map<string, LiveToast>();const dismissed = new Set<string>();+ /**+ * Toasts we tore down ourselves. Their `onDismiss` reports our own teardown+ * — item left the set, action taken, owner disposed — rather than a user+ * decision, so it must not be recorded as one. An entry whose toast was+ * still queued (never rendered) has no unmount and simply stays here;+ * that's harmless.+ */+ const selfDismissed = new Set<LiveToast>();++ const persistKey = options.persistKey;+ const persisted = new Set(persistKey ? readDismissed(persistKey) : []);+ for (const key of persisted) dismissed.add(key);const dismissToast = (key: string) => {- const id = toastIds.get(key);- if (id !== undefined) {- toast.dismiss(id);- toastIds.delete(key);+ const entry = live.get(key);+ if (entry) {+ selfDismissed.add(entry);+ // Kobalte tears a dismissed toast out of the region in the same+ // synchronous update, so its onDismiss can fire inside this call —+ // the entry must already be gone from `live` by then.+ live.delete(key);+ toast.dismiss(entry.id);+ }+ };++ const forget = (key: string) => {+ dismissed.delete(key);+ if (persistKey && persisted.delete(key)) {+ writeDismissed(persistKey, persisted);}};@@ -33,33 +112,49 @@ export function useKeyedPersistentToasts<T>(options: {const items = options.items();const liveKeys = new Set(items.map(options.key));- for (const key of [...toastIds.keys()]) {+ for (const key of [...live.keys()]) {if (!liveKeys.has(key)) dismissToast(key);}- for (const key of [...dismissed]) {- if (!liveKeys.has(key)) dismissed.delete(key);+ if (options.itemsLoaded?.() ?? true) {+ for (const key of [...dismissed]) {+ if (!liveKeys.has(key)) forget(key);+ }}for (const item of items) {const key = options.key(item);- if (toastIds.has(key) || dismissed.has(key)) continue;+ if (live.has(key) || dismissed.has(key)) continue;const suppress = () => {dismissed.add(key);dismissToast(key);};- const id = toast.custom(options.toast(item, suppress), {+ const entry: LiveToast = { id: 0 };+ entry.id = toast.custom(options.toast(item, suppress), {persistent: true,+ // The prompt region caps how many of these are visible and queues+ // the rest, so every eligible item gets its toast created eagerly.+ region: isMobile() ? 'mobile-prompt-region' : 'prompt-region',onDismiss: () => {- toastIds.delete(key);+ // Only retract ourselves; the key may already hold a replacement.+ if (live.get(key) === entry) live.delete(key);+ // Our own teardown already left `dismissed` how it wants it, and+ // the unmount can land after the item was forgotten — re-adding+ // here would strand a returning item.+ if (selfDismissed.delete(entry)) return;+dismissed.add(key);+ if (persistKey && !persisted.has(key)) {+ persisted.add(key);+ writeDismissed(persistKey, persisted);+ }},});- toastIds.set(key, id);+ live.set(key, entry);}});onCleanup(() => {- for (const key of [...toastIds.keys()]) dismissToast(key);+ for (const key of [...live.keys()]) dismissToast(key);});}