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.

15.6 KB
Raw Blame
import type { QueryRevalidation } from '@graphql-cache/exchange/optimistic';
import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
import { queryClient } from '@queries/client';
import { type Client, gql } from '@urql/core';
import { describe, expect, it, onTestFinished, vi } from 'vitest';
import { soupKeys } from '../keys';
import { refreshPropertyQueries } from '../property-queries';

import {
  getActiveGraphqlSoupRevalidations,
  refreshActiveGraphqlSoupQueries,
  registerActiveGraphqlSoupQuery,
  registerGraphqlSoupRevalidations,
} from './active-queries';

vi.mock('@queries/client', async () => {
  const { QueryClient } = await import('@tanstack/solid-query');
  return { queryClient: new QueryClient() };
});

function register(query: Parameters<typeof registerActiveGraphqlSoupQuery>[0]) {
  const unregister = registerActiveGraphqlSoupQuery(query);
  onTestFinished(unregister);
  return unregister;
}

describe('active GraphQL Soup queries', () => {
  it('snapshots and deduplicates live descriptors, excluding disabled and unmounted readers', () => {
    const document = gql`query Soup($input: SoupInput!) { soup(input: $input) { nextCursor } }`;
    const initial = { document, variables: { input: { initial: {} } } };
    const continuation = { document, variables: { input: { cursor: 'next' } } };
    let enabled = true;
    let pages: QueryRevalidation[] = [initial];
    const unregister = registerGraphqlSoupRevalidations(() =>
      enabled ? pages : []
    );
    const unregisterDuplicate = registerGraphqlSoupRevalidations(() => [
      initial,
    ]);
    onTestFinished(unregister);
    onTestFinished(unregisterDuplicate);

    expect(getActiveGraphqlSoupRevalidations()).toEqual([initial]);
    pages = [initial, continuation];
    expect(getActiveGraphqlSoupRevalidations()).toEqual([
      initial,
      continuation,
    ]);
    enabled = false;
    expect(getActiveGraphqlSoupRevalidations()).toEqual([initial]);
    unregisterDuplicate();
    expect(getActiveGraphqlSoupRevalidations()).toEqual([]);
    enabled = true;
    unregister();
    expect(getActiveGraphqlSoupRevalidations()).toEqual([]);
  });

  it('keeps channel descriptors scoped to the owning client before deduplication', () => {
    const first = { query: vi.fn() } as unknown as Client;
    const second = { query: vi.fn() } as unknown as Client;
    const descriptor = { document: gql`query Channel { id }`, variables: {} };
    onTestFinished(
      registerGraphqlSoupRevalidations(
        () => [descriptor],
        () => first
      )
    );
    expect(getActiveGraphqlSoupRevalidations(first)).toEqual([descriptor]);
    expect(getActiveGraphqlSoupRevalidations(second)).toEqual([]);
    onTestFinished(
      registerGraphqlSoupRevalidations(
        () => [descriptor],
        () => second
      )
    );
    expect(getActiveGraphqlSoupRevalidations(second)).toEqual([descriptor]);
    expect(getActiveGraphqlSoupRevalidations()).toEqual([descriptor]);
  });

  it('excludes targeted detail readers from generic Soup refreshes', async () => {
    const list = vi.fn(async () => {});
    const detail = vi.fn(async () => {
      throw new Error('must not refresh');
    });
    register({ isEnabled: () => true, refresh: list });
    register({
      isEnabled: () => true,
      refresh: detail,
      target: () => ({ kind: 'email-archive', threadId: 'thread-1' }),
    });
    await refreshActiveGraphqlSoupQueries({ throwOnError: true });
    expect(list).toHaveBeenCalledOnce();
    expect(detail).not.toHaveBeenCalled();
  });

  it('refreshes only a matching detail target, while preserving list refreshes', async () => {
    const list = vi.fn(async () => {});
    const first = vi.fn(async () => {});
    const second = vi.fn(async () => {});
    let firstId = 'first';
    register({ isEnabled: () => true, refresh: list });
    register({
      isEnabled: () => true,
      refresh: first,
      target: () => ({ kind: 'email-archive', threadId: firstId }),
    });
    register({
      isEnabled: () => true,
      refresh: second,
      target: () => ({ kind: 'email-archive', threadId: 'second' }),
    });
    await refreshActiveGraphqlSoupQueries({
      throwOnError: true,
      target: { kind: 'email-archive', threadId: 'first' },
    });
    expect(list).toHaveBeenCalledOnce();
    expect(first).toHaveBeenCalledOnce();
    expect(second).not.toHaveBeenCalled();
    firstId = 'moved';
    await refreshActiveGraphqlSoupQueries({
      throwOnError: true,
      target: { kind: 'email-archive', threadId: 'first' },
    });
    expect(first).toHaveBeenCalledOnce();
    expect(list).toHaveBeenCalledTimes(2);
  });

  it('coalesces refreshes requested while one is in flight into one follow-up', async () => {
    const settle: Array<() => void> = [];
    const refresh = vi.fn(
      () => new Promise<void>((resolve) => settle.push(resolve))
    );
    register({ isEnabled: () => true, refresh });
    const first = refreshActiveGraphqlSoupQueries();
    const second = refreshActiveGraphqlSoupQueries();
    const third = refreshActiveGraphqlSoupQueries();
    expect(refresh).toHaveBeenCalledOnce();
    settle[0]!();
    await first;
    await vi.waitFor(() => expect(refresh).toHaveBeenCalledTimes(2));
    settle[1]!();
    await Promise.all([second, third]);
    expect(refresh).toHaveBeenCalledTimes(2);
    const fourth = refreshActiveGraphqlSoupQueries();
    expect(refresh).toHaveBeenCalledTimes(3);
    settle[2]!();
    await fourth;
  });

  it('strict revalidation fails until every enabled reader succeeds', async () => {
    const consoleError = vi
      .spyOn(console, 'error')
      .mockImplementation(() => {});
    onTestFinished(() => consoleError.mockRestore());
    const failure = vi
      .fn()
      .mockRejectedValueOnce(new Error('offline'))
      .mockResolvedValue(undefined);
    const success = vi.fn(async () => undefined);
    register({ isEnabled: () => true, refresh: failure });
    register({ isEnabled: () => true, refresh: success });
    await expect(
      refreshActiveGraphqlSoupQueries({ throwOnError: true })
    ).rejects.toThrow('every active query');
    expect(success).toHaveBeenCalledOnce();
    await expect(
      refreshActiveGraphqlSoupQueries({ throwOnError: true })
    ).resolves.toBeUndefined();
    expect(success).toHaveBeenCalledTimes(2);
  });

  it('strict revalidation ignores disabled readers', async () => {
    const disabled = vi.fn(async () => {
      throw new Error('must not run');
    });
    register({ isEnabled: () => false, refresh: disabled });
    await expect(
      refreshActiveGraphqlSoupQueries({ throwOnError: true })
    ).resolves.toBeUndefined();
    expect(disabled).not.toHaveBeenCalled();
  });

  it('does not claim success for a reader registered during a refresh', async () => {
    let finish!: () => void;
    const firstPass = new Promise<void>((resolve) => {
      finish = resolve;
    });
    register({ isEnabled: () => true, refresh: () => firstPass });
    const refreshed = expect(
      refreshActiveGraphqlSoupQueries({ throwOnError: true })
    ).rejects.toThrow('every active query');
    const newReader = vi.fn(async () => undefined);
    register({ isEnabled: () => true, refresh: newReader });
    finish();
    await refreshed;
    expect(newReader).not.toHaveBeenCalled();
    await expect(
      refreshActiveGraphqlSoupQueries({ throwOnError: true })
    ).resolves.toBeUndefined();
    expect(newReader).toHaveBeenCalledOnce();
  });

  it('a failing reader which unmounts no longer blocks strict completion', async () => {
    const consoleError = vi
      .spyOn(console, 'error')
      .mockImplementation(() => {});
    onTestFinished(() => consoleError.mockRestore());
    let fail!: (error: Error) => void;
    const pending = new Promise<void>((_resolve, reject) => {
      fail = reject;
    });
    const unregister = register({
      isEnabled: () => true,
      refresh: () => pending,
    });
    const result = refreshActiveGraphqlSoupQueries({ throwOnError: true });
    unregister();
    fail(new Error('unmounted'));
    await expect(result).resolves.toBeUndefined();
  });

  it('refreshes only enabled registered queries', async () => {
    const enabledRefresh = vi.fn(async () => undefined);
    const disabledRefresh = vi.fn(async () => undefined);
    const unregisterEnabled = registerActiveGraphqlSoupQuery({
      isEnabled: () => true,
      refresh: enabledRefresh,
    });
    const unregisterDisabled = registerActiveGraphqlSoupQuery({
      isEnabled: () => false,
      refresh: disabledRefresh,
    });

    await refreshActiveGraphqlSoupQueries();

    expect(enabledRefresh).toHaveBeenCalledOnce();
    expect(disabledRefresh).not.toHaveBeenCalled();

    unregisterEnabled();
    unregisterDisabled();
  });

  it('stops refreshing a query after it unregisters', async () => {
    const refresh = vi.fn(async () => undefined);
    const unregister = registerActiveGraphqlSoupQuery({
      isEnabled: () => true,
      refresh,
    });
    unregister();

    await refreshActiveGraphqlSoupQueries();

    expect(refresh).not.toHaveBeenCalled();
  });

  it('isolates refresh failures so other active queries still refresh', async () => {
    const error = new Error('refresh failed');
    const consoleError = vi
      .spyOn(console, 'error')
      .mockImplementation(() => {});
    const unregisterFailure = registerActiveGraphqlSoupQuery({
      isEnabled: () => true,
      refresh: vi.fn(async () => {
        throw error;
      }),
    });
    const successfulRefresh = vi.fn(async () => undefined);
    const unregisterSuccess = registerActiveGraphqlSoupQuery({
      isEnabled: () => true,
      refresh: successfulRefresh,
    });

    await refreshActiveGraphqlSoupQueries();

    expect(successfulRefresh).toHaveBeenCalledOnce();
    expect(consoleError).toHaveBeenCalledWith(
      '[graphql-soup] failed to refresh active query',
      error
    );

    unregisterFailure();
    unregisterSuccess();
    consoleError.mockRestore();
  });
  it('limits a scoped refresh to readers whose filter body matches', async () => {
    const scoped = vi.fn(async () => {});
    const other = vi.fn(async () => {});
    const unbodied = vi.fn(async () => {});
    register({
      isEnabled: () => true,
      refresh: scoped,
      body: () => ({ crma: { company: 'c' } }),
    });
    register({ isEnabled: () => true, refresh: other, body: () => ({}) });
    register({ isEnabled: () => true, refresh: unbodied });

    await refreshActiveGraphqlSoupQueries({
      where: (body) =>
        typeof body === 'object' && body !== null && 'crma' in body,
    });
    expect(scoped).toHaveBeenCalledOnce();
    expect(other).not.toHaveBeenCalled();
    expect(unbodied).not.toHaveBeenCalled();
  });

  it('skips lists the cache maintains when only the others need a read', async () => {
    const maintained = vi.fn(async () => {});
    const grouped = vi.fn(async () => {});
    let current = true;
    register({
      isEnabled: () => true,
      refresh: maintained,
      cacheMaintained: () => current,
    });
    register({ isEnabled: () => true, refresh: grouped });

    await refreshActiveGraphqlSoupQueries({ unmaintainedOnly: true });
    expect(maintained).not.toHaveBeenCalled();
    expect(grouped).toHaveBeenCalledOnce();

    // A list whose local evaluation stopped working reads the server again.
    current = false;
    await refreshActiveGraphqlSoupQueries({ unmaintainedOnly: true });
    expect(maintained).toHaveBeenCalledOnce();

    // Without the option every list is read, as for writes the cache lacks.
    current = true;
    await refreshActiveGraphqlSoupQueries();
    expect(maintained).toHaveBeenCalledTimes(2);
  });

  it('leaves maintained pages out of the revalidations a write carries', () => {
    const document = gql`query Soup($input: SoupInput!) { soup(input: $input) { nextCursor } }`;
    const mail = { document, variables: { input: { initial: { mail: 1 } } } };
    const grouped = { document, variables: { input: { initial: { g: 1 } } } };
    onTestFinished(
      registerGraphqlSoupRevalidations(
        () => [mail],
        undefined,
        () => true
      )
    );
    onTestFinished(registerGraphqlSoupRevalidations(() => [grouped]));

    expect(
      getActiveGraphqlSoupRevalidations(undefined, { unmaintainedOnly: true })
    ).toEqual([grouped]);
    expect(getActiveGraphqlSoupRevalidations()).toEqual([mail, grouped]);
  });
});

it.each([undefined, SYSTEM_PROPERTY_IDS.DUE_DATE])(
  'refreshes due-date sorting without a property filter after a date edit (%s)',
  async (definitionId) => {
    onTestFinished(() => queryClient.clear());
    const dueKey = soupKeys.astItems({
      params: {
        sort_method: 'property',
        sort_property_definition_id: SYSTEM_PROPERTY_IDS.DUE_DATE,
      },
      body: { df: { l: { dst: 'task' } } },
    }).queryKey;
    const ordinaryKey = soupKeys.astItems({
      params: { sort_method: 'updated_at' },
      body: { df: { l: { dst: 'task' } } },
    }).queryKey;
    queryClient.setQueryData(dueKey, []);
    queryClient.setQueryData(ordinaryKey, []);
    const dueRefresh = vi.fn(async () => {});
    const ordinaryRefresh = vi.fn(async () => {});
    register({
      isEnabled: () => true,
      refresh: dueRefresh,
      body: () => ({
        params: {
          sort_method: 'property',
          sort_property_definition_id: SYSTEM_PROPERTY_IDS.DUE_DATE,
        },
      }),
    });
    register({
      isEnabled: () => true,
      refresh: ordinaryRefresh,
      body: () => ({ params: { sort_method: 'updated_at' } }),
    });

    await refreshPropertyQueries(definitionId);

    expect(queryClient.getQueryState(dueKey)?.isInvalidated).toBe(true);
    expect(queryClient.getQueryState(ordinaryKey)?.isInvalidated).toBe(false);
    expect(dueRefresh).toHaveBeenCalledOnce();
    expect(ordinaryRefresh).not.toHaveBeenCalled();
  }
);

it('matches selected sort/group definitions and date predicates, not ordinary option filters', async () => {
  onTestFinished(() => queryClient.clear());
  const id = SYSTEM_PROPERTY_IDS.STATUS;
  const matching = [
    { params: { sort_method: 'property', sort_property_definition_id: id } },
    { initial: { sortMethod: 'PROPERTY', sortPropertyDefinitionId: id } },
    { groupBy: { type: 'property', propertyDefinitionId: id } },
    { initial: { groupBy: { field: 'PROPERTY', propertyDefinitionId: id } } },
    { params: { group_by: { property: { property_definition_id: id } } } },
    { propf: { '!': { l: { pd: id, v: { dr: {} } } } } },
    { propf: { l: { pd: id, v: { dr: { start: '2026-01-01T00:00:00Z' } } } } },
    {
      filters: {
        propertiesFilter: {
          not: {
            literal: { propertyDefinitionId: id, value: { dateRange: {} } },
          },
        },
      },
    },
  ].map((body) => {
    const refresh = vi.fn(async () => {});
    register({ isEnabled: () => true, refresh, body: () => body });
    return refresh;
  });
  const unrelated = [
    { propf: { l: { pd: id, v: { so: 'option' } } } },
    { propf: { l: { pd: id, v: { er: 'user' } } } },
    {
      params: {
        sort_method: 'property',
        sort_property_definition_id: `${id}-other`,
      },
    },
    { groupBy: { type: 'property', propertyDefinitionId: `${id}-other` } },
  ].map((body) => {
    const refresh = vi.fn(async () => {});
    register({ isEnabled: () => true, refresh, body: () => body });
    return refresh;
  });
  await refreshPropertyQueries(id);
  for (const refresh of matching) expect(refresh).toHaveBeenCalledOnce();
  for (const refresh of unrelated) expect(refresh).not.toHaveBeenCalled();
  await refreshPropertyQueries();
  expect(unrelated[2]).toHaveBeenCalledOnce();
  expect(unrelated[3]).toHaveBeenCalledOnce();
  expect(unrelated[0]).not.toHaveBeenCalled();
  expect(unrelated[1]).not.toHaveBeenCalled();
});