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.

16.5 KB
Raw Blame
import type { TaskEntityWithProperties } from '@entity/types/entity';
import type { GroupedSoupPaging } from '@queries/soup/graphql/create-grouped-soup-live-query';
import type { CreateGroupedSoupQueriesArgs } from '@queries/soup/grouped/create-grouped-soup-queries';
import { createRoot, createSignal } from 'solid-js';
import { expect, it, vi } from 'vitest';

const fixture = vi.hoisted(() => ({
  query: {} as Record<string, unknown>,
  groupQueries: new Map<string, unknown>(),
  groupArgs: undefined as CreateGroupedSoupQueriesArgs | undefined,
  calls: [] as { args: () => unknown; options?: () => unknown }[],
  searchState: vi.fn(),
  mapItem: vi.fn(),
}));
vi.mock('@queries/properties/definitions', () => ({
  useListPropertiesQuery: () => ({ isSuccess: false, data: [] }),
}));
vi.mock('@app/features/soup', async () => ({
  ...(await import('@app/features/soup/filters')),
  ...(await import('@app/features/soup/collection/rows')),
  ...(await import('@app/features/soup/collection/row-store')),
  ...(await import('@app/features/soup/collection/transforms')),
  useSearchContext: () => ({ entityPool: () => [], routinePool: () => [] }),
  createSearchState: () => {
    fixture.searchState();
    return {
      isSearching: () => false,
      usesServiceSearch: () => false,
      isSettling: () => false,
    };
  },
}));
vi.mock('@entity', async () => ({
  ...(await import('@entity/types/entity')),
  ...(await import('@entity/utils/task-properties')),
}));
vi.mock('@components/app/GlobalAppState', () => ({
  useGlobalNotificationSource: () => ({ notificationsByEntity: () => ({}) }),
}));
vi.mock('@queries/soup/transform-utils', () => ({
  mapApiSoupItemToEntity: fixture.mapItem,
}));
vi.mock('@queries/soup/items', () => ({
  useSoupAstItemsQuery: (args: () => unknown, options?: () => unknown) => {
    fixture.calls.push({ args, options });
    return fixture.query;
  },
}));
vi.mock('@queries/soup/grouped/create-grouped-soup-queries', () => ({
  createGroupedSoupQueries: (args: CreateGroupedSoupQueriesArgs) => {
    fixture.groupArgs = args;
    return { map: () => fixture.groupQueries };
  },
}));

import type { TasksTab } from '../types';
import { useTasksDataSource } from './use-tasks-query';

it('delegates grouped task pagination to the current Soup query owner', async () => {
  const [paging, setPaging] = createSignal<GroupedSoupPaging>();
  const [hasMore, setHasMore] = createSignal(true);
  const task: TaskEntityWithProperties = {
    type: 'document',
    fileType: 'md',
    id: 'task',
    name: 'Task',
    ownerId: 'viewer',
    subType: { type: 'task', is_completed: false },
    properties: [],
  };
  const fetchNextPage = vi.fn(async () => {
    setHasMore(false);
  });
  fixture.query = {
    isLoading: false,
    isPending: false,
    isPlaceholderData: false,
    get groupedPaging() {
      return paging();
    },
    data: {
      entities: [task],
      itemsById: {},
      groups: [
        {
          key: 'todo',
          label: 'To do',
          totalCount: 2,
          itemIds: [task.id],
          nextCursor: 'next',
        },
      ],
    },
  };
  // The group reader consumes the owner's live capability, not another cursor chain.
  fixture.groupQueries = new Map([
    [
      'todo',
      {
        data: () => ({ entities: [] }),
        hasNextPage: () =>
          fixture.groupArgs?.groupedPaging?.()?.hasNextPage('todo') ?? false,
        isFetchingNextPage: () => false,
        fetchNextPage: () =>
          fixture.groupArgs?.groupedPaging?.()?.fetchNextPage('todo'),
        error: () => null,
      },
    ],
  ]);
  let cleanup = () => {};
  const source = createRoot((dispose) => {
    cleanup = dispose;
    return useTasksDataSource(
      {
        tab: 'team-tasks',
        search: '',
        facets: {},
        groupBy: 'status',
        sort: [],
      },
      {
        userId: () => 'viewer',
        tagSets: () => [],
        tagSetsReady: () => true,
        isGroupExpanded: () => true,
      }
    );
  });
  try {
    expect(source.items().some((row) => row.kind === 'load-more')).toBe(false);
    setPaging({
      hasNextPage: hasMore,
      isFetchingNextPage: () => false,
      error: () => null,
      fetchNextPage,
      resetToInitialPage: () => {},
    });
    expect(source.items().some((row) => row.kind === 'load-more')).toBe(true);
    await source.loadMoreGroup('todo');
    expect(fetchNextPage).toHaveBeenCalledExactlyOnceWith('todo');
    expect(source.items().some((row) => row.kind === 'load-more')).toBe(false);
  } finally {
    cleanup();
    fixture.groupQueries = new Map();
    fixture.groupArgs = undefined;
  }
});

it('retains referenced list rows but hides stale board groups and inaccessible tasks', () => {
  const [placeholder, setPlaceholder] = createSignal(false);
  const [enabled, setEnabled] = createSignal(true);
  const task = {
    type: 'document',
    fileType: 'md',
    id: 'task',
    name: 'Task',
    ownerId: 'viewer',
    createdAt: new Date(),
    updatedAt: new Date(),
    subType: { type: 'task', is_completed: false },
    properties: [
      {
        definition: { id: 'project-definition' },
        value: {
          type: 'EntityReference',
          value: [{ entity_type: 'INITIATIVE', entity_id: 'project' }],
        },
      },
    ],
  } as unknown as TaskEntityWithProperties;
  fixture.query = {
    isLoading: false,
    get isPlaceholderData() {
      return placeholder();
    },
    data: { entities: [task] },
  };
  createRoot((dispose) => {
    try {
      const source = useTasksDataSource(
        {
          tab: 'team-tasks',
          search: '',
          facets: {},
          groupBy: 'none',
          sort: [],
        },
        {
          userId: () => 'viewer',
          tagSets: () => [],
          tagSetsReady: () => true,
          isGroupExpanded: () => true,
          reference: () => ({
            propertyDefinitionId: 'project-definition',
            entityId: 'project',
          }),
          enabled,
        }
      );
      expect(source.items()).toHaveLength(1);
      expect(source.boardRows?.()).toHaveLength(1);
      expect(source.isLoading()).toBe(false);
      setPlaceholder(true);
      expect(source.items()).toHaveLength(1);
      expect(source.boardRows?.()).toEqual([]);
      expect(source.isLoading()).toBe(false);
      setPlaceholder(false);
      setEnabled(false);
      expect(source.items()).toEqual([]);
      expect(source.boardRows?.()).toEqual([]);
      expect(source.isLoading()).toBe(false);
    } finally {
      dispose();
    }
  });
});

it.each([false, true])(
  'scopes grouped continuation rows to the referenced entity (board: %s)',
  (board) => {
    const companies = 'companies-definition';
    const task = (id: string, companyId: string) =>
      ({
        type: 'document',
        fileType: 'md',
        id,
        name: id,
        ownerId: 'viewer',
        createdAt: new Date(),
        updatedAt: new Date(),
        subType: { type: 'task', is_completed: false },
        properties: [
          {
            definition: { id: companies },
            value: {
              type: 'EntityReference',
              value: [{ entity_type: 'COMPANY', entity_id: companyId }],
            },
          },
        ],
      }) as unknown as TaskEntityWithProperties;
    fixture.query = {
      isLoading: false,
      isPlaceholderData: false,
      data: {
        entities: [],
        itemsById: {},
        groups: [
          {
            key: 'todo',
            label: 'To do',
            displayOrder: 0,
            totalCount: 2,
            itemIds: [],
            nextCursor: 'next',
          },
        ],
      },
    };
    // A "Load more" page holding one task that no longer references Acme.
    fixture.groupQueries = new Map([
      [
        'todo',
        {
          data: () => ({
            entities: [task('linked', 'acme'), task('unlinked', 'globex')],
          }),
          hasNextPage: () => false,
          isFetchingNextPage: () => false,
          fetchNextPage: async () => {},
        },
      ],
    ]);
    createRoot((dispose) => {
      try {
        const source = useTasksDataSource(
          {
            tab: 'team-tasks',
            search: '',
            facets: {},
            groupBy: 'status',
            sort: [],
          },
          {
            userId: () => 'viewer',
            tagSets: () => [],
            tagSetsReady: () => true,
            isGroupExpanded: () => !board,
            board: () => board,
            reference: () => ({
              propertyDefinitionId: companies,
              entityId: 'acme',
            }),
          }
        );
        const rows = board ? source.boardRows?.() : source.items();
        expect(
          rows?.flatMap((row) => (row.kind === 'entity' ? [row.entity.id] : []))
        ).toEqual(['linked']);
      } finally {
        dispose();
        fixture.groupQueries = new Map();
      }
    });
  }
);

it('exposes uncollapsed board rows and hides stale groups during query changes', () => {
  const [pending, setPending] = createSignal(false);
  const task: TaskEntityWithProperties = {
    type: 'document',
    fileType: 'md',
    id: 'task',
    name: 'Task',
    ownerId: 'viewer',
    subType: { type: 'task', is_completed: false },
    properties: [],
  };

  fixture.query = {
    get isPending() {
      return pending();
    },
    get isLoading() {
      return pending();
    },
    data: {
      entities: [task],
      itemsById: {},
      groups: [
        { key: 'todo', label: 'To do', totalCount: 1, itemIds: ['task'] },
      ],
    },
  };
  fixture.groupQueries = new Map();

  createRoot((dispose) => {
    try {
      const source = useTasksDataSource(
        {
          tab: 'team-tasks',
          search: '',
          facets: {},
          groupBy: 'status',
          sort: [],
        },
        {
          userId: () => 'viewer',
          tagSets: () => [],
          tagSetsReady: () => true,
          isGroupExpanded: () => false,
          board: () => true,
        }
      );

      expect(
        source.items().filter((row) => row.kind === 'entity')
      ).toHaveLength(0);
      expect(
        source.boardRows?.().filter((row) => row.kind === 'entity')
      ).toHaveLength(1);

      setPending(true);

      expect(source.boardRows?.()).toEqual([]);
      expect(source.boardLoading?.()).toBe(true);

      setPending(false);

      expect(
        source.boardRows?.().filter((row) => row.kind === 'entity')
      ).toHaveLength(1);
    } finally {
      dispose();
    }
  });
});

const COMPANIES = '00000001-0000-0000-0000-00000000000c';

function crmTask(id: string, companyIds: string[] = []) {
  return {
    type: 'document',
    fileType: 'md',
    id,
    name: id,
    ownerId: 'viewer',
    createdAt: new Date(),
    updatedAt: new Date(),
    subType: { type: 'task', is_completed: false },
    properties: companyIds.length
      ? [
          {
            definition: { id: COMPANIES },
            value: {
              type: 'EntityReference',
              value: companyIds.map((entity_id) => ({
                entity_type: 'COMPANY',
                entity_id,
              })),
            },
          },
        ]
      : [],
  } as unknown as TaskEntityWithProperties;
}

function crmSource(groupBy: 'none' | 'status' = 'none') {
  return useTasksDataSource(
    { tab: 'team-tasks', search: '', facets: {}, groupBy, sort: [] },
    {
      userId: () => 'viewer',
      tagSets: () => [],
      tagSetsReady: () => true,
      isGroupExpanded: () => true,
      crm: () => ({ type: 'company', id: 'acme' }),
    }
  );
}

it('keeps server-matched CRM tasks that only mention the record', () => {
  fixture.calls = [];
  fixture.query = {
    isLoading: false,
    isPending: false,
    isPlaceholderData: false,
    data: { entities: [crmTask('mention-only'), crmTask('linked', ['acme'])] },
  };
  createRoot((dispose) => {
    try {
      const source = crmSource();
      expect(
        source
          .items()
          .flatMap((row) => (row.kind === 'entity' ? [row.entity.id] : []))
      ).toEqual(['mention-only', 'linked']);
      const query = fixture.calls[0]?.args() as {
        body: Record<string, unknown>;
      };
      expect(query.body.crma).toEqual({ company: 'acme' });
      expect(query.body.propf).toBeUndefined();
      // The search service cannot express the scope, so it is not used.
      expect(fixture.searchState).not.toHaveBeenCalled();
    } finally {
      dispose();
    }
  });
});

it('keeps CRM continuation rows the server returned for a group', () => {
  fixture.query = {
    isLoading: false,
    isPending: false,
    isPlaceholderData: false,
    data: {
      entities: [],
      itemsById: {},
      groups: [
        {
          key: 'todo',
          label: 'To do',
          displayOrder: 0,
          totalCount: 2,
          itemIds: [],
          nextCursor: 'next',
        },
      ],
    },
  };
  fixture.groupQueries = new Map([
    [
      'todo',
      {
        data: () => ({
          entities: [crmTask('contact-mention'), crmTask('linked', ['acme'])],
        }),
        hasNextPage: () => false,
        isFetchingNextPage: () => false,
        fetchNextPage: async () => {},
      },
    ],
  ]);
  createRoot((dispose) => {
    try {
      const source = crmSource('status');
      expect(
        source
          .items()
          .flatMap((row) => (row.kind === 'entity' ? [row.entity.id] : []))
      ).toEqual(['contact-mention', 'linked']);
    } finally {
      dispose();
      fixture.groupQueries = new Map();
    }
  });
});

it('admits only optimistic CRM tasks that name the record', () => {
  fixture.calls = [];
  fixture.query = {
    isLoading: false,
    isPending: false,
    isPlaceholderData: false,
    data: { entities: [] },
  };
  createRoot((dispose) => {
    try {
      crmSource();
      const options = fixture.calls[0]?.options?.() as {
        meta: { insertFilter: (item: unknown) => boolean };
      };
      fixture.mapItem.mockReturnValueOnce(crmTask('created', ['acme']));
      expect(options.meta.insertFilter({})).toBe(true);
      fixture.mapItem.mockReturnValueOnce(crmTask('unrelated', ['globex']));
      expect(options.meta.insertFilter({})).toBe(false);
      fixture.mapItem.mockReturnValueOnce(crmTask('cached'));
      expect(options.meta.insertFilter({})).toBe(false);
    } finally {
      dispose();
    }
  });
});

it('keeps activity membership in list and grouped paging and excludes optimistic rows', () => {
  fixture.calls = [];
  fixture.query = {
    isLoading: false,
    isPending: false,
    isPlaceholderData: false,
    data: { entities: [] },
  };
  createRoot((dispose) => {
    try {
      useTasksDataSource(
        {
          tab: 'team-tasks',
          search: '',
          facets: {},
          groupBy: 'date',
          sort: [],
        },
        {
          userId: () => 'viewer',
          tagSets: () => [],
          tagSetsReady: () => true,
          isGroupExpanded: () => true,
          crm: () => ({ type: 'activity' }),
          board: () => true,
        }
      );
      const call = fixture.calls[0];
      expect(
        (call?.args() as { body: { crma: unknown } } | undefined)?.body.crma
      ).toBe('activity');
      expect(fixture.groupArgs?.soupBody().crma).toBe('activity');
      const meta = call?.options?.() as {
        meta: { insertFilter: (item: unknown) => boolean };
      };
      fixture.mapItem.mockReturnValueOnce(crmTask('linked', ['acme']));
      expect(meta.meta.insertFilter({})).toBe(false);
      expect(fixture.searchState).not.toHaveBeenCalled();
    } finally {
      dispose();
    }
  });
});

it('pauses task reads across project views and resumes when returning to tasks', () => {
  fixture.calls = [];
  fixture.query = {
    isLoading: false,
    isPending: false,
    data: { entities: [] },
  };
  createRoot((dispose) => {
    try {
      const [tab, setTab] = createSignal<TasksTab>('my-projects');
      useTasksDataSource(
        {
          get tab() {
            return tab();
          },
          search: '',
          facets: {},
          groupBy: 'none',
          sort: [],
        },
        {
          userId: () => 'viewer',
          tagSets: () => [],
          tagSetsReady: () => true,
          isGroupExpanded: () => true,
        }
      );
      const options = fixture.calls[0]?.options;
      expect(options?.()).toMatchObject({ enabled: false });
      setTab('created-projects');
      expect(options?.()).toMatchObject({ enabled: false });
      setTab('projects');
      expect(options?.()).toMatchObject({ enabled: false });
      setTab('my-tasks');
      expect(options?.()).toMatchObject({ enabled: true });
    } finally {
      dispose();
    }
  });
});