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.

12.9 KB
Raw Blame
import { fireAndForget } from '@core/util/fireAndForget';
import { Telemetry } from '@macro-inc/observability';
import type { MessageEvent } from '@service-storage/generated/schemas/messageEvent';
import type {
  Message,
  MessageListItem,
  MessageParent,
  MessageThread,
  TimelineActivity,
} from '@service-storage/messages';
import { queryClient } from '../client';
import { consumeNonce } from '../nonce';
import { MessageNonceKeys, messageKeys } from './keys';
import { normalizeMessageSender } from './message-sender';
import {
  getCachedThreadState,
  getTargetMessage,
  insertMessageIntoTargetCaches,
  patchTargetMessage,
  removeMessageFromTargetCaches,
  resolveMessageTarget,
  softInvalidateTargetCaches,
  topLevelMessageHasReplies,
} from './reconcile';
import { fetchMessageThread, getThreadRepliesQueryKey } from './thread-replies';
import {
  getMessageTimelineQueryKey,
  getMessageTimelineQueryKeyPrefix,
  insertActivitiesIntoMessageTimeline,
  invalidateMessageTimeline,
  type MessageTimelineData,
  setMessageTimelineData,
} from './timeline';
import { handleCommsTyping } from './typing';

/**
 * A refetch can have read before this committed event, including on a page that
 * has already resolved while older pages are still loading. Restart the whole
 * fetch after updating the visible cache so its eventual commit cannot undo the
 * event. Idle timelines still apply live updates without making a request.
 */
async function restartPendingChannelTimeline(parent: MessageParent) {
  if (parent.type !== 'channel') return;
  const pending = queryClient.getQueryCache().findAll({
    queryKey: getMessageTimelineQueryKeyPrefix(parent),
    type: 'active',
    predicate: (query) =>
      query.state.data !== undefined && query.state.fetchStatus === 'fetching',
  });
  if (pending.length === 0) return;
  await Telemetry.span('channel.timeline_restart', async (span) => {
    span.setAttr('channel.id', parent.id);
    span.setAttr('query.count', pending.length);
    span.setAttr(
      'query.fetch_more_directions',
      pending.map(
        (query) => query.state.fetchMeta?.fetchMore?.direction ?? 'refetch'
      )
    );
    // Keep fetchMore direction: replacing pagination with an ordinary refetch
    // would silently discard the user's request for an older/newer page.
    const results = await Promise.allSettled(
      pending.map((query) =>
        query.fetch(undefined, {
          cancelRefetch: true,
          meta: query.state.fetchMeta ?? undefined,
        })
      )
    );
    const rejected = results.filter(
      (result) => result.status === 'rejected'
    ).length;
    span.setAttr(
      'query.outcomes',
      results.map((result) => result.status)
    );
    span.setAttr('query.fulfilled_count', results.length - rejected);
    span.setAttr('query.rejected_count', rejected);
    if (rejected > 0) {
      // Request errors can contain URLs or message data; record only a category.
      span.error('Channel timeline restart failed');
    }
  });
}

/** Committed timeline activity, delivered whole so loaded history needs no re-read. */
export function handleTimelineActivity(event: {
  parent: MessageParent;
  activities: TimelineActivity[];
}) {
  // A fact committed before the bottom page's first fetch resolved may be
  // missing from a response the server already computed. Loaded windows still
  // take it below.
  refetchTimelineAwaitingFirstPage(event.parent);
  queryClient.setQueriesData<MessageTimelineData>(
    { queryKey: getMessageTimelineQueryKeyPrefix(event.parent) },
    (data) => insertActivitiesIntoMessageTimeline(data, event.activities)
  );
  fireAndForget(restartPendingChannelTimeline(event.parent), 'messages-sync');
}

type ThreadStateListener = (
  parent: MessageParent,
  state: MessageThread['state']
) => void;
const threadStateListeners = new Set<ThreadStateListener>();

/** Notify annotation editors of committed lifecycle changes without inferring deletion from paged reads. */
export function onThreadStateUpdated(listener: ThreadStateListener) {
  threadStateListeners.add(listener);
  return () => threadStateListeners.delete(listener);
}

/** Preserve the event kind: only posts insert messages, and only deletes remove them. */
export function applyMessage(
  message: Message,
  change: Extract<MessageEvent['change'], { message: unknown }>['type']
) {
  const parent = message.parent;
  const target = resolveMessageTarget({
    parent,
    messageId: message.id,
    threadId: message.thread_id ?? undefined,
  });
  const normalized = normalizeMessageSender(message);
  const existing = getTargetMessage(parent, target);
  if (change === 'reaction_changed') {
    patchTargetMessage(parent, target, {
      reactions: message.reactions,
      updated_at: message.updated_at,
    });
  } else if (change === 'message_deleted') {
    patchTargetMessage(parent, target, normalized);
    if (target.kind === 'thread_reply' && !existing) {
      // A deletion outside the preview (or one already applied) needs the
      // authoritative count, not another guessed decrement.
      queryClient.invalidateQueries({
        queryKey: getMessageTimelineQueryKeyPrefix(parent),
      });
      queryClient.invalidateQueries({
        queryKey: [...messageKeys.messagesByIds._def, parent],
      });
    } else if (
      target.kind === 'thread_reply' ||
      (parent.type === 'channel' &&
        !topLevelMessageHasReplies(parent, message.id))
    ) {
      removeMessageFromTargetCaches(parent, target);
    }
  } else if (change === 'posted' && !existing) {
    if (target.kind === 'thread_reply') {
      insertMessageIntoTargetCaches(parent, target, normalized);
    } else {
      const item: MessageListItem = {
        ...normalized,
        state: {
          root_id: message.id,
          user_id: message.sender_id,
          created_at: message.created_at,
          updated_at: message.created_at,
          resolved: false,
          // Only document roots can be anchored; theirs load with the thread.
          ...(parent.type !== 'document' && { anchor: null }),
        },
        thread: { reply_count: 0, preview: [], latest_reply_at: null },
      };
      insertMessageIntoTargetCaches(parent, target, item);
    }
  } else {
    patchTargetMessage(parent, target, normalized);
  }
  softInvalidateTargetCaches(parent, target);
  fireAndForget(restartPendingChannelTimeline(parent), 'messages-sync');
  // Calls have one thread and no mounted timeline to seed its first fetch.
  // A view may still be showing the empty response when the first post arrives.
  if (
    parent.type === 'call' &&
    change === 'posted' &&
    !queryClient.getQueryData(getThreadRepliesQueryKey(parent, parent.id))
  ) {
    fireAndForget(refreshUnloadedCallThread(parent), 'messages-sync');
  }
}

async function refreshUnloadedCallThread(parent: MessageParent) {
  const queryKey = getThreadRepliesQueryKey(parent, parent.id);
  const inFlight = queryClient
    .getQueryCache()
    .find({ queryKey, exact: true })?.promise;
  if (inFlight) {
    try {
      await inFlight;
    } catch {
      // An empty call may return 404; retry after the committed first message.
    }
  }
  await queryClient.invalidateQueries({ queryKey, exact: true });
}

/**
 * Deleting the root of a discussion deletes the discussion, and the response
 * carries only the root's own tombstone. Apply the committed teardown so the
 * margin and the document mark clear without waiting on the live event, using
 * the thread state `cached` before the optimistic delete dropped the root from
 * the caches; the refetch it triggers reconciles the rest. With no state to
 * build on, only that refetch can report the teardown.
 */
export function applyRootDeletion(
  message: Message,
  cached?: MessageThread['state']
) {
  const parent = message.parent;
  if (parent.type === 'channel' || parent.type === 'call' || message.thread_id)
    return;
  const state = cached ?? getCachedThreadState(parent, message.id);
  if (!state) {
    queryClient.invalidateQueries({
      queryKey: getMessageTimelineQueryKeyPrefix(parent),
    });
    return;
  }
  applyThreadState(parent, {
    ...state,
    deleted_at: message.deleted_at ?? new Date().toISOString(),
  });
}

/** One live message protocol for channel screens, document discussions, and linked drawers. */
export function handleMessageEvent(
  event: MessageEvent,
  currentUserId?: string
) {
  if (!event?.parent || !event.change) return;
  const parent = event.parent;
  const change = event.change;
  if (change.type === 'typing') {
    handleCommsTyping(
      {
        parent,
        user_id: event.actor,
        thread_id: change.thread_id,
        action: change.active ? 'start' : 'stop',
        agent: change.agent,
      },
      currentUserId ?? ''
    );
    return;
  }
  if (change.type === 'thread_updated') {
    applyThreadState(parent, change.state);
    return;
  }
  if (change.type === 'call_root_posted') {
    // The call's row carries server-owned life facts, so it is read, not built.
    fireAndForget(invalidateMessageTimeline(parent), 'messages-sync');
    return;
  }
  const isRootPost = change.type === 'posted' && !change.message.thread_id;
  const isOwnEcho = consumeNonce(
    change.type === 'reaction_changed'
      ? MessageNonceKeys.REACTION
      : MessageNonceKeys.MESSAGE,
    event.nonce ?? ''
  );
  // A root posted before the bottom page loaded cannot be inserted — the
  // sender's own optimistic insert no-ops there too — so recover it with a
  // fresh fetch once the page settles, even when the echo is the sender's own.
  if (isRootPost && refetchTimelineAwaitingFirstPage(parent)) return;
  if (isOwnEcho) return;
  applyMessage(change.message, change.type);
  if (isRootPost && parent.type !== 'channel') {
    fireAndForget(
      loadDiscussionRootState(parent, change.message.id),
      'messages-sync'
    );
  }
}

/**
 * A root posted before the bottom page's first fetch resolved cannot be
 * inserted, and a response the server already computed would overwrite it, so
 * that fetch runs again once it settles (invalidating a fetch still in flight
 * only dedupes into it). Slices around a message never need it.
 */
function refetchTimelineAwaitingFirstPage(parent: MessageParent): boolean {
  const queryKey = getMessageTimelineQueryKey(parent, null);
  const query = queryClient
    .getQueryCache()
    .find<MessageTimelineData>({ queryKey, exact: true });
  if (!query || query.state.data) return false;
  const refetch = () =>
    queryClient.invalidateQueries({ queryKey, exact: true });
  const inFlight = query.promise;
  if (inFlight)
    fireAndForget(refetchAfterPendingPage(inFlight, refetch), 'messages-sync');
  else fireAndForget(refetch(), 'messages-sync');
  return true;
}

async function refetchAfterPendingPage(
  pending: Promise<unknown>,
  refetch: () => Promise<void>
) {
  try {
    await pending;
  } catch {
    // The new message still needs a fetch if the initial page request failed.
  }
  await refetch();
}

/**
 * Live discussion roots need authoritative thread state. Preserve derived senders
 * when replacing cached roots so agent comments keep their names after live updates.
 */
async function loadDiscussionRootState(parent: MessageParent, rootId: string) {
  try {
    const thread = await fetchMessageThread(parent, rootId);
    queryClient.setQueryData<MessageThread>(
      getThreadRepliesQueryKey(parent, rootId),
      thread
    );
    applyThreadState(parent, thread.state);
  } catch {
    queryClient.invalidateQueries({
      queryKey: getMessageTimelineQueryKeyPrefix(parent),
    });
  }
}

export function applyThreadState(
  parent: MessageParent,
  state: MessageThread['state']
) {
  const update = (item: MessageListItem) =>
    item.id === state.root_id ? { ...item, state } : item;
  setMessageTimelineData(
    parent,
    (data) =>
      data && {
        ...data,
        pages: data.pages.map((page) => ({
          ...page,
          entries: page.entries
            .filter(
              (item) =>
                item.type !== 'message' ||
                parent.type === 'document' ||
                !state.deleted_at ||
                item.message.id !== state.root_id
            )
            .map((entry) =>
              entry.type === 'message'
                ? { ...entry, message: update(entry.message) }
                : entry
            ),
        })),
      }
  );
  queryClient.setQueryData<MessageThread>(
    getThreadRepliesQueryKey(parent, state.root_id),
    (thread) =>
      thread
        ? { ...thread, state, replies: state.deleted_at ? [] : thread.replies }
        : undefined
  );
  for (const listener of threadStateListeners) listener(parent, state);
  if (!state.deleted_at)
    fireAndForget(restartPendingChannelTimeline(parent), 'messages-sync');
  if (state.deleted_at) {
    // Annotation layout also reads tombstones, including roots outside loaded
    // pages. Fetch the committed state so it survives late document mounting.
    queryClient.invalidateQueries({
      queryKey: getMessageTimelineQueryKeyPrefix(parent),
    });
  }
}