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.

feat: undo mark-as-done + notification refetch cleanup (#2701)

gbirman1932ce852bc9
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index d42a82e32f..c5b24d0067 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -37,6 +37,7 @@ import {
import { prefetchHistory } from '@queries/history/history';
import { invalidateUserNotifications } from '@queries/notification/user-notifications';
import { QuerySyncProvider } from '@queries/sync/SyncProvider';
+import { MutationUndoProvider } from '@queries/undo';
import { ws as connectionGatewayWebsocket } from '@service-connection/websocket';
import { MetaProvider, Title } from '@solidjs/meta';
import {
@@ -436,32 +437,34 @@ export function Root() {
<QuerySyncProviderWithUserId />
<UserInfoSideEffects />
<ConfiguredGlobalAppStateProvider>
- <ChannelsContextProvider>
- <QuickAccessProvider>
- <SearchProvider>
- <ChatAttachmentsInit />
- <ReactiveFavicon />
- <Title>{tabTitle()}</Title>
- <MacroJump />
- <Visor />
- <Suspense>
- <IsomorphicRouter
- transformUrl={transformShortIdInUrlPathname}
- root={Layout}
- rootPreload={rootPreload}
- base={ROUTER_BASE}
- >
- {{
- path: '/',
- component: TauriRouteListener,
- children: ROUTES,
- }}
- </IsomorphicRouter>
- </Suspense>
- <ToastRegion />
- </SearchProvider>
- </QuickAccessProvider>
- </ChannelsContextProvider>
+ <MutationUndoProvider>
+ <ChannelsContextProvider>
+ <QuickAccessProvider>
+ <SearchProvider>
+ <ChatAttachmentsInit />
+ <ReactiveFavicon />
+ <Title>{tabTitle()}</Title>
+ <MacroJump />
+ <Visor />
+ <Suspense>
+ <IsomorphicRouter
+ transformUrl={transformShortIdInUrlPathname}
+ root={Layout}
+ rootPreload={rootPreload}
+ base={ROUTER_BASE}
+ >
+ {{
+ path: '/',
+ component: TauriRouteListener,
+ children: ROUTES,
+ }}
+ </IsomorphicRouter>
+ </Suspense>
+ <ToastRegion />
+ </SearchProvider>
+ </QuickAccessProvider>
+ </ChannelsContextProvider>
+ </MutationUndoProvider>
</ConfiguredGlobalAppStateProvider>
</UserContextProvider>
</EntityProvider>
diff --git a/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
index 789014b8e9..1561fd85ee 100644
--- a/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
+++ b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
@@ -1,19 +1,108 @@
+import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
import { toast } from '@core/component/Toast/Toast';
import { type EntityData, isTaskEntity } from '@entity';
+import type { NotificationSource } from '@notifications';
+import { useMutationUndoContext, useUndoableMutation } from '@queries/undo';
import {
- markNotificationsForEntityAsDone,
- type NotificationSource,
-} from '@notifications';
+ applyEntitiesDoneOptimistic,
+ executeMarkEntitiesDone,
+ executeMarkEntitiesUndone,
+ type MarkEntitiesDoneContext,
+ resolveMarkEntitiesDoneVariables,
+ restoreSoupFocus,
+} from '@app/component/next-soup/utils';
+import { useMaybePreviewPanel } from '@app/component/PreviewPanel';
import type { SoupState } from '../create-soup-state';
-import { archiveEmail } from '@app/component/next-soup/utils';
type MakeMarkDoneOptions = {
userId?: () => string | undefined;
notificationSource: () => NotificationSource;
};
+type MarkDoneVariables = {
+ entities: EntityData[];
+ emailIds: string[];
+ notificationIds: string[];
+};
+
+/** Must be invoked inside a component tree that provides MutationUndoProvider. */
export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
const { notificationSource } = options;
+ const previewPanel = useMaybePreviewPanel();
+ const inPreview = previewPanel !== undefined;
+ const undoCtx = useMutationUndoContext();
+
+ const mutation = useUndoableMutation<
+ void,
+ Error,
+ MarkDoneVariables,
+ MarkEntitiesDoneContext
+ >(() => ({
+ onMutate: (variables) =>
+ applyEntitiesDoneOptimistic({
+ emailIds: variables.emailIds,
+ notificationIds: variables.notificationIds,
+ }),
+ mutationFn: async (variables) =>
+ await executeMarkEntitiesDone({
+ emailIds: variables.emailIds,
+ notificationIds: variables.notificationIds,
+ }),
+ onSuccess: (_data, variables) => {
+ const count = variables.entities.length;
+ const firstEntityId = variables.entities[0]?.id;
+ const toastId = toast.success(
+ count > 1 ? `Marked ${count} items as done` : 'Marked as done',
+ undefined,
+ [
+ {
+ label: 'Undo',
+ icon: ArrowCounterClockwise,
+ onClick: () => {
+ if (toastId != null) toast.dismiss(toastId);
+ // Route through the undo stack so the entry is popped and
+ // Cmd+Z / shift+Cmd+Z stay in sync with the toast action.
+ undoCtx.undo({
+ onError: () => toast.failure('Failed to undo'),
+ });
+ restoreSoupFocus(firstEntityId, inPreview);
+ },
+ },
+ ],
+ 10_000,
+ true
+ );
+ },
+ onError: (_err, _variables, context) => {
+ context?.rollback();
+ toast.failure('Failed to mark as done');
+ },
+ undoFn: async (variables, context) => {
+ context?.applyUndone();
+ try {
+ await executeMarkEntitiesUndone({
+ emailIds: variables.emailIds,
+ notificationIds: variables.notificationIds,
+ });
+ } catch (err) {
+ context?.reapply();
+ throw err;
+ }
+ },
+ redoFn: async (variables, context) => {
+ context?.reapply();
+ try {
+ await executeMarkEntitiesDone({
+ emailIds: variables.emailIds,
+ notificationIds: variables.notificationIds,
+ });
+ } catch (err) {
+ context?.applyUndone();
+ throw err;
+ }
+ },
+ undoLabel: 'Mark Done',
+ }));
const canExecute = (entity: EntityData): boolean => {
if (entity.type === 'channel_message') return false;
@@ -32,26 +121,11 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
};
const execute = async (entities: EntityData[]) => {
- const source = notificationSource();
-
- await Promise.all(
- entities.map(async (entity) => {
- if (entity.type === 'email') {
- await archiveEmail(entity.id, {
- archive: true,
- optimisticallyExclude: true,
- });
- }
-
- markNotificationsForEntityAsDone(source, entity);
- })
- );
-
- toast.success(
- entities.length > 1
- ? `Marked ${entities.length} items as done`
- : 'Marked as done'
- );
+ const { emailIds, notificationIds } = resolveMarkEntitiesDoneVariables({
+ entities,
+ notificationSource: notificationSource(),
+ });
+ await mutation.mutateAsync({ entities, emailIds, notificationIds });
};
const executeWithSoup = async (
diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.ts
index 37f14c22fe..e9d711cc3b 100644
--- a/js/app/packages/app/component/next-soup/utils.ts
+++ b/js/app/packages/app/component/next-soup/utils.ts
@@ -28,6 +28,16 @@ import {
import { match } from 'ts-pattern';
import { isAfter } from 'date-fns';
import { getChannelParams } from '@block-channel/utils/link';
+import {
+ compositeEntity,
+ type NotificationSource,
+ setDoneOverride,
+} from '@notifications';
+import {
+ bulkMarkNotificationsAsDone,
+ bulkMarkNotificationsAsUndone,
+} from '@queries/notification/user-notifications';
+import { notificationKeys } from '@queries/notification/keys';
const mergeSearchEntities = <T extends EntityData>(
first: WithSearch<T>,
@@ -247,25 +257,29 @@ export const restoreSoupFocus = async (
);
}
- if (!domRef) return;
+ if (!(domRef instanceof HTMLElement)) return;
// Wait for DOM to update after modal closes
await waitForFrames(2);
- // Find and focus the entity element
+ // Entity rows are plain divs without a `tabindex` attribute so `.focus()`
+ // on them is a no-op. Targeting them is still useful because the browser
+ // may scroll them into view as part of the focus attempt. Always follow
+ // up by focusing the soup container (which has `tabindex={-1}`) — that's
+ // what actually reactivates the hotkey scope.
if (entityId) {
const entityEl = domRef.querySelector(`[data-entity-id="${entityId}"]`);
- if (entityEl instanceof HTMLElement) {
- entityEl.focus();
- return;
- }
+ if (entityEl instanceof HTMLElement) entityEl.focus();
}
- // Fallback: focus the first entity in the list if no specific entity to focus
+ if (document.activeElement && domRef.contains(document.activeElement)) return;
+
const firstEntityEl = domRef.querySelector('[data-entity-id]');
- if (firstEntityEl instanceof HTMLElement) {
- firstEntityEl.focus();
- }
+ if (firstEntityEl instanceof HTMLElement) firstEntityEl.focus();
+
+ if (document.activeElement && domRef.contains(document.activeElement)) return;
+
+ domRef.focus();
};
export interface OpenEntityOptions {
@@ -572,3 +586,233 @@ export function trashEmails(ids: string[]): TrashEmailsHandle {
},
};
}
+
+export type MarkEntitiesDoneContext = {
+ /** Clears optimistic state — use for mark-done failure (cache is pre-mutation). */
+ rollback: () => void;
+ /** Re-applies the optimistic done state. Use for redo / undo failure. */
+ reapply: () => void;
+ /** Reverts email/soup caches and forces `done=false` override. Use for undo. */
+ applyUndone: () => void;
+};
+
+/**
+ * Extract the email ids and notification ids targeted by a mark-done on these
+ * entities. The ids are snapshotted here so mutationFn/undoFn/redoFn operate
+ * on the set that existed at mutation time.
+ */
+export function resolveMarkEntitiesDoneVariables(args: {
+ entities: EntityData[];
+ notificationSource: NotificationSource;
+}): { emailIds: string[]; notificationIds: string[] } {
+ const { entities, notificationSource } = args;
+ const emailIds = entities.filter((e) => e.type === 'email').map((e) => e.id);
+ const notificationIds = entities.flatMap((entity) =>
+ (
+ notificationSource.notificationsByEntity()[compositeEntity(entity)] ?? []
+ ).map((n) => n.id)
+ );
+ return { emailIds, notificationIds };
+}
+
+/**
+ * Applies the optimistic UI state for marking entities as done — removes
+ * emails from the soup + email caches and flips the notification `done`
+ * override. Returns a context the mutation uses for rollback / reapply.
+ */
+export function applyEntitiesDoneOptimistic(args: {
+ emailIds: string[];
+ notificationIds: string[];
+}): MarkEntitiesDoneContext {
+ const { emailIds, notificationIds } = args;
+ const emailIdSet = new Set(emailIds);
+
+ type EmailQueryKey = readonly unknown[];
+ type EmailCacheData = { pages: { items: EntityData[] }[] };
+ const removedEmails = new Map<EmailQueryKey, Map<string, EntityData>>();
+
+ const filterEmailCache = () => {
+ if (emailIdSet.size === 0) return;
+ for (const [key, data] of queryClient.getQueriesData<EmailCacheData>({
+ queryKey: queryKeys.all.email,
+ })) {
+ if (!data) continue;
+ const bucket = removedEmails.get(key) ?? new Map<string, EntityData>();
+ let mutated = false;
+ const pages = data.pages.map((page) => {
+ const items: EntityData[] = [];
+ for (const item of page.items) {
+ if (emailIdSet.has(item.id)) {
+ bucket.set(item.id, item);
+ mutated = true;
+ } else {
+ items.push(item);
+ }
+ }
+ return mutated && items.length !== page.items.length
+ ? { ...page, items }
+ : page;
+ });
+ if (mutated) {
+ removedEmails.set(key, bucket);
+ queryClient.setQueryData(key, { ...data, pages });
+ }
+ }
+ };
+
+ const restoreEmailCache = () => {
+ for (const [key, bucket] of removedEmails) {
+ if (bucket.size === 0) continue;
+ const toRestore = [...bucket.values()];
+ bucket.clear();
+ queryClient.setQueryData<EmailCacheData>(key, (current) => {
+ if (!current) return current;
+ const restoredIds = new Set(toRestore.map((e) => e.id));
+ return {
+ ...current,
+ pages: current.pages.map((page, idx) => {
+ const filtered = page.items.filter((i) => !restoredIds.has(i.id));
+ if (idx === 0) {
+ return { ...page, items: [...toRestore, ...filtered] };
+ }
+ if (filtered.length === page.items.length) {
+ return page;
+ }
+ return { ...page, items: filtered };
+ }),
+ };
+ });
+ }
+ };
+
+ let soupTxn: ReturnType<typeof removeSoupEntities> | null = null;
+
+ const reapply = () => {
+ soupTxn = emailIds.length > 0 ? removeSoupEntities(emailIdSet) : null;
+ filterEmailCache();
+ setDoneOverride(notificationIds, true);
+ };
+
+ const rollback = () => {
+ soupTxn?.rollback();
+ soupTxn = null;
+ restoreEmailCache();
+ setDoneOverride(notificationIds, undefined);
+ };
+
+ const applyUndone = () => {
+ soupTxn?.rollback();
+ soupTxn = null;
+ restoreEmailCache();
+ // Force `done=false` — cache may have reconciled to `done=true` from the
+ // server, so clearing the override would leave the UI hidden after undo.
+ setDoneOverride(notificationIds, false);
+ };
+
+ reapply();
+
+ return { rollback, reapply, applyUndone };
+}
+
+/**
+ * Fires the archive + bulk-done APIs for the given ids. Throws on any
+ * failure; caller is responsible for rollback via the context returned by
+ * `applyEntitiesDoneOptimistic`.
+ */
+export async function executeMarkEntitiesDone(args: {
+ emailIds: string[];
+ notificationIds: string[];
+}): Promise<void> {
+ const { emailIds, notificationIds } = args;
+ await Promise.all([
+ queryClient.cancelQueries({ queryKey: queryKeys.all.email }),
+ queryClient.cancelQueries({ queryKey: notificationKeys.user._def }),
+ ]);
+
+ const results = await Promise.allSettled([
+ ...emailIds.map((id) =>
+ throwOnErr(
+ async () => await emailClient.flagArchived({ value: true, id })
+ )
+ ),
+ notificationIds.length > 0
+ ? bulkMarkNotificationsAsDone(notificationIds)
+ : Promise.resolve(),
+ ]);
+
+ const rejected = results.find(
+ (r): r is PromiseRejectedResult => r.status === 'rejected'
+ );
+
+ if (rejected) {
+ // Real refetch to reconcile server state with the UI after the caller
+ // rolls back its optimistic cache writes.
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
+ queryClient.invalidateQueries({ queryKey: notificationKeys.user._def }),
+ ...emailIds.map((id) => invalidateSoupEntity(id)),
+ ]);
+ throw rejected.reason ?? new Error('Failed to mark as done');
+ }
+
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.all.email,
+ refetchType: 'none',
+ }),
+ queryClient.invalidateQueries({
+ queryKey: notificationKeys.user._def,
+ refetchType: 'none',
+ }),
+ ...emailIds.map((id) => invalidateSoupEntity(id)),
+ ]);
+}
+
+/**
+ * Fires the unarchive + bulk-undone APIs for the given ids. Throws on any
+ * failure; caller is responsible for re-applying optimistic state.
+ */
+export async function executeMarkEntitiesUndone(args: {
+ emailIds: string[];
+ notificationIds: string[];
+}): Promise<void> {
+ const { emailIds, notificationIds } = args;
+ await Promise.all([
+ queryClient.cancelQueries({ queryKey: queryKeys.all.email }),
+ queryClient.cancelQueries({ queryKey: notificationKeys.user._def }),
+ ]);
+
+ const results = await Promise.allSettled([
+ ...emailIds.map((id) =>
+ throwOnErr(
+ async () => await emailClient.flagArchived({ value: false, id })
+ )
+ ),
+ notificationIds.length > 0
+ ? bulkMarkNotificationsAsUndone(notificationIds)
+ : Promise.resolve(),
+ ]);
+
+ const rejected = results.find(
+ (r): r is PromiseRejectedResult => r.status === 'rejected'
+ );
+
+ if (rejected) {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
+ queryClient.invalidateQueries({ queryKey: notificationKeys.user._def }),
+ ]);
+ throw rejected.reason ?? new Error('Failed to undo');
+ }
+
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.all.email,
+ refetchType: 'none',
+ }),
+ queryClient.invalidateQueries({
+ queryKey: notificationKeys.user._def,
+ refetchType: 'none',
+ }),
+ ]);
+}
diff --git a/js/app/packages/core/component/Toast/Toast.tsx b/js/app/packages/core/component/Toast/Toast.tsx
index 9b5eb57317..9a195da0de 100644
--- a/js/app/packages/core/component/Toast/Toast.tsx
+++ b/js/app/packages/core/component/Toast/Toast.tsx
@@ -165,10 +165,19 @@ function success(
message: string,
subtext?: string,
actions?: ToastAction[],
- duration?: number
+ duration?: number,
+ /** When true, bypasses the 3s dedupe so repeated calls stack instead of replacing. */
+ stack?: boolean
): number | undefined {
- dismissIfRecent(message, ToastType.SUCCESS);
- return createToast(message, ToastType.SUCCESS, subtext, actions, duration);
+ if (!stack) dismissIfRecent(message, ToastType.SUCCESS);
+ return createToast(
+ message,
+ ToastType.SUCCESS,
+ subtext,
+ actions,
+ duration,
+ stack
+ );
}
function dismiss(toastId: number) {
@@ -189,26 +198,22 @@ function alert(message: string, subtext?: string, duration?: number) {
// ─── Shared actions row ──────────────────────────────────────────────────────
-function ActionsRow(props: { actions: ToastAction[] }) {
+function ActionButtons(props: { actions: ToastAction[] }) {
return (
- <div class="flex flex-row flex-wrap justify-end gap-2 mt-2">
- <For each={props.actions}>
- {(action) => (
- <Button
- onClick={action.onClick}
- variant="secondary"
- class="flex items-center gap-1.5 rounded py-1.5 px-3 text-sm font-semibold"
- >
- <Show when={action.icon}>
- {(icon) => (
- <Dynamic component={icon()} class="size-3.5 shrink-0" />
- )}
- </Show>
- {action.label}
- </Button>
- )}
- </For>
- </div>
+ <For each={props.actions}>
+ {(action) => (
+ <Button
+ onClick={action.onClick}
+ variant="secondary"
+ class="flex items-center gap-1.5 rounded py-1 px-2 text-sm font-semibold shrink-0"
+ >
+ <Show when={action.icon}>
+ {(icon) => <Dynamic component={icon()} class="size-3.5 shrink-0" />}
+ </Show>
+ {action.label}
+ </Button>
+ )}
+ </For>
);
}
@@ -335,6 +340,9 @@ function ToastContent(props: {
<Toast.Title class="font-semibold text-ink grow shrink truncate">
{customConfig().title}
</Toast.Title>
+ <Show when={customConfig().actions?.length}>
+ <ActionButtons actions={customConfig().actions!} />
+ </Show>
<Toast.CloseButton>
<Button variant="ghost" size="icon-sm" class="rounded-xs">
<XIcon />
@@ -344,9 +352,6 @@ function ToastContent(props: {
<Show when={customConfig().content}>
<div class="my-2 ml-7">{customConfig().content?.()}</div>
</Show>
- <Show when={customConfig().actions?.length}>
- <ActionsRow actions={customConfig().actions!} />
- </Show>
</>
)}
</Match>
@@ -373,6 +378,9 @@ function ToastContent(props: {
<Toast.Title class="font-semibold text-ink grow shrink truncate">
{props.message}
</Toast.Title>
+ <Show when={props.actions?.length}>
+ <ActionButtons actions={props.actions!} />
+ </Show>
<Toast.CloseButton>
<Button variant="ghost" size="icon-sm" class="rounded-xs">
<XIcon />
@@ -384,9 +392,6 @@ function ToastContent(props: {
{props.subtext}
</Toast.Description>
</Show>
- <Show when={props.actions?.length}>
- <ActionsRow actions={props.actions!} />
- </Show>
</>
)}
</Match>
@@ -472,19 +477,18 @@ function createToast(
actions?: ToastAction[],
// When undefined, the toast auto-dismisses after a default delay but shows NO progress bar.
// When explicitly set, the toast uses that duration AND shows the progress bar.
- duration?: number
+ duration?: number,
+ /** Skip recentToasts tracking so this toast never dedupes against a future call. */
+ stack?: boolean
) {
- const key = createToastKey(message, toastType);
-
- const existingToast = recentToasts.get(key);
- if (existingToast?.timeoutId) {
- clearTimeout(existingToast.timeoutId);
+ if (!stack) {
+ const key = createToastKey(message, toastType);
+ const existingToast = recentToasts.get(key);
+ if (existingToast?.timeoutId) {
+ clearTimeout(existingToast.timeoutId);
+ }
}
- const timeoutId = setTimeout(() => {
- recentToasts.delete(key);
- }, THROTTLE_DURATION);
-
const toastId = toaster.show(
(props) => (
<ToastContent
@@ -501,15 +505,21 @@ function createToast(
{ region: 'toast-region' }
);
- recentToasts.set(key, {
- message,
- toastType,
- timestamp: Date.now(),
- timeoutId,
- toastId,
- subtext,
- actions,
- });
+ if (!stack) {
+ const key = createToastKey(message, toastType);
+ const timeoutId = setTimeout(() => {
+ recentToasts.delete(key);
+ }, THROTTLE_DURATION);
+ recentToasts.set(key, {
+ message,
+ toastType,
+ timestamp: Date.now(),
+ timeoutId,
+ toastId,
+ subtext,
+ actions,
+ });
+ }
return toastId;
}
diff --git a/js/app/packages/entity/src/extractors-notification/mobile-notification-stacks.tsx b/js/app/packages/entity/src/extractors-notification/mobile-notification-stacks.tsx
index 654db0b2a5..8c27453f95 100644
--- a/js/app/packages/entity/src/extractors-notification/mobile-notification-stacks.tsx
+++ b/js/app/packages/entity/src/extractors-notification/mobile-notification-stacks.tsx
@@ -3,7 +3,6 @@ import { reconcile, createStore } from 'solid-js/store';
import {
type NotificationStack,
getMostRecentNotification,
- getAllNotificationsFromGroup,
openNotification,
} from '@notifications';
import { globalSplitManager } from '@app/signal/splitLayout';
@@ -15,8 +14,8 @@ import { Entity } from '../entity';
import { UnreadIndicator } from '../components/UnreadIndicator';
import { EntityRow, EntityRowContext } from '@app/component/mobile/EntityRow';
import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
-import { toast } from '@core/component/Toast/Toast';
import { cn } from '@ui/utils/classname';
+import { useNotificationStackActions } from './notification-actions';
import { NotificationContent } from './notification-content';
import { NotificationTimestamp } from './notification-timestamp';
@@ -88,15 +87,15 @@ function MobileStackRow(props: {
}) {
const ctx = useContext(EntityRowContext);
const notificationSource = useGlobalNotificationSource();
+ const { markStackAsDone } = useNotificationStackActions({
+ stack: props.stack,
+ });
const stackEntityId = () => getMostRecentNotification(props.stack).id;
const unread = () => isNotificationUnread(props.stack);
const handleSwipeLeft = async () => {
await ctx?.collapseEntity(stackEntityId());
- void notificationSource.bulkMarkAsDone(
- getAllNotificationsFromGroup(props.stack)
- );
- toast.success('Marked as done');
+ markStackAsDone();
};
const handleClick = async (e: MouseEvent) => {
diff --git a/js/app/packages/entity/src/extractors-notification/notification-actions.tsx b/js/app/packages/entity/src/extractors-notification/notification-actions.tsx
index bc1c908343..75f98e3319 100644
--- a/js/app/packages/entity/src/extractors-notification/notification-actions.tsx
+++ b/js/app/packages/entity/src/extractors-notification/notification-actions.tsx
@@ -1,7 +1,14 @@
-import type { NotificationStack } from '@notifications';
-import type { UnifiedNotification } from '@notifications';
-import { getAllNotificationsFromGroup } from '@notifications';
+import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
+import { toast } from '@core/component/Toast/Toast';
+import type { NotificationStack, UnifiedNotification } from '@notifications';
+import {
+ executeMarkNotificationsDone,
+ executeMarkNotificationsUndone,
+ getAllNotificationsFromGroup,
+} from '@notifications';
+import { useMutationUndoContext, useUndoableMutation } from '@queries/undo';
import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
+import { restoreSoupFocus } from '@app/component/next-soup/utils';
interface NotificationActionsProps {
stack: NotificationStack;
@@ -15,13 +22,52 @@ interface SingleNotificationActionsProps {
onMarkAsRead?: () => void;
}
+type MarkStackDoneVariables = { notificationIds: string[] };
+
export function useNotificationStackActions(props: NotificationActionsProps) {
const notificationSource = useGlobalNotificationSource();
+ const undoCtx = useMutationUndoContext();
+
+ const mutation = useUndoableMutation<void, Error, MarkStackDoneVariables>(
+ () => ({
+ mutationFn: async (vars) =>
+ await executeMarkNotificationsDone(vars.notificationIds),
+ onSuccess: () => {
+ const toastId = toast.success(
+ 'Marked as done',
+ undefined,
+ [
+ {
+ label: 'Undo',
+ icon: ArrowCounterClockwise,
+ onClick: () => {
+ if (toastId != null) toast.dismiss(toastId);
+ undoCtx.undo({
+ onError: () => toast.failure('Failed to undo'),
+ });
+ restoreSoupFocus();
+ },
+ },
+ ],
+ 10_000,
+ true
+ );
+ props.onMarkAsDone?.();
+ },
+ onError: () => {
+ toast.failure('Failed to mark as done');
+ },
+ undoFn: async (vars) =>
+ await executeMarkNotificationsUndone(vars.notificationIds),
+ redoFn: async (vars) =>
+ await executeMarkNotificationsDone(vars.notificationIds),
+ undoLabel: 'Mark Done',
+ })
+ );
- const markStackAsDone = async () => {
+ const markStackAsDone = () => {
const notifications = getAllNotificationsFromGroup(props.stack);
- await notificationSource.bulkMarkAsDone(notifications);
- props.onMarkAsDone?.();
+ mutation.mutate({ notificationIds: notifications.map((n) => n.id) });
};
const markStackAsRead = async () => {
diff --git a/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx b/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx
index 5d0724d2e1..a4b607539d 100644
--- a/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx
+++ b/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx
@@ -72,9 +72,9 @@ function NotificationStackRow(props: {
props.onClick?.(e);
};
- const handleMarkAsDone = async (e?: PointerEvent | MouseEvent) => {
+ const handleMarkAsDone = (e?: PointerEvent | MouseEvent) => {
e?.stopPropagation();
- await markStackAsDone();
+ markStackAsDone();
};
const handleMarkAsRead = async () => {
diff --git a/js/app/packages/notifications/index.ts b/js/app/packages/notifications/index.ts
index f34a235d5a..f46e0847a8 100644
--- a/js/app/packages/notifications/index.ts
+++ b/js/app/packages/notifications/index.ts
@@ -20,6 +20,8 @@ export { createTabLeaderSignal } from './notification-election';
export {
createEffectOnEntityTypeNotification,
entityHasUnreadNotifications,
+ executeMarkNotificationsDone,
+ executeMarkNotificationsUndone,
markNotificationForEntityIdAsRead,
markNotificationsForEntityAsDone,
markNotificationsForEntityAsRead,
@@ -66,7 +68,10 @@ export type {
} from './notification-settings';
export { useNotificationSettings } from './notification-settings';
export type { NotificationSource } from './notification-source';
-export { createNotificationSource } from './notification-source';
+export {
+ createNotificationSource,
+ setDoneOverride,
+} from './notification-source';
export type { NotificationStack } from './notification-stacking';
export {
getAllNotificationsFromGroup,
diff --git a/js/app/packages/notifications/notification-helpers.ts b/js/app/packages/notifications/notification-helpers.ts
index a5e2de587c..3f80e63edf 100644
--- a/js/app/packages/notifications/notification-helpers.ts
+++ b/js/app/packages/notifications/notification-helpers.ts
@@ -1,7 +1,13 @@
import type { Entity, EntityType } from '@core/types';
+import { queryClient } from '@queries/client';
+import { notificationKeys } from '@queries/notification/keys';
+import {
+ bulkMarkNotificationsAsDone,
+ bulkMarkNotificationsAsUndone,
+} from '@queries/notification/user-notifications';
import { type Accessor, createEffect, createMemo, onCleanup } from 'solid-js';
import { isMatching, P } from 'ts-pattern';
-import { CHANNEL_EVENT_TYPES } from './notification-source';
+import { CHANNEL_EVENT_TYPES, setDoneOverride } from './notification-source';
import type { NotificationSource } from './notification-source';
import { type UnifiedNotification, compositeEntity } from './types';
@@ -201,6 +207,52 @@ export function useNotificationsMutedForEntity(
);
}
+/**
+ * Optimistically flips the `done` override to `true` for these ids, fires the
+ * bulk-done API, and rolls the override back on failure. Used as a mutation's
+ * mutationFn / redoFn.
+ */
+export async function executeMarkNotificationsDone(
+ notificationIds: string[]
+): Promise<void> {
+ setDoneOverride(notificationIds, true);
+ await queryClient.cancelQueries({ queryKey: notificationKeys.user._def });
+ try {
+ await bulkMarkNotificationsAsDone(notificationIds);
+ } catch (err) {
+ setDoneOverride(notificationIds, false);
+ throw err;
+ } finally {
+ await queryClient.invalidateQueries({
+ queryKey: notificationKeys.user._def,
+ refetchType: 'none',
+ });
+ }
+}
+
+/**
+ * Optimistically flips the override to `false` and fires the bulk-undone API.
+ * On failure the override is re-applied so the UI stays consistent with the
+ * server. Used as a mutation's undoFn.
+ */
+export async function executeMarkNotificationsUndone(
+ notificationIds: string[]
+): Promise<void> {
+ setDoneOverride(notificationIds, false);
+ await queryClient.cancelQueries({ queryKey: notificationKeys.user._def });
+ try {
+ await bulkMarkNotificationsAsUndone(notificationIds);
+ } catch (err) {
+ setDoneOverride(notificationIds, true);
+ throw err;
+ } finally {
+ await queryClient.invalidateQueries({
+ queryKey: notificationKeys.user._def,
+ refetchType: 'none',
+ });
+ }
+}
+
export function createEffectOnEntityTypeNotification(
notificationSource: NotificationSource,
type: EntityType,
diff --git a/js/app/packages/notifications/notification-source.ts b/js/app/packages/notifications/notification-source.ts
index 77b466d980..d7df423f2b 100644
--- a/js/app/packages/notifications/notification-source.ts
+++ b/js/app/packages/notifications/notification-source.ts
@@ -23,6 +23,7 @@ import {
createEffect,
createMemo,
createSignal,
+ createRoot,
} from 'solid-js';
import { reconcile } from 'solid-js/store';
import { createMutedEntitiesQuery } from './queries/muted-entities-query';
@@ -85,6 +86,29 @@ const NOTIFICATION_EVENT_TYPE = 'notification';
const QUERY_LIMIT = 500;
+// Persistent overrides for the `done` flag that survive cache writes.
+// In-flight infinite-query page fetches can land after an optimistic cache
+// flip and overwrite it with stale server data; this map keeps the UI
+// consistent regardless of what the cache says.
+const [doneOverrides, setDoneOverrides] = createRoot(() =>
+ createSignal<ReadonlyMap<string, boolean>>(new Map())
+);
+
+export function setDoneOverride(
+ ids: readonly string[],
+ done: boolean | undefined
+) {
+ if (ids.length === 0) return;
+ setDoneOverrides((prev) => {
+ const next = new Map(prev);
+ for (const id of ids) {
+ if (done === undefined) next.delete(id);
+ else next.set(id, done);
+ }
+ return next;
+ });
+}
+
export function createNotificationSource(
ws: ConnectionGatewayWebsocket,
onNotification?: (notification: UnifiedNotification) => void
@@ -99,9 +123,35 @@ export function createNotificationSource(
const markNotificationsAsSeenMutation = useMarkNotificationsAsSeenMutation();
const markNotificationsAsDoneMutation = useMarkNotificationsAsDoneMutation();
- const notifications = createMemo(() =>
- notificationsQuery.isSuccess ? notificationsQuery.data : []
- );
+ const notifications = createMemo(() => {
+ if (!notificationsQuery.isSuccess) return [];
+ const raw = notificationsQuery.data;
+ const overrides = doneOverrides();
+ if (overrides.size === 0) return raw;
+ return raw.map((n) => {
+ const override = overrides.get(n.id);
+ return override !== undefined ? { ...n, done: override } : n;
+ });
+ });
+
+ // Prune overrides for notifications that are no longer in the query cache
+ // (aged out of QUERY_LIMIT, deleted server-side) so the map doesn't grow
+ // unbounded. Overrides whose value happens to match the cache are NOT
+ // pruned — during an in-flight mutation the cache may still hold the
+ // pre-mutation value and a stale fetch could flip it back before the
+ // API lands.
+ createEffect(() => {
+ if (!notificationsQuery.isSuccess) return;
+ const raw = notificationsQuery.data;
+ const overrides = doneOverrides();
+ if (overrides.size === 0) return;
+ const presentIds = new Set(raw.map((n) => n.id));
+ const toPrune: string[] = [];
+ for (const id of overrides.keys()) {
+ if (!presentIds.has(id)) toPrune.push(id);
+ }
+ if (toPrune.length > 0) setDoneOverride(toPrune, undefined);
+ });
const notificationsByEntity = createMemo(() => {
const data = notifications();
diff --git a/js/app/packages/queries/notification/user-notifications.ts b/js/app/packages/queries/notification/user-notifications.ts
index 98d382bd9c..317cbf895b 100644
--- a/js/app/packages/queries/notification/user-notifications.ts
+++ b/js/app/packages/queries/notification/user-notifications.ts
@@ -192,6 +192,30 @@ export function invalidateUserNotifications() {
});
}
+/** Plain-async wrapper around `bulkMarkNotificationAsDone`. Throws on failure. */
+export async function bulkMarkNotificationsAsDone(
+ notificationIds: string[]
+): Promise<void> {
+ await throwOnErr(
+ async () =>
+ await notificationServiceClient.bulkMarkNotificationAsDone({
+ notificationIds,
+ })
+ );
+}
+
+/** Plain-async wrapper around `bulkMarkNotificationAsUndone`. Throws on failure. */
+export async function bulkMarkNotificationsAsUndone(
+ notificationIds: string[]
+): Promise<void> {
+ await throwOnErr(
+ async () =>
+ await notificationServiceClient.bulkMarkNotificationAsUndone({
+ notificationIds,
+ })
+ );
+}
+
export function invalidateEntityNotifications(eventItemId: string) {
return queryClient.invalidateQueries({
queryKey: [...notificationKeys.entity._def, eventItemId],
@@ -439,5 +463,11 @@ export function optimisticInsertNotification(
);
}
- invalidateUserNotifications();
+ // Cache is already updated via setQueriesData above. Mark as stale without
+ // refetching — refetchType default would re-fetch every cached page of the
+ // infinite notification query for every incoming websocket notification.
+ queryClient.invalidateQueries({
+ queryKey: notificationKeys.user._def,
+ refetchType: 'none',
+ });
}
diff --git a/js/app/packages/service-clients/service-notification/client.ts b/js/app/packages/service-clients/service-notification/client.ts
index 3388b708fd..2cf64b8ac3 100644
--- a/js/app/packages/service-clients/service-notification/client.ts
+++ b/js/app/packages/service-clients/service-notification/client.ts
@@ -173,6 +173,16 @@ export const notificationServiceClient = {
(result) => result
);
},
+ async bulkMarkNotificationAsUndone(args: NotificationBulkRequest) {
+ const { notificationIds } = args;
+ return mapOk(
+ await notificationFetch<any>(`/user_notifications/bulk/undone`, {
+ method: 'PATCH',
+ body: JSON.stringify({ notificationIds }),
+ }),
+ (result) => result
+ );
+ },
async markNotificationEntityAsSeen(args: WithEventItemId) {
const { event_item_id } = args;
return mapOk(