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.

9.3 KB
Raw Blame
import { invalidateInvitationScheduling } from '@queries/calendar/invitations';
import { createLocalDraftSource } from '@queries/email/local-draft-source';
import { localDraftMessage } from '@queries/email/local-drafts';
import type { ThreadQueryData, ThreadQueryResult } from '@queries/email/thread';
import type { ApiThread } from '@service-email/generated/schemas';
import { type Accessor, createEffect, createMemo, on } from 'solid-js';
import type { EmailThreadSource } from '../context/email-thread-context';
import type { EmailThread } from '../core/email-thread';

/** Project transport data onto feature-owned values; this is not runtime validation. */
export function toEmailThread(thread: ApiThread): EmailThread {
  return {
    access_level: thread.access_level,
    db_id: thread.db_id,
    created_at: thread.created_at,
    updated_at: thread.updated_at,
    inbox_visible: thread.inbox_visible,
    has_received_mail: thread.has_received_mail,
    is_read: thread.is_read,
    latest_inbound_message_ts: thread.latest_inbound_message_ts,
    link_id: thread.link_id,
    messages: thread.messages.map((message) => ({
      calendar_invitations: message.calendar_invitations,
      attachments: message.attachments.map((attachment) => ({
        content_id: attachment.content_id,
        db_id: attachment.db_id,
        filename: attachment.filename,
        mime_type: attachment.mime_type,
        reference_url: attachment.reference_url,
        sfs_id: attachment.sfs_id,
        size_bytes: attachment.size_bytes,
      })),
      attachments_draft: message.attachments_draft.map((attachment) => ({
        content_type: attachment.content_type,
        file_name: attachment.file_name,
        id: attachment.id,
        s3_key: attachment.s3_key,
        upload_pending: attachment.upload_pending,
        content_id: attachment.content_id,
        is_inline: attachment.is_inline,
        size: attachment.size,
      })),
      attachments_forwarded: message.attachments_forwarded.map(
        (attachment) => ({
          attachment_id: attachment.attachment_id,
          filename: attachment.filename,
          mime_type: attachment.mime_type,
          size_bytes: attachment.size_bytes,
        })
      ),
      bcc: message.bcc.map((contact) => ({
        email: contact.email,
        name: contact.name,
        photo_url: contact.photo_url,
      })),
      body_html_sanitized: message.body_html_sanitized,
      body_macro: message.body_macro,
      body_replyless: message.body_replyless,
      body_text: message.body_text,
      cc: message.cc.map((contact) => ({
        email: contact.email,
        name: contact.name,
        photo_url: contact.photo_url,
      })),
      created_at: message.created_at,
      db_id: message.db_id,
      draft_generation: message.draft_generation,
      from: message.from
        ? {
            email: message.from.email,
            name: message.from.name,
            photo_url: message.from.photo_url,
          }
        : message.from,
      internal_date_ts: message.internal_date_ts,
      is_draft: message.is_draft,
      operation: message.operation_status
        ? {
            state: message.operation_status.state,
            revision: message.operation_status.revision,
            remoteVersion: message.operation_status.remote_version,
            issue: message.operation_status.issue,
          }
        : undefined,
      is_read: message.is_read,
      labels: message.labels.map((label) => ({
        name: label.name,
        provider_label_id: label.provider_label_id,
      })),
      link_id: message.link_id,
      provider_id: message.provider_id,
      replying_to_id: message.replying_to_id,
      scheduled_send_time: message.scheduled_send_time,
      scheduled_send_status: message.scheduled_send_status,
      sent_at: message.sent_at,
      snippet: message.snippet,
      subject: message.subject,
      thread_db_id: message.thread_db_id,
      to: message.to.map((contact) => ({
        email: contact.email,
        name: contact.name,
        photo_url: contact.photo_url,
      })),
      updated_at: message.updated_at,
    })),
    project_id: thread.project_id,
    provider_id: thread.provider_id,
  };
}

export function createEmailThreadSource(
  threadId: Accessor<string>,
  query: ThreadQueryResult<ThreadQueryData>
): EmailThreadSource & { isLocalDraft: Accessor<boolean> } {
  // Status guards prevent a pending Solid resource from suspending its owner.
  const snapshot = createMemo<{ requested: string; thread?: EmailThread }>(
    (previous) => {
      const requested = threadId();
      if (!query.isSuccess && !query.isError) {
        // Resolving a local handle changes the query key, but must not unmount
        // an open composer while the same thread's canonical page loads.
        return {
          requested,
          thread:
            previous?.requested === requested ? previous.thread : undefined,
        };
      }
      const data = query.data?.thread;
      if (!data) return { requested };
      // Cache aliases and the async identity lookup have separate subscribers.
      // Keep the last verified row until both observe the canonical identity.
      return {
        requested,
        thread:
          data.db_id === requested || data.db_id === query.resolvedThreadId
            ? toEmailThread(data)
            : previous?.requested === requested
              ? previous.thread
              : undefined,
      };
    }
  );
  const local = createLocalDraftSource(() => query.transport === 'graphql');
  const discoveringDrafts = () =>
    query.transport === 'graphql' && !local.ready();
  const thread = () => {
    const base = snapshot().thread;
    if (query.transport !== 'graphql') return base;
    // Establish the recovered draft before a reply editor can latch its seed.
    if (discoveringDrafts()) return undefined;
    const requested = threadId();
    const copies = local
      .drafts()
      .filter(
        (draft) =>
          [draft.threadId, draft.serverThreadId].includes(requested) ||
          (base && [draft.threadId, draft.serverThreadId].includes(base.db_id))
      );
    const edits = copies.filter(
      (draft) =>
        draft.status !== 'synced' &&
        !(
          draft.status === 'deleting' &&
          draft.queuedAttemptId &&
          draft.queuedAttemptId === draft.latestAttemptId
        )
    );
    const messages = edits.map(localDraftMessage);
    if (!base) {
      const draft = edits.find((draft) => !draft.content.replying_to_id);
      if (!draft) return undefined;
      return {
        access_level: 'owner' as const,
        db_id: draft.serverThreadId ?? draft.threadId ?? requested,
        inbox_visible: false,
        has_received_mail: false,
        is_read: true,
        link_id: draft.inboxId ?? '',
        messages,
      };
    }
    const ids = new Set(
      copies
        .filter((draft) => draft.status !== 'synced')
        .flatMap((draft) => [draft.draftId, draft.serverDraftId])
    );
    return copies.length
      ? {
          ...base,
          messages: [
            ...base.messages.filter(
              (message) => !message.is_draft || !ids.has(message.db_id)
            ),
            ...messages.filter(
              (message) =>
                !base.messages.some(
                  (saved) => saved.db_id === message.db_id && !saved.is_draft
                )
            ),
          ],
        }
      : base;
  };
  // Memo equality prevents ordinary email refreshes from revalidating calendar state.
  const scheduling = createMemo(
    () => {
      const current = thread();
      return (
        current && {
          threadId: current.db_id,
          invitations: JSON.stringify(
            current.messages
              .filter((message) => message.calendar_invitations?.length)
              .map((message) => [message.db_id, message.calendar_invitations])
          ),
        }
      );
    },
    undefined,
    {
      equals: (a, b) =>
        a?.threadId === b?.threadId && a?.invitations === b?.invitations,
    }
  );
  // Only a change inside an already-loaded thread, never its first load or a switch.
  createEffect(
    on(scheduling, (next, previous) => {
      if (next && next.threadId === previous?.threadId)
        invalidateInvitationScheduling(next.threadId);
    })
  );
  return {
    id: () => thread()?.db_id ?? query.resolvedThreadId ?? threadId(),
    thread,
    // A first-use working copy may not have reached the mutation queue, so
    // its temporary thread ID can still return NOT_FOUND from the server.
    isLocalDraft: () =>
      query.transport === 'graphql' &&
      query.resolvedThreadId === threadId() &&
      !!thread() &&
      local
        .drafts()
        .some(
          (draft) =>
            draft.threadId === threadId() &&
            !draft.serverDraftId &&
            !draft.serverThreadId &&
            !draft.content.replying_to_id &&
            draft.status !== 'synced'
        ),
    isError: () =>
      query.isError && (query.transport !== 'graphql' || !thread()),
    isLoading: () =>
      discoveringDrafts() ||
      (query.isLoading && (query.transport !== 'graphql' || !thread())),
    isFetching: () => query.isFetching,
    isFetchingOlder: () => query.isFetchingNextPage,
    hasMore: () => query.hasNextPage,
    fetchOlder: async () => {
      await query.fetchNextPage();
    },
    refresh: async () => {
      await query.refetch();
    },
  };
}