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(soup): make Done and Undo immediate with safe unarchive (#7300)
Sean Ayeeac5bbca6ae5
diff --git a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts b/apps/web/src/features/block-agent/context/resolve-session-id.test.tsindex 9db8b52013..e6eb40fd5b 100644--- a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts+++ b/apps/web/src/features/block-agent/context/resolve-session-id.test.ts@@ -9,6 +9,11 @@ import type { AgentAction } from '@service-agent-harness/generated/schemas';import { createRoot } from 'solid-js';import { beforeEach, describe, expect, it, vi } from 'vitest';+const refetchSoupEntity = vi.hoisted(() => vi.fn(async () => {}));+// Session creation refreshes Soup in the background. Keep this unit test at+// the query boundary so real auth/network work cannot outlive its environment.+vi.mock('@queries/soup/normalized-cache', () => ({ refetchSoupEntity }));+const create = vi.hoisted(() => ({resolve: undefined as ((id?: string) => void) | undefined,reject: undefined as (() => void) | undefined,@@ -111,6 +116,7 @@ const { resolveSessionId } = await import('./resolve-session-id');const flush = () => new Promise((resolve) => setTimeout(resolve, 0));beforeEach(() => {+ refetchSoupEntity.mockClear();create.control.mockReset();create.release.mockReset();create.autoConfirm = true;@@ -160,6 +166,11 @@ describe('an id whose create is in flight', () => {expect(resolved.sessionId()).toBe(placeholder);expect(resolved.pending()).toBe(false);+ expect(refetchSoupEntity).toHaveBeenCalledExactlyOnceWith(+ placeholder,+ 'agentSession',+ { created: true }+ );dispose();});});@@ -174,6 +185,11 @@ describe('an id whose create is in flight', () => {await flush();expect(resolved.sessionId()).toBe('server-minted');expect(resolved.pending()).toBe(false);+ expect(refetchSoupEntity).toHaveBeenCalledExactlyOnceWith(+ 'server-minted',+ 'agentSession',+ { created: true }+ );dispose();});});@@ -189,6 +205,7 @@ describe('an id whose create is in flight', () => {expect(resolved.pending()).toBe(false);expect(resolved.error()).toBe('Connect GitHub to use this repository.');expect(resolved.sessionId()).toBeUndefined();+ expect(refetchSoupEntity).not.toHaveBeenCalled();dispose();});});diff --git a/apps/web/src/features/email-thread/thread-completion-adapter.test.ts b/apps/web/src/features/email-thread/thread-completion-adapter.test.tsnew file mode 100644index 0000000000..323e279d3d--- /dev/null+++ b/apps/web/src/features/email-thread/thread-completion-adapter.test.ts@@ -0,0 +1,230 @@+import type { EntityData } from '@entity';+import type { useUndoableArchiveThreadMutation } from '@queries/email/thread';+import { createMemo, createRoot, createSignal } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { EmailThread } from './core/email-thread';++type ArchiveOptions = Parameters<typeof useUndoableArchiveThreadMutation>[0];+const mocks = vi.hoisted(() => ({+ feature: vi.fn(() => ({ enabled: false })),+ lookup: vi.fn<() => { original: EntityData } | undefined>(),+ executeNotDone: vi.fn(async () => 'committed' as const),+ trackArchive: vi.fn(),+ mutate: vi.fn(+ (+ _params: { threadId: string; archive: boolean; linkId?: string },+ _callbacks?: {+ onSuccess: (disposition: 'committed' | 'queued') => Promise<void>;+ }+ ) => {}+ ),+ archiveOptions: undefined as ArchiveOptions | undefined,+ refetchSoupEntity: vi.fn(async () => {}),+ invalidateAllSoup: vi.fn(),+}));+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => mocks.feature,+}));+vi.mock('@core/constant/featureFlags', () => ({+ enableGraphqlSoup: { key: 'enable-graphql-soup' },+}));+vi.mock('@app/features/entity/utils/buildEntityData', () => ({+ buildEntityData: vi.fn(),+}));+vi.mock('@app/features/next-soup/actions', () => ({+ makeMarkDoneAction: () => ({ execute: vi.fn(), executeWithSoup: vi.fn() }),+ makeMarkNotDoneAction: () => ({+ canExecute: () => true,+ execute: mocks.executeNotDone,+ }),+}));+vi.mock('@app/features/next-soup/soup-context', () => ({+ useMaybeSoup: () => ({ items: { get: mocks.lookup } }),+}));+vi.mock('@app/features/next-soup/utils', () => ({+ openEntityInSplitFromUnifiedList: vi.fn(),+}));+vi.mock('@components/app/GlobalAppState', () => ({+ useGlobalNotificationSource: () => ({ notificationsByEntity: () => ({}) }),+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanel: () => undefined,+}));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'viewer' }));+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: vi.fn(() => 1), failure: vi.fn(), dismiss: vi.fn() },+}));+vi.mock('@notifications', () => ({+ compositeEntity: () => 'thread',+ setDoneOverride: vi.fn(),+}));+vi.mock(+ '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid',+ () => ({ default: () => null })+);+vi.mock('@queries/email/thread', () => ({+ trackExternalThreadArchive: mocks.trackArchive,+ useUndoableArchiveThreadMutation: (options: ArchiveOptions) => {+ mocks.archiveOptions = options;+ return { mutate: mocks.mutate };+ },+}));+vi.mock('@queries/notification/user-notifications', () => ({+ bulkMarkNotificationsAsDone: vi.fn(async () => {}),+ bulkMarkNotificationsAsUndone: vi.fn(async () => {}),+ fetchDoneNotificationIdsByEventItemIds: vi.fn(async () => []),+}));+vi.mock('@queries/soup/cache', () => ({+ getSoupEntityById: vi.fn(),+ refetchSoupEntity: mocks.refetchSoupEntity,+ invalidateAllSoup: mocks.invalidateAllSoup,+}));+vi.mock('@queries/soup/transform-utils', () => ({+ isDisplayableSoupItem: () => false,+ mapApiSoupItemToEntity: vi.fn(),+}));++import { createThreadCompletionAdapter } from './thread-completion-adapter';++const disposals: (() => void)[] = [];+afterEach(() => {+ for (const dispose of disposals.splice(0)) dispose();+});+beforeEach(() => {+ vi.clearAllMocks();+ mocks.feature.mockReturnValue({ enabled: false });+ mocks.lookup.mockReturnValue(undefined);+});+function setup(thread: EmailThread | undefined) {+ return createRoot((dispose) => {+ disposals.push(dispose);+ return createThreadCompletionAdapter(+ () => thread,+ (link) => link ?? undefined+ );+ });+}+const thread = (+ inbox_visible = false,+ latest_inbound_message_ts: string | null = null+): EmailThread => ({+ db_id: 'thread',+ link_id: 'link',+ access_level: 'owner',+ is_read: true,+ inbox_visible,+ latest_inbound_message_ts,+ messages: [],+});++describe('thread-header unarchive eligibility', () => {+ it('offers GraphQL unarchive with no inbox timestamp or complete message history', () => {+ mocks.feature.mockReturnValue({ enabled: true });+ const adapter = setup(thread());+ expect(adapter.canMarkThreadNotDone()).toBe(true);+ expect(adapter.markThreadNotDone()).toBe(true);+ expect(mocks.mutate).toHaveBeenCalledWith(+ { threadId: 'thread', archive: false, linkId: 'link' },+ expect.any(Object)+ );+ });++ it('preserves the REST timestamp gate', () => {+ const missing = setup(thread());+ expect(missing.canMarkThreadNotDone()).toBe(false);+ expect(missing.markThreadNotDone()).toBe(false);+ expect(mocks.mutate).not.toHaveBeenCalled();+ const received = setup(thread(false, '2026-10-01T10:00:00Z'));+ expect(received.canMarkThreadNotDone()).toBe(true);+ });++ it.each([false, true])(+ 'rejects unloaded or already-open threads (GraphQL=%s)',+ (graphql) => {+ mocks.feature.mockReturnValue({ enabled: graphql });+ for (const value of [undefined, thread(true, '2026-10-01T10:00:00Z')]) {+ const adapter = setup(value);+ expect(adapter.canMarkThreadNotDone()).toBe(false);+ expect(adapter.markThreadNotDone()).toBe(false);+ }+ expect(mocks.mutate).not.toHaveBeenCalled();+ }+ );++ it('reacts when GraphQL is enabled after the thread snapshot loaded', () => {+ const [enabled, setEnabled] = createSignal(false);+ mocks.feature.mockImplementation(() => ({ enabled: enabled() }));+ createRoot((dispose) => {+ disposals.push(dispose);+ const adapter = createThreadCompletionAdapter(+ () => thread(),+ (link) => link ?? undefined+ );+ const canRestore = createMemo(adapter.canMarkThreadNotDone);+ expect(canRestore()).toBe(false);+ setEnabled(true);+ expect(canRestore()).toBe(true);+ });+ });++ it('routes a loaded GraphQL Soup entity through the shared unarchive action', () => {+ mocks.feature.mockReturnValue({ enabled: true });+ const entity = { type: 'email', id: 'thread', done: true } as EntityData;+ mocks.lookup.mockReturnValue({ original: entity });+ const adapter = setup(thread());+ expect(adapter.markThreadNotDone()).toBe(true);+ expect(mocks.executeNotDone).toHaveBeenCalledWith([entity]);+ expect(mocks.trackArchive).toHaveBeenCalledWith(+ 'thread',+ expect.any(Promise),+ false+ );+ expect(mocks.mutate).not.toHaveBeenCalled();+ });+});++describe('direct unarchive fallback reconciliation', () => {+ it.each([false, true])(+ 'refetches REST Soup only on the REST path (GraphQL=%s)',+ async (graphql) => {+ mocks.feature.mockReturnValue({ enabled: graphql });+ const adapter = setup(thread(false, '2026-10-01T10:00:00Z'));+ adapter.markThreadNotDone();+ await mocks.mutate.mock.calls[0][1]!.onSuccess('committed');+ if (graphql) {+ expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();+ expect(mocks.invalidateAllSoup).not.toHaveBeenCalled();+ } else {+ expect(mocks.refetchSoupEntity).toHaveBeenCalledWith(+ 'thread',+ 'emailThread'+ );+ expect(mocks.invalidateAllSoup).toHaveBeenCalledOnce();+ }+ }+ );++ it.each([false, true])(+ 'preserves transport-specific Undo/Redo side effects (GraphQL=%s)',+ (graphql) => {+ mocks.feature.mockReturnValue({ enabled: graphql });+ setup(thread(false, '2026-10-01T10:00:00Z'));+ const lifecycle = mocks.archiveOptions!.onPushed!(+ { id: 'undo', undo: vi.fn(async () => {}), dispose: vi.fn() },+ { threadId: 'thread', archive: false },+ () => 'committed'+ );+ if (!lifecycle) throw Error('Missing undo lifecycle');+ lifecycle.onUndone?.();+ lifecycle.onRedone?.();+ if (graphql) {+ expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();+ expect(mocks.invalidateAllSoup).not.toHaveBeenCalled();+ } else {+ expect(mocks.refetchSoupEntity).toHaveBeenCalledOnce();+ expect(mocks.invalidateAllSoup).toHaveBeenCalledTimes(2);+ }+ }+ );+});diff --git a/apps/web/src/features/email-thread/thread-completion-adapter.tsx b/apps/web/src/features/email-thread/thread-completion-adapter.tsxindex 795a6a80f6..5b92bc257f 100644--- a/apps/web/src/features/email-thread/thread-completion-adapter.tsx+++ b/apps/web/src/features/email-thread/thread-completion-adapter.tsx@@ -6,9 +6,11 @@ import {} from '@app/features/next-soup/actions';import { useMaybeSoup } from '@app/features/next-soup/soup-context';import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { toast } from '@core/component/Toast/Toast';+import { enableGraphqlSoup } from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { compositeEntity, setDoneOverride } from '@notifications';@@ -48,6 +50,7 @@ export function createThreadCompletionAdapter(| 'markThreadNotDone'> {const notificationSource = useGlobalNotificationSource();+ const graphqlSoup = useFeatureFlag(enableGraphqlSoup);const soup = useMaybeSoup();const splitPanel = useSplitPanel();@@ -108,7 +111,7 @@ export function createThreadCompletionAdapter(: bulkMarkNotificationsAsUndone(ids)).catch(() => setDoneOverride(ids, undefined));}- if (disposition() !== 'queued') {+ if (!graphqlSoup().enabled && disposition() !== 'queued') {if (!nowArchived) {void refetchSoupEntity(params.threadId, 'emailThread');}@@ -139,16 +142,13 @@ export function createThreadCompletionAdapter(return thread ? !thread.inbox_visible : false;};- // Doneness is derived, not stored: `inbox_visible` is recomputed from the- // thread's messages as "some message has INBOX and not SENT", and the inbox- // view additionally requires an inbound message. A thread with only sent- // messages can satisfy neither, so it is permanently done — unarchiving it- // reverts on the next recompute and meanwhile labels its sent messages- // INBOX, in Gmail too. Only offer the reversal when it can hold.+ // GraphQL validates received-message history on the server. An archived+ // received thread may have no inbox-sorting timestamp, and a paginated+ // message snapshot cannot prove it is sent-only. Keep REST's existing gate.const canMarkThreadNotDone = () => {const thread = threadSource();- if (!thread) return false;- return !thread.inbox_visible && thread.latest_inbound_message_ts != null;+ if (!thread || thread.inbox_visible) return false;+ return graphqlSoup().enabled || thread.latest_inbound_message_ts != null;};// Resolve a thread's soup representation for the mark-done / mark-not-done@@ -232,7 +232,9 @@ export function createThreadCompletionAdapter(toast.failure('Failed to mark as not done');}}- if (disposition !== 'queued') {+ // GraphQL owns its normalized write and durable revalidation;+ // keep the legacy REST Soup reconciliation on the REST path only.+ if (!graphqlSoup().enabled && disposition !== 'queued') {void refetchSoupEntity(threadId, 'emailThread');invalidateAllSoup();}diff --git a/apps/web/src/features/entity/utils/draggable.test.tsx b/apps/web/src/features/entity/utils/draggable.test.tsxindex 2600a56e5c..bec1f43c13 100644--- a/apps/web/src/features/entity/utils/draggable.test.tsx+++ b/apps/web/src/features/entity/utils/draggable.test.tsx@@ -5,6 +5,7 @@ import {useDragDropContext,} from '@thisbeyond/solid-dnd';import { type Accessor, createSignal, Show } from 'solid-js';+import { createStore } from 'solid-js/store';import { afterEach, describe, expect, it, vi } from 'vitest';import type { ChannelEntity } from '../types/entity';import { createEntityDraggable } from './draggable';@@ -21,12 +22,15 @@ const entity: ChannelEntity = {ownerId: 'owner',};-function setup(deferUntilInteraction?: Accessor<boolean>) {+function setup(+ deferUntilInteraction?: Accessor<boolean>,+ rowEntity: ChannelEntity = entity+) {let state!: NonNullable<ReturnType<typeof useDragDropContext>>[0];let removeRow!: () => void;function Row() {const draggable = createEntityDraggable({- entity,+ entity: rowEntity,splitId: 'split',deferUntilInteraction,});@@ -76,6 +80,31 @@ describe('createEntityDraggable', () => {});+ it.each([false, true])(+ 'keeps drag data current without another layout read (deferred=%s)',+ (deferred) => {+ const [row, setRow] = createStore({ ...entity });+ const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect');+ const { state, getByTestId } = setup(() => deferred, row);+ if (deferred) {+ fireEvent.mouseDown(getByTestId('child'), { button: 0 });+ fireEvent.mouseUp(document, { button: 0 });+ }+ const data = state.draggables['row-split']!.data;+ rect.mockClear();++ setRow({ name: 'Renamed channel', channelType: 'public' });+ expect(data.name).toBe('Renamed channel');+ expect(data.channelType).toBe('public');+ expect(data.dragType).toBe('entity');+ expect(data.splitId).toBe('split');+ expect(state.draggables['row-split']!.data).toBe(data);+ expect(rect).not.toHaveBeenCalled();+ // Registering the merged payload must not add DnD fields to the query store.+ expect('dragType' in row).toBe(false);+ }+ );+it('does not register or measure opted-in rows until a primary press', () => {const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect');const { state, getByTestId } = setup(() => true);diff --git a/apps/web/src/features/entity/utils/draggable.ts b/apps/web/src/features/entity/utils/draggable.tsindex a817b86dc7..64b266ceb8 100644--- a/apps/web/src/features/entity/utils/draggable.ts+++ b/apps/web/src/features/entity/utils/draggable.ts@@ -6,6 +6,7 @@ import {createEffect,createUniqueId,getOwner,+ mergeProps,onCleanup,untrack,} from 'solid-js';@@ -22,12 +23,14 @@ export function createEntityDraggable(options: {const draggableId = `${options.entity.id}-${options.splitId ?? createUniqueId()}`;const create = () => {- const dragData: EntityDragData = {- dragType: 'entity',+ // Rows now survive entity updates. Keep the payload reactive without+ // re-registering the draggable (which measures layout). Project the fields+ // rather than forwarding the source store's internal symbols into DnD's store.+ const dragData: EntityDragData = mergeProps(() => ({ ...options.entity }), {+ dragType: 'entity' as const,splitId: options.splitId,- ...options.entity,operation: () => (isAltKey() ? 'copy' : 'move'),- };+ });return createDraggable(draggableId, dragData);};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 ee57d619bb..56206c68f0 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@@ -347,6 +347,66 @@ describe('makeMarkDoneAction', () => {dispose();});+ it('applies Undo before its server reply and settles only afterwards', async () => {+ const { dispose } = createAction();+ const variables = {+ emailIds: ['current'],+ exactNotificationIds: { current: ['exact-id'] },+ reminderIds: [],+ };+ const context = {+ applyUndone: vi.fn(),+ reapply: vi.fn(),+ settle: vi.fn(),+ releaseGraphql: vi.fn(),+ };+ const options = mocks.undoableOptionsFactory() as {+ undoFn: (input: typeof variables, ctx: typeof context) => Promise<void>;+ };+ let finish!: () => void;+ mocks.executeMarkEntitiesUndone.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ })+ );+ const undo = options.undoFn(variables, context);+ expect(context.applyUndone).toHaveBeenCalledOnce();+ expect(context.settle).not.toHaveBeenCalled();+ finish();+ await undo;+ expect(context.settle).toHaveBeenCalledWith(['exact-id']);+ dispose();+ });++ it('does not pin guessed GraphQL state after a partially failed reversal', async () => {+ const { dispose } = createAction();+ const variables = {+ emailIds: ['current'],+ exactNotificationIds: { current: ['exact-id'] },+ reminderIds: [],+ };+ const context = {+ applyUndone: vi.fn(),+ reapply: vi.fn(),+ settle: vi.fn(),+ releaseGraphql: vi.fn(),+ };+ const options = mocks.undoableOptionsFactory() as {+ undoFn: (input: typeof variables, ctx: typeof context) => Promise<void>;+ };+ mocks.executeMarkEntitiesUndone.mockRejectedValueOnce(+ new Error('partial failure')+ );+ await expect(options.undoFn(variables, context)).rejects.toThrow(+ 'partial failure'+ );+ expect(context.reapply).toHaveBeenCalledOnce();+ expect(context.releaseGraphql).toHaveBeenCalledOnce();+ expect(context.settle).not.toHaveBeenCalled();+ dispose();+ });+it('retains authoritative entity results for exact undo and ID-scoped redo', async () => {mocks.graphqlSoupEnabled.mockReturnValue(true);mocks.resolveMarkEntitiesDoneVariables.mockReturnValue({diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-done-action.tsindex 021bd369f2..697662c908 100644--- a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.ts@@ -73,6 +73,7 @@ type MarkDoneVariables = {emailIds: string[];/** Locally known IDs used only for the immediate optimistic cache patch. */optimisticNotificationIds: string[];+ scopeChannelThreads: boolean;/** Exact IDs used by undo/redo; entity mutation results are appended here. */exactNotificationIds: { current: string[] };/** Entity-wide targets used only by the initial committed mark-done. */@@ -129,6 +130,7 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {emailIds: variables.emailIds,notificationIds: variables.optimisticNotificationIds,reminderIds: variables.reminderIds,+ scopeChannelThreads: variables.scopeChannelThreads,}),mutationFn: async (variables) => {const authoritativeNotificationIds = await executeMarkEntitiesDone({@@ -144,6 +146,9 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {]),];},+ onSuccess: (_data, variables, context) => {+ context?.settle(variables.exactNotificationIds.current);+ },onError: (_err, _variables, context) => {context?.rollback();toast.failure('Failed to mark as done');@@ -156,8 +161,10 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {notificationIds: variables.exactNotificationIds.current,reminderIds: variables.reminderIds,});+ context?.settle(variables.exactNotificationIds.current);} catch (err) {context?.reapply();+ context?.releaseGraphql();throw err;}},@@ -169,8 +176,10 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {notificationIds: variables.exactNotificationIds.current,reminderIds: variables.reminderIds,});+ context?.settle(variables.exactNotificationIds.current);} catch (err) {context?.applyUndone();+ context?.releaseGraphql();throw err;}},@@ -302,6 +311,7 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {entities: targets,emailIds: resolved.emailIds,optimisticNotificationIds: resolved.notificationIds,+ scopeChannelThreads: scopeChannelNotifications,exactNotificationIds: { current: exactNotificationIds },notificationEntities,reminderIds: resolved.reminderIds,diff --git a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.tsindex cd8eeb581b..bf8d2c9b1d 100644--- a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts@@ -1,47 +1,63 @@+import type { executeMarkEntitiesUndone } from '@app/features/next-soup/utils';import type { EntityData } from '@entity';import type { NotificationSource } from '@notifications';+import type { EmailArchiveDisposition } from '@queries/email/integration';import { beforeEach, describe, expect, it, vi } from 'vitest';+type UndoneArgs = Parameters<typeof executeMarkEntitiesUndone>[0];const mocks = vi.hoisted(() => ({+ graphql: true,threadCanBeMarkedNotDone: vi.fn(async (_id: string) => true),- executeMarkEntitiesUndone: vi.fn(- async (): Promise<'committed' | 'queued'> => 'committed'+ executeMarkEntitiesUndone:+ vi.fn<(args: UndoneArgs) => Promise<EmailArchiveDisposition>>(),+ outcomes: new Map<string, EmailArchiveDisposition | Error>(),+ writeGate: undefined as Promise<void> | undefined,+ notificationFailure: undefined as Error | undefined,+ applyOptimistic: vi.fn(+ (_args: {+ emailIds: string[];+ notificationIds: string[];+ reminderIds?: string[];+ }) => ({+ rollback: vi.fn(),+ settle: vi.fn(),+ })+ ),+ fetchDoneNotificationIds: vi.fn(async (ids: string[]) =>+ ids.map((id) => `server-${id}`)),invalidateAllSoup: vi.fn(),refetchSoupEntity: vi.fn(async () => {}),resolveMarkEntitiesDoneVariables: vi.fn(({ entities }: { entities: EntityData[] }) => ({emailIds: entities.map((e) => e.id),- notificationIds: [],+ notificationIds: entities.map((e) => `local-${e.id}`),})),alert: vi.fn(),+ failure: vi.fn(),success: vi.fn(),}));+vi.mock('@core/constant/featureFlags', () => ({+ enableGraphqlSoup: { key: 'enable-graphql-soup' },+ isFeatureEnabled: () => mocks.graphql,+}));vi.mock('@core/component/Toast/Toast', () => ({- toast: {- alert: mocks.alert,- failure: vi.fn(),- success: mocks.success,- },+ toast: { alert: mocks.alert, failure: mocks.failure, success: mocks.success },}));-vi.mock('@queries/email/thread', () => ({threadCanBeMarkedNotDone: mocks.threadCanBeMarkedNotDone,}));-vi.mock('@queries/notification/user-notifications', () => ({- fetchDoneNotificationIdsByEventItemIds: vi.fn(async () => []),+ fetchDoneNotificationIdsByEventItemIds: mocks.fetchDoneNotificationIds,}));-vi.mock('@queries/soup/cache', () => ({invalidateAllSoup: mocks.invalidateAllSoup,refetchSoupEntity: mocks.refetchSoupEntity,}));-vi.mock('@app/features/next-soup/utils', () => ({- applyEntitiesNotDoneOptimistic: vi.fn(() => ({ rollback: vi.fn() })),+ applyEntitiesNotDoneOptimistic: mocks.applyOptimistic,executeMarkEntitiesUndone: mocks.executeMarkEntitiesUndone,resolveMarkEntitiesDoneVariables: mocks.resolveMarkEntitiesDoneVariables,}));@@ -50,35 +66,76 @@ import { makeMarkNotDoneAction } from './make-mark-not-done-action';const doneEmail = (id: string) =>({ type: 'email', id, done: true }) as EntityData;--function createAction() {- return makeMarkNotDoneAction({+const createAction = () =>+ makeMarkNotDoneAction({notificationSource: () => ({}) as NotificationSource,});+function optimisticFor(id: string) {+ const index = mocks.applyOptimistic.mock.calls.findIndex(([args]) =>+ args.emailIds.includes(id)+ );+ return mocks.applyOptimistic.mock.results[index].value;}describe('makeMarkNotDoneAction', () => {beforeEach(() => {vi.clearAllMocks();+ mocks.graphql = true;+ mocks.outcomes.clear();+ mocks.writeGate = undefined;+ mocks.notificationFailure = undefined;mocks.threadCanBeMarkedNotDone.mockImplementation(async () => true);+ mocks.fetchDoneNotificationIds.mockImplementation(async (ids) =>+ ids.map((id) => `server-${id}`)+ );+ mocks.refetchSoupEntity.mockReset().mockResolvedValue(undefined);+ mocks.executeMarkEntitiesUndone.mockImplementation(async (args) => {+ if (args.emailIds.length === 0) {+ if (mocks.notificationFailure) throw mocks.notificationFailure;+ return 'committed';+ }+ await mocks.writeGate;+ let failure: Error | undefined;+ let disposition: EmailArchiveDisposition = 'committed';+ for (const id of args.emailIds) {+ const outcome = mocks.outcomes.get(id) ?? 'committed';+ if (outcome instanceof Error) {+ failure ??= outcome;+ args.onEmailSettled?.(id, { status: 'rejected', reason: outcome });+ } else {+ args.onEmailSettled?.(id, { status: 'fulfilled', value: outcome });+ if (outcome === 'queued') disposition = outcome;+ }+ }+ if (failure) throw failure;+ if (args.notificationIds.length > 0 && mocks.notificationFailure)+ throw mocks.notificationFailure;+ return disposition;+ });});- it('unarchives a thread that has an inbound message', async () => {- await createAction().execute([doneEmail('inbound')]);-- expect(mocks.executeMarkEntitiesUndone).toHaveBeenCalledWith(- expect.objectContaining({ emailIds: ['inbound'] })+ it('unarchives a thread and restores only its notifications', async () => {+ await expect(createAction().execute([doneEmail('inbound')])).resolves.toBe(+ 'committed');+ expect(mocks.executeMarkEntitiesUndone).toHaveBeenNthCalledWith(1, {+ emailIds: ['inbound'],+ notificationIds: [],+ onEmailSettled: expect.any(Function),+ });+ expect(mocks.executeMarkEntitiesUndone).toHaveBeenNthCalledWith(2, {+ emailIds: [],+ notificationIds: ['local-inbound', 'server-inbound'],+ });+ expect(optimisticFor('inbound').settle).toHaveBeenCalledOnce();+ expect(optimisticFor('inbound').rollback).not.toHaveBeenCalled();expect(mocks.alert).not.toHaveBeenCalled();- expect(mocks.invalidateAllSoup).toHaveBeenCalledOnce();- expect(mocks.refetchSoupEntity).toHaveBeenCalledWith(- 'inbound',- 'emailThread'- );+ expect(mocks.invalidateAllSoup).not.toHaveBeenCalled();+ expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();});it('does not refetch REST caches after a queued unarchive', async () => {- mocks.executeMarkEntitiesUndone.mockResolvedValueOnce('queued');+ mocks.outcomes.set('inbound', 'queued');await expect(createAction().execute([doneEmail('inbound')])).resolves.toBe('queued');@@ -86,38 +143,215 @@ describe('makeMarkNotDoneAction', () => {expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();});- // A send-only thread is permanently done: unarchiving reverts on the next- // server-side recompute and meanwhile labels its sent messages INBOX.- it('skips a thread with no inbound message and explains why', async () => {- mocks.threadCanBeMarkedNotDone.mockImplementation(async () => false);-+ it('still skips threads rejected by the legacy eligibility preflight', async () => {+ mocks.graphql = false;+ mocks.threadCanBeMarkedNotDone.mockResolvedValue(false);await createAction().execute([doneEmail('sent-only')]);-expect(mocks.executeMarkEntitiesUndone).not.toHaveBeenCalled();expect(mocks.alert).toHaveBeenCalledOnce();});- it('unarchives only the eligible threads in a mixed selection', async () => {+ it('unarchives only eligible threads in a legacy mixed selection', async () => {+ mocks.graphql = false;mocks.threadCanBeMarkedNotDone.mockImplementation(- async (id: string) => id === 'inbound'+ async (id) => id === 'inbound');-await createAction().execute([doneEmail('inbound'),doneEmail('sent-only'),]);-- expect(mocks.executeMarkEntitiesUndone).toHaveBeenCalledWith(+ expect(mocks.executeMarkEntitiesUndone).toHaveBeenNthCalledWith(+ 1,expect.objectContaining({ emailIds: ['inbound'] }));expect(mocks.alert).not.toHaveBeenCalled();});+ it.each(['committed', 'queued'] as const)(+ 'preserves a %s unarchive when a sent-only sibling is rejected by GraphQL',+ async (disposition) => {+ mocks.outcomes.set('inbound', disposition);+ mocks.outcomes.set(+ 'sent-only',+ new Error('thread has no received messages')+ );+ await expect(+ createAction().execute([doneEmail('inbound'), doneEmail('sent-only')])+ ).resolves.toBe(disposition);+ expect(optimisticFor('inbound').settle).toHaveBeenCalledOnce();+ expect(optimisticFor('inbound').rollback).not.toHaveBeenCalled();+ expect(optimisticFor('sent-only').rollback).toHaveBeenCalledOnce();+ expect(optimisticFor('sent-only').settle).not.toHaveBeenCalled();+ expect(mocks.fetchDoneNotificationIds).toHaveBeenCalledWith(['inbound']);+ expect(mocks.executeMarkEntitiesUndone).toHaveBeenLastCalledWith({+ emailIds: [],+ notificationIds: ['local-inbound', 'server-inbound'],+ });+ expect(mocks.alert).toHaveBeenCalledWith(+ 'Marked 1 of 2 items as not done. 1 could not be restored.',+ expect.objectContaining({ hideOnMobile: false })+ );+ expect(mocks.failure).not.toHaveBeenCalled();+ expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();+ expect(mocks.invalidateAllSoup).not.toHaveBeenCalled();+ }+ );++ it('skips shared-list refresh for mixed committed, queued and rejected writes', async () => {+ mocks.outcomes.set('queued', 'queued');+ mocks.outcomes.set('rejected', new Error('cannot unarchive'));+ await expect(+ createAction().execute(['committed', 'queued', 'rejected'].map(doneEmail))+ ).resolves.toBe('queued');+ expect(mocks.fetchDoneNotificationIds).toHaveBeenCalledWith([+ 'committed',+ 'queued',+ ]);+ expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();+ expect(mocks.invalidateAllSoup).not.toHaveBeenCalled();+ expect(optimisticFor('committed').rollback).not.toHaveBeenCalled();+ expect(optimisticFor('queued').rollback).not.toHaveBeenCalled();+ });++ it.each(['lookup', 'write'] as const)(+ 'does not roll back accepted emails when notification %s fails',+ async (phase) => {+ if (phase === 'lookup')+ mocks.fetchDoneNotificationIds.mockRejectedValueOnce(+ new Error('lookup failed')+ );+ else mocks.notificationFailure = new Error('notification write failed');+ await expect(+ createAction().execute([doneEmail('inbound')])+ ).resolves.toBe('committed');+ expect(optimisticFor('inbound').rollback).not.toHaveBeenCalled();+ expect(mocks.alert).toHaveBeenCalledWith(+ 'Marked as not done. Some notifications could not be restored.',+ expect.any(Object)+ );+ const notifications = mocks.applyOptimistic.mock.results.at(-1)!.value;+ expect(notifications.rollback).toHaveBeenCalledOnce();+ expect(notifications.settle).not.toHaveBeenCalled();+ }+ );++ it('keeps queued emails accepted when notification restoration is offline', async () => {+ mocks.outcomes.set('inbound', 'queued');+ mocks.fetchDoneNotificationIds.mockRejectedValueOnce(new Error('offline'));+ await expect(createAction().execute([doneEmail('inbound')])).resolves.toBe(+ 'queued'+ );+ expect(optimisticFor('inbound').rollback).not.toHaveBeenCalled();+ expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();+ expect(mocks.invalidateAllSoup).not.toHaveBeenCalled();+ });++ it('does not start a replica-backed REST refresh after GraphQL commits', async () => {+ mocks.refetchSoupEntity.mockRejectedValueOnce(new Error('must not fetch'));+ await expect(createAction().execute([doneEmail('inbound')])).resolves.toBe(+ 'committed'+ );+ expect(optimisticFor('inbound').rollback).not.toHaveBeenCalled();+ expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();+ expect(mocks.invalidateAllSoup).not.toHaveBeenCalled();+ expect(mocks.alert).not.toHaveBeenCalled();+ });++ it('still rejects a completely failed selection for single-thread cache wrappers', async () => {+ const error = new Error('cannot unarchive');+ mocks.outcomes.set('sent-only', error);+ await expect(createAction().execute([doneEmail('sent-only')])).rejects.toBe(+ error+ );+ expect(optimisticFor('sent-only').rollback).toHaveBeenCalledOnce();+ expect(mocks.fetchDoneNotificationIds).not.toHaveBeenCalled();+ expect(mocks.failure).toHaveBeenCalledWith('Failed to mark as not done');+ expect(mocks.success).not.toHaveBeenCalled();+ });++ it('rolls back every field patch if the batch fails before any write result', async () => {+ mocks.executeMarkEntitiesUndone.mockRejectedValueOnce(+ new Error('cancel failed')+ );+ await expect(+ createAction().execute([doneEmail('a'), doneEmail('b')])+ ).rejects.toThrow('cancel failed');+ expect(optimisticFor('a').rollback).toHaveBeenCalledOnce();+ expect(optimisticFor('b').rollback).toHaveBeenCalledOnce();+ });++ it('patches all rows before waiting for the server and deduplicates repeated entities', async () => {+ const gate = Promise.withResolvers<void>();+ mocks.writeGate = gate.promise;+ const action = createAction().execute([+ doneEmail('a'),+ doneEmail('a'),+ doneEmail('b'),+ ]);+ await vi.waitFor(() =>+ expect(mocks.executeMarkEntitiesUndone).toHaveBeenCalledOnce()+ );+ expect(+ mocks.applyOptimistic.mock.calls.map(([args]) => args.emailIds)+ ).toEqual([['a'], ['b']]);+ expect(mocks.fetchDoneNotificationIds).not.toHaveBeenCalled();+ gate.resolve();+ await action;+ });++ it('preserves REST notification lookup, single batch and post-success refetch', async () => {+ mocks.graphql = false;+ await expect(+ createAction().execute([doneEmail('a'), doneEmail('b')])+ ).resolves.toBe('committed');+ expect(mocks.applyOptimistic).toHaveBeenCalledOnce();+ expect(mocks.applyOptimistic).toHaveBeenCalledWith({+ emailIds: ['a', 'b'],+ notificationIds: ['local-a', 'local-b'],+ });+ expect(mocks.executeMarkEntitiesUndone).toHaveBeenCalledOnce();+ expect(mocks.executeMarkEntitiesUndone).toHaveBeenCalledWith({+ emailIds: ['a', 'b'],+ notificationIds: ['local-a', 'local-b', 'server-a', 'server-b'],+ });+ expect(+ mocks.fetchDoneNotificationIds.mock.invocationCallOrder[0]+ ).toBeLessThan(mocks.executeMarkEntitiesUndone.mock.invocationCallOrder[0]);+ expect(mocks.refetchSoupEntity).toHaveBeenCalledWith('a', 'emailThread');+ expect(mocks.refetchSoupEntity).toHaveBeenCalledWith('b', 'emailThread');+ expect(mocks.invalidateAllSoup).toHaveBeenCalledOnce();+ });++ it('preserves the legacy REST whole-batch rollback on a rejected sibling', async () => {+ mocks.graphql = false;+ const error = new Error('failed');+ mocks.outcomes.set('b', error);+ await expect(+ createAction().execute([doneEmail('a'), doneEmail('b')])+ ).rejects.toBe(error);+ expect(mocks.applyOptimistic).toHaveBeenCalledOnce();+ expect(+ mocks.applyOptimistic.mock.results[0].value.rollback+ ).toHaveBeenCalledOnce();+ expect(mocks.failure).toHaveBeenCalledWith('Failed to mark as not done');+ expect(mocks.refetchSoupEntity).not.toHaveBeenCalled();+ });++ it('preserves legacy REST rollback when its post-write refetch fails', async () => {+ mocks.graphql = false;+ mocks.refetchSoupEntity.mockRejectedValueOnce(new Error('refresh failed'));+ await expect(createAction().execute([doneEmail('a')])).rejects.toThrow(+ 'refresh failed'+ );+ expect(+ mocks.applyOptimistic.mock.results[0].value.rollback+ ).toHaveBeenCalledOnce();+ });+it('does not resolve threads when nothing is done', async () => {await createAction().execute([{ type: 'email', id: 'not-done', done: false } as EntityData,]);-expect(mocks.threadCanBeMarkedNotDone).not.toHaveBeenCalled();expect(mocks.executeMarkEntitiesUndone).not.toHaveBeenCalled();});diff --git a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.tsindex 127e1802a4..f3a247f780 100644--- a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts@@ -4,8 +4,13 @@ import {resolveMarkEntitiesDoneVariables,} from '@app/features/next-soup/utils';import { toast } from '@core/component/Toast/Toast';+import {+ enableGraphqlSoup,+ isFeatureEnabled,+} from '@core/constant/featureFlags';import type { EntityData } from '@entity';import type { NotificationSource } from '@notifications';+import type { EmailArchiveDisposition } from '@queries/email/integration';import { threadCanBeMarkedNotDone } from '@queries/email/thread';import { fetchDoneNotificationIdsByEventItemIds } from '@queries/notification/user-notifications';import { invalidateAllSoup, refetchSoupEntity } from '@queries/soup/cache';@@ -33,6 +38,7 @@ const uncompleteReminders = async (reminders: EntityData[]) => {notificationIds: [],reminderIds,});+ optimistic.settle();toast.success(reminderIds.length > 1? `Marked ${reminderIds.length} reminders as not done`@@ -45,13 +51,126 @@ const uncompleteReminders = async (reminders: EntityData[]) => {}};+/** Preserve the legacy REST batch, notification ordering and reconciliation. */+async function unarchiveRestTargets(+ targets: EntityData[],+ source: NotificationSource+) {+ const { emailIds, notificationIds } = resolveMarkEntitiesDoneVariables({+ entities: targets,+ notificationSource: source,+ });+ const optimistic = applyEntitiesNotDoneOptimistic({+ emailIds,+ notificationIds,+ });+ try {+ const serverNotificationIds =+ await fetchDoneNotificationIdsByEventItemIds(emailIds);+ const disposition = await executeMarkEntitiesUndone({+ emailIds,+ notificationIds: [+ ...new Set([...notificationIds, ...serverNotificationIds]),+ ],+ });+ toast.success(+ targets.length > 1+ ? `Marked ${targets.length} items as not done`+ : 'Marked as not done',+ { duration: 3_000, stack: true, hideOnMobile: true }+ );+ if (disposition !== 'queued') {+ await Promise.all(+ emailIds.map((id) => refetchSoupEntity(id, 'emailThread'))+ );+ invalidateAllSoup();+ }+ return disposition;+ } catch (err) {+ optimistic.rollback();+ toast.failure('Failed to mark as not done');+ throw err;+ }+}++/** Each GraphQL email owns its optimistic state; rejected siblings cannot undo it. */+async function unarchiveTargets(targets: EntityData[]) {+ const attempts = new Map(+ targets.map((entity) => [+ entity.id,+ {+ entity,+ optimistic: applyEntitiesNotDoneOptimistic({+ emailIds: [entity.id],+ notificationIds: [],+ }),+ },+ ])+ );+ const results = new Map<+ string,+ PromiseSettledResult<EmailArchiveDisposition>+ >();+ let error: unknown;+ try {+ await executeMarkEntitiesUndone({+ emailIds: [...attempts.keys()],+ notificationIds: [],+ onEmailSettled: (id, result) => {+ results.set(id, result);+ const optimistic = attempts.get(id)?.optimistic;+ if (result.status === 'fulfilled') optimistic?.settle();+ else optimistic?.rollback();+ },+ });+ } catch (err) {+ error = err;+ }+ const accepted: EntityData[] = [];+ let disposition: EmailArchiveDisposition = 'committed';+ for (const [id, attempt] of attempts) {+ const result = results.get(id);+ if (!result) attempt.optimistic.rollback(); // Failure before writes started.+ if (result?.status !== 'fulfilled') continue;+ accepted.push(attempt.entity);+ if (result.value === 'queued') disposition = 'queued';+ }+ return { accepted, disposition, error };+}++/** Restore notifications only after the corresponding unarchive was accepted. */+async function restoreEmailNotifications(+ entities: EntityData[],+ source: NotificationSource+) {+ const { emailIds, notificationIds } = resolveMarkEntitiesDoneVariables({+ entities,+ notificationSource: source,+ });+ const optimistic = applyEntitiesNotDoneOptimistic({+ emailIds: [],+ notificationIds,+ });+ try {+ const serverIds = await fetchDoneNotificationIdsByEventItemIds(emailIds);+ await executeMarkEntitiesUndone({+ emailIds: [],+ notificationIds: [...new Set([...notificationIds, ...serverIds])],+ });+ optimistic.settle();+ return true;+ } catch {+ // Notification lookup/write failure cannot reverse an accepted archive write.+ optimistic.rollback();+ return false;+ }+}+/*** Reverses a mark-done: unarchives email threads and restores their- * notifications, and un-completes reminders. Other entity types' done state- * lives on their notifications, and their rows never render as done in the- * mark-done-capable views. Threads whose done state can't be reversed (no- * inbound message) are dropped at execute time; see- * `threadCanBeMarkedNotDone`.+ * notifications, and un-completes reminders. GraphQL validates unarchive+ * eligibility on the server. Each thread settles independently, including+ * queued writes; only a completely failed email selection rejects the action.*/export const makeMarkNotDoneAction = (options: MakeMarkNotDoneOptions) => {// Always reversible — unlike a done thread there is no "permanently done" case.@@ -66,14 +185,23 @@ export const makeMarkNotDoneAction = (options: MakeMarkNotDoneOptions) => {const reminders = entities.filter(isCompletedReminder);if (reminders.length > 0) await uncompleteReminders(reminders);- const candidates = entities.filter(+ const graphql = isFeatureEnabled(enableGraphqlSoup);+ const doneEmails = entities.filter((e) => e.type === 'email' && e.done === true);+ // GraphQL owns per-thread transactions: snapshot identities before awaiting+ // and deduplicate group occurrences. Keep REST's existing input flow intact.+ const candidates = graphql+ ? [+ ...new Map(+ doneEmails.map((entity) => [entity.id, { ...entity }] as const)+ ).values(),+ ]+ : doneEmails;if (candidates.length === 0) return;- // `done` alone doesn't mean the state is reversible — a thread with only- // sent messages is permanently done. Soup rows can't tell, so resolve it- // from the thread itself (cached when the thread is open).+ // REST may rule out sent-only threads up front. GraphQL leaves eligibility+ // to the server; the per-thread transactions below isolate those rejections.const eligibility = await Promise.all(candidates.map((entity) => threadCanBeMarkedNotDone(entity.id)));@@ -89,55 +217,38 @@ export const makeMarkNotDoneAction = (options: MakeMarkNotDoneOptions) => {return;}- const { emailIds, notificationIds } = resolveMarkEntitiesDoneVariables({- entities: targets,- notificationSource: options.notificationSource(),- });-- const optimistic = applyEntitiesNotDoneOptimistic({- emailIds,- notificationIds,- });-- try {- // The live notification stream only carries not-done notifications, so- // a done thread's ids may have aged out of the local cache — resolve- // them from the server and merge before restoring.- const serverNotificationIds =- await fetchDoneNotificationIdsByEventItemIds(emailIds);- const disposition = await executeMarkEntitiesUndone({- emailIds,- notificationIds: [- ...new Set([...notificationIds, ...serverNotificationIds]),- ],- });- // Match the mark-done action's success feedback (and the direct- // unarchive fallback's toast in EmailContext).- toast.success(- targets.length > 1- ? `Marked ${targets.length} items as not done`- : 'Marked as not done',- { duration: 3_000, stack: true, hideOnMobile: true }- );- // Restore the rows deterministically: refetch each thread's soup item- // and upsert it into the caches (flat, grouped parents, and expanded- // group queries), then refetch the lists so done-filtered views- // reconcile membership and ordering.- if (disposition !== 'queued') {- await Promise.all(- emailIds.map((id) => refetchSoupEntity(id, 'emailThread'))- );- invalidateAllSoup();- }- return disposition;- } catch (err) {- optimistic.rollback();+ const source = options.notificationSource();+ if (!graphql) return unarchiveRestTargets(targets, source);+ const { accepted, disposition, error } = await unarchiveTargets(targets);+ if (accepted.length === 0) {toast.failure('Failed to mark as not done');- // Rethrow (matching makeMarkDoneAction's mutateAsync) so wrappers like- // trackExternalThreadArchive can restore their own caches; UI feedback- // is already handled above.- throw err;+ // Single-thread wrappers still need rejection to restore their own cache.+ throw error ?? new Error('Failed to mark as not done');}++ const warnings: string[] = [];+ const failedCount = targets.length - accepted.length;+ if (failedCount > 0) warnings.push(`${failedCount} could not be restored.`);+ if (!(await restoreEmailNotifications(accepted, source))) {+ warnings.push('Some notifications could not be restored.');+ }+ // The GraphQL mutation/queue owns revalidation. A follow-up REST Soup read+ // can return replica-stale archive state after accepted rows have settled,+ // including when a sibling failed. Do not feed it over those accepted rows.+ const message =+ failedCount > 0+ ? `Marked ${accepted.length} of ${targets.length} items as not done`+ : accepted.length > 1+ ? `Marked ${accepted.length} items as not done`+ : 'Marked as not done';+ const feedback = { duration: 3_000, stack: true, hideOnMobile: true };+ if (warnings.length > 0)+ toast.alert(`${message}. ${warnings.join(' ')}`, {+ ...feedback,+ hideOnMobile: false,+ });+ else toast.success(message, feedback);+ return disposition;};/** Signature parity with makeMarkDoneAction's executeWithSoup — nodiff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.tsindex 2915d0ed0e..7c87b26c3c 100644--- a/apps/web/src/features/next-soup/utils.test.ts+++ b/apps/web/src/features/next-soup/utils.test.ts@@ -45,7 +45,11 @@ const operationMocks = vi.hoisted(() => {},});return {+ graphql: false,archive: vi.fn(async (): Promise<'committed' | 'queued'> => 'committed'),+ doneOverride: vi.fn((_ids: readonly string[], _done: boolean | undefined) =>+ Object.assign(vi.fn(), { release: vi.fn() })+ ),bulkMarkNotificationsAsDone: vi.fn(async () => {}),bulkMarkNotificationsAsUndone: vi.fn(async () => {}),cancelQueries: vi.fn(async () => {}),@@ -78,6 +82,10 @@ vi.mock('@service-connection/websocket', () => ({createConnectionBlockWebsocketEffect: vi.fn(),createConnectionWebsocketEffect: vi.fn(),}));+vi.mock('@notifications', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@notifications')>()),+ setDoneOverride: operationMocks.doneOverride,+}));vi.mock('@queries/email/integration', async (importOriginal) => ({...(await importOriginal<typeof import('@queries/email/integration')>()),archiveEmailThread: operationMocks.archive,@@ -90,6 +98,7 @@ vi.mock('@queries/client', () => ({queryClient: {cancelQueries: operationMocks.cancelQueries,invalidateQueries: operationMocks.invalidateQueries,+ getQueriesData: vi.fn(() => []),},}));vi.mock('@queries/notification/entity-mutations', () => ({@@ -116,7 +125,7 @@ vi.mock('@queries/soup/cache', () => ({})),}));const hideGraphqlSoupEntitiesAsDone = vi.hoisted(() =>- vi.fn(() => ({ release: vi.fn() }))+ vi.fn(() => ({ release: vi.fn(), setDone: vi.fn(), settle: vi.fn() })));vi.mock('@queries/soup/graphql/optimistic-done', () => ({hideGraphqlSoupEntitiesAsDone,@@ -131,11 +140,14 @@ vi.mock('@core/constant/featureFlags', async (importOriginal) => {...actual,enableCalendarUi: { key: 'enable-calendar-ui' },enableReminders: { key: 'enable-reminders' },- isFeatureEnabled: (flag: Parameters<typeof actual.isFeatureEnabled>[0]) =>- 'key' in flag &&- (flag.key === 'enable-calendar-ui' || flag.key === 'enable-reminders')+ isFeatureEnabled: (flag: Parameters<typeof actual.isFeatureEnabled>[0]) => {+ if ('key' in flag && flag.key === 'enable-graphql-soup')+ return operationMocks.graphql;+ return 'key' in flag &&+ (flag.key === 'enable-calendar-ui' || flag.key === 'enable-reminders')? true- : actual.isFeatureEnabled(flag),+ : actual.isFeatureEnabled(flag);+ },};});@@ -150,6 +162,7 @@ import type { NotificationSource, UnifiedNotification } from '@notifications';import { hydrateChannelNotificationSelection } from '@queries/channel/notification-selection';import {applyEntitiesDoneOptimistic,+ applyEntitiesNotDoneOptimistic,type CalendarPreviewSelection,type ChannelPreviewSelection,channelIdForPreviewNavigation,@@ -176,6 +189,7 @@ function targetSearch(}afterEach(() => {+ operationMocks.graphql = false;setGlobalSplitManager(undefined);vi.clearAllMocks();vi.mocked(isTouchDevice).mockReturnValue(false);@@ -728,6 +742,129 @@ describe('mark-done orchestration', () => {});}+ it.each([false, true])(+ 'GraphQL mixed rejection does not refetch accepted email state (per-thread=%s)',+ async (perThread) => {+ operationMocks.graphql = true;+ const failure = new Error('cannot unarchive');+ operationMocks.archive+ .mockResolvedValueOnce('committed')+ .mockRejectedValueOnce(failure);+ const onEmailSettled = perThread ? vi.fn() : undefined;+ await expect(+ executeMarkEntitiesUndone({+ emailIds: ['accepted', 'rejected'],+ notificationIds: [],+ onEmailSettled,+ })+ ).rejects.toBe(failure);+ expect(invalidatedEmailList()).toBe(false);+ expect(operationMocks.invalidateSoupEntity).not.toHaveBeenCalled();+ expect(operationMocks.cancelQueries).not.toHaveBeenCalledWith({+ queryKey: queryKeys.all.email,+ });+ if (onEmailSettled)+ expect(onEmailSettled).toHaveBeenCalledWith('accepted', {+ status: 'fulfilled',+ value: 'committed',+ });+ }+ );++ it('leaves GraphQL success reconciliation to the normalized writer', async () => {+ operationMocks.graphql = true;+ await expect(+ executeMarkEntitiesUndone({ emailIds: ['accepted'], notificationIds: [] })+ ).resolves.toBe('committed');+ expect(invalidatedEmailList()).toBe(false);+ expect(operationMocks.invalidateSoupEntity).not.toHaveBeenCalled();+ expect(operationMocks.invalidateQueries).toHaveBeenCalledTimes(1); // notifications only+ });++ it.each([false, true])(+ 'preserves REST notification-only cancellation and reconciliation (failure=%s)',+ async (failure) => {+ if (failure)+ operationMocks.bulkMarkNotificationsAsUndone.mockRejectedValueOnce(+ new Error('failed')+ );+ const write = executeMarkEntitiesUndone({+ emailIds: [],+ notificationIds: ['notification'],+ });+ if (failure) await expect(write).rejects.toThrow('failed');+ else await write;+ expect(operationMocks.cancelQueries).toHaveBeenCalledWith({+ queryKey: queryKeys.all.email,+ });+ expect(invalidatedEmailList()).toBe(true);+ }+ );++ it('reports every unarchive outcome without refreshing over a queued sibling', async () => {+ operationMocks.graphql = true;+ const failure = new Error('thread has no received messages');+ operationMocks.archive+ .mockResolvedValueOnce('committed')+ .mockRejectedValueOnce(failure)+ .mockResolvedValueOnce('queued');+ const onEmailSettled = vi.fn();+ await expect(+ executeMarkEntitiesUndone({+ emailIds: ['received', 'sent-only', 'queued'],+ notificationIds: [],+ onEmailSettled,+ })+ ).rejects.toBe(failure);+ expect(onEmailSettled.mock.calls).toEqual([+ ['received', { status: 'fulfilled', value: 'committed' }],+ ['sent-only', { status: 'rejected', reason: failure }],+ ['queued', { status: 'fulfilled', value: 'queued' }],+ ]);+ expect(invalidatedEmailList()).toBe(false);+ expect(operationMocks.invalidateSoupEntity).not.toHaveBeenCalled();+ });++ it('reports committed email writes even when notification reversal fails', async () => {+ operationMocks.bulkMarkNotificationsAsUndone.mockRejectedValueOnce(+ new Error('notification failed')+ );+ const onEmailSettled = vi.fn();+ await expect(+ executeMarkEntitiesUndone({+ emailIds: ['received'],+ notificationIds: ['notification'],+ onEmailSettled,+ })+ ).rejects.toThrow('notification failed');+ expect(onEmailSettled).toHaveBeenCalledWith('received', {+ status: 'fulfilled',+ value: 'committed',+ });+ });++ it.each([false, true])(+ 'GraphQL notification-only reversal never refreshes shared email lists (failure=%s)',+ async (failure) => {+ operationMocks.graphql = true;+ if (failure)+ operationMocks.bulkMarkNotificationsAsUndone.mockRejectedValueOnce(+ new Error('notification failed')+ );+ const write = executeMarkEntitiesUndone({+ emailIds: [],+ notificationIds: ['notification'],+ });+ if (failure) await expect(write).rejects.toThrow('notification failed');+ else await expect(write).resolves.toBe('committed');+ expect(invalidatedEmailList()).toBe(false);+ expect(operationMocks.cancelQueries).not.toHaveBeenCalledWith({+ queryKey: queryKeys.all.email,+ });+ expect(operationMocks.archive).not.toHaveBeenCalled();+ }+ );+it('executes entity notification writes directly and returns exact ids', async () => {operationMocks.updateNotificationsForEntities.mockResolvedValueOnce([{ id: 'entity-notification' },@@ -749,7 +886,42 @@ describe('mark-done orchestration', () => {});describe('mark-done optimism', () => {+ it('keeps REST Done rollback behavior without creating GraphQL display intent', () => {+ const context = applyEntitiesDoneOptimistic({+ entityIds: ['document-1'],+ emailIds: [],+ notificationIds: ['notification-1'],+ });+ const lease = operationMocks.doneOverride.mock.results[0].value;+ context.rollback();+ context.releaseGraphql();+ expect(hideGraphqlSoupEntitiesAsDone).not.toHaveBeenCalled();+ expect(operationMocks.doneOverride).toHaveBeenLastCalledWith(+ ['notification-1'],+ undefined+ );+ expect(lease).not.toHaveBeenCalled();+ expect(lease.release).not.toHaveBeenCalled();+ });++ it('keeps REST Not Done rollback behavior without creating GraphQL display intent', () => {+ const context = applyEntitiesNotDoneOptimistic({+ emailIds: ['email-1'],+ notificationIds: ['notification-1'],+ });+ const lease = operationMocks.doneOverride.mock.results[0].value;+ context.rollback();+ context.settle();+ expect(hideGraphqlSoupEntitiesAsDone).not.toHaveBeenCalled();+ expect(operationMocks.doneOverride).toHaveBeenLastCalledWith(+ ['notification-1'],+ undefined+ );+ expect(lease).not.toHaveBeenCalled();+ });+it('hides GraphQL rows until a rollback or undo releases them', () => {+ operationMocks.graphql = true;const context = applyEntitiesDoneOptimistic({entityIds: ['document-1'],emailIds: [],@@ -758,6 +930,7 @@ describe('mark-done optimism', () => {expect(hideGraphqlSoupEntitiesAsDone).toHaveBeenCalledWith({entityIds: ['document-1'],notificationIds: ['notification-1'],+ scopeChannelThreads: undefined,});const applied = hideGraphqlSoupEntitiesAsDone.mock.results[0]?.value;@@ -765,11 +938,18 @@ describe('mark-done optimism', () => {expect(applied?.release).toHaveBeenCalledOnce();context.reapply();- const reapplied = hideGraphqlSoupEntitiesAsDone.mock.results[1]?.value;- expect(reapplied).toBeDefined();+ expect(applied?.setDone).toHaveBeenLastCalledWith(true);+ expect(hideGraphqlSoupEntitiesAsDone).toHaveBeenCalledOnce();context.applyUndone();- expect(reapplied?.release).toHaveBeenCalledOnce();+ expect(applied?.setDone).toHaveBeenLastCalledWith(false);+ context.settle(['notification-1', 'authoritative-id']);+ expect(applied?.settle).toHaveBeenCalledWith([+ 'notification-1',+ 'authoritative-id',+ ]);+ context.releaseGraphql();+ expect(applied?.release).toHaveBeenCalledTimes(2);});});diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.tsindex 0910db73fa..c6c6f9282b 100644--- a/apps/web/src/features/next-soup/utils.ts+++ b/apps/web/src/features/next-soup/utils.ts@@ -1347,6 +1347,10 @@ export type MarkEntitiesDoneContext = {reapply: () => void;/** Reverts email/soup caches and forces `done=false` override. Use for undo. */applyUndone: () => void;+ /** Release GraphQL intent only after mounted cache readers acknowledge it. */+ settle: (notificationIds?: readonly string[]) => void;+ /** After a partial inverse failure, let authoritative GraphQL state reconcile. */+ releaseGraphql: () => void;};function notificationsForMarkDone(@@ -1432,8 +1436,10 @@ export function applyEntitiesDoneOptimistic(args: {emailIds: string[];notificationIds: string[];reminderIds?: string[];+ scopeChannelThreads?: boolean;}): MarkEntitiesDoneContext {const { entityIds, emailIds, notificationIds, reminderIds = [] } = args;+ const graphql = isFeatureEnabled(enableGraphqlSoup);const emailIdSet = new Set(emailIds);const entityIdSet = new Set(entityIds);@@ -1505,6 +1511,7 @@ export function applyEntitiesDoneOptimistic(args: {let soupTxn: ReturnType<typeof removeSoupEntities> | null = null;let graphqlDone: GraphqlSoupDoneOverlay | null = null;+ let rollbackNotifications: ReturnType<typeof setDoneOverride> | undefined;let emailRowTxns: { rollback: () => void }[] = [];let reminderRowTxns: { rollback: () => void }[] = [];const completedStamp = new Date().toISOString();@@ -1521,11 +1528,14 @@ export function applyEntitiesDoneOptimistic(args: {// notification mutation waits for the server, and even the optimistic// archive only drops a row after its durable enqueue and a list// re-evaluation, so hide the rows locally until the cache catches up.- graphqlDone?.release();- graphqlDone =- entityIds.length > 0- ? hideGraphqlSoupEntitiesAsDone({ entityIds, notificationIds })- : null;+ if (graphqlDone) graphqlDone.setDone(true);+ else if (graphql && entityIds.length > 0) {+ graphqlDone = hideGraphqlSoupEntitiesAsDone({+ entityIds,+ notificationIds,+ scopeChannelThreads: args.scopeChannelThreads,+ });+ }// Rows that remain visible flip to the done state.emailRowTxns = emailIds.map((id) =>optimisticUpdateSoupEntity({@@ -1545,7 +1555,7 @@ export function applyEntitiesDoneOptimistic(args: {}));filterEmailCache();- setDoneOverride(notificationIds, true);+ rollbackNotifications = setDoneOverride(notificationIds, true);};const rollbackSoup = () => {@@ -1559,28 +1569,39 @@ export function applyEntitiesDoneOptimistic(args: {emailRowTxns = [];soupTxn?.rollback();soupTxn = null;- graphqlDone?.release();- graphqlDone = null;};const rollback = () => {rollbackSoup();+ graphqlDone?.release();restoreEmailCache();- setDoneOverride(notificationIds, undefined);+ if (graphql) rollbackNotifications?.();+ else setDoneOverride(notificationIds, undefined);};const applyUndone = () => {rollbackSoup();+ graphqlDone?.setDone(false);restoreEmailCache();restoreUserNotifications(notificationSnapshots);// Force `done=false` — cache may have reconciled to `done=true` from the// server, so clearing the override would leave the UI hidden after undo.- setDoneOverride(notificationIds, false);+ rollbackNotifications = setDoneOverride(notificationIds, false);};reapply();- return { rollback, reapply, applyUndone };+ return {+ rollback,+ reapply,+ applyUndone,+ settle: (ids) => graphqlDone?.settle(ids),+ releaseGraphql: () => {+ if (!graphql) return;+ graphqlDone?.release();+ rollbackNotifications?.release();+ },+ };}/**@@ -1593,8 +1614,16 @@ export function applyEntitiesNotDoneOptimistic(args: {emailIds: string[];notificationIds: string[];reminderIds?: string[];-}): { rollback: () => void } {+}): { rollback: () => void; settle: () => void } {const { emailIds, notificationIds, reminderIds = [] } = args;+ const graphql = isFeatureEnabled(enableGraphqlSoup);+ const graphqlDone = graphql+ ? hideGraphqlSoupEntitiesAsDone({+ entityIds: [...emailIds, ...reminderIds],+ notificationIds,+ done: false,+ })+ : undefined;// Clearing `completedAt` is what returns a reminder to Active or Scheduled// (whichever its `nextRunAt` puts it in); both predicates require it unset.const reminderRowTxns = reminderIds.map((id) =>@@ -1612,17 +1641,20 @@ export function applyEntitiesNotDoneOptimistic(args: {frecency_score: getSoupEntityById(id)?.frecency_score ?? 0,}));- setDoneOverride(notificationIds, false);+ const rollbackNotifications = setDoneOverride(notificationIds, false);return {+ settle: () => graphqlDone?.settle(),rollback: () => {+ graphqlDone?.release();for (const txn of [...reminderRowTxns].reverse()) {txn.rollback();}for (const txn of [...emailRowTxns].reverse()) {txn.rollback();}- setDoneOverride(notificationIds, undefined);+ if (graphql) rollbackNotifications?.();+ else setDoneOverride(notificationIds, undefined);},};}@@ -1738,38 +1770,51 @@ export async function executeMarkEntitiesUndone(args: {emailIds: string[];notificationIds: string[];reminderIds?: string[];+ /** Report each write before reconciliation, so bulk actions can settle or+ * roll back just that thread even when a sibling write fails. */+ onEmailSettled?: (+ id: string,+ result: PromiseSettledResult<EmailArchiveDisposition>+ ) => void;}): Promise<EmailArchiveDisposition> {const { emailIds, notificationIds, reminderIds = [] } = args;+ const graphql = isFeatureEnabled(enableGraphqlSoup);await Promise.all([- queryClient.cancelQueries({ queryKey: queryKeys.all.email }),+ ...(!graphql+ ? [queryClient.cancelQueries({ queryKey: queryKeys.all.email })]+ : []),queryClient.cancelQueries({ queryKey: notificationKeys.user._def }),]);- const results = await Promise.allSettled([- ...emailIds.map((id) => archiveEmailThread({ value: false, id })),- notificationIds.length > 0- ? bulkMarkNotificationsAsUndone(notificationIds)- : Promise.resolve(),- ...setRemindersCompleted(reminderIds, false),+ const [emailResults, otherResults] = await Promise.all([+ Promise.allSettled(+ emailIds.map((id) => archiveEmailThread({ value: false, id }))+ ),+ Promise.allSettled([+ notificationIds.length > 0+ ? bulkMarkNotificationsAsUndone(notificationIds)+ : Promise.resolve(),+ ...setRemindersCompleted(reminderIds, false),+ ]),]);-- const hasQueuedEmail = results- .slice(0, emailIds.length)- .some(- (result) => result.status === 'fulfilled' && result.value === 'queued'- );+ for (const [index, result] of emailResults.entries()) {+ args.onEmailSettled?.(emailIds[index], result);+ }+ const results = [...emailResults, ...otherResults];+ const hasQueuedEmail = emailResults.some(+ (result) => result.status === 'fulfilled' && result.value === 'queued'+ );const rejected = results.find((r): r is PromiseRejectedResult => r.status === 'rejected');if (rejected) {- // `allSettled`, so some of these may have succeeded even though the caller- // rolls every optimistic transaction back. Reconcile both kinds against the- // server or their Soup rows keep the state the rollback restored — an- // unarchived thread would sit there still showing as done.+ // REST retains its legacy batch rollback/reconciliation. GraphQL owns+ // per-write rollback and revalidation: a sibling rejection must not fetch+ // replica-stale REST state over an accepted unarchive after it settles.invalidateRemindersById(reminderIds, { refetch: true });await Promise.all([- ...(!hasQueuedEmail+ ...(!graphql && !hasQueuedEmail? [queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),...emailIds.map((id) => invalidateSoupEntity(id)),@@ -1784,7 +1829,7 @@ export async function executeMarkEntitiesUndone(args: {invalidateRemindersById(reminderIds);await Promise.all([- ...(!hasQueuedEmail+ ...(!graphql && !hasQueuedEmail? [queryClient.invalidateQueries({queryKey: queryKeys.all.email,diff --git a/apps/web/src/features/notifications/notification-source.ts b/apps/web/src/features/notifications/notification-source.tsindex ab69270cf7..c3c17b5433 100644--- a/apps/web/src/features/notifications/notification-source.ts+++ b/apps/web/src/features/notifications/notification-source.ts@@ -118,7 +118,8 @@ export function setDoneOverride(ids: readonly string[],done: boolean | undefined) {- if (ids.length === 0) return () => undefined;+ if (ids.length === 0)+ return Object.assign(() => undefined, { release: () => {} });const previous = untrack(() => new Map(ids.map((id) => [id, doneOverrides().get(id)])));@@ -139,17 +140,22 @@ export function setDoneOverride(return next;});// A failed older mutation must not undo a newer local action.- return () =>+ const finish = (restorePrevious: boolean) =>setDoneOverrides((current) => {const next = new Map(current);for (const id of ids) {if (current.get(id) !== applied.get(id)) continue;- const before = previous.get(id);+ const before = restorePrevious ? previous.get(id) : undefined;if (before === undefined) next.delete(id);else next.set(id, before);}return next;});+ return Object.assign(() => finish(true), {+ // A partially committed reversal needs authoritative state, not a guessed+ // all-or-nothing rollback. Only release this operation's own contribution.+ release: () => finish(false),+ });}// Client-asserted seen state, the `doneOverrides` twin for `viewed_at`. Seendiff --git a/apps/web/src/features/notifications/tests/notification-source.test.ts b/apps/web/src/features/notifications/tests/notification-source.test.tsindex 5318762961..f4a061cc2c 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,38 @@ describe('createNotificationSource', () => {});+ it('can release a failed reversal to authoritative state without clearing newer intent', () => {+ mocks.graphqlEnabled = true;+ const row: UnifiedNotification = {+ ...notification('partial-reversal', 'document', 'task'),+ state: 'seen',+ };+ mocks.notificationsQuery = {+ data: [row],+ transport: 'graphql',+ isFetching: false,+ };+ const { source, dispose } = createRoot((dispose) => ({+ source: createNotificationSource({} as ConnectionGatewayWebsocket),+ dispose,+ }));+ try {+ setDoneOverride([row.id], true);+ const inverse = setDoneOverride([row.id], false);+ inverse.release();+ expect(source.notifications()[0].state).toBe('seen'); // not the prior done override++ const older = setDoneOverride([row.id], true);+ setDoneOverride([row.id], false);+ row.state = 'done';+ older.release();+ expect(source.notifications()[0].state).toBe('seen'); // newer local Undo still owns the id+ } finally {+ setDoneOverride([row.id], undefined);+ dispose();+ }+ });+it('undo reopens a GraphQL-attached notification whose cached server state is already done', () => {mocks.graphqlEnabled = true;mocks.graphqlCacheEnabled = true;diff --git a/apps/web/src/lib/core/auth/logout.test.ts b/apps/web/src/lib/core/auth/logout.test.tsindex 2a5dfe3b8f..ae12fd83c0 100644--- a/apps/web/src/lib/core/auth/logout.test.ts+++ b/apps/web/src/lib/core/auth/logout.test.ts@@ -1,4 +1,5 @@import { notificationKeys } from '@queries/notification/keys';+import { graphqlSoupKeys } from '@queries/soup/graphql/keys';import { isCancelledError, QueryClient } from '@tanstack/solid-query';import { describe, expect, it, vi } from 'vitest';@@ -40,6 +41,29 @@ vi.mock('./push-registration-lifecycle', () => ({import { clearLocalAuthSession } from './logout';describe('logout notification cache isolation', () => {+ it('retires pending Done buckets and rotates the display-intent session', async () => {+ const queryClient = new QueryClient();+ client.current = queryClient;+ const first = graphqlSoupKeys.pendingDone('alice', 'old-session').queryKey;+ const second = graphqlSoupKeys.pendingDone('bob', 'older-session').queryKey;+ queryClient.setQueryData(first, [{ entityId: 'shared' }]);+ queryClient.setQueryData(second, [{ entityId: 'shared' }]);+ queryClient.setQueryData(+ graphqlSoupKeys.doneSession.queryKey,+ 'old-session'+ );+ await clearLocalAuthSession();+ expect(queryClient.getQueryData(first)).toBeUndefined();+ expect(queryClient.getQueryData(second)).toBeUndefined();+ expect(+ queryClient.getQueryData(graphqlSoupKeys.doneSession.queryKey)+ ).toEqual(expect.any(String));+ expect(+ queryClient.getQueryData(graphqlSoupKeys.doneSession.queryKey)+ ).not.toBe('old-session');+ queryClient.clear();+ });+it('cancels an old in-flight snapshot even when its transport ignores abort', async () => {const queryClient = new QueryClient();client.current = queryClient;diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.tsindex 3c04f9791a..5dc38f3929 100644--- a/apps/web/src/lib/core/auth/logout.ts+++ b/apps/web/src/lib/core/auth/logout.ts@@ -10,6 +10,7 @@ import { queryClient } from '@queries/client';import { emailKeys } from '@queries/email/keys';import { notificationKeys } from '@queries/notification/keys';import { propertiesKeys } from '@queries/properties/keys';+import { resetGraphqlSoupDoneSession } from '@queries/soup/graphql/done-session';import { clearDocumentQueryCache } from '@queries/storage/document-cache';import { clearOfflineDocumentContexts } from '@queries/storage/documentLoad/offline-context-runtime';import { authServiceClient } from '@service-auth/client';@@ -44,6 +45,7 @@ export async function clearLocalAuthSession() {queryClient.setQueryData(authKeys.userInfo.queryKey, unauthenticatedUserInfo);queryClient.removeQueries({ queryKey: emailKeys.links.queryKey });queryClient.removeQueries({ queryKey: notificationKeys._def });+ resetGraphqlSoupDoneSession();queryClient.removeQueries({ queryKey: propertiesKeys._def });// The billing position (usage, credits, overage settings) belongs to the// account that fetched it; never let it render for the next sign-in.diff --git a/apps/web/src/lib/queries/auth/user-info.test.ts b/apps/web/src/lib/queries/auth/user-info.test.tsnew file mode 100644index 0000000000..2641f64dd9--- /dev/null+++ b/apps/web/src/lib/queries/auth/user-info.test.ts@@ -0,0 +1,57 @@+import { QueryClient } from '@tanstack/solid-query';+import { afterEach, describe, expect, it, vi } from 'vitest';++const client = vi.hoisted(() => ({+ current: undefined as QueryClient | undefined,+}));+vi.mock('../client', () => ({+ get queryClient() {+ return client.current;+ },+ queryPersistence: { restoreQuery: vi.fn() },+}));+vi.mock('@core/auth/push-registration-lifecycle', () => ({+ syncPushRegistrations: vi.fn(),+}));+vi.mock('@core/context/user-info-gate', () => ({+ enableUserInfoQuery: vi.fn(),+}));+vi.mock('@core/util/cookies', () => ({ hasLoginCookie: () => true }));+vi.mock('@service-auth/client', () => ({ authServiceClient: {} }));++import { graphqlSoupKeys } from '../soup/graphql/keys';+import { authKeys } from './keys';+import { invalidateAllAfterLogin } from './user-info';++afterEach(() => {+ client.current?.clear();+});++describe('login display-intent lifetime', () => {+ it('retires old intent even when native login keeps the same viewer and mounted app', async () => {+ const queryClient = new QueryClient();+ client.current = queryClient;+ const identity = { userId: 'viewer', authenticated: true };+ queryClient.setQueryData(authKeys.userInfo.queryKey, identity);+ queryClient.setQueryData(+ graphqlSoupKeys.doneSession.queryKey,+ 'previous-session'+ );+ const previousKey = graphqlSoupKeys.pendingDone(+ 'viewer',+ 'previous-session'+ ).queryKey;+ queryClient.setQueryData(previousKey, [{ done: true }]);++ await invalidateAllAfterLogin();++ expect(queryClient.getQueryData(previousKey)).toBeUndefined();+ expect(queryClient.getQueryData(authKeys.userInfo.queryKey)).toBe(identity);+ expect(+ queryClient.getQueryData(graphqlSoupKeys.doneSession.queryKey)+ ).toEqual(expect.any(String));+ expect(+ queryClient.getQueryData(graphqlSoupKeys.doneSession.queryKey)+ ).not.toBe('previous-session');+ });+});diff --git a/apps/web/src/lib/queries/auth/user-info.ts b/apps/web/src/lib/queries/auth/user-info.tsindex bdd1380fda..25886d6f7b 100644--- a/apps/web/src/lib/queries/auth/user-info.ts+++ b/apps/web/src/lib/queries/auth/user-info.ts@@ -5,6 +5,7 @@ import { catchToResult, type ResultType, throwOnErr } from '@core/util/result';import { authServiceClient } from '@service-auth/client';import { useQuery } from '@tanstack/solid-query';import { queryClient, queryPersistence } from '../client';+import { resetGraphqlSoupDoneSession } from '../soup/graphql/done-session';import { authKeys } from './keys';import { hasCachedUserIdentity } from './user-info-cache';@@ -55,6 +56,9 @@ export function invalidateUserInfo() {/** Invalidate all queries after a successful login. */export function invalidateAllAfterLogin() {+ // Login may replace a session without visiting logout (including native auth).+ // Invalidate old display-intent handles before refetching the new identity.+ resetGraphqlSoupDoneSession();enableUserInfoQuery();const invalidated = queryClient.invalidateQueries();// Rebind this device's push registrations once the refetches above havediff --git a/apps/web/src/lib/queries/email/graphql/thread.test.ts b/apps/web/src/lib/queries/email/graphql/thread.test.tsindex 34150daab5..3366f5cd6c 100644--- a/apps/web/src/lib/queries/email/graphql/thread.test.ts+++ b/apps/web/src/lib/queries/email/graphql/thread.test.ts@@ -4,14 +4,24 @@ import type {} from '@service-storage/graphql/generated/graphql';import {CombinedError,+ createClient,+ type Exchange,+ fetchExchange,type GraphQLRequest,makeOperation,type OperationContext,type OperationResult,} from '@urql/core';import { createRoot, createSignal } from 'solid-js';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { makeSubject } from 'wonka';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { filter, makeSubject, pipe } from 'wonka';++vi.mock('@core/constant/featureFlags', () => ({+ enableGraphqlSoup: {},+ isFeatureEnabled: () => true,+}));+vi.mock('@service-email/client', () => ({ emailClient: {} }));+vi.mock('@service-storage/client', () => ({ storageServiceClient: {} }));const queryMock = vi.hoisted(() => vi.fn());const executeQueryMock = vi.hoisted(() => vi.fn());@@ -35,6 +45,11 @@ vi.mock('@service-storage/graphql-soup', () => {beforeEach(() => activeClientMock.mockReset());import { EmailThreadPageDocument } from '@service-storage/graphql/generated/graphql';+import {+ refreshActiveGraphqlSoupQueries,+ registerActiveGraphqlSoupQuery,+} from '../../soup/graphql/active-queries';+import { archiveEmailThread } from '../integration';import {createGraphqlEmailThreadQuery,fetchGraphqlEmailThread,@@ -89,6 +104,384 @@ const cachedPage: EmailThreadPageQuery = {},};+function threadMessages(offset: number, count: number) {+ return Array.from({ length: count }, (_, i) => ({+ __typename: 'GraphqlSoupEmailMessage' as const,+ id: `message-${offset + i}`,+ threadId: 'thread-1',+ linkId: 'link-1',+ providerId: null,+ replyingToId: null,+ subject: 'Subject',+ snippet: null,+ internalDateTs: null,+ sentAt: null,+ isRead: true,+ isStarred: false,+ isSent: false,+ isDraft: false,+ hasAttachments: false,+ scheduledSendTime: null,+ from: null,+ to: [],+ cc: [],+ bcc: [],+ labels: [],+ bodyText: null,+ bodyHtmlSanitized: null,+ bodyMacro: null,+ calendarInvitations: [],+ bodyReplyless: null,+ attachments: [],+ attachmentsDraft: [],+ attachmentsForwarded: [],+ createdAt: '2026-09-01T00:00:00Z',+ updatedAt: '2026-09-01T00:00:00Z',+ }));+}++describe('open-thread revalidation without normalized caching', () => {+ const cleanup: Array<() => void> = [];+ afterEach(() => {+ for (const dispose of cleanup.splice(0)) dispose();+ vi.restoreAllMocks();+ });++ function setup(+ options: {+ enabled?: () => boolean;+ messageCount?: number;+ cached?: boolean;+ threadId?: string;+ identity?: 'unreadable' | 'local' | 'alias';+ missingHost?: boolean;+ } = {}+ ) {+ initializeClientMock.mockReset();+ cacheEnabledMock.mockReturnValue(options.cached ?? false);+ const readIdentity = vi.fn(async () => {+ if (options.identity === 'unreadable')+ throw new Error('identity unavailable');+ const id =+ options.identity === 'alias'+ ? 'thread-1'+ : (options.threadId ?? 'thread-1');+ return {+ revision: '1',+ records: options.identity+ ? [+ {+ recordKey: `GraphqlSoupEmailThread:${id}`,+ record: {+ id,+ cacheProjection:+ options.identity === 'local' ? null : 'server-capsule',+ },+ identity: { pending: options.identity === 'local' },+ },+ ]+ : [],+ };+ });+ let notifyIdentityChange = () => {};+ hostMock.mockReturnValue(+ options.cached && !options.missingHost+ ? {+ readRecordsByKeys: readIdentity,+ onCacheChanged: (callback: () => void) => {+ notifyIdentityChange = callback;+ return () => {};+ },+ }+ : undefined+ );+ const server = { inboxVisible: false, failThreadRead: false };+ const reads: number[] = [];+ const readIds: string[] = [];+ const fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {+ const body = JSON.parse(String(init?.body)) as {+ operationName: string;+ variables: {+ threadId?: string;+ offset?: number;+ input?: { threadId: string; archived: boolean };+ };+ };+ const respond = (body: unknown) =>+ new Response(JSON.stringify(body), {+ headers: { 'Content-Type': 'application/json' },+ });+ if (body.operationName === 'SetEmailThreadArchived') {+ const { threadId, archived } = body.variables.input!;+ if (threadId === 'thread-1') server.inboxVisible = !archived;+ return respond({+ data: {+ setEmailThreadArchived: {+ __typename: 'GraphqlSoupEmailThread',+ id: threadId,+ inboxVisible: !archived,+ },+ },+ });+ }+ if (body.operationName !== 'EmailThreadPage')+ throw new Error(`Unexpected query ${body.operationName}`);+ const offset = body.variables.offset ?? 0;+ reads.push(offset);+ readIds.push(body.variables.threadId!);+ if (server.failThreadRead)+ return respond({ errors: [{ message: 'thread refresh failed' }] });+ return respond({+ data: {+ user: {+ ...cachedPage.user,+ emailThread: {+ ...cachedPage.user.emailThread!,+ id: body.variables.threadId,+ inboxVisible: server.inboxVisible,+ messages: threadMessages(+ offset,+ Math.min(20, Math.max(0, (options.messageCount ?? 0) - offset))+ ),+ },+ },+ },+ });+ });+ // Model cache-only reads while a cache is active. fetchExchange alone does+ // not enforce this policy, which is why known local drafts must be disabled+ // entirely after the session switches to the fetch-only client.+ const cacheOnlyGuard: Exchange =+ ({ forward }) =>+ (operations) =>+ forward(+ pipe(+ operations,+ filter(+ (operation) =>+ operation.kind !== 'query' ||+ operation.context.requestPolicy !== 'cache-only' ||+ !cacheEnabledMock()+ )+ )+ );+ const client = createClient({+ url: 'http://example.test/graphql',+ preferGetMethod: false,+ exchanges: [cacheOnlyGuard, fetchExchange],+ fetch,+ });+ activeClientMock.mockReturnValue(client);+ let listInboxVisible = false;+ cleanup.push(+ registerActiveGraphqlSoupQuery({+ isEnabled: () => true,+ refresh: async () => {+ listInboxVisible = server.inboxVisible;+ },+ })+ );+ const root = createRoot((dispose) => ({+ dispose,+ ...createGraphqlEmailThreadQuery(+ () => options.threadId ?? 'thread-1',+ () => ({ enabled: options.enabled?.() ?? true })+ ),+ }));+ cleanup.push(root.dispose);+ return {+ ...root,+ server,+ reads,+ readIds,+ readIdentity,+ notifyIdentityChange: () => notifyIdentityChange(),+ listInboxVisible: () => listInboxVisible,+ };+ }++ it('updates an open thread after a list unarchive without a REST-cache wrapper', async () => {+ const f = setup();+ await vi.waitFor(() =>+ expect(f.query.data?.pages[0].inbox_visible).toBe(false)+ );+ await expect(+ archiveEmailThread({ id: 'thread-1', value: false })+ ).resolves.toBe('committed');+ expect(f.listInboxVisible()).toBe(true);+ expect(f.query.data?.pages[0].inbox_visible).toBe(true);+ expect(f.reads).toEqual([0, 0]);+ await archiveEmailThread({ id: 'thread-1', value: true });+ expect(f.query.data?.pages[0].inbox_visible).toBe(false);+ });++ it('refreshes all loaded message pages without resetting pagination', async () => {+ const f = setup({ messageCount: 22 });+ await vi.waitFor(() => expect(f.query.isSuccess).toBe(true));+ await f.query.fetchNextPage();+ expect(f.query.data?.pageParams).toEqual([0, 20]);+ await archiveEmailThread({ id: 'thread-1', value: false });+ expect(f.reads).toEqual([0, 20, 0, 20]);+ expect(f.query.data?.pageParams).toEqual([0, 20]);+ expect(f.query.data?.pages.map((page) => page.inbox_visible)).toEqual([+ true,+ true,+ ]);+ });++ it('does not force network refreshes when the normalized cache owns updates', async () => {+ const f = setup({ cached: true });+ await vi.waitFor(() => expect(f.query.isSuccess).toBe(true));+ await archiveEmailThread({ id: 'thread-1', value: false });+ expect(f.reads).toEqual([0]);+ });++ it('stops refreshing when a mounted reader is disabled', async () => {+ const [enabled, setEnabled] = createSignal(true);+ const f = setup({ enabled });+ await vi.waitFor(() => expect(f.query.isSuccess).toBe(true));+ setEnabled(false);+ await archiveEmailThread({ id: 'thread-1', value: false });+ expect(f.reads).toEqual([0]);+ });++ it('does not activate a disabled GraphQL reader, including the REST facade path', async () => {+ const f = setup({ enabled: () => false });+ await archiveEmailThread({ id: 'thread-1', value: false });+ expect(f.reads).toEqual([]);+ });++ it('unregisters an open-thread reader when it unmounts', async () => {+ const f = setup();+ await vi.waitFor(() => expect(f.query.isSuccess).toBe(true));+ f.dispose();+ await archiveEmailThread({ id: 'thread-1', value: false });+ expect(f.reads).toEqual([0]);+ });++ it('starts participating if the session falls back from normalized caching', async () => {+ const f = setup({ cached: true });+ await vi.waitFor(() => expect(f.query.isSuccess).toBe(true));+ cacheEnabledMock.mockReturnValue(false);+ hostMock.mockReturnValue(undefined);+ await archiveEmailThread({ id: 'thread-1', value: false });+ expect(f.query.data?.pages[0].inbox_visible).toBe(true);+ expect(f.reads).toEqual([0, 0]);+ });++ it('does not roll back a committed archive because the thread refresh fails', async () => {+ const f = setup();+ await vi.waitFor(() => expect(f.query.isSuccess).toBe(true));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ f.server.failThreadRead = true;+ await expect(+ archiveEmailThread({ id: 'thread-1', value: false })+ ).resolves.toBe('committed');+ expect(f.server.inboxVisible).toBe(true);+ expect(f.query.error).toBeDefined();+ f.server.failThreadRead = false;+ await refreshActiveGraphqlSoupQueries({+ throwOnError: true,+ target: { kind: 'email-archive', threadId: 'thread-1' },+ });+ expect(f.query.data?.pages[0].inbox_visible).toBe(true);+ });++ it('leaves open threads alone during generic refreshes used by seen/unread and unrelated mutations', async () => {+ const f = setup();+ await vi.waitFor(() => expect(f.query.isSuccess).toBe(true));+ f.server.failThreadRead = true;+ await refreshActiveGraphqlSoupQueries({ throwOnError: true });+ expect(f.reads).toEqual([0]);+ expect(f.query.error).toBeNull();+ await archiveEmailThread({ id: 'another-thread', value: false });+ expect(f.reads).toEqual([0]);+ expect(f.query.error).toBeNull();+ });++ it('refreshes only the matching open thread for archive/unarchive', async () => {+ const f = setup();+ const other = createRoot((dispose) => ({+ dispose,+ ...createGraphqlEmailThreadQuery(+ () => 'other-thread',+ () => ({ enabled: true })+ ),+ }));+ cleanup.push(other.dispose);+ await vi.waitFor(() =>+ expect(f.query.isSuccess && other.query.isSuccess).toBe(true)+ );+ await archiveEmailThread({ id: 'thread-1', value: false });+ expect(f.query.data?.pages[0].inbox_visible).toBe(true);+ expect(f.readIds.filter((id) => id === 'thread-1')).toHaveLength(2);+ expect(f.readIds.filter((id) => id === 'other-thread')).toHaveLength(1);+ });++ it.each([false, true])(+ 'recovers uncertain server identity after cache fallback (missing host=%s)',+ async (missingHost) => {+ const [cached, setCached] = createSignal(true);+ const f = setup({ cached: true, identity: 'unreadable', missingHost });+ cacheEnabledMock.mockImplementation(cached);+ if (missingHost) await new Promise((resolve) => setTimeout(resolve, 0));+ else await vi.waitFor(() => expect(f.query.isEnabled).toBe(true));+ expect(f.reads).toEqual([]); // Unknown while cache is active: no network.+ setCached(false);+ await vi.waitFor(() => expect(f.query.isSuccess).toBe(true));+ expect(f.reads).toEqual([0]);+ await archiveEmailThread({ id: 'thread-1', value: false });+ expect(f.query.data?.pages[0].inbox_visible).toBe(true);+ expect(f.reads).toEqual([0, 0]);+ }+ );++ it('keeps a positively known local draft off the network after a later identity failure', async () => {+ const [cached, setCached] = createSignal(true);+ const f = setup({+ cached: true,+ threadId: 'local-thread',+ identity: 'local',+ });+ cacheEnabledMock.mockImplementation(cached);+ await vi.waitFor(() => expect(f.query.isEnabled).toBe(true));+ expect(f.reads).toEqual([]);+ f.readIdentity.mockImplementationOnce(async () => {+ setCached(false);+ throw new Error('cache retired during identity lookup');+ });+ f.notifyIdentityChange();+ await vi.waitFor(() => expect(f.readIdentity).toHaveBeenCalledTimes(2));+ await refreshActiveGraphqlSoupQueries({+ throwOnError: true,+ target: { kind: 'email-archive', threadId: 'local-thread' },+ });+ expect(f.reads).toEqual([]);+ });++ it('preserves a resolved server alias when the cache retires during an identity read', async () => {+ const [cached, setCached] = createSignal(true);+ const f = setup({+ cached: true,+ threadId: 'local-alias',+ identity: 'alias',+ });+ cacheEnabledMock.mockImplementation(cached);+ await vi.waitFor(() => expect(f.query.isSuccess).toBe(true));+ expect(f.resolvedThreadId()).toBe('thread-1');+ f.readIdentity.mockImplementationOnce(async () => {+ setCached(false);+ throw new Error('cache retired during identity lookup');+ });+ f.notifyIdentityChange();+ await vi.waitFor(() => expect(f.readIdentity).toHaveBeenCalledTimes(2));+ await archiveEmailThread({ id: 'thread-1', value: false });+ expect(f.resolvedThreadId()).toBe('thread-1');+ expect(f.readIds.every((id) => id === 'thread-1')).toBe(true);+ expect(f.query.data?.pages[0].inbox_visible).toBe(true);+ });+});+function failCacheInitialization(asynchronously: boolean) {const retiredClient = { query: vi.fn(), executeQuery: vi.fn() };const fallbackClient = { query: queryMock, executeQuery: executeQueryMock };@@ -124,6 +517,28 @@ describe('fetchGraphqlEmailThread', () => {cacheEnabledMock.mockReturnValue(true);});+ it('does not fetch a positively identified local draft after its cache retires', async () => {+ hostMock.mockReturnValue({+ readRecordsByKeys: vi.fn(async () => {+ cacheEnabledMock.mockReturnValue(false);+ return {+ revision: '1',+ records: [+ {+ recordKey: 'GraphqlSoupEmailThread:local-thread',+ record: { id: 'local-thread', cacheProjection: null },+ identity: { pending: true },+ },+ ],+ };+ }),+ });+ await expect(fetchGraphqlEmailThread('local-thread')).rejects.toThrow(+ 'cache is unavailable for this local draft'+ );+ expect(queryMock).not.toHaveBeenCalled();+ });+it.each([false, true])('loads through the fallback client after cache initialization fails (async=%s)',async (asynchronously) => {@@ -548,39 +963,7 @@ it('preserves loaded older pages while saving a reply to an existing server thre...cachedPage.user,emailThread: {...cachedPage.user.emailThread!,- messages: Array.from({ length: 20 }, (_, i) => ({- __typename: 'GraphqlSoupEmailMessage' as const,- id: `message-${request.variables.offset + i}`,- threadId: 'thread-1',- linkId: 'link-1',- providerId: null,- replyingToId: null,- subject: 'Subject',- snippet: null,- internalDateTs: null,- sentAt: null,- isRead: true,- isStarred: false,- isSent: false,- isDraft: false,- hasAttachments: false,- scheduledSendTime: null,- from: null,- to: [],- cc: [],- bcc: [],- labels: [],- bodyText: null,- bodyHtmlSanitized: null,- bodyMacro: null,- calendarInvitations: [],- bodyReplyless: null,- attachments: [],- attachmentsDraft: [],- attachmentsForwarded: [],- createdAt: '2026-09-01T00:00:00Z',- updatedAt: '2026-09-01T00:00:00Z',- })),+ messages: threadMessages(request.variables.offset, 20),},},},diff --git a/apps/web/src/lib/queries/email/graphql/thread.ts b/apps/web/src/lib/queries/email/graphql/thread.tsindex 9139fd54bd..3acd18b1c4 100644--- a/apps/web/src/lib/queries/email/graphql/thread.ts+++ b/apps/web/src/lib/queries/email/graphql/thread.ts@@ -28,7 +28,9 @@ import {createSignal,on,onCleanup,+ untrack,} from 'solid-js';+import { registerActiveGraphqlSoupQuery } from '../../soup/graphql/active-queries';import { mapGraphqlEmailThreadPage } from './mapper';/** REST-compatible pages exposed to the email query facade. */@@ -95,8 +97,19 @@ export function mapGraphqlThreadError(error: CombinedError): ThrownResultError {);}+type ThreadIdentity = {+ requested: string;+ canonical: string;+ /** A failed lookup is not proof of a local draft. Only `local` forbids+ * network reads after the session has abandoned its normalized cache. */+ kind: 'remote' | 'local' | 'unknown';+};+/** Resolve a durable local route before contacting the server with its ID. */-async function cachedThreadIdentity(threadId: string) {+async function cachedThreadIdentity(+ threadId: string,+ previous?: ThreadIdentity+): Promise<ThreadIdentity> {const cacheRequired = graphqlCacheEnabled();const host = cacheRequired ? getGraphqlCacheHost() : undefined;if (cacheRequired && !host) {@@ -114,6 +127,16 @@ async function cachedThreadIdentity(threadId: string) {return undefined;}): undefined;+ // Cache fallback must not discard positive knowledge of an unsynced draft+ // or an already-resolved server alias, even if the latest lookup failed.+ if (+ !result &&+ !graphqlCacheEnabled() &&+ previous?.requested === threadId &&+ previous.kind !== 'unknown'+ ) {+ return previous;+ }const selected = result?.records[0];return {requested: threadId,@@ -121,10 +144,12 @@ async function cachedThreadIdentity(threadId: string) {// Pending edits do not make an existing server identity local again.// Every authoritative Mail thread carries a projection capsule; only a// newly created optimistic thread has no server capsule yet.- localOnly:+ kind:selected?.identity?.pending === true &&selected.record.id === threadId &&- selected.record.cacheProjection === null,+ selected.record.cacheProjection === null+ ? 'local'+ : 'remote',};}@@ -144,6 +169,14 @@ export async function fetchGraphqlEmailThread(// An asynchronous cache initialization failure can replace the client while// resolving identity. Use the session's current transport after that read.const client = getGraphqlSoupClient();+ if (identity.kind === 'local' && !graphqlCacheEnabled()) {+ throw new ThrownResultError([+ {+ code: 'UNKNOWN',+ message: 'Email cache is unavailable for this local draft',+ },+ ]);+ }const variables: EmailThreadPageQueryVariables = {threadId: identity.canonical,offset,@@ -153,7 +186,10 @@ export async function fetchGraphqlEmailThread(.query<EmailThreadPageQuery, EmailThreadPageQueryVariables>(EmailThreadPageDocument,variables,- { requestPolicy: identity.localOnly ? 'cache-only' : 'cache-and-network' }+ {+ requestPolicy:+ identity.kind === 'local' ? 'cache-only' : 'cache-and-network',+ }).toPromise();@@ -199,20 +235,19 @@ export function createGraphqlEmailThreadQuery<TData = GraphqlEmailThreadPages>(// settlement cannot leave a reopened local thread stuck on cache-only.getGraphqlSoupClient();const host = getGraphqlCacheHost();- const [identity, setIdentity] =- createSignal<Awaited<ReturnType<typeof cachedThreadIdentity>>>();+ const [identity, setIdentity] = createSignal<ThreadIdentity>();let request = 0;let disposed = false;const refreshIdentity = async () => {const id = threadId();const generation = ++request;try {- const result = await cachedThreadIdentity(id);+ const result = await cachedThreadIdentity(id, untrack(identity));if (disposed || generation !== request || id !== threadId()) return;setIdentity((previous) =>previous?.requested === result.requested &&previous.canonical === result.canonical &&- previous.localOnly === result.localOnly+ previous.kind === result.kind? previous: result);@@ -220,11 +255,15 @@ export function createGraphqlEmailThreadQuery<TData = GraphqlEmailThreadPages>(// An initially unreadable identity may still be a local draft. Preserve// any known identity and policy; otherwise wait for resolution in cache.if (!disposed && generation === request && id === threadId())- setIdentity((previous) => ({- requested: id,- canonical: previous?.requested === id ? previous.canonical : id,- localOnly: previous?.requested === id ? previous.localOnly : true,- }));+ setIdentity((previous) =>+ previous?.requested === id+ ? previous+ : {+ requested: id,+ canonical: id,+ kind: 'unknown',+ }+ );}};// The memo re-reads identity only when the id value changes, not whenever@@ -266,10 +305,16 @@ export function createGraphqlEmailThreadQuery<TData = GraphqlEmailThreadPages>(},enabled:options().enabled &&- (!graphqlCacheEnabled() || !!getGraphqlCacheHost()) &&+ (graphqlCacheEnabled()+ ? !!getGraphqlCacheHost()+ : identity()?.kind !== 'local') &&threadId().length > 0 &&identity()?.requested === threadId(),- requestPolicy: identity()?.localOnly ? 'cache-only' : 'cache-and-network',+ requestPolicy:+ identity()?.kind === 'local' ||+ (identity()?.kind === 'unknown' && graphqlCacheEnabled())+ ? 'cache-only'+ : 'cache-and-network',keepPreviousData: false,select: ({ pages, pageParams }) => {const mapped = {@@ -281,5 +326,23 @@ export function createGraphqlEmailThreadQuery<TData = GraphqlEmailThreadPages>(return options().select?.(mapped) ?? (mapped as TData);},}));+ // Cached threads observe the shared email record. Fetch-only readers instead+ // opt into their own archive/unarchive completion, never generic Soup or+ // read/unread refreshes (which can disrupt a successfully opened thread).+ onCleanup(+ registerActiveGraphqlSoupQuery({+ isEnabled: () =>+ query.isEnabled &&+ !graphqlCacheEnabled() &&+ identity()?.kind !== 'local',+ target: () => ({ kind: 'email-archive', threadId: resolvedThreadId() }),+ refresh: async () => {+ await query.refetch({+ requestPolicy: 'network-only',+ throwOnError: true,+ });+ },+ })+ );return { query, resolvedThreadId };}diff --git a/apps/web/src/lib/queries/email/integration.test.ts b/apps/web/src/lib/queries/email/integration.test.tsindex 3831c49e60..bb883ddf32 100644--- a/apps/web/src/lib/queries/email/integration.test.ts+++ b/apps/web/src/lib/queries/email/integration.test.ts@@ -80,7 +80,9 @@ describe('GraphQL email archive writes', () => {expect(mocks.refresh).not.toHaveBeenCalled();finish();await expect(result).resolves.toBe('committed');- expect(mocks.refresh).toHaveBeenCalledOnce();+ expect(mocks.refresh).toHaveBeenCalledExactlyOnceWith({+ target: { kind: 'email-archive', threadId: 'thread' },+ });});diff --git a/apps/web/src/lib/queries/email/integration.ts b/apps/web/src/lib/queries/email/integration.tsindex 05fec60c0e..59dc40cc65 100644--- a/apps/web/src/lib/queries/email/integration.ts+++ b/apps/web/src/lib/queries/email/integration.ts@@ -33,7 +33,9 @@ export async function archiveEmailThread(getActiveGraphqlSoupRevalidations());if (disposition === 'committed') {- await refreshActiveGraphqlSoupQueries();+ await refreshActiveGraphqlSoupQueries({+ target: { kind: 'email-archive', threadId: id },+ });}return disposition;}diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.tsindex e52fc93e89..ed447aa3bc 100644--- a/apps/web/src/lib/queries/email/thread.ts+++ b/apps/web/src/lib/queries/email/thread.ts@@ -158,22 +158,22 @@ export async function fetchFreshEmailThread(}/**- * Whether a thread's done state can actually be reversed.+ * Legacy REST eligibility preflight. GraphQL validates received-message history+ * in the email domain instead of guessing from an inbox-sorting timestamp or a+ * partial message page. Bulk callers must settle each email independently: one+ * rejected unarchive must not roll back successful or durably queued siblings.*- * Doneness is derived, not stored: `inbox_visible` is recomputed server-side- * as "some message has INBOX and not SENT", and the inbox view additionally- * requires an inbound message. A thread with only sent messages satisfies- * neither, so it is permanently done — unarchiving it reverts on the next- * recompute and meanwhile labels its own sent messages INBOX, in Gmail too.- *- * Soup rows carry no inbound-message field, so this resolves the thread- * (served from cache when it is already loaded). A failed lookup resolves to- * `true`: the unarchive that follows would fail the same way, and blocking on- * a transient error would misreport ordinary threads as unreversible.+ * Failed legacy lookups remain permissive, so a transient read error does not+ * misreport an ordinary thread as permanently done.*/export async function threadCanBeMarkedNotDone(threadId: string): Promise<boolean> {+ // GraphQL validates received-message history in the email domain. Its inbox+ // sort timestamp can be null after archive, and a partial cached message page+ // cannot prove a thread is sent-only. Let the mutation decide and roll back+ // on rejection, without delaying the optimistic UI for another thread fetch.+ if (isFeatureEnabled(enableGraphqlSoup)) return true;const result = await fetchAndCacheThread(threadId);if (result.isErr()) return true;return result.value.thread.latest_inbound_message_ts != null;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 2453d0e94c..6ebc6416b3 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@@ -67,6 +67,54 @@ describe('active GraphQL Soup queries', () => {expect(getActiveGraphqlSoupRevalidations()).toEqual([descriptor]);});+ it('excludes targeted detail readers from generic Soup refreshes', async () => {+ const list = vi.fn(async () => {});+ const detail = vi.fn(async () => {+ throw new Error('must not refresh');+ });+ register({ isEnabled: () => true, refresh: list });+ register({+ isEnabled: () => true,+ refresh: detail,+ target: () => ({ kind: 'email-archive', threadId: 'thread-1' }),+ });+ await refreshActiveGraphqlSoupQueries({ throwOnError: true });+ expect(list).toHaveBeenCalledOnce();+ expect(detail).not.toHaveBeenCalled();+ });++ it('refreshes only a matching detail target, while preserving list refreshes', async () => {+ const list = vi.fn(async () => {});+ const first = vi.fn(async () => {});+ const second = vi.fn(async () => {});+ let firstId = 'first';+ register({ isEnabled: () => true, refresh: list });+ register({+ isEnabled: () => true,+ refresh: first,+ target: () => ({ kind: 'email-archive', threadId: firstId }),+ });+ register({+ isEnabled: () => true,+ refresh: second,+ target: () => ({ kind: 'email-archive', threadId: 'second' }),+ });+ await refreshActiveGraphqlSoupQueries({+ throwOnError: true,+ target: { kind: 'email-archive', threadId: 'first' },+ });+ expect(list).toHaveBeenCalledOnce();+ expect(first).toHaveBeenCalledOnce();+ expect(second).not.toHaveBeenCalled();+ firstId = 'moved';+ await refreshActiveGraphqlSoupQueries({+ throwOnError: true,+ target: { kind: 'email-archive', threadId: 'first' },+ });+ expect(first).toHaveBeenCalledOnce();+ expect(list).toHaveBeenCalledTimes(2);+ });+it('strict revalidation fails until every enabled reader succeeds', async () => {const consoleError = vi.spyOn(console, 'error')diff --git a/apps/web/src/lib/queries/soup/graphql/active-queries.ts b/apps/web/src/lib/queries/soup/graphql/active-queries.tsindex 6d55825d6c..0cd50548f5 100644--- a/apps/web/src/lib/queries/soup/graphql/active-queries.ts+++ b/apps/web/src/lib/queries/soup/graphql/active-queries.ts@@ -1,9 +1,17 @@import type { QueryRevalidation } from '@graphql-cache/exchange/optimistic';import { type Client, createRequest } from '@urql/core';+/** An explicit mutation target; detail readers opt out of generic list refreshes. */+export type GraphqlSoupRefreshTarget = {+ kind: 'email-archive';+ threadId: string;+};+type ActiveGraphqlSoupQuery = {isEnabled: () => boolean;refresh: () => Promise<void>;+ /** Only refresh this reader for its matching mutation, never for broad Soup work. */+ target?: () => GraphqlSoupRefreshTarget;};const activeQueries = new Set<ActiveGraphqlSoupQuery>();@@ -44,17 +52,26 @@ export function registerActiveGraphqlSoupQuery(return () => activeQueries.delete(query);}-/** Network-refreshes every mounted and enabled GraphQL Soup query.- * Strict callers may only release optimistic state after every active reader+/** Refresh enabled list readers and any explicitly targeted detail readers.+ * Strict callers may only release optimistic state after every applicable reader* succeeded. Other callers retain the existing best-effort behavior.*/export async function refreshActiveGraphqlSoupQueries(- options: { throwOnError?: boolean } = {}+ options: { throwOnError?: boolean; target?: GraphqlSoupRefreshTarget } = {}): Promise<void> {+ const applicable = (query: ActiveGraphqlSoupQuery) => {+ if (!query.isEnabled()) return false;+ if (!query.target) return true;+ const target = query.target();+ return (+ target.kind === options.target?.kind &&+ target.threadId === options.target.threadId+ );+ };const refreshed = new Set<ActiveGraphqlSoupQuery>();await Promise.all([...activeQueries].map(async (query) => {- if (!query.isEnabled()) return;+ if (!applicable(query)) return;try {await query.refresh();refreshed.add(query);@@ -68,7 +85,7 @@ export async function refreshActiveGraphqlSoupQueries(if (options.throwOnError &&[...activeQueries].some(- (query) => query.isEnabled() && !refreshed.has(query)+ (query) => applicable(query) && !refreshed.has(query))) {throw new Error(diff --git a/apps/web/src/lib/queries/soup/graphql/ast.test.ts b/apps/web/src/lib/queries/soup/graphql/ast.test.tsindex 090b084903..e462944d90 100644--- a/apps/web/src/lib/queries/soup/graphql/ast.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/ast.test.ts@@ -488,15 +488,18 @@ describe('makeGraphqlSoupInput', () => {).toThrow('Unsupported GraphQL Soup AST');});- it('rejects email views for grouped queries instead of dropping them', () => {- expect(() =>- makeGraphqlGroupedSoupInput({- params: { limit: 100, sort_method: 'updated_at' },- body: { emailView: 'inbox' } as never,- groupBy: { type: 'entity_type' },- })- ).toThrow('Unsupported GraphQL Soup AST');- });+ it.each(['inbox', 'drafts', 'sent', 'all'] as const)(+ 'rejects grouped %s mail, including the date-grouped cached-mail slice',+ (emailView) => {+ expect(() =>+ makeGraphqlGroupedSoupInput({+ params: { limit: 100, sort_method: 'updated_at' },+ body: { emailView },+ groupBy: { type: 'date' },+ })+ ).toThrow('email views are not supported by grouped GraphQL Soup yet');+ }+ );it('rejects unknown email views instead of using the GraphQL default', () => {expect(() =>diff --git a/apps/web/src/lib/queries/soup/graphql/done-projection.test.ts b/apps/web/src/lib/queries/soup/graphql/done-projection.test.tsnew file mode 100644index 0000000000..c3d7f2a192--- /dev/null+++ b/apps/web/src/lib/queries/soup/graphql/done-projection.test.ts@@ -0,0 +1,255 @@+import type { EmailEntity, EntityData } from '@entity/types/entity';+import { createRoot } from 'solid-js';+import { createStore } from 'solid-js/store';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { SoupAstItemsData } from '../items';+import { createGraphqlSoupDoneProjection } from './done-projection';+import {+ type PendingGraphqlSoupDone,+ soupDoneNotifications,+} from './optimistic-done';++// These tests exercise the display boundary, not application query setup.+vi.mock('../../client', () => ({ queryClient: {} }));+vi.mock('./active-queries', () => ({+ refreshActiveGraphqlSoupQueries: vi.fn(),+}));++const disposers: (() => void)[] = [];+afterEach(() => {+ for (const dispose of disposers.splice(0)) dispose();+});+const createProjection = () =>+ createRoot((dispose) => {+ disposers.push(dispose);+ return createGraphqlSoupDoneProjection();+ });+const email = (id: string, done = false): EmailEntity =>+ ({ id, type: 'email', name: id, done }) as EmailEntity;+const page = (entities: EntityData[]): SoupAstItemsData => ({+ entities,+ groups: undefined,+});+const intent = (done = true): PendingGraphqlSoupDone => ({+ operation: {},+ viewerId: 'viewer',+ session: 'test-session',+ entityIds: new Set(['a']),+ notificationIds: new Set(),+ done,+ startedAt: Date.now(),+ notificationStartedAt: Date.now(),+ scopeChannelThreads: false,+ observe: vi.fn(),+ unobserve: vi.fn(),+});+const deleted = new Set<string>();++it('changes All indicators immediately without changing the query store or other rows', () => {+ const project = createProjection();+ const source = page([email('a'), email('b')]);+ const done = intent();+ const result = project('all', source, [done], false, deleted)!;+ expect((result.entities[0] as EmailEntity).done).toBe(true);+ expect((source.entities[0] as EmailEntity).done).toBe(false);+ expect(result.entities[1]).toBe(source.entities[1]);+ expect(done.observe).toHaveBeenLastCalledWith(expect.any(Object), false);+});++it('acknowledges raw fields, not the optimistic fields it just projected', () => {+ const project = createProjection();+ const done = intent();+ project('all', page([email('a')]), [done], false, deleted);+ expect(done.observe).toHaveBeenLastCalledWith(expect.any(Object), false);+ project('all', page([email('a', true)]), [done], false, deleted);+ expect(done.observe).toHaveBeenLastCalledWith(expect.any(Object), true);+});++it('restores an admitted row at once on Undo after the cache removed it', () => {+ const project = createProjection();+ const before = page([email('b'), email('a'), email('c')]);+ const done = intent();+ expect(+ project('signal', before, [done], true, deleted)?.entities.map((e) => e.id)+ ).toEqual(['b', 'c']);+ const committed = page([before.entities[0], before.entities[2]]);+ project('signal', committed, [done], true, deleted);+ // Acknowledged Done can be released; the action still owns its weak snapshot.+ project('signal', committed, [], true, deleted);+ const undone = { ...done, done: false };+ const result = project('signal', committed, [undone], true, deleted)!;+ expect(result.entities.map((e) => e.id)).toEqual(['b', 'a', 'c']);+ expect((result.entities[1] as EmailEntity).done).toBe(false);+ expect(result.entities[0]).toBe(committed.entities[0]);+ expect(undone.observe).toHaveBeenLastCalledWith(expect.any(Object), false);+ // Another stale response must not remove the optimistic restoration.+ expect(+ project('signal', committed, [undone], true, deleted)?.entities+ ).toEqual(result.entities);+ expect(+ project('signal', committed, [done], true, deleted)?.entities.map(+ (e) => e.id+ )+ ).toEqual(['b', 'c']);+});++it('does not acknowledge an admitted row when its reader temporarily loses data', () => {+ const project = createProjection();+ const done = intent();+ project('signal', page([email('a')]), [done], true, deleted);+ project('signal', undefined, [done], true, deleted);+ expect(done.observe).toHaveBeenLastCalledWith(expect.any(Object), false);+ const restored = project(+ 'signal',+ page([]),+ [{ ...done, done: false }],+ true,+ deleted+ )!;+ expect(restored.entities.map((e) => e.id)).toEqual(['a']);+});++it('does not restore into another filter/sort scope or over a deletion', () => {+ const project = createProjection();+ const done = intent();+ project('signal', page([email('a')]), [done], true, deleted);+ const undone = { ...done, done: false };+ expect(+ project('signal', page([]), [undone], true, new Set(['a']))?.entities+ ).toEqual([]);+ expect(project('noise', page([]), [undone], true, deleted)?.entities).toEqual(+ []+ );+ // Returning to the old scope doesn't reuse snapshots across a query transition.+ expect(+ project('signal', page([]), [undone], true, deleted)?.entities+ ).toEqual([]);+});++it('restores grouped membership, count and raw pool without mutating server data', () => {+ const project = createProjection();+ const done = intent();+ const item = {+ tag: 'emailThread',+ data: { id: 'a', inboxVisible: true },+ frecency_score: 0,+ } as NonNullable<SoupAstItemsData['itemsById']>[string];+ const original: SoupAstItemsData = {+ entities: [email('a')],+ groups: [+ {+ key: 'group',+ label: 'Group',+ displayOrder: 0,+ itemIds: ['a'],+ totalCount: 1,+ nextCursor: null,+ },+ ],+ itemsById: { a: item },+ };+ project('grouped', original, [done], true, deleted);+ const committed: SoupAstItemsData = {+ entities: [],+ groups: [],+ itemsById: {},+ };+ const result = project(+ 'grouped',+ committed,+ [{ ...done, done: false }],+ true,+ deleted+ )!;+ expect(result.groups).toEqual(original.groups);+ expect(result.itemsById?.a).toBe(item);+ expect(committed).toEqual({ entities: [], groups: [], itemsById: {} });+});++it('applies the newest intent and preserves untouched collection identity', () => {+ const project = createProjection();+ const source = page([email('a')]);+ expect(project('signal', source, [], true, deleted)).toBe(source);+ const old = intent();+ const latest = intent(false);+ expect(project('signal', source, [old, latest], true, deleted)).toBe(source);+ expect(old.observe).not.toHaveBeenCalled();+});++describe('notification-backed rows', () => {+ const document = (state: string): EntityData =>+ ({+ id: 'a',+ type: 'document',+ name: 'Document',+ notifications: [{ id: 'n1', state, created_at: '2020-01-01T00:00:00Z' }],+ }) as unknown as EntityData;++ it('restores only a row admitted by this notification query', () => {+ const project = createProjection();+ const done = { ...intent(), notificationIds: new Set(['n1']) };+ project('home-feed', page([document('unseen')]), [done], true, deleted);+ const undone = { ...done, done: false };+ expect(+ project('home-feed', page([]), [undone], true, deleted)?.entities+ ).toHaveLength(1);+ project('home-feed', page([document('seen')]), [undone], true, deleted);+ expect(undone.observe).toHaveBeenLastCalledWith(expect.any(Object), true);+ });++ it('retains notification witnesses when a query store clears its edge in place', () => {+ const project = createProjection();+ const done = { ...intent(), notificationIds: new Set(['n1']) };+ const [query, setQuery] = createStore({+ entities: [+ {+ id: 'a',+ type: 'document',+ name: 'Document',+ notifications: [+ { id: 'n1', state: 'unseen', created_at: '2020-01-01T00:00:00Z' },+ ],+ },+ ],+ });+ const current = () => page(query.entities as unknown as EntityData[]);+ project('home-feed', current(), [done], true, deleted);+ setQuery('entities', 0, 'notifications', []);+ project('home-feed', current(), [done], true, deleted);+ expect(done.observe).toHaveBeenLastCalledWith(expect.any(Object), false);+ setQuery('entities', []);+ const restored = project(+ 'home-feed',+ current(),+ [{ ...done, done: false }],+ true,+ deleted+ )!;+ expect(+ soupDoneNotifications(restored.entities[0], false).map((n) => n.id)+ ).toEqual(['n1']);+ expect(query.entities).toEqual([]);+ });++ it('does not acknowledge missing notification evidence while the row is still present', () => {+ const project = createProjection();+ const done = { ...intent(), notificationIds: new Set(['n1']) };+ project('home-feed', page([document('unseen')]), [done], true, deleted);+ const incomplete = {+ ...document('unseen'),+ notifications: [],+ } as unknown as EntityData;+ project('home-feed', page([incomplete]), [done], true, deleted);+ expect(done.observe).toHaveBeenLastCalledWith(expect.any(Object), false);+ project('home-feed', page([]), [done], true, deleted);+ expect(done.observe).toHaveBeenLastCalledWith(expect.any(Object), true);+ });++ it('does not redefine unfiltered Home-recents membership', () => {+ const project = createProjection();+ const source = page([document('unseen')]);+ const done = intent();+ expect(project('recents', source, [done], false, deleted)).toBe(source);+ expect(done.observe).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/queries/soup/graphql/done-projection.ts b/apps/web/src/lib/queries/soup/graphql/done-projection.tsnew file mode 100644index 0000000000..f58471ea29--- /dev/null+++ b/apps/web/src/lib/queries/soup/graphql/done-projection.ts@@ -0,0 +1,269 @@+import type { EntityData } from '@entity/types/entity';+import type { Notification } from '@entity/types/notification';+import { onCleanup } from 'solid-js';+import type { SoupAstItemsData } from '../items';+import { withoutPendingGraphqlSoupDeletes } from './optimistic-deletions';+import {+ hasActivityAfterDone,+ type PendingGraphqlSoupDone,+ soupDoneNotifications,+ withPendingDoneIds,+} from './optimistic-done';++type Group = NonNullable<SoupAstItemsData['groups']>[number];+type Snapshot = {+ entity: EntityData;+ index: number;+ groups: { group: Group; index: number; itemIndex: number }[];+ item: NonNullable<SoupAstItemsData['itemsById']>[string] | undefined;+};++function reflectsIntent(+ entity: EntityData | undefined,+ snapshot: Snapshot | undefined,+ intent: PendingGraphqlSoupDone,+ excludesDone: boolean+): boolean {+ if (!entity) return intent.done && excludesDone;+ if (hasActivityAfterDone(entity, intent)) return true;+ if (entity.type === 'email') return entity.done === intent.done;+ if (entity.type === 'reminder')+ return (entity.completedAt != null) === intent.done;+ const notifications = soupDoneNotifications(+ entity,+ intent.scopeChannelThreads+ );+ const knownIds = soupDoneNotifications(+ snapshot?.entity ?? entity,+ intent.scopeChannelThreads+ )+ .filter(({ id }) => intent.notificationIds.has(id))+ .map(({ id }) => id);+ if (knownIds.length === 0) return false;+ return intent.done+ ? notifications.every(({ state }) => state === 'done') &&+ knownIds.every((id) =>+ notifications.some((n) => n.id === id && n.state === 'done')+ )+ : knownIds.every((id) =>+ notifications.some((n) => n.id === id && n.state !== 'done')+ );+}++function projectState(+ entity: EntityData,+ intent: PendingGraphqlSoupDone+): EntityData {+ if (hasActivityAfterDone(entity, intent)) return entity;+ if (entity.type === 'email' && entity.done !== intent.done) {+ return { ...entity, done: intent.done };+ }+ if (+ entity.type === 'reminder' &&+ (entity.completedAt != null) !== intent.done+ ) {+ return {+ ...entity,+ completedAt: intent.done+ ? new Date(intent.startedAt).toISOString()+ : null,+ };+ }+ return entity;+}++function captureSnapshot(+ data: SoupAstItemsData,+ entity: EntityData,+ index: number+): Snapshot {+ const copy = { ...entity };+ const attached = (entity as { notifications?: unknown }).notifications;+ if (Array.isArray(attached)) {+ // Query stores clear active edges in place when Done commits. Undo must+ // retain the original notification witnesses, not a proxy to the emptied edge.+ Object.assign(copy, {+ notifications: (attached as Notification[]).map((notification) => ({+ ...notification,+ })),+ });+ }+ return {+ entity: copy,+ index,+ groups: (data.groups ?? []).flatMap((group, groupIndex) => {+ const itemIndex = group.itemIds.indexOf(entity.id);+ return itemIndex < 0+ ? []+ : [+ {+ group: { ...group, itemIds: [...group.itemIds] },+ index: groupIndex,+ itemIndex,+ },+ ];+ }),+ item: data.itemsById?.[entity.id],+ };+}++function restoreSnapshots(+ data: SoupAstItemsData,+ restore: Snapshot[]+): SoupAstItemsData {+ if (restore.length === 0) return data;+ const entities = [...data.entities];+ const groups = data.groups ? [...data.groups] : undefined;+ const itemsById = data.itemsById ? { ...data.itemsById } : undefined;+ for (const snapshot of restore.sort((a, b) => a.index - b.index)) {+ const id = snapshot.entity.id;+ entities.splice(+ Math.min(snapshot.index, entities.length),+ 0,+ snapshot.entity+ );+ if (itemsById && snapshot.item) itemsById[id] = snapshot.item;+ if (!groups) continue;+ for (const previous of snapshot.groups) {+ let groupIndex = groups.findIndex(+ (group) => group.key === previous.group.key+ );+ if (groupIndex < 0) {+ groupIndex = Math.min(previous.index, groups.length);+ groups.splice(groupIndex, 0, {+ ...previous.group,+ itemIds: [],+ totalCount: 0,+ });+ }+ const group = groups[groupIndex];+ if (group.itemIds.includes(id)) continue;+ const itemIds = [...group.itemIds];+ itemIds.splice(Math.min(previous.itemIndex, itemIds.length), 0, id);+ groups[groupIndex] = {+ ...group,+ itemIds,+ totalCount: group.totalCount + 1,+ };+ }+ }+ return { ...data, entities, groups, itemsById };+}++/**+ * A mounted query remembers only its own admitted rows for Undo. Snapshots are+ * weakly owned by the undo operation and discarded on any filter/sort change;+ * they never insert an entity into a view where its membership was not known.+ */+export function createGraphqlSoupDoneProjection() {+ const reader = {};+ let scope: string | undefined;+ let snapshots = new WeakMap<object, Map<string, Snapshot>>();+ let observed: readonly PendingGraphqlSoupDone[] = [];+ const detach = () => {+ for (const entry of observed) entry.unobserve(reader);+ observed = [];+ };+ onCleanup(detach);++ return (+ queryScope: string,+ data: SoupAstItemsData | undefined,+ pending: readonly PendingGraphqlSoupDone[],+ excludesDone: boolean,+ deletedIds: ReadonlySet<string>+ ): SoupAstItemsData | undefined => {+ detach();+ if (scope !== queryScope) {+ scope = queryScope;+ snapshots = new WeakMap();+ }+ if (!data) {+ // A pending/error read is not an acknowledgement of a previously admitted+ // row. Keep that reader's veto until it has data or actually unmounts.+ for (const entry of pending) {+ const remembered = snapshots.get(entry.operation);+ if ([...entry.entityIds].some((id) => remembered?.has(id))) {+ entry.observe(reader, false);+ }+ }+ observed = pending;+ return undefined;+ }+ if (pending.length === 0) {+ return withoutPendingGraphqlSoupDeletes(data, deletedIds);+ }++ const latest = new Map<string, PendingGraphqlSoupDone>();+ for (const entry of pending) {+ for (const id of entry.entityIds) latest.set(id, entry);+ }+ const raw = new Map(+ data.entities.map((entity, index) => [entity.id, { entity, index }])+ );+ const restore = pending.flatMap((entry) => {+ const restoring: Snapshot[] = [];+ let remembered = snapshots.get(entry.operation);+ if (!remembered) {+ remembered = new Map();+ snapshots.set(entry.operation, remembered);+ }+ let relevant = false;+ let acknowledged = true;+ for (const id of entry.entityIds) {+ if (latest.get(id) !== entry) continue;+ const current = raw.get(id);+ // Unfiltered document/channel recents have no entity-level done field.+ // Their inclusion rules are not notification-feed membership rules.+ if (+ current &&+ !excludesDone &&+ !['email', 'reminder'].includes(current.entity.type)+ )+ continue;+ if (current && entry.done && !remembered.has(id)) {+ remembered.set(+ id,+ captureSnapshot(data, current.entity, current.index)+ );+ }+ const snapshot = remembered.get(id);+ if (!current && !snapshot) continue;+ relevant = true;+ acknowledged &&= reflectsIntent(+ current?.entity,+ snapshot,+ entry,+ excludesDone+ );+ if (+ !entry.done &&+ excludesDone &&+ !current &&+ snapshot &&+ !deletedIds.has(id)+ ) {+ restoring.push(snapshot);+ }+ }+ if (relevant) entry.observe(reader, acknowledged);+ return restoring;+ });+ observed = pending;++ let result = restoreSnapshots(data, restore);+ const entities = result.entities.map((entity) => {+ const intent = latest.get(entity.id);+ return intent ? projectState(entity, intent) : entity;+ });+ if (entities.some((entity, index) => entity !== result.entities[index])) {+ result = { ...result, entities };+ }+ return withoutPendingGraphqlSoupDeletes(+ result,+ excludesDone+ ? withPendingDoneIds(deletedIds, result.entities, pending)+ : deletedIds+ );+ };+}diff --git a/apps/web/src/lib/queries/soup/graphql/done-session.ts b/apps/web/src/lib/queries/soup/graphql/done-session.tsnew file mode 100644index 0000000000..7de569b7fc--- /dev/null+++ b/apps/web/src/lib/queries/soup/graphql/done-session.ts@@ -0,0 +1,24 @@+import { queryClient } from '../../client';+import { graphqlSoupKeys } from './keys';++/** Ephemeral session fence, not a credential or a persisted cache identity. */+export function getGraphqlSoupDoneSession(): string {+ const current = queryClient.getQueryData<string>(+ graphqlSoupKeys.doneSession.queryKey+ );+ if (current) return current;+ const session = crypto.randomUUID();+ queryClient.setQueryData(graphqlSoupKeys.doneSession.queryKey, session);+ return session;+}++/** Retire old operations before a login/logout refetch can publish new identity. */+export function resetGraphqlSoupDoneSession(): void {+ queryClient.removeQueries({ queryKey: graphqlSoupKeys.pendingDone._def });+ // Rotate after removal so mounted observers rebind to a fresh query even when+ // native authentication signs back into the same account without a reload.+ queryClient.setQueryData(+ graphqlSoupKeys.doneSession.queryKey,+ crypto.randomUUID()+ );+}diff --git a/apps/web/src/lib/queries/soup/graphql/grouped-items.test.ts b/apps/web/src/lib/queries/soup/graphql/grouped-items.test.tsindex 34ec068bf6..f5915d58e2 100644--- a/apps/web/src/lib/queries/soup/graphql/grouped-items.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/grouped-items.test.ts@@ -34,15 +34,20 @@ vi.mock('../grouped/mail-date-groups', () => ({}));vi.mock('../transform-utils', () => ({ mapSoupPageToEntityList: vi.fn() }));+import { authKeys } from '@queries/auth/keys';import { queryClient } from '@queries/client';import { createGraphqlGroupedSoupAstItemsQuery } from './grouped-items';import { hideGraphqlSoupEntitiesAsDone } from './optimistic-done';beforeEach(() => {queryClient.clear();+ queryClient.setQueryData(authKeys.userInfo.queryKey, {+ userId: 'viewer',+ authenticated: true,+ });});-function fixture(emailView: 'inbox' | 'drafts' = 'drafts') {+function fixture(emailView: 'inbox' | 'drafts' | 'all' = 'drafts') {const local = { cachedMail: true, entities: [{ id: 'offline-draft' }] };const network = { entities: [{ id: 'server-draft' }] };const [optimistic, setOptimistic] = createSignal(true);@@ -56,7 +61,7 @@ function fixture(emailView: 'inbox' | 'drafts' = 'drafts') {mocks.query.mockImplementation((options: () => { onResult: typeof onResult }) => {onResult = options().onResult;- return { data: network, error: undefined };+ return { data: { viewerId: 'viewer', data: network }, error: undefined };});const root = createRoot((dispose) => ({@@ -155,6 +160,78 @@ describe('grouped Mail pending done filtering', () => {});+ it.each(['local', 'network'] as const)(+ 'restores a removed %s inbox row immediately on Undo',+ async (source) => {+ const f = fixture('inbox');+ if (source === 'network') {+ f.setOptimistic(false);+ const persistence = Promise.resolve('1');+ f.publish(persistence);+ await persistence;+ }+ const data = f[source];+ const id = data.entities[0].id;+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: [id],+ notificationIds: [],+ });+ try {+ await vi.waitFor(() => expect(f.query.data()?.entities).toEqual([]));+ data.entities.length = 0; // The selected cache/server source has caught up with Done.+ overlay.setDone(false);+ await vi.waitFor(() =>+ expect(f.query.data()?.entities.map((e) => e.id)).toEqual([id])+ );+ expect(data.entities).toEqual([]); // Undo never writes back into the source.+ } finally {+ overlay.release();+ f.dispose();+ }+ }+ );++ it.each(['local', 'network'] as const)(+ 'updates the All done indicator in the %s projection without removing the row',+ async (source) => {+ const f = fixture('all');+ const data = f[source];+ const entity = Object.assign(data.entities[0], {+ type: 'email',+ done: false,+ });+ if (source === 'network') {+ f.setOptimistic(false);+ const persistence = Promise.resolve('1');+ f.publish(persistence);+ await persistence;+ }+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: [entity.id],+ notificationIds: [],+ });+ try {+ await vi.waitFor(() =>+ expect(f.query.data()?.entities[0]).toMatchObject({+ id: entity.id,+ done: true,+ })+ );+ expect(entity.done).toBe(false);+ overlay.setDone(false);+ await vi.waitFor(() =>+ expect(f.query.data()?.entities[0]).toMatchObject({+ id: entity.id,+ done: false,+ })+ );+ } finally {+ overlay.release();+ f.dispose();+ }+ }+ );+it('keeps cached drafts visible when the view includes done items', async () => {const f = fixture();const overlay = hideGraphqlSoupEntitiesAsDone({diff --git a/apps/web/src/lib/queries/soup/graphql/grouped-items.ts b/apps/web/src/lib/queries/soup/graphql/grouped-items.tsindex ab662a8d61..345c7a3921 100644--- a/apps/web/src/lib/queries/soup/graphql/grouped-items.ts+++ b/apps/web/src/lib/queries/soup/graphql/grouped-items.ts@@ -41,18 +41,13 @@ import type { SoupAstBody, SoupAstItemsData, SoupAstParams } from '../items';import { mapSoupPageToEntityList } from '../transform-utils';import { registerGraphqlSoupRevalidations } from './active-queries';import { makeGraphqlGroupedSoupInput } from './ast';+import { createGraphqlSoupDoneProjection } from './done-projection';import {createGraphqlSoupAstItemsQuery,type GraphqlSoupAstItemsQuery,} from './items';-import {- usePendingGraphqlSoupDeleteIds,- withoutPendingGraphqlSoupDeletes,-} from './optimistic-deletions';-import {- usePendingGraphqlSoupDone,- withPendingDoneIds,-} from './optimistic-done';+import { usePendingGraphqlSoupDeleteIds } from './optimistic-deletions';+import { usePendingGraphqlSoupDone } from './optimistic-done';export type GraphqlGroupedSoupAstItemsQueryArgs = {params: SoupAstParams;@@ -113,6 +108,7 @@ export function createGraphqlGroupedSoupAstItemsQuery(const instructionsIdQuery = useInstructionsMdIdQuery();const pendingDeleteIds = usePendingGraphqlSoupDeleteIds();const pendingDone = usePendingGraphqlSoupDone();+ const projectDone = createGraphqlSoupDoneProjection();const excludesDone = createMemo(() => soupQueryExcludesDone([args().body]));const [now, setNow] = createSignal(new Date());const dateTimer = setInterval(() => setNow(new Date()), 60_000);@@ -171,7 +167,7 @@ export function createGraphqlGroupedSoupAstItemsQuery(const query = createUrqlQuery<GroupSoupQuery,GroupSoupQueryVariables,- SoupAstItemsData+ { viewerId: string; data: SoupAstItemsData }>(() => {const queryOptions = options();const groupBy = args().groupBy;@@ -201,12 +197,14 @@ export function createGraphqlGroupedSoupAstItemsQuery(version);},- select: (data: GroupSoupQuery) =>- mapGraphqlGroupedSoupData(data, groupBy!, {+ select: (data: GroupSoupQuery) => ({+ viewerId: data.user.id,+ data: mapGraphqlGroupedSoupData(data, groupBy!, {instructionsIdQuery,showSupportedForeignEntities:queryOptions.showSupportedForeignEntities,}),+ }),};if (!queryOptions.enabled || !groupBy || queryInput === undefined) {@@ -220,6 +218,13 @@ export function createGraphqlGroupedSoupAstItemsQuery(};});+ // Missing data during a refetch does not itself switch identities. A new+ // viewer's first response still invalidates every old restoration snapshot.+ const viewerId = createMemo<string | undefined>(+ (previous) => query.data?.viewerId ?? previous,+ undefined+ );+onCleanup(registerGraphqlSoupRevalidations(() => {const queryInput = input();@@ -257,19 +262,15 @@ export function createGraphqlGroupedSoupAstItemsQuery();return {- data: () => {- const data = cachedMail() ?? query.data;- return withoutPendingGraphqlSoupDeletes(- data,- excludesDone()- ? withPendingDoneIds(- pendingDeleteIds(),- data?.entities ?? [],- pendingDone()- )- : pendingDeleteIds()- );- },+ data: createMemo(() =>+ projectDone(+ JSON.stringify([input(), viewerId()]),+ cachedMail() ?? query.data?.data,+ pendingDone(),+ excludesDone(),+ pendingDeleteIds()+ )+ ),error,isSupported,isEnabled: () => query.isEnabled,diff --git a/apps/web/src/lib/queries/soup/graphql/items.ts b/apps/web/src/lib/queries/soup/graphql/items.tsindex 34133490c4..636af14879 100644--- a/apps/web/src/lib/queries/soup/graphql/items.ts+++ b/apps/web/src/lib/queries/soup/graphql/items.ts@@ -65,15 +65,10 @@ import {} from '../transform-utils';import { registerGraphqlSoupRevalidations } from './active-queries';import { makeGraphqlSoupInput } from './ast';+import { createGraphqlSoupDoneProjection } from './done-projection';import { isCachedMailView, materializeMailView } from './mail-view';-import {- usePendingGraphqlSoupDeleteIds,- withoutPendingGraphqlSoupDeletes,-} from './optimistic-deletions';-import {- usePendingGraphqlSoupDone,- withPendingDoneIds,-} from './optimistic-done';+import { usePendingGraphqlSoupDeleteIds } from './optimistic-deletions';+import { usePendingGraphqlSoupDone } from './optimistic-done';import {materializeReconciledSoup,soupItemKey,@@ -132,6 +127,7 @@ export function createGraphqlSoupAstItemsQuery(const instructionsIdQuery = useInstructionsMdIdQuery();const pendingDeleteIds = usePendingGraphqlSoupDeleteIds();const pendingDone = usePendingGraphqlSoupDone();+ const projectDone = createGraphqlSoupDoneProjection();const excludesDone = createMemo(() => soupQueryExcludesDone([args().body]));const offline = createBrowserOfflineSignal();const [fetchingMailPage, setFetchingMailPage] = createSignal(false);@@ -855,18 +851,15 @@ export function createGraphqlSoupAstItemsQuery(localOptimistic: () => displayLocalProjection()?.mail?.optimistic ?? false,data: createMemo(() => {const data = displayData();- return withoutPendingGraphqlSoupDeletes(+ return projectDone(+ JSON.stringify([firstPageInput(), cacheGeneration]),data && {...data,oldestFetchedTimestamp: query.data?.data.oldestFetchedTimestamp,},- excludesDone()- ? withPendingDoneIds(- pendingDeleteIds(),- data?.entities ?? [],- pendingDone()- )- : pendingDeleteIds()+ pendingDone(),+ excludesDone(),+ pendingDeleteIds());}),error,diff --git a/apps/web/src/lib/queries/soup/graphql/keys.ts b/apps/web/src/lib/queries/soup/graphql/keys.tsindex 0fa3d2c95a..6de2f0549b 100644--- a/apps/web/src/lib/queries/soup/graphql/keys.ts+++ b/apps/web/src/lib/queries/soup/graphql/keys.ts@@ -3,5 +3,8 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';/** Ephemeral client state, outside the persisted REST Soup query namespace. */export const graphqlSoupKeys = createQueryKeys('graphql-soup', {retainedDeletions: null,- pendingDone: null,+ doneSession: null,+ pendingDone: (viewerId: string, session: string) => ({+ queryKey: [viewerId, session],+ }),});diff --git a/apps/web/src/lib/queries/soup/graphql/optimistic-done.test.ts b/apps/web/src/lib/queries/soup/graphql/optimistic-done.test.tsindex 736f0d2e2e..87590f79ec 100644--- a/apps/web/src/lib/queries/soup/graphql/optimistic-done.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/optimistic-done.test.ts@@ -1,5 +1,5 @@import type { EntityData } from '@entity/types/entity';-import { QueryClient } from '@tanstack/solid-query';+import { QueryClient, useQuery } from '@tanstack/solid-query';import { createRoot } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -9,6 +9,14 @@ vi.mock('@queries/client', () => ({},}));+const refresh = vi.hoisted(() => vi.fn(async () => {}));+vi.mock('./active-queries', () => ({+ refreshActiveGraphqlSoupQueries: refresh,+}));++import { authKeys } from '../../auth/keys';+import { resetGraphqlSoupDoneSession } from './done-session';+import { graphqlSoupKeys } from './keys';import {GRAPHQL_SOUP_DONE_RETENTION_MS,hideGraphqlSoupEntitiesAsDone,@@ -20,7 +28,13 @@ import {let client: QueryClient;let dispose: (() => void) | undefined;beforeEach(() => {+ refresh.mockReset();+ refresh.mockResolvedValue();client = new QueryClient();+ client.setQueryData(authKeys.userInfo.queryKey, {+ userId: 'viewer',+ authenticated: true,+ });});afterEach(() => {dispose?.();@@ -29,18 +43,37 @@ afterEach(() => {vi.useRealTimers();});+const STARTED_AT = Date.parse('2026-10-01T12:00:00Z');+const AFTER_ACTION = new Date(STARTED_AT + 1_000).toISOString();+const entity = (id: string,- notifications: { id: string; state: string }[] = []+ notifications: { id: string; state: string; created_at?: string }[] = []): EntityData =>- ({ id, type: 'email', notifications }) as unknown as EntityData;+ ({+ id,+ type: 'email',+ notifications: notifications.map((notification) => ({+ created_at: new Date(STARTED_AT - 1_000).toISOString(),+ ...notification,+ })),+ }) as unknown as EntityData;const pending = (entityIds: string[],notificationIds: string[] = []): PendingGraphqlSoupDone => ({+ operation: {},+ viewerId: 'viewer',+ session: 'test-session',+ done: true,+ observe: vi.fn(),+ unobserve: vi.fn(),entityIds: new Set(entityIds),notificationIds: new Set(notificationIds),+ startedAt: STARTED_AT,+ notificationStartedAt: STARTED_AT,+ scopeChannelThreads: false,});function observePending() {@@ -73,7 +106,7 @@ describe('withPendingDoneIds', () => {[entity('a', [{ id: 'n1', state: 'unseen' },- { id: 'n2', state: 'unseen' },+ { id: 'n2', state: 'unseen', created_at: AFTER_ACTION },]),],[pending(['a'], ['n1'])]@@ -81,6 +114,56 @@ describe('withPendingDoneIds', () => {expect(hidden.has('a')).toBe(false);});+ it('lets the latest Done win after fresh activity re-admitted the row', () => {+ const row = entity('a', [+ { id: 'n1', state: 'done' },+ { id: 'n2', state: 'unseen', created_at: AFTER_ACTION },+ ]);+ const first = pending(['a'], ['n1']);+ const second = pending(['a'], ['n1', 'n2']);+ expect(withPendingDoneIds(new Set(), [row], [first]).has('a')).toBe(false);+ expect(withPendingDoneIds(new Set(), [row], [first, second]).has('a')).toBe(+ true+ );+ // Releasing the second action restores the earlier decision, not a global clear.+ expect(withPendingDoneIds(new Set(), [row], [first]).has('a')).toBe(false);+ });++ it.each([new Date(STARTED_AT - 1).toISOString(), 'invalid', undefined])(+ 'does not mistake a previously unloaded notification for new activity (%s)',+ (created_at) => {+ const row = entity('a', [+ { id: 'unloaded', state: 'unseen', created_at },+ ]);+ expect(+ withPendingDoneIds(new Set(), [row], [pending(['a'])]).has('a')+ ).toBe(true);+ }+ );++ it('does not let a separate thread re-admit a scoped channel row', () => {+ const row = {+ id: 'a',+ type: 'channel',+ notifications: [+ {+ id: 'thread-notification',+ state: 'unseen',+ created_at: AFTER_ACTION,+ notification_metadata: {+ tag: 'channel_message_reply',+ content: { messageId: 'reply', threadId: 'root' },+ },+ },+ ],+ } as unknown as EntityData;+ expect(+ withPendingDoneIds(new Set(), [row], [pending(['a'])]).has('a')+ ).toBe(false);+ const scoped = { ...pending(['a']), scopeChannelThreads: true };+ expect(withPendingDoneIds(new Set(), [row], [scoped]).has('a')).toBe(true);+ });+it('keeps hiding once the marked notifications are done', () => {const hidden = withPendingDoneIds(new Set(),@@ -107,15 +190,340 @@ describe('hideGraphqlSoupEntitiesAsDone', () => {await vi.waitFor(() => expect(read()).toEqual([]));});- it('expires overlays that are never released', async () => {+ it('does not expire a write that is still pending', async () => {+ vi.useFakeTimers();+ const read = observePending();+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DONE_RETENTION_MS * 2);+ expect(read()).toHaveLength(1);+ expect(refresh).not.toHaveBeenCalled();+ overlay.release();+ });++ it('collects settled intents with no mounted readers', async () => {+ vi.useFakeTimers();+ const read = observePending();+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ overlay.settle();+ await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DONE_RETENTION_MS);+ expect(read()).toEqual([]);+ });++ it('waits for both settlement and every mounted reader to acknowledge', async () => {+ const read = observePending();+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ await vi.waitFor(() => expect(read()).toHaveLength(1));+ const entry = read()[0];+ const all = {},+ signal = {};+ entry.observe(all, true);+ entry.observe(signal, false);+ overlay.settle();+ await Promise.resolve();+ expect(read()).toHaveLength(1);+ entry.observe(signal, true);+ await vi.waitFor(() => expect(read()).toEqual([]));+ });++ it('retains intent when reconciliation is stale or fails past the old expiry', async () => {vi.useFakeTimers();+ refresh.mockRejectedValue(new Error('offline'));const read = observePending();- hideGraphqlSoupEntitiesAsDone({ entityIds: ['a'], notificationIds: [] });- hideGraphqlSoupEntitiesAsDone({ entityIds: ['b'], notificationIds: [] });+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });await vi.advanceTimersByTimeAsync(1);- expect(read()).toHaveLength(2);+ read()[0].observe({}, false);+ overlay.settle();+ await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DONE_RETENTION_MS);+ expect(refresh).toHaveBeenCalledOnce();+ expect(read()).toHaveLength(1);+ overlay.release();+ });+ it('collects an unmounted settled intent even when its refresh never responds', async () => {+ vi.useFakeTimers();+ let finish!: () => void;+ refresh.mockReturnValue(+ new Promise<void>((resolve) => {+ finish = resolve;+ })+ );+ const read = observePending();+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ await vi.advanceTimersByTimeAsync(1);+ const reader = {};+ read()[0].observe(reader, false);+ overlay.settle();+ await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DONE_RETENTION_MS * 2);+ expect(refresh).toHaveBeenCalledOnce();+ expect(read()).toHaveLength(1);+ read()[0].unobserve(reader);await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DONE_RETENTION_MS);expect(read()).toEqual([]);+ finish();+ });++ it('retires superseded intent after acknowledgement without losing other bulk targets', async () => {+ const read = observePending();+ const first = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a', 'b'],+ notificationIds: [],+ });+ const latest = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ done: false,+ });+ await vi.waitFor(() => expect(read()).toHaveLength(2));+ read()[1].observe({}, true);+ latest.settle();+ await vi.waitFor(() => expect(read()).toHaveLength(1));+ expect([...read()[0].entityIds]).toEqual(['b']);+ first.release();+ });++ it('does not let a delayed old acknowledgement release an intent with new exact IDs', async () => {+ const read = observePending();+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: ['known'],+ });+ await vi.waitFor(() => expect(read()).toHaveLength(1));+ const old = read()[0];+ const reader = {};+ old.observe(reader, true);+ overlay.settle(['known', 'authoritative']);+ old.observe(reader, true);+ await vi.waitFor(() =>+ expect(read()[0].notificationIds.has('authoritative')).toBe(true)+ );+ expect(read()).toHaveLength(1);+ read()[0].observe(reader, true);+ await vi.waitFor(() => expect(read()).toEqual([]));+ });++ it('keeps the original notification cutoff across Undo/Redo', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(STARTED_AT);+ const read = observePending();+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: ['n1'],+ });+ await vi.advanceTimersByTimeAsync(1);+ overlay.setDone(false);+ await vi.advanceTimersByTimeAsync(2_000);+ overlay.setDone(true);+ await vi.advanceTimersByTimeAsync(1);+ const entry = read()[0];+ expect(entry.startedAt).toBeGreaterThan(STARTED_AT);+ expect(entry.notificationStartedAt).toBe(STARTED_AT);+ const document = {+ ...entity('a', [{ id: 'n2', state: 'unseen', created_at: AFTER_ACTION }]),+ type: 'document',+ } as EntityData;+ expect(withPendingDoneIds(new Set(), [document], [entry]).has('a')).toBe(+ false+ );+ overlay.release();+ });++ it('does not replace the authenticated viewer query fetcher', async () => {+ const fetchViewer = vi.fn(async () => ({+ userId: 'bob',+ authenticated: true,+ }));+ let read!: ReturnType<typeof usePendingGraphqlSoupDone>;+ dispose = createRoot((disposeRoot) => {+ useQuery(+ () => ({+ queryKey: authKeys.userInfo.queryKey,+ queryFn: fetchViewer,+ staleTime: Infinity,+ }),+ () => client+ );+ read = usePendingGraphqlSoupDone();+ return disposeRoot;+ });+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ await vi.waitFor(() => expect(read()).toHaveLength(1));+ await client.invalidateQueries(+ { queryKey: authKeys.userInfo.queryKey },+ { throwOnError: true }+ );+ expect(fetchViewer).toHaveBeenCalledOnce();+ await vi.waitFor(() => expect(read()).toEqual([]));+ overlay.release();+ });++ it('isolates a shared entity id when the authenticated viewer changes', async () => {+ const read = observePending();+ const alice = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['shared'],+ notificationIds: [],+ });+ await vi.waitFor(() => expect(read()).toHaveLength(1));+ const previous = read()[0];+ client.setQueryData(authKeys.userInfo.queryKey, {+ userId: 'bob',+ authenticated: true,+ });+ const bob = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['shared'],+ notificationIds: [],+ });+ await vi.waitFor(() =>+ expect(read().map((e) => e.viewerId)).toEqual(['bob'])+ );+ const current = read()[0];+ alice.setDone(false);+ alice.settle();+ alice.release();+ await Promise.resolve();+ expect(read()[0].operation).toBe(current.operation);+ expect(read()[0].operation).not.toBe(previous.operation);+ expect(read()[0].done).toBe(true);+ bob.release();+ });++ it('rebinds mounted readers and fences old handles on same-account login', async () => {+ const read = observePending();+ const previous = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ await vi.waitFor(() => expect(read()).toHaveLength(1));+ const session = read()[0].session;+ resetGraphqlSoupDoneSession();+ const current = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ done: false,+ });+ await vi.waitFor(() => expect(read()[0]?.done).toBe(false));+ expect(read()[0].session).not.toBe(session);+ previous.setDone(true);+ previous.settle();+ previous.release();+ expect(+ client.getQueryData(+ graphqlSoupKeys.pendingDone('viewer', session).queryKey+ )+ ).toBeUndefined();+ expect(read()[0].done).toBe(false);+ current.release();+ });++ it('does not publish display intent without an authenticated viewer', async () => {+ client.setQueryData(authKeys.userInfo.queryKey, {+ userId: '',+ authenticated: false,+ });+ const read = observePending();+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ overlay.setDone(false);+ overlay.settle();+ await Promise.resolve();+ expect(read()).toEqual([]);+ overlay.release();+ });++ it('preserves the cached viewer through an offline auth refresh error', async () => {+ const read = observePending();+ client+ .getQueryCache()+ .find({ queryKey: authKeys.userInfo.queryKey })!+ .setState({+ status: 'error',+ error: new Error('offline'),+ });+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ await vi.waitFor(() =>+ expect(read().map((e) => e.viewerId)).toEqual(['viewer'])+ );+ overlay.release();+ });++ it('ignores a late refresh and Undo from a retired session', async () => {+ vi.useFakeTimers();+ let finish!: () => void;+ refresh.mockReturnValue(+ new Promise<void>((resolve) => {+ finish = resolve;+ })+ );+ const read = observePending();+ const previous = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ await vi.advanceTimersByTimeAsync(1);+ read()[0].observe({}, false);+ previous.settle();+ await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DONE_RETENTION_MS);+ expect(refresh).toHaveBeenCalledOnce();+ client.setQueryData(authKeys.userInfo.queryKey, {+ userId: 'bob',+ authenticated: true,+ });+ resetGraphqlSoupDoneSession();+ const current = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: [],+ });+ await vi.advanceTimersByTimeAsync(1);+ finish();+ previous.setDone(false);+ previous.settle();+ await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DONE_RETENTION_MS);+ expect(refresh).toHaveBeenCalledOnce();+ expect(read().map((e) => [e.viewerId, e.done])).toEqual([['bob', true]]);+ current.release();+ });++ it('retains operation identity across Undo and ignores acknowledgements of older intent', async () => {+ const read = observePending();+ const overlay = hideGraphqlSoupEntitiesAsDone({+ entityIds: ['a'],+ notificationIds: ['n1'],+ });+ await vi.waitFor(() => expect(read()).toHaveLength(1));+ const old = read()[0];+ overlay.setDone(false);+ await vi.waitFor(() => expect(read()[0].done).toBe(false));+ const undone = read()[0];+ expect(undone.operation).toBe(old.operation);+ const reader = {};+ undone.observe(reader, false);+ old.observe(reader, true);+ overlay.settle();+ await Promise.resolve();+ expect(read()).toHaveLength(1);+ undone.observe(reader, true);+ await vi.waitFor(() => expect(read()).toEqual([]));});});diff --git a/apps/web/src/lib/queries/soup/graphql/optimistic-done.ts b/apps/web/src/lib/queries/soup/graphql/optimistic-done.tsindex 88ac38c942..d5a97a0882 100644--- a/apps/web/src/lib/queries/soup/graphql/optimistic-done.ts+++ b/apps/web/src/lib/queries/soup/graphql/optimistic-done.ts@@ -1,92 +1,337 @@+import { scopeChannelNotificationsForEntity } from '@app/features/soup/entity-notifications';import type { EntityData } from '@entity/types/entity';import type { Notification } from '@entity/types/notification';import { skipToken, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';+import { authKeys } from '../../auth/keys';+import type { UserInfoData } from '../../auth/user-info';import { queryClient } from '../../client';+import { refreshActiveGraphqlSoupQueries } from './active-queries';+import { getGraphqlSoupDoneSession } from './done-session';import { graphqlSoupKeys } from './keys';-/** How long a done overlay may outlive the action that created it. */+/** Retry reconciliation, or collect a settled intent with no mounted readers. */export const GRAPHQL_SOUP_DONE_RETENTION_MS = 60_000;-/** Entities marked done, with the notifications that were active at the time. */export type PendingGraphqlSoupDone = {+ /** Stable across Done/Undo/Redo; query-local snapshots are weakly keyed by it. */+ operation: object;+ viewerId: string;+ session: string;entityIds: ReadonlySet<string>;notificationIds: ReadonlySet<string>;+ done: boolean;+ startedAt: number;+ /** Redo is ID-scoped and must not dismiss notifications arriving after the initial action. */+ notificationStartedAt: number;+ scopeChannelThreads: boolean;+ /** Acknowledge raw query state, never the locally projected result. */+ observe: (reader: object, acknowledged: boolean) => void;+ unobserve: (reader: object) => void;};export type GraphqlSoupDoneOverlay = {- /** Stop hiding the entities, e.g. after a rollback or an undo. */release: () => void;+ /** Publish a new intent, retaining this operation's query-local undo snapshots. */+ setDone: (done: boolean) => void;+ /** The write succeeded (or was durably accepted); wait for cache acknowledgement. */+ settle: (notificationIds?: readonly string[]) => void;};-const PENDING_DONE_KEY = graphqlSoupKeys.pendingDone.queryKey;+type DoneIntentViewer = Pick<UserInfoData, 'userId' | 'authenticated'>;-/**- * Hides entities from done-excluding GraphQL lists until the cache or server- * reflects the done write. The entity-scoped notification mutation is not- * cache-optimistic, and an optimistic archive still has to be durably queued- * and re-evaluated by the list, so without this the row stays visible for a- * worker or server round trip plus the list re-renders.- */+function viewerIdFromInfo(+ info: DoneIntentViewer | undefined+): string | undefined {+ return info?.authenticated && info.userId ? info.userId : undefined;+}++function currentViewerId(): string | undefined {+ return viewerIdFromInfo(+ queryClient.getQueryData<DoneIntentViewer>(authKeys.userInfo.queryKey)+ );+}++/** Immediate display state, independent of durable enqueue and list recomputation. */export function hideGraphqlSoupEntitiesAsDone(args: {entityIds: readonly string[];notificationIds: readonly string[];+ scopeChannelThreads?: boolean;+ done?: boolean;}): GraphqlSoupDoneOverlay {- const entry: PendingGraphqlSoupDone = {- entityIds: new Set(args.entityIds),- notificationIds: new Set(args.notificationIds),+ const viewerId = currentViewerId();+ if (!viewerId) {+ return {+ release: () => undefined,+ setDone: () => undefined,+ settle: () => undefined,+ };+ }+ const session = getGraphqlSoupDoneSession();+ const pendingKey = graphqlSoupKeys.pendingDone(viewerId, session).queryKey;+ let retired = false;+ const ownsSession = () => {+ if (+ currentViewerId() !== viewerId ||+ queryClient.getQueryData(graphqlSoupKeys.doneSession.queryKey) !== session+ ) {+ retired = true;+ }+ return !retired;};- queryClient.setQueryData<PendingGraphqlSoupDone[]>(- PENDING_DONE_KEY,- (pending) => [...(pending ?? []), entry]- );- let released = false;- const release = () => {- if (released) return;- released = true;- clearTimeout(expiry);+ const operation = { id: crypto.randomUUID() };+ let current: PendingGraphqlSoupDone;+ let generation = 0;+ let active = false;+ let settled = false;+ let checking = false;+ let refreshing = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const readers = new Map<object, { version: number; acknowledged: boolean }>();++ const release = (acknowledged = false) => {+ if (!active) return;+ active = false;+ clearTimeout(timer);+ if (+ queryClient.getQueryData(graphqlSoupKeys.doneSession.queryKey) !== session+ )+ return;queryClient.setQueryData<PendingGraphqlSoupDone[]>(- PENDING_DONE_KEY,- (pending) => pending?.filter((candidate) => candidate !== entry)+ pendingKey,+ (pending) => {+ const position =+ pending?.findIndex((entry) => entry.operation === operation) ?? -1;+ return pending?.flatMap((entry, index) => {+ if (entry.operation === operation) return [];+ if (!acknowledged || position < 0 || index > position) return [entry];+ // Once the newest intent is acknowledged, an older overlapping intent+ // must not become visible again merely because this layer is collected.+ const entityIds = new Set(+ [...entry.entityIds].filter((id) => !current.entityIds.has(id))+ );+ if (entityIds.size === entry.entityIds.size) return [entry];+ return entityIds.size > 0 ? [{ ...entry, entityIds }] : [];+ });+ });};- // Server pushes and list refreshes replace the overlay long before this. The- // bound only keeps an overlay from outliving its action indefinitely.- const expiry = setTimeout(release, GRAPHQL_SOUP_DONE_RETENTION_MS);- return { release };+ const check = () => {+ if (checking) return;+ checking = true;+ // Query projections must finish registering/acknowledging before changing+ // their input. Never write the query cache inside a derivation.+ queueMicrotask(() => {+ checking = false;+ if (!ownsSession()) {+ release();+ return;+ }+ if (+ active &&+ settled &&+ readers.size > 0 &&+ [...readers.values()].every((reader) => reader.acknowledged)+ ) {+ release(true);+ }+ });+ };+ const retry = async () => {+ const version = generation;+ if (!active) return;+ if (!ownsSession()) {+ release();+ return;+ }+ if (settled && readers.size === 0) {+ release(true);+ return;+ }+ // Keep cleanup independent of a hung refresh, without starting overlapping+ // network retries. A later tick can collect an intent whose readers unmounted.+ timer = setTimeout(() => void retry(), GRAPHQL_SOUP_DONE_RETENTION_MS);+ if (settled && !refreshing) {+ refreshing = true;+ try {+ await refreshActiveGraphqlSoupQueries({ throwOnError: true });+ } catch {+ // A failed/stale refresh must not resurrect rows. Mounted readers keep+ // their intent until they actually observe it, or the user reverses it.+ } finally {+ refreshing = false;+ }+ }+ if (version !== generation) return;+ check();+ };+ const observations = (+ version: number+ ): Pick<PendingGraphqlSoupDone, 'observe' | 'unobserve'> => ({+ observe: (reader, acknowledged) => {+ if (version !== generation || !active) return;+ readers.set(reader, { version, acknowledged });+ check();+ },+ unobserve: (reader) => {+ if (readers.get(reader)?.version !== version) return;+ readers.delete(reader);+ check();+ },+ });+ const publish = (done: boolean) => {+ if (!ownsSession()) {+ release();+ return;+ }+ clearTimeout(timer);+ const version = ++generation;+ const now = Date.now();+ active = true;+ settled = false;+ readers.clear();+ current = {+ operation,+ viewerId,+ session,+ entityIds: new Set(args.entityIds),+ notificationIds: new Set(+ current?.notificationIds ?? args.notificationIds+ ),+ done,+ startedAt: now,+ notificationStartedAt: current?.notificationStartedAt ?? now,+ scopeChannelThreads: args.scopeChannelThreads ?? false,+ ...observations(version),+ };+ queryClient.setQueryData<PendingGraphqlSoupDone[]>(+ pendingKey,+ (pending) => [+ ...(pending ?? []).filter((entry) => entry.operation !== operation),+ current,+ ]+ );+ timer = setTimeout(() => void retry(), GRAPHQL_SOUP_DONE_RETENTION_MS);+ };+ publish(args.done ?? true);++ return {+ release: () => release(),+ setDone: publish,+ settle: (notificationIds = []) => {+ if (!active) return;+ if (!ownsSession()) {+ release();+ return;+ }+ settled = true;+ if (notificationIds.some((id) => !current.notificationIds.has(id))) {+ // Re-evaluate acknowledgements against the exact changed rows, not just+ // the subset known when the optimistic action started.+ for (const [reader, state] of readers) {+ readers.set(reader, { ...state, acknowledged: false });+ }+ current = {+ ...current,+ ...observations(++generation),+ notificationIds: new Set([+ ...current.notificationIds,+ ...notificationIds,+ ]),+ };+ queryClient.setQueryData<PendingGraphqlSoupDone[]>(+ pendingKey,+ (pending) =>+ pending?.map((entry) =>+ entry.operation === operation ? current : entry+ )+ );+ }+ check();+ },+ };}-/** The done overlays currently in effect. */export function usePendingGraphqlSoupDone(): Accessor<readonly PendingGraphqlSoupDone[]> {+ const viewer = useQuery(+ () => ({+ queryKey: authKeys.userInfo.queryKey,+ // Observe only. Unlike the private intent keys below, this key already+ // has an auth fetcher: skipToken would overwrite it during invalidation.+ enabled: false,+ select: (info: DoneIntentViewer) => viewerIdFromInfo(info),+ }),+ () => queryClient+ );+ // Background auth fetch errors may retain a valid cached/offline identity.+ // Read that cache directly rather than touching a pending resource's data.+ const viewerId = () => (viewer.isSuccess ? viewer.data : currentViewerId());+ const session = useQuery(+ () => ({+ queryKey: graphqlSoupKeys.doneSession.queryKey,+ queryFn: skipToken,+ initialData: () => crypto.randomUUID(),+ gcTime: Infinity,+ }),+ () => queryClient+ );+ const sessionId = () => (session.isSuccess ? session.data : undefined);const pending = useQuery(() => ({- queryKey: PENDING_DONE_KEY,+ queryKey: graphqlSoupKeys.pendingDone(viewerId() ?? '', sessionId() ?? '')+ .queryKey,queryFn: skipToken,initialData: [] as PendingGraphqlSoupDone[],- // Entries have bounded lifetimes even when no view observes this query.gcTime: Infinity,}),() => queryClient);- return () => (pending.isSuccess ? pending.data : []);+ return () => {+ const owner = viewerId();+ const currentSession = sessionId();+ return owner && currentSession && pending.isSuccess+ ? pending.data.filter(+ (entry) =>+ entry.viewerId === owner && entry.session === currentSession+ )+ : [];+ };}-function activeNotifications(entity: EntityData): Notification[] {- const notifications = (entity as { notifications?: unknown }).notifications;- return Array.isArray(notifications)- ? (notifications as Notification[]).filter(- (notification) => notification.state !== 'done'- )- : [];+export function soupDoneNotifications(+ entity: EntityData,+ scopeChannelThreads: boolean+): Notification[] {+ const attached = (entity as { notifications?: unknown }).notifications;+ if (!Array.isArray(attached)) return [];+ const notifications = attached as Notification[];+ return scopeChannelThreads &&+ (entity.type === 'channel' || entity.type === 'channel_thread')+ ? scopeChannelNotificationsForEntity(entity, notifications)+ : notifications;+}++/** Only positively newer, in-scope activity may supersede Done. */+export function hasActivityAfterDone(+ entity: EntityData,+ intent: PendingGraphqlSoupDone+): boolean {+ return (+ intent.done &&+ soupDoneNotifications(entity, intent.scopeChannelThreads).some(+ ({ id, state, created_at }) =>+ state !== 'done' &&+ !intent.notificationIds.has(id) &&+ Date.parse(created_at) >+ (entity.type === 'email'+ ? intent.startedAt+ : intent.notificationStartedAt)+ )+ );}-/**- * Adds the ids a done-excluding list hides to `hiddenIds`. An entity that has- * an active notification newer than the done action (one that was not marked)- * stays visible, so fresh activity re-admits it immediately.- */export function withPendingDoneIds(hiddenIds: ReadonlySet<string>,entities: readonly EntityData[],@@ -95,12 +340,10 @@ export function withPendingDoneIds(if (pending.length === 0) return hiddenIds;let hidden: Set<string> | undefined;for (const entity of entities) {- const covering = pending.find(({ entityIds }) => entityIds.has(entity.id));- if (!covering) continue;- const readmitted = activeNotifications(entity).some(- ({ id }) => !covering.notificationIds.has(id)+ const covering = pending.findLast(({ entityIds }) =>+ entityIds.has(entity.id));- if (readmitted) continue;+ if (!covering?.done || hasActivityAfterDone(entity, covering)) continue;hidden ??= new Set(hiddenIds);hidden.add(entity.id);}diff --git a/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.ts b/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.tsindex d8f602f8fe..8b95cc66c4 100644--- a/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.ts+++ b/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.ts@@ -103,10 +103,11 @@ function makeFakeClient(): {executions.push({variables: request.variables,next: (page, state) =>- subject.next({ operation, data: { page }, ...state } as OperationResult<- unknown,- GroupSoupQueryVariables- >),+ subject.next({+ operation,+ data: { page, user: { id: 'viewer' } },+ ...state,+ } as OperationResult<unknown, GroupSoupQueryVariables>),fail: (error) =>subject.next({ operation, error, stale: false, hasNext: false }),get unsubscribed() {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 a250ac2d5a..15c5ca22c2 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@@ -96,6 +96,8 @@ vi.mock('./graphql/grouped-items', () => ({}));import { refreshActiveGraphqlSoupQueries } from './graphql/active-queries';+import { makeGraphqlGroupedSoupInput } from './graphql/ast';+import { createGraphqlGroupedSoupAstItemsQuery } from './graphql/grouped-items';import { createGraphqlSoupAstItemsQuery } from './graphql/items';import {type SoupAstItemsData,@@ -242,6 +244,50 @@ describe('Soup refetch transport selection', () => {expect(groupedQuery.refresh).not.toHaveBeenCalled();});+ it.each(['inbox', 'drafts', 'sent', 'all'] as const)(+ 'keeps grouped %s mail on REST even when GraphQL is explicitly requested and cached mail exists',+ async (emailView) => {+ testState.graphqlEnabled = true;+ vi.mocked(createGraphqlGroupedSoupAstItemsQuery).mockImplementationOnce(+ (args) => ({+ ...groupedQuery,+ // Use the real AST eligibility boundary, not the default supported mock.+ isSupported: () => {+ const request = args();+ if (!request.groupBy) return false;+ try {+ makeGraphqlGroupedSoupInput({+ ...request,+ groupBy: request.groupBy,+ });+ return true;+ } catch {+ return false;+ }+ },+ data: () => ({ cachedMail: true, entities: [], groups: [] }),+ })+ );+ const query = createRoot((dispose) => {+ disposeRoot = dispose;+ return useSoupAstItemsQuery(() => ({+ params: { sort_method: 'updated_at' },+ body: { emailView },+ groupBy: { type: 'date' },+ transport: 'graphql',+ }));+ });+ expect(query.transport).toBe('rest');+ expect(query.data).toBeUndefined(); // Never exposes the private cached-Mail projection.+ const restOptions = vi.mocked(useInfiniteQuery).mock.calls.at(-1)?.[0];+ expect(restOptions?.().enabled).toBe(true);+ await query.refetch();+ await refreshActiveGraphqlSoupQueries();+ expect(restRefetch).toHaveBeenCalledOnce();+ expect(groupedQuery.refresh).not.toHaveBeenCalled();+ }+ );+it('uses GraphQL refetch and mutation-driven refresh when the flag is on', async () => {testState.graphqlEnabled = true;const query = mountAutoTransportQuery();diff --git a/crates/email/fixtures/email_thread_unarchive.sql b/crates/email/fixtures/email_thread_unarchive.sqlnew file mode 100644index 0000000000..6cff81ad98--- /dev/null+++ b/crates/email/fixtures/email_thread_unarchive.sql@@ -0,0 +1,23 @@+-- Received-message history is independent of the current INBOX label/timestamp.+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES+ ('c0000001-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW()),+ ('c0000002-0000-0000-0000-000000000002', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NOW(), NOW());++INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES+ ('44444444-4444-4444-4444-444444444444', 'sent-only', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, true, NOW(), NOW()),+ ('55555555-5555-5555-5555-555555555555', 'self-addressed-draft', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, true, NOW(), NOW()),+ ('66666666-6666-6666-6666-666666666666', 'self-addressed-mail', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, true, NOW(), NOW());++INSERT INTO email_messages (id, thread_id, link_id, provider_id, from_contact_id, is_read, is_starred, is_sent, is_draft, has_attachments, internal_date_ts, created_at, updated_at)+VALUES+ ('44444444-aaaa-aaaa-aaaa-444444444444', '44444444-4444-4444-4444-444444444444', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sent-only-message', 'c0000001-0000-0000-0000-000000000001', true, false, true, false, false, '2025-01-01T10:00:00Z', NOW(), NOW()),+ ('55555555-aaaa-aaaa-aaaa-555555555555', '55555555-5555-5555-5555-555555555555', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'c0000001-0000-0000-0000-000000000001', true, false, false, true, false, '2025-01-01T10:00:00Z', NOW(), NOW()),+ ('66666666-aaaa-aaaa-aaaa-666666666666', '66666666-6666-6666-6666-666666666666', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'self-addressed-message', 'c0000001-0000-0000-0000-000000000001', true, false, true, false, false, '2025-01-01T10:00:00Z', NOW(), NOW());++INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)+VALUES+ ('44444444-aaaa-aaaa-aaaa-444444444444', 'c0000002-0000-0000-0000-000000000002', 'TO'),+ ('55555555-aaaa-aaaa-aaaa-555555555555', 'c0000001-0000-0000-0000-000000000001', 'TO'),+ ('66666666-aaaa-aaaa-aaaa-666666666666', 'c0000001-0000-0000-0000-000000000001', 'BCC');diff --git a/crates/email/src/domain/service/thread_labels.rs b/crates/email/src/domain/service/thread_labels.rsindex 08387cddd2..c850b46b17 100644--- a/crates/email/src/domain/service/thread_labels.rs+++ b/crates/email/src/domain/service/thread_labels.rs@@ -125,14 +125,9 @@ where.await.map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?.ok_or(EmailErr::ThreadNotFound)?;- let thread = self- .email_repo- .thread_by_id(thread_id)- .await- .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?- .ok_or(EmailErr::ThreadNotFound)?;- if !archived && thread.latest_inbound_message_ts.is_none() {- return Err(EmailErr::ThreadHasNoInboundMessages);+ if !archived {+ self.ensure_thread_has_received_messages(thread_id, link.id)+ .await?;}let label = self.email_repo@@ -147,6 +142,63 @@ whereOk(())}+ /// Inbox sorting timestamps disappear after archive/provider sync. Determine+ /// whether a thread can be restored from its messages, not current labels.+ async fn ensure_thread_has_received_messages(+ &self,+ thread_id: Uuid,+ link_id: Uuid,+ ) -> Result<(), EmailErr> {+ let messages = self+ .email_repo+ .get_thread_label_messages(thread_id, link_id)+ .await+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;+ if messages+ .iter()+ .any(|message| !message.is_draft && !message.is_sent)+ {+ return Ok(());+ }++ // A sent message addressed back to its sender is also received mail.+ // Drafts never establish received-message history, even if self-addressed.+ let sent_ids: Vec<_> = messages+ .iter()+ .filter(|message| message.is_sent && !message.is_draft)+ .map(|message| message.db_id)+ .collect();+ if sent_ids.is_empty() {+ return Err(EmailErr::ThreadHasNoInboundMessages);+ }+ let (senders, recipients) = tokio::try_join!(+ async {+ self.email_repo+ .senders_by_message_ids(&sent_ids)+ .await+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))+ },+ async {+ self.email_repo+ .recipients_by_message_ids(&sent_ids)+ .await+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))+ },+ )?;+ if sent_ids.iter().any(|id| {+ senders.get(id).is_some_and(|sender| {+ recipients.get(id).is_some_and(|recipients| {+ recipients+ .iter()+ .any(|(recipient, _)| recipient.email.eq_ignore_ascii_case(&sender.email))+ })+ })+ }) {+ return Ok(());+ }+ Err(EmailErr::ThreadHasNoInboundMessages)+ }+#[tracing::instrument(err, skip(self), fields(user_id = %macro_id, %thread_id, %label_id, add))]pub(crate) async fn update_thread_labels_for_user_impl(&self,diff --git a/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs b/crates/email/src/outbound/email_pg_repo/test/thread_archive.rsindex 088d0c9c67..79e1fee28a 100644--- a/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs+++ b/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs@@ -172,7 +172,7 @@ async fn assert_inbox_state(async fn archive_undo_redo_are_idempotent_and_use_the_threads_own_inbox(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let service = service(pool);+ let service = service(pool.clone());let owner = MacroUserIdStr::try_from_email("[email protected]")?;let first = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;let second = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;@@ -182,6 +182,27 @@ async fn archive_undo_redo_are_idempotent_and_use_the_threads_own_inbox(.await?;assert_inbox_state(&service.email_repo, second, !archived).await?;assert_inbox_state(&service.email_repo, first, true).await?;+ // Model provider sync between actions, including delayed Undo. The+ // inbox sort timestamp legitimately vanishes when INBOX is removed.+ let mut tx = pool.begin().await?;+ super::super::thread::update_thread_metadata(+ &mut tx,+ second,+ Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-bbbbbbbbbbbb")?,+ )+ .await?;+ tx.commit().await?;+ if archived {+ assert!(+ service+ .email_repo+ .thread_by_id(second)+ .await?+ .unwrap()+ .latest_inbound_message_ts+ .is_none()+ );+ }}Ok(())}@@ -257,21 +278,60 @@ async fn failed_archive_rolls_back_inbox_label_removal(pool: Pool<Postgres>) ->migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../../fixtures", scripts("email_thread_labels")))]-async fn unarchive_requires_a_canonical_inbound_message(+async fn unarchive_uses_messages_when_the_inbox_sort_timestamp_is_missing(pool: Pool<Postgres>,) -> anyhow::Result<()> {let service = service(pool);let thread = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;- assert!(matches!(+ assert!(service- .set_thread_archived_impl(- MacroUserIdStr::try_from_email("[email protected]")?,- thread,- false,- )- .await,- Err(EmailErr::ThreadHasNoInboundMessages)- ));+ .email_repo+ .thread_by_id(thread)+ .await?+ .unwrap()+ .latest_inbound_message_ts+ .is_none()+ );+ service+ .set_thread_archived_impl(+ MacroUserIdStr::try_from_email("[email protected]")?,+ thread,+ false,+ )+ .await?;assert_inbox_state(&service.email_repo, thread, true).await?;Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_thread_labels", "email_thread_unarchive")+ )+)]+async fn unarchive_rejects_sent_only_and_drafts_but_accepts_self_addressed_mail(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let service = service(pool);+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;+ for id in [+ "44444444-4444-4444-4444-444444444444",+ "55555555-5555-5555-5555-555555555555",+ ] {+ let thread = Uuid::parse_str(id)?;+ assert!(matches!(+ service+ .set_thread_archived_impl(owner.clone(), thread, false)+ .await,+ Err(EmailErr::ThreadHasNoInboundMessages)+ ));+ assert_inbox_state(&service.email_repo, thread, false).await?;+ }+ let self_addressed = Uuid::parse_str("66666666-6666-6666-6666-666666666666")?;+ service+ .set_thread_archived_impl(owner, self_addressed, false)+ .await?;+ assert_inbox_state(&service.email_repo, self_addressed, true).await?;+ Ok(())+}diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 038e7f54fd..5cda809585 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -101,14 +101,29 @@ other entity partitions, and notified-at sorting still use the network path.The Mark done action (`e`, row menu) hides its rows at once from GraphQL lists thatexclude done items, such as Email Important/Noise and Home Signal, without waiting-for the server. Lists that show done items, such as Email All, keep the row. Undo-or a failed write brings the row back, and so does a new active notification on the-entity. To verify, mark a row done and watch it for a few seconds. It must not-reappear once the server reply lands, and it must stay gone after a reload.+for the server. Email All keeps the row and flips its done indicator immediately.+Undo restores a previously admitted row even after the cache has removed it,+without waiting for the reversal's server reply; changing filters/sort clears+those view-local restoration snapshots. Home's separate recent-activity inclusion+rules are unchanged. Test Done/Undo/Redo with delayed replies and verify both flat+and grouped rows/counts. A failure must roll back only its own local intent.+Newer in-scope activity can re-admit a row, but loading an older notification or+activity in a separate channel thread must not. Redo targets the original exact+notification IDs, not notifications received since the original action. A newer+Done must win over an older retained overlay. Delay reconciliation past a minute:+pending/stale state must not simply expire and resurrect the row. Once committed,+mounted cache readers must acknowledge the intent before its overlay is released.+GraphQL display intents are scoped to the authenticated viewer and login session.+Login/logout retires old buckets; even same-account native reauthentication must+not let old overlay Undo/Redo handles or a late refresh republish old intent.+Verify account changes with overlapping entity IDs and a pending/failed refresh.+After a successful Done, verify that the row stays gone after a reload.In Tasks, Email, Home and Drive, rows keep their DOM when the list updates. Aproperty edit or a rename updates the edited row in place instead of rebuildingevery visible row. To verify, watch the row nodes with a `MutationObserver` while-editing: only moved or removed rows should be added or removed.+editing: only moved or removed rows should be added or removed. Rename a row and+then drag it: its drag label/payload must use the new fields without another+registration/layout measurement.Channels use the same general Soup reconciliation path, not a separate local pagechain. Channel ID, type, team, organization, importance, and participant-scoped@@ -426,6 +441,16 @@ show the previous email. A failed load must still show its error and Retry actioreconciling an already-open offline draft must preserve its composer and text.If local cache initialization fails, ordinary server threads must still loadthrough the session's uncached GraphQL client, including the thread being opened.+In that fallback, leave a thread open and mark it Done/Not Done from its list:+only the matching open thread refreshes through GraphQL after the committed archive+mutation, including its loaded message pages. Mark Seen/Unread and generic Soup+refreshes must not refetch open threads. Disabled/unmounted readers must not refetch.+Also delay cache initialization failure until after the first identity lookup fails:+an uncertain server route must then load and participate in archive refreshes,+while a positively identified unsynced local draft must never be sent to the server.+Keep already-resolved server aliases through that fallback. With the normalized+cache active, the shared email record updates the thread without an extra network+refresh. Neither path relies on REST thread-cache invalidation.If a saved inbox selection references an unlinked account, successfully loadinglinked accounts resets the filter to All inboxes while preserving an open or@@ -477,7 +502,23 @@ skip 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.Check Signal/Noise removal and All's done indicator, then Undo/Redo, including an-offline action followed by reconnect. Sent-only threads cannot be unarchived.+offline action followed by reconnect. Also wait for provider/metadata synchronization+before Undo, and repeat after reloading: an archived received thread can lose its+inbox-sorting timestamp but must still be unarchivable. Sent-only threads and+unsent drafts cannot be unarchived; sent mail addressed back to its sender can.+With GraphQL Soup enabled, bulk Mark Not Done settles per email: a rejected+sent-only/draft thread stays done, while successful and durably queued siblings+remain restored. Only accepted+threads get their notifications restored. Notification or list-refresh failures+warn 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,+Mark Not Done remains available for an archived thread whose inbox timestamp is+missing; the server decides whether its received-message history allows restoration.+The REST path retains its timestamp preflight, whole-batch handling, notification+ordering, and existing cache reconciliation.The service retains both replica-backed Soup reads and a primary-backed emailwriter. Email mutations and their uncached reply reloads use the primary; ordinary