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.

14.0 KB
Raw Blame
import { QueryClient } from '@tanstack/solid-query';
import { err, ok } from 'neverthrow';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mountEmailMutation } from './tests/mutation';

const mocks = vi.hoisted(() => ({
  graphqlEnabled: true,
  cacheEnabled: true,
  markSeen: vi.fn(),
  updateLabel: vi.fn(),
  getLabels: vi.fn(),
  legacyPatch: vi.fn(),
  graphqlMutation: vi.fn(),
  refresh: vi.fn(),
  refetch: vi.fn(),
}));
vi.mock('@core/constant/featureFlags', async (importOriginal) => ({
  ...(await importOriginal<typeof import('@core/constant/featureFlags')>()),
  enableGraphqlSoup: { key: 'enable-graphql-soup' },
  isFeatureEnabled: () => mocks.graphqlEnabled,
}));
vi.mock('@service-email/client', () => ({
  emailClient: {
    markThreadAsSeen: mocks.markSeen,
    updateThreadLabel: mocks.updateLabel,
    updateThreadState: mocks.updateLabel,
    getUserLabels: mocks.getLabels,
  },
}));
vi.mock('../client', () => ({
  get queryClient() {
    return client;
  },
}));
vi.mock('../soup/cache', () => ({
  optimisticUpdateSoupEntity: mocks.legacyPatch,
  refetchSoupEntity: mocks.refetch,
}));
vi.mock('../soup/graphql/active-queries', async (importOriginal) => ({
  ...(await importOriginal<typeof import('../soup/graphql/active-queries')>()),
  refreshActiveGraphqlSoupQueries: mocks.refresh,
}));
vi.mock('../soup/normalized-cache', () => ({ invalidateAllSoup: vi.fn() }));
vi.mock('../undo', () => ({ useUndoableMutation: vi.fn() }));
vi.mock('./graphql/thread', () => ({
  createGraphqlEmailThreadQuery: vi.fn(),
  fetchGraphqlEmailThread: vi.fn(),
  mapGraphqlThreadError: vi.fn(),
}));
vi.mock('@app/lib/analytics/analytics-context', () => ({
  useAnalytics: () => ({ track: vi.fn() }),
}));
vi.mock('@app/lib/analytics/posthog', () => ({
  useFeatureFlag: () => () => ({ enabled: mocks.graphqlEnabled }),
}));
vi.mock('@core/component/Toast/Toast', () => ({ toast: { failure: vi.fn() } }));
vi.mock('@macro-inc/observability', () => ({ Telemetry: { error: vi.fn() } }));
vi.mock('@service-storage/graphql-soup', () => ({
  getGraphqlSoupClient: () => ({ mutation: mocks.graphqlMutation }),
  graphqlCacheEnabled: () => mocks.cacheEnabled,
}));

import { predictOptimisticMutation } from '@graphql-cache/exchange/optimistic-resolvers';
import {
  MarkEmailThreadSeenDocument,
  MarkEmailThreadUnreadDocument,
  SoupDocument,
} from '@service-storage/graphql/generated/graphql';
import { soupOptimisticResolvers } from '../optimistic-resolvers';
import { registerGraphqlSoupRevalidations } from '../soup/graphql/active-queries';
import { soupKeys } from '../soup/keys';
import { emailKeys } from './keys';
import { markEmailThreadSeen } from './read-state';
import {
  trackExternalThreadArchive,
  useMarkThreadAsSeenMutation,
  useMarkThreadAsUnreadMutation,
} from './thread';

let client: QueryClient;

function hasReadPatch(value: unknown, isRead: boolean): boolean {
  if (!value || typeof value !== 'object') return false;
  if (Array.isArray(value))
    return value.some((item) => hasReadPatch(item, isRead));
  const record = value as Record<string, unknown>;
  return (
    (record.__typename === 'GraphqlSoupEmailThread' &&
      record.id === 'thread' &&
      record.isRead === isRead) ||
    Object.values(record).some((item) => hasReadPatch(item, isRead))
  );
}

beforeEach(() => {
  vi.resetAllMocks();
  mocks.graphqlEnabled = true;
  mocks.cacheEnabled = true;
  mocks.legacyPatch.mockReturnValue({ rollback: vi.fn() });
  mocks.refresh.mockResolvedValue(undefined);
  client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
  client.setQueryData(emailKeys.labels.queryKey, {
    labels: [
      { id: 'unread-label', linkId: 'inbox', providerLabelId: 'UNREAD' },
    ],
  });
});
afterEach(() => client.clear());

describe('external archive disposition', () => {
  it.each(['queued', 'committed', 'failed'] as const)(
    'retains the optimistic thread until a %s archive can be reconciled',
    async (disposition) => {
      const key = emailKeys.threadMessages('thread').queryKey;
      client.setQueryData(key, {
        pages: [{ inbox_visible: true }],
        pageParams: [0],
      });
      const invalidate = vi.spyOn(client, 'invalidateQueries');
      await trackExternalThreadArchive(
        'thread',
        disposition === 'failed'
          ? Promise.reject(new Error('archive failed'))
          : Promise.resolve(disposition)
      );
      expect(
        client.getQueryData<{ pages: { inbox_visible: boolean }[] }>(key)
          ?.pages[0].inbox_visible
      ).toBe(disposition === 'failed');
      expect(invalidate).toHaveBeenCalledTimes(
        disposition === 'queued' ? 0 : 2
      );
    }
  );
});

describe('email read state with GraphQL Soup', () => {
  it.each([
    { read: true, graphql: true },
    { read: false, graphql: true },
    { read: true, graphql: false },
    { read: false, graphql: false },
  ])(
    'propagates isRead=$read before the request settles (GraphQL=$graphql)',
    async ({ read, graphql }) => {
      mocks.graphqlEnabled = graphql;
      const folderKeys = ['spam', 'trash'].map(
        (emailView) =>
          soupKeys.astItems({
            params: {},
            body: { emailView },
            transport: 'rest',
          }).queryKey
      );
      const allKey = soupKeys.astItems({
        params: {},
        body: { emailView: 'all' },
      }).queryKey;
      for (const key of [...folderKeys, allKey])
        client.setQueryData(key, { pages: [] });
      let finish!: () => void;
      const network = new Promise<void>((resolve) => {
        finish = resolve;
      });
      const restRequest = read ? mocks.markSeen : mocks.updateLabel;
      restRequest.mockImplementation(async () => {
        await network;
        return ok(undefined);
      });
      // The call supplies variables; the shared registry supplies the optimistic fields.
      mocks.graphqlMutation.mockReturnValue({
        toPromise: async () => {
          await network;
          return {
            data: read
              ? { markEmailThreadSeen: { id: 'thread', isRead: true } }
              : { markEmailThreadUnread: { id: 'thread', isRead: false } },
          };
        },
      });
      const mutation = mountEmailMutation(
        read ? useMarkThreadAsSeenMutation : useMarkThreadAsUnreadMutation,
        client
      );
      const result = mutation.mutateAsync({
        threadId: 'thread',
        linkId: 'inbox',
      });
      try {
        await vi.waitFor(() =>
          expect(
            graphql ? mocks.graphqlMutation : restRequest
          ).toHaveBeenCalledOnce()
        );
        expect(mutation.isPending).toBe(true);
        if (graphql) {
          const [document, variables] = mocks.graphqlMutation.mock.calls[0];
          expect(document).toBe(
            read ? MarkEmailThreadSeenDocument : MarkEmailThreadUnreadDocument
          );
          expect(variables).toEqual({
            input: { threadId: 'thread' },
          });
          expect(
            hasReadPatch(
              predictOptimisticMutation(
                soupOptimisticResolvers,
                document,
                variables
              )?.response,
              read
            ),
            'A legacy Soup patch does not update GraphqlSoupEmailThread.isRead'
          ).toBe(true);
          expect(restRequest).not.toHaveBeenCalled();
          expect(mocks.legacyPatch).not.toHaveBeenCalled();
        } else {
          expect(mocks.graphqlMutation).not.toHaveBeenCalled();
          expect(mocks.legacyPatch).toHaveBeenCalledWith(
            expect.objectContaining({
              tag: 'emailThread',
              data: { id: 'thread', isRead: read },
            })
          );
        }
        expect(mocks.refresh).not.toHaveBeenCalled();
      } finally {
        finish();
        await result;
      }
      // Shared-cache lists stay local; isolated folder previews need a new read.
      expect(mocks.refresh).not.toHaveBeenCalled();
      for (const key of folderKeys)
        expect(client.getQueryState(key)?.isInvalidated).toBe(true);
      expect(client.getQueryState(allKey)?.isInvalidated).toBe(false);
    }
  );

  it.each(['missing', 'stale'] as const)(
    'starts unread optimism without fetching %s labels',
    async (labelsState) => {
      if (labelsState === 'missing') {
        client.removeQueries({ queryKey: emailKeys.labels.queryKey });
      } else {
        client.setQueryData(
          emailKeys.labels.queryKey,
          { labels: [] },
          {
            updatedAt: Date.now() - 10 * 60 * 1000,
          }
        );
      }
      let finish!: () => void;
      const network = new Promise<void>((resolve) => {
        finish = resolve;
      });
      // A label request would block forever. The GraphQL path must not need it.
      mocks.getLabels.mockReturnValue(new Promise(() => {}));
      mocks.graphqlMutation.mockReturnValue({
        toPromise: async () => {
          await network;
          return {
            data: { markEmailThreadUnread: { id: 'thread', isRead: false } },
          };
        },
      });
      const mutation = mountEmailMutation(
        useMarkThreadAsUnreadMutation,
        client
      );
      const result = mutation.mutateAsync({
        threadId: 'thread',
        linkId: 'secondary-inbox',
      });
      try {
        await vi.waitFor(() =>
          expect(mocks.graphqlMutation).toHaveBeenCalledOnce()
        );
        const [document, variables] = mocks.graphqlMutation.mock.calls[0];
        expect(document).toBe(MarkEmailThreadUnreadDocument);
        expect(variables).toEqual({ input: { threadId: 'thread' } });
        expect(
          hasReadPatch(
            predictOptimisticMutation(
              soupOptimisticResolvers,
              document,
              variables
            )?.response,
            false
          )
        ).toBe(true);
        expect(mutation.isPending).toBe(true);
        expect(mocks.getLabels).not.toHaveBeenCalled();
        expect(mocks.legacyPatch).not.toHaveBeenCalled();
        expect(mocks.refresh).not.toHaveBeenCalled();
      } finally {
        finish();
        await result;
      }
      expect(mocks.refresh).not.toHaveBeenCalled();
    }
  );

  it.each([useMarkThreadAsSeenMutation, useMarkThreadAsUnreadMutation])(
    'refreshes lists only without the normalized cache',
    async (useMutation) => {
      mocks.cacheEnabled = false;
      mocks.graphqlMutation.mockReturnValue({
        toPromise: async () => ({
          data: {
            markEmailThreadSeen: { id: 'thread', isRead: true },
            markEmailThreadUnread: { id: 'thread', isRead: false },
          },
        }),
      });
      const mutation = mountEmailMutation(useMutation, client);
      await mutation.mutateAsync({ threadId: 'thread' });
      expect(mocks.refresh).toHaveBeenCalledOnce();
    }
  );

  it.each([useMarkThreadAsSeenMutation, useMarkThreadAsUnreadMutation])(
    'queues an offline write that reads only unmaintained lists on replay',
    async (useMutation) => {
      const variables = { input: { initial: { limit: 50 } } };
      const grouped = { input: { initial: { limit: 20 } } };
      const unregisterMaintained = registerGraphqlSoupRevalidations(
        () => [{ document: SoupDocument, variables }],
        undefined,
        () => true
      );
      const unregisterGrouped = registerGraphqlSoupRevalidations(() => [
        { document: SoupDocument, variables: grouped },
      ]);
      mocks.graphqlMutation.mockReturnValue({
        toPromise: async () => ({
          extensions: {
            normalizedCacheMutationDisposition: {
              kind: 'queued',
              transactionId: 'tx',
            },
          },
        }),
      });
      try {
        const mutation = mountEmailMutation(useMutation, client);
        await mutation.mutateAsync({ threadId: 'thread' });
        // Replay commits the record, which the maintained list reads; only
        // the list the cache cannot keep current is read again.
        expect(
          mocks.graphqlMutation.mock.calls[0][2].optimisticMutation
            .revalidations
        ).toEqual([{ document: SoupDocument, variables: grouped }]);
        expect(mocks.refresh).not.toHaveBeenCalled();
        expect(mocks.markSeen).not.toHaveBeenCalled();
      } finally {
        unregisterMaintained();
        unregisterGrouped();
      }
    }
  );
});

describe('row-open email read operation', () => {
  it('patches the REST row synchronously, preserves inbox targeting and refreshes only the failed thread', async () => {
    mocks.graphqlEnabled = false;
    const folderKey = soupKeys.astItems({
      params: {},
      body: { emailView: 'spam' },
      transport: 'rest',
    }).queryKey;
    const allKey = soupKeys.astItems({
      params: {},
      body: { emailView: 'all' },
    }).queryKey;
    client.setQueryData(folderKey, { pages: [] });
    client.setQueryData(allKey, { pages: [] });
    const pending = Promise.withResolvers<ReturnType<typeof ok<void>>>();
    mocks.markSeen.mockReturnValueOnce(pending.promise);
    const request = markEmailThreadSeen({
      threadId: 'thread',
      linkId: 'secondary-inbox',
    });
    expect(mocks.legacyPatch).toHaveBeenCalledExactlyOnceWith({
      tag: 'emailThread',
      data: { id: 'thread', isRead: true },
      frecency_score: 0,
    });
    expect(mocks.markSeen).toHaveBeenCalledExactlyOnceWith(
      { thread_id: 'thread' },
      'secondary-inbox'
    );
    pending.resolve(ok(undefined));
    await request;
    expect(mocks.refetch).not.toHaveBeenCalled();
    expect(client.getQueryState(folderKey)?.isInvalidated).toBe(true);
    expect(client.getQueryState(allKey)?.isInvalidated).toBe(false);

    client.setQueryData(folderKey, { pages: [] });
    mocks.markSeen.mockResolvedValueOnce(
      err([{ code: 'NETWORK', message: 'offline' }])
    );
    await expect(
      markEmailThreadSeen({ threadId: 'thread', linkId: 'secondary-inbox' })
    ).rejects.toThrow('offline');
    expect(mocks.refetch).toHaveBeenCalledExactlyOnceWith(
      'thread',
      'emailThread'
    );
    expect(client.getQueryState(folderKey)?.isInvalidated).toBe(true);
    expect(client.getQueryState(allKey)?.isInvalidated).toBe(false);
  });
});