Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): keep the email list stable through Done, Undo and new mail (#8247)
teo75a0313cc1ec
diff --git a/.agents/rules/web/data.md b/.agents/rules/web/data.mdindex 71709f184d..752d240acd 100644--- a/.agents/rules/web/data.md+++ b/.agents/rules/web/data.md@@ -83,5 +83,12 @@ Examples: [session query factory](../../../apps/web/src/lib/queries/agent-sessionever openable.- **FE-50** Scope invalidation to what changed, but update every reader of it.Query keys hold exactly the fetch inputs.+- **FE-58** With the GraphQL normalized cache, a mutation never refetches the+ lists the cache maintains: its optimistic write and returned records update+ them, and they re-evaluate locally. A refetch reads a replica that can lag the+ write and puts stale state back. Read again only lists the cache cannot keep+ current (`unmaintainedOnly`), everything without the cache, or as a failure+ fallback; a write the server answers only in part writes the confirmed rest+ into the cache itself.- **FE-51** State moved into the URL round-trips every field. Removed or renamedroutes and route ids get redirects, and saved split layouts keep working.diff --git a/apps/web/docs/local-predicate-pagination-plan.md b/apps/web/docs/local-predicate-pagination-plan.mdindex ac97e0432d..aa16d78757 100644--- a/apps/web/docs/local-predicate-pagination-plan.md+++ b/apps/web/docs/local-predicate-pagination-plan.md@@ -44,7 +44,7 @@ After the optimistic fact-index prerequisite is complete, the index has the requ1. Local predicate cursors are separate from opaque server GraphQL Soup cursors. Neither cursor is translated into the other.2. A local page chain is valid only within one cache-engine generation and one exact cache revision.-3. Any cache revision or engine-generation change discards the complete local continuation chain and reevaluates its initial page. Pages from different revisions are never merged.+3. A cache revision change discards the complete local continuation chain and re-reads it from the first row through its last loaded row. An input change (filter, sort, limit, view) or an engine-generation change starts again from the initial page. Pages from different revisions are never merged.4. A live network response tagged with the current cache revision replaces the local chain and becomes authoritative again.5. Local pagination remains all-or-network. Unsupported compilation, incomplete projections, malformed cursors, storage errors, or query-relevant uncertainty never produce an approximate page.6. Cursor pagination uses keyset semantics over `(sort_value, record_key)`, matching the existing ordering exactly.@@ -152,7 +152,7 @@ type EntityFilterCacheResult =| { kind: 'stale-cursor'; revision: CacheRevision };```-A stale cursor means the engine generation or query changed; native engines that predate row positions also return it after any write. It is a recoverable control-flow result: clear the local page chain and request its first page at the reported current revision. It is not a user-visible error and must not silently continue from the stale boundary.+A stale cursor means the engine generation or query changed; native engines that predate row positions also return it after any write. It is a recoverable control-flow result: reevaluate the chain from its first page at the reported current revision. It is not a user-visible error and must not silently continue from the stale boundary.## Keyset semantics@@ -222,9 +222,10 @@ The exact generation representation should reuse the cache host's replacement liBehavior:- initial local evaluation replaces the entire local chain;-- local `fetchNextPage` evaluates with the last page's local cursor and appends only after revision checks pass;+- local `fetchNextPage` evaluates with the last page's local cursor and appends only when the page and the displayed chain share a revision; when a cache write raced the page, it re-reads the list through the page's last row instead;- duplicate concurrent next-page calls share or reject behind one in-flight promise;-- a filter, sort, limit, feature-option, revision, or generation change invalidates the chain;+- a filter, sort, limit, or feature-option change invalidates the chain and starts again from the initial page;+- a revision change re-reads the chain through its last loaded row (`through`), and at least as many rows as the server pages shown, so a cache write never collapses a scrolled Mail list to its first page, and mail arriving above never pushes its last row off. A generation change, or a native engine that predates `endCursor`, re-reads the first page. The `graphql_cache.soup_local_evaluation` span records `evaluation.through` and `evaluation.depth` (rows read);- local pages are flattened in order with defensive key deduplication at the page boundary;- `hasNextPage` comes from the authoritative chain: local `nextCursor` while local, urql while network;- `isFetchingNextPage` combines local and urql fetch state;diff --git a/apps/web/src/features/email-view/components/EmailList.tsx b/apps/web/src/features/email-view/components/EmailList.tsxindex f5cade44ed..6233bb5011 100644--- a/apps/web/src/features/email-view/components/EmailList.tsx+++ b/apps/web/src/features/email-view/components/EmailList.tsx@@ -68,6 +68,7 @@ import {type EmailListStateSnapshot,} from '../persistence';import { createEmailRowActionState } from '../primitives/row-action-state';+import { createScrollAnchor } from '../primitives/scroll-anchor';import type { EmailDataSourceItem } from '../queries/use-email-query';import type { EmailListPane } from '../reader-pane';import { EMAIL_TOUR } from '../tour';@@ -217,6 +218,7 @@ export function EmailList(props: EmailListProps) {);const rows = source.items;+ const scrollAnchor = createScrollAnchor({ scroller: viewport, rows });const swipeRowsByEntityId = createMemo(() => {const entities = new Map<string, EmailActionRow>();@@ -633,7 +635,10 @@ export function EmailList(props: EmailListProps) {? [list.focus.index()]: undefined}- onScroll={checkNearEnd}+ onScroll={() => {+ scrollAnchor.capture();+ checkNearEnd();+ }}>{(row) => (<Switch>diff --git a/apps/web/src/features/email-view/primitives/scroll-anchor.test.ts b/apps/web/src/features/email-view/primitives/scroll-anchor.test.tsnew file mode 100644index 0000000000..a41b79cde0--- /dev/null+++ b/apps/web/src/features/email-view/primitives/scroll-anchor.test.ts@@ -0,0 +1,129 @@+import { createRoot, createSignal } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { createScrollAnchor } from './scroll-anchor';++const device = vi.hoisted(() => ({ touch: false }));+vi.mock('@core/mobile/isTouchDevice', () => ({+ isTouchDevice: () => device.touch,+}));++afterEach(() => {+ document.body.replaceChildren();+ device.touch = false;+ vi.useRealTimers();+});++/**+ * A scroller whose rows sit at fixed offsets in the content, like the+ * virtualizer's absolutely positioned rows; jsdom has no layout, so each row+ * reports its offset minus the scroll position.+ */+function list(ids: string[]) {+ const scroller = document.createElement('div');+ let scrollTop = 0;+ Object.defineProperty(scroller, 'scrollTop', {+ get: () => scrollTop,+ set: (value: number) => {+ scrollTop = value;+ },+ });+ scroller.getBoundingClientRect = () => ({ top: 0 }) as DOMRect;+ const layout = (next: string[]) => {+ scroller.replaceChildren(+ ...next.map((id, index) => {+ const row = document.createElement('div');+ row.id = id;+ row.setAttribute('role', 'row');+ row.getBoundingClientRect = () =>+ ({ top: index * 44 - scrollTop }) as DOMRect;+ return row;+ })+ );+ };+ layout(ids);+ document.body.append(scroller);+ return {+ scroller,+ layout,+ scrollTo: (value: number) => {+ scrollTop = value;+ },+ };+}++function setup(ids: string[]) {+ const dom = list(ids);+ const [rows, setRows] = createSignal(ids.map((id) => ({ id })));+ const anchor = createRoot(() =>+ createScrollAnchor({ scroller: () => dom.scroller, rows })+ );+ const update = (next: string[]) => {+ dom.layout(next);+ setRows(next.map((id) => ({ id })));+ };+ return { dom, anchor, update };+}++it('keeps the rows on screen still when mail arrives above them', () => {+ const ids = Array.from({ length: 20 }, (_, index) => `row-${index}`);+ const { dom, anchor, update } = setup(ids);+ dom.scrollTo(440);+ anchor.capture();++ update(['header', 'new-mail', ...ids]);++ // row-10 was at the top of the viewport and still is.+ expect(dom.scroller.scrollTop).toBe(440 + 88);+});++it('anchors a second split that shows the same rows', () => {+ const ids = Array.from({ length: 20 }, (_, index) => `row-${index}`);+ // The first split, earlier in the document, has the same row ids.+ list(ids);+ const { dom, anchor, update } = setup(ids);+ dom.scrollTo(440);+ anchor.capture();++ update(['new-mail', ...ids]);++ expect(dom.scroller.scrollTop).toBe(440 + 44);+});++it('keeps the anchor through the removal of the row it was on', () => {+ const ids = Array.from({ length: 20 }, (_, index) => `row-${index}`);+ const { dom, anchor, update } = setup(ids);+ dom.scrollTo(440);+ anchor.capture();++ update(['new-mail', ...ids.filter((id) => id !== 'row-10')]);++ // row-11 stays where it was; nothing jumps.+ expect(dom.scroller.scrollTop).toBe(440);+});++it('leaves the list at the top so new mail shows there', () => {+ const ids = Array.from({ length: 20 }, (_, index) => `row-${index}`);+ const { dom, anchor, update } = setup(ids);+ anchor.capture();++ update(['new-mail', ...ids]);++ expect(dom.scroller.scrollTop).toBe(0);+});++it('leaves a touch scroll that is still moving alone, so iOS momentum continues', () => {+ vi.useFakeTimers();+ device.touch = true;+ const ids = Array.from({ length: 20 }, (_, index) => `row-${index}`);+ const { dom, anchor, update } = setup(ids);+ dom.scrollTo(440);+ anchor.capture();++ update(['new-mail', ...ids]);+ expect(dom.scroller.scrollTop).toBe(440);++ // Once the scroll has settled, arrivals are anchored again.+ vi.advanceTimersByTime(500);+ update(['newer-mail', 'new-mail', ...ids]);+ expect(dom.scroller.scrollTop).toBe(440 + 44);+});diff --git a/apps/web/src/features/email-view/primitives/scroll-anchor.ts b/apps/web/src/features/email-view/primitives/scroll-anchor.tsnew file mode 100644index 0000000000..84ef76f911--- /dev/null+++ b/apps/web/src/features/email-view/primitives/scroll-anchor.ts@@ -0,0 +1,88 @@+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { type Accessor, createEffect, on } from 'solid-js';++type Anchor = { id: string; top: number };++/** A row past the first one keeps the anchor when the first is the one removed. */+const ANCHOR_CANDIDATES = 3;+/**+ * A touch scroll still moving is left alone: setting `scrollTop` stops iOS+ * momentum scrolling dead. Scroll events arrive every frame while it moves.+ */+const TOUCH_SCROLL_SETTLE_MS = 150;++const rowElements = (scroller: HTMLElement) => [+ ...scroller.querySelectorAll<HTMLElement>('[role="row"][id]'),+];++/**+ * Keeps the rows on screen where they are when rows are added or removed+ * above them: new mail arriving, or a thread marked done from elsewhere.+ * Without it the list's content shifts under the user while the scroll+ * offset stays put. At the top of the list nothing is anchored, so new mail+ * shows up there.+ *+ * Rows are found within the scroller by their DOM `id`, which is their row id.+ */+export function createScrollAnchor(options: {+ scroller: Accessor<HTMLElement | undefined>;+ rows: Accessor<readonly { id: string }[]>;+}) {+ let anchors: Anchor[] = [];+ let lastScrollAt = Number.NEGATIVE_INFINITY;++ const measure = () => {+ const scroller = options.scroller();+ anchors = [];+ if (!scroller || scroller.scrollTop <= 0) return;+ const viewTop = scroller.getBoundingClientRect().top;+ // Virtualized rows are positioned, so DOM order is not screen order.+ anchors = rowElements(scroller)+ .map((element) => ({+ id: element.id,+ top: element.getBoundingClientRect().top,+ }))+ .filter((anchor) => anchor.top >= viewTop)+ .sort((left, right) => left.top - right.top)+ .slice(0, ANCHOR_CANDIDATES);+ };+ /** Records where the first rows on screen are; call on every scroll. */+ const capture = () => {+ lastScrollAt = performance.now();+ measure();+ };+ const touchScrolling = () =>+ isTouchDevice() &&+ performance.now() - lastScrollAt < TOUCH_SCROLL_SETTLE_MS;++ // The virtualizer positions the new rows in the same flush, so the anchor's+ // move is measurable here, before the user sees a frame of it.+ createEffect(+ on(+ options.rows,+ () => {+ const scroller = options.scroller();+ if (!scroller) return;+ if (touchScrolling()) {+ measure();+ return;+ }+ // Another split can show the same rows under the same ids.+ const rows = new Map(+ rowElements(scroller).map((element) => [element.id, element])+ );+ for (const anchor of anchors) {+ const element = rows.get(anchor.id);+ if (!element) continue;+ const moved = element.getBoundingClientRect().top - anchor.top;+ if (Math.abs(moved) >= 1) scroller.scrollTop += moved;+ break;+ }+ measure();+ },+ { defer: true }+ )+ );++ return { capture };+}diff --git a/apps/web/src/features/email-view/queries/email-results.ts b/apps/web/src/features/email-view/queries/email-results.tsindex 8906903d78..ffc1d5220b 100644--- a/apps/web/src/features/email-view/queries/email-results.ts+++ b/apps/web/src/features/email-view/queries/email-results.ts@@ -28,7 +28,9 @@ export function buildEmailDateRows(entities: WithNotification<EntityData>[],now = new Date()) {- const rows = buildGroupedSoupRows(groupEmailEntitiesByDate(entities, now));+ const rows = buildGroupedSoupRows(groupEmailEntitiesByDate(entities, now), {+ keyByEntity: true,+ });if (rows[0]?.kind === 'group-header' && rows[0].groupId === 'today')rows.shift();return rows;diff --git a/apps/web/src/features/email-view/queries/use-email-query.test.ts b/apps/web/src/features/email-view/queries/use-email-query.test.tsindex e888ec7c4a..eb16ae5b34 100644--- a/apps/web/src/features/email-view/queries/use-email-query.test.ts+++ b/apps/web/src/features/email-view/queries/use-email-query.test.ts@@ -510,6 +510,16 @@ describe('Email list query transitions', () => {expect(source.isLoading()).toBe(false);});+ it('keeps archived hits when searching Signal and Noise', () => {+ const { source, setState, setSearchEntities } = mount('invoice');+ const archived = { ...email('archived'), done: true };+ const active = { ...email('active'), done: false };+ setSearchEntities([archived, active]);+ expect(ids(source)).toEqual(['archived', 'active']);+ setState('tab', 'important');+ expect(ids(source)).toEqual(['archived', 'active']);+ });+it('trims archived search results to done threads', () => {const { source, setState, setSearchEntities } = mount('invoice');const archived = { ...email('archived'), done: true };diff --git a/apps/web/src/features/email-view/queries/use-email-query.ts b/apps/web/src/features/email-view/queries/use-email-query.tsindex 48c168d378..7646d6860e 100644--- a/apps/web/src/features/email-view/queries/use-email-query.ts+++ b/apps/web/src/features/email-view/queries/use-email-query.ts@@ -70,7 +70,9 @@ export type UseEmailDataSourceOptions = {function emailMatchesTab(entity: EmailEntity,tab: EmailTab,- userId: string | undefined+ userId: string | undefined,+ /** A search hit, which the service matched across archived mail too. */+ searchHit: boolean): boolean {return (match(tab)@@ -79,7 +81,8 @@ function emailMatchesTab(.with('shared', () => userId !== undefined && entity.ownerId !== userId)// The inbox views list only threads still in the inbox; a cached page can// carry a row whose record was archived after the page was fetched.- .with('important', 'noise', () => entity.done !== true)+ // Searching them still finds archived mail, as it always has.+ .with('important', 'noise', () => searchHit || entity.done !== true).with('favorites','sent',@@ -168,10 +171,12 @@ export function useEmailDataSource(const selectEmails = (entities: EntityData[]): EmailEntity[] => {const context = queryContext();+ // Rows and their lookups come from search hits while searching.+ const searchHits = search.isSearching();const selected: EmailEntity[] = [];for (const entity of entities) {if (!isEmailEntity(entity)) continue;- if (!emailMatchesTab(entity, context.tab, userId())) continue;+ if (!emailMatchesTab(entity, context.tab, userId(), searchHits)) continue;if (showsFavorites()) {if (entity.isFavorited === false) continue;// Search results have no Soup favorite field and use search's ID scope.diff --git a/apps/web/src/features/home/queries/use-home-unread-query.test.ts b/apps/web/src/features/home/queries/use-home-unread-query.test.tsindex d38a9e01a4..71d6ee1d19 100644--- a/apps/web/src/features/home/queries/use-home-unread-query.test.ts+++ b/apps/web/src/features/home/queries/use-home-unread-query.test.ts@@ -26,6 +26,7 @@ vi.mock('@app/lib/analytics/posthog', () => ({}));vi.mock('@service-storage/graphql-soup', () => ({getGraphqlSoupClient: mocks.client,+ hasGraphqlCacheHost: () => false,}));vi.mock('./use-home-query', () => ({ useHomeEntitiesQuery: mocks.legacy }));vi.mock('@core/context/user', () => ({ useUserId: () => mocks.userId }));diff --git a/apps/web/src/features/home/queries/use-home-unread-query.ts b/apps/web/src/features/home/queries/use-home-unread-query.tsindex df5cd43fdd..9afc01672b 100644--- a/apps/web/src/features/home/queries/use-home-unread-query.ts+++ b/apps/web/src/features/home/queries/use-home-unread-query.ts@@ -14,7 +14,10 @@ import {HomeUnreadPresenceDocument,type HomeUnreadPresenceQuery,} from '@service-storage/graphql/generated/graphql';-import { getGraphqlSoupClient } from '@service-storage/graphql-soup';+import {+ getGraphqlSoupClient,+ hasGraphqlCacheHost,+} from '@service-storage/graphql-soup';import { type Accessor, createMemo, onCleanup } from 'solid-js';import { buildHomeQuery } from './home-query';import { hasHomeUnreadWitness } from './home-unread';@@ -71,7 +74,16 @@ export function useHomeUnreadQuery(]),},}));- onCleanup(registerGraphqlSoupRevalidations(queries, getGraphqlSoupClient));+ // Unread is read from each witness's cached state.+ onCleanup(+ registerGraphqlSoupRevalidations(+ queries,+ getGraphqlSoupClient,+ hasGraphqlCacheHost+ )+ );+ // Not maintained for list refreshes: a delivered reminder adds to a+ // thread's `unreadReminders` edge, which no cached write fills.onCleanup(registerActiveGraphqlSoupQuery({ isEnabled: enabled, refresh }));onCleanup(registerActivityRevalidator({diff --git a/apps/web/src/features/next-soup/actions/graphql-done-operation.test.ts b/apps/web/src/features/next-soup/actions/graphql-done-operation.test.tsindex 279991cbba..934f88cfcc 100644--- a/apps/web/src/features/next-soup/actions/graphql-done-operation.test.ts+++ b/apps/web/src/features/next-soup/actions/graphql-done-operation.test.ts@@ -22,6 +22,7 @@ const writes = vi.hoisted(() => ({notificationOverride: vi.fn(() =>Object.assign(vi.fn(), { release: vi.fn() })),+ confirmDone: vi.fn((_ids: readonly string[]) => false),}));vi.mock('../utils', () => ({executeMarkEntitiesDone: writes.done,@@ -38,6 +39,9 @@ vi.mock('@queries/soup/graphql/active-queries', () => ({vi.mock('@notifications', () => ({setDoneOverride: writes.notificationOverride,}));+vi.mock('@queries/notification/state-cache', () => ({+ confirmEntityNotificationsDone: writes.confirmDone,+}));let client: QueryClient;const cleanup: (() => void)[] = [];@@ -46,6 +50,8 @@ beforeEach(() => {writes.done.mockReset();writes.undone.mockReset();writes.notificationOverride.mockClear();+ writes.confirmDone.mockReset();+ writes.confirmDone.mockReturnValue(false);client = new QueryClient();client.setQueryData(authKeys.userInfo.queryKey, {userId: 'viewer',@@ -68,7 +74,11 @@ const document = (id: string) =>],}) as unknown as EntityData;-function setup(grouped: boolean, targets: string[]) {+function setup(+ grouped: boolean,+ targets: string[],+ knownIds: (id: string) => string[] = (id) => [`n-${id}`]+) {const source: SoupAstItemsData = {entities: [document('a'), document('b')],groups: grouped@@ -106,7 +116,7 @@ function setup(grouped: boolean, targets: string[]) {emailIds: [],notificationIds: [],notificationIdsByEntity: new Map(- entities.map((entity) => [doneEntityKey(entity), [`n-${entity.id}`]])+ entities.map((entity) => [doneEntityKey(entity), knownIds(entity.id)])),notificationEntities: entities.map(({ id }) => ({type: 'document',@@ -187,3 +197,54 @@ describe('no-op receipts with real GraphQL display intents', () => {});});++describe('partial receipts with the normalized cache', () => {+ it('records known rows the server left out as done, and undoes only its own', async () => {+ writes.confirmDone.mockReturnValue(true);+ const { operation, reply } = setup(false, ['a'], (id) => [+ `n-${id}`,+ `n-${id}-earlier`,+ ]);+ const write = operation.execute();+ // n-a changed; n-a-earlier was already done on the server and left out.+ reply.resolve([notificationReceipt('n-a', { type: 'document', id: 'a' })]);+ await write;+ operation.settle();++ expect(writes.confirmDone).toHaveBeenCalledExactlyOnceWith(['n-a-earlier']);+ expect(operation.completedCount()).toBe(1);+ expect(operation.hasNoopRows()).toBe(false);+ writes.undone.mockResolvedValue(undefined);+ await operation.undo();+ expect(writes.undone).toHaveBeenCalledWith(+ expect.objectContaining({ notificationIds: ['n-a'] })+ );+ });+});++describe('no-op receipts with the normalized cache', () => {+ it('records stale notifications as done and keeps the row hidden', async () => {+ writes.confirmDone.mockReturnValue(true);+ const { operation, visible, reply } = setup(false, ['a']);+ await vi.waitFor(() =>+ expect(visible().entities.map(({ id }) => id)).toEqual(['b'])+ );+ const write = operation.execute();+ // The server changed nothing: it already held the entity as done.+ reply.resolve([]);+ await write;+ operation.settle();++ expect(writes.confirmDone).toHaveBeenCalledExactlyOnceWith(['n-a']);+ expect(operation.hasNoopRows()).toBe(false);+ expect(operation.completedCount()).toBe(1);+ // No rollback: the row does not come back while its cache catches up.+ expect(+ writes.notificationOverride.mock.results[0].value+ ).not.toHaveBeenCalled();+ expect(visible().entities.map(({ id }) => id)).toEqual(['b']);+ // Nothing changed on the server, so Undo has nothing to reverse.+ await operation.undo();+ expect(writes.undone).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/next-soup/actions/graphql-done-operation.ts b/apps/web/src/features/next-soup/actions/graphql-done-operation.tsindex dbb23535e7..bed8e75af3 100644--- a/apps/web/src/features/next-soup/actions/graphql-done-operation.ts+++ b/apps/web/src/features/next-soup/actions/graphql-done-operation.ts@@ -2,6 +2,7 @@ import { scopeChannelNotificationsForEntity } from '@app/features/soup/entity-noimport type { EntityData } from '@entity';import { toNotificationEntity } from '@entity/utils/notification';import type { NotificationEntityRef } from '@queries/notification/entity-mutations';+import { confirmEntityNotificationsDone } from '@queries/notification/state-cache';import { batch } from 'solid-js';import {executeMarkEntitiesDone,@@ -160,15 +161,25 @@ export function createGraphqlDoneOperation(args: Args) {);ids = notifications.map(({ id }) => id);}+ // An entity-wide Done changes only rows still open on the server.+ // Known rows it left out were already done there; record that.+ const missed =+ outcome.kind === 'entity-notifications'+ ? attempt.knownNotificationIds.filter((id) => !ids.includes(id))+ : [];+ const confirmed =+ missed.length > 0 && confirmEntityNotificationsDone(missed);if (ids.length > 0) {attempt.receipt = {emailIds: [],notificationIds: ids,};- } else {+ } else if (!confirmed) {// No matching receipt justifies neither a hide nor a restoration.// Release this attempt even when Undo was never requested: a stale- // reader might otherwise keep the row hidden indefinitely.+ // reader might otherwise keep the row hidden indefinitely. A+ // confirmed Done keeps the row hidden: its cached notifications+ // now read done, and there is nothing to undo.attempt.state = 'noop';attempt.optimistic.rollback();}diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.pending.test.tsx b/apps/web/src/features/next-soup/actions/make-mark-done-action.pending.test.tsxindex 516a285477..2f727b16c2 100644--- a/apps/web/src/features/next-soup/actions/make-mark-done-action.pending.test.tsx+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.pending.test.tsx@@ -54,6 +54,10 @@ vi.mock('@core/component/Toast/Toast', () => ({ toast: mocks.toast }));vi.mock('./graphql-done-optimism', () => ({applyGraphqlDoneOptimistic: mocks.apply,}));+// No normalized cache here: a no-op entity write rolls its hide back.+vi.mock('@queries/notification/state-cache', () => ({+ confirmEntityNotificationsDone: () => false,+}));vi.mock('@queries/notification/entity-mutations', () => ({toNotificationEntityRef: (entity: EntityData) => ({type: entity.type,diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.test.ts b/apps/web/src/features/next-soup/actions/make-mark-done-action.test.tsindex 8d06024a35..e9de505558 100644--- a/apps/web/src/features/next-soup/actions/make-mark-done-action.test.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.test.ts@@ -69,6 +69,10 @@ vi.mock('@core/component/Toast/Toast', () => ({},}));+// No normalized cache here: a no-op entity write rolls its hide back.+vi.mock('@queries/notification/state-cache', () => ({+ confirmEntityNotificationsDone: () => false,+}));vi.mock('@queries/notification/entity-mutations', () => ({toNotificationEntityRef: mocks.toNotificationEntityRef,updateNotificationsForEntities: vi.fn(),diff --git a/apps/web/src/features/next-soup/actions/make-mark-notifications-read-action.ts b/apps/web/src/features/next-soup/actions/make-mark-notifications-read-action.tsindex 16c6a7ccb2..481cd3ca34 100644--- a/apps/web/src/features/next-soup/actions/make-mark-notifications-read-action.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-notifications-read-action.ts@@ -10,7 +10,11 @@ import {notificationIsRead,toNotificationEntity,} from '@entity/utils/notification';-import type { NotificationSource, UnifiedNotification } from '@notifications';+import {+ type NotificationSource,+ shownUnseenNotificationIds,+ type UnifiedNotification,+} from '@notifications';import { compositeEntity } from '@notifications/types';import {type NotificationEntityRef,@@ -61,6 +65,7 @@ export const makeMarkNotificationsReadAction = (const execute = async (entities: EntityData[]) => {const notificationsById = new Map<string, UnifiedNotification>();const entityRefs: NotificationEntityRef[] = [];+ const expectedNotificationIds: string[] = [];const useEntityMutations = isFeatureEnabled(enableGraphqlSoup);let targetCount = 0;@@ -68,6 +73,13 @@ export const makeMarkNotificationsReadAction = (const entityRef = toNotificationEntityRef(entity);if (useEntityMutations && entityRef) {entityRefs.push(entityRef);+ expectedNotificationIds.push(+ ...shownUnseenNotificationIds(+ options.notificationSource(),+ toNotificationEntity(entity),+ isWithNotification(entity) ? entity.notifications?.() : undefined+ )+ );targetCount += 1;continue;}@@ -90,6 +102,7 @@ export const makeMarkNotificationsReadAction = (? updateNotificationsForEntities({entities: entityRefs,operation: 'MARK_SEEN',+ expectedNotificationIds,}): Promise.resolve(),notifications.length > 0diff --git a/apps/web/src/features/notifications/index.ts b/apps/web/src/features/notifications/index.tsindex 9463036594..2b35064879 100644--- a/apps/web/src/features/notifications/index.ts+++ b/apps/web/src/features/notifications/index.ts@@ -34,6 +34,7 @@ export {notificationIsOfEntity,notificationIsOfEntityType,notificationIsRead,+ shownUnseenNotificationIds,useEntityHasUnreadNotifications,useEntityTypeNotifications,useNotificationsForEntity,diff --git a/apps/web/src/features/notifications/notification-helpers.ts b/apps/web/src/features/notifications/notification-helpers.tsindex 575b639c60..7fa4ed8501 100644--- a/apps/web/src/features/notifications/notification-helpers.ts+++ b/apps/web/src/features/notifications/notification-helpers.ts@@ -200,6 +200,25 @@ export async function ensureNotificationSourceLoaded(}}+/**+ * The entity's notifications this client shows as unseen, from the row's own+ * edges when it has them. A GraphQL feed that has not started shows nothing+ * yet, and reading it would start the full notification feed.+ */+export function shownUnseenNotificationIds(+ notificationSource: NotificationSource,+ entity: Entity,+ attached?: readonly UnifiedNotification[]+): string[] {+ const shown =+ attached ??+ (notificationSource._notificationsQuery.isStarted+ ? notificationSource.notificationsByEntity()[compositeEntity(entity)]+ : undefined) ??+ [];+ return shown.filter(({ state }) => state === 'unseen').map(({ id }) => id);+}+/*** Marks all notifications for an entity as read* @param notificationSource@@ -215,6 +234,10 @@ export async function markNotificationsForEntityAsRead(await updateNotificationsForEntities({entities: [entityRef],operation: 'MARK_SEEN',+ expectedNotificationIds: shownUnseenNotificationIds(+ notificationSource,+ entity+ ),});return;}diff --git a/apps/web/src/features/notifications/tests/notification-source.test.ts b/apps/web/src/features/notifications/tests/notification-source.test.tsindex 9db480ca39..5d43ee7d05 100644--- a/apps/web/src/features/notifications/tests/notification-source.test.ts+++ b/apps/web/src/features/notifications/tests/notification-source.test.ts@@ -460,6 +460,81 @@ describe('createNotificationSource', () => {});+ it('tells an entity-wide mark seen which notifications it expects to change', async () => {+ mocks.graphqlEnabled = true;+ const { toNotificationEntityRef, updateNotificationsForEntities } =+ await import('@queries/notification/entity-mutations');+ vi.mocked(toNotificationEntityRef).mockReturnValue({+ type: 'document',+ id: 'doc',+ });+ vi.mocked(updateNotificationsForEntities).mockResolvedValue([]);+ const unseen = notification('expected-unseen', 'document', 'doc');+ const seen = {+ ...notification('already-seen', 'document', 'doc'),+ state: 'seen' as const,+ };+ mocks.notificationsQuery = {+ data: [unseen, seen],+ transport: 'graphql',+ isFetching: false,+ };+ const { source, dispose } = createRoot((dispose) => ({+ source: createNotificationSource({} as ConnectionGatewayWebsocket),+ dispose,+ }));+ try {+ await markNotificationsForEntityAsRead(source, {+ type: 'document',+ id: 'doc',+ });+ // A reply without one of these means this tab was stale.+ expect(updateNotificationsForEntities).toHaveBeenCalledWith({+ entities: [{ type: 'document', id: 'doc' }],+ operation: 'MARK_SEEN',+ expectedNotificationIds: ['expected-unseen'],+ });+ } finally {+ dispose();+ }+ });++ it('expects nothing from a feed that has not started, without starting it', async () => {+ mocks.graphqlEnabled = true;+ const { toNotificationEntityRef, updateNotificationsForEntities } =+ await import('@queries/notification/entity-mutations');+ vi.mocked(toNotificationEntityRef).mockReturnValue({+ type: 'document',+ id: 'doc',+ });+ vi.mocked(updateNotificationsForEntities).mockResolvedValue([]);+ const read = vi.fn(() => [notification('unseen', 'document', 'doc')]);+ mocks.notificationsQuery = {+ isStarted: false,+ get data() {+ return read();+ },+ transport: 'graphql',+ isFetching: false,+ };+ const { source, dispose } = createRoot((dispose) => ({+ source: createNotificationSource({} as ConnectionGatewayWebsocket),+ dispose,+ }));+ try {+ await markNotificationsForEntityAsRead(source, {+ type: 'document',+ id: 'doc',+ });+ expect(updateNotificationsForEntities).toHaveBeenCalledWith(+ expect.objectContaining({ expectedNotificationIds: [] })+ );+ expect(read).not.toHaveBeenCalled();+ } finally {+ dispose();+ }+ });+it('can release a failed reversal to authoritative state without clearing newer intent', () => {mocks.graphqlEnabled = true;const row: UnifiedNotification = {diff --git a/apps/web/src/features/soup/collection/rows.test.ts b/apps/web/src/features/soup/collection/rows.test.tsindex 9449460600..7011c5af08 100644--- a/apps/web/src/features/soup/collection/rows.test.ts+++ b/apps/web/src/features/soup/collection/rows.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { getSoupMenuEntities } from './rows';+import { buildGroupedSoupRows, getSoupMenuEntities } from './rows';describe('getSoupMenuEntities', () => {const rows = [@@ -20,3 +20,40 @@ describe('getSoupMenuEntities', () => {expect(getSoupMenuEntities(rows[0], [])).toEqual([rows[0]]);});});++describe('buildGroupedSoupRows keyed by entity', () => {+ const thread = { id: 't1', type: 'email' };+ const other = { id: 't2', type: 'email' };+ const rowIdOf = (rows: { kind: string; id: string }[], index: number) =>+ rows.filter((row) => row.kind === 'entity')[index]?.id;++ it('keeps a row id when its entity moves to another group', () => {+ const before = buildGroupedSoupRows(+ [+ { id: 'today', label: 'Today', entities: [other] },+ { id: 'yesterday', label: 'Yesterday', entities: [thread] },+ ],+ { keyByEntity: true }+ );+ // A reply arrives: the thread is now today's.+ const after = buildGroupedSoupRows(+ [{ id: 'today', label: 'Today', entities: [thread, other] }],+ { keyByEntity: true }+ );++ expect(rowIdOf(after, 0)).toBe(rowIdOf(before, 1));+ expect(rowIdOf(after, 1)).toBe(rowIdOf(before, 0));+ });++ it('still gives an entity listed in two groups two rows', () => {+ const rows = buildGroupedSoupRows(+ [+ { id: 'today', label: 'Today', entities: [thread] },+ { id: 'yesterday', label: 'Yesterday', entities: [thread] },+ ],+ { keyByEntity: true }+ );++ expect(rowIdOf(rows, 0)).not.toBe(rowIdOf(rows, 1));+ });+});diff --git a/apps/web/src/features/soup/collection/rows.ts b/apps/web/src/features/soup/collection/rows.tsindex a7fd349c61..ebcfb9761e 100644--- a/apps/web/src/features/soup/collection/rows.ts+++ b/apps/web/src/features/soup/collection/rows.ts@@ -23,6 +23,8 @@ const createSoupRowId = (export type CreateSoupEntityRowOptions = {groupId?: string;occurrenceId?: string;+ /** Leave the group out of the row id, so moving groups keeps the row. */+ keyByEntity?: boolean;};export function createSoupEntityRow<TEntity extends SoupEntityIdentity>(@@ -35,7 +37,7 @@ export function createSoupEntityRow<TEntity extends SoupEntityIdentity>('entity',entity.type,entity.id,- options.groupId,+ options.keyByEntity ? undefined : options.groupId,options.occurrenceId),entity,@@ -125,6 +127,12 @@ export function buildFlatSoupRows<TEntity extends SoupEntityIdentity>(}export type BuildGroupedSoupRowsOptions<TEntity extends SoupEntityIdentity> = {+ /**+ * Identify rows by entity alone, for lists where each entity sits in one+ * group (date buckets). A thread moving to another group then keeps its+ * row, its DOM and the keyboard cursor instead of becoming a new row.+ */+ keyByEntity?: boolean;getOccurrenceId?: (entity: TEntity,index: number,@@ -137,6 +145,8 @@ export function buildGroupedSoupRows<TEntity extends SoupEntityIdentity>(options: BuildGroupedSoupRowsOptions<TEntity> = {}): SoupRow<TEntity>[] {const groupIds = new Set<string>();+ // Keyed by entity, a repeat in another group still needs its own id.+ const listOccurrences = new Map<string, number>();const rows = groups.flatMap((group) => {if (groupIds.has(group.id)) {throw new Error(@@ -146,11 +156,14 @@ export function buildGroupedSoupRows<TEntity extends SoupEntityIdentity>(groupIds.add(group.id);const groupRows: SoupRow<TEntity>[] = [createSoupGroupHeaderRow(group)];- const occurrences = new Map<string, number>();+ const occurrences = options.keyByEntity+ ? listOccurrences+ : new Map<string, number>();group.entities.forEach((entity, index) => {groupRows.push(createSoupEntityRow(entity, {groupId: group.id,+ keyByEntity: options.keyByEntity,occurrenceId:options.getOccurrenceId?.(entity, index, group) ??nextDuplicateOccurrence(entity, occurrences),diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.tsindex 92eb908808..95d6f6b26f 100644--- a/apps/web/src/lib/graphql-cache/protocol.ts+++ b/apps/web/src/lib/graphql-cache/protocol.ts@@ -127,7 +127,13 @@ export type EntityFilterCacheArgs = {/** Omit for exact evaluation; even an empty array requests reconciliation. */baseline?: Array<{ key: string; sortTimestamp: string }>;/** Explicit cached-Mail pagination, independent of server cursors. */- mail?: { view: 'ALL' | 'INBOX' | 'DRAFTS' | 'SENT'; cursor?: string };+ mail?: {+ view: 'ALL' | 'INBOX' | 'DRAFTS' | 'SENT';+ /** Continue after this row. Valid across writes; not with `through`. */+ cursor?: string;+ /** A page's `endCursor`: read from the top through that row instead of `limit` rows. */+ through?: string;+ };};export type EntityFilterCacheResult =@@ -139,8 +145,11 @@ export type EntityFilterCacheResult =/** View-correct timestamps aligned with keys, independent of cached previews. */sortTimestamps: string[];nextCursor: string | null;+ /** Position of the last row. Absent from native engines that predate `through`. */+ endCursor?: string | null;optimistic: boolean;}+ /** The cursor's engine generation or query changed; on native engines that predate `through`, any write. */| { kind: 'stale-cursor'; revision: CacheRevision }| {kind: 'reconciled';@@ -291,6 +300,8 @@ export type CacheRevisionResult = {};export const MAX_RECORD_SELECTION_PAGE_SIZE = 500;+/** The most rows a Mail read `through` a position returns, as the engine caps it. */+export const MAX_MAIL_THROUGH_ROWS = 5_000;export const MAX_CACHE_SEARCH_QUERY_BYTES = 512;export const MAX_NORMALIZED_RECORD_KEY_LENGTH = 1024;diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.test.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.test.tsindex 8a62dc3875..cb95aef47f 100644--- a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.test.ts+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.test.ts@@ -293,6 +293,28 @@ describe('coordinator runtime protocol', () => {);});+ it('validates Mail pages and reads through a position', () => {+ const request = {+ filters: {},+ sortMethod: 'UPDATED_AT',+ sortDirection: 'DESC',+ limit: 20,+ };+ const valid = (value: unknown) =>+ isCacheRequest({ id: 1, kind: 'entity-filter', request: value });+ const mail = (fields: Record<string, unknown>, limit = 20) =>+ valid({ ...request, limit, mail: { view: 'INBOX', ...fields } });+ expect(mail({})).toBe(true);+ expect(mail({ cursor: 'row' })).toBe(true);+ expect(mail({}, 500)).toBe(false);+ // `limit` is the fewest rows of a read through a position.+ expect(mail({ through: 'row' }, 2_000)).toBe(true);+ expect(mail({ through: 'row' }, 5_001)).toBe(false);+ expect(mail({ cursor: 'row', through: 'row' })).toBe(false);+ expect(mail({ through: 'x'.repeat(4097) })).toBe(false);+ expect(mail({ unexpected: true })).toBe(false);+ });+it('validates calendar range, commit, and uncertain-event requests', () => {const range = { startMs: 0, endMs: 10, startDay: 0, endDay: 1 };const rangeRequest = (request: unknown) =>diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.tsindex e3851e4830..24837d76f5 100644--- a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts@@ -15,6 +15,7 @@ import {isValidCalendarRangeArgs,isValidNormalizedRecordKey,isWorkerMessage,+ MAX_MAIL_THROUGH_ROWS,MAX_RECONCILIATION_BASELINE,MAX_RECORD_SELECTION_PAGE_SIZE,type WorkerMessage,@@ -730,6 +731,11 @@ export function isCacheRequest(value: unknown): value is CacheRequest {);case 'entity-filter': {const request = value.request;+ // A Mail read through a position takes `limit` as its fewest rows.+ const through =+ isRecord(request) && isRecord(request.mail)+ ? request.mail.through+ : undefined;return (hasOnlyKeys(value, ['id', 'kind', 'request']) &&isRecord(request) &&@@ -747,7 +753,11 @@ export function isCacheRequest(value: unknown): value is CacheRequest {request.sortMethod as string) &&(request.sortDirection === 'ASC' || request.sortDirection === 'DESC') &&- isValidCacheSearchLimit(request.limit) &&+ (through === undefined+ ? isValidCacheSearchLimit(request.limit)+ : Number.isSafeInteger(request.limit) &&+ (request.limit as number) >= 1 &&+ (request.limit as number) <= MAX_MAIL_THROUGH_ROWS) &&(request.liveQuery === undefined ||(isRecord(request.liveQuery) &&hasOnlyKeys(request.liveQuery, [@@ -772,11 +782,15 @@ export function isCacheRequest(value: unknown): value is CacheRequest {request.baseline !== undefined)) &&(request.mail === undefined ||(isRecord(request.mail) &&- hasOnlyKeys(request.mail, ['view', 'cursor']) &&+ hasOnlyKeys(request.mail, ['view', 'cursor', 'through']) &&['ALL', 'INBOX', 'DRAFTS', 'SENT'].includes(request.mail.view as string) &&- request.limit < 500 &&+ (through === undefined+ ? (request.limit as number) < 500+ : request.mail.cursor === undefined &&+ typeof through === 'string' &&+ through.length <= 4096) &&request.baseline === undefined &&(request.mail.cursor === undefined ||(typeof request.mail.cursor === 'string' &&diff --git a/apps/web/src/lib/queries/channel/unread-presence.test.ts b/apps/web/src/lib/queries/channel/unread-presence.test.tsindex f80ea48362..cf308260c7 100644--- a/apps/web/src/lib/queries/channel/unread-presence.test.ts+++ b/apps/web/src/lib/queries/channel/unread-presence.test.ts@@ -3,6 +3,10 @@ import { createClient, type Operation, type OperationResult } from '@urql/core';import { createRoot, createSignal } from 'solid-js';import { describe, expect, it, vi } from 'vitest';import { makeSubject, pipe, subscribe } from 'wonka';+import {+ getActiveGraphqlSoupRevalidations,+ refreshActiveGraphqlSoupQueries,+} from '../soup/graphql/active-queries';import {getChannelListRevalidations,revalidateChannelLists,@@ -10,8 +14,10 @@ import {import { createChannelUnreadQuery } from './unread-presence';const clientMock = vi.hoisted(() => vi.fn());+const cache = vi.hoisted(() => ({ host: false }));vi.mock('@service-storage/graphql-soup', () => ({getGraphqlSoupClient: clientMock,+ hasGraphqlCacheHost: () => cache.host,}));function setup() {@@ -121,4 +127,33 @@ describe('channel unread presence query', () => {}expect(getChannelListRevalidations()).toHaveLength(0);});++ it('counts as kept current by the cache, which writes its witness states', async () => {+ const visible = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false);+ const f = setup();+ try {+ f.setEnabled(true);+ await vi.waitFor(() =>+ expect(f.operations.filter((op) => op.kind === 'query')).toHaveLength(1)+ );+ f.respond('UNSEEN');+ const unmaintained = () =>+ getActiveGraphqlSoupRevalidations(undefined, {+ unmaintainedOnly: true,+ });++ cache.host = false;+ expect(unmaintained()).toHaveLength(1);++ cache.host = true;+ expect(unmaintained()).toHaveLength(0);+ const reads = f.operations.length;+ await refreshActiveGraphqlSoupQueries({ unmaintainedOnly: true });+ expect(f.operations).toHaveLength(reads);+ } finally {+ cache.host = false;+ visible.mockRestore();+ f.dispose();+ }+ });});diff --git a/apps/web/src/lib/queries/channel/unread-presence.ts b/apps/web/src/lib/queries/channel/unread-presence.tsindex e2caf62428..b57ab42238 100644--- a/apps/web/src/lib/queries/channel/unread-presence.ts+++ b/apps/web/src/lib/queries/channel/unread-presence.ts@@ -4,7 +4,10 @@ import {type ChannelUnreadPresenceQuery,type SoupInput,} from '@service-storage/graphql/generated/graphql';-import { getGraphqlSoupClient } from '@service-storage/graphql-soup';+import {+ getGraphqlSoupClient,+ hasGraphqlCacheHost,+} from '@service-storage/graphql-soup';import { type Accessor, onCleanup } from 'solid-js';import {registerActiveGraphqlSoupQuery,@@ -39,7 +42,9 @@ export function createChannelUnreadQuery(enabled()? [{ document: ChannelUnreadPresenceDocument, variables }]: [],- getGraphqlSoupClient+ getGraphqlSoupClient,+ // Unread is read from each witness's cached state.+ hasGraphqlCacheHost));const refresh = registerChannelNotificationRefresh(() => ({@@ -54,6 +59,12 @@ export function createChannelUnreadQuery(: [],},}));- onCleanup(registerActiveGraphqlSoupQuery({ isEnabled: enabled, refresh }));+ onCleanup(+ registerActiveGraphqlSoupQuery({+ isEnabled: enabled,+ refresh,+ cacheMaintained: hasGraphqlCacheHost,+ })+ );return query;}diff --git a/apps/web/src/lib/queries/email/graphql/draft.test.ts b/apps/web/src/lib/queries/email/graphql/draft.test.tsindex 0178a16e87..90fa4b0253 100644--- a/apps/web/src/lib/queries/email/graphql/draft.test.ts+++ b/apps/web/src/lib/queries/email/graphql/draft.test.ts@@ -1,8 +1,12 @@import { optimisticContextOf } from '@graphql-cache/exchange/optimistic';-import type { SaveEmailDraftMutation } from '@service-storage/graphql/generated/graphql';+import {+ type SaveEmailDraftMutation,+ SoupDocument,+} from '@service-storage/graphql/generated/graphql';import { createClient, type Operation } from '@urql/core';import { describe, expect, it } from 'vitest';import { map, pipe } from 'wonka';+import { registerGraphqlSoupRevalidations } from '../../soup/graphql/active-queries';import {executeGraphqlDeleteEmailDraft,executeGraphqlSaveEmailDraft,@@ -352,6 +356,40 @@ it('discards a standalone draft with the original coalescing key and bindings fo).toBe(true);});+it('saves and discards without refetching the lists the cache maintains', async () => {+ // A mounted list's pages. The returned draft and thread records update it.+ const unregister = registerGraphqlSoupRevalidations(+ () => [+ {+ document: SoupDocument,+ variables: { input: { initial: { limit: 50 } } },+ },+ ],+ undefined,+ () => true+ );+ try {+ const { client, operations, thread } = await standalone();+ await executeGraphqlSaveEmailDraft(client, {+ ...args,+ existingThread: { ...thread, cacheProjection: 'server-capsule' },+ });+ await executeGraphqlDeleteEmailDraft(client, {+ draftId: String(args.draftId),+ threadDbId: args.threadDbId,+ existingThread: thread,+ });+ for (const operation of operations) {+ const documents = (+ optimisticContextOf(operation)?.revalidations ?? []+ ).map(({ operationName }) => operationName);+ expect(documents).not.toContain('Soup');+ }+ } finally {+ unregister();+ }+});+it.each([false, true])('preserves a newer read intent through repeated draft saves and discard (read=%s)',async (isRead) => {diff --git a/apps/web/src/lib/queries/email/graphql/draft.ts b/apps/web/src/lib/queries/email/graphql/draft.tsindex 7bf2f09f4c..204143d385 100644--- a/apps/web/src/lib/queries/email/graphql/draft.ts+++ b/apps/web/src/lib/queries/email/graphql/draft.ts@@ -9,7 +9,7 @@ import {select,update,} from '@graphql-cache/exchange/optimistic';-import { getActiveGraphqlSoupRevalidations } from '@queries/soup/graphql/active-queries';+import { getUnmaintainedGraphqlSoupRevalidations } from '@queries/soup/graphql/active-queries';import {DeleteEmailDraftDocument,type DeleteEmailDraftMutation,@@ -351,11 +351,12 @@ export async function executeGraphqlSaveEmailDraft(),]: [],+ // The returned draft and thread records update every list the cache+ // maintains; the rest are read again. Refetch the thread page only+ // when a missing snapshot or an inbox move prevents the message-list+ // patch; otherwise a save can reset the open thread.revalidations: [- ...getActiveGraphqlSoupRevalidations(),- // Ordinary autosaves already return the draft and thread records.- // Refetch only when a missing snapshot or inbox move prevents the- // message-list patch; otherwise a save can reset the open thread.+ ...getUnmaintainedGraphqlSoupRevalidations(),...(canPatchThread? []: [@@ -488,7 +489,7 @@ export async function executeGraphqlDeleteEmailDraft(),],revalidations: [- ...getActiveGraphqlSoupRevalidations(),+ ...getUnmaintainedGraphqlSoupRevalidations(),{document: EmailThreadPageDocument,variables: threadPageVariables,diff --git a/apps/web/src/lib/queries/email/integration.test.ts b/apps/web/src/lib/queries/email/integration.test.tsindex 21307bf4c7..3686681373 100644--- a/apps/web/src/lib/queries/email/integration.test.ts+++ b/apps/web/src/lib/queries/email/integration.test.ts@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({graphql: true,+ cache: true,archive: vi.fn(),archiveBatch: vi.fn(),mutation: vi.fn(),@@ -24,13 +25,14 @@ vi.mock('@service-email/client', () => ({vi.mock('@service-storage/client', () => ({ storageServiceClient: {} }));vi.mock('@service-storage/graphql-soup', () => ({getGraphqlSoupClient: () => ({ mutation: mocks.mutation }),+ graphqlCacheEnabled: () => mocks.cache,}));vi.mock('../reminders/email-collection', () => ({invalidateEmailReminderCollection: mocks.reminders,}));vi.mock('../soup/graphql/active-queries', () => ({refreshActiveGraphqlSoupQueries: mocks.refresh,- getActiveGraphqlSoupRevalidations: mocks.revalidations,+ getUnmaintainedGraphqlSoupRevalidations: mocks.revalidations,}));import { predictOptimisticMutation } from '@graphql-cache/exchange/optimistic-resolvers';@@ -45,6 +47,7 @@ import { archiveEmailThread, archiveEmailThreads } from './integration';beforeEach(() => {vi.resetAllMocks();mocks.graphql = true;+ mocks.cache = true;mocks.refresh.mockResolvedValue(undefined);mocks.revalidations.mockReturnValue([]);});@@ -96,12 +99,28 @@ describe('GraphQL email archive writes', () => {finish();await expect(result).resolves.toBe('committed');expect(mocks.reminders).toHaveBeenCalledOnce();- expect(mocks.refresh).toHaveBeenCalledExactlyOnceWith({- target: { kind: 'email-archive', threadId: 'thread' },- });+ // The cached record carries the change to every list the cache+ // maintains; only the others are read again, by the exchange.+ expect(mocks.refresh).not.toHaveBeenCalled();+ expect(mocks.revalidations).toHaveBeenCalledOnce();});+ it('refreshes lists after the write only without the normalized cache', async () => {+ mocks.cache = false;+ mocks.mutation.mockReturnValue({+ toPromise: async () => ({+ data: { setEmailThreadArchived: { id: 'thread' } },+ }),+ });+ await expect(+ archiveEmailThread({ id: 'thread', value: true })+ ).resolves.toBe('committed');+ expect(mocks.refresh).toHaveBeenCalledExactlyOnceWith({+ target: { kind: 'email-archive', threadId: 'thread' },+ });+ });+it('gives Done, Undo and Redo distinct ordered mutation intents', async () => {mocks.mutation.mockReturnValue({toPromise: async () => ({@@ -126,14 +145,11 @@ describe('GraphQL email archive writes', () => {).toBe(true);});- it('preserves replay revalidations, including continuation pages, without refetching queued writes', async () => {- const variables = [- { input: { initial: { limit: 100 } } },- { input: { continuation: { cursor: 'next' } } },+ it('queues an offline write that reads only unmaintained lists on replay', async () => {+ const unmaintained = [+ { document: SoupDocument, variables: { input: { initial: {} } } },];- mocks.revalidations.mockReturnValue(- variables.map((variables) => ({ document: SoupDocument, variables }))- );+ mocks.revalidations.mockReturnValue(unmaintained);mocks.mutation.mockReturnValue({toPromise: async () => ({extensions: {@@ -147,14 +163,12 @@ describe('GraphQL email archive writes', () => {await expect(archiveEmailThread({ id: 'thread', value: true })).resolves.toBe('queued');+ // Replay commits the record; only lists the cache does not maintain are+ // read again, even after a reload.+ expect(mocks.revalidations).toHaveBeenCalled();expect(mocks.mutation.mock.calls[0][2].optimisticMutation.revalidations- ).toEqual(- variables.map((variables) => ({- document: SoupDocument,- variables,- }))- );+ ).toEqual(unmaintained);expect(mocks.refresh).not.toHaveBeenCalled();expect(mocks.reminders).not.toHaveBeenCalled();});@@ -268,12 +282,27 @@ describe('bulk email archive writes', () => {expect(results[0]).toEqual({ status: 'fulfilled', value: 'committed' });expect(results[1].status).toBe('rejected');expect(results[2]).toEqual({ status: 'fulfilled', value: 'committed' });+ expect(mocks.refresh).not.toHaveBeenCalled();+ expect(mocks.reminders).toHaveBeenCalledOnce();+ expect(mocks.archive).not.toHaveBeenCalled();+ });++ it('refreshes lists for each changed thread only without the normalized cache', async () => {+ mocks.cache = false;+ mocks.mutation.mockReturnValue({+ toPromise: async () => ({+ data: {+ setEmailThreadsArchived: {+ threads: [],+ failedThreadIds: ['skipped'],+ },+ },+ }),+ });+ await archiveEmailThreads(['archived', 'skipped'], true);expect(mocks.refresh.mock.calls).toEqual([[{ target: { kind: 'email-archive', threadId: 'archived' } }],- [{ target: { kind: 'email-archive', threadId: 'unreloaded' } }],]);- expect(mocks.reminders).toHaveBeenCalledOnce();- expect(mocks.archive).not.toHaveBeenCalled();});it('settles every thread as queued when the GraphQL write is queued', async () => {diff --git a/apps/web/src/lib/queries/email/integration.ts b/apps/web/src/lib/queries/email/integration.tsindex df99190848..6457aed8c6 100644--- a/apps/web/src/lib/queries/email/integration.ts+++ b/apps/web/src/lib/queries/email/integration.ts@@ -10,10 +10,13 @@ import {setGraphqlEmailThreadArchived,setGraphqlEmailThreadsArchived,} from '@service-storage/graphql-email-archive-state';-import { getGraphqlSoupClient } from '@service-storage/graphql-soup';+import {+ getGraphqlSoupClient,+ graphqlCacheEnabled,+} from '@service-storage/graphql-soup';import { invalidateEmailReminderCollection } from '../reminders/email-collection';import {- getActiveGraphqlSoupRevalidations,+ getUnmaintainedGraphqlSoupRevalidations,refreshActiveGraphqlSoupQueries,} from '../soup/graphql/active-queries';import { updateEntitySharePolicy } from '../storage/entity-mutations';@@ -25,8 +28,10 @@ export const scheduleEmailMessage = (export type EmailArchiveDisposition = 'committed' | 'queued';/** Shared archive path for Done, Not Done, send completion, and Undo/Redo.- * GraphQL owns optimistic state and durable replay; queued writes must not- * refetch the server's pre-write membership over the optimistic update. */+ * GraphQL owns optimistic state and durable replay. The optimistic+ * `inboxVisible` and the committed record update every list the cache+ * maintains (FE-58); only the others, such as grouped lists, are read again+ * when the write commits, including on a replay after reload. */export async function archiveEmailThread(...args: Parameters<typeof emailClient.flagArchived>): Promise<EmailArchiveDisposition> {@@ -36,12 +41,14 @@ export async function archiveEmailThread(getGraphqlSoupClient(),id,value,- getActiveGraphqlSoupRevalidations()+ getUnmaintainedGraphqlSoupRevalidations());if (disposition === 'committed') {- await refreshActiveGraphqlSoupQueries({- target: { kind: 'email-archive', threadId: id },- });+ if (!graphqlCacheEnabled()) {+ await refreshActiveGraphqlSoupQueries({+ target: { kind: 'email-archive', threadId: id },+ });+ }fireAndForget(invalidateEmailReminderCollection(), 'email-reminders');}return disposition;@@ -100,19 +107,20 @@ async function archiveThreadsRequest(getGraphqlSoupClient(),ids,value,- getActiveGraphqlSoupRevalidations()+ getUnmaintainedGraphqlSoupRevalidations());if (result.kind === 'queued')return ids.map(() => ({ status: 'fulfilled', value: 'queued' }));- await Promise.all(- ids- .filter((threadId) => !result.failedThreadIds.has(threadId))- .map((threadId) =>- refreshActiveGraphqlSoupQueries({- target: { kind: 'email-archive', threadId },- })- )- );+ if (!graphqlCacheEnabled())+ await Promise.all(+ ids+ .filter((threadId) => !result.failedThreadIds.has(threadId))+ .map((threadId) =>+ refreshActiveGraphqlSoupQueries({+ target: { kind: 'email-archive', threadId },+ })+ )+ );return settle(result.failedThreadIds);}const response = await throwOnErr(() =>diff --git a/apps/web/src/lib/queries/email/read-state-graphql.test.tsx b/apps/web/src/lib/queries/email/read-state-graphql.test.tsxindex a0083ad316..a7c0ae26e4 100644--- a/apps/web/src/lib/queries/email/read-state-graphql.test.tsx+++ b/apps/web/src/lib/queries/email/read-state-graphql.test.tsx@@ -5,6 +5,7 @@ import { mountEmailMutation } from './tests/mutation';const mocks = vi.hoisted(() => ({graphqlEnabled: true,+ cacheEnabled: true,markSeen: vi.fn(),updateLabel: vi.fn(),getLabels: vi.fn(),@@ -55,6 +56,7 @@ vi.mock('@core/component/Toast/Toast', () => ({ toast: { failure: vi.fn() } }));vi.mock('@macro-inc/observability', () => ({ Telemetry: { error: vi.fn() } }));vi.mock('@service-storage/graphql-soup', () => ({getGraphqlSoupClient: () => ({ mutation: mocks.graphqlMutation }),+ graphqlCacheEnabled: () => mocks.cacheEnabled,}));import { predictOptimisticMutation } from '@graphql-cache/exchange/optimistic-resolvers';@@ -90,6 +92,7 @@ function hasReadPatch(value: unknown, isRead: boolean): boolean {beforeEach(() => {vi.resetAllMocks();mocks.graphqlEnabled = true;+ mocks.cacheEnabled = true;mocks.legacyPatch.mockReturnValue({ rollback: vi.fn() });mocks.refresh.mockResolvedValue(undefined);client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });@@ -208,7 +211,8 @@ describe('email read state with GraphQL Soup', () => {finish();await result;}- expect(mocks.refresh).toHaveBeenCalledTimes(graphql ? 1 : 0);+ // The cached record carries the change to every list.+ expect(mocks.refresh).not.toHaveBeenCalled();});@@ -273,16 +277,40 @@ describe('email read state with GraphQL Soup', () => {finish();await result;}+ expect(mocks.refresh).not.toHaveBeenCalled();+ }+ );++ it.each([useMarkThreadAsSeenMutation, useMarkThreadAsUnreadMutation])(+ 'refreshes lists only without the normalized cache',+ async (useMutation) => {+ mocks.cacheEnabled = false;+ mocks.graphqlMutation.mockReturnValue({+ toPromise: async () => ({+ data: {+ markEmailThreadSeen: { id: 'thread', isRead: true },+ markEmailThreadUnread: { id: 'thread', isRead: false },+ },+ }),+ });+ const mutation = mountEmailMutation(useMutation, client);+ await mutation.mutateAsync({ threadId: 'thread' });expect(mocks.refresh).toHaveBeenCalledOnce();});it.each([useMarkThreadAsSeenMutation, useMarkThreadAsUnreadMutation])(- 'queues membership revalidation without refetching over offline optimism',+ 'queues an offline write that reads only unmaintained lists on replay',async (useMutation) => {const variables = { input: { initial: { limit: 50 } } };- const unregister = registerGraphqlSoupRevalidations(() => [- { document: SoupDocument, variables },+ const grouped = { input: { initial: { limit: 20 } } };+ const unregisterMaintained = registerGraphqlSoupRevalidations(+ () => [{ document: SoupDocument, variables }],+ undefined,+ () => true+ );+ const unregisterGrouped = registerGraphqlSoupRevalidations(() => [+ { document: SoupDocument, variables: grouped },]);mocks.graphqlMutation.mockReturnValue({toPromise: async () => ({@@ -297,19 +325,17 @@ describe('email read state with GraphQL Soup', () => {try {const mutation = mountEmailMutation(useMutation, client);await mutation.mutateAsync({ threadId: 'thread' });+ // Replay commits the record, which the maintained list reads; only+ // the list the cache cannot keep current is read again.expect(mocks.graphqlMutation.mock.calls[0][2].optimisticMutation.revalidations- ).toEqual([- {- document: SoupDocument,- variables,- },- ]);+ ).toEqual([{ document: SoupDocument, variables: grouped }]);expect(mocks.refresh).not.toHaveBeenCalled();expect(mocks.markSeen).not.toHaveBeenCalled();} finally {- unregister();+ unregisterMaintained();+ unregisterGrouped();}});diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.tsindex 7dba2c9f33..0ec1e57a25 100644--- a/apps/web/src/lib/queries/email/thread.ts+++ b/apps/web/src/lib/queries/email/thread.ts@@ -20,7 +20,10 @@ import {markGraphqlEmailThreadSeen,markGraphqlEmailThreadUnread,} from '@service-storage/graphql-email-read-state';-import { getGraphqlSoupClient } from '@service-storage/graphql-soup';+import {+ getGraphqlSoupClient,+ graphqlCacheEnabled,+} from '@service-storage/graphql-soup';import {type InfiniteData,useInfiniteQuery,@@ -31,7 +34,7 @@ import type { Accessor } from 'solid-js';import { queryClient } from '../client';import { optimisticUpdateSoupEntity, refetchSoupEntity } from '../soup/cache';import {- getActiveGraphqlSoupRevalidations,+ getUnmaintainedGraphqlSoupRevalidations,refreshActiveGraphqlSoupQueries,} from '../soup/graphql/active-queries';import { invalidateAllSoup } from '../soup/normalized-cache';@@ -356,12 +359,14 @@ export function useMarkThreadAsSeenMutation(return useMutation(() => ({mutationFn: async (params: MarkThreadAsSeenParams) => {if (isFeatureEnabled(enableGraphqlSoup)) {+ // The optimistic and committed `isRead` reach every list the cache+ // maintains; the rest are read again when the write commits.const disposition = await markGraphqlEmailThreadSeen(getGraphqlSoupClient(),params.threadId,- getActiveGraphqlSoupRevalidations()+ getUnmaintainedGraphqlSoupRevalidations());- if (disposition === 'committed')+ if (disposition === 'committed' && !graphqlCacheEnabled())await refreshActiveGraphqlSoupQueries();return;}@@ -413,12 +418,14 @@ export function useMarkThreadAsUnreadMutation(return useMutation(() => ({mutationFn: async (params: MarkThreadAsUnreadParams) => {if (isFeatureEnabled(enableGraphqlSoup)) {+ // The optimistic and committed `isRead` reach every list the cache+ // maintains; the rest are read again when the write commits.const disposition = await markGraphqlEmailThreadUnread(getGraphqlSoupClient(),params.threadId,- getActiveGraphqlSoupRevalidations()+ getUnmaintainedGraphqlSoupRevalidations());- if (disposition === 'committed')+ if (disposition === 'committed' && !graphqlCacheEnabled())await refreshActiveGraphqlSoupQueries();return;}diff --git a/apps/web/src/lib/queries/notification/entity-mutations.ts b/apps/web/src/lib/queries/notification/entity-mutations.tsindex 49821f9e4b..9dea6448f1 100644--- a/apps/web/src/lib/queries/notification/entity-mutations.ts+++ b/apps/web/src/lib/queries/notification/entity-mutations.ts@@ -115,20 +115,27 @@ export function toNotificationEntityInput(/*** Mark all notifications associated with the supplied entities seen or done.- * The changed-row response updates the normalized GraphQL cache; the client- * also revalidates mounted readers to reconcile stale rows omitted by a no-op.- * It is deliberately not mirrored into the legacy TanStack notification cache.- * Returned rows include only the exact IDs needed by a later ID-scoped undo.+ * The changed-row response updates the normalized GraphQL cache and every+ * reader the cache maintains, and the rest are read again. A Done records the+ * rows this client showed but the server left out+ * (`confirmEntityNotificationsDone`); a mark seen that left out an expected+ * row reads every reader again. Without the cache, mounted readers are read+ * again. It is deliberately not mirrored into the legacy TanStack+ * notification cache. Returned rows include only the exact IDs needed by a+ * later ID-scoped undo.*/export async function updateNotificationsForEntities(args: {entities: NotificationEntityRef[];operation: NotificationEntityUpdateOperation;+ /** Notifications this client shows as changing, to detect a stale view. */+ expectedNotificationIds?: readonly string[];}): Promise<UnifiedNotification[]> {if (args.entities.length === 0) return [];const rows = await updateGraphqlNotificationsForEntities({entities: args.entities.map(toNotificationEntityInput),operation: args.operation,+ expectedNotificationIds: args.expectedNotificationIds,});if (!graphqlCacheEnabled()) {await refreshActiveGraphqlSoupQueries();diff --git a/apps/web/src/lib/queries/notification/graphql/user-notifications.ts b/apps/web/src/lib/queries/notification/graphql/user-notifications.tsindex 34c670fc0f..474f96ca21 100644--- a/apps/web/src/lib/queries/notification/graphql/user-notifications.ts+++ b/apps/web/src/lib/queries/notification/graphql/user-notifications.ts@@ -16,6 +16,7 @@ import {} from '@service-storage/graphql/generated/graphql';import {getGraphqlSoupClient,+ hasGraphqlCacheHost,mapGraphqlNotification,} from '@service-storage/graphql-soup';import { executeGraphqlUpdateNotifications } from '@service-storage/graphql-update-notifications';@@ -123,6 +124,8 @@ export function createGraphqlNotificationsQuery(registerNotificationReader({client: getGraphqlSoupClient,isEnabled: () => query.isEnabled,+ // Rows render each notification's cached state.+ cacheMaintained: hasGraphqlCacheHost,refresh: () =>query.refetch({ requestPolicy: 'network-only', throwOnError: true }),})diff --git a/apps/web/src/lib/queries/notification/revalidation.ts b/apps/web/src/lib/queries/notification/revalidation.tsindex 0ee8b1751e..40e13ebc7d 100644--- a/apps/web/src/lib/queries/notification/revalidation.ts+++ b/apps/web/src/lib/queries/notification/revalidation.ts@@ -16,6 +16,8 @@ type NotificationReader = {client: () => Client;isEnabled: () => boolean;refresh: () => Promise<unknown>;+ /** Cached notification writes keep this reader current. */+ cacheMaintained?: () => boolean;};const notificationReaders = new Set<NotificationReader>();@@ -45,15 +47,20 @@ async function refreshSafely(refresh: () => Promise<unknown>): Promise<void> {}/**- * Entity writes return only changed rows. Empty AND partial responses can leave- * stale notifications behind, so refresh mounted readers after every commit.- * Reuse loaded page variables instead of resetting pagination or reading all- * cached history. Disabled/unstarted notification feeds remain dormant.+ * Reads mounted notification readers again after a notification write.+ * `unmaintainedOnly` skips readers the cache keeps current from the written+ * rows (FE-58); callers use it once the cache holds every row the write+ * changed, and read everything when it may not (a stale mark seen, Home's+ * work-feed Done and Undo, which return no notification rows). Without the+ * cache no reader is maintained. Reuses loaded page variables instead of+ * resetting pagination or reading all cached history. Disabled/unstarted+ * feeds remain dormant.*/export async function revalidateNotificationReaders(- client: Client+ client: Client,+ options: { unmaintainedOnly?: boolean } = {}): Promise<void> {- const pages = getActiveGraphqlSoupRevalidations(client).filter(+ const pages = getActiveGraphqlSoupRevalidations(client, options).filter(({ document }) => notificationDocuments.has(document));await Promise.all([@@ -68,7 +75,12 @@ export async function revalidateNotificationReaders(})),...[...notificationReaders]- .filter((reader) => reader.isEnabled() && reader.client() === client)+ .filter(+ (reader) =>+ reader.isEnabled() &&+ reader.client() === client &&+ !(options.unmaintainedOnly && reader.cacheMaintained?.())+ ).map((reader) => refreshSafely(reader.refresh)),]);}diff --git a/apps/web/src/lib/queries/notification/state-cache.ts b/apps/web/src/lib/queries/notification/state-cache.tsnew file mode 100644index 0000000000..920d6d1984--- /dev/null+++ b/apps/web/src/lib/queries/notification/state-cache.ts@@ -0,0 +1,56 @@+import { fireAndForget } from '@core/util/fireAndForget';+import type { CacheHost } from '@graphql-cache/host/types';+import {+ type NotificationState,+ NotificationStateCacheWriteDocument,+ type NotificationStateCacheWriteSubscription,+} from '@service-storage/graphql/generated/graphql';+import { getGraphqlCacheHost } from '@service-storage/graphql-soup';+import { stringifyDocument } from '@urql/core';++const stateWrite = stringifyDocument(NotificationStateCacheWriteDocument);++/**+ * Writes notification states the server confirmed without returning them.+ * Every cached reader of those rows updates, with no network read.+ */+export async function writeNotificationStates(+ host: Pick<CacheHost, 'writeQuery'>,+ ids: readonly string[],+ state: NotificationState+): Promise<void> {+ // The subscription root carries one notification per event.+ for (const id of ids) {+ await host.writeQuery({+ query: stateWrite,+ operationName: 'NotificationStateCacheWrite',+ variables: {},+ data: {+ notificationUpdates: {+ __typename: 'GraphqlUpdatedNotification',+ notification: { __typename: 'GraphqlNotification', id, state },+ },+ } satisfies NotificationStateCacheWriteSubscription,+ });+ }+}++/**+ * An entity-wide mark done answers with only the rows it changed, and rows it+ * did not change are not pushed. Every notification of the entity is done on+ * the server afterwards, so known rows the answer left out were already done+ * there and are stale here. Records them as done; false when there is no+ * cache to record them in.+ */+export function confirmEntityNotificationsDone(+ ids: readonly string[]+): boolean {+ const host = getGraphqlCacheHost();+ if (!host || ids.length === 0) return false;+ // The Done overlay retries reconciliation if the rows never read done.+ fireAndForget(+ writeNotificationStates(host, ids, 'DONE'),+ 'notification-state-cache'+ );+ return true;+}diff --git a/apps/web/src/lib/queries/notification/tests/graphql-revalidation.test.ts b/apps/web/src/lib/queries/notification/tests/graphql-revalidation.test.tsindex 1171721eaf..21c4eef876 100644--- a/apps/web/src/lib/queries/notification/tests/graphql-revalidation.test.ts+++ b/apps/web/src/lib/queries/notification/tests/graphql-revalidation.test.ts@@ -19,6 +19,7 @@ vi.mock('@app/lib/urql-solid', () => ({}));vi.mock('@service-storage/graphql-soup', () => ({getGraphqlSoupClient: () => mocks.client,+ hasGraphqlCacheHost: () => false,mapGraphqlNotification: vi.fn(),}));diff --git a/apps/web/src/lib/queries/notification/tests/state-cache.test.ts b/apps/web/src/lib/queries/notification/tests/state-cache.test.tsnew file mode 100644index 0000000000..91c85ad0ce--- /dev/null+++ b/apps/web/src/lib/queries/notification/tests/state-cache.test.ts@@ -0,0 +1,77 @@+import { beforeEach, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ host: undefined as { writeQuery: ReturnType<typeof vi.fn> } | undefined,+}));+vi.mock('@service-storage/graphql-soup', () => ({+ getGraphqlCacheHost: () => mocks.host,+}));++import {+ confirmEntityNotificationsDone,+ writeNotificationStates,+} from '../state-cache';++beforeEach(() => {+ mocks.host = { writeQuery: vi.fn(async () => ({ kind: 'written' })) };+});++it('writes only the state of each notification', async () => {+ const host = { writeQuery: vi.fn(async (_args: unknown) => ({}) as never) };+ await writeNotificationStates(host, ['n1', 'n2'], 'SEEN');+ expect(host.writeQuery.mock.calls.map(([args]) => args)).toEqual(+ ['n1', 'n2'].map((id) =>+ expect.objectContaining({+ operationName: 'NotificationStateCacheWrite',+ variables: {},+ data: {+ notificationUpdates: {+ __typename: 'GraphqlUpdatedNotification',+ notification: {+ __typename: 'GraphqlNotification',+ id,+ state: 'SEEN',+ },+ },+ },+ })+ )+ );+});++it('writes nothing for no notifications', async () => {+ const host = { writeQuery: vi.fn() };+ await writeNotificationStates(host, [], 'DONE');+ expect(host.writeQuery).not.toHaveBeenCalled();+});++it('confirms done in the cache when there is one', async () => {+ expect(confirmEntityNotificationsDone(['n1'])).toBe(true);+ await vi.waitFor(() =>+ expect(mocks.host?.writeQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ data: {+ notificationUpdates: expect.objectContaining({+ notification: expect.objectContaining({ id: 'n1', state: 'DONE' }),+ }),+ },+ })+ )+ );+});++it('reports that it cannot confirm without a cache or notifications', () => {+ expect(confirmEntityNotificationsDone([])).toBe(false);+ mocks.host = undefined;+ expect(confirmEntityNotificationsDone(['n1'])).toBe(false);+});++it('keeps a failed cache write from escaping', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ mocks.host = {+ writeQuery: vi.fn(async () => Promise.reject(new Error('closed'))),+ };+ expect(confirmEntityNotificationsDone(['n1'])).toBe(true);+ await vi.waitFor(() => expect(error).toHaveBeenCalledOnce());+ error.mockRestore();+});diff --git a/apps/web/src/lib/queries/reminders/email-followup-query.test.ts b/apps/web/src/lib/queries/reminders/email-followup-query.test.tsindex 494c756356..d8bff4bc49 100644--- a/apps/web/src/lib/queries/reminders/email-followup-query.test.ts+++ b/apps/web/src/lib/queries/reminders/email-followup-query.test.ts@@ -12,6 +12,9 @@ vi.mock('@service-storage/client', () => ({storageServiceClient: { reminders: { getEmailFollowup: read } },}));vi.mock('../soup/cache', () => ({ refetchSoupEntity: vi.fn() }));+vi.mock('@service-storage/graphql-soup', () => ({+ graphqlCacheEnabled: () => true,+}));vi.mock('../soup/graphql/active-queries', () => ({refreshActiveGraphqlSoupQueries: vi.fn(),}));diff --git a/apps/web/src/lib/queries/reminders/email-followup.test.ts b/apps/web/src/lib/queries/reminders/email-followup.test.tsindex 19acd71b3d..86dc22b727 100644--- a/apps/web/src/lib/queries/reminders/email-followup.test.ts+++ b/apps/web/src/lib/queries/reminders/email-followup.test.ts@@ -14,6 +14,10 @@ const mocks = vi.hoisted(() => ({graphql: vi.fn(),refreshGraphql: vi.fn(),fetchThread: vi.fn(),+ cacheEnabled: vi.fn(() => true),+}));+vi.mock('@service-storage/graphql-soup', () => ({+ graphqlCacheEnabled: mocks.cacheEnabled,}));vi.mock('@service-storage/client', () => ({storageServiceClient: { reminders: { setEmailFollowup: mocks.write } },@@ -75,8 +79,18 @@ describe('email follow-up cache reconciliation', () => {});expect(mocks.refreshGraphql).not.toHaveBeenCalled();});+ it('reads the thread again, and only the lists the cache does not maintain', async () => {+ mocks.graphql.mockReturnValue(true);+ mocks.cacheEnabled.mockReturnValue(true);+ await executeEmailFollowup('thread', command);+ expect(mocks.fetchThread).toHaveBeenCalledWith('thread');+ expect(mocks.refreshGraphql).toHaveBeenCalledExactlyOnceWith({+ unmaintainedOnly: true,+ });+ });it('refreshes GraphQL lists and the thread even when host navigation fails', async () => {mocks.graphql.mockReturnValue(true);+ mocks.cacheEnabled.mockReturnValue(false);const log = vi.spyOn(console, 'error').mockImplementation(() => {});try {await expect(diff --git a/apps/web/src/lib/queries/reminders/email-refresh.ts b/apps/web/src/lib/queries/reminders/email-refresh.tsindex 66af6f8897..276b9227b6 100644--- a/apps/web/src/lib/queries/reminders/email-refresh.ts+++ b/apps/web/src/lib/queries/reminders/email-refresh.ts@@ -22,8 +22,13 @@ export async function refreshEmailFollowup(threadId: string) {queryKey: emailKeys.threadMessages(threadId).queryKey,}),queryClient.invalidateQueries({ queryKey: emailKeys.previews._def }),+ // Reading the thread again updates its cached record, and with it every+ // list the cache maintains; only the others are read again....(isFeatureEnabled(enableGraphqlSoup)- ? [refreshActiveGraphqlSoupQueries(), fetchGraphqlEmailThread(threadId)]+ ? [+ fetchGraphqlEmailThread(threadId),+ refreshActiveGraphqlSoupQueries({ unmaintainedOnly: true }),+ ]: []),]);}diff --git a/apps/web/src/lib/queries/soup/graphql/active-queries.test.ts b/apps/web/src/lib/queries/soup/graphql/active-queries.test.tsindex ddf46f16cd..a506a0cf2e 100644--- a/apps/web/src/lib/queries/soup/graphql/active-queries.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/active-queries.test.ts@@ -292,4 +292,49 @@ describe('active GraphQL Soup queries', () => {expect(other).not.toHaveBeenCalled();expect(unbodied).not.toHaveBeenCalled();});++ it('skips lists the cache maintains when only the others need a read', async () => {+ const maintained = vi.fn(async () => {});+ const grouped = vi.fn(async () => {});+ let current = true;+ register({+ isEnabled: () => true,+ refresh: maintained,+ cacheMaintained: () => current,+ });+ register({ isEnabled: () => true, refresh: grouped });++ await refreshActiveGraphqlSoupQueries({ unmaintainedOnly: true });+ expect(maintained).not.toHaveBeenCalled();+ expect(grouped).toHaveBeenCalledOnce();++ // A list whose local evaluation stopped working reads the server again.+ current = false;+ await refreshActiveGraphqlSoupQueries({ unmaintainedOnly: true });+ expect(maintained).toHaveBeenCalledOnce();++ // Without the option every list is read, as for writes the cache lacks.+ current = true;+ await refreshActiveGraphqlSoupQueries();+ expect(maintained).toHaveBeenCalledTimes(2);+ });++ it('leaves maintained pages out of the revalidations a write carries', () => {+ const document = gql`query Soup($input: SoupInput!) { soup(input: $input) { nextCursor } }`;+ const mail = { document, variables: { input: { initial: { mail: 1 } } } };+ const grouped = { document, variables: { input: { initial: { g: 1 } } } };+ onTestFinished(+ registerGraphqlSoupRevalidations(+ () => [mail],+ undefined,+ () => true+ )+ );+ onTestFinished(registerGraphqlSoupRevalidations(() => [grouped]));++ expect(+ getActiveGraphqlSoupRevalidations(undefined, { unmaintainedOnly: true })+ ).toEqual([grouped]);+ expect(getActiveGraphqlSoupRevalidations()).toEqual([mail, grouped]);+ });});diff --git a/apps/web/src/lib/queries/soup/graphql/active-queries.ts b/apps/web/src/lib/queries/soup/graphql/active-queries.tsindex b0d6df5d58..83c112c334 100644--- a/apps/web/src/lib/queries/soup/graphql/active-queries.ts+++ b/apps/web/src/lib/queries/soup/graphql/active-queries.ts@@ -14,6 +14,8 @@ type ActiveGraphqlSoupQuery = {target?: () => GraphqlSoupRefreshTarget;/** The REST-shaped filter body, for refreshes scoped to matching lists. */body?: () => unknown;+ /** The normalized cache keeps this list's rows and membership current. */+ cacheMaintained?: () => boolean;};const activeQueries = new Set<ActiveGraphqlSoupQuery>();@@ -66,25 +68,32 @@ async function refreshAfter(const revalidationSources = new Set<{queries: () => readonly QueryRevalidation[];client?: () => Pick<Client, 'query'>;+ cacheMaintained?: () => boolean;}>();/** Each reader supplies its enabled, loaded pages for durable mutation replay. */export function registerGraphqlSoupRevalidations(queries: () => readonly QueryRevalidation[],- client?: () => Pick<Client, 'query'>+ client?: () => Pick<Client, 'query'>,+ /** The normalized cache keeps these pages current (see FE-58). */+ cacheMaintained?: () => boolean): () => void {- const source = { queries, client };+ const source = { queries, client, cacheMaintained };revalidationSources.add(source);return () => revalidationSources.delete(source);}-/** Snapshot query descriptors without fetching or waiting on the cache. */+/** Snapshot query descriptors without fetching or waiting on the cache.+ * `unmaintainedOnly` keeps the pages the cache cannot keep current: the only+ * ones a write that updates the cache still has to read again. */export function getActiveGraphqlSoupRevalidations(- client?: Pick<Client, 'query'>+ client?: Pick<Client, 'query'>,+ options: { unmaintainedOnly?: boolean } = {}): QueryRevalidation[] {const queries = new Map<number, QueryRevalidation>();for (const source of revalidationSources) {if (client && source.client && source.client() !== client) continue;+ if (options.unmaintainedOnly && source.cacheMaintained?.()) continue;for (const query of source.queries()) {queries.set(createRequest(query.document, query.variables).key, query);}@@ -92,6 +101,10 @@ export function getActiveGraphqlSoupRevalidations(return [...queries.values()];}+/** The pages a write that updates the normalized cache still reads again. */+export const getUnmaintainedGraphqlSoupRevalidations = () =>+ getActiveGraphqlSoupRevalidations(undefined, { unmaintainedOnly: true });+/** Registers a mounted GraphQL Soup query for mutation-driven revalidation. */export function registerActiveGraphqlSoupQuery(query: ActiveGraphqlSoupQuery@@ -110,10 +123,13 @@ export async function refreshActiveGraphqlSoupQueries(target?: GraphqlSoupRefreshTarget;/** Only refresh list readers whose filter body matches. */where?: (body: unknown) => boolean;+ /** Skip lists the cache keeps current: the write already updated them. */+ unmaintainedOnly?: boolean;} = {}): Promise<void> {const applicable = (query: ActiveGraphqlSoupQuery) => {if (!query.isEnabled()) return false;+ if (options.unmaintainedOnly && query.cacheMaintained?.()) return false;if (options.where && !options.where(query.body?.())) return false;if (!query.target) return true;const target = query.target();diff --git a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.tsindex ad732a5257..776d9dd0e6 100644--- a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts+++ b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts@@ -19,7 +19,10 @@ import { isResponseFreeNetworkError } from '../../../core/util/request-error';import { querySnapshot } from '../../../graphql-cache/exchange/live-query';import { normalizedCacheResultMetadata } from '../../../graphql-cache/exchange/normalized-cache-exchange';import { selectRecords } from '../../../graphql-cache/exchange/record-selection';-import type { CacheRevision } from '../../../graphql-cache/protocol';+import {+ type CacheRevision,+ MAX_MAIL_THROUGH_ROWS,+} from '../../../graphql-cache/protocol';import {ChannelListItemFieldsFragmentDoc,ChannelListSoupDocument,@@ -37,6 +40,7 @@ import {getGraphqlSoupCacheHost,getGraphqlSoupClient,graphqlSoupProjectionSupported,+ hasGraphqlCacheHost,} from '../../../service-clients/service-storage/graphql-soup';import { createUrqlInfiniteQuery } from '../../../urql-solid/create-urql-infinite-query';import type { UrqlInfiniteData } from '../../../urql-solid/types';@@ -89,6 +93,18 @@ export function createSoupLiveQuery(const pendingDeleteIds = usePendingGraphqlSoupDeleteIds();const offline = createBrowserOfflineSignal();const [fetchingMailPage, setFetchingMailPage] = createSignal(false);+ // The position of the last local Mail row loaded (a page's `endCursor`).+ // Cache writes re-read the page through it, so a scrolled list neither+ // collapses to its first page nor loses its last row when mail arrives+ // above it. Native engines that predate positions report none and re-read+ // the first page.+ const [localMailEdge, setLocalMailEdge] = createSignal<string | null>(null);+ // Bumped when the page chain starts over (new input, reset to the first+ // page), so paging still in flight then cannot restore the old depth.+ let pagingGeneration = 0;+ // The last local Mail evaluation for this input succeeded, so cache writes+ // keep the page current; incomplete or failed ones leave the network page.+ const [localMailCurrent, setLocalMailCurrent] = createSignal(false);const firstPageInput = createMemo<GraphqlSoupInput | undefined>(() => {const input = request();@@ -129,6 +145,8 @@ export function createSoupLiveQuery(nextCursor: string | null;revision: CacheRevision;optimistic: boolean;+ /** Position of the page's last row; null when the engine reports none. */+ edge: string | null;};};type UnpersistedPage = {@@ -175,6 +193,9 @@ export function createSoupLiveQuery(const [baselineInputKey, setBaselineInputKey] = createSignal<string>();let previousInitialInput: GraphqlSoupInput | undefined;let networkAuthorityInput: GraphqlSoupInput | undefined;+ // The server page fetched only to keep the server pages as deep as a local+ // Mail list (fetchNextPage). It never takes over from that list.+ let inStepPageIndex: number | undefined;let staleFallbackSpan: ReturnType<typeof Telemetry.span> | undefined;const recordAuthority = (@@ -249,6 +270,7 @@ export function createSoupLiveQuery(setLocalProjection(undefined);setBaselineGeneration(undefined);setUnpersistedPages(new Map());+ setLocalMailCurrent(false);};const observeCurrentRevision = async () => {const observedGeneration = cacheGeneration;@@ -375,6 +397,13 @@ export function createSoupLiveQuery(return;}if (metadata.persistence) {+ if (+ page.pageIndex === inStepPageIndex &&+ untrack(displayLocalProjection)?.mail+ ) {+ forgetUnpersistedPage(page.pageIndex);+ return;+ }const pending: UnpersistedPage = {input: firstInput,generation: cacheGeneration,@@ -425,16 +454,20 @@ export function createSoupLiveQuery(});onCleanup(- registerGraphqlSoupRevalidations(() => {- if (!query.isEnabled) return [];- const cursors = new Set([null, ...(query.data?.pageParams ?? [])]);- return [...cursors].flatMap((cursor) => {- const input = inputForCursor(cursor);- return input- ? [{ document: queryDocument(), variables: { input } }]- : [];- });- }, getGraphqlSoupClient)+ registerGraphqlSoupRevalidations(+ () => {+ if (!query.isEnabled) return [];+ const cursors = new Set([null, ...(query.data?.pageParams ?? [])]);+ return [...cursors].flatMap((cursor) => {+ const input = inputForCursor(cursor);+ return input+ ? [{ document: queryDocument(), variables: { input } }]+ : [];+ });+ },+ getGraphqlSoupClient,+ () => cacheMaintained()+ ));registerChannelNotificationRefresh(() => ({@@ -552,6 +585,19 @@ export function createSoupLiveQuery(live.status() !== 'idle' &&live.status() !== 'unsupported' &&live.status() !== 'error';+ // Whether a write that updates the cache also updates this list: a local+ // Mail page that evaluates, or a maintained predicate query. Other lists+ // (unsupported filters, a cold cache) still read the server after writes.+ const cacheMaintained = (): boolean => {+ if (!hasGraphqlCacheHost()) return false;+ if (localSource()?.mailView) return localMailCurrent();+ // A folder list keeps its email rows from the server, and a maintained+ // query still loading leaves the server page on screen.+ return (+ options().localReconciliation !== 'without-email' &&+ live.status() === 'ready'+ );+ };const liveRecords = createMemo(() => {const snapshot = live.data();@@ -597,14 +643,23 @@ export function createSoupLiveQuery(const requestGeneration = cacheGeneration;if (input !== previousInitialInput) {previousInitialInput = input;+ pagingGeneration += 1;setLocalProjection(undefined);+ setLocalMailEdge(null);+ setLocalMailCurrent(false);}+ // Server pages loaded while the network was authoritative.+ const loaded = definition?.records.length ?? 0;+ const edge = localMailEdge();const existing = untrack(localProjection);if (existing?.mail &&existing.input === input &&existing.generation === cacheGeneration &&- existing.mail.revision === revision+ existing.mail.revision === revision &&+ existing.mail.edge === edge &&+ (existing.displayedKeys.size >= loaded ||+ existing.mail.nextCursor == null))return;const host = getGraphqlSoupCacheHost();@@ -641,6 +696,7 @@ export function createSoupLiveQuery(let retryCount = 0;let discarded = false;let outcome: 'success' | 'incomplete' | 'error' = 'incomplete';+ let through = edge;try {for (let attempt = 0; attempt < 3; attempt += 1) {if (requestId !== localRequest) {@@ -651,9 +707,29 @@ export function createSoupLiveQuery(filters,sortMethod,sortDirection,- limit,- ...(mailView ? { mail: { view: mailView } } : { baseline }),+ ...(!mailView+ ? { limit, baseline }+ : through+ ? {+ // At least as deep as the server pages already shown.+ limit: Math.min(+ Math.max(limit, loaded),+ MAX_MAIL_THROUGH_ROWS+ ),+ mail: { view: mailView, through },+ }+ : { limit, mail: { view: mailView } }),});+ // A position from a replaced engine: read from the top instead.+ if (result.kind === 'stale-cursor' && through) {+ through = null;+ continue;+ }+ if (mailView) {+ span.setAttr('evaluation.through', Boolean(through));+ if (result.kind === 'mail-page')+ span.setAttr('evaluation.depth', result.keys.length);+ }if (mailView &&(result.kind === 'unsupported' || result.kind === 'incomplete')@@ -708,11 +784,18 @@ export function createSoupLiveQuery(nextCursor: result.nextCursor,revision: result.revision,optimistic: result.optimistic,+ edge: result.endCursor ?? null,},}: {}),records: reconciledRecords,});+ // The next evaluation reads through this one's last row.+ if (result.kind === 'mail-page')+ setLocalMailEdge(result.endCursor ?? null);+ // Set here: a new edge reruns the effect, which supersedes+ // this request before its `finally`.+ if (mailView) setLocalMailCurrent(true);// The filter, fragments, and final revision agree. A newer coherent// page is valid even if hydration advanced past the initial read.// Publish both result kinds' watermarks: the Mail guard avoids a@@ -733,6 +816,9 @@ export function createSoupLiveQuery(// Unsupported, incomplete, validation, and storage failures retain// the stale network/normalized-cache fallback already on screen.} finally {+ // Only the latest request decides, after any stale-revision retries.+ if (mailView && requestId === localRequest && outcome !== 'success')+ setLocalMailCurrent(false);span.setAttr('evaluation.outcome', outcome);span.setAttr('evaluation.retry_count', retryCount);span.setAttr('evaluation.discarded', discarded);@@ -806,8 +892,49 @@ export function createSoupLiveQuery(return additions.length ? [...local.records, ...additions] : local.records;});+ // Keeps the server pages as deep as a local Mail list, so it stays as deep+ // when the network page becomes authoritative again. Load More raises the+ // rows wanted, and one chain fetches pages until the server has them: the+ // infinite query coalesces a next page requested while one is in flight.+ // Not awaited: the local page is what the user sees. A failed page ends the+ // chain, and the next Load More retries it; so does a restarted page chain.+ let serverCatchUp: { generation: number; rows: number } | undefined;+ const fetchServerPagesInStep = (rows: number) => {+ if (serverCatchUp?.generation === pagingGeneration) {+ serverCatchUp.rows = Math.max(serverCatchUp.rows, rows);+ return;+ }+ const catchUp = { generation: pagingGeneration, rows };+ serverCatchUp = catchUp;+ fireAndForget(+ (async () => {+ try {+ while (+ catchUp.generation === pagingGeneration &&+ query.hasNextPage &&+ !offline() &&+ (query.data?.records().length ?? 0) < catchUp.rows+ ) {+ const pages = query.data?.pageParams.length ?? 0;+ inStepPageIndex = pages;+ await query.fetchNextPage();+ if ((query.data?.pageParams.length ?? 0) <= pages) return;+ }+ } finally {+ if (serverCatchUp === catchUp) serverCatchUp = undefined;+ }+ })(),+ 'soup-live-query'+ );+ };+ const cachedMail = createMemo(+ () => !networkIsAuthoritative() && Boolean(displayLocalProjection()?.mail)+ );const error = (): CombinedError | undefined => {const error = query.error;+ // A local Mail list pages from the cache; the server page kept in step+ // behind it is retried on the next scroll and must not replace the list.+ if (query.isFetchNextPageError && cachedMail()) return undefined;// A background transport failure must not replace usable current-query// cache results (including an empty result) with the full-screen error state.// A normalized page is usable before local reconciliation finishes. Keep@@ -836,6 +963,7 @@ export function createSoupLiveQuery();return {+ cacheMaintained,queryScope: () => JSON.stringify([firstPageInput(), cacheGeneration]),localRevision: () => displayLocalProjection()?.mail?.revision,localOptimistic: () => displayLocalProjection()?.mail?.optimistic ?? false,@@ -844,15 +972,14 @@ export function createSoupLiveQuery(return records && withoutPendingSoupEntities(records, pendingDeleteIds());}),fetchedRecords: () => query.data?.records() ?? [],- cachedMail: createMemo(- () => !networkIsAuthoritative() && Boolean(displayLocalProjection()?.mail)- ),+ cachedMail,error,isSupported,isEnabled: () => query.isEnabled,isLoading: () => query.isLoading && displayLocalProjection() === undefined,isFetching: () => query.isFetching,- isFetchingNextPage: () => fetchingMailPage() || query.isFetchingNextPage,+ isFetchingNextPage: () =>+ fetchingMailPage() || (!cachedMail() && query.isFetchingNextPage),isFetchNextPageError: () => query.isFetchNextPageError,// Current-query cache results are usable data, not previous-tab// placeholders. In particular, local recomputation must not animate the@@ -865,12 +992,15 @@ export function createSoupLiveQuery(fetchNextPage: async () => {const local = displayLocalProjection();if (!local?.mail || networkIsAuthoritative()) {+ inStepPageIndex = undefined;await query.fetchNextPage();return;}if (!local.mail.nextCursor || fetchingMailPage()) return;+ const generation = pagingGeneration;const initial ='initial' in local.input ? local.input.initial : undefined;+ fetchServerPagesInStep(local.displayedKeys.size + (initial?.limit ?? 20));const host = getGraphqlSoupCacheHost();if (!initial ||@@ -904,34 +1034,52 @@ export function createSoupLiveQuery(keys,mailView,});+ if (generation !== pagingGeneration) return;if (displayLocalProjection() !== local ||result.revision !== local.mail.revision ||selected.kind === 'stale') {- setLocalEvaluationTrigger((value) => value + 1);+ // A cache write raced the page: read the list again through the+ // page's last row, at the new revision.+ batch(() => {+ setLocalMailEdge(result.endCursor ?? null);+ setLocalEvaluationTrigger((value) => value + 1);+ });return;}const records = selected.records;- setLocalProjection({- ...local,- displayedKeys: new Set(keys),- mail: {- nextCursor: result.nextCursor,- revision: result.revision,- optimistic: result.optimistic,- },- records,+ const edge = result.endCursor ?? null;+ // Together, so the evaluation sees the new edge already displayed.+ batch(() => {+ setLocalMailEdge(edge);+ setLocalProjection({+ ...local,+ displayedKeys: new Set(keys),+ mail: {+ nextCursor: result.nextCursor,+ revision: result.revision,+ // Pending writes shown on earlier pages are still pending.+ optimistic:+ (local.mail?.optimistic ?? false) || result.optimistic,+ edge,+ },+ records,+ });});} finally {setFetchingMailPage(false);}},resetToInitialPage: () => {+ pagingGeneration += 1;query.resetToInitialPage();if (displayLocalProjection()?.mail) {- setLocalProjection(undefined);- setLocalEvaluationTrigger((value) => value + 1);+ batch(() => {+ setLocalProjection(undefined);+ setLocalMailEdge(null);+ setLocalEvaluationTrigger((value) => value + 1);+ });}},refresh: async () => {diff --git a/apps/web/src/lib/queries/soup/graphql/items.test.ts b/apps/web/src/lib/queries/soup/graphql/items.test.tsindex 9a810f7ccf..3efdc0fffa 100644--- a/apps/web/src/lib/queries/soup/graphql/items.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/items.test.ts@@ -46,6 +46,7 @@ vi.mock('../../../graphql-cache/exchange/normalized-cache-exchange', () => ({vi.mock('@service-storage/graphql-soup', () => ({getGraphqlSoupClient: getGraphqlSoupClientMock,getGraphqlSoupCacheHost: getGraphqlSoupCacheHostMock,+ hasGraphqlCacheHost: () => getGraphqlSoupCacheHostMock() !== undefined,graphqlSoupProjectionSupported: () => true,mapGraphqlSoupItem: mapGraphqlSoupItemMock,}));@@ -168,6 +169,29 @@ function deferred<T>() {return { promise, resolve, reject };}+/** Cached Mail thread records for `readRecordsByKeys`, named by their keys. */+function mailThreadRecords(requested: string[]) {+ return requested.map((key) => ({+ recordKey: key,+ record: {+ __typename: 'GraphqlSoupEmailThread',+ id: key.split(':')[1],+ name: key,+ mailAllPreview: {+ id: `${key}-preview`,+ subject: key,+ snippet: 'canonical',+ isDraft: false,+ senderEmail: null,+ senderName: null,+ senderPhotoUrl: null,+ },+ mailDraftPreview: null,+ mailSentPreview: null,+ },+ }));+}+describe('createGraphqlSoupAstItemsQuery', () => {beforeEach(() => {queryClient.clear();@@ -371,6 +395,75 @@ describe('createGraphqlSoupAstItemsQuery', () => {});+ it.each([+ { localReconciliation: undefined, maintained: true },+ { localReconciliation: 'without-email' as const, maintained: false },+ ])(+ 'reports a live list cache-maintained only once its query is ready ($localReconciliation)',+ async ({ localReconciliation, maintained }) => {+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ const record = {+ __typename: 'GraphqlSoupDocument',+ id: 'one',+ documentName: 'Doc',+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ };+ const key = 'GraphqlSoupDocument:one';+ getGraphqlSoupCacheHostMock.mockReturnValue({+ liveQueries: true,+ currentRevision: async () => REVISION_1,+ entityFilter: entityFilterMock,+ onCacheChanged: () => () => {},+ onCacheGenerationChanged: () => () => {},+ });+ const firstEvaluation = deferred<unknown>();+ entityFilterMock.mockImplementation(async (args) =>+ args.liveQuery?.release+ ? { kind: 'unsupported' }+ : firstEvaluation.promise+ );+ const { query, dispose } = createRoot((dispose) => ({+ dispose,+ query: createSoupLiveQuery(+ () => ({ filters: {}, sortMethod: 'UPDATED_AT', limit: 50 }),+ () => ({ localReconciliation })+ ),+ }));+ try {+ fake.executions[0].next(+ graphqlSoupPage({ items: [record], next_cursor: null }),+ { source: 'live-network', revision: REVISION_1 }+ );+ await vi.waitFor(() =>+ expect(entityFilterMock).toHaveBeenCalledWith(+ expect.objectContaining({ liveQuery: expect.anything() })+ )+ );+ // Still loading, the list shows the server page: writes read it again.+ expect(query.cacheMaintained?.()).toBe(false);+ firstEvaluation.resolve({+ kind: 'live-query',+ revision: REVISION_1,+ reset: true,+ keys: [key],+ upserts: [{ recordKey: key, record }],+ patches: [],+ removed: [],+ retainedKeys: [],+ optimistic: false,+ });+ // A folder list keeps its email rows from the server.+ await vi.waitFor(() =>+ expect(query.cacheMaintained?.()).toBe(maintained)+ );+ } finally {+ dispose();+ }+ }+ );+it('keeps fetched timestamp coverage when a live version of the same row has a different timestamp', async () => {const fake = makeFakeClient();getGraphqlSoupClientMock.mockReturnValue(fake.client);@@ -1822,6 +1915,453 @@ describe('createGraphqlSoupAstItemsQuery', () => {}});+ it('keeps the server page fetched behind a local Mail list out of its loading and error state', async () => {+ const online = vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(true);+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ getGraphqlSoupCacheHostMock.mockReturnValue({+ currentRevision: async () => REVISION_0,+ entityFilter: entityFilterMock,+ onCacheChanged: () => () => {},+ onCacheGenerationChanged: () => () => {},+ });+ entityFilterMock.mockImplementation(async (args) => ({+ kind: 'mail-page',+ revision: REVISION_0,+ keys: [`GraphqlSoupEmailThread:${args.mail.cursor ? 'two' : 'one'}`],+ sortTimestamps: ['2025-01-01T00:00:00.000001Z'],+ nextCursor: args.mail.cursor ? null : 'local-next',+ // Only the first page shows a pending write.+ optimistic: !args.mail.cursor,+ }));+ readRecordsByKeysMock.mockImplementation(+ async (_host, _selection, requested) => ({+ revision: REVISION_0,+ records: requested.map((key: string) => ({+ recordKey: key,+ record: {+ __typename: 'GraphqlSoupEmailThread',+ id: key.split(':')[1],+ name: key,+ mailAllPreview: {+ id: `${key}-preview`,+ subject: key,+ snippet: 'canonical',+ isDraft: false,+ senderEmail: null,+ senderName: null,+ senderPhotoUrl: null,+ },+ mailDraftPreview: null,+ mailSentPreview: null,+ },+ })),+ })+ );+ let dispose!: () => void;+ let query!: ReturnType<typeof createGraphqlSoupAstItemsQuery>;+ createRoot((d) => {+ dispose = d;+ makeGraphqlSoupInputMock.mockReturnValue({+ initial: { emailView: 'ALL', sortMethod: 'UPDATED_AT', limit: 1 },+ });+ query = createGraphqlSoupAstItemsQuery(+ () => ({ params: {}, body: {} }) as never,+ () => ({ enabled: true })+ );+ });+ try {+ await vi.waitFor(() => expect(query.data()?.cachedMail).toBe(true));+ fake.executions[0].next(+ graphqlSoupPage({ items: [], next_cursor: 'server-cursor' }),+ { source: 'normalized-cache-hit', revision: REVISION_0 }+ );+ await query.fetchNextPage();+ expect(query.data()?.entities.map((entity) => entity.id)).toEqual([+ 'one',+ 'two',+ ]);+ // The server page behind the list is requested but not waited on.+ expect(fake.executions).toHaveLength(2);+ expect(query.isFetchingNextPage()).toBe(false);+ fake.executions[1].fail(+ new CombinedError({ networkError: new Error('offline') })+ );+ expect(query.error()).toBeUndefined();+ expect(query.data()?.entities).toHaveLength(2);+ // The write still pending on the first page keeps the local list up.+ expect(query.data()?.cachedMail).toBe(true);+ } finally {+ dispose();+ online.mockRestore();+ }+ });++ it('keeps fetching server pages behind a local Mail list until they are as deep', async () => {+ const online = vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(true);+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ getGraphqlSoupCacheHostMock.mockReturnValue({+ currentRevision: async () => REVISION_0,+ entityFilter: entityFilterMock,+ onCacheChanged: () => () => {},+ onCacheGenerationChanged: () => () => {},+ });+ const all = ['one', 'two', 'three', 'four'].map(+ (id) => `GraphqlSoupEmailThread:${id}`+ );+ entityFilterMock.mockImplementation(+ async (args: {+ limit: number;+ mail: { cursor?: string; through?: string };+ }) => {+ const start = args.mail.cursor ? all.indexOf(args.mail.cursor) + 1 : 0;+ const end = args.mail.through+ ? Math.max(all.indexOf(args.mail.through) + 1, args.limit)+ : start + args.limit;+ const keys = all.slice(start, end);+ return {+ kind: 'mail-page',+ revision: REVISION_0,+ keys,+ sortTimestamps: keys.map(() => '2025-01-01T00:00:00.000001Z'),+ nextCursor: start + keys.length < all.length ? keys.at(-1) : null,+ endCursor: keys.at(-1) ?? null,+ optimistic: false,+ };+ }+ );+ readRecordsByKeysMock.mockImplementation(+ async (_host, _selection, requested: string[]) => ({+ revision: REVISION_0,+ records: mailThreadRecords(requested),+ })+ );+ let dispose!: () => void;+ let query!: ReturnType<typeof createGraphqlSoupAstItemsQuery>;+ createRoot((d) => {+ dispose = d;+ makeGraphqlSoupInputMock.mockReturnValue({+ initial: { emailView: 'ALL', sortMethod: 'UPDATED_AT', limit: 1 },+ });+ query = createGraphqlSoupAstItemsQuery(+ () => ({ params: {}, body: {} }) as never,+ () => ({ enabled: true })+ );+ });+ const serverPage = (id: string, next: string | null) =>+ graphqlSoupPage({ items: [{ id }], next_cursor: next });+ const ids = () => query.data()?.entities.map((entity) => entity.id);+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0));+ try {+ await vi.waitFor(() => expect(query.data()?.cachedMail).toBe(true));+ fake.executions[0].next(serverPage('one', 's1'), {+ source: 'normalized-cache-hit',+ revision: REVISION_0,+ });+ // Two local pages while the first server page behind them is in flight.+ await query.fetchNextPage();+ await query.fetchNextPage();+ expect(ids()).toEqual(['one', 'two', 'three']);+ expect(fake.executions).toHaveLength(2);+ fake.executions[1].next(serverPage('two', 's2'), {+ source: 'normalized-cache-hit',+ revision: REVISION_0,+ });+ // The server pages catch up with the third local row, then stop.+ await vi.waitFor(() => expect(fake.executions).toHaveLength(3));+ expect(fake.executions[2].variables).toMatchObject({+ input: { continuation: { cursor: 's2' } },+ });+ fake.executions[2].next(serverPage('three', 's3'), {+ source: 'normalized-cache-hit',+ revision: REVISION_0,+ });+ await tick();+ expect(fake.executions).toHaveLength(3);++ // A reset while a server page is in flight ends the catch-up: nothing+ // fetches the pages it dropped again.+ await query.fetchNextPage();+ expect(fake.executions).toHaveLength(4);+ query.resetToInitialPage();+ await vi.waitFor(() => expect(ids()).toEqual(['one']));+ fake.executions[3].next(serverPage('four', null), {+ source: 'normalized-cache-hit',+ revision: REVISION_0,+ });+ await tick();+ expect(fake.executions).toHaveLength(4);+ expect(ids()).toEqual(['one']);+ } finally {+ dispose();+ online.mockRestore();+ }+ });++ it('stays cache-maintained across a stale retry and stops on an engine handoff', async () => {+ const online = vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(false);+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ let revision = REVISION_0;+ let notifyGeneration: () => void = () => undefined;+ getGraphqlSoupCacheHostMock.mockReturnValue({+ currentRevision: async () => revision,+ entityFilter: entityFilterMock,+ onCacheChanged: () => () => undefined,+ onCacheGenerationChanged: (callback: () => void) => {+ notifyGeneration = callback;+ return () => undefined;+ },+ });+ entityFilterMock.mockImplementation(async () => ({+ kind: 'mail-page',+ revision,+ keys: ['GraphqlSoupEmailThread:a'],+ sortTimestamps: ['2025-01-01T00:00:00.000001Z'],+ nextCursor: null,+ optimistic: false,+ }));+ // The first read races a write: its records come from a newer revision.+ let reads = 0;+ readRecordsByKeysMock.mockImplementation(+ async (_host, _selection, requested: string[]) => {+ reads += 1;+ if (reads === 1) revision = REVISION_1;+ return {+ revision,+ records: requested.map((key) => ({+ recordKey: key,+ record: {+ __typename: 'GraphqlSoupEmailThread',+ id: key.split(':')[1],+ name: key,+ mailAllPreview: {+ id: `${key}-preview`,+ subject: key,+ snippet: 'canonical',+ isDraft: false,+ senderEmail: null,+ senderName: null,+ senderPhotoUrl: null,+ },+ mailDraftPreview: null,+ mailSentPreview: null,+ },+ })),+ };+ }+ );+ let dispose!: () => void;+ let query!: ReturnType<typeof createGraphqlSoupAstItemsQuery>;+ createRoot((d) => {+ dispose = d;+ makeGraphqlSoupInputMock.mockReturnValue({+ initial: { emailView: 'INBOX', sortMethod: 'UPDATED_AT', limit: 2 },+ });+ query = createGraphqlSoupAstItemsQuery(+ () => ({ params: {}, body: {} }) as never,+ () => ({ enabled: true })+ );+ });+ try {+ await vi.waitFor(() =>+ expect(query.data()?.entities.map(({ id }) => id)).toEqual(['a'])+ );+ expect(reads).toBeGreaterThan(1);+ // The retry succeeded, so cache writes keep this page current.+ expect(query.cacheMaintained?.()).toBe(true);++ // A new engine generation has not evaluated the page yet.+ entityFilterMock.mockImplementation(() => new Promise(() => {}));+ notifyGeneration();+ expect(query.cacheMaintained?.()).toBe(false);+ } finally {+ dispose();+ online.mockRestore();+ }+ });++ it('keeps a paged Mail list ending at the same row when mail arrives above it', async () => {+ const online = vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(false);+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ let revision = REVISION_0;+ let notifyCacheChanged: (revision: string) => void = () => undefined;+ getGraphqlSoupCacheHostMock.mockReturnValue({+ currentRevision: async () => revision,+ entityFilter: entityFilterMock,+ onCacheChanged: (callback: (revision: string) => void) => {+ notifyCacheChanged = callback;+ return () => undefined;+ },+ onCacheGenerationChanged: () => () => {},+ });+ const key = (id: string) => `GraphqlSoupEmailThread:${id}`;+ let all = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].map(key);+ let generation = 'first';+ // Like the engine's, a position names a row of one engine generation and+ // outlives writes.+ const row = (position: string) => {+ const [positionGeneration, rowKey] = position.split('|');+ return positionGeneration === generation ? rowKey : undefined;+ };+ entityFilterMock.mockImplementation(+ async (args: {+ limit: number;+ mail: { cursor?: string; through?: string };+ }) => {+ const position = args.mail.cursor ?? args.mail.through;+ const rowKey = position === undefined ? undefined : row(position);+ if (position !== undefined && rowKey === undefined)+ return { kind: 'stale-cursor', revision };+ const index = rowKey === undefined ? -1 : all.indexOf(rowKey);+ const start = args.mail.cursor ? index + 1 : 0;+ const end = args.mail.through+ ? Math.max(index + 1, args.limit)+ : start + args.limit;+ const keys = all.slice(start, end);+ const last = keys.length ? `${generation}|${keys.at(-1)}` : null;+ return {+ kind: 'mail-page',+ revision,+ keys,+ sortTimestamps: keys.map(() => '2025-01-01T00:00:00.000001Z'),+ nextCursor: start + keys.length < all.length ? last : null,+ endCursor: last,+ optimistic: false,+ };+ }+ );+ readRecordsByKeysMock.mockImplementation(+ async (_host, _selection, requested: string[]) => ({+ revision,+ records: mailThreadRecords(requested),+ })+ );+ let dispose!: () => void;+ let query!: ReturnType<typeof createGraphqlSoupAstItemsQuery>;+ createRoot((d) => {+ dispose = d;+ makeGraphqlSoupInputMock.mockReturnValue({+ initial: {+ emailView: 'INBOX',+ sortMethod: 'UPDATED_AT',+ limit: 2,+ filters: {},+ },+ });+ query = createGraphqlSoupAstItemsQuery(+ () => ({ params: {}, body: {} }) as never,+ () => ({ enabled: true })+ );+ });+ const ids = () => query.data()?.entities.map((entity) => entity.id);+ try {+ await vi.waitFor(() => expect(ids()).toEqual(['a', 'b']));+ // The first evaluation's edge does not keep it from counting as current.+ expect(query.cacheMaintained?.()).toBe(true);+ await query.fetchNextPage();+ expect(ids()).toEqual(['a', 'b', 'c', 'd']);++ // New mail lands above the list: it re-reads through its last row,+ // which a row count would have pushed off the bottom.+ all = [key('z'), ...all];+ revision = REVISION_1;+ notifyCacheChanged(REVISION_1);+ await vi.waitFor(() => expect(ids()).toEqual(['z', 'a', 'b', 'c', 'd']));+ expect(entityFilterMock.mock.calls.at(-1)?.[0]).toMatchObject({+ limit: 2,+ mail: { view: 'INBOX', through: `first|${key('d')}` },+ });++ // The next page continues after the same row, with no re-read.+ const requestsBeforePage = entityFilterMock.mock.calls.length;+ await query.fetchNextPage();+ expect(ids()).toEqual(['z', 'a', 'b', 'c', 'd', 'e', 'f']);+ expect(entityFilterMock.mock.calls.length - requestsBeforePage).toBe(1);++ // A write racing the next page: the list is read again through the+ // page's last row at the new revision.+ revision = REVISION_2;+ await query.fetchNextPage();+ await vi.waitFor(() =>+ expect(ids()).toEqual(['z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])+ );+ expect(entityFilterMock.mock.calls.at(-1)?.[0]).toMatchObject({+ mail: { through: `first|${key('h')}` },+ });++ // Resetting to the first page forgets the edge.+ query.resetToInitialPage();+ await vi.waitFor(() => expect(ids()).toEqual(['z', 'a']));+ expect(entityFilterMock.mock.calls.at(-1)?.[0].mail).toEqual({+ view: 'INBOX',+ });++ // A Load More still reading its records when the list resets does not+ // bring the old depth back.+ const pageRecords = deferred<{+ revision: string;+ records: ReturnType<typeof mailThreadRecords>;+ }>();+ let pageKeys: string[] = [];+ readRecordsByKeysMock.mockImplementationOnce(+ (_host, _selection, requested: string[]) => {+ pageKeys = requested;+ return pageRecords.promise;+ }+ );+ const loading = query.fetchNextPage();+ await vi.waitFor(() => expect(pageKeys).not.toHaveLength(0));+ query.resetToInitialPage();+ await vi.waitFor(() => expect(ids()).toEqual(['z', 'a']));+ pageRecords.resolve({ revision, records: mailThreadRecords(pageKeys) });+ await loading;+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(ids()).toEqual(['z', 'a']);+ expect(entityFilterMock.mock.calls.at(-1)?.[0].mail).toEqual({+ view: 'INBOX',+ });++ // A replaced engine no longer knows the position: read from the top.+ generation = 'second';+ revision = '3';+ const requestsBeforeReplacement = entityFilterMock.mock.calls.length;+ notifyCacheChanged('3');+ await vi.waitFor(() =>+ expect(+ entityFilterMock.mock.calls+ .slice(requestsBeforeReplacement)+ .map(([args]) => [args.limit, args.mail])+ ).toEqual([+ [2, { view: 'INBOX', through: `first|${key('a')}` }],+ [2, { view: 'INBOX' }],+ ])+ );+ await vi.waitFor(() => expect(query.localRevision?.()).toBe('3'));+ expect(ids()).toEqual(['z', 'a']);++ // Load More from a replaced engine restarts at the first page.+ generation = 'third';+ const requestsBeforeRestart = entityFilterMock.mock.calls.length;+ await query.fetchNextPage();+ await vi.waitFor(() => expect(ids()).toEqual(['z', 'a']));+ expect(+ entityFilterMock.mock.calls+ .slice(requestsBeforeRestart)+ .map(([args]) => args.mail)+ ).toEqual([+ { view: 'INBOX', cursor: `second|${key('a')}` },+ { view: 'INBOX', through: `second|${key('a')}` },+ { view: 'INBOX' },+ ]);+ } finally {+ dispose();+ online.mockRestore();+ }+ });+it.each([{ mail: true, kind: 'mail-page' },{ mail: true, kind: 'incomplete' },@@ -1878,6 +2418,9 @@ describe('createGraphqlSoupAstItemsQuery', () => {if (kind === 'mail-page' || kind === 'reconciled') {await vi.waitFor(() => expect(query.data()?.entities).toEqual([]));expect(query.data()?.cachedMail).toBe(mail);+ // A local Mail page that evaluates keeps itself current: writes+ // that update the cache need not read it again.+ if (mail) expect(query.cacheMaintained?.()).toBe(true);if (!mail)expect(entityFilterMock.mock.calls.at(-1)?.[0].baseline).toEqual([]@@ -1904,6 +2447,8 @@ describe('createGraphqlSoupAstItemsQuery', () => {} else {expect(query.data()?.cachedMail).not.toBe(true);expect(query.error()).toBe(offlineError);+ // An incomplete or unsupported page still needs the server.+ if (mail) expect(query.cacheMaintained?.()).toBe(false);}} finally {dispose();diff --git a/apps/web/src/lib/queries/soup/graphql/items.ts b/apps/web/src/lib/queries/soup/graphql/items.tsindex eb139e5e55..dac53c3e8e 100644--- a/apps/web/src/lib/queries/soup/graphql/items.ts+++ b/apps/web/src/lib/queries/soup/graphql/items.ts@@ -37,6 +37,8 @@ export type GraphqlSoupAstItemsQueryOptions = SoupLiveQueryOptions & {export type GraphqlSoupAstItemsQuery = {groupedPaging?: GroupedSoupPaging;+ /** Cache writes keep this list current. Grouped lists leave it out. */+ cacheMaintained?: Accessor<boolean>;localRevision?: Accessor<CacheRevision | undefined>;localOptimistic?: Accessor<boolean>;data: Accessor<SoupAstItemsData | undefined>;diff --git a/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts b/apps/web/src/lib/queries/soup/items.transport-refetch.test.tsindex 68eea9eea6..174775b91f 100644--- a/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts+++ b/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts@@ -318,6 +318,8 @@ describe('Soup refetch transport selection', () => {vi.clearAllMocks();await refreshActiveGraphqlSoupQueries();+ // The refresh rebuilds every loaded page; resetting first would collapse+ // a scrolled list to its first page after each mutation.expect(groupedQuery.resetToInitialPage).not.toHaveBeenCalled();expect(groupedQuery.refresh).toHaveBeenCalledOnce();expect(restRefetch).not.toHaveBeenCalled();diff --git a/apps/web/src/lib/queries/soup/items.ts b/apps/web/src/lib/queries/soup/items.tsindex 5605cf4a33..df57c443dd 100644--- a/apps/web/src/lib/queries/soup/items.ts+++ b/apps/web/src/lib/queries/soup/items.ts@@ -439,14 +439,17 @@ export function useSoupAstItemsQuery(usesGraphql() &&activeGraphqlQuery().isEnabled() &&!options?.().networkPaused,+ // The refresh refetches every loaded page in cursor order and keeps the+ // old pages on screen until their replacements arrive, so a mutation+ // never collapses a scrolled list to its first page.refresh: async () => {- if (args().groupBy === undefined) {- activeGraphqlQuery().resetToInitialPage();+ if (args().groupBy === undefined)options?.().onBeforeGraphqlRefresh?.();- }await activeGraphqlQuery().refresh();},body: () => args().body,+ // Grouped lists don't report it yet, so writes still read them again.+ cacheMaintained: () => activeGraphqlQuery().cacheMaintained?.() ?? false,}));diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-notification-revalidation.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-notification-revalidation.test.tsindex 2de0782782..2ec692e19e 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-notification-revalidation.test.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-notification-revalidation.test.ts@@ -12,10 +12,17 @@ import {} from './graphql/generated/graphql';import { executeGraphqlUpdateNotificationsForEntities } from './graphql-update-notifications';+const mocks = vi.hoisted(() => ({ cache: false }));+vi.mock('./graphql-soup', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./graphql-soup')>()),+ graphqlCacheEnabled: () => mocks.cache,+}));+const cleanup: Array<() => void> = [];afterEach(() => {for (const dispose of cleanup.splice(0)) dispose();vi.restoreAllMocks();+ mocks.cache = false;});function setup() {@@ -48,7 +55,7 @@ const input = {operation: 'MARK_SEEN' as const,};-describe('entity notification reconciliation', () => {+describe('entity notification reconciliation without the normalized cache', () => {it.each(['MARK_SEEN', 'MARK_DONE'] as const)('reconciles an empty %s response without changing its undo IDs',async (operation) => {@@ -188,3 +195,94 @@ describe('entity notification reconciliation', () => {expect(query).not.toHaveBeenCalled();});});++describe('entity notification reconciliation with the normalized cache', () => {+ function setupCached() {+ mocks.cache = true;+ const query = vi.fn(() => ({ toPromise: async () => ({ data: {} }) }));+ const initial = { input: { initial: { limit: 20 } } };+ const maintained = { document: SoupDocument, variables: initial };+ const grouped = { document: GroupSoupDocument, variables: initial };+ cleanup.push(+ registerGraphqlSoupRevalidations(+ () => [maintained],+ undefined,+ () => true+ ),+ registerGraphqlSoupRevalidations(() => [grouped])+ );+ const feed = vi.fn(async () => undefined);+ cleanup.push(+ registerNotificationReader({+ client: () => client,+ isEnabled: () => true,+ refresh: feed,+ cacheMaintained: () => true,+ })+ );+ const respond = (rows: { id: string }[]) =>+ vi.fn(() => ({+ toPromise: async () => ({+ data: {+ updateNotificationsForEntity: rows.map((row) => ({+ __typename: 'GraphqlNotification',+ state: 'SEEN',+ ...row,+ })),+ },+ }),+ }));+ const client = { query, mutation: respond([]) } as unknown as Client;+ return { client, query, feed, grouped, maintained, respond };+ }++ it('reads again only the readers the cache does not maintain', async () => {+ const { client, query, feed, grouped, respond } = setupCached();+ const withRows = {+ ...client,+ mutation: respond([{ id: 'n1' }]),+ } as unknown as Client;++ await executeGraphqlUpdateNotificationsForEntities(withRows, {+ ...input,+ expectedNotificationIds: ['n1'],+ });++ expect(query).toHaveBeenCalledExactlyOnceWith(+ grouped.document,+ grouped.variables,+ { requestPolicy: 'network-only' }+ );+ expect(feed).not.toHaveBeenCalled();+ });++ it('reads every reader again when a mark seen leaves out an expected row', async () => {+ const { client, query, feed, maintained } = setupCached();++ // This client showed n1 unseen; the server changed nothing, so n1 is+ // already seen or done there and only a read can tell which.+ await executeGraphqlUpdateNotificationsForEntities(client, {+ ...input,+ expectedNotificationIds: ['n1'],+ });++ expect(query).toHaveBeenCalledWith(+ maintained.document,+ maintained.variables,+ { requestPolicy: 'network-only' }+ );+ expect(feed).toHaveBeenCalledOnce();+ });++ it('never sends the expected rows to the server', async () => {+ const { client } = setupCached();+ await executeGraphqlUpdateNotificationsForEntities(client, {+ ...input,+ expectedNotificationIds: ['n1'],+ });+ expect(client.mutation).toHaveBeenCalledWith(+ UpdateNotificationsForEntityDocument,+ { input }+ );+ });+});diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.tsindex 8e4923f32a..80e23e2577 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts@@ -645,6 +645,10 @@ export function getGraphqlCacheHost(): CacheHost | undefined {return cachedCacheHost?.disabled ? undefined : cachedCacheHost;}+/** Cache writes reach readers of the normalized cache only while it runs. */+export const hasGraphqlCacheHost = (): boolean =>+ graphqlCacheEnabled() && getGraphqlCacheHost() !== undefined;+/*** Resolves the urql client, lazily assembling the cached client on first* use. The cache scope is an anonymous client uuid — no identity lookup isdiff --git a/apps/web/src/lib/service-clients/service-storage/graphql-update-notifications.ts b/apps/web/src/lib/service-clients/service-storage/graphql-update-notifications.tsindex aaf1d34d20..fa83a7eac2 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-update-notifications.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-update-notifications.ts@@ -30,8 +30,22 @@ export type GraphqlUpdateNotificationsResult =export type GraphqlUpdateNotificationsForEntitiesArgs = {entities: NotificationEntityInput[];operation: Exclude<NotificationUpdateOperation, 'MARK_UNDONE'>;+ /** Notifications this client shows as changing; never sent. A mark seen+ * that leaves one out means this client was stale. */+ expectedNotificationIds?: readonly string[];};+/** A mark seen answers with only the rows it changed. An expected row it left+ * out is seen or done elsewhere, which this client cannot tell apart. */+function missedExpectedSeen(+ args: GraphqlUpdateNotificationsForEntitiesArgs,+ rows: readonly { id: string }[]+): boolean {+ if (args.operation !== 'MARK_SEEN') return false;+ const changed = new Set(rows.map(({ id }) => id));+ return (args.expectedNotificationIds ?? []).some((id) => !changed.has(id));+}+/** Authoritative rows returned after an entity-scoped notification write. */export type GraphqlUpdateNotificationsForEntitiesResult =UpdateNotificationsForEntityMutation['updateNotificationsForEntity'];@@ -103,6 +117,16 @@ export async function executeGraphqlUpdateNotificationsForEntities(const result = await client.mutation(UpdateNotificationsForEntityDocument, variables).toPromise();- if (!result.error && result.data) await revalidateNotificationReaders(client);+ if (!result.error && result.data) {+ // The changed rows update every reader the cache maintains; the others+ // are read again. A stale mark seen reads every reader again: the rows+ // it left out are seen or done, and only the server knows which.+ await revalidateNotificationReaders(client, {+ unmaintainedOnly: !missedExpectedSeen(+ args,+ result.data.updateNotificationsForEntity+ ),+ });+ }return result;}diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.tsindex 1b41a20783..ad7d1222dd 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts@@ -12387,6 +12387,15 @@ export type DeleteInitiativeMutationVariables = Exact<{export type DeleteInitiativeMutation = { deleteInitiative: boolean };+export type NotificationStateCacheWriteSubscriptionVariables = Exact<{ [key: string]: never; }>;+++export type NotificationStateCacheWriteSubscription = { notificationUpdates:+ | { __typename: 'GraphqlCacheDeletion' }+ | { __typename: 'GraphqlNewNotification' }+ | { __typename: 'GraphqlUpdatedNotification', notification: { __typename: 'GraphqlNotification', id: string, state: NotificationState } }+ };+export type NotificationUpdatesSubscriptionVariables = Exact<{ [key: string]: never; }>;@@ -20877,6 +20886,7 @@ export const CreateInitiativeDocument = {"kind":"Document","definitions":[{"kindexport const UpdateInitiativeDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateInitiative"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"initiativeId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateInitiativeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateInitiative"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"initiativeId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"initiativeId"}}},{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"InitiativeDetailFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyValueFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDateRangePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"rangeStart"},"name":{"kind":"Name","value":"start"}},{"kind":"Field","alias":{"kind":"Name","value":"rangeEnd"},"name":{"kind":"Name","value":"end"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyValueFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"InitiativeDetailFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupInitiative"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"viewerPermission"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAccessLevelPermission"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"accessLevel"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"taskCount"}},{"kind":"Field","name":{"kind":"Name","value":"completedTaskCount"}},{"kind":"Field","name":{"kind":"Name","value":"memberIds"}},{"kind":"Field","name":{"kind":"Name","value":"taskIds"}},{"kind":"Field","name":{"kind":"Name","value":"sharePermission"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"owner"}},{"kind":"Field","name":{"kind":"Name","value":"linkShare"}},{"kind":"Field","name":{"kind":"Name","value":"linkShareAccessLevel"}},{"kind":"Field","name":{"kind":"Name","value":"teamShareAccessLevel"}},{"kind":"Field","name":{"kind":"Name","value":"channelSharePermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"accessLevel"}}]}}]}}]}}]} as unknown as DocumentNode<UpdateInitiativeMutation, UpdateInitiativeMutationVariables>;export const EnsureInitiativeDescriptionSurfaceDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"EnsureInitiativeDescriptionSurface"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"initiativeId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"ensureInitiativeDescriptionSurface"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"initiativeId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"initiativeId"}}}]}]}}]} as unknown as DocumentNode<EnsureInitiativeDescriptionSurfaceMutation, EnsureInitiativeDescriptionSurfaceMutationVariables>;export const DeleteInitiativeDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteInitiative"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"initiativeId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteInitiative"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"initiativeId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"initiativeId"}}}]}]}}]} as unknown as DocumentNode<DeleteInitiativeMutation, DeleteInitiativeMutationVariables>;+export const NotificationStateCacheWriteDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"NotificationStateCacheWrite"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"notificationUpdates"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlUpdatedNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"notification"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"state"}}]}}]}}]}}]}}]} as unknown as DocumentNode<NotificationStateCacheWriteSubscription, NotificationStateCacheWriteSubscriptionVariables>;export const NotificationUpdatesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"NotificationUpdates"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"notificationUpdates"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNewNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"notification"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlUpdatedNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"notification"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCacheDeletion"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"graphqlTypeName"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationStateFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","alias":{"kind":"Name","value":"entityType"},"name":{"kind":"Name","value":"targetEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationNavigationMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotifEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlWhatsappGroupMessageMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"whatsappGroupName"},"name":{"kind":"Name","value":"groupName"}},{"kind":"Field","alias":{"kind":"Name","value":"whatsappMessageId"},"name":{"kind":"Name","value":"messageId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelType"},"name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDocumentMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentMentionDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlMentionedInDocumentCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentMentionId"},"name":{"kind":"Name","value":"mentionId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRepliedToDocumentCommentThreadMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityAccessRequestedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"entityAccessRequestedRequestId"},"name":{"kind":"Name","value":"requestId"}},{"kind":"Field","alias":{"kind":"Name","value":"entityAccessRequestedRevision"},"name":{"kind":"Name","value":"revision"}},{"kind":"Field","alias":{"kind":"Name","value":"entityAccessRequestedEntityName"},"name":{"kind":"Name","value":"entityName"}},{"kind":"Field","alias":{"kind":"Name","value":"entityAccessRequestedFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"entityAccessRequestedAccessLevel"},"name":{"kind":"Name","value":"accessLevel"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityAccessGrantedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"entityAccessGrantedRequestId"},"name":{"kind":"Name","value":"requestId"}},{"kind":"Field","alias":{"kind":"Name","value":"entityAccessGrantedRevision"},"name":{"kind":"Name","value":"revision"}},{"kind":"Field","alias":{"kind":"Name","value":"entityAccessGrantedEntityName"},"name":{"kind":"Name","value":"entityName"}},{"kind":"Field","alias":{"kind":"Name","value":"entityAccessGrantedFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"entityAccessGrantedAccessLevel"},"name":{"kind":"Name","value":"accessLevel"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCommentedOnDocumentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInitiativeDiscussionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionProjectName"},"name":{"kind":"Name","value":"projectName"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionReason"},"name":{"kind":"Name","value":"reason"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCrmDiscussionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionRecordName"},"name":{"kind":"Name","value":"recordName"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionReason"},"name":{"kind":"Name","value":"reason"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelInviteMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelInviteInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageSendMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelType"},"name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageReactionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionEmoji"},"name":{"kind":"Name","value":"emoji"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelReplyMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyUserId"},"name":{"kind":"Name","value":"userId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadParentSenderId"},"name":{"kind":"Name","value":"threadParentSenderId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelType"},"name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCallStartedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"callStartedChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"callStartedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNewEmailMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"newEmailSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailToEmail"},"name":{"kind":"Name","value":"toEmail"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSubject"},"name":{"kind":"Name","value":"subject"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSnippet"},"name":{"kind":"Name","value":"snippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInboxReauthRequiredMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inboxReauthRequiredEmailAddress"},"name":{"kind":"Name","value":"emailAddress"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInviteToTeamMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamName"},"name":{"kind":"Name","value":"teamName"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamInviteId"},"name":{"kind":"Name","value":"teamInviteId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamRole"},"name":{"kind":"Name","value":"role"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskAssignedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskId"},"name":{"kind":"Name","value":"taskId"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskName"},"name":{"kind":"Name","value":"taskName"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedAssignedBy"},"name":{"kind":"Name","value":"assignedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"reminderReminderId"},"name":{"kind":"Name","value":"reminderId"}},{"kind":"Field","alias":{"kind":"Name","value":"reminderDescription"},"name":{"kind":"Name","value":"description"}},{"kind":"Field","alias":{"kind":"Name","value":"reminderScheduledFor"},"name":{"kind":"Name","value":"scheduledFor"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCalendarEventReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEventId"},"name":{"kind":"Name","value":"eventId"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderOccurrenceKey"},"name":{"kind":"Name","value":"occurrenceKey"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartsAt"},"name":{"kind":"Name","value":"startsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEndsAt"},"name":{"kind":"Name","value":"endsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartDate"},"name":{"kind":"Name","value":"startDate"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTimeZone"},"name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderMinutesBefore"},"name":{"kind":"Name","value":"minutesBefore"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCalendarEventJoinRequestMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"calendarEventJoinRequestRequestId"},"name":{"kind":"Name","value":"requestId"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventJoinRequestEventId"},"name":{"kind":"Name","value":"eventId"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventJoinRequestTitle"},"name":{"kind":"Name","value":"title"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAiResponseMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"aiResponseSummary"},"name":{"kind":"Name","value":"summary"}},{"kind":"Field","alias":{"kind":"Name","value":"aiResponseMessageId"},"name":{"kind":"Name","value":"messageId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrStatusChangedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedStatus"},"name":{"kind":"Name","value":"status"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedAction"},"name":{"kind":"Name","value":"action"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedPreviousStatus"},"name":{"kind":"Name","value":"previousStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedHeadBranch"},"name":{"kind":"Name","value":"headBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedBaseBranch"},"name":{"kind":"Name","value":"baseBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedMergedAt"},"name":{"kind":"Name","value":"mergedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCheckRunMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckRunGithubId"},"name":{"kind":"Name","value":"checkRunGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckName"},"name":{"kind":"Name","value":"checkName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckStatus"},"name":{"kind":"Name","value":"checkStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunConclusion"},"name":{"kind":"Name","value":"conclusion"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckUrl"},"name":{"kind":"Name","value":"checkUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCompletedAt"},"name":{"kind":"Name","value":"completedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubReviewRequestedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubLogin"},"name":{"kind":"Name","value":"requestedReviewerGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubUserId"},"name":{"kind":"Name","value":"requestedReviewerGithubUserId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentKind"},"name":{"kind":"Name","value":"commentKind"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentSnippet"},"name":{"kind":"Name","value":"commentSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionLocation"},"name":{"kind":"Name","value":"location"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTextSnippet"},"name":{"kind":"Name","value":"textSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrReviewMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewGithubId"},"name":{"kind":"Name","value":"reviewGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewUrl"},"name":{"kind":"Name","value":"reviewUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewSnippet"},"name":{"kind":"Name","value":"reviewSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionSettledMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledActor"},"name":{"kind":"Name","value":"actor"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledStopReason"},"name":{"kind":"Name","value":"stopReason"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledExcerpt"},"name":{"kind":"Name","value":"excerpt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionWaitingForInputMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputQuestion"},"name":{"kind":"Name","value":"question"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionMentionedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedMentionedBy"},"name":{"kind":"Name","value":"mentionedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedActionId"},"name":{"kind":"Name","value":"actionId"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotifEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationNavigationMetadataFields"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageSendMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelReplyMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelReplyHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationStateFields"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationMetadataFields"}}]}}]}}]} as unknown as DocumentNode<NotificationUpdatesSubscription, NotificationUpdatesSubscriptionVariables>;export const ItemPreviewNameCacheWriteDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ItemPreviewNameCacheWrite"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelDisplayName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"companyName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<ItemPreviewNameCacheWriteQuery, ItemPreviewNameCacheWriteQueryVariables>;export const ItemPreviewFileTypeCacheWriteDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ItemPreviewFileTypeCacheWrite"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"fileType"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<ItemPreviewFileTypeCacheWriteQuery, ItemPreviewFileTypeCacheWriteQueryVariables>;diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/notification-state-cache-write.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/notification-state-cache-write.graphqlnew file mode 100644index 0000000000..cc5ffedee0--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/graphql/notification-state-cache-write.graphql@@ -0,0 +1,15 @@+# Local cache entrypoint only: subscription roots are not persisted as query+# membership. Writes a notification state the server has confirmed without+# replaying any of the notification's other fields.+subscription NotificationStateCacheWrite {+ notificationUpdates {+ __typename+ ... on GraphqlUpdatedNotification {+ notification {+ __typename+ id+ state+ }+ }+ }+}diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex e42315403b..41e3a4e435 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -1130,6 +1130,10 @@ scroll position, and input focus. To check stale-cache recovery, mark notificatiread/done in another tab, then repeat the action in a stale tab. Empty or partialchanged-row responses must still reconcile mounted Soup and notification readers,without resetting loaded pages or starting an unused global notification feed.+With the normalized cache, a Done writes the rows it left out as done+(`confirmEntityNotificationsDone`), and a mark seen that left out a row the tab+showed unseen reads every reader again; otherwise only readers the cache does not+maintain are read again.Undo must use only the mutation's returned IDs, not IDs from the subsequent refresh.The backend must support the new edge arguments before deploying the frontendthat requests them.diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex d5dd3ffa44..08dadc520c 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -148,6 +148,15 @@ that start within 40px of the left edge are left to swipe-back navigation.Search results use the same reserved column, with actions aligned to the firstline; snippets, highlighted matches, and expanded hits remain unobstructed.+The list holds still while mail changes under it. Scrolled down, new mail or a+thread marked done elsewhere above the viewport leaves the rows on screen where+they are; at the top, new mail appears at the top. Cache writes (the mail+backfill, read marks, thread loads) and mutation refreshes keep the list as deep+as it was loaded, and Load More keeps working while they land. Verify by+scrolling past the first 100 threads, then marking a thread done and letting new+mail arrive (locally: insert a thread and publish `email.message_received` on+`macro.email`).+When switching email tabs or inboxes, the list shows current-query cached resultsor a scoped `Loading email` spinner until they arrive—not the previous tab's rowsunder the new heading. Active searches also hide retained results and show loading@@ -217,17 +226,19 @@ the server resolves that inbox's UNREAD label and returns the canonical thread(`__typename`, `id`, `isRead`) to reconcile the cache. The row should flip immediatelyeven when the client labels cache is missing or stale—no label fetch precedes theoptimistic update. Queued read/unread writes retain revalidation descriptors for-active flat and grouped lists, including loaded continuation pages. Once replay-commits (even after a reload), those queries refresh from the server; they should-not refetch over the optimistic state merely because a write was queued. Trash+the active lists the cache does not maintain (grouped lists, filters it cannot+evaluate, a Mail page the cache cannot evaluate locally), including loaded+continuation pages. Once replay commits (even after a reload), only those queries+refresh from the server; they should not refetch over the optimistic state merely+because a write was queued. Trashand its Undo refresh mounted GraphQL lists after the server operation finishes.The GraphQL-disabled REST path is unchanged. With GraphQL enabled, archive-basedMark Done, Mark Not Done, and Undo/Redo use `setEmailThreadArchived`: `inboxVisible`updates optimistically in the normalized cache, and each reversal is a distinctordered queue entry. The server resolves the thread's owning/delegated inbox;-no client INBOX-label lookup is needed. Confirmed writes revalidate mounted lists,-including continuation pages; queued writes retain those descriptors for replay-without refetching over optimism. Callers preserve the queued disposition and+no client INBOX-label lookup is needed. Confirmed writes revalidate the mounted+lists the cache does not maintain, including continuation pages; queued writes+retain those descriptors for replay without refetching over optimism. Callers preserve the queued disposition andskip REST/TanStack email invalidations as well, including Done/Undo batches andthread archive replay. Committed writes and failed non-queued batches stillreconcile. Permanent failures roll back the failed intent.@@ -248,9 +259,17 @@ remain restored. Only acceptedthreads get their notifications restored. Notification or list-refresh failureswarn without rolling back accepted unarchives. Verify mixed committed/queued/rejected selections, partial-success counts, and that a queued sibling prevents-shared-list refetch even when notification restoration fails. GraphQL reversals-rely on normalized writes and their durable revalidation, not an extra REST Soup-refetch after rows settle. Verify the open-thread header too: with GraphQL enabled,+shared-list refetch even when notification restoration fails. With the normalized+cache, a list the cache maintains is not read again after Done, Not Done, Undo,+read/unread, an entity notification update or a draft save: the optimistic write+and the returned records update it, and it re-evaluates from the cache (FE-58).+Every Mail tab is maintained once its local evaluation succeeds; grouped lists and+filters the cache cannot evaluate are still read again. A reminder reads its+thread again plus Home's unread presence, whose `unreadReminders` edge no cached+write fills. Home's work-feed Done and Undo return no notification rows, so they+still read every notification reader again. In the+network panel one `e` in the Email view sends its two mutations and no `Soup`,+`SoupNotifications` or `ChannelUnreadPresence` query. Verify the open-thread header too: with GraphQL enabled,Mark Not Done remains available for an archived thread whose inbox timestamp ismissing; the server decides whether its received-message history allows restoration.The REST path retains its timestamp preflight, whole-batch handling, notification@@ -306,8 +325,8 @@ retain their Inbox scope, so archived mail is found in Archived (All + Done).A `Showing cached mail` notice identifies results over synchronized metadata, not aclaim of complete mailbox coverage. These lists paginate locally beyond the first-page without a server cursor. Filter, revision, or engine-generation changes restart-the local page chain; online server results take over again when available. After+page without a server cursor. Filter or engine-generation changes restart+the local page chain, and a cache write re-reads it through the last row already loaded; online server results take over again when available. Afterreconnecting, `Load more` follows the same server page chain as the displayed rows,not a leftover local cursor. Account choices are cached in the viewer-scoped GraphQL catalog. Timestamp ordering and dateheaders use the selected Mail view's indexed timestamps, not a preview cached fromdiff --git a/docs/agent-guide/soup-live-updates.md b/docs/agent-guide/soup-live-updates.mdindex 270a387457..b25a650d5f 100644--- a/docs/agent-guide/soup-live-updates.md+++ b/docs/agent-guide/soup-live-updates.md@@ -90,7 +90,10 @@ reappear in its request nor be retried by Redo. Partial feedback keeps an Undoaction. A reply with no matching notification IDs must release that target'soptimistic hide and notification overrides immediately, even if Undo was neverclicked and mounted readers remain stale. Do not wait for acknowledgement or a-timer when there is no receipt. Accepted siblings keep their own display intent;+timer when there is no receipt. The exception is an entity-wide Done with the+normalized cache: the rows it left out were already done on the server, so they+are written as done into the cache and the hide stays until readers acknowledge+it; that target has nothing to undo. Accepted siblings keep their own display intent;a no-op target cannot borrow their IDs to restore its row. Mixed accepted/no-opresults replace the optimistic full-count toast with the actual completed countand retain Undo for accepted writes. An empty notification receipt alone must not