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.

7.5 KB
Raw Blame
import { fireAndForget } from '@core/util/fireAndForget';
import { refreshSharedAccess } from '@queries/access-requests/requests';
import { calendarKeys } from '@queries/calendar/keys';
import { queryClient } from '@queries/client';
import { emailKeys } from '@queries/email/keys';
import { invalidateEmailLinks } from '@queries/email/link';
import { messageKeys } from '@queries/messages/keys';
import { invalidateEntityNotifications } from '@queries/notification/user-notifications';
import { refreshEmailFollowup } from '@queries/reminders/email-refresh';
import {
  invalidateSoupEntity,
  refetchSoupEntity,
} from '@queries/soup/normalized-cache';
import { teamKeys } from '@queries/team/keys';
import { onCleanup } from 'solid-js';
import { match, P } from 'ts-pattern';
import { shareEntity } from '../access-requests/core/types';
import { scheduledActionKeys } from '../routines/queries/keys';
import type { NotificationSource } from './notification-source';
import type { UnifiedNotification } from './types';

function refreshSoupEntity(
  notification: UnifiedNotification,
  entityType: Parameters<typeof refetchSoupEntity>[1]
) {
  fireAndForget(
    refetchSoupEntity(notification.entity_id, entityType),
    'notifications'
  );
  invalidateSoupEntity(notification.entity_id);
  fireAndForget(
    invalidateEntityNotifications(notification.entity_id),
    'notifications'
  );
}

function refreshChannel(
  notification: UnifiedNotification,
  threadId?: string | null
) {
  refreshSoupEntity(notification, 'channel');

  if (!threadId) return;

  fireAndForget(refetchSoupEntity(threadId, 'channelThread'), 'notifications');
  invalidateSoupEntity(threadId);
  fireAndForget(invalidateEntityNotifications(threadId), 'notifications');
}

function refreshEmailThread(notification: UnifiedNotification) {
  fireAndForget(
    refetchSoupEntity(notification.entity_id, 'emailThread'),
    'notifications'
  );
  invalidateSoupEntity(notification.entity_id);
  queryClient.invalidateQueries({
    queryKey: emailKeys.threadMessages(notification.entity_id).queryKey,
  });
}

async function refreshDeliveredEmailReminder(threadId: string) {
  try {
    await refreshEmailFollowup(threadId);
  } catch (error) {
    console.warn('Failed to refresh delivered email reminder', error);
  }
}

/**
 * Applies domain cache updates for a connection-gateway notification.
 *
 * Known notification types are handled explicitly. Unknown types are ignored
 * so a newer backend cannot break clients that have not added support yet.
 */
export function handleNotificationUpdate(notification: UnifiedNotification) {
  match(notification.notification_metadata)
    .with(
      { tag: P.union('entity_access_requested', 'entity_access_granted') },
      () => {
        const entity = shareEntity(
          notification.entity_type,
          notification.entity_id
        );
        if (entity) refreshSharedAccess(entity);
      }
    )
    .with(
      { tag: 'channel_mention' },
      { tag: 'channel_message_reaction' },
      ({ content }) => {
        refreshChannel(
          notification,
          (content.threadId ?? content.messageId)?.toString()
        );
      }
    )
    .with({ tag: 'document_mention' }, ({ content }) => {
      refreshChannel(notification, content.threadId?.toString());
    })
    .with({ tag: 'mentioned_in_document_comment' }, () => {
      refreshSoupEntity(notification, 'document');
    })
    .with({ tag: 'replied_to_document_comment_thread' }, () => {
      refreshSoupEntity(notification, 'document');
    })
    .with({ tag: 'initiative_discussion' }, () => {
      const parent = { type: 'initiative', id: notification.entity_id };
      for (const key of [
        messageKeys.messages,
        messageKeys.messagesByIds,
        messageKeys.threadReplies,
      ]) {
        queryClient.invalidateQueries({ queryKey: [...key._def, parent] });
      }
      fireAndForget(
        invalidateEntityNotifications(notification.entity_id),
        'notifications'
      );
    })
    .with({ tag: 'commented_on_document' }, () => {
      refreshSoupEntity(notification, 'document');
    })
    // An open event's details list the new request.
    .with({ tag: 'calendar_event_join_request' }, ({ content }) => {
      queryClient.invalidateQueries({
        queryKey: calendarKeys.joinRequests(content.eventId).queryKey,
      });
    })
    .with({ tag: 'crm_discussion' }, () => {
      const parent = {
        type: notification.entity_type,
        id: notification.entity_id,
      };
      for (const key of [
        messageKeys.messages,
        messageKeys.messagesByIds,
        messageKeys.threadReplies,
      ]) {
        queryClient.invalidateQueries({ queryKey: [...key._def, parent] });
      }
      fireAndForget(
        invalidateEntityNotifications(notification.entity_id),
        'notifications'
      );
    })
    .with(
      { tag: 'channel_invite' },
      { tag: 'channel_access_requested' },
      () => {
        refreshChannel(notification);
      }
    )
    .with({ tag: 'channel_message_send' }, () => {
      refreshChannel(notification);
    })
    .with({ tag: 'channel_message_reply' }, ({ content }) => {
      refreshChannel(notification, content.threadId?.toString());
    })
    .with({ tag: 'call_started' }, () => {
      refreshChannel(notification);
    })
    // DSS's `external_chat_changed` push already refreshes what an open page shows.
    .with({ tag: 'external_chat_message' }, () => {})
    .with({ tag: 'new_email' }, () => {
      refreshEmailThread(notification);
    })
    .with({ tag: 'reminder' }, () => {
      if (notification.entity_type !== 'email_thread') return;
      fireAndForget(
        refreshDeliveredEmailReminder(notification.entity_id),
        'notifications'
      );
    })
    .with({ tag: 'inbox_reauth_required' }, () => {
      invalidateEmailLinks();
    })
    .with({ tag: 'routine_run_finished' }, () => {
      queryClient.invalidateQueries({
        queryKey: scheduledActionKeys.list.queryKey,
      });
    })
    .with({ tag: 'invite_to_team' }, () => {
      queryClient.invalidateQueries({
        queryKey: teamKeys.userInvites.queryKey,
      });
    })
    .with({ tag: 'task_assigned' }, () => {
      refreshSoupEntity(notification, 'document');
    })
    .with({ tag: 'ai_response' }, () => {
      refreshSoupEntity(notification, 'chat');
    })
    .with({ tag: 'github_pr_status_changed' }, () => {
      refreshSoupEntity(notification, 'foreignEntity');
    })
    .with({ tag: 'github_pr_check_run' }, () => {
      refreshSoupEntity(notification, 'foreignEntity');
    })
    .with({ tag: 'github_review_requested' }, () => {
      refreshSoupEntity(notification, 'foreignEntity');
    })
    .with({ tag: 'github_pr_comment' }, () => {
      refreshSoupEntity(notification, 'foreignEntity');
    })
    .with({ tag: 'github_pr_mention' }, () => {
      refreshSoupEntity(notification, 'foreignEntity');
    })
    .with({ tag: 'github_pr_review' }, () => {
      refreshSoupEntity(notification, 'foreignEntity');
    })
    .with(
      {
        tag: P.union(
          'agent_session_settled',
          'agent_session_waiting_for_input',
          'agent_session_mentioned'
        ),
      },
      () => {
        refreshSoupEntity(notification, 'agentSession');
      }
    )
    .otherwise(() => {
      // Ignore notification types introduced by a newer backend.
    });
}

/** Subscribe globally to notification-driven domain cache updates. */
export function useNotificationUpdates(notificationSource: NotificationSource) {
  const unsubscribe = notificationSource.subscribe(handleNotificationUpdate);
  onCleanup(unsubscribe);
}