Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(soup): make GraphQL Done and Undo immediate (#7391)

Sean Ayeb079530b27ce
diff --git a/apps/web/src/features/next-soup/actions/graphql-done-operation.test.ts b/apps/web/src/features/next-soup/actions/graphql-done-operation.test.ts
new file mode 100644
index 0000000000..279991cbba
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/graphql-done-operation.test.ts
@@ -0,0 +1,189 @@
+import type { EntityData } from '@entity';
+import type { UnifiedNotification } from '@notifications';
+import { authKeys } from '@queries/auth/keys';
+import { createGraphqlSoupDoneProjection } from '@queries/soup/graphql/done-projection';
+import { usePendingGraphqlSoupDone } from '@queries/soup/graphql/optimistic-done';
+import type { SoupAstItemsData } from '@queries/soup/items';
+import { QueryClient } from '@tanstack/solid-query';
+import { createMemo, createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ createGraphqlDoneOperation,
+ doneEntityKey,
+} from './graphql-done-operation';
+import { notificationReceipt } from './tests/done-write-fixture';
+
+type DoneArgs = Parameters<
+ typeof import('../utils').executeMarkEntitiesDone
+>[0];
+const writes = vi.hoisted(() => ({
+ done: vi.fn<(args: DoneArgs) => Promise<string[]>>(),
+ undone: vi.fn(),
+ notificationOverride: vi.fn(() =>
+ Object.assign(vi.fn(), { release: vi.fn() })
+ ),
+}));
+vi.mock('../utils', () => ({
+ executeMarkEntitiesDone: writes.done,
+ executeMarkEntitiesUndone: writes.undone,
+}));
+vi.mock('@queries/client', () => ({
+ get queryClient() {
+ return client;
+ },
+}));
+vi.mock('@queries/soup/graphql/active-queries', () => ({
+ refreshActiveGraphqlSoupQueries: vi.fn(async () => {}),
+}));
+vi.mock('@notifications', () => ({
+ setDoneOverride: writes.notificationOverride,
+}));
+
+let client: QueryClient;
+const cleanup: (() => void)[] = [];
+beforeEach(() => {
+ vi.useFakeTimers();
+ writes.done.mockReset();
+ writes.undone.mockReset();
+ writes.notificationOverride.mockClear();
+ client = new QueryClient();
+ client.setQueryData(authKeys.userInfo.queryKey, {
+ userId: 'viewer',
+ authenticated: true,
+ });
+});
+afterEach(() => {
+ for (const dispose of cleanup.splice(0)) dispose();
+ client.clear();
+ vi.useRealTimers();
+});
+
+const document = (id: string) =>
+ ({
+ type: 'document',
+ id,
+ name: id,
+ notifications: [
+ { id: `n-${id}`, state: 'unseen', created_at: '2020-01-01T00:00:00Z' },
+ ],
+ }) as unknown as EntityData;
+
+function setup(grouped: boolean, targets: string[]) {
+ const source: SoupAstItemsData = {
+ entities: [document('a'), document('b')],
+ groups: grouped
+ ? [
+ {
+ key: 'group',
+ label: 'Group',
+ displayOrder: 0,
+ itemIds: ['a', 'b'],
+ totalCount: 2,
+ nextCursor: null,
+ },
+ ]
+ : undefined,
+ };
+ const reply = Promise.withResolvers<UnifiedNotification[]>();
+ writes.done.mockImplementationOnce(async (args) => {
+ const rows = await reply.promise;
+ args.onWriteSettled?.({
+ kind: 'entity-notifications',
+ result: { status: 'fulfilled', value: rows },
+ });
+ return rows.map(({ id }) => id);
+ });
+ return createRoot((dispose) => {
+ const pending = usePendingGraphqlSoupDone();
+ const project = createGraphqlSoupDoneProjection();
+ const deleted = new Set<string>();
+ const visible = createMemo(
+ () => project('same-query', source, pending(), true, deleted)!
+ );
+ const entities = source.entities.filter(({ id }) => targets.includes(id));
+ const operation = createGraphqlDoneOperation({
+ entities,
+ emailIds: [],
+ notificationIds: [],
+ notificationIdsByEntity: new Map(
+ entities.map((entity) => [doneEntityKey(entity), [`n-${entity.id}`]])
+ ),
+ notificationEntities: entities.map(({ id }) => ({
+ type: 'document',
+ id,
+ })),
+ scopeChannelThreads: false,
+ });
+ cleanup.push(() => {
+ operation.releaseGraphql();
+ dispose();
+ });
+ return { operation, visible, pending, source, reply };
+ });
+}
+
+describe('no-op receipts with real GraphQL display intents', () => {
+ it.each([false, true])(
+ 'releases an unacknowledged hide without waiting for stale readers (grouped=%s)',
+ async (grouped) => {
+ const { operation, visible, pending, source, reply } = setup(grouped, [
+ 'a',
+ ]);
+ await vi.waitFor(() =>
+ expect(visible().entities.map(({ id }) => id)).toEqual(['b'])
+ );
+ const write = operation.execute();
+ reply.resolve([]);
+ await write;
+ operation.settle(); // Same success path that used to pin the unacknowledged hide.
+ await vi.waitFor(() => expect(pending()).toEqual([]));
+ expect(operation.hasAccepted()).toBe(false);
+ expect(operation.completedCount()).toBe(0);
+ expect(
+ writes.notificationOverride.mock.results[0].value
+ ).toHaveBeenCalledOnce();
+ expect(visible()).toBe(source);
+ await vi.advanceTimersByTimeAsync(120_001);
+ expect(visible()).toBe(source);
+ expect(writes.done).toHaveBeenCalledOnce();
+ expect(writes.undone).not.toHaveBeenCalled();
+ }
+ );
+
+ it.each([false, true])(
+ 'releases only the no-op sibling while accepted intent awaits acknowledgement (grouped=%s)',
+ async (grouped) => {
+ const { operation, visible, pending, source, reply } = setup(grouped, [
+ 'a',
+ 'b',
+ ]);
+ await vi.waitFor(() => expect(visible().entities).toEqual([]));
+ const write = operation.execute();
+ reply.resolve([
+ notificationReceipt('n-a', { type: 'document', id: 'a' }),
+ ]);
+ await write;
+ operation.settle();
+ await vi.waitFor(() =>
+ expect(visible().entities.map(({ id }) => id)).toEqual(['b'])
+ );
+ expect(visible().entities[0]).toBe(source.entities[1]);
+ expect(operation.completedCount()).toBe(1);
+ expect(
+ writes.notificationOverride.mock.results[0].value
+ ).not.toHaveBeenCalled();
+ expect(
+ writes.notificationOverride.mock.results[1].value
+ ).toHaveBeenCalledOnce();
+ expect(pending()).toHaveLength(1);
+ if (grouped)
+ expect(visible().groups?.[0]).toMatchObject({
+ itemIds: ['b'],
+ totalCount: 1,
+ });
+ await vi.advanceTimersByTimeAsync(120_001);
+ expect(visible().entities.map(({ id }) => id)).toEqual(['b']);
+ expect(pending()).toHaveLength(1);
+ }
+ );
+});
diff --git a/apps/web/src/features/next-soup/actions/graphql-done-operation.ts b/apps/web/src/features/next-soup/actions/graphql-done-operation.ts
new file mode 100644
index 0000000000..dbb23535e7
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/graphql-done-operation.ts
@@ -0,0 +1,291 @@
+import { scopeChannelNotificationsForEntity } from '@app/features/soup/entity-notifications';
+import type { EntityData } from '@entity';
+import { toNotificationEntity } from '@entity/utils/notification';
+import type { NotificationEntityRef } from '@queries/notification/entity-mutations';
+import { batch } from 'solid-js';
+import {
+ executeMarkEntitiesDone,
+ executeMarkEntitiesUndone,
+ type MarkDoneWriteOutcome,
+} from '../utils';
+import { applyGraphqlDoneOptimistic } from './graphql-done-optimism';
+
+export type DoneEntityKey = `${EntityData['type']}:${string}`;
+
+export function doneEntityKey(
+ entity: Pick<EntityData, 'type' | 'id'>
+): DoneEntityKey {
+ return `${entity.type}:${entity.id}`;
+}
+
+type Receipt = {
+ emailIds: string[];
+ notificationIds: string[];
+};
+type Attempt = {
+ kind: MarkDoneWriteOutcome['kind'];
+ id?: string;
+ entity?: EntityData;
+ knownNotificationIds: string[];
+ rowIds: string[];
+ state: 'pending' | 'done' | 'undone' | 'failed' | 'noop';
+ displayDone: boolean;
+ receipt?: Receipt;
+ optimistic: ReturnType<typeof applyGraphqlDoneOptimistic>;
+};
+
+type Args = {
+ entities: EntityData[];
+ emailIds: string[];
+ notificationIds: string[];
+ notificationIdsByEntity: ReadonlyMap<DoneEntityKey, string[]>;
+ notificationEntities: NotificationEntityRef[];
+ scopeChannelThreads: boolean;
+};
+
+/** Each independently persisted field owns its display intent and exact receipt. */
+export function createGraphqlDoneOperation(args: Args) {
+ const attempts: Attempt[] = [];
+ const add = (
+ kind: Attempt['kind'],
+ rowIds: string[],
+ notificationIds: string[],
+ id?: string,
+ entity?: EntityData
+ ) => {
+ attempts.push({
+ kind,
+ id,
+ entity,
+ knownNotificationIds: notificationIds,
+ rowIds,
+ state: 'pending',
+ displayDone: true,
+ optimistic: applyGraphqlDoneOptimistic({
+ entityIds: rowIds,
+ notificationIds,
+ scopeChannelThreads: args.scopeChannelThreads,
+ }),
+ });
+ };
+ batch(() => {
+ for (const id of args.emailIds) add('email', [id], [], id);
+ const selectiveIds = new Set(args.notificationIds);
+ const claimedIds = new Set<string>();
+ for (const entity of args.entities) {
+ const entityScoped = args.notificationEntities.some(
+ (ref) => ref.type === entity.type && ref.id === entity.id
+ );
+ const notificationIds = (
+ args.notificationIdsByEntity.get(doneEntityKey(entity)) ?? []
+ ).filter((id) => {
+ if (claimedIds.has(id) || (!entityScoped && !selectiveIds.has(id)))
+ return false;
+ claimedIds.add(id);
+ return true;
+ });
+ if (!entityScoped && notificationIds.length === 0) continue;
+ add(
+ entityScoped ? 'entity-notifications' : 'notifications',
+ entity.type === 'email' ? [] : [entity.id],
+ notificationIds,
+ undefined,
+ entity
+ );
+ }
+ });
+
+ const matches = (
+ attempt: Attempt,
+ outcome: MarkDoneWriteOutcome,
+ replay = false
+ ) => {
+ if (outcome.kind === 'email')
+ return attempt.kind === outcome.kind && attempt.id === outcome.id;
+ return (
+ attempt.kind === outcome.kind ||
+ (replay &&
+ outcome.kind === 'notifications' &&
+ attempt.kind === 'entity-notifications')
+ );
+ };
+ const hasAccepted = () =>
+ attempts.some((attempt) => attempt.receipt !== undefined);
+ const failInitial = (attempt: Attempt) => {
+ attempt.optimistic.rollback();
+ attempt.state = 'failed';
+ };
+ const apply = (attempt: Attempt, done: boolean) => {
+ if (attempt.displayDone === done) return;
+ if (done) attempt.optimistic.reapply();
+ else attempt.optimistic.applyUndone();
+ attempt.displayDone = done;
+ };
+ const observeInitial = (outcome: MarkDoneWriteOutcome) =>
+ batch(() => {
+ for (const attempt of attempts.filter((attempt) =>
+ matches(attempt, outcome)
+ )) {
+ if (outcome.result.status === 'rejected') {
+ failInitial(attempt);
+ continue;
+ }
+ attempt.state = 'done';
+ if (outcome.kind === 'email') {
+ attempt.receipt = {
+ emailIds: [outcome.id],
+ notificationIds: [],
+ };
+ } else {
+ let ids: string[];
+ if (outcome.kind === 'notifications') {
+ const requested = new Set(attempt.knownNotificationIds);
+ ids = outcome.result.value.filter((id) => requested.has(id));
+ } else {
+ const entity = attempt.entity;
+ const target = entity && toNotificationEntity(entity);
+ let notifications = outcome.result.value.filter(
+ (notification) =>
+ notification.entity_id === target?.id &&
+ notification.entity_type === target?.type
+ );
+ if (
+ entity &&
+ args.scopeChannelThreads &&
+ (entity.type === 'channel' || entity.type === 'channel_thread')
+ )
+ notifications = scopeChannelNotificationsForEntity(
+ entity,
+ notifications
+ );
+ ids = notifications.map(({ id }) => id);
+ }
+ if (ids.length > 0) {
+ attempt.receipt = {
+ emailIds: [],
+ notificationIds: ids,
+ };
+ } else {
+ // No matching receipt justifies neither a hide nor a restoration.
+ // Release this attempt even when Undo was never requested: a stale
+ // reader might otherwise keep the row hidden indefinitely.
+ attempt.state = 'noop';
+ attempt.optimistic.rollback();
+ }
+ }
+ }
+ });
+
+ const run = async (done: boolean) => {
+ const selected = attempts.filter(
+ (attempt) =>
+ attempt.receipt && attempt.state === (done ? 'undone' : 'done')
+ );
+ batch(() => {
+ for (const attempt of selected) apply(attempt, done);
+ });
+ if (selected.length === 0) return;
+ const pending = new Set(selected);
+ const fail = (attempt: Attempt) => {
+ apply(attempt, !done);
+ attempt.optimistic.releaseGraphql();
+ };
+ const onWriteSettled = (outcome: MarkDoneWriteOutcome) =>
+ batch(() => {
+ for (const attempt of selected.filter((attempt) =>
+ matches(attempt, outcome, true)
+ )) {
+ pending.delete(attempt);
+ if (outcome.result.status === 'rejected') fail(attempt);
+ else {
+ attempt.state = done ? 'done' : 'undone';
+ attempt.optimistic.settle(attempt.receipt?.notificationIds);
+ }
+ }
+ });
+ const receipt = {
+ emailIds: selected.flatMap((attempt) => attempt.receipt?.emailIds ?? []),
+ notificationIds: [
+ ...new Set(
+ selected.flatMap((attempt) => attempt.receipt?.notificationIds ?? [])
+ ),
+ ],
+ onWriteSettled,
+ };
+ try {
+ if (done) await executeMarkEntitiesDone(receipt);
+ else await executeMarkEntitiesUndone(receipt);
+ } finally {
+ // Failures before dispatch/reconciliation cannot leave guessed intent.
+ // Already acknowledged siblings retain their new state and are skipped
+ // when the user retries this Undo/Redo.
+ batch(() => {
+ for (const attempt of pending) fail(attempt);
+ });
+ }
+ };
+
+ return {
+ hasAccepted,
+ hasFailures: () => attempts.some(({ state }) => state === 'failed'),
+ // Ancillary notification no-ops do not undo an accepted archive.
+ hasNoopRows: () =>
+ attempts.some(
+ ({ state, rowIds }) => state === 'noop' && rowIds.length > 0
+ ),
+ completedCount: () =>
+ new Set(
+ attempts
+ .filter(({ state }) => state === 'done')
+ .flatMap(({ rowIds }) => rowIds)
+ ).size,
+ execute: async () => {
+ try {
+ await executeMarkEntitiesDone({
+ emailIds: args.emailIds,
+ notificationIds: args.notificationIds,
+ notificationEntities: args.notificationEntities,
+ onWriteSettled: observeInitial,
+ });
+ } catch (error) {
+ batch(() => {
+ for (const attempt of attempts)
+ if (attempt.state === 'pending') failInitial(attempt);
+ });
+ if (!hasAccepted()) throw error;
+ }
+ },
+ undo: () => run(false),
+ redo: () => run(true),
+ applyUndone: () =>
+ batch(() => {
+ for (const attempt of attempts)
+ if (
+ attempt.state === 'pending' ||
+ (attempt.state === 'done' && attempt.receipt)
+ )
+ apply(attempt, false);
+ }),
+ reapply: () =>
+ batch(() => {
+ for (const attempt of attempts)
+ if (attempt.state === 'undone' && attempt.receipt)
+ apply(attempt, true);
+ }),
+ settle: () =>
+ batch(() => {
+ for (const attempt of attempts)
+ if (attempt.state === 'done' && attempt.displayDone)
+ attempt.optimistic.settle(attempt.receipt?.notificationIds);
+ }),
+ rollback: () =>
+ batch(() => {
+ for (const attempt of attempts)
+ if (attempt.state === 'pending') failInitial(attempt);
+ }),
+ releaseGraphql: () =>
+ batch(() => {
+ for (const attempt of attempts) attempt.optimistic.releaseGraphql();
+ }),
+ };
+}
diff --git a/apps/web/src/features/next-soup/actions/graphql-done-optimism.ts b/apps/web/src/features/next-soup/actions/graphql-done-optimism.ts
new file mode 100644
index 0000000000..97d66a29ab
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/graphql-done-optimism.ts
@@ -0,0 +1,50 @@
+import { setDoneOverride } from '@notifications';
+import { hideGraphqlSoupEntitiesAsDone } from '@queries/soup/graphql/optimistic-done';
+import { batch } from 'solid-js';
+
+/** GraphQL display intent never reads or patches the legacy REST caches. */
+export function applyGraphqlDoneOptimistic(args: {
+ entityIds: string[];
+ notificationIds: string[];
+ scopeChannelThreads?: boolean;
+ done?: boolean;
+}) {
+ return batch(() => {
+ const { done = true, ...intentArgs } = args;
+ const intent =
+ args.entityIds.length > 0
+ ? hideGraphqlSoupEntitiesAsDone({ ...intentArgs, done })
+ : undefined;
+ let rollbackNotifications = setDoneOverride(args.notificationIds, done);
+ const notificationRollbacks = [rollbackNotifications];
+
+ const apply = (done: boolean) =>
+ batch(() => {
+ intent?.setDone(done);
+ rollbackNotifications = setDoneOverride(args.notificationIds, done);
+ notificationRollbacks.push(rollbackNotifications);
+ });
+
+ return {
+ rollback: () =>
+ batch(() => {
+ intent?.release();
+ // Initial Done can fail after an early Undo. Unwind all of this
+ // action's leases, not just Undo back to its own pending Done.
+ for (const rollback of notificationRollbacks.reverse()) rollback();
+ notificationRollbacks.length = 0;
+ }),
+ reapply: () => apply(true),
+ // The query-local projection retains admitted rows/notification witnesses
+ // for Undo; it does not need a snapshot of the REST notification feed.
+ applyUndone: () => apply(false),
+ settle: (notificationIds?: readonly string[]) =>
+ intent?.settle(notificationIds),
+ releaseGraphql: () =>
+ batch(() => {
+ intent?.release();
+ rollbackNotifications.release();
+ }),
+ };
+ });
+}
diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.pending.test.tsx b/apps/web/src/features/next-soup/actions/make-mark-done-action.pending.test.tsx
new file mode 100644
index 0000000000..516a285477
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.pending.test.tsx
@@ -0,0 +1,748 @@
+import type { EntityData } from '@entity';
+import type { NotificationSource } from '@notifications';
+import {
+ MutationUndoProvider,
+ type UndoHandle,
+ useMutationUndoContext,
+} from '@queries/undo';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ type DoneWriteArgs,
+ notificationReceipt,
+ reportDoneWriteOutcomes,
+} from './tests/done-write-fixture';
+
+const mocks = vi.hoisted(() => ({
+ graphql: true,
+ home: false,
+ notificationIdsForEntity: undefined as
+ | ((entity: EntityData) => string[])
+ | undefined,
+ done: vi.fn(async (_args: DoneWriteArgs) => [] as string[]),
+ undone: vi.fn(async (_args: DoneWriteArgs) => {}),
+ report: undefined as typeof reportDoneWriteOutcomes | undefined,
+ apply: vi.fn(() => ({
+ applyUndone: vi.fn(),
+ reapply: vi.fn(),
+ rollback: vi.fn(),
+ settle: vi.fn(),
+ releaseGraphql: vi.fn(),
+ })),
+ toast: {
+ success: vi.fn(() => 1),
+ alert: vi.fn(() => 2),
+ dismiss: vi.fn(),
+ failure: vi.fn(),
+ },
+}));
+
+vi.mock('@components/app/split-layout/layoutUtils', () => ({
+ useSplitPanel: () => ({
+ handle: {
+ content: () => ({ id: mocks.home ? 'home' : 'other' }),
+ referredFrom: () => undefined,
+ },
+ }),
+}));
+vi.mock('@core/constant/featureFlags', () => ({
+ enableGraphqlSoup: { key: 'enable-graphql-soup' },
+ isFeatureEnabled: () => mocks.graphql,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({ toast: mocks.toast }));
+vi.mock('./graphql-done-optimism', () => ({
+ applyGraphqlDoneOptimistic: mocks.apply,
+}));
+vi.mock('@queries/notification/entity-mutations', () => ({
+ toNotificationEntityRef: (entity: EntityData) => ({
+ type: entity.type,
+ id: entity.id,
+ }),
+}));
+vi.mock('@app/features/next-soup/utils', () => ({
+ applyEntitiesDoneOptimistic: mocks.apply,
+ executeMarkEntitiesDone: async (args: DoneWriteArgs) => {
+ const [result] = await Promise.allSettled([mocks.done(args)]);
+ (mocks.report ?? reportDoneWriteOutcomes)(args, result);
+ if (result.status === 'rejected') throw result.reason;
+ return result.value;
+ },
+ executeMarkEntitiesUndone: async (args: DoneWriteArgs) => {
+ const [result] = await Promise.allSettled([mocks.undone(args)]);
+ (mocks.report ?? reportDoneWriteOutcomes)(
+ args,
+ result.status === 'fulfilled'
+ ? { status: 'fulfilled', value: [] }
+ : result
+ );
+ if (result.status === 'rejected') throw result.reason;
+ },
+ resolveMarkEntitiesDoneVariables: ({
+ entities,
+ }: {
+ entities: EntityData[];
+ }) => ({
+ emailIds: entities
+ .filter(({ type }) => type === 'email')
+ .map(({ id }) => id),
+ notificationIds: mocks.notificationIdsForEntity
+ ? entities.flatMap(mocks.notificationIdsForEntity)
+ : ['locally-known-id'],
+ }),
+ restoreSoupFocus: vi.fn(async () => {}),
+}));
+
+import { makeMarkDoneAction } from './make-mark-done-action';
+
+const email = (id = 'email-1') => ({ type: 'email', id }) as EntityData;
+const cleanup: (() => void)[] = [];
+
+function mount() {
+ const client = new QueryClient({
+ defaultOptions: { mutations: { retry: false } },
+ });
+ let action!: ReturnType<typeof makeMarkDoneAction>;
+ let undo!: ReturnType<typeof useMutationUndoContext>;
+ createRoot((dispose) => {
+ cleanup.push(() => {
+ dispose();
+ client.clear();
+ });
+ const Capture = () => {
+ undo = useMutationUndoContext();
+ action = makeMarkDoneAction({
+ notificationSource: () => ({}) as NotificationSource,
+ });
+ return null;
+ };
+ return (
+ <QueryClientProvider client={client}>
+ <MutationUndoProvider>
+ <Capture />
+ </MutationUndoProvider>
+ </QueryClientProvider>
+ );
+ });
+ return { action, undo };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.graphql = true;
+ mocks.home = false;
+ mocks.notificationIdsForEntity = undefined;
+ mocks.report = undefined;
+});
+afterEach(() => {
+ for (const dispose of cleanup.splice(0)) dispose();
+});
+
+describe('pending GraphQL Done undo', () => {
+ it('registers immediately, restores locally, then reverses only the authoritative IDs', async () => {
+ const write = Promise.withResolvers<string[]>();
+ const inverse = Promise.withResolvers<void>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ mocks.undone.mockReturnValueOnce(inverse.promise);
+ const { action, undo } = mount();
+ const restoreFocus = vi.fn();
+ const navigateBack = vi.fn();
+ const done = action.execute([email()], restoreFocus, { navigateBack });
+ await vi.waitFor(() => expect(undo.canUndo()).toBe(true));
+ expect(mocks.toast.success).toHaveBeenCalledOnce();
+ const context = mocks.apply.mock.results[0].value;
+
+ const reversal = undo.undo();
+ expect(context.applyUndone).toHaveBeenCalledOnce();
+ expect(restoreFocus).toHaveBeenCalledOnce();
+ expect(navigateBack).toHaveBeenCalledOnce();
+ expect(mocks.toast.dismiss).toHaveBeenCalledWith(1);
+ expect(mocks.undone).not.toHaveBeenCalled();
+ expect(context.settle).not.toHaveBeenCalled();
+
+ write.resolve(['authoritative-id']);
+ await done;
+ await vi.waitFor(() =>
+ expect(mocks.undone).toHaveBeenCalledWith({
+ emailIds: ['email-1'],
+ notificationIds: ['authoritative-id'],
+ onWriteSettled: expect.any(Function),
+ })
+ );
+ // Done's late success cannot acknowledge the pending Undo display intent.
+ expect(context.settle).not.toHaveBeenCalled();
+ expect(mocks.toast.success).toHaveBeenCalledOnce();
+ inverse.resolve();
+ await reversal;
+ expect(context.settle).toHaveBeenCalledExactlyOnceWith([]);
+ expect(
+ mocks.apply.mock.results[1].value.settle
+ ).toHaveBeenCalledExactlyOnceWith(['authoritative-id']);
+ expect(undo.canRedo()).toBe(true);
+ await undo.redo();
+ expect(mocks.done).toHaveBeenLastCalledWith({
+ emailIds: ['email-1'],
+ notificationIds: ['authoritative-id'],
+ onWriteSettled: expect.any(Function),
+ });
+ });
+
+ it.each([false, true])(
+ 'discards failed Done history, including an in-flight Undo (undo=%s)',
+ async (requestUndo) => {
+ const write = Promise.withResolvers<string[]>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ const { action, undo } = mount();
+ const done = action.execute([email()]);
+ const failed = expect(done).rejects.toThrow('rejected');
+ await vi.waitFor(() => expect(undo.canUndo()).toBe(true));
+ const reversal = requestUndo ? undo.undo() : Promise.resolve();
+ write.reject(new Error('rejected'));
+ await failed;
+ await reversal;
+ expect(mocks.apply.mock.results[0].value.rollback).toHaveBeenCalledOnce();
+ expect(mocks.undone).not.toHaveBeenCalled();
+ expect(undo.canUndo()).toBe(false);
+ expect(undo.canRedo()).toBe(false);
+ expect(mocks.toast.dismiss).toHaveBeenCalledWith(1);
+ expect(mocks.toast.failure).toHaveBeenCalledExactlyOnceWith(
+ 'Failed to mark as done'
+ );
+ }
+ );
+
+ it('keeps a failed reversal retryable without pinning guessed GraphQL state', async () => {
+ const write = Promise.withResolvers<string[]>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ mocks.undone.mockRejectedValueOnce(new Error('inverse failed'));
+ const { action, undo } = mount();
+ const done = action.execute([email()]);
+ await vi.waitFor(() => expect(undo.canUndo()).toBe(true));
+ const onError = vi.fn();
+ const reversal = undo.undo({ onError });
+ write.resolve(['exact']);
+ await done;
+ await reversal;
+ const context = mocks.apply.mock.results[0].value;
+ expect(context.reapply).toHaveBeenCalledOnce();
+ expect(context.releaseGraphql).toHaveBeenCalledOnce();
+ expect(context.settle).not.toHaveBeenCalled();
+ expect(onError).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'inverse failed' })
+ );
+ expect(undo.canUndo()).toBe(true);
+ expect(undo.canRedo()).toBe(false);
+ await undo.undo();
+ expect(mocks.undone).toHaveBeenLastCalledWith({
+ emailIds: ['email-1'],
+ notificationIds: ['exact'],
+ onWriteSettled: expect.any(Function),
+ });
+ });
+
+ it('does not register a second entry when a disposed pending Done succeeds', async () => {
+ const write = Promise.withResolvers<string[]>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ const { action, undo } = mount();
+ let handle!: UndoHandle;
+ const done = action.execute([email()], undefined, {
+ onUndoHandle: (value) => {
+ handle = value;
+ },
+ });
+ await vi.waitFor(() => expect(handle).toBeDefined());
+ handle.dispose();
+ write.resolve(['exact']);
+ await done;
+ expect(undo.canUndo()).toBe(false);
+ expect(undo.canRedo()).toBe(false);
+ });
+
+ it('isolates concurrent actions and cannot borrow a sibling reply for Undo', async () => {
+ const first = Promise.withResolvers<string[]>();
+ const second = Promise.withResolvers<string[]>();
+ mocks.done
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const { action, undo } = mount();
+ let firstHandle!: UndoHandle;
+ const doneFirst = action.execute([email('first')], undefined, {
+ onUndoHandle: (handle) => {
+ firstHandle = handle;
+ },
+ });
+ await vi.waitFor(() => expect(firstHandle).toBeDefined());
+ const reversal = firstHandle.undo();
+ const doneSecond = action.execute([email('second')]);
+ await vi.waitFor(() => expect(mocks.done).toHaveBeenCalledTimes(2));
+ second.resolve(['second-exact']);
+ await doneSecond;
+ expect(mocks.undone).not.toHaveBeenCalled();
+ first.resolve(['first-exact']);
+ await doneFirst;
+ await reversal;
+ expect(mocks.undone).toHaveBeenCalledExactlyOnceWith({
+ emailIds: ['first'],
+ notificationIds: ['first-exact'],
+ onWriteSettled: expect.any(Function),
+ });
+ expect(undo.canUndo()).toBe(true);
+ // The second action cleared redo history while the first Undo was pending.
+ expect(undo.canRedo()).toBe(false);
+ });
+
+ it.each([false, true])(
+ 'preserves a queued archive and undoes only it when siblings fail (early=%s)',
+ async (early) => {
+ const write = Promise.withResolvers<string[]>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ mocks.report = (args, result) => {
+ if (!args.notificationEntities)
+ return reportDoneWriteOutcomes(args, result);
+ args.onWriteSettled?.({
+ kind: 'email',
+ id: 'accepted',
+ result: { status: 'fulfilled', value: 'queued' },
+ });
+ args.onWriteSettled?.({
+ kind: 'email',
+ id: 'rejected',
+ result: { status: 'rejected', reason: new Error('archive rejected') },
+ });
+ args.onWriteSettled?.({
+ kind: 'entity-notifications',
+ result: {
+ status: 'rejected',
+ reason: new Error('notification rejected'),
+ },
+ });
+ };
+ const { action, undo } = mount();
+ const done = action.execute([email('accepted'), email('rejected')]);
+ await vi.waitFor(() => expect(undo.canUndo()).toBe(true));
+ const reversal = early ? undo.undo() : undefined;
+ write.reject(new Error('partial failure'));
+ await done;
+ const accepted = mocks.apply.mock.results[0].value;
+ const rejected = mocks.apply.mock.results[1].value;
+ expect(accepted.rollback).not.toHaveBeenCalled();
+ expect(rejected.rollback).toHaveBeenCalledOnce();
+ expect(mocks.toast.alert).toHaveBeenCalled();
+ if (early) await reversal;
+ else await undo.undo();
+ expect(mocks.undone).toHaveBeenCalledExactlyOnceWith({
+ emailIds: ['accepted'],
+ notificationIds: [],
+ onWriteSettled: expect.any(Function),
+ });
+ expect(undo.canRedo()).toBe(true);
+ await undo.redo();
+ expect(mocks.done).toHaveBeenLastCalledWith({
+ emailIds: ['accepted'],
+ notificationIds: [],
+ onWriteSettled: expect.any(Function),
+ });
+ expect(rejected.reapply).not.toHaveBeenCalled();
+ }
+ );
+
+ it('rolls back no-op notification overrides when the archive fails and nothing was accepted', async () => {
+ mocks.done.mockRejectedValueOnce(new Error('archive rejected'));
+ mocks.report = (args) => {
+ args.onWriteSettled?.({
+ kind: 'email',
+ id: 'email-1',
+ result: { status: 'rejected', reason: new Error('archive rejected') },
+ });
+ args.onWriteSettled?.({
+ kind: 'entity-notifications',
+ result: { status: 'fulfilled', value: [] },
+ });
+ };
+ const { action, undo } = mount();
+ await expect(action.execute([email()])).rejects.toThrow('archive rejected');
+ expect(mocks.apply.mock.results[0].value.rollback).toHaveBeenCalledOnce();
+ expect(mocks.apply.mock.results[1].value.rollback).toHaveBeenCalledOnce();
+ expect(undo.canUndo()).toBe(false);
+ expect(undo.canRedo()).toBe(false);
+ });
+
+ it('retains exact notification receipts when the archive fails', async () => {
+ mocks.done.mockRejectedValueOnce(new Error('archive rejected'));
+ mocks.report = (args, result) => {
+ if (!args.notificationEntities)
+ return reportDoneWriteOutcomes(args, result);
+ args.onWriteSettled?.({
+ kind: 'email',
+ id: 'email-1',
+ result: { status: 'rejected', reason: new Error('archive rejected') },
+ });
+ args.onWriteSettled?.({
+ kind: 'entity-notifications',
+ result: {
+ status: 'fulfilled',
+ value: [
+ notificationReceipt('changed-on-server', {
+ type: 'email',
+ id: 'email-1',
+ }),
+ ],
+ },
+ });
+ };
+ const { action, undo } = mount();
+ await action.execute([email()]);
+ expect(undo.canUndo()).toBe(true);
+ expect(mocks.apply.mock.results[0].value.rollback).toHaveBeenCalledOnce();
+ expect(mocks.apply.mock.results[1].value.rollback).not.toHaveBeenCalled();
+ await undo.undo();
+ expect(mocks.undone).toHaveBeenCalledExactlyOnceWith({
+ emailIds: [],
+ notificationIds: ['changed-on-server'],
+ onWriteSettled: expect.any(Function),
+ });
+ await undo.redo();
+ expect(mocks.done).toHaveBeenLastCalledWith({
+ emailIds: [],
+ notificationIds: ['changed-on-server'],
+ onWriteSettled: expect.any(Function),
+ });
+ });
+
+ it('isolates archive failure from accepted email and document writes', async () => {
+ mocks.done.mockRejectedValueOnce(new Error('archive rejected'));
+ mocks.report = (args, result) => {
+ if (!args.notificationEntities)
+ return reportDoneWriteOutcomes(args, result);
+ args.onWriteSettled?.({
+ kind: 'email',
+ id: 'email-1',
+ result: { status: 'fulfilled', value: 'committed' },
+ });
+ args.onWriteSettled?.({
+ kind: 'email',
+ id: 'rejected-email',
+ result: { status: 'rejected', reason: new Error('archive rejected') },
+ });
+ args.onWriteSettled?.({
+ kind: 'entity-notifications',
+ result: {
+ status: 'fulfilled',
+ value: [
+ notificationReceipt('doc-exact', {
+ type: 'document',
+ id: 'document-1',
+ }),
+ ],
+ },
+ });
+ };
+ const { action, undo } = mount();
+ await action.execute([
+ email(),
+ email('rejected-email'),
+ { type: 'document', id: 'document-1' } as EntityData,
+ ]);
+ await undo.undo();
+ expect(mocks.undone).toHaveBeenCalledExactlyOnceWith({
+ emailIds: ['email-1'],
+ notificationIds: ['doc-exact'],
+ onWriteSettled: expect.any(Function),
+ });
+ expect(mocks.apply.mock.results[1].value.rollback).toHaveBeenCalledOnce();
+ expect(mocks.apply.mock.results[0].value.rollback).not.toHaveBeenCalled();
+ // Both email notification writes were no-ops; only the document
+ // notification attempt has an accepted receipt.
+ expect(mocks.apply.mock.results[2].value.rollback).toHaveBeenCalledOnce();
+ expect(mocks.apply.mock.results[3].value.rollback).toHaveBeenCalledOnce();
+ expect(mocks.apply.mock.results[4].value.rollback).not.toHaveBeenCalled();
+ });
+
+ it.each(['undo', 'redo'] as const)(
+ 'retries only failed %s writes, not already accepted siblings',
+ async (direction) => {
+ const { action, undo } = mount();
+ await action.execute([email('accepted'), email('retry')]);
+ if (direction === 'redo') await undo.undo();
+ const writer = direction === 'undo' ? mocks.undone : mocks.done;
+ writer.mockRejectedValueOnce(new Error('partial inverse failure'));
+ mocks.report = (args) => {
+ args.onWriteSettled?.({
+ kind: 'email',
+ id: 'accepted',
+ result: { status: 'fulfilled', value: 'committed' },
+ });
+ args.onWriteSettled?.({
+ kind: 'email',
+ id: 'retry',
+ result: { status: 'rejected', reason: new Error('retry this write') },
+ });
+ };
+ const onError = vi.fn();
+ await undo[direction]({ onError });
+ expect(onError).toHaveBeenCalledOnce();
+ mocks.report = undefined;
+ writer.mockClear();
+ await undo[direction]();
+ expect(writer).toHaveBeenCalledExactlyOnceWith({
+ emailIds: ['retry'],
+ notificationIds: [],
+ onWriteSettled: expect.any(Function),
+ });
+ }
+ );
+
+ it.each(['empty', 'unmatched'] as const)(
+ 'releases a %s receipt instead of pinning the hide after discarding Undo',
+ async (receipt) => {
+ mocks.report = (args) =>
+ args.onWriteSettled?.({
+ kind: 'entity-notifications',
+ result: {
+ status: 'fulfilled',
+ value:
+ receipt === 'empty'
+ ? []
+ : [
+ notificationReceipt('unrelated', {
+ type: 'document',
+ id: 'other-document',
+ }),
+ ],
+ },
+ });
+ const { action, undo } = mount();
+ await action.execute([
+ { type: 'document', id: 'document-1' } as EntityData,
+ ]);
+ const optimistic = mocks.apply.mock.results[0].value;
+ expect(optimistic.rollback).toHaveBeenCalledOnce();
+ expect(optimistic.settle).not.toHaveBeenCalled();
+ expect(undo.canUndo()).toBe(false);
+ expect(undo.canRedo()).toBe(false);
+ expect(mocks.toast.dismiss).toHaveBeenCalledWith(1);
+ }
+ );
+
+ it('keeps notification snapshots separate for different entity types sharing an id', async () => {
+ mocks.notificationIdsForEntity = (entity) => [
+ `${entity.type}-notification`,
+ ];
+ const { action } = mount();
+ await action.execute([
+ email('same-id'),
+ { type: 'document', id: 'same-id' } as EntityData,
+ ]);
+ expect(mocks.apply).toHaveBeenNthCalledWith(2, {
+ entityIds: [],
+ notificationIds: ['email-notification'],
+ scopeChannelThreads: false,
+ });
+ expect(mocks.apply).toHaveBeenNthCalledWith(3, {
+ entityIds: ['same-id'],
+ notificationIds: ['document-notification'],
+ scopeChannelThreads: false,
+ });
+ });
+
+ it('never guesses notification IDs when an early Undo receives a no-op reply', async () => {
+ const write = Promise.withResolvers<string[]>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ const { action, undo } = mount();
+ const done = action.execute([
+ { type: 'document', id: 'document-1' } as EntityData,
+ ]);
+ await vi.waitFor(() => expect(undo.canUndo()).toBe(true));
+ const reversal = undo.undo();
+ write.resolve([]);
+ await done;
+ await reversal;
+ expect(mocks.undone).not.toHaveBeenCalled();
+ expect(undo.canUndo()).toBe(false);
+ expect(undo.canRedo()).toBe(false);
+ expect(mocks.apply.mock.results[0].value.rollback).toHaveBeenCalledOnce();
+ });
+
+ it('reports mixed no-op results accurately without restoring or redoing the no-op row', async () => {
+ const write = Promise.withResolvers<string[]>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ const { action, undo } = mount();
+ const done = action.execute([
+ { type: 'document', id: 'changed-doc' } as EntityData,
+ { type: 'document', id: 'unchanged-doc' } as EntityData,
+ ]);
+ await vi.waitFor(() => expect(undo.canUndo()).toBe(true));
+ expect(mocks.toast.success).toHaveBeenCalledExactlyOnceWith(
+ 'Marked 2 items as done',
+ expect.any(Object)
+ );
+ expect(mocks.toast.alert).not.toHaveBeenCalled();
+ write.resolve(['changed']);
+ await done;
+ expect(mocks.toast.dismiss).toHaveBeenCalledWith(1);
+ expect(mocks.toast.alert).toHaveBeenCalledExactlyOnceWith(
+ 'Marked 1 of 2 items as done',
+ expect.objectContaining({
+ actions: [expect.objectContaining({ label: 'Undo' })],
+ })
+ );
+ await undo.undo();
+ const changed = mocks.apply.mock.results[0].value;
+ const unchanged = mocks.apply.mock.results[1].value;
+ expect(unchanged.rollback).toHaveBeenCalledOnce();
+ expect(unchanged.settle).not.toHaveBeenCalled();
+ expect(changed.rollback).not.toHaveBeenCalled();
+ expect(changed.applyUndone).toHaveBeenCalledOnce();
+ expect(unchanged.applyUndone).not.toHaveBeenCalled();
+ await undo.redo();
+ expect(changed.reapply).toHaveBeenCalledOnce();
+ expect(unchanged.reapply).not.toHaveBeenCalled();
+ expect(mocks.toast.alert).toHaveBeenCalledTimes(2);
+ expect(mocks.toast.alert).toHaveBeenLastCalledWith(
+ 'Marked 1 of 2 items as done',
+ expect.any(Object)
+ );
+ expect(mocks.done).toHaveBeenLastCalledWith({
+ emailIds: [],
+ notificationIds: ['changed'],
+ onWriteSettled: expect.any(Function),
+ });
+ });
+
+ it('does not announce late Done/no-op counts after the user already requested Undo', async () => {
+ const write = Promise.withResolvers<string[]>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ const { action, undo } = mount();
+ const done = action.execute([
+ { type: 'document', id: 'changed' } as EntityData,
+ { type: 'document', id: 'unchanged' } as EntityData,
+ ]);
+ await vi.waitFor(() => expect(undo.canUndo()).toBe(true));
+ const reversal = undo.undo();
+ write.resolve(['exact']);
+ await done;
+ await reversal;
+ expect(mocks.toast.success).toHaveBeenCalledOnce();
+ expect(mocks.toast.alert).not.toHaveBeenCalled();
+ expect(undo.canRedo()).toBe(true);
+ });
+
+ it('does not report partial success when only an archived email\u2019s notifications are a no-op', async () => {
+ const { action, undo } = mount();
+ await action.execute([email('accepted')]);
+ expect(mocks.toast.success).toHaveBeenCalledExactlyOnceWith(
+ 'Marked as done',
+ expect.any(Object)
+ );
+ expect(mocks.toast.alert).not.toHaveBeenCalled();
+ expect(mocks.toast.dismiss).not.toHaveBeenCalled();
+ expect(undo.canUndo()).toBe(true);
+ });
+
+ it('matches thread receipts by their thread, not just their shared channel', async () => {
+ mocks.home = true;
+ mocks.report = (args, result) => {
+ if (!args.notificationEntities)
+ return reportDoneWriteOutcomes(args, result);
+ const notification = notificationReceipt('thread-exact', {
+ type: 'channel',
+ id: 'shared-channel',
+ });
+ notification.notification_metadata = {
+ tag: 'channel_message_reply',
+ content: { threadId: 'root-a', messageId: 'reply-a' },
+ } as typeof notification.notification_metadata;
+ args.onWriteSettled?.({
+ kind: 'entity-notifications',
+ result: { status: 'fulfilled', value: [notification] },
+ });
+ };
+ const { action, undo } = mount();
+ await action.execute([
+ {
+ type: 'channel_thread',
+ id: 'row-a',
+ channelId: 'shared-channel',
+ messageId: 'root-a',
+ } as EntityData,
+ {
+ type: 'channel_thread',
+ id: 'row-b',
+ channelId: 'shared-channel',
+ messageId: 'root-b',
+ } as EntityData,
+ ]);
+ await undo.undo();
+ expect(
+ mocks.apply.mock.results[0].value.applyUndone
+ ).toHaveBeenCalledOnce();
+ expect(
+ mocks.apply.mock.results[1].value.applyUndone
+ ).not.toHaveBeenCalled();
+ expect(mocks.undone).toHaveBeenCalledExactlyOnceWith({
+ emailIds: [],
+ notificationIds: ['thread-exact'],
+ onWriteSettled: expect.any(Function),
+ });
+ });
+
+ it('does not re-show a disposed action when partial outcomes arrive', async () => {
+ const write = Promise.withResolvers<string[]>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ mocks.report = (args) => {
+ args.onWriteSettled?.({
+ kind: 'email',
+ id: 'email-1',
+ result: { status: 'fulfilled', value: 'committed' },
+ });
+ args.onWriteSettled?.({
+ kind: 'entity-notifications',
+ result: { status: 'rejected', reason: new Error('failed') },
+ });
+ };
+ const { action, undo } = mount();
+ let handle!: UndoHandle;
+ const done = action.execute([email()], undefined, {
+ onUndoHandle: (value) => {
+ handle = value;
+ },
+ });
+ await vi.waitFor(() => expect(handle).toBeDefined());
+ handle.dispose();
+ write.reject(new Error('partial failure'));
+ await done;
+ expect(undo.canUndo()).toBe(false);
+ expect(mocks.toast.success).toHaveBeenCalledOnce();
+ expect(mocks.toast.alert).not.toHaveBeenCalled();
+ });
+
+ it('deduplicates repeated group occurrences before writing', async () => {
+ const { action } = mount();
+ await action.execute([email(), email()]);
+ expect(mocks.done).toHaveBeenCalledWith(
+ expect.objectContaining({
+ emailIds: ['email-1'],
+ notificationEntities: [{ type: 'email', id: 'email-1' }],
+ })
+ );
+ });
+
+ it('retains success-only registration for REST', async () => {
+ mocks.graphql = false;
+ const write = Promise.withResolvers<string[]>();
+ mocks.done.mockReturnValueOnce(write.promise);
+ const { action, undo } = mount();
+ const done = action.execute([email()]);
+ await vi.waitFor(() => expect(mocks.done).toHaveBeenCalledOnce());
+ expect(undo.canUndo()).toBe(false);
+ expect(mocks.toast.success).not.toHaveBeenCalled();
+ write.resolve([]);
+ await done;
+ expect(undo.canUndo()).toBe(true);
+ await undo.undo();
+ expect(mocks.undone).toHaveBeenCalledWith({
+ emailIds: ['email-1'],
+ notificationIds: ['locally-known-id'],
+ });
+ });
+});
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.ts
index 91e3896c23..5ab2fa7015 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
@@ -3,14 +3,20 @@ import type { NotificationSource } from '@notifications';
import { createRoot } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { SoupState } from '../create-soup-state';
+import {
+ type DoneWriteArgs,
+ reportDoneWriteOutcomes,
+} from './tests/done-write-fixture';
const mocks = vi.hoisted(() => ({
splitHandle: {
content: vi.fn(() => ({ id: 'other' })),
referredFrom: vi.fn(() => undefined),
},
- executeMarkEntitiesDone: vi.fn(async () => [] as string[]),
- executeMarkEntitiesUndone: vi.fn(async () => {}),
+ executeMarkEntitiesDone: vi.fn(
+ async (_args: DoneWriteArgs) => [] as string[]
+ ),
+ executeMarkEntitiesUndone: vi.fn(async (_args: DoneWriteArgs) => {}),
graphqlSoupEnabled: vi.fn(() => false),
mutateAsync: vi.fn(async (_variables: unknown) => {}),
openEntityInSplitFromUnifiedList: vi.fn(async () => {}),
@@ -19,7 +25,22 @@ const mocks = vi.hoisted(() => ({
notificationIds: [] as string[],
})),
toNotificationEntityRef: vi.fn(),
- undoableOptionsFactory: vi.fn(),
+ mutationOptionsFactory: vi.fn(),
+ pushUndo: vi.fn(
+ (_entry: {
+ undo: () => Promise<void>;
+ redo: () => Promise<void>;
+ onUndone?: () => void;
+ onRedone?: () => void;
+ }) => ({ id: 'undo', undo: vi.fn(async () => {}), dispose: vi.fn() })
+ ),
+ applyOptimistic: vi.fn(() => ({
+ applyUndone: vi.fn(),
+ reapply: vi.fn(),
+ rollback: vi.fn(),
+ settle: vi.fn(),
+ releaseGraphql: vi.fn(),
+ })),
}));
vi.mock('@components/app/split-layout/layoutUtils', () => ({
@@ -41,6 +62,7 @@ vi.mock('@core/component/Toast/Toast', () => ({
dismiss: vi.fn(),
failure: vi.fn(),
success: vi.fn(),
+ alert: vi.fn(),
},
}));
@@ -49,17 +71,42 @@ vi.mock('@queries/notification/entity-mutations', () => ({
updateNotificationsForEntities: vi.fn(),
}));
+vi.mock('./graphql-done-optimism', () => ({
+ applyGraphqlDoneOptimistic: mocks.applyOptimistic,
+}));
+
vi.mock('@queries/undo', () => ({
- useUndoableMutation: (optionsFactory: () => unknown) => {
- mocks.undoableOptionsFactory.mockImplementation(optionsFactory);
+ useMutationUndoContext: () => ({ pushUndo: mocks.pushUndo }),
+}));
+vi.mock('@tanstack/solid-query', () => ({
+ useMutation: (optionsFactory: () => unknown) => {
+ mocks.mutationOptionsFactory.mockImplementation(optionsFactory);
return { mutateAsync: mocks.mutateAsync };
},
}));
vi.mock('@app/features/next-soup/utils', () => ({
- applyEntitiesDoneOptimistic: vi.fn(),
- executeMarkEntitiesDone: mocks.executeMarkEntitiesDone,
- executeMarkEntitiesUndone: mocks.executeMarkEntitiesUndone,
+ applyEntitiesDoneOptimistic: mocks.applyOptimistic,
+ executeMarkEntitiesDone: async (args: DoneWriteArgs) => {
+ const [result] = await Promise.allSettled([
+ mocks.executeMarkEntitiesDone(args),
+ ]);
+ reportDoneWriteOutcomes(args, result);
+ if (result.status === 'rejected') throw result.reason;
+ return result.value;
+ },
+ executeMarkEntitiesUndone: async (args: DoneWriteArgs) => {
+ const [result] = await Promise.allSettled([
+ mocks.executeMarkEntitiesUndone(args),
+ ]);
+ reportDoneWriteOutcomes(
+ args,
+ result.status === 'fulfilled'
+ ? { status: 'fulfilled', value: [] }
+ : result
+ );
+ if (result.status === 'rejected') throw result.reason;
+ },
openEntityInSplitFromUnifiedList: mocks.openEntityInSplitFromUnifiedList,
resolveMarkEntitiesDoneVariables: mocks.resolveMarkEntitiesDoneVariables,
restoreSoupFocus: vi.fn(),
@@ -149,6 +196,8 @@ describe('makeMarkDoneAction', () => {
mocks.graphqlSoupEnabled.mockReturnValue(false);
mocks.mutateAsync.mockReset();
mocks.mutateAsync.mockResolvedValue(undefined);
+ mocks.pushUndo.mockClear();
+ mocks.applyOptimistic.mockClear();
mocks.openEntityInSplitFromUnifiedList.mockClear();
mocks.resolveMarkEntitiesDoneVariables.mockReset();
mocks.resolveMarkEntitiesDoneVariables.mockReturnValue({
@@ -357,9 +406,19 @@ describe('makeMarkDoneAction', () => {
settle: vi.fn(),
releaseGraphql: vi.fn(),
};
- const options = mocks.undoableOptionsFactory() as {
- undoFn: (input: typeof variables, ctx: typeof context) => Promise<void>;
+ const options = mocks.mutationOptionsFactory() as {
+ onSuccess: (
+ data: void,
+ input: typeof variables & { entities: EntityData[] },
+ ctx: typeof context
+ ) => void;
};
+ options.onSuccess(
+ undefined,
+ { ...variables, entities: [currentEntity] },
+ context
+ );
+ context.settle.mockClear();
let finish!: () => void;
mocks.executeMarkEntitiesUndone.mockImplementationOnce(
() =>
@@ -367,7 +426,7 @@ describe('makeMarkDoneAction', () => {
finish = resolve;
})
);
- const undo = options.undoFn(variables, context);
+ const undo = mocks.pushUndo.mock.calls[0][0].undo();
expect(context.applyUndone).toHaveBeenCalledOnce();
expect(context.settle).not.toHaveBeenCalled();
finish();
@@ -388,13 +447,23 @@ describe('makeMarkDoneAction', () => {
settle: vi.fn(),
releaseGraphql: vi.fn(),
};
- const options = mocks.undoableOptionsFactory() as {
- undoFn: (input: typeof variables, ctx: typeof context) => Promise<void>;
+ const options = mocks.mutationOptionsFactory() as {
+ onSuccess: (
+ data: void,
+ input: typeof variables & { entities: EntityData[] },
+ ctx: typeof context
+ ) => void;
};
+ options.onSuccess(
+ undefined,
+ { ...variables, entities: [currentEntity] },
+ context
+ );
+ context.settle.mockClear();
mocks.executeMarkEntitiesUndone.mockRejectedValueOnce(
new Error('partial failure')
);
- await expect(options.undoFn(variables, context)).rejects.toThrow(
+ await expect(mocks.pushUndo.mock.calls[0][0].undo()).rejects.toThrow(
'partial failure'
);
expect(context.reapply).toHaveBeenCalledOnce();
@@ -423,33 +492,41 @@ describe('makeMarkDoneAction', () => {
exactNotificationIds: { current: string[] };
notificationEntities: Array<{ type: string; id: string }>;
};
- const mutationOptions = mocks.undoableOptionsFactory() as {
+ const mutationOptions = mocks.mutationOptionsFactory() as {
+ onMutate: (
+ input: typeof variables
+ ) => ReturnType<typeof mocks.applyOptimistic>;
mutationFn: (input: typeof variables) => Promise<void>;
- redoFn: (input: typeof variables, context: undefined) => Promise<void>;
- undoFn: (input: typeof variables, context: undefined) => Promise<void>;
+ onSuccess: (
+ data: void,
+ input: typeof variables,
+ context: ReturnType<typeof mocks.applyOptimistic>
+ ) => void;
};
+ const context = mutationOptions.onMutate(variables);
await mutationOptions.mutationFn(variables);
+ mutationOptions.onSuccess(undefined, variables, context);
expect(mocks.executeMarkEntitiesDone).toHaveBeenCalledWith({
emailIds: ['current'],
notificationIds: [],
notificationEntities: [{ type: 'email', id: 'current' }],
+ onWriteSettled: expect.any(Function),
});
- expect(variables.exactNotificationIds.current).toEqual([
- 'authoritative-notification',
- ]);
- await mutationOptions.undoFn(variables, undefined);
+ await mocks.pushUndo.mock.calls[0][0].undo();
expect(mocks.executeMarkEntitiesUndone).toHaveBeenCalledWith({
emailIds: ['current'],
notificationIds: ['authoritative-notification'],
+ onWriteSettled: expect.any(Function),
});
mocks.executeMarkEntitiesDone.mockClear();
- await mutationOptions.redoFn(variables, undefined);
+ await mocks.pushUndo.mock.calls[0][0].redo();
expect(mocks.executeMarkEntitiesDone).toHaveBeenCalledWith({
emailIds: ['current'],
notificationIds: ['authoritative-notification'],
+ onWriteSettled: expect.any(Function),
});
dispose();
});
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.ts
index 94bc855259..1420da235a 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
@@ -21,11 +21,17 @@ import {
type NotificationEntityRef,
toNotificationEntityRef,
} from '@queries/notification/entity-mutations';
-import { type UndoHandle, useUndoableMutation } from '@queries/undo';
+import { type UndoHandle, useMutationUndoContext } from '@queries/undo';
+import { useMutation } from '@tanstack/solid-query';
import type {
EntityActionListState,
EntityActionNavigationHandler,
} from './entity-action-context';
+import {
+ createGraphqlDoneOperation,
+ type DoneEntityKey,
+ doneEntityKey,
+} from './graphql-done-operation';
// Valid list views where the mark done should be allowed to run
const VALID_MARK_DONE_LIST_VIEWS: `${ListView}-${string}`[] = [
@@ -62,10 +68,14 @@ type MakeMarkDoneOptions = {
};
type MarkDoneVariables = {
+ /** Snapshot the transport when this action starts, not when its reply lands. */
+ earlyUndo: boolean;
+ operation?: ReturnType<typeof createGraphqlDoneOperation>;
entities: EntityData[];
emailIds: string[];
/** Locally known IDs used only for the immediate optimistic cache patch. */
optimisticNotificationIds: string[];
+ notificationIdsByEntity: ReadonlyMap<DoneEntityKey, string[]>;
scopeChannelThreads: boolean;
/** Exact IDs used by undo/redo; entity mutation results are appended here. */
exactNotificationIds: { current: string[] };
@@ -93,6 +103,30 @@ type MarkDoneExecuteWithSoupOpts = MarkDoneExecuteOpts & {
nextEntityId?: string;
};
+type PendingDoneUndo = {
+ requested: boolean;
+ result: Promise<boolean>;
+ finish: (accepted: boolean) => void;
+};
+
+function createPendingDoneUndo(): PendingDoneUndo {
+ let finish!: PendingDoneUndo['finish'];
+ const result = new Promise<boolean>((resolve) => {
+ finish = resolve;
+ });
+ return { requested: false, result, finish };
+}
+
+type MarkDoneContext = MarkEntitiesDoneContext & {
+ operation?: ReturnType<typeof createGraphqlDoneOperation>;
+ pendingUndo?: PendingDoneUndo;
+ registration?: {
+ handle: UndoHandle;
+ dismiss: () => void;
+ showToast: () => void;
+ };
+};
+
/** Must be invoked inside a component tree that provides MutationUndoProvider. */
export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
const splitPanel = useSplitPanel();
@@ -109,110 +143,191 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
splitPanel?.handle.referredFrom() === 'home';
const { notificationSource, hotkeyGroup } = options;
- const mutation = useUndoableMutation<
- void,
- Error,
- MarkDoneVariables,
- MarkEntitiesDoneContext
- >(() => ({
- hotkeyGroup,
- onMutate: (variables) =>
- applyEntitiesDoneOptimistic({
- entityIds: variables.entities.map((entity) => entity.id),
- emailIds: variables.emailIds,
- notificationIds: variables.optimisticNotificationIds,
- scopeChannelThreads: variables.scopeChannelThreads,
- }),
- mutationFn: async (variables) => {
- const authoritativeNotificationIds = await executeMarkEntitiesDone({
- emailIds: variables.emailIds,
- notificationIds: variables.exactNotificationIds.current,
- notificationEntities: variables.notificationEntities,
+ const { pushUndo } = useMutationUndoContext();
+
+ const registerUndo = (
+ variables: MarkDoneVariables,
+ context: MarkDoneContext
+ ) => {
+ const firstEntityId = variables.entities[0]?.id;
+ let toastId: number | undefined;
+ let disposed = false;
+ const dismiss = () => {
+ if (toastId !== undefined) toast.dismiss(toastId);
+ };
+ const restoreFocus = () => {
+ dismiss();
+ variables.restoreFocus?.();
+ void restoreSoupFocus(firstEntityId);
+ variables.navigateBack?.();
+ };
+ const showToast = () => {
+ if (variables.silent || disposed) return;
+ const total = variables.entities.length;
+ const failed = context.operation?.hasFailures();
+ const partial = failed || context.operation?.hasNoopRows();
+ const message = partial
+ ? `Marked ${context.operation?.completedCount()} of ${total} items as done${failed ? '. Some changes could not be saved.' : ''}`
+ : total > 1
+ ? `Marked ${total} items as done`
+ : 'Marked as done';
+ toastId = (partial ? toast.alert : toast.success)(message, {
+ actions: [
+ {
+ label: 'Undo',
+ icon: ArrowCounterClockwise,
+ onClick: () => {
+ void handle.undo({
+ onError: () => toast.failure('Failed to undo'),
+ });
+ },
+ },
+ ],
+ duration: 3_000,
+ stack: true,
+ hideOnMobile: true,
});
- variables.exactNotificationIds.current = [
- ...new Set([
- ...variables.exactNotificationIds.current,
- ...authoritativeNotificationIds,
- ]),
- ];
- },
- onSuccess: (_data, variables, context) => {
- context?.settle(variables.exactNotificationIds.current);
- },
- onError: (_err, _variables, context) => {
- context?.rollback();
- toast.failure('Failed to mark as done');
- },
- undoFn: async (variables, context) => {
- context?.applyUndone();
- try {
- await executeMarkEntitiesUndone({
- emailIds: variables.emailIds,
- notificationIds: variables.exactNotificationIds.current,
- });
- context?.settle(variables.exactNotificationIds.current);
- } catch (err) {
- context?.reapply();
- context?.releaseGraphql();
- throw err;
- }
- },
- redoFn: async (variables, context) => {
- context?.reapply();
- try {
- await executeMarkEntitiesDone({
+ };
+ const stackHandle = pushUndo({
+ label: 'Mark Done',
+ undo: async () => {
+ if (context.pendingUndo) context.pendingUndo.requested = true;
+ context.applyUndone();
+ if (context.pendingUndo) {
+ // Display and focus reverse now; the write must wait for exact IDs.
+ restoreFocus();
+ if (!(await context.pendingUndo.result)) return;
+ }
+ try {
+ if (context.operation) await context.operation.undo();
+ else {
+ await executeMarkEntitiesUndone({
+ emailIds: variables.emailIds,
+ notificationIds: variables.exactNotificationIds.current,
+ });
+ context.settle(variables.exactNotificationIds.current);
+ }
+ } catch (err) {
+ if (!context.operation) {
+ context.reapply();
+ context.releaseGraphql();
+ }
+ throw err;
+ }
+ },
+ redo: async () => {
+ context.reapply();
+ try {
+ if (context.operation) await context.operation.redo();
+ else {
+ await executeMarkEntitiesDone({
+ emailIds: variables.emailIds,
+ notificationIds: variables.exactNotificationIds.current,
+ });
+ context.settle(variables.exactNotificationIds.current);
+ }
+ } catch (err) {
+ if (!context.operation) {
+ context.applyUndone();
+ context.releaseGraphql();
+ }
+ throw err;
+ }
+ },
+ onUndone: context.pendingUndo ? undefined : restoreFocus,
+ onRedone: showToast,
+ });
+ const handle: UndoHandle = {
+ ...stackHandle,
+ dispose: () => {
+ disposed = true;
+ stackHandle.dispose();
+ dismiss();
+ },
+ };
+ context.registration = { handle, dismiss, showToast };
+ hotkeyGroup?.addDisposer(handle.dispose);
+ showToast();
+ variables.onUndoHandle?.(handle);
+ };
+
+ const mutation = useMutation<void, Error, MarkDoneVariables, MarkDoneContext>(
+ () => ({
+ onMutate: (variables) => {
+ const operation = variables.earlyUndo
+ ? createGraphqlDoneOperation({
+ ...variables,
+ notificationIds: variables.exactNotificationIds.current,
+ })
+ : undefined;
+ variables.operation = operation;
+ const context: MarkDoneContext = {
+ ...(operation ??
+ applyEntitiesDoneOptimistic({
+ entityIds: variables.entities.map((entity) => entity.id),
+ emailIds: variables.emailIds,
+ notificationIds: variables.optimisticNotificationIds,
+ scopeChannelThreads: variables.scopeChannelThreads,
+ })),
+ operation,
+ pendingUndo: variables.earlyUndo
+ ? createPendingDoneUndo()
+ : undefined,
+ };
+ if (context.pendingUndo) registerUndo(variables, context);
+ return context;
+ },
+ mutationFn: async (variables) => {
+ if (variables.operation) return variables.operation.execute();
+ const authoritativeNotificationIds = await executeMarkEntitiesDone({
emailIds: variables.emailIds,
notificationIds: variables.exactNotificationIds.current,
+ notificationEntities: variables.notificationEntities,
});
- context?.settle(variables.exactNotificationIds.current);
- } catch (err) {
- context?.applyUndone();
- context?.releaseGraphql();
- throw err;
- }
- },
- undoLabel: 'Mark Done',
- onPushed: (handle, variables) => {
- variables.onUndoHandle?.(handle);
- const firstEntityId = variables.entities[0]?.id;
- const count = variables.entities.length;
- const message =
- count > 1 ? `Marked ${count} items as done` : 'Marked as done';
- let toastId: number | undefined;
-
- const showToast = () => {
- if (variables.silent) return;
- toastId = toast.success(message, {
- actions: [
- {
- label: 'Undo',
- icon: ArrowCounterClockwise,
- onClick: () => {
- handle.undo({
- onError: () => toast.failure('Failed to undo'),
- });
- },
- },
- ],
- duration: 3_000,
- stack: true,
- hideOnMobile: true,
- });
- };
-
- showToast();
-
- return {
- onUndone: () => {
- if (toastId !== undefined) toast.dismiss(toastId);
- variables.restoreFocus?.();
- restoreSoupFocus(firstEntityId);
- variables.navigateBack?.();
- },
- onRedone: showToast,
- };
- },
- }));
+ variables.exactNotificationIds.current = [
+ ...new Set([
+ ...variables.exactNotificationIds.current,
+ ...authoritativeNotificationIds,
+ ]),
+ ];
+ },
+ onSuccess: (_data, variables, context) => {
+ if (!context) return;
+ // A late Done acknowledgement must not settle the newer Undo display
+ // intent before its reversal has written anything.
+ if (!context.pendingUndo?.requested) {
+ context.settle(variables.exactNotificationIds.current);
+ }
+ if (context.pendingUndo) {
+ const accepted = context.operation?.hasAccepted() ?? false;
+ if (!accepted) {
+ context.registration?.handle.dispose();
+ context.registration?.dismiss();
+ } else if (
+ context.operation?.hasFailures() ||
+ context.operation?.hasNoopRows()
+ ) {
+ context.registration?.dismiss();
+ if (!context.pendingUndo.requested)
+ context.registration?.showToast();
+ else if (context.operation?.hasFailures()) {
+ toast.alert(
+ 'Some changes could not be saved. Undo will reverse the accepted changes.'
+ );
+ }
+ }
+ context.pendingUndo.finish(accepted);
+ } else registerUndo(variables, context);
+ },
+ onError: (_err, _variables, context) => {
+ context?.registration?.handle.dispose();
+ context?.registration?.dismiss();
+ context?.rollback();
+ context?.pendingUndo?.finish(false);
+ toast.failure('Failed to mark as done');
+ },
+ })
+ );
const canExecute = (entity: EntityData): boolean => {
if (entity.type === 'channel_message') {
@@ -249,7 +364,15 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
): Promise<void> => {
// Skip already-done emails so a mixed selection (e.g. done + not-done rows
// in mail "All") doesn't re-archive the done ones or overcount the toast.
- const targets = entities.filter(isMarkDoneTarget);
+ const useEntityMutations = isFeatureEnabled(enableGraphqlSoup);
+ const eligible = entities.filter(isMarkDoneTarget);
+ const targets = useEntityMutations
+ ? [
+ ...new Map(
+ eligible.map((entity) => [doneEntityKey(entity), entity])
+ ).values(),
+ ]
+ : eligible;
if (targets.length === 0) return;
const source = notificationSource();
@@ -260,7 +383,6 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
scopeChannelNotificationsToEntity: scopeChannelNotifications,
});
- const useEntityMutations = isFeatureEnabled(enableGraphqlSoup);
// A whole-channel row in the new inbox intentionally excludes notification
// stacks rendered as separate thread rows. The entity endpoint cannot
// express "channel except its threads", so only that selective case keeps
@@ -292,10 +414,26 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
? selectiveChannelIds
: resolved.notificationIds;
+ const notificationIdsByEntity = new Map<DoneEntityKey, string[]>();
+ if (useEntityMutations) {
+ for (const entity of targets) {
+ notificationIdsByEntity.set(
+ doneEntityKey(entity),
+ resolveMarkEntitiesDoneVariables({
+ entities: [entity],
+ notificationSource: source,
+ scopeChannelNotificationsToEntity: scopeChannelNotifications,
+ }).notificationIds
+ );
+ }
+ }
+
await mutation.mutateAsync({
+ earlyUndo: useEntityMutations,
entities: targets,
emailIds: resolved.emailIds,
optimisticNotificationIds: resolved.notificationIds,
+ notificationIdsByEntity,
scopeChannelThreads: scopeChannelNotifications,
exactNotificationIds: { current: exactNotificationIds },
notificationEntities,
diff --git a/apps/web/src/features/next-soup/actions/tests/done-write-fixture.ts b/apps/web/src/features/next-soup/actions/tests/done-write-fixture.ts
new file mode 100644
index 0000000000..2e33fa3e38
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/tests/done-write-fixture.ts
@@ -0,0 +1,67 @@
+import type { UnifiedNotification } from '@notifications';
+import type { NotificationEntityRef } from '@queries/notification/entity-mutations';
+import type { MarkDoneWriteOutcome } from '../../utils';
+
+export function notificationReceipt(
+ id: string,
+ entity: NotificationEntityRef
+): UnifiedNotification {
+ return {
+ id,
+ entity_id: entity.id,
+ entity_type: entity.type === 'email' ? 'email_thread' : entity.type,
+ notification_metadata: {
+ tag: 'channel_message_send',
+ content: { messageId: entity.id },
+ },
+ } as UnifiedNotification;
+}
+
+/** Fake write boundary for action tests; production reports each backend result. */
+export type DoneWriteArgs = {
+ emailIds: string[];
+ notificationIds: string[];
+ notificationEntities?: NotificationEntityRef[];
+ onWriteSettled?: (outcome: MarkDoneWriteOutcome) => void;
+};
+
+export function reportDoneWriteOutcomes(
+ args: DoneWriteArgs,
+ result: PromiseSettledResult<string[]>
+) {
+ for (const id of args.emailIds)
+ args.onWriteSettled?.({
+ kind: 'email',
+ id,
+ result:
+ result.status === 'fulfilled'
+ ? { status: 'fulfilled', value: 'committed' }
+ : result,
+ });
+ if (args.notificationIds.length > 0)
+ args.onWriteSettled?.({
+ kind: 'notifications',
+ result:
+ result.status === 'fulfilled'
+ ? { status: 'fulfilled', value: args.notificationIds }
+ : result,
+ });
+ if (args.notificationEntities?.length)
+ args.onWriteSettled?.({
+ kind: 'entity-notifications',
+ result:
+ result.status === 'fulfilled'
+ ? {
+ status: 'fulfilled',
+ value: result.value.map((id, index) =>
+ notificationReceipt(
+ id,
+ args.notificationEntities![
+ index % args.notificationEntities!.length
+ ]
+ )
+ ),
+ }
+ : result,
+ });
+}
diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.ts
index aef8ef5d9b..2cb7b1c962 100644
--- a/apps/web/src/features/next-soup/utils.test.ts
+++ b/apps/web/src/features/next-soup/utils.test.ts
@@ -63,6 +63,7 @@ const operationMocks = vi.hoisted(() => {
),
invalidateSoupEntity: vi.fn(async () => {}),
openExternalUrl: vi.fn(),
+ refreshGraphqlSoup: vi.fn(async () => {}),
updateNotificationsForEntities: vi.fn(
async (): Promise<Array<{ id: string }>> => []
),
@@ -125,6 +126,9 @@ const hideGraphqlSoupEntitiesAsDone = vi.hoisted(() =>
vi.mock('@queries/soup/graphql/optimistic-done', () => ({
hideGraphqlSoupEntitiesAsDone,
}));
+vi.mock('@queries/soup/graphql/active-queries', () => ({
+ refreshActiveGraphqlSoupQueries: operationMocks.refreshGraphqlSoup,
+}));
vi.mock('@service-email/client', () => ({
emailClient: { flagArchived: operationMocks.flagArchived },
}));
@@ -161,6 +165,16 @@ import {
} from '@entity';
import type { NotificationSource, UnifiedNotification } from '@notifications';
import { hydrateChannelNotificationSelection } from '@queries/channel/notification-selection';
+import { queryClient } from '@queries/client';
+import {
+ restoreUserNotifications,
+ snapshotUserNotifications,
+} from '@queries/notification/user-notifications';
+import {
+ getSoupEntityById,
+ optimisticUpdateSoupEntity,
+ removeSoupEntitiesFromDoneFilteredQueries,
+} from '@queries/soup/cache';
import {
applyEntitiesDoneOptimistic,
applyEntitiesNotDoneOptimistic,
@@ -861,6 +875,45 @@ describe('mark-done orchestration', () => {
});
}
+ for (const [label, execute, notify] of [
+ [
+ 'Done',
+ executeMarkEntitiesDone,
+ operationMocks.bulkMarkNotificationsAsDone,
+ ],
+ [
+ 'Undo',
+ executeMarkEntitiesUndone,
+ operationMocks.bulkMarkNotificationsAsUndone,
+ ],
+ ] as const) {
+ it.each(['committed', 'queued', 'rejected'] as const)(
+ `GraphQL ${label} never cancels or invalidates REST caches (%s)`,
+ async (outcome) => {
+ operationMocks.graphql = true;
+ if (outcome === 'rejected') {
+ operationMocks.archive.mockRejectedValueOnce(
+ new Error('write failed')
+ );
+ } else {
+ operationMocks.archive.mockResolvedValueOnce(outcome);
+ }
+ const write = execute({
+ emailIds: ['email-1'],
+ notificationIds: ['notification-1'],
+ });
+ if (outcome === 'rejected')
+ await expect(write).rejects.toThrow('write failed');
+ else await write;
+ expect(notify).toHaveBeenCalledWith(['notification-1']);
+ expect(operationMocks.cancelQueries).not.toHaveBeenCalled();
+ expect(operationMocks.invalidateQueries).not.toHaveBeenCalled();
+ expect(operationMocks.invalidateSoupEntity).not.toHaveBeenCalled();
+ expect(operationMocks.refreshGraphqlSoup).not.toHaveBeenCalled();
+ }
+ );
+ }
+
it.each([false, true])(
'GraphQL mixed rejection does not refetch accepted email state (per-thread=%s)',
async (perThread) => {
@@ -897,7 +950,8 @@ describe('mark-done orchestration', () => {
).resolves.toBe('committed');
expect(invalidatedEmailList()).toBe(false);
expect(operationMocks.invalidateSoupEntity).not.toHaveBeenCalled();
- expect(operationMocks.invalidateQueries).toHaveBeenCalledTimes(1); // notifications only
+ expect(operationMocks.invalidateQueries).not.toHaveBeenCalled();
+ expect(operationMocks.cancelQueries).not.toHaveBeenCalled();
});
it.each([false, true])(
@@ -984,6 +1038,73 @@ describe('mark-done orchestration', () => {
}
);
+ it('reports every GraphQL write receipt before throwing a sibling failure', async () => {
+ operationMocks.graphql = true;
+ const archiveError = new Error('archive failed');
+ operationMocks.archive
+ .mockResolvedValueOnce('queued')
+ .mockRejectedValueOnce(archiveError);
+ operationMocks.updateNotificationsForEntities.mockResolvedValueOnce([
+ { id: 'server-exact' },
+ ]);
+ const onWriteSettled = vi.fn();
+ await expect(
+ executeMarkEntitiesDone({
+ emailIds: ['queued', 'failed'],
+ notificationIds: ['selected-id'],
+ notificationEntities: [{ type: 'document', id: 'document-1' }],
+ onWriteSettled,
+ })
+ ).rejects.toBe(archiveError);
+ expect(onWriteSettled.mock.calls.map(([outcome]) => outcome)).toEqual([
+ {
+ kind: 'email',
+ id: 'queued',
+ result: { status: 'fulfilled', value: 'queued' },
+ },
+ {
+ kind: 'email',
+ id: 'failed',
+ result: { status: 'rejected', reason: archiveError },
+ },
+ {
+ kind: 'notifications',
+ result: { status: 'fulfilled', value: ['selected-id'] },
+ },
+ {
+ kind: 'entity-notifications',
+ result: { status: 'fulfilled', value: [{ id: 'server-exact' }] },
+ },
+ ]);
+ expect(operationMocks.cancelQueries).not.toHaveBeenCalled();
+ expect(operationMocks.invalidateQueries).not.toHaveBeenCalled();
+ });
+
+ it('reports accepted GraphQL reversals even when notification reversal fails', async () => {
+ operationMocks.graphql = true;
+ const failure = new Error('notification failed');
+ operationMocks.bulkMarkNotificationsAsUndone.mockRejectedValueOnce(failure);
+ const onWriteSettled = vi.fn();
+ await expect(
+ executeMarkEntitiesUndone({
+ emailIds: ['email-1'],
+ notificationIds: ['exact-id'],
+ onWriteSettled,
+ })
+ ).rejects.toBe(failure);
+ expect(onWriteSettled.mock.calls.map(([outcome]) => outcome)).toEqual([
+ {
+ kind: 'email',
+ id: 'email-1',
+ result: { status: 'fulfilled', value: 'committed' },
+ },
+ {
+ kind: 'notifications',
+ result: { status: 'rejected', reason: failure },
+ },
+ ]);
+ });
+
it('executes entity notification writes directly and returns exact ids', async () => {
operationMocks.updateNotificationsForEntities.mockResolvedValueOnce([
{ id: 'entity-notification' },
@@ -1005,6 +1126,96 @@ describe('mark-done orchestration', () => {
});
describe('mark-done optimism', () => {
+ const expectNoRestCacheAccess = () => {
+ for (const operation of [
+ queryClient.getQueriesData,
+ getSoupEntityById,
+ optimisticUpdateSoupEntity,
+ removeSoupEntitiesFromDoneFilteredQueries,
+ snapshotUserNotifications,
+ restoreUserNotifications,
+ ])
+ expect(operation).not.toHaveBeenCalled();
+ };
+
+ it('keeps GraphQL Done, Undo, Redo and rollback independent of REST caches', () => {
+ operationMocks.graphql = true;
+ const context = applyEntitiesDoneOptimistic({
+ entityIds: ['email-1', 'document-1'],
+ emailIds: ['email-1'],
+ notificationIds: ['notification-1'],
+ scopeChannelThreads: true,
+ });
+ expectNoRestCacheAccess();
+ expect(hideGraphqlSoupEntitiesAsDone).toHaveBeenCalledWith({
+ entityIds: ['email-1', 'document-1'],
+ notificationIds: ['notification-1'],
+ scopeChannelThreads: true,
+ done: true,
+ });
+ const intent = hideGraphqlSoupEntitiesAsDone.mock.results[0].value;
+ context.settle(['exact-id']);
+ context.applyUndone();
+ expect(intent.setDone).toHaveBeenLastCalledWith(false);
+ expect(operationMocks.doneOverride).toHaveBeenLastCalledWith(
+ ['notification-1'],
+ false
+ );
+ context.reapply();
+ expect(intent.setDone).toHaveBeenLastCalledWith(true);
+ expect(operationMocks.doneOverride).toHaveBeenLastCalledWith(
+ ['notification-1'],
+ true
+ );
+ const lease = operationMocks.doneOverride.mock.results.at(-1)!.value;
+ context.rollback();
+ expect(lease).toHaveBeenCalledOnce();
+ context.releaseGraphql();
+ expect(lease.release).toHaveBeenCalledOnce();
+ expect(intent.settle).toHaveBeenCalledWith(['exact-id']);
+ expectNoRestCacheAccess();
+ });
+
+ it('unwinds the initial GraphQL Done lease when the write fails after early Undo', () => {
+ operationMocks.graphql = true;
+ const context = applyEntitiesDoneOptimistic({
+ entityIds: ['document-1'],
+ emailIds: [],
+ notificationIds: ['notification-1'],
+ });
+ const doneLease = operationMocks.doneOverride.mock.results[0].value;
+ context.applyUndone();
+ const undoneLease = operationMocks.doneOverride.mock.results[1].value;
+ context.rollback();
+ expect(undoneLease).toHaveBeenCalledOnce();
+ expect(doneLease).toHaveBeenCalledOnce();
+ expect(undoneLease.mock.invocationCallOrder[0]).toBeLessThan(
+ doneLease.mock.invocationCallOrder[0]
+ );
+ expectNoRestCacheAccess();
+ });
+
+ it('keeps GraphQL Not Done and rollback independent of REST caches', () => {
+ operationMocks.graphql = true;
+ const context = applyEntitiesNotDoneOptimistic({
+ emailIds: ['email-1'],
+ notificationIds: ['notification-1'],
+ });
+ expect(hideGraphqlSoupEntitiesAsDone).toHaveBeenCalledWith({
+ entityIds: ['email-1'],
+ notificationIds: ['notification-1'],
+ done: false,
+ });
+ const lease = operationMocks.doneOverride.mock.results[0].value;
+ context.settle();
+ context.rollback();
+ expect(lease).toHaveBeenCalledOnce();
+ expect(
+ hideGraphqlSoupEntitiesAsDone.mock.results[0].value.release
+ ).toHaveBeenCalledOnce();
+ expectNoRestCacheAccess();
+ });
+
it('keeps REST Done rollback behavior without creating GraphQL display intent', () => {
const context = applyEntitiesDoneOptimistic({
entityIds: ['document-1'],
@@ -1050,6 +1261,7 @@ describe('mark-done optimism', () => {
entityIds: ['document-1'],
notificationIds: ['notification-1'],
scopeChannelThreads: undefined,
+ done: true,
});
const applied = hideGraphqlSoupEntitiesAsDone.mock.results[0]?.value;
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index 0ddc1f98ed..439dee540f 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -119,13 +119,10 @@ import {
removeSoupEntitiesFromDoneFilteredQueries,
} from '@queries/soup/cache';
import { refreshActiveGraphqlSoupQueries } from '@queries/soup/graphql/active-queries';
-import {
- type GraphqlSoupDoneOverlay,
- hideGraphqlSoupEntitiesAsDone,
-} from '@queries/soup/graphql/optimistic-done';
import { emailClient } from '@service-email/client';
import { isAfter } from 'date-fns';
import { match } from 'ts-pattern';
+import { applyGraphqlDoneOptimistic } from './actions/graphql-done-optimism';
import {
searchLocationTarget,
searchLocationUpdates,
@@ -1384,7 +1381,13 @@ export function applyEntitiesDoneOptimistic(args: {
scopeChannelThreads?: boolean;
}): MarkEntitiesDoneContext {
const { entityIds, emailIds, notificationIds } = args;
- const graphql = isFeatureEnabled(enableGraphqlSoup);
+ if (isFeatureEnabled(enableGraphqlSoup)) {
+ return applyGraphqlDoneOptimistic({
+ entityIds,
+ notificationIds,
+ scopeChannelThreads: args.scopeChannelThreads,
+ });
+ }
const emailIdSet = new Set(emailIds);
const entityIdSet = new Set(entityIds);
@@ -1455,8 +1458,6 @@ 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 }[] = [];
const reapply = () => {
@@ -1467,18 +1468,6 @@ export function applyEntitiesDoneOptimistic(args: {
entityIds.length > 0
? removeSoupEntitiesFromDoneFilteredQueries(entityIdSet)
: null;
- // GraphQL lists never read the REST caches patched here. The entity
- // 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.
- 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({
@@ -1488,7 +1477,7 @@ export function applyEntitiesDoneOptimistic(args: {
})
);
filterEmailCache();
- rollbackNotifications = setDoneOverride(notificationIds, true);
+ setDoneOverride(notificationIds, true);
};
const rollbackSoup = () => {
@@ -1502,20 +1491,17 @@ export function applyEntitiesDoneOptimistic(args: {
const rollback = () => {
rollbackSoup();
- graphqlDone?.release();
restoreEmailCache();
- if (graphql) rollbackNotifications?.();
- else setDoneOverride(notificationIds, undefined);
+ 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.
- rollbackNotifications = setDoneOverride(notificationIds, false);
+ setDoneOverride(notificationIds, false);
};
reapply();
@@ -1524,12 +1510,8 @@ export function applyEntitiesDoneOptimistic(args: {
rollback,
reapply,
applyUndone,
- settle: (ids) => graphqlDone?.settle(ids),
- releaseGraphql: () => {
- if (!graphql) return;
- graphqlDone?.release();
- rollbackNotifications?.release();
- },
+ settle: () => {},
+ releaseGraphql: () => {},
};
}
@@ -1544,14 +1526,13 @@ export function applyEntitiesNotDoneOptimistic(args: {
notificationIds: string[];
}): { rollback: () => void; settle: () => void } {
const { emailIds, notificationIds } = args;
- const graphql = isFeatureEnabled(enableGraphqlSoup);
- const graphqlDone = graphql
- ? hideGraphqlSoupEntitiesAsDone({
- entityIds: emailIds,
- notificationIds,
- done: false,
- })
- : undefined;
+ if (isFeatureEnabled(enableGraphqlSoup)) {
+ return applyGraphqlDoneOptimistic({
+ entityIds: emailIds,
+ notificationIds,
+ done: false,
+ });
+ }
const emailRowTxns = emailIds.map((id) =>
optimisticUpdateSoupEntity({
tag: 'emailThread',
@@ -1559,24 +1540,45 @@ export function applyEntitiesNotDoneOptimistic(args: {
frecency_score: getSoupEntityById(id)?.frecency_score ?? 0,
})
);
- const rollbackNotifications = setDoneOverride(notificationIds, false);
+ setDoneOverride(notificationIds, false);
return {
- settle: () => graphqlDone?.settle(),
+ settle: () => {},
rollback: () => {
- graphqlDone?.release();
for (const txn of [...emailRowTxns].reverse()) {
txn.rollback();
}
- if (graphql) rollbackNotifications?.();
- else setDoneOverride(notificationIds, undefined);
+ setDoneOverride(notificationIds, undefined);
},
};
}
/**
- * Fires archive, selective ID-scoped notification, entity-scoped notification,
- * and reminder completion writes. Returns the authoritative notification IDs
+ * A write receipt is delivered even when another write in the action fails.
+ * ID-scoped notification receipts keep the explicit requested scope (including
+ * durably queued writes); the backend atomically updates its owned, non-deleted
+ * matches in one statement. Entity-scoped receipts instead carry returned rows
+ * so Undo can discover exact IDs without including later notifications.
+ *
+ * A rejected response is not proof of no persistence: post-commit push-cleanup
+ * lookups can fail, and transport responses can be lost. Retire unacknowledged
+ * display intent; do not guess additional inverse IDs from those failures.
+ */
+export type MarkDoneWriteOutcome =
+ | {
+ kind: 'email';
+ id: string;
+ result: PromiseSettledResult<EmailArchiveDisposition>;
+ }
+ | { kind: 'notifications'; result: PromiseSettledResult<string[]> }
+ | {
+ kind: 'entity-notifications';
+ result: PromiseSettledResult<UnifiedNotification[]>;
+ };
+
+/**
+ * Fires archive, selective ID-scoped notification, and entity-scoped notification
+ * writes. Returns the authoritative notification IDs
* produced by the entity write. Throws on any failure; the caller owns rollback
* through the context returned by `applyEntitiesDoneOptimistic`.
*/
@@ -1584,40 +1586,63 @@ export async function executeMarkEntitiesDone(args: {
emailIds: string[];
notificationIds: string[];
notificationEntities?: NotificationEntityRef[];
+ onWriteSettled?: (outcome: MarkDoneWriteOutcome) => void;
}): Promise<string[]> {
const { emailIds, notificationIds, notificationEntities = [] } = args;
- await Promise.all([
- queryClient.cancelQueries({ queryKey: queryKeys.all.email }),
- queryClient.cancelQueries({ queryKey: notificationKeys.user._def }),
- ]);
-
- let authoritativeNotificationIds: string[] = [];
- const results = await Promise.allSettled([
- ...emailIds.map((id) => archiveEmailThread({ value: true, id })),
- notificationIds.length > 0
- ? bulkMarkNotificationsAsDone(notificationIds)
- : Promise.resolve(),
- notificationEntities.length > 0
- ? updateNotificationsForEntities({
- entities: notificationEntities,
- operation: 'MARK_DONE',
- }).then((notifications) => {
- authoritativeNotificationIds = notifications.map(
- (notification) => notification.id
- );
- })
- : Promise.resolve(),
- ]);
+ const graphql = isFeatureEnabled(enableGraphqlSoup);
+ if (!graphql) {
+ await Promise.all([
+ queryClient.cancelQueries({ queryKey: queryKeys.all.email }),
+ queryClient.cancelQueries({ queryKey: notificationKeys.user._def }),
+ ]);
+ }
- const hasQueuedEmail = results
- .slice(0, emailIds.length)
- .some(
- (result) => result.status === 'fulfilled' && result.value === 'queued'
- );
+ const writeNotificationIds = async () => {
+ if (notificationIds.length > 0)
+ await bulkMarkNotificationsAsDone(notificationIds);
+ return notificationIds;
+ };
+ const writeNotificationEntities = async () => {
+ if (notificationEntities.length === 0) return [];
+ return await updateNotificationsForEntities({
+ entities: notificationEntities,
+ operation: 'MARK_DONE',
+ });
+ };
+ const [emailResults, [notificationResult], [entityResult]] =
+ await Promise.all([
+ Promise.allSettled(
+ emailIds.map((id) => archiveEmailThread({ value: true, id }))
+ ),
+ Promise.allSettled([writeNotificationIds()]),
+ Promise.allSettled([writeNotificationEntities()]),
+ ]);
+ const report = args.onWriteSettled ?? (() => {});
+ for (const [index, result] of emailResults.entries())
+ report({ kind: 'email', id: emailIds[index], result });
+ if (notificationIds.length > 0)
+ report({ kind: 'notifications', result: notificationResult });
+ if (notificationEntities.length > 0)
+ report({ kind: 'entity-notifications', result: entityResult });
+
+ const authoritativeNotificationIds =
+ entityResult.status === 'fulfilled'
+ ? entityResult.value.map(({ id }) => id)
+ : [];
+ const results = [...emailResults, notificationResult, entityResult];
+ const hasQueuedEmail = emailResults.some(
+ (result) => result.status === 'fulfilled' && result.value === 'queued'
+ );
const rejected = results.find(
(r): r is PromiseRejectedResult => r.status === 'rejected'
);
+ if (graphql) {
+ // Email/notification writers own normalized rollback and revalidation.
+ if (rejected) throw rejected.reason ?? new Error('Failed to mark as done');
+ return authoritativeNotificationIds;
+ }
+
if (rejected) {
// Real refetch to reconcile server state with the UI after the caller
// rolls back its optimistic cache writes. Some email or notification
@@ -1668,30 +1693,38 @@ export async function executeMarkEntitiesUndone(args: {
id: string,
result: PromiseSettledResult<EmailArchiveDisposition>
) => void;
+ onWriteSettled?: (outcome: MarkDoneWriteOutcome) => void;
}): Promise<EmailArchiveDisposition> {
const { emailIds, notificationIds } = args;
const graphql = isFeatureEnabled(enableGraphqlSoup);
- await Promise.all([
- ...(!graphql
- ? [queryClient.cancelQueries({ queryKey: queryKeys.all.email })]
- : []),
- queryClient.cancelQueries({ queryKey: notificationKeys.user._def }),
- ]);
+ if (!graphql) {
+ await Promise.all([
+ queryClient.cancelQueries({ queryKey: queryKeys.all.email }),
+ queryClient.cancelQueries({ queryKey: notificationKeys.user._def }),
+ ]);
+ }
- const [emailResults, otherResults] = await Promise.all([
+ const writeNotificationIds = async () => {
+ if (notificationIds.length > 0)
+ await bulkMarkNotificationsAsUndone(notificationIds);
+ return notificationIds;
+ };
+ const [emailResults, [notificationResult]] = await Promise.all([
Promise.allSettled(
emailIds.map((id) => archiveEmailThread({ value: false, id }))
),
- Promise.allSettled([
- notificationIds.length > 0
- ? bulkMarkNotificationsAsUndone(notificationIds)
- : Promise.resolve(),
- ]),
+ Promise.allSettled([writeNotificationIds()]),
]);
for (const [index, result] of emailResults.entries()) {
args.onEmailSettled?.(emailIds[index], result);
+ args.onWriteSettled?.({ kind: 'email', id: emailIds[index], result });
}
- const results = [...emailResults, ...otherResults];
+ if (notificationIds.length > 0)
+ args.onWriteSettled?.({
+ kind: 'notifications',
+ result: notificationResult,
+ });
+ const results = [...emailResults, notificationResult];
const hasQueuedEmail = emailResults.some(
(result) => result.status === 'fulfilled' && result.value === 'queued'
);
@@ -1699,12 +1732,15 @@ export async function executeMarkEntitiesUndone(args: {
(r): r is PromiseRejectedResult => r.status === 'rejected'
);
+ if (graphql) {
+ if (rejected) throw rejected.reason ?? new Error('Failed to undo');
+ return hasQueuedEmail ? 'queued' : 'committed';
+ }
+
if (rejected) {
- // 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.
+ // REST retains its legacy batch rollback/reconciliation.
await Promise.all([
- ...(!graphql && !hasQueuedEmail
+ ...(!hasQueuedEmail
? [
queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
...emailIds.map((id) => invalidateSoupEntity(id)),
@@ -1716,7 +1752,7 @@ export async function executeMarkEntitiesUndone(args: {
}
await Promise.all([
- ...(!graphql && !hasQueuedEmail
+ ...(!hasQueuedEmail
? [
queryClient.invalidateQueries({
queryKey: queryKeys.all.email,
diff --git a/apps/web/src/lib/core/component/Toast/Toast.tsx b/apps/web/src/lib/core/component/Toast/Toast.tsx
index ccf99d6d32..b3e8e5e67e 100644
--- a/apps/web/src/lib/core/component/Toast/Toast.tsx
+++ b/apps/web/src/lib/core/component/Toast/Toast.tsx
@@ -125,7 +125,7 @@ interface ToastOptions {
hideOnMobile?: boolean;
}
-interface ToastSuccessOptions extends ToastOptions {
+interface ToastActionOptions extends ToastOptions {
actions?: ToastAction[];
/** When true, bypasses the 3s duplicate-message throttle. */
stack?: boolean;
@@ -242,7 +242,7 @@ function dismissIfRecent(message: string, type: ToastType): void {
// Tell users that an action has successfully completed
function success(
message: string,
- options?: ToastSuccessOptions
+ options?: ToastActionOptions
): number | undefined {
if (!options?.stack) dismissIfRecent(message, ToastType.SUCCESS);
return createToast(message, ToastType.SUCCESS, options);
@@ -262,9 +262,12 @@ function failure(
}
// Tell users that an action has failed, because of them
-function alert(message: string, options?: ToastOptions) {
- dismissIfRecent(message, ToastType.ALERT);
- createToast(message, ToastType.ALERT, options);
+function alert(
+ message: string,
+ options?: ToastActionOptions
+): number | undefined {
+ if (!options?.stack) dismissIfRecent(message, ToastType.ALERT);
+ return createToast(message, ToastType.ALERT, options);
}
function ActionButtons(props: { actions: ToastAction[]; mobile?: boolean }) {
@@ -663,7 +666,7 @@ async function promise<T>(
function createToast(
message: string,
toastType: ToastType,
- options?: ToastSuccessOptions
+ options?: ToastActionOptions
) {
const { subtext, actions, duration, stack, hideOnMobile } = options ?? {};
diff --git a/apps/web/src/lib/queries/undo.test.ts b/apps/web/src/lib/queries/undo.test.ts
index a0d18daf6f..dba3596a13 100644
--- a/apps/web/src/lib/queries/undo.test.ts
+++ b/apps/web/src/lib/queries/undo.test.ts
@@ -1,5 +1,5 @@
import { createRoot } from 'solid-js';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { MutationUndoProvider, useMutationUndoContext } from './undo';
describe('MutationUndoProvider', () => {
@@ -80,6 +80,63 @@ describe('MutationUndoProvider', () => {
});
});
+ for (const failure of [false, true]) {
+ it.each([false, true])(
+ `retires an in-flight redo after a new action (failure=${failure}, newer undone=%s)`,
+ async (undoNewer) => {
+ await createRoot(async (dispose) => {
+ let ctx!: ReturnType<typeof useMutationUndoContext>;
+ MutationUndoProvider({
+ get children() {
+ ctx = useMutationUndoContext();
+ return null;
+ },
+ });
+ const pending = Promise.withResolvers<void>();
+ const oldUndo = vi.fn();
+ const onRedone = vi.fn();
+ ctx.pushUndo({
+ undo: oldUndo,
+ redo: () => pending.promise,
+ onRedone,
+ });
+ await ctx.undo();
+ oldUndo.mockClear();
+ const callbacks = {
+ onSuccess: vi.fn(),
+ onError: vi.fn(),
+ onSettled: vi.fn(),
+ };
+ const redo = ctx.redo(callbacks);
+ const newerUndo = vi.fn();
+ const newerRedo = vi.fn();
+ ctx.pushUndo({ undo: newerUndo, redo: newerRedo });
+ if (undoNewer) await ctx.undo();
+ if (failure) pending.reject(new Error('old redo failed'));
+ else pending.resolve();
+ await redo;
+ expect(onRedone).not.toHaveBeenCalled();
+ expect(callbacks.onSuccess).not.toHaveBeenCalled();
+ expect(callbacks.onError).not.toHaveBeenCalled();
+ expect(callbacks.onSettled).toHaveBeenCalledOnce();
+ if (undoNewer) {
+ expect(ctx.canUndo()).toBe(false);
+ await ctx.redo();
+ expect(newerRedo).toHaveBeenCalledOnce();
+ await ctx.undo();
+ } else {
+ expect(ctx.canRedo()).toBe(false);
+ await ctx.undo();
+ }
+ expect(newerUndo).toHaveBeenCalledTimes(undoNewer ? 2 : 1);
+ expect(oldUndo).not.toHaveBeenCalled();
+ expect(ctx.canUndo()).toBe(false);
+ dispose();
+ });
+ }
+ );
+ }
+
it('no-ops when stacks are empty', async () => {
await createRoot(async (dispose) => {
let ctx!: ReturnType<typeof useMutationUndoContext>;
@@ -184,6 +241,47 @@ describe('MutationUndoProvider', () => {
});
});
+ for (const operation of ['undo', 'redo'] as const) {
+ for (const retire of ['dispose', 'clear'] as const) {
+ it.each([false, true])(
+ `does not resurrect a pending ${operation} after ${retire} (failure=%s)`,
+ async (failure) => {
+ await createRoot(async (dispose) => {
+ let ctx!: ReturnType<typeof useMutationUndoContext>;
+ MutationUndoProvider({
+ get children() {
+ ctx = useMutationUndoContext();
+ return null;
+ },
+ });
+ const pending = Promise.withResolvers<void>();
+ const onUndone = vi.fn();
+ const onRedone = vi.fn();
+ const handle = ctx.pushUndo({
+ undo: () => (operation === 'undo' ? pending.promise : undefined),
+ redo: () => pending.promise,
+ onUndone,
+ onRedone,
+ });
+ if (operation === 'redo') await ctx.undo();
+ onUndone.mockClear();
+ const action = ctx[operation]();
+ if (retire === 'dispose') handle.dispose();
+ else ctx.clear();
+ if (failure) pending.reject(new Error('failed'));
+ else pending.resolve();
+ await action;
+ expect(ctx.canUndo()).toBe(false);
+ expect(ctx.canRedo()).toBe(false);
+ expect(onUndone).not.toHaveBeenCalled();
+ expect(onRedone).not.toHaveBeenCalled();
+ dispose();
+ });
+ }
+ );
+ }
+ }
+
it('calls onError on failed redo and restores stack', async () => {
await createRoot(async (dispose) => {
let ctx!: ReturnType<typeof useMutationUndoContext>;
diff --git a/apps/web/src/lib/queries/undo.ts b/apps/web/src/lib/queries/undo.ts
index 99045d3606..aa9738134b 100644
--- a/apps/web/src/lib/queries/undo.ts
+++ b/apps/web/src/lib/queries/undo.ts
@@ -83,6 +83,9 @@ export const [MutationUndoProvider, useMutationUndoContext] =
(): MutationUndoContextValue => {
const [undoStack, setUndoStack] = createSignal<UndoEntry[]>([]);
const [redoStack, setRedoStack] = createSignal<UndoEntry[]>([]);
+ const disposed = new WeakSet<UndoEntry>();
+ let generation = 0;
+ let redoGeneration = 0;
const runUndo = async (
entry: UndoEntry,
@@ -94,15 +97,19 @@ export const [MutationUndoProvider, useMutationUndoContext] =
// cleared by a new pushUndo after redoStack reset).
if (prevPos < 0) return;
+ const startedGeneration = generation;
+ const startedRedoGeneration = redoGeneration;
setUndoStack(current.filter((e) => e !== entry));
try {
await entry.undo();
- if (entry.redo) {
+ if (disposed.has(entry) || generation !== startedGeneration) return;
+ if (entry.redo && redoGeneration === startedRedoGeneration) {
setRedoStack((prev) => [...prev, entry]);
}
entry.onUndone?.();
callbacks?.onSuccess?.();
} catch (err) {
+ if (disposed.has(entry) || generation !== startedGeneration) return;
// Restore at original position so a non-top undo that fails doesn't
// reorder the stack.
setUndoStack((prev) => {
@@ -122,14 +129,24 @@ export const [MutationUndoProvider, useMutationUndoContext] =
entry: UndoEntry,
callbacks?: UndoCallbacks
): Promise<void> => {
+ const startedGeneration = generation;
+ const startedRedoGeneration = redoGeneration;
+ // A new action retires the redo branch, including requests already in
+ // flight. Their completion must not repopulate either stack or UI.
+ const isRetired = () =>
+ disposed.has(entry) ||
+ generation !== startedGeneration ||
+ redoGeneration !== startedRedoGeneration;
try {
if (entry.redo) {
await entry.redo();
}
+ if (isRetired()) return;
setUndoStack((prev) => [...prev, entry]);
entry.onRedone?.();
callbacks?.onSuccess?.();
} catch (err) {
+ if (isRetired()) return;
setRedoStack((prev) => [...prev, entry]);
callbacks?.onError?.(
err instanceof Error ? err : new Error(String(err))
@@ -142,12 +159,14 @@ export const [MutationUndoProvider, useMutationUndoContext] =
return {
pushUndo: (input) => {
const entry: UndoEntry = { ...input, id: genId() };
+ redoGeneration += 1;
setUndoStack((prev) => [...prev, entry]);
setRedoStack([]);
return {
id: entry.id,
undo: (callbacks) => runUndo(entry, callbacks),
dispose: () => {
+ disposed.add(entry);
setUndoStack((prev) => prev.filter((e) => e !== entry));
setRedoStack((prev) => prev.filter((e) => e !== entry));
},
@@ -158,6 +177,8 @@ export const [MutationUndoProvider, useMutationUndoContext] =
canRedo: () => redoStack().length > 0,
clear: () => {
+ generation += 1;
+ redoGeneration += 1;
setUndoStack([]);
setRedoStack([]);
},
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 709216b91c..1e565fe3f6 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -102,11 +102,34 @@ 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 that
exclude done items, such as Email Important/Noise and Home Signal, without waiting
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,
+GraphQL Undo is offered as soon as Done applies locally, even while its initial
+write is pending. Undo restores the row and focus immediately; its server write
+waits for the initial outcomes and uses only acknowledged notification IDs.
+A late Done reply must not settle or overwrite the newer Undo display intent.
+Undo also restores a previously admitted row 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.
+Test mixed committed/queued/rejected archives and notification writes,
+including an archive that fails while its notifications succeed (and vice versa). Accepted writes retain Undo; rejected siblings must neither
+reappear in its request nor be retried by Redo. Partial feedback keeps an Undo
+action. A reply with no matching notification IDs must release that target's
+optimistic hide and notification overrides immediately, even if Undo was never
+clicked and mounted readers remain stale. Do not wait for acknowledgement or a
+timer when there is no receipt. Accepted siblings keep their own display intent;
+a no-op target cannot borrow their IDs to restore its row. Mixed accepted/no-op
+results replace the optimistic full-count toast with the actual completed count
+and retain Undo for accepted writes. An empty notification receipt alone must not
+make a successfully archived email or completed reminder look partially failed.
+Partial Undo/Redo failures retry only the failed writes.
+If every initial write fails, retire its pending Undo/Redo entry and unwind both
+Done and any early Undo overrides. Disposal or clearing history while a reversal
+is pending must not resurrect that entry when its response arrives. Also delay
+Redo, then perform a new action: the late Redo's success or failure must not
+repopulate either history stack or show its stale completion toast. The next Undo
+must still target the newer action; already-dispatched network writes are not
+cancelled by this history fence.
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
@@ -118,6 +141,14 @@ 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.
+Test GraphQL list optimism independently of REST: block REST Soup, email-thread,
+and user-notification data endpoints before page initialization, then confirm
+GraphQL alone populates the list. Hold GraphQL mutation replies while testing
+Done/Undo/Redo and rejection: row feedback must not depend on REST cache reads,
+patches, cancellation, or invalidation. Auth/account metadata is outside this
+row-data boundary. Test the REST path separately, not as a GraphQL fallback.
+Email Reminders contains original email rows: Done archives those conversations,
+with the same immediate GraphQL Undo behavior as the other email tabs.
In Tasks, Email, Home and Drive, rows keep their DOM when the list updates. A
property edit or a rename updates the edited row in place instead of rebuilding
every visible row. To verify, watch the row nodes with a `MutationObserver` while