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(notifications): stop stale fetches clobbering channel mark-read (#4867)

gbirman3058a40d8820
diff --git a/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx b/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx
index a193bbd77e..9a933b230b 100644
--- a/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx
+++ b/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx
@@ -5,7 +5,9 @@ import {
} from '@notifications/notification-helpers';
import type { UnifiedNotification } from '@notifications/types';
import type { JSXElement } from 'solid-js';
-import { createEffect } from 'solid-js';
+import { createEffect, createSignal } from 'solid-js';
+
+const MAX_MARK_ATTEMPTS = 3;
export function MarkMessageNotifications(props: {
messageId: string;
@@ -21,15 +23,28 @@ export function MarkMessageNotifications(props: {
isChannelNotification(n) &&
n.notification_metadata.content.messageId === props.messageId;
- let marked = false;
+ // Not a one-shot latch: a stale refetch can land after the optimistic write
+ // and flip the notification back to unviewed while this row stays mounted,
+ // so re-mark whenever the cache regresses, bounded per mount. inFlight is a
+ // signal so a regression that lands mid-mark re-runs the effect on settle.
+ const [inFlight, setInFlight] = createSignal(false);
+ let attempts = 0;
createEffect(() => {
- if (marked) return;
const existing = notifications().find(isMessageNotification);
- if (existing && !existing.viewed_at) {
- marked = true;
- notificationSource.markAsRead(existing);
+ if (
+ !existing ||
+ existing.viewed_at ||
+ inFlight() ||
+ attempts >= MAX_MARK_ATTEMPTS
+ ) {
+ return;
}
+ attempts += 1;
+ setInFlight(true);
+ notificationSource.markAsRead(existing).finally(() => {
+ setInFlight(false);
+ });
});
return <>{props.children}</>;
diff --git a/apps/web/src/features/notifications/notification-helpers.ts b/apps/web/src/features/notifications/notification-helpers.ts
index 45982d32d7..f561e754f6 100644
--- a/apps/web/src/features/notifications/notification-helpers.ts
+++ b/apps/web/src/features/notifications/notification-helpers.ts
@@ -224,7 +224,6 @@ export async function executeMarkNotificationsDone(
notificationIds: string[]
): Promise<void> {
setDoneOverride(notificationIds, true);
- await queryClient.cancelQueries({ queryKey: notificationKeys.user._def });
try {
await bulkMarkNotificationsAsDone(notificationIds);
} catch (err) {
@@ -247,7 +246,6 @@ export async function executeMarkNotificationsUndone(
notificationIds: string[]
): Promise<void> {
setDoneOverride(notificationIds, false);
- await queryClient.cancelQueries({ queryKey: notificationKeys.user._def });
try {
await bulkMarkNotificationsAsUndone(notificationIds);
} catch (err) {
diff --git a/apps/web/src/features/notifications/notification-source.ts b/apps/web/src/features/notifications/notification-source.ts
index a99bb1ce80..7d1d365a21 100644
--- a/apps/web/src/features/notifications/notification-source.ts
+++ b/apps/web/src/features/notifications/notification-source.ts
@@ -115,6 +115,29 @@ export function setDoneOverride(
});
}
+// Client-asserted seen state, the `doneOverrides` twin for `viewed_at`. Seen
+// is monotone (there is no unsee API), so once a mark is initiated no fetch
+// snapshot may present the notification as unread: a full refetch reads its
+// pages over several seconds and a page read before the mark's POST commits
+// resurrects pre-write state when it lands. Entries are removed on mutation
+// failure (that rollback is deliberate) and pruned once the cache confirms
+// the seen state at a quiet moment.
+const [seenOverrides, setSeenOverrides] = createRoot(() =>
+ createSignal<ReadonlyMap<string, string>>(new Map())
+);
+
+function setSeenOverride(ids: readonly string[], viewedAt: string | undefined) {
+ if (ids.length === 0) return;
+ setSeenOverrides((prev) => {
+ const next = new Map(prev);
+ for (const id of ids) {
+ if (viewedAt === undefined) next.delete(id);
+ else next.set(id, viewedAt);
+ }
+ return next;
+ });
+}
+
export function createNotificationSource(
ws: ConnectionGatewayWebsocket,
onNotification?: (notification: UnifiedNotification) => void
@@ -129,14 +152,25 @@ export function createNotificationSource(
const markNotificationsAsSeenMutation = useMarkNotificationsAsSeenMutation();
const markNotificationsAsDoneMutation = useMarkNotificationsAsDoneMutation();
+ // Gate on data presence, not isSuccess: a failed or cancelled background
+ // refetch flips status to error while the cached pages remain, and blanking
+ // every unread surface over a transient refetch is worse than showing the
+ // cached state.
const notifications = createMemo(() => {
- if (!notificationsQuery.isSuccess) return [];
const raw = notificationsQuery.data;
- const overrides = doneOverrides();
- if (overrides.size === 0) return raw;
+ if (!raw) return [];
+ const done = doneOverrides();
+ const seen = seenOverrides();
+ if (done.size === 0 && seen.size === 0) return raw;
return raw.map((n) => {
- const override = overrides.get(n.id);
- return override !== undefined ? { ...n, done: override } : n;
+ const doneOverride = done.get(n.id);
+ const seenOverride = n.viewed_at ? undefined : seen.get(n.id);
+ if (doneOverride === undefined && seenOverride === undefined) return n;
+ return {
+ ...n,
+ ...(doneOverride !== undefined ? { done: doneOverride } : {}),
+ ...(seenOverride !== undefined ? { viewed_at: seenOverride } : {}),
+ };
});
});
@@ -147,8 +181,8 @@ export function createNotificationSource(
// pre-mutation value and a stale fetch could flip it back before the
// API lands.
createEffect(() => {
- if (!notificationsQuery.isSuccess) return;
const raw = notificationsQuery.data;
+ if (!raw) return;
const overrides = doneOverrides();
if (overrides.size === 0) return;
const presentIds = new Set(raw.map((n) => n.id));
@@ -159,6 +193,29 @@ export function createNotificationSource(
if (toPrune.length > 0) setDoneOverride(toPrune, undefined);
});
+ // Prune seen overrides once they stop being load-bearing: the id left the
+ // cache, or the cache row itself is seen at a quiet moment. Quiet matters —
+ // while a mark is in flight the seen cache row is the optimistic write, and
+ // a fetch that is still running may hold a pre-write snapshot that will
+ // land later; in both cases the override must survive.
+ createEffect(() => {
+ const raw = notificationsQuery.data;
+ if (!raw) return;
+ const seen = seenOverrides();
+ if (seen.size === 0) return;
+ const quiet =
+ !notificationsQuery.isFetching &&
+ !markNotificationsAsSeenMutation.isPending;
+ const byId = new Map(raw.map((n) => [n.id, n]));
+ const toPrune: string[] = [];
+ for (const id of seen.keys()) {
+ const row = byId.get(id);
+ if (!row) toPrune.push(id);
+ else if (row.viewed_at && quiet) toPrune.push(id);
+ }
+ if (toPrune.length > 0) setSeenOverride(toPrune, undefined);
+ });
+
const notificationsByEntity = createMemo(() => {
const data = notifications();
const grouped: NotificationsByEntity = {};
@@ -173,7 +230,7 @@ export function createNotificationSource(
});
createEffect(() => {
- if (!notificationsQuery.isSuccess) return;
+ if (!notificationsQuery.data) return;
if (notificationsQuery.hasNextPage && !notificationsQuery.isFetching) {
notificationsQuery.fetchNextPage();
}
@@ -241,16 +298,35 @@ export function createNotificationSource(
optimisticInsertNotification(parsedNotification);
});
+ // Skip empty batches: entity-level read markers fire on mount regardless
+ // of whether the entity has notifications, and an empty batch would still
+ // POST a no-op mutation.
const bulkMarkAsDone = async (notifications: UnifiedNotification[]) => {
- await markNotificationsAsDoneMutation.mutateAsync({
- notificationIds: notifications.map((n) => n.id),
- });
+ if (notifications.length === 0) return;
+ const ids = notifications.map((n) => n.id);
+ setDoneOverride(ids, true);
+ try {
+ await markNotificationsAsDoneMutation.mutateAsync({
+ notificationIds: ids,
+ });
+ } catch (err) {
+ setDoneOverride(ids, false);
+ throw err;
+ }
};
const bulkMarkAsRead = async (notifications: UnifiedNotification[]) => {
- await markNotificationsAsSeenMutation.mutateAsync({
- notificationIds: notifications.map((n) => n.id),
- });
+ if (notifications.length === 0) return;
+ const ids = notifications.map((n) => n.id);
+ setSeenOverride(ids, new Date().toISOString());
+ try {
+ await markNotificationsAsSeenMutation.mutateAsync({
+ notificationIds: ids,
+ });
+ } catch (err) {
+ setSeenOverride(ids, undefined);
+ throw err;
+ }
};
const markAsDone = async (notification: UnifiedNotification) => {
diff --git a/apps/web/src/lib/queries/notification/user-notifications.ts b/apps/web/src/lib/queries/notification/user-notifications.ts
index ffce795d1e..baeb952c74 100644
--- a/apps/web/src/lib/queries/notification/user-notifications.ts
+++ b/apps/web/src/lib/queries/notification/user-notifications.ts
@@ -34,6 +34,88 @@ const DEFAULT_NOTIFICATION_LIMIT = 20;
const NOTIFICATION_STALE_TIME = 5 * 60 * 1000; // 5 minutes
const NOTIFICATION_GC_TIME = 10 * 60 * 1000; // 10 minutes
+// Websocket-inserted notifications young enough that a fetch snapshot may
+// predate them: a full refetch reads its pages over several seconds and
+// commits atomically, so a snapshot begun before the insert lands without
+// the row and would silently drop it from the cache. A query-cache
+// subscription re-prepends tracked rows after every non-manual success
+// commit (solid-query hard-disables structuralSharing, so a commit-time
+// merge hook is not available). Entries retire by TTL, realtime delete, or
+// done removal — not by cache containment, since our own optimistic writes
+// also contain the row and are not server confirmation.
+const UNCONFIRMED_INSERT_TTL_MS = 5 * 60 * 1000;
+const MAX_UNCONFIRMED_INSERTS = 200;
+const unconfirmedInserts = new Map<
+ string,
+ { item: NotificationItem; insertedAt: number }
+>();
+
+let unconfirmedInsertsSubscribed = false;
+
+// Subscribed lazily on the first tracked insert so importing this module
+// never touches the query client (test setups mock it after import).
+function ensureUnconfirmedInsertReapply() {
+ if (unconfirmedInsertsSubscribed || typeof window === 'undefined') return;
+ unconfirmedInsertsSubscribed = true;
+ queryClient.getQueryCache().subscribe((event) => {
+ if (event.type !== 'updated') return;
+ const action = event.action as { type: string; manual?: boolean };
+ if (action.type !== 'success' || action.manual) return;
+ const key = event.query.queryKey;
+ if (!Array.isArray(key) || key[0] !== 'notification' || key[1] !== 'user')
+ return;
+ reapplyUnconfirmedInserts(key);
+ });
+}
+
+function trackUnconfirmedInsert(item: NotificationItem) {
+ ensureUnconfirmedInsertReapply();
+ unconfirmedInserts.delete(item.id);
+ unconfirmedInserts.set(item.id, { item, insertedAt: Date.now() });
+ while (unconfirmedInserts.size > MAX_UNCONFIRMED_INSERTS) {
+ const oldest = unconfirmedInserts.keys().next().value;
+ if (oldest === undefined) break;
+ unconfirmedInserts.delete(oldest);
+ }
+}
+
+function retireUnconfirmedInserts(ids: Iterable<string>) {
+ for (const id of ids) unconfirmedInserts.delete(id);
+}
+
+function pruneExpiredUnconfirmedInserts() {
+ const now = Date.now();
+ for (const [id, entry] of unconfirmedInserts) {
+ if (now - entry.insertedAt > UNCONFIRMED_INSERT_TTL_MS) {
+ unconfirmedInserts.delete(id);
+ }
+ }
+}
+
+function reapplyUnconfirmedInserts(queryKey: readonly unknown[]) {
+ pruneExpiredUnconfirmedInserts();
+ if (unconfirmedInserts.size === 0) return;
+ queryClient.setQueryData<NotificationData<UserNotificationsPageParam>>(
+ queryKey,
+ (data) => {
+ if (!data?.pages?.length) return data;
+ const presentIds = new Set(
+ data.pages.flatMap((page) => page.items.map((n) => n.id))
+ );
+ const missing = [...unconfirmedInserts.values()]
+ .map((entry) => entry.item)
+ .filter((item) => !presentIds.has(item.id));
+ if (missing.length === 0) return data;
+ return {
+ ...data,
+ pages: data.pages.map((page, index) =>
+ index === 0 ? { ...page, items: [...missing, ...page.items] } : page
+ ),
+ };
+ }
+ );
+}
+
function normalizeLimit(limit?: number): number {
return limit && limit > 0 && limit <= 500
? limit
@@ -281,15 +363,17 @@ function notificationsMutationSuccessCallback<T>(
});
}
-/** Creates an optimistic update handler that snapshots previous data for rollback. */
+/**
+ * Creates an optimistic update handler that snapshots previous data for
+ * rollback. In-flight fetches are deliberately left alone: seen/done
+ * overrides and unconfirmed-insert preservation make a completing stale
+ * snapshot harmless, so refetches always run to completion and freshness is
+ * never sacrificed for write consistency.
+ */
function createNotificationsMutateFn(
updaterFn: NotificationsUpdater
): NotificationsOnMutateFn {
return async (params) => {
- await queryClient.cancelQueries({
- queryKey: notificationKeys.user._def,
- });
-
const previousData = queryClient.getQueriesData<
NotificationData<UserNotificationsPageParam>
>({
@@ -391,6 +475,10 @@ const filterOutDoneNotifications = (
);
};
+const markNotificationsAsDoneMutateFn = createNotificationsMutateFn(
+ filterOutDoneNotifications
+);
+
/** Marks notifications as done (removes from list) with optimistic update. */
export const useMarkNotificationsAsDoneMutation = createNotificationsMutation(
async (params: NotificationsMutationParams) =>
@@ -398,7 +486,10 @@ export const useMarkNotificationsAsDoneMutation = createNotificationsMutation(
notificationIds: params.notificationIds,
}),
{
- onMutate: createNotificationsMutateFn(filterOutDoneNotifications),
+ onMutate: async (params) => {
+ retireUnconfirmedInserts(params.notificationIds);
+ return await markNotificationsAsDoneMutateFn(params);
+ },
onError: notificationsMutationErrorFn,
}
);
@@ -489,6 +580,8 @@ export function applyNotificationStatusUpdate(
);
const removeIds = new Set([...deleteIds, ...doneIds]);
+ retireUnconfirmedInserts(removeIds);
+
queryClient.setQueriesData<NotificationData<UserNotificationsPageParam>>(
{ queryKey: notificationKeys.user._def },
(data) => {
@@ -624,6 +717,8 @@ export function optimisticInsertNotification(
const item = notification as NotificationItem;
const soupTag = notificationEntityTypeToSoupTag(notification.entity_type);
+ trackUnconfirmedInsert(item);
+
queryClient.setQueriesData<NotificationData<UserNotificationsPageParam>>(
{ queryKey: notificationKeys.user._def },
(data) => {