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.

Seanaye/fix/home not updating (#6930)

Sean Ayeacc3aa14e820
diff --git a/apps/web/src/features/notifications/notification-source.ts b/apps/web/src/features/notifications/notification-source.ts
index 1c7e4735bf..cb0a64bf70 100644
--- a/apps/web/src/features/notifications/notification-source.ts
+++ b/apps/web/src/features/notifications/notification-source.ts
@@ -2,6 +2,7 @@ import { ENABLE_DOCUMENT_MENTION_NOTIFICATIONS } from '@core/constant/featureFla
import type { Entity } from '@core/types';
import { muteItemForRef } from '@entity/utils/notification';
import { createSocketEffect } from '@macro-inc/collaboration/websocket';
+import { updateSoupForNotification } from '@queries/notification/notification-soup';
import {
useMuteItemMutation,
useUnmuteItemMutation,
@@ -412,7 +413,9 @@ export function createNotificationSource(
if (!usesGraphql()) return;
scheduleGraphqlNotificationRefetch();
if (patch.__typename !== 'GraphqlNewNotification') return;
- dispatchIncomingNotification(mapGraphqlNotification(patch.notification));
+ const notification = mapGraphqlNotification(patch.notification);
+ updateSoupForNotification(notification);
+ dispatchIncomingNotification(notification);
}
);
onCleanup(() => {
@@ -457,11 +460,12 @@ export function createNotificationSource(
console.error('Failed to parse notification', wsData.data, e);
return;
}
- dispatchIncomingNotification(parsedNotification);
-
+ // Apply optimistic Soup writes before callbacks start list revalidation;
+ // otherwise those writes cancel the refetch triggered by this delivery.
if (notificationsQuery.transport === 'rest') {
optimisticInsertNotification(parsedNotification);
}
+ dispatchIncomingNotification(parsedNotification);
});
// Skip empty batches: entity-level read markers fire on mount regardless
diff --git a/apps/web/src/features/notifications/tests/notification-source.test.ts b/apps/web/src/features/notifications/tests/notification-source.test.ts
index 18634646d5..5318762961 100644
--- a/apps/web/src/features/notifications/tests/notification-source.test.ts
+++ b/apps/web/src/features/notifications/tests/notification-source.test.ts
@@ -26,6 +26,7 @@ const mocks = vi.hoisted(() => ({
mutedEntitiesQuery: {} as Record<string, unknown>,
notificationsQuery: {} as Record<string, unknown>,
optimisticInsertNotification: vi.fn(),
+ updateSoupForNotification: vi.fn(),
socketCallback: undefined as
| ((data: { type: string; data: string }) => void)
| undefined,
@@ -58,6 +59,10 @@ vi.mock('@macro-inc/collaboration/websocket', () => ({
),
}));
+vi.mock('@queries/notification/notification-soup', () => ({
+ updateSoupForNotification: mocks.updateSoupForNotification,
+}));
+
vi.mock('@queries/notification/user-notifications', () => ({
optimisticInsertNotification: mocks.optimisticInsertNotification,
useMarkNotificationsAsDoneMutation: () => mocks.doneMutation,
@@ -128,6 +133,7 @@ describe('createNotificationSource', () => {
mocks.graphqlPatchCallback = undefined;
mocks.socketCallback = undefined;
mocks.optimisticInsertNotification.mockReset();
+ mocks.updateSoupForNotification.mockReset();
mocks.seenMutation.mutateAsync.mockReset().mockResolvedValue(undefined);
mocks.doneMutation.mutateAsync.mockReset().mockResolvedValue(undefined);
mocks.mutedEntitiesQuery = {
@@ -180,6 +186,7 @@ describe('createNotificationSource', () => {
});
await Promise.resolve();
expect(receive).toHaveBeenCalledWith(incoming);
+ expect(mocks.updateSoupForNotification).toHaveBeenCalledWith(incoming);
expect(started).toBe(false);
expect(dataRead).not.toHaveBeenCalled();
expect(refetch).not.toHaveBeenCalled();
@@ -941,6 +948,12 @@ describe('createNotificationSource', () => {
expect(onNotification).toHaveBeenCalledWith(incoming);
expect(subscriber).toHaveBeenCalledOnce();
expect(subscriber).toHaveBeenCalledWith(incoming);
+ expect(mocks.updateSoupForNotification).toHaveBeenCalledExactlyOnceWith(
+ incoming
+ );
+ expect(
+ mocks.updateSoupForNotification.mock.invocationCallOrder[0]
+ ).toBeLessThan(subscriber.mock.invocationCallOrder[0]);
expect(refetch).not.toHaveBeenCalled();
await Promise.resolve();
expect(refetch).toHaveBeenCalledOnce();
@@ -1056,6 +1069,10 @@ describe('createNotificationSource', () => {
});
expect(onNotification).toHaveBeenCalledOnce();
expect(mocks.optimisticInsertNotification).toHaveBeenCalledOnce();
+ expect(
+ mocks.optimisticInsertNotification.mock.invocationCallOrder[0]
+ ).toBeLessThan(onNotification.mock.invocationCallOrder[0]);
+ expect(mocks.updateSoupForNotification).not.toHaveBeenCalled();
} finally {
dispose();
}
diff --git a/apps/web/src/lib/queries/notification/notification-soup.ts b/apps/web/src/lib/queries/notification/notification-soup.ts
new file mode 100644
index 0000000000..d689367565
--- /dev/null
+++ b/apps/web/src/lib/queries/notification/notification-soup.ts
@@ -0,0 +1,81 @@
+import { channelThreadRootId } from '@notifications/channel-thread-root';
+import type { UnifiedNotification } from '@notifications/types';
+import { match, P } from 'ts-pattern';
+import {
+ bumpSoupEntityNotifiedAt,
+ hasSoupEntity,
+ optimisticUpdateSoupItemUpdatedAt,
+ refetchSoupEntity,
+ restoreSoupEntityToDoneFilteredQueries,
+ type SoupEntityTag,
+} from '../soup/normalized-cache';
+
+function notificationEntityTypeToSoupTag(
+ entityType: UnifiedNotification['entity_type']
+): SoupEntityTag | null {
+ return match(entityType)
+ .with('document', () => 'document' as const)
+ .with('chat', () => 'chat' as const)
+ .with('channel', () => 'channel' as const)
+ .with('project', () => 'project' as const)
+ .with('email_thread', () => 'emailThread' as const)
+ .with('foreign_entity', () => 'foreignEntity' as const)
+ .with('reminder', () => 'reminder' as const)
+ .with('calendar_event', () => 'calendarEvent' as const)
+ .with('agent_session', () => 'agentSession' as const)
+ .with(
+ P.union(
+ 'user',
+ 'team',
+ 'call',
+ 'channel_message',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ 'skill',
+ 'scheduled_action',
+ 'initiative'
+ ),
+ () => null
+ )
+ .exhaustive();
+}
+
+/** Keep REST-backed Home rows live even when notifications use GraphQL. */
+export function updateSoupForNotification(notification: UnifiedNotification) {
+ const soupTag = notificationEntityTypeToSoupTag(notification.entity_type);
+ if (!soupTag) return;
+
+ if (hasSoupEntity(notification.entity_id)) {
+ if (notification.created_at) {
+ optimisticUpdateSoupItemUpdatedAt(
+ notification.entity_id,
+ soupTag,
+ notification.created_at
+ );
+ }
+ } else {
+ void refetchSoupEntity(notification.entity_id, soupTag);
+ }
+
+ // Mentions and replies belong to the thread's Home row, not the channel's.
+ // The floor also protects against older pages that are already in flight.
+ const threadRootId = channelThreadRootId(notification);
+ if (notification.created_at) {
+ bumpSoupEntityNotifiedAt(
+ threadRootId ?? notification.entity_id,
+ notification.created_at
+ );
+ }
+ if (threadRootId && !hasSoupEntity(threadRootId)) {
+ void refetchSoupEntity(threadRootId, 'channelThread');
+ }
+
+ // A field merge cannot restore a cached row removed by a done filter.
+ if (notification.state !== 'done') {
+ restoreSoupEntityToDoneFilteredQueries(
+ threadRootId ?? notification.entity_id,
+ notification.state
+ );
+ }
+}
diff --git a/apps/web/src/lib/queries/notification/user-notifications.ts b/apps/web/src/lib/queries/notification/user-notifications.ts
index 918c159e1d..fe096ade73 100644
--- a/apps/web/src/lib/queries/notification/user-notifications.ts
+++ b/apps/web/src/lib/queries/notification/user-notifications.ts
@@ -5,21 +5,12 @@ import {
} from '@core/constant/featureFlags';
import type { Maybe } from '@core/types';
import { throwOnErr } from '@core/util/result';
-import { channelThreadRootId } from '@notifications/channel-thread-root';
import {
nextNotificationState,
notificationStatesForFilter,
} from '@notifications/notification-state';
import type { UnifiedNotification } from '@notifications/types';
import { refreshActiveGraphqlSoupQueries } from '@queries/soup/graphql/active-queries';
-import {
- bumpSoupEntityNotifiedAt,
- hasSoupEntity,
- optimisticUpdateSoupItemUpdatedAt,
- refetchSoupEntity,
- restoreSoupEntityToDoneFilteredQueries,
- type SoupEntityTag,
-} from '@queries/soup/normalized-cache';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { notificationServiceClient } from '@service-notification/client';
import type { ApiUserNotification } from '@service-notification/generated/schemas/apiUserNotification';
@@ -34,7 +25,6 @@ import {
useMutation,
} from '@tanstack/solid-query';
import { type Accessor, createSignal, untrack } from 'solid-js';
-import { match, P } from 'ts-pattern';
import { z } from 'zod';
import { queryClient } from '../client';
import {
@@ -43,6 +33,7 @@ import {
type UpdateNotificationsResult,
} from './graphql/user-notifications';
import { notificationKeys } from './keys';
+import { updateSoupForNotification } from './notification-soup';
function stripOwnerId({
owner_id: _,
@@ -930,37 +921,6 @@ export async function getNotificationById(
return stripOwnerId(res as NotificationItem);
}
-function notificationEntityTypeToSoupTag(
- entityType: UnifiedNotification['entity_type']
-): SoupEntityTag | null {
- return match(entityType)
- .with('document', () => 'document' as const)
- .with('chat', () => 'chat' as const)
- .with('channel', () => 'channel' as const)
- .with('project', () => 'project' as const)
- .with('email_thread', () => 'emailThread' as const)
- .with('foreign_entity', () => 'foreignEntity' as const)
- .with('reminder', () => 'reminder' as const)
- .with('calendar_event', () => 'calendarEvent' as const)
- .with('agent_session', () => 'agentSession' as const)
- .with(
- P.union(
- 'user',
- 'team',
- 'call',
- 'channel_message',
- 'static_file',
- 'crm_company',
- 'crm_contact',
- 'skill',
- 'scheduled_action',
- 'initiative'
- ),
- () => null
- )
- .exhaustive();
-}
-
/**
* Snapshot the cached notification objects for the given ids. The returned
* items can later be put back via `restoreUserNotifications`. Optimistic
@@ -1088,7 +1048,6 @@ export function optimisticInsertNotification(
notification: UnifiedNotification
) {
const item = notification as NotificationItem;
- const soupTag = notificationEntityTypeToSoupTag(notification.entity_type);
trackUnconfirmedInsert(item);
@@ -1133,48 +1092,7 @@ export function optimisticInsertNotification(
};
});
- if (soupTag) {
- if (hasSoupEntity(notification.entity_id)) {
- if (notification.created_at) {
- optimisticUpdateSoupItemUpdatedAt(
- notification.entity_id,
- soupTag,
- notification.created_at
- );
- }
- } else {
- refetchSoupEntity(notification.entity_id, soupTag);
- }
-
- // The inbox's notified_at order moves the notified row up right away
- // rather than on the next refetch of the page. A mention or thread reply
- // belongs to its channel-thread row — the row the soup feed keys it on —
- // so that is the row stamped (and fetched in, when it is not cached yet),
- // not the channel's.
- const threadRootId = channelThreadRootId(notification);
- if (notification.created_at) {
- bumpSoupEntityNotifiedAt(
- threadRootId ?? notification.entity_id,
- notification.created_at
- );
- }
- if (threadRootId && !hasSoupEntity(threadRootId)) {
- refetchSoupEntity(threadRootId, 'channelThread');
- }
-
- // A cached row may be absent from the done-filtered feeds — dropped when
- // it was marked done, or the feed was fetched while it had nothing
- // outstanding. The field merges above only patch rows already present,
- // so put the row back where it is missing; otherwise this notification
- // stays invisible in the inbox until the next refetch. No-op for rows
- // the refetch paths above insert.
- if (notification.state !== 'done') {
- restoreSoupEntityToDoneFilteredQueries(
- threadRootId ?? notification.entity_id,
- notification.state
- );
- }
- }
+ updateSoupForNotification(notification);
// Cache is already updated via setQueriesData above. Mark as stale without
// refetching — refetchType default would re-fetch every cached page of the
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/notified-floor.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/notified-floor.test.ts
index 4e9b3f797b..73a7465441 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/notified-floor.test.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/notified-floor.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
clearNotifiedFloors,
raiseNotifiedFloor,
@@ -7,6 +7,7 @@ import {
afterEach(() => {
clearNotifiedFloors();
+ vi.useRealTimers();
});
describe('notified floors', () => {
@@ -35,15 +36,40 @@ describe('notified floors', () => {
expect(resolveNotifiedAt('e-1', null)).toBe('2026-09-02T17:00:00Z');
});
- it('clears once the server catches up', () => {
+ it('survives optimistic reads and older responses arriving after a fresh snapshot', () => {
raiseNotifiedFloor('e-1', '2026-09-02T17:00:00Z');
+ // Mapping the local write must not acknowledge it as server confirmation.
+ expect(resolveNotifiedAt('e-1', '2026-09-02T17:00:00Z')).toBe(
+ '2026-09-02T17:00:00Z'
+ );
expect(resolveNotifiedAt('e-1', '2026-09-02T17:00:00.000123Z')).toBe(
'2026-09-02T17:00:00.000123Z'
);
- // The floor is gone: subsequent reads are pass-through.
expect(resolveNotifiedAt('e-1', '2026-09-01T00:00:00Z')).toBe(
- '2026-09-01T00:00:00Z'
+ '2026-09-02T17:00:00Z'
);
});
+
+ it('expires without duplicate or older deliveries extending retention', () => {
+ vi.useFakeTimers();
+ raiseNotifiedFloor('e-1', '2026-09-02T17:00:00Z');
+ vi.advanceTimersByTime(4 * 60 * 1000);
+ raiseNotifiedFloor('e-1', '2026-09-02T17:00:00Z');
+ raiseNotifiedFloor('e-1', '2026-09-02T16:00:00Z');
+ expect(resolveNotifiedAt('e-1', null)).toBe('2026-09-02T17:00:00Z');
+ vi.advanceTimersByTime(60 * 1000);
+ expect(resolveNotifiedAt('e-1', null)).toBeNull();
+ });
+
+ it('bounds retained stamps and keeps the most recently advanced entities', () => {
+ for (let i = 0; i < 200; i++) {
+ raiseNotifiedFloor(`e-${i}`, '2026-09-02T16:00:00Z');
+ }
+ raiseNotifiedFloor('e-0', '2026-09-02T17:00:00Z');
+ raiseNotifiedFloor('new', '2026-09-02T17:00:00Z');
+ expect(resolveNotifiedAt('e-1', null)).toBeNull();
+ expect(resolveNotifiedAt('e-0', null)).toBe('2026-09-02T17:00:00Z');
+ expect(resolveNotifiedAt('new', null)).toBe('2026-09-02T17:00:00Z');
+ });
});
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/notified-floor.ts b/apps/web/src/lib/queries/soup/normalized-cache/notified-floor.ts
index 02c553d47b..174b2568c2 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/notified-floor.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/notified-floor.ts
@@ -10,7 +10,12 @@
import { createStampFloors } from './stamp-floors';
-const notifiedFloors = createStampFloors();
+// Entity mappers read both network and optimistic snapshots. Reading our own
+// stamp must not retire the guard before a replica-stale refetch completes.
+const NOTIFIED_FLOOR_RETENTION_MS = 5 * 60 * 1000;
+const notifiedFloors = createStampFloors({
+ retainForMs: NOTIFIED_FLOOR_RETENTION_MS,
+});
/** Record a delivered notification's time as the entity's floor. */
export function raiseNotifiedFloor(entityId: string, notifiedAt: string): void {
@@ -18,8 +23,9 @@ export function raiseNotifiedFloor(entityId: string, notifiedAt: string): void {
}
/**
- * Resolve the effective notified_at for an entity: the server value unless a
- * newer floor exists. Clears the floor once the server catches up.
+ * Resolve the effective notified_at for an entity: the snapshot value unless
+ * a newer delivered stamp exists. Retained briefly across optimistic reads
+ * and overlapping refetches; bounded by age and entity count.
*/
export function resolveNotifiedAt(
entityId: string,
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.realtime.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.realtime.test.ts
new file mode 100644
index 0000000000..4f82147978
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.realtime.test.ts
@@ -0,0 +1,255 @@
+/** @vitest-environment jsdom */
+import type { UnifiedNotification } from '@notifications/types';
+import type { SoupApiItem } from '@service-storage/generated/schemas';
+import {
+ type InfiniteData,
+ QueryClient,
+ QueryObserver,
+} from '@tanstack/solid-query';
+import { ok } from 'neverthrow';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+let testQueryClient: QueryClient;
+const getSoupItems = vi.hoisted(() => vi.fn());
+vi.mock('../../client', () => ({
+ get queryClient() {
+ return testQueryClient;
+ },
+}));
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: { getSoupItems },
+}));
+vi.mock('../graphql/active-queries', () => ({
+ refreshActiveGraphqlSoupQueries: vi.fn(),
+}));
+
+import { updateSoupForNotification } from '../../notification/notification-soup';
+import type { SoupAstItemsFlatPage } from '../items';
+import { soupKeys } from '../keys';
+import { getSoupNormalizer, initSoupNormalizer } from './normalizer';
+import { clearNotifiedFloors, resolveNotifiedAt } from './notified-floor';
+import {
+ getSoupEntityById,
+ invalidateSoupEntity,
+ refetchSoupEntity,
+ removeSoupEntitiesFromDoneFilteredQueries,
+} from './operations';
+
+type HomeData = InfiniteData<SoupAstItemsFlatPage, unknown>;
+const OLD = '2026-09-22T12:00:00.000Z';
+const NEW = '2026-09-24T12:00:00.000Z';
+const homeKey = soupKeys.astItems({
+ params: { expand: true, limit: 100, sort_method: 'notified_at' },
+ body: { chanf: { l: { NotificationState: 'unseen' } } },
+}).queryKey;
+
+function channel(updatedAt: string, notifiedAt?: string): SoupApiItem {
+ return {
+ tag: 'channel',
+ frecency_score: 1,
+ is_favorited: false,
+ ...(notifiedAt ? { notified_at: notifiedAt } : {}),
+ data: {
+ channel: {
+ id: 'channel-1',
+ name: 'Live notification test',
+ channel_type: 'direct_message',
+ owner_id: 'macro|[email protected]',
+ created_at: OLD,
+ updated_at: updatedAt,
+ },
+ participants: [],
+ },
+ };
+}
+
+function page(items: SoupApiItem[]): HomeData {
+ return {
+ pages: [{ kind: 'flat', items, nextCursor: null }],
+ pageParams: [null],
+ };
+}
+
+function notification(createdAt = NEW): UnifiedNotification {
+ return {
+ id: `notification-${createdAt}`,
+ entity_id: 'channel-1',
+ entity_type: 'channel',
+ created_at: createdAt,
+ updated_at: createdAt,
+ viewed_at: null,
+ state: 'unseen',
+ sent: true,
+ notification_event_type: 'channel_message_send',
+ notification_metadata: {
+ tag: 'channel_message_send',
+ content: {
+ sender: 'macro|[email protected]',
+ messageId: 'message-1',
+ messageContent: 'Live notification test',
+ channelType: 'directMessage',
+ },
+ },
+ };
+}
+
+let cleanup: Array<() => void>;
+beforeEach(() => {
+ getSoupItems.mockReset();
+ testQueryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ cleanup = [initSoupNormalizer(testQueryClient)];
+});
+afterEach(() => {
+ for (const dispose of cleanup.reverse()) dispose();
+ testQueryClient.clear();
+ clearNotifiedFloors();
+});
+
+function mountHome(items = [channel(OLD, OLD)]) {
+ let resolve!: (data: HomeData) => void;
+ const response = new Promise<HomeData>((r) => {
+ resolve = r;
+ });
+ let signal: AbortSignal | undefined;
+ const queryFn = vi.fn(async (context: { signal: AbortSignal }) => {
+ signal = context.signal;
+ return await response;
+ });
+ const observer = new QueryObserver(testQueryClient, {
+ queryKey: homeKey,
+ queryFn,
+ meta: { normalize: true },
+ initialData: page(items),
+ });
+ cleanup.push(observer.subscribe(() => {}));
+ // A success event indexes dependencies in the real Normy cache.
+ testQueryClient.setQueryData(homeKey, page(items));
+ return { observer, queryFn, resolve, signal: () => signal };
+}
+
+function homeItems() {
+ return testQueryClient.getQueryData<HomeData>(homeKey)!.pages[0].items;
+}
+
+function cacheChannelOutsideHome() {
+ // Another list keeps the channel normalized after Home removes it.
+ testQueryClient.setQueryDefaults(['soup', 'items', 'other'], {
+ meta: { normalize: true },
+ });
+ testQueryClient.setQueryData(
+ ['soup', 'items', 'other'],
+ page([channel(OLD)])
+ );
+}
+
+describe('Home notification revalidation with real normalized query keys', () => {
+ it('invalidates complete JSON-roundtripped keys with undefined optional slots', async () => {
+ const home = mountHome();
+ const [key] = getSoupNormalizer().getDependentQueriesByIds([
+ 'soup:channel-1',
+ ]);
+ expect(homeKey.slice(-2)).toEqual([undefined, undefined]);
+ expect(key.slice(-2)).toEqual([null, null]);
+ expect(testQueryClient.getQueryCache().findAll({ queryKey: key })).toEqual(
+ []
+ );
+
+ invalidateSoupEntity('channel-1');
+ expect(home.queryFn).toHaveBeenCalledOnce();
+ home.resolve(page([channel(NEW, NEW)]));
+ await vi.waitFor(() => expect(homeItems()[0].notified_at).toBe(NEW));
+ });
+
+ it('keeps a slow Home refetch alive when single-entity hydration finishes first', async () => {
+ const home = mountHome();
+ const refetch = testQueryClient.invalidateQueries({
+ queryKey: homeKey,
+ exact: true,
+ });
+ expect(home.queryFn).toHaveBeenCalledOnce();
+ getSoupItems.mockResolvedValue(ok({ items: [channel(NEW)] }));
+
+ await refetchSoupEntity('channel-1', 'channel');
+
+ expect(home.signal()?.aborted).toBe(false);
+ expect(home.observer.getCurrentResult().fetchStatus).toBe('fetching');
+ // A single-entity response has no notification stamp; only the list does.
+ expect(homeItems()[0].notified_at).toBe(OLD);
+ home.resolve(page([channel(NEW, NEW)]));
+ await refetch;
+ expect(homeItems()[0].notified_at).toBe(NEW);
+ });
+
+ it('stamps Home immediately without inserting into the REST notification feed', () => {
+ mountHome();
+ updateSoupForNotification(notification());
+ expect(homeItems()[0].notified_at).toBe(NEW);
+ expect(
+ testQueryClient.getQueryCache().findAll({ queryKey: ['notification'] })
+ ).toEqual([]);
+
+ updateSoupForNotification(notification(OLD));
+ expect(homeItems()[0].notified_at).toBe(NEW);
+ });
+
+ it('keeps delivered recency when a replica-stale Home response arrives after the optimistic read', async () => {
+ const home = mountHome();
+ updateSoupForNotification(notification());
+ expect(resolveNotifiedAt('channel-1', homeItems()[0].notified_at)).toBe(
+ NEW
+ );
+ const refetch = testQueryClient.invalidateQueries({
+ queryKey: homeKey,
+ exact: true,
+ });
+ home.resolve(page([channel(NEW, OLD)]));
+ await refetch;
+ expect(resolveNotifiedAt('channel-1', homeItems()[0].notified_at)).toBe(
+ NEW
+ );
+ });
+
+ it('keeps a restored done-filtered row when its notification-triggered refetch omits it', async () => {
+ const home = mountHome();
+ cacheChannelOutsideHome();
+ testQueryClient.setQueryData(homeKey, page([]));
+ expect(getSoupEntityById('channel-1')).toBeDefined();
+
+ updateSoupForNotification(notification());
+
+ expect(homeItems()).toHaveLength(1);
+ // Non-notified lists omit the stamp; Home's entity mapper applies its
+ // delivered-notification floor when the cached row is restored.
+ expect(resolveNotifiedAt('channel-1', homeItems()[0].notified_at)).toBe(
+ NEW
+ );
+
+ // Notification callbacks revalidate after restoring the row. The replica
+ // may still return the done-filtered page from before this notification.
+ invalidateSoupEntity('channel-1');
+ expect(home.queryFn).toHaveBeenCalledOnce();
+ home.resolve(page([]));
+ await vi.waitFor(() =>
+ expect(home.observer.getCurrentResult().fetchStatus).toBe('idle')
+ );
+ expect(homeItems()).toHaveLength(1);
+ });
+
+ it('does not resurrect a restored row that the user marks done again', async () => {
+ const home = mountHome([]);
+ cacheChannelOutsideHome();
+ updateSoupForNotification(notification());
+ expect(homeItems()).toHaveLength(1);
+
+ removeSoupEntitiesFromDoneFilteredQueries(new Set(['channel-1']));
+ const refetch = testQueryClient.invalidateQueries({
+ queryKey: homeKey,
+ exact: true,
+ });
+ home.resolve(page([]));
+ await refetch;
+ expect(homeItems()).toEqual([]);
+ });
+});
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
index 030b42a769..b53e438efd 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
@@ -38,6 +38,7 @@ import {
} from './normalizer';
import { raiseNotifiedFloor } from './notified-floor';
import { ownTouchStamp } from './own-touch';
+import { retainRestoredSoupItem } from './restored-membership';
import type {
SoupEntityPartial,
SoupEntityTag,
@@ -79,6 +80,14 @@ function cancelSoupQueries() {
export function optimisticUpdateSoupEntity<T extends SoupEntityTag>(
partial: SoupEntityPartial<T>
+): SoupTransaction {
+ return updateSoupEntity(partial, true);
+}
+
+/** Server hydration must not cancel the list revalidation it accompanies. */
+function updateSoupEntity<T extends SoupEntityTag>(
+ partial: SoupEntityPartial<T>,
+ cancelRefetches: boolean
): SoupTransaction {
const normalizer = getSoupNormalizer();
const normKey = getNormalizationObjectKey(partial);
@@ -92,7 +101,7 @@ export function optimisticUpdateSoupEntity<T extends SoupEntityTag>(
// list refetching on mount): the fetch dies and nothing retries it.
// Skip cold initial fetches (data === undefined); cancelling those can leave
// the query stuck pending, which is why cancelSoupQueries has the same guard.
- for (const queryKey of dependentKeys) {
+ for (const queryKey of cancelRefetches ? dependentKeys : []) {
if (
partialMatchKey(queryKey, soupKeys.items._def) ||
partialMatchKey(queryKey, soupKeys.astItems._def)
@@ -184,9 +193,9 @@ export function bumpSoupEntityTouchedAt(
* without waiting for a refetch. Newest wins: an out-of-order delivery never
* moves a row back down. The stamp is also recorded as a floor (see
* `notified-floor.ts`) so a notified page that was in flight when the
- * notification landed cannot overwrite it with the previous stamp; the floor
- * clears once the server's value catches up. Non-notified responses omit the
- * field, so the field-merge never clears the stamp either.
+ * notification landed cannot overwrite it with the previous stamp. The floor
+ * survives optimistic reads and overlapping refreshes for a bounded interval.
+ * Non-notified responses omit the field, so field merges preserve the stamp.
*/
export function bumpSoupEntityNotifiedAt(
entityId: string,
@@ -231,7 +240,9 @@ export function invalidateSoupEntity(entityId: string): void {
const normalizer = getSoupNormalizer();
const keys = normalizer.getDependentQueriesByIds([soupNormKey(entityId)]);
for (const queryKey of keys) {
- queryClient.invalidateQueries({ queryKey });
+ // Normy JSON-roundtrips complete keys, turning undefined array slots into
+ // null. Exact matching uses the same hash; partial matching misses them.
+ void queryClient.invalidateQueries({ queryKey, exact: true });
}
}
@@ -578,6 +589,7 @@ export function restoreSoupEntityToDoneFilteredQueries(
index === 0 ? { ...page, items: [item, ...page.items] } : page
),
});
+ retainRestoredSoupItem(queryClient, key, item);
}
for (const [
@@ -613,6 +625,7 @@ export function restoreSoupEntityToDoneFilteredQueries(
: page
),
});
+ retainRestoredSoupItem(queryClient, key, item);
continue;
}
@@ -828,7 +841,7 @@ export async function refetchSoupEntity(
item = { ...item, touched_at: ownTouchStamp(itemId) };
}
if (hasSoupEntity(itemId)) {
- optimisticUpdateSoupEntity(item);
+ updateSoupEntity(item, false);
} else {
insertSoupEntity(item);
if (options?.created) continue;
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/restored-membership.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/restored-membership.test.ts
new file mode 100644
index 0000000000..9148495fea
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/normalized-cache/restored-membership.test.ts
@@ -0,0 +1,139 @@
+/** @vitest-environment jsdom */
+import type { SoupApiItem } from '@service-storage/generated/schemas';
+import { QueryClient, type QueryKey } from '@tanstack/solid-query';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { retainRestoredSoupItem } from './restored-membership';
+
+const item: SoupApiItem = {
+ tag: 'channel',
+ frecency_score: 1,
+ is_favorited: false,
+ data: {
+ channel: {
+ id: 'channel-1',
+ name: 'Restored conversation',
+ channel_type: 'direct_message',
+ owner_id: 'macro|[email protected]',
+ created_at: '2026-09-24T12:00:00Z',
+ updated_at: '2026-09-24T12:00:00Z',
+ },
+ participants: [],
+ },
+};
+const key = ['soup', 'astItems', {}, {}, undefined, undefined];
+const data = (...pages: SoupApiItem[][]) => ({
+ pages: pages.map((items) => ({
+ kind: 'flat' as const,
+ items,
+ nextCursor: null,
+ })),
+ pageParams: pages.map((_, index) => index),
+});
+let client: QueryClient;
+beforeEach(() => {
+ client = new QueryClient();
+});
+afterEach(() => {
+ client.clear();
+ vi.useRealTimers();
+});
+
+function retain(queryKey: QueryKey = key) {
+ const query = client.getQueryCache().build(client, {
+ queryKey,
+ initialData: data([item]),
+ });
+ retainRestoredSoupItem(client, queryKey, item);
+ return query;
+}
+
+describe('retained notification-driven flat Soup membership', () => {
+ it('survives repeated stale successes without replacing cursors or later pages', () => {
+ const query = retain();
+ const stale = data([], []);
+ query.setData(stale);
+ expect(query.state.data).toEqual({
+ ...stale,
+ pages: [{ ...stale.pages[0], items: [item] }, stale.pages[1]],
+ });
+ query.setData(data([item]));
+ query.setData(stale);
+ expect(query.state.data?.pages[0].items).toEqual([item]);
+ });
+
+ it('does not duplicate a restored item returned on a continuation page', () => {
+ const query = retain();
+ const response = data([], [item]);
+ query.setData(response);
+ expect(query.state.data).toEqual(response);
+ });
+
+ it('honors a later explicit local removal instead of restoring it again', () => {
+ const query = retain();
+ query.setData(data([]), { manual: true });
+ query.setData(data([]));
+ expect(query.state.data?.pages[0].items).toEqual([]);
+ });
+
+ it('retains the latest local entity snapshot', () => {
+ const query = retain();
+ const updated: SoupApiItem = { ...item, is_favorited: true };
+ query.setData(data([updated]), { manual: true });
+ query.setData(data([]));
+ expect(query.state.data?.pages[0].items).toEqual([updated]);
+ });
+
+ it.each(['itemFilter', 'insertFilter'] as const)(
+ 'rechecks the current %s before replaying membership',
+ (filter) => {
+ const query = retain();
+ query.setOptions({ ...query.options, meta: { [filter]: () => false } });
+ query.setData(data([]));
+ expect(query.state.data?.pages[0].items).toEqual([]);
+ }
+ );
+
+ it('does not leak admission to a different query or query client', () => {
+ retain();
+ const otherFilter = client.getQueryCache().build(client, {
+ queryKey: [...key, 'other-filter'],
+ initialData: data([]),
+ });
+ otherFilter.setData(data([]));
+ expect(otherFilter.state.data?.pages[0].items).toEqual([]);
+
+ const otherClient = new QueryClient();
+ try {
+ const otherUser = otherClient.getQueryCache().build(otherClient, {
+ queryKey: key,
+ initialData: data([]),
+ });
+ otherUser.setData(data([]));
+ expect(otherUser.state.data?.pages[0].items).toEqual([]);
+ } finally {
+ otherClient.clear();
+ }
+ });
+
+ it('forgets restores when the query is removed', () => {
+ retain();
+ client.removeQueries({ queryKey: key, exact: true });
+ const replacement = client.getQueryCache().build(client, {
+ queryKey: key,
+ initialData: data([]),
+ });
+ replacement.setData(data([]));
+ expect(replacement.state.data?.pages[0].items).toEqual([]);
+ });
+
+ it('expires admission even if stale successes keep arriving', () => {
+ vi.useFakeTimers();
+ const query = retain();
+ vi.advanceTimersByTime(4 * 60 * 1000);
+ query.setData(data([]));
+ expect(query.state.data?.pages[0].items).toEqual([item]);
+ vi.advanceTimersByTime(60 * 1000);
+ query.setData(data([]));
+ expect(query.state.data?.pages[0].items).toEqual([]);
+ });
+});
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/restored-membership.ts b/apps/web/src/lib/queries/soup/normalized-cache/restored-membership.ts
new file mode 100644
index 0000000000..64331d0279
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/normalized-cache/restored-membership.ts
@@ -0,0 +1,118 @@
+import type { SoupApiItem } from '@service-storage/generated/schemas';
+import type {
+ InfiniteData,
+ Query,
+ QueryCache,
+ QueryClient,
+ QueryKey,
+} from '@tanstack/solid-query';
+import { getNormalizationObjectKey } from './normalizer';
+import { getSoupQueryMeta } from './utils';
+
+type FlatSoupData = InfiniteData<{ items: SoupApiItem[] }, unknown>;
+type RetainedItem = { item: SoupApiItem; expiresAt: number };
+
+// Bookkeeping belongs to individual queries, not entity IDs across users or
+// filter scopes. Removing a query releases its restores with it.
+const caches = new WeakMap<
+ QueryCache,
+ WeakMap<Query, Map<string, RetainedItem>>
+>();
+const RETENTION_MS = 5 * 60 * 1000;
+const MAX_RESTORED_ITEMS = 200;
+
+function isFlatSoupData(data: unknown): data is FlatSoupData {
+ return (
+ data !== null &&
+ typeof data === 'object' &&
+ 'pages' in data &&
+ Array.isArray(data.pages) &&
+ data.pages.length > 0 &&
+ data.pages.every((page) => Array.isArray(page?.items))
+ );
+}
+
+function acceptsItem(query: Query, item: SoupApiItem): boolean {
+ const { itemFilter, insertFilter } = getSoupQueryMeta(query.meta);
+ return (
+ (!itemFilter || itemFilter(item)) && (!insertFilter || insertFilter(item))
+ );
+}
+
+function restoresForCache(cache: QueryCache) {
+ const existing = caches.get(cache);
+ if (existing) return existing;
+
+ const queries = new WeakMap<Query, Map<string, RetainedItem>>();
+ caches.set(cache, queries);
+ cache.subscribe((event) => {
+ if (event.type === 'removed') {
+ queries.delete(event.query);
+ return;
+ }
+ if (event.type !== 'updated' || event.action.type !== 'success') return;
+ const retained = queries.get(event.query);
+ if (!retained?.size) return;
+ const data = event.query.state.data;
+ if (!isFlatSoupData(data)) return;
+
+ const present = new Map(
+ data.pages.flatMap((page) =>
+ page.items.map(
+ (item) => [getNormalizationObjectKey(item), item] as const
+ )
+ )
+ );
+ const missing: SoupApiItem[] = [];
+ for (const [id, entry] of retained) {
+ const item = present.get(id);
+ if (
+ entry.expiresAt <= Date.now() ||
+ !acceptsItem(event.query, item ?? entry.item) ||
+ (event.action.manual && !item)
+ ) {
+ // Explicit local removal (done, delete, move) beats an earlier restore.
+ retained.delete(id);
+ } else if (item) {
+ entry.item = item;
+ } else {
+ missing.push(entry.item);
+ }
+ }
+ if (!missing.length) return;
+
+ // Network success must not drop an admitted row just because a replica
+ // still sees it as done. Do not cancel or restart the completed fetch.
+ event.query.setData(
+ {
+ ...data,
+ pages: data.pages.map((page, index) =>
+ index === 0 ? { ...page, items: [...missing, ...page.items] } : page
+ ),
+ },
+ { manual: true, updatedAt: event.query.state.dataUpdatedAt }
+ );
+ });
+ return queries;
+}
+
+/** Protect a just-restored flat Soup row from overlapping stale list results. */
+export function retainRestoredSoupItem(
+ client: QueryClient,
+ key: QueryKey,
+ item: SoupApiItem
+): void {
+ const cache = client.getQueryCache();
+ const query = cache.find({ queryKey: key, exact: true });
+ const id = getNormalizationObjectKey(item);
+ if (!query || !id) return;
+ const queries = restoresForCache(cache);
+ const retained = queries.get(query) ?? new Map<string, RetainedItem>();
+ retained.delete(id);
+ retained.set(id, { item, expiresAt: Date.now() + RETENTION_MS });
+ if (retained.size > MAX_RESTORED_ITEMS) {
+ const oldest = retained.keys().next().value;
+ if (oldest !== undefined) retained.delete(oldest);
+ }
+ queries.set(query, retained);
+}
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/stamp-floors.ts b/apps/web/src/lib/queries/soup/normalized-cache/stamp-floors.ts
index 865c6e087f..9b8fb165ed 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/stamp-floors.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/stamp-floors.ts
@@ -6,50 +6,72 @@
* server recorded it and so returns the OLD value; the normalized cache's
* field-merge would let that stale page overwrite the fresher stamp. Instead
* of racing the server, stamps are recorded here and reads resolve to
- * max(server, floor); an entry clears itself the moment the server value
- * catches up, so steady-state reads are pass-through.
+ * max(server, floor). By default an entry clears when the value catches up.
+ * Consumers that also map optimistic snapshots can retain floors briefly:
+ * seeing the local stamp is not proof that an older refetch cannot arrive.
*
* Import-free on purpose: floors sit below the normalized cache, the entity
* mappers, and the list-view gates, which would otherwise form an import
* cycle.
*/
-export function createStampFloors() {
- const floors = new Map<string, string>();
+export function createStampFloors(options: { retainForMs?: number } = {}) {
+ const maxRetainedFloors = 200;
+ const floors = new Map<string, { stamp: string; expiresAt?: number }>();
+ const { retainForMs } = options;
+
+ function getFloor(entityId: string) {
+ const floor = floors.get(entityId);
+ if (floor?.expiresAt !== undefined && floor.expiresAt <= Date.now()) {
+ floors.delete(entityId);
+ return undefined;
+ }
+ return floor;
+ }
return {
/** Record `stamp` as the entity's floor unless a newer one is held. */
raise(entityId: string, stamp: string): void {
- const current = floors.get(entityId);
+ const current = getFloor(entityId);
if (
current === undefined ||
- new Date(stamp).getTime() > new Date(current).getTime()
+ new Date(stamp).getTime() > new Date(current.stamp).getTime()
) {
- floors.set(entityId, stamp);
+ floors.delete(entityId);
+ floors.set(entityId, {
+ stamp,
+ expiresAt:
+ retainForMs === undefined ? undefined : Date.now() + retainForMs,
+ });
+ // Retained floors do not clear on reads, so cap their session state.
+ if (retainForMs !== undefined && floors.size > maxRetainedFloors) {
+ const oldest = floors.keys().next().value;
+ if (oldest !== undefined) floors.delete(oldest);
+ }
}
},
/**
- * The server value unless a newer floor exists. Clears the floor once the
- * server catches up.
+ * The snapshot value unless a newer floor exists. Retained floors expire
+ * by age, not by reading an optimistic snapshot equal to the floor.
*/
resolve(
entityId: string,
serverValue: string | null | undefined
): string | null | undefined {
- const floor = floors.get(entityId);
+ const floor = getFloor(entityId);
if (floor === undefined) return serverValue;
if (
serverValue &&
- new Date(serverValue).getTime() >= new Date(floor).getTime()
+ new Date(serverValue).getTime() >= new Date(floor.stamp).getTime()
) {
- floors.delete(entityId);
+ if (retainForMs === undefined) floors.delete(entityId);
return serverValue;
}
- return floor;
+ return floor.stamp;
},
has(entityId: string): boolean {
- return floors.has(entityId);
+ return getFloor(entityId) !== undefined;
},
/** Test-only: reset all floors between cases. */
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 87ed4b61b1..7b2c547b4f 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -96,6 +96,18 @@ loading settles, including when the list itself uses REST (notified-at sorting).
Email alone is not sufficient verification: its inbox membership does not require
the global notification feed.
+Check live Home recency with two accounts: leave the recipient on Home without
+opening the conversation, then send a DM from the other account. The row should
+move into **Last few minutes** and show unread without reloading, including when
+notifications use GraphQL but Home's notified-at list uses REST. Read the DM,
+return to Home, and repeat; also check a row previously marked done and a thread
+reply. Delay the Home list response while allowing single-entity hydration to
+finish: hydration must not cancel the list refresh or leave an old notification
+timestamp. Older in-flight snapshots must not move the delivered row backward.
+Also test a stale response that entirely omits a just-restored, previously done
+row: the row must stay visible. Marking it done again must override that restore,
+and other filter scopes must not inherit the retained membership.
+
GraphQL-attached notification rows share the global feed's local seen/done
overrides: Mark Done and Undo reflect local intent without waiting for an older
cached notification snapshot to be replaced. These display overrides do not turn