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.

5.4 KB
Raw Blame
import {
  clause,
  compileClause,
  compileFacets,
  confine,
  type FacetClause,
  type FacetSelection,
  mergeAst,
  NIL_UUID,
  type TargetExpr,
} from '@app/features/soup/filters';
import type { SoupAstBody, SoupAstItemsQueryArgs } from '@queries/soup/items';
import { startOfDay, subWeeks } from 'date-fns';
import { match } from 'ts-pattern';
import { HOME_FACETS, type HomeFacetContext } from '../home-facets';
import type { HomeTab } from '../types';

export type HomeQueryCapabilities = {
  calendar: boolean;
  foreignEntities: boolean;
  notifiedSort: boolean;
  snippets: boolean;
};

function documentClause(
  expressions: TargetExpr[],
  capabilities: HomeQueryCapabilities
): TargetExpr {
  if (capabilities.snippets) return clause.and(...expressions);

  return clause.and(
    ...expressions,
    clause.not(clause.eq('subType', 'snippet'))
  );
}

function signalClause(
  capabilities: HomeQueryCapabilities,
  now: Date,
  userId: string | undefined
): FacetClause {
  const recent = subWeeks(startOfDay(now), 2).toISOString();

  const filters: FacetClause = {
    df: documentClause(
      [
        clause.eq('documentDone', false),
        clause.eq('documentUpdatedAt', { gte: recent }),
      ],
      capabilities
    ),
    ef: clause.and(
      clause.eq('emailDone', false),
      clause.eq('emailImportance', true),
      clause.eq('emailUpdatedAt', { gte: recent }),
      clause.eq('emailShared', 'exclude')
    ),
    chanf: clause.and(
      clause.eq('channelDone', false),
      clause.eq('channelIsParticipant', true)
    ),
    // Participant only accepts `macro|` user ids, so an unknown viewer
    // matches no threads instead of sending a placeholder id.
    cthf: clause.and(
      clause.eq('channelThreadDone', false),
      userId
        ? clause.eq('channelThreadParticipantId', userId)
        : clause.eq('channelThreadId', NIL_UUID)
    ),
    cf: clause.and(
      clause.eq('chatDone', false),
      clause.eq('chatUpdatedAt', { gte: recent })
    ),
    pf: clause.and(
      clause.eq('folderDone', false),
      clause.eq('folderUpdatedAt', { gte: recent })
    ),
    // Projects with a not-done notification (an access request, a
    // discussion). Off by default server-side, so this literal is also what
    // opts them into the feed.
    if: clause.eq('initiativeDone', false),
  };

  if (capabilities.foreignEntities) {
    filters.fef = clause.and(
      clause.eq('foreignEntitySource', 'github_pull_request'),
      clause.eq('foreignEntityDone', false),
      clause.eq('foreignEntityIncludesMe', true)
    );
  }

  if (capabilities.calendar) {
    filters.calf = clause.eq('calendarEventDone', false);
  }

  return confine(filters);
}

function noiseClause(): FacetClause {
  return confine({
    ef: clause.and(
      clause.eq('emailDone', false),
      clause.eq('emailImportance', false),
      clause.eq('emailShared', 'exclude')
    ),
  });
}

function tabClause(
  tab: HomeTab,
  capabilities: HomeQueryCapabilities,
  now: Date,
  userId: string | undefined
): FacetClause {
  return match(tab)
    .with('signal', () => signalClause(capabilities, now, userId))
    .with('noise', noiseClause)
    .exhaustive(() => signalClause(capabilities, now, userId));
}

export type HomeViewContext = {
  tab: HomeTab;
  facets: FacetSelection;
  facetContext: HomeFacetContext;
  capabilities: HomeQueryCapabilities;
  userId: string | undefined;
};

/**
 * Signal and Noise are notification feeds: a row belongs where its latest
 * notification puts it, not where its content's last edit does — a comment
 * on a week-old task is today's news.
 */
export const homeTabIsNotificationFeed = (tab: HomeTab): boolean =>
  tab === 'signal' || tab === 'noise';

/**
 * Whether to ask the server to sort (and, being a sort-as-filter, restrict)
 * these tabs by the viewer's latest notification. Gated behind a flag: the
 * candidate query is costly. Client-side date bucketing is not gated on it —
 * see `homeGroupTimestamp` — so a live notification still re-buckets its row
 * even while the server keeps sorting by content recency.
 */
export const homeTabOrdersByNotification = (
  context: Pick<HomeViewContext, 'tab' | 'capabilities'>
): boolean =>
  context.capabilities.notifiedSort && homeTabIsNotificationFeed(context.tab);

/** Builds the heterogeneous Soup AST for the composable Home view. */
export function buildHomeQuery(
  context: HomeViewContext,
  options: { now?: Date } = {}
): SoupAstItemsQueryArgs {
  const base = compileClause(
    tabClause(
      context.tab,
      context.capabilities,
      options.now ?? new Date(),
      context.userId
    )
  );
  const refinements = compileFacets(
    context.facets,
    HOME_FACETS,
    context.facetContext
  );
  const body: SoupAstBody = mergeAst(base, refinements);

  // Type facets exclude entity targets by nil-filling their ids; projects are
  // opt-in instead, so a type selection without them drops their clause, and
  // so does Noise, which lists emails only: a facet's own project clause
  // would otherwise be the opt-in.
  const types = context.facets.type ?? [];
  if (
    context.tab === 'noise' ||
    (types.length > 0 && !types.includes('initiatives'))
  ) {
    delete body.if;
  }

  if (context.tab === 'signal' || context.tab === 'noise') {
    body.emailView = 'inbox';
  }

  return {
    params: {
      expand: true,
      limit: 100,
      sort_method: homeTabOrdersByNotification(context)
        ? 'notified_at'
        : 'updated_at',
      sort_direction: 'desc',
    },
    body,
  };
}