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(soup): stop soup list refresh storms from notifications, agent sessions, and PR updates (#6891)

teoea7a41f9fd8a
diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.ts
index d1f26e369a..e743caf8bb 100644
--- a/apps/web/src/features/block-agent/context/pending-session.ts
+++ b/apps/web/src/features/block-agent/context/pending-session.ts
@@ -21,6 +21,7 @@
*/
import { AgentSession } from '@core/agent-session/AgentSession';
+import { refetchSoupEntity } from '@queries/soup/normalized-cache';
import { agentHarnessServiceClient } from '@service-agent-harness/client';
import type {
CreateAgentSessionRequest,
@@ -107,6 +108,7 @@ export function startPendingSession(
// Normally the id this tab minted; a service that predates the field
// mints its own, and the block adopts that one the way it always did.
const created = result.value.session.id;
+ void refetchSoupEntity(created, 'agentSession', { created: true });
// The block adopts the session the moment it exists. The first prompt
// then goes through the shared session like any other, so it is folded
// speculatively - bubble and working line on screen at once - while
diff --git a/apps/web/src/features/next-soup/filters/query-filters.test.ts b/apps/web/src/features/next-soup/filters/query-filters.test.ts
index b2fcb86e40..08ad33005f 100644
--- a/apps/web/src/features/next-soup/filters/query-filters.test.ts
+++ b/apps/web/src/features/next-soup/filters/query-filters.test.ts
@@ -156,6 +156,33 @@ describe('filterSoupItemByRequestBody', () => {
})
).toBe(false);
});
+
+ it('only accepts agent sessions when the body opts into them', () => {
+ const session = {
+ tag: 'agentSession',
+ data: { id: 'session-1', ownerId: 'macro|[email protected]' },
+ } as unknown as SoupApiItem;
+
+ expect(filterSoupItemByRequestBody(session, {})).toBe(false);
+ expect(
+ filterSoupItemByRequestBody(session, { ...QUERY_FILTERS_BASE })
+ ).toBe(false);
+ expect(
+ filterSoupItemByRequestBody(session, {
+ agent_session_filters: { include: true },
+ })
+ ).toBe(true);
+ expect(
+ filterSoupItemByRequestBody(session, {
+ agent_session_filters: { owners: ['macro|[email protected]'] },
+ })
+ ).toBe(true);
+ expect(
+ filterSoupItemByRequestBody(session, {
+ agent_session_filters: { include: true, owners: ['macro|[email protected]'] },
+ })
+ ).toBe(false);
+ });
});
describe('soupItemMatchesProjectMembership', () => {
diff --git a/apps/web/src/features/next-soup/filters/query-filters.ts b/apps/web/src/features/next-soup/filters/query-filters.ts
index ac88761470..a45e6a95ce 100644
--- a/apps/web/src/features/next-soup/filters/query-filters.ts
+++ b/apps/web/src/features/next-soup/filters/query-filters.ts
@@ -167,12 +167,20 @@ export function filterSoupItemByRequestBody(
{ tag: 'reminder' },
({ data }) => !isIdFilteredOut(body.reminder_filters?.ids, data.id)
)
- .with(
- { tag: 'agentSession' },
- ({ data }) =>
- !isIdFilteredOut(body.agent_session_filters?.ids, data.id) &&
- !isValueFilteredOut(body.agent_session_filters?.owners, data.ownerId)
- )
+ .with({ tag: 'agentSession' }, ({ data }) => {
+ const filters = body.agent_session_filters;
+ // Agent sessions are opt-in on the server: a body that neither includes
+ // them nor names ids or owners returns none.
+ const optedIn =
+ filters?.include === true ||
+ Boolean(filters?.ids?.length) ||
+ Boolean(filters?.owners?.length);
+ return (
+ optedIn &&
+ !isIdFilteredOut(filters?.ids, data.id) &&
+ !isValueFilteredOut(filters?.owners, data.ownerId)
+ );
+ })
.exhaustive();
}
diff --git a/apps/web/src/lib/queries/agent-session/list-sync.test.ts b/apps/web/src/lib/queries/agent-session/list-sync.test.ts
index 4ccc7045a3..b15a38ef4d 100644
--- a/apps/web/src/lib/queries/agent-session/list-sync.test.ts
+++ b/apps/web/src/lib/queries/agent-session/list-sync.test.ts
@@ -15,13 +15,18 @@ vi.mock('@queries/soup/refresh', () => ({
vi.mock('@queries/soup/graphql/active-queries', () => ({
refreshActiveGraphqlSoupQueries: mocks.graphql,
}));
+vi.mock('@queries/client', async () => {
+ const { QueryClient } = await import('@tanstack/query-core');
+ return { queryClient: new QueryClient() };
+});
import { refreshAgentSessionLists } from './list-sync';
+import { invalidateAgentSessionMetadata } from './session-metadata-sync';
beforeEach(() => vi.clearAllMocks());
afterEach(() => vi.restoreAllMocks());
-it('coalesces a metadata burst and refreshes both list transports', async () => {
+it('coalesces a metadata burst into one REST list refresh', async () => {
await Promise.all([
refreshAgentSessionLists('first'),
refreshAgentSessionLists('first'),
@@ -30,16 +35,16 @@ it('coalesces a metadata burst and refreshes both list transports', async () =>
expect(mocks.rest.mock.calls).toEqual([
[['first', 'second'], { throwOnError: true }],
]);
- expect(mocks.graphql).toHaveBeenCalledExactlyOnceWith({ throwOnError: true });
});
-it('reconnect refreshes all lists to recover missed events', async () => {
- await Promise.all([
- refreshAgentSessionLists('first'),
- refreshAgentSessionLists(),
- ]);
- expect(mocks.rest.mock.calls).toEqual([[undefined, { throwOnError: true }]]);
- expect(mocks.graphql).toHaveBeenCalledOnce();
+it('never network-refreshes the GraphQL soup queries', async () => {
+ await refreshAgentSessionLists('first');
+ expect(mocks.graphql).not.toHaveBeenCalled();
+});
+
+it('leaves soup lists alone when the gateway socket opens', async () => {
+ await invalidateAgentSessionMetadata();
+ expect(mocks.rest).not.toHaveBeenCalled();
});
it('does not lose metadata committed while a refresh is in flight', async () => {
@@ -53,10 +58,8 @@ it('does not lose metadata committed while a refresh is in flight', async () =>
const first = refreshAgentSessionLists('first');
await Promise.resolve();
const second = refreshAgentSessionLists('second');
- expect(mocks.graphql).toHaveBeenCalledOnce();
release();
await Promise.all([first, second]);
- expect(mocks.graphql).toHaveBeenCalledTimes(2);
expect(mocks.rest.mock.calls).toEqual([
[['first'], { throwOnError: true }],
[['second'], { throwOnError: true }],
@@ -81,26 +84,6 @@ it('retries a failed batch together with updates queued while it was in flight',
['first'],
['second', 'first'],
]);
- expect(mocks.graphql).toHaveBeenCalledTimes(2);
-});
-
-it('waits for both transports before retrying after either one fails', async () => {
- let release!: () => void;
- mocks.rest.mockRejectedValueOnce(new Error('REST outage'));
- mocks.graphql.mockImplementationOnce(
- () =>
- new Promise<void>((resolve) => {
- release = resolve;
- })
- );
- const refresh = refreshAgentSessionLists('session');
- await Promise.resolve();
- await Promise.resolve();
- expect(mocks.rest).toHaveBeenCalledOnce();
- release();
- await refresh;
- expect(mocks.rest).toHaveBeenCalledTimes(2);
- expect(mocks.graphql).toHaveBeenCalledTimes(2);
});
it('retains failed IDs after a bounded retry for the next refresh', async () => {
@@ -121,18 +104,3 @@ it('retains failed IDs after a bounded retry for the next refresh', async () =>
['failed', 'next'],
]);
});
-
-it('preserves a failed reconnect refresh across later session-specific updates', async () => {
- const error = new Error('GraphQL offline');
- const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
- mocks.graphql.mockRejectedValueOnce(error).mockRejectedValueOnce(error);
- await expect(refreshAgentSessionLists()).resolves.toBeUndefined();
-
- await refreshAgentSessionLists('next');
- expect(mocks.rest.mock.calls.map(([ids]) => ids)).toEqual([
- undefined,
- undefined,
- undefined,
- ]);
- expect(logged).toHaveBeenCalledOnce();
-});
diff --git a/apps/web/src/lib/queries/agent-session/list-sync.ts b/apps/web/src/lib/queries/agent-session/list-sync.ts
index cbae429c10..1a0e15a71e 100644
--- a/apps/web/src/lib/queries/agent-session/list-sync.ts
+++ b/apps/web/src/lib/queries/agent-session/list-sync.ts
@@ -1,31 +1,17 @@
-import { refreshActiveGraphqlSoupQueries } from '@queries/soup/graphql/active-queries';
import { refreshSoupEntities } from '@queries/soup/refresh';
const changedSessions = new Set<string>();
-let refreshAll = false;
let pending: Promise<void> | undefined;
async function refreshQueuedLists(resolve: () => void): Promise<void> {
let retryAvailable = true;
try {
- while (refreshAll || changedSessions.size) {
- const all = refreshAll;
+ while (changedSessions.size) {
const sessions = [...changedSessions];
- refreshAll = false;
changedSessions.clear();
try {
- // Wait for both transports before retrying so an older pass cannot
- // finish after its replacement and restore a stale snapshot.
- const results = await Promise.allSettled([
- refreshSoupEntities(all ? undefined : sessions, {
- throwOnError: true,
- }),
- refreshActiveGraphqlSoupQueries({ throwOnError: true }),
- ]);
- const failed = results.find((result) => result.status === 'rejected');
- if (failed?.status === 'rejected') throw failed.reason;
+ await refreshSoupEntities(sessions, { throwOnError: true });
} catch (error) {
- refreshAll ||= all;
for (const session of sessions) changedSessions.add(session);
if (!retryAvailable) throw error;
retryAvailable = false;
@@ -42,14 +28,13 @@ async function refreshQueuedLists(resolve: () => void): Promise<void> {
}
/**
- * Refresh persisted row metadata after a session update or gateway reconnect.
+ * Refresh the REST lists that show a session after its metadata changes.
* A burst shares one pass; updates committed during a fetch get a later pass.
* A failed pass retries once with queued updates. Further failures retain the
- * batch for the next event or reconnect instead of dropping it or spinning.
+ * batch for the next event instead of dropping it or spinning.
*/
-export function refreshAgentSessionLists(sessionId?: string): Promise<void> {
- if (sessionId) changedSessions.add(sessionId);
- else refreshAll = true;
+export function refreshAgentSessionLists(sessionId: string): Promise<void> {
+ changedSessions.add(sessionId);
if (!pending) {
pending = new Promise<void>((resolve) => {
diff --git a/apps/web/src/lib/queries/agent-session/session-metadata-sync.ts b/apps/web/src/lib/queries/agent-session/session-metadata-sync.ts
index 37106a5e44..57dfb5ca6f 100644
--- a/apps/web/src/lib/queries/agent-session/session-metadata-sync.ts
+++ b/apps/web/src/lib/queries/agent-session/session-metadata-sync.ts
@@ -53,8 +53,5 @@ export async function handleAgentSessionUpdated(
export async function invalidateAgentSessionMetadata(): Promise<void> {
const filters = { queryKey: agentSessionKeys.detail._def };
await queryClient.cancelQueries(filters);
- await Promise.all([
- queryClient.invalidateQueries(filters),
- refreshAgentSessionLists(),
- ]);
+ await queryClient.invalidateQueries(filters);
}
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
index f6877cb0d9..7b75f28183 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
@@ -14,6 +14,19 @@ let testQueryClient: QueryClient;
const getSoupItemsMock = vi.hoisted(() => vi.fn());
const refreshActiveGraphqlSoupQueriesMock = vi.hoisted(() => vi.fn());
+const graphqlSoup = vi.hoisted(() => ({ enabled: false }));
+
+vi.mock('@core/constant/featureFlags', async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import('@core/constant/featureFlags')>();
+ return {
+ ...actual,
+ isFeatureEnabled: (flag: Parameters<typeof actual.isFeatureEnabled>[0]) =>
+ flag === actual.enableGraphqlSoup
+ ? graphqlSoup.enabled
+ : actual.isFeatureEnabled(flag),
+ };
+});
vi.mock('@service-storage/client', () => ({
storageServiceClient: { getSoupItems: getSoupItemsMock },
@@ -191,6 +204,7 @@ function getSearchQuery() {
beforeEach(() => {
vi.clearAllMocks();
+ graphqlSoup.enabled = false;
getSoupItemsMock.mockResolvedValue({
isErr: () => false,
value: { items: [] },
@@ -303,6 +317,66 @@ describe('refetchSoupEntity', () => {
expect(refreshActiveGraphqlSoupQueriesMock).not.toHaveBeenCalled();
expect(getSoupItemsMock).toHaveBeenCalledOnce();
});
+
+ describe('when GraphQL owns the soup lists', () => {
+ beforeEach(() => {
+ graphqlSoup.enabled = true;
+ getSoupItemsMock.mockResolvedValue({
+ isErr: () => false,
+ value: { items: [mockDocumentItem('doc-new')] },
+ });
+ });
+ afterEach(() => {
+ mockNormalizer.getObjectById.mockReturnValue(null);
+ });
+
+ it('neither fetches nor invalidates REST lists for an entity no REST list holds', async () => {
+ seedSoupQuery(mockSoupCache([[mockDocumentItem('d-1')]]));
+
+ await refetchSoupEntity('doc-new', 'document');
+
+ expect(getSoupItemsMock).not.toHaveBeenCalled();
+ expect(testQueryClient.getQueryState(soupSeedKey)?.isInvalidated).toBe(
+ false
+ );
+ expect(getSoupQuery()?.pages[0].items.map(getSoupItemId)).toEqual([
+ 'd-1',
+ ]);
+ });
+
+ it('still refetches an entity a REST list already holds', async () => {
+ mockNormalizer.getObjectById.mockReturnValue(mockDocumentItem('doc-new'));
+
+ await refetchSoupEntity('doc-new', 'document');
+
+ expect(getSoupItemsMock).toHaveBeenCalledOnce();
+ });
+
+ it('inserts a just-created entity into REST lists without refetching them', async () => {
+ seedSoupQuery(mockSoupCache([[mockDocumentItem('d-1')]]));
+
+ await refetchSoupEntity('doc-new', 'document', { created: true });
+
+ expect(getSoupQuery()?.pages[0].items.map(getSoupItemId)).toEqual([
+ 'doc-new',
+ 'd-1',
+ ]);
+ expect(testQueryClient.getQueryState(soupSeedKey)?.isInvalidated).toBe(
+ false
+ );
+ });
+
+ it('still inserts own-touch creations into REST lists', async () => {
+ seedSoupQuery(mockSoupCache([[mockDocumentItem('d-1')]]));
+
+ await refetchSoupEntity('doc-new', 'document', { ownTouch: true });
+
+ expect(getSoupQuery()?.pages[0].items.map(getSoupItemId)).toEqual([
+ 'doc-new',
+ 'd-1',
+ ]);
+ });
+ });
});
describe('insertSoupEntity', () => {
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 fa39654e0d..030b42a769 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
@@ -1,5 +1,8 @@
import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';
-
+import {
+ enableGraphqlSoup,
+ isFeatureEnabled,
+} from '@core/constant/featureFlags';
import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
import type {
PostSoupRequest,
@@ -768,6 +771,10 @@ export function removeSearchEntities(entityIds: Set<string>): SoupTransaction {
* `refreshGraphql` also network-refreshes mounted GraphQL Soup operations.
* REST's normalized entity insertion cannot change GraphQL list or grouped-bin
* membership, so creation callers must request this transport revalidation.
+ *
+ * `created` marks an entity that did not exist a moment ago, so it sorts first
+ * in newest-first lists. It is inserted into the REST lists whose filters admit
+ * it, without refetching any list, in either transport.
*/
export async function refetchSoupEntity(
entityId: string,
@@ -776,12 +783,25 @@ export async function refetchSoupEntity(
includeRoot?: boolean;
ownTouch?: boolean;
refreshGraphql?: boolean;
+ created?: boolean;
}
): Promise<void> {
if (options?.refreshGraphql) {
void refreshActiveGraphqlSoupQueries();
}
+ // GraphQL lists never read this cache, so a miss means no REST list shows
+ // the entity. Own-touch inserts still land because Home's touched_by_me
+ // feed stays on REST.
+ if (
+ !options?.ownTouch &&
+ !options?.created &&
+ isFeatureEnabled(enableGraphqlSoup) &&
+ !hasSoupEntity(entityId)
+ ) {
+ return;
+ }
+
const { storageServiceClient } = await import('@service-storage/client');
const filter = buildSingleEntityFilter(entityType, entityId, options);
@@ -811,6 +831,7 @@ export async function refetchSoupEntity(
optimisticUpdateSoupEntity(item);
} else {
insertSoupEntity(item);
+ if (options?.created) continue;
if (options?.ownTouch) {
invalidateAllSoupExceptTouched();
} else {
diff --git a/apps/web/src/lib/queries/soup/refresh.test.ts b/apps/web/src/lib/queries/soup/refresh.test.ts
index 76cb62b7a6..eb6adeb584 100644
--- a/apps/web/src/lib/queries/soup/refresh.test.ts
+++ b/apps/web/src/lib/queries/soup/refresh.test.ts
@@ -16,9 +16,6 @@ vi.mock('./normalized-cache/normalizer', () => ({
getSoupNormalizer: () => ({ getDependentQueriesByIds: dependencies }),
soupNormKey: (id: string) => `soup:${id}`,
}));
-vi.mock('./graphql/active-queries', () => ({
- refreshActiveGraphqlSoupQueries: vi.fn(async () => {}),
-}));
import { refreshAgentSessionLists } from '../agent-session/list-sync';
import { soupKeys } from './keys';
@@ -40,70 +37,69 @@ afterEach(() => {
client.clear();
});
-function mountInitialList() {
- const responses: Array<(state: string) => void> = [];
- const queryFn = vi.fn(
- () => new Promise<string>((resolve) => responses.push(resolve))
- );
- const observer = new QueryObserver(client, { queryKey: key, queryFn });
+function mountList(
+ queryKey: QueryKey,
+ queryFn: () => Promise<string>,
+ initialData?: string
+) {
+ const observer = new QueryObserver(client, {
+ queryKey,
+ queryFn,
+ ...(initialData === undefined ? {} : { initialData, staleTime: Infinity }),
+ });
unsubscribers.push(observer.subscribe(() => {}));
- return { queryFn, responses };
}
-it('supersedes an initial REST snapshot before the session has normalized dependencies', async () => {
- const { queryFn, responses } = mountInitialList();
- expect(queryFn).toHaveBeenCalledTimes(1);
- expect(client.getQueryData(key)).toBeUndefined();
+it('leaves loading and loaded lists alone for a session no list holds', async () => {
+ const loading = vi.fn(() => new Promise<string>(() => {}));
+ const loaded = vi.fn(async () => 'refetched');
+ mountList(key, loading);
+ mountList([...soupKeys.items._def, { documents: true }], loaded, 'loaded');
- const refresh = refreshSoupEntities(['session']);
- await vi.waitFor(() => expect(queryFn).toHaveBeenCalledTimes(2));
- responses[1]('idle');
- await refresh;
- responses[0]('running');
- await Promise.resolve();
- expect(client.getQueryData(key)).toBe('idle');
-});
+ await refreshSoupEntities(['session']);
-it('awaits REST and repeats when another update arrives during revalidation', async () => {
- const { queryFn, responses } = mountInitialList();
- const first = refreshAgentSessionLists('session');
- await vi.waitFor(() => expect(queryFn).toHaveBeenCalledTimes(2));
- const second = refreshAgentSessionLists('session');
- responses[1]('running');
- await vi.waitFor(() => expect(queryFn).toHaveBeenCalledTimes(3));
- responses[2]('blocked');
- await Promise.all([first, second]);
- responses[0]('idle');
- await Promise.resolve();
- expect(client.getQueryData(key)).toBe('blocked');
+ expect(loading).toHaveBeenCalledOnce();
+ expect(loaded).not.toHaveBeenCalled();
});
it('leaves unrelated loaded REST lists alone for a known session', async () => {
dependencies.mockReturnValue([key]);
const otherKey = [...soupKeys.items._def, { documents: true }];
const unrelated = vi.fn(async () => 'unrelated');
- const observer = new QueryObserver(client, {
- queryKey: otherKey,
- queryFn: unrelated,
- initialData: 'already loaded',
- staleTime: Infinity,
- });
- unsubscribers.push(observer.subscribe(() => {}));
+ mountList(otherKey, unrelated, 'already loaded');
+ mountList(key, async () => 'updated', 'old');
+
await refreshSoupEntities(['session']);
+
expect(unrelated).not.toHaveBeenCalled();
expect(client.getQueryData(otherKey)).toBe('already loaded');
+ expect(client.getQueryData(key)).toBe('updated');
+});
+
+it('awaits REST and repeats when another update arrives during revalidation', async () => {
+ dependencies.mockReturnValue([key]);
+ const responses: Array<(state: string) => void> = [];
+ const queryFn = vi.fn(
+ () => new Promise<string>((resolve) => responses.push(resolve))
+ );
+ mountList(key, queryFn, 'idle');
+
+ const first = refreshAgentSessionLists('session');
+ await vi.waitFor(() => expect(queryFn).toHaveBeenCalledTimes(1));
+ const second = refreshAgentSessionLists('session');
+ responses[0]('running');
+ await vi.waitFor(() => expect(queryFn).toHaveBeenCalledTimes(2));
+ responses[1]('blocked');
+ await Promise.all([first, second]);
+
+ expect(client.getQueryData(key)).toBe('blocked');
});
it('retries a real query failure so persisted metadata can replace the cached row', async () => {
+ dependencies.mockReturnValue([key]);
const queryFn = vi.fn(async () => 'updated branch');
queryFn.mockRejectedValueOnce(new Error('temporary outage'));
- const observer = new QueryObserver(client, {
- queryKey: key,
- queryFn,
- initialData: 'old branch',
- staleTime: Infinity,
- });
- unsubscribers.push(observer.subscribe(() => {}));
+ mountList(key, queryFn, 'old branch');
await refreshAgentSessionLists('session');
diff --git a/apps/web/src/lib/queries/soup/refresh.ts b/apps/web/src/lib/queries/soup/refresh.ts
index 6e589220bc..071150124d 100644
--- a/apps/web/src/lib/queries/soup/refresh.ts
+++ b/apps/web/src/lib/queries/soup/refresh.ts
@@ -4,20 +4,17 @@ import { soupKeys } from './keys';
import { getSoupNormalizer, soupNormKey } from './normalized-cache/normalizer';
/**
- * Revalidate REST lists after a committed server change. Initial reads have no
- * normalized dependencies yet, so they must also be cancelled and restarted.
- * Unknown entities can enter any list; known entities target dependent lists.
+ * Revalidate the REST lists that already hold these entities after a committed
+ * server change. Lists that do not hold them are left alone.
*/
export async function refreshSoupEntities(
- entityIds?: string[],
+ entityIds: string[],
options: { throwOnError?: boolean } = {}
): Promise<void> {
- const dependencies = entityIds?.map((id) =>
+ const keys = entityIds.flatMap((id) =>
getSoupNormalizer().getDependentQueriesByIds([soupNormKey(id)])
);
- const all =
- !dependencies?.length || dependencies.some((keys) => !keys.length);
- const keys = dependencies?.flat() ?? [];
+ if (keys.length === 0) return;
const listPrefixes = [
soupKeys.items._def,
soupKeys.astItems._def,
@@ -25,12 +22,9 @@ export async function refreshSoupEntities(
];
const predicate = (query: Query) =>
listPrefixes.some((prefix) => partialMatchKey(query.queryKey, prefix)) &&
- (all ||
- query.state.data === undefined ||
- keys.some((key) => partialMatchKey(query.queryKey, key)));
+ keys.some((key) => partialMatchKey(query.queryKey, key));
- // Explicit cancellation also supersedes initial requests with no data;
- // invalidateQueries alone would share their older in-flight result.
+ // Cancel an in-flight refetch so its older snapshot cannot land after this one.
await queryClient.cancelQueries({ predicate, type: 'active' });
await queryClient.invalidateQueries({ predicate }, options);
}
diff --git a/apps/web/src/lib/queries/storage/pr-mention-sync.test.ts b/apps/web/src/lib/queries/storage/pr-mention-sync.test.ts
index ee27df847f..53b4f1ae23 100644
--- a/apps/web/src/lib/queries/storage/pr-mention-sync.test.ts
+++ b/apps/web/src/lib/queries/storage/pr-mention-sync.test.ts
@@ -49,7 +49,7 @@ describe('PR gateway updates', () => {
await handlePullRequestUpdated(entity);
expect(queryClient.getQueryData(byKey)).toEqual(entity);
expect(queryClient.getQueryData(byId)).toEqual(entity);
- expect(refreshLists).toHaveBeenCalledOnce();
+ expect(refreshLists).not.toHaveBeenCalled();
});
it('cancels an older lookup so its null response cannot erase a push', async () => {
diff --git a/apps/web/src/lib/queries/storage/pr-mention-sync.ts b/apps/web/src/lib/queries/storage/pr-mention-sync.ts
index 2d388f234e..7d91e409e5 100644
--- a/apps/web/src/lib/queries/storage/pr-mention-sync.ts
+++ b/apps/web/src/lib/queries/storage/pr-mention-sync.ts
@@ -1,4 +1,3 @@
-import { refreshAgentSessionLists } from '@queries/agent-session/list-sync';
import { queryClient } from '@queries/client';
import type { ForeignEntity } from '@service-storage/generated/schemas';
import { getForeignEntityResponse } from '@service-storage/generated/zod';
@@ -32,7 +31,6 @@ export async function handlePullRequestUpdated(
: entity
);
}
- await refreshAgentSessionLists();
}
export function invalidatePullRequestMentions(): void {