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.

14.8 KB
Raw Blame
import type { LexicalEditor } from 'lexical';
import type { Accessor } from 'solid-js';
import type { MessageOperationSourceFactory } from '../../email-message/context/message-operation-source';
import type { EmailMessage } from '../../email-message/core/email-message';
import type { EmailDraft } from '../core/email-draft';
import type { EmailRecipient } from '../core/email-recipient';
import type { SenderInbox } from '../core/email-sender';
import type { LocalDraft } from '../core/local-draft';
import type { DraftFormAttachment } from '../primitives/email-form-state';

export interface EmailInbox extends SenderInbox {
  provider?: 'GMAIL' | 'OUTLOOK';
  settings: {
    signature?: string | null;
    signature_on_replies_forwards?: boolean | null;
  };
}

/** Identity returned by a successful save or send. Transport envelopes stay in adapters. */
export interface PersistedEmailIdentity {
  /** Present when durable send admission owns this message. */
  sendAttemptId?: string;
  persistence?: 'committed' | 'queued';
  draftId?: string;
  threadId?: string;
  inboxId: string;
}

/**
 * A draft save's identity plus how it landed. `queued`: the durable
 * mutation queue accepted the write under the caller's client handles, which
 * the server may not know yet; REST-only actions cannot use them until a
 * later save commits. Absent means committed.
 */
export interface DraftSaveResult extends PersistedEmailIdentity {
  persistence?: 'committed' | 'queued';
}

/** Server rejection codes for a draft save or delete. None is retried by autosave. */
export type DraftPersistFailureCode =
  | 'DRAFT_ALREADY_SENT'
  | 'NOT_FOUND'
  | 'INBOX_NOT_FOUND'
  | 'UNAUTHORIZED'
  | 'INVALID'
  | 'INVALID_SENDER'
  | 'NEEDS_REAUTH'
  | 'SEND_AS_UNAVAILABLE'
  | 'INTERNAL';

/**
 * A deterministic server rejection of a draft save or delete. Transport
 * failures reject with a plain error and may be retried; this one carries
 * the code so a composer can interpret it (an already-sent draft resets the
 * composer, anything else latches autosave).
 */
export class DraftPersistRejected extends Error {
  constructor(readonly code: DraftPersistFailureCode) {
    super(`Draft persistence rejected: ${code}`);
    this.name = 'DraftPersistRejected';
  }
}

/**
 * Client-minted identity for a draft the server has not confirmed. Carried
 * apart from `draft.db_id` (a server id) because only the durable queue can
 * resolve handles; a REST save ignores them and mints server ids instead.
 */
export interface DraftClientHandles {
  draftId: string;
  threadId?: string;
}

export interface SaveEmailDraft {
  draft: EmailDraft;
  clientHandles?: DraftClientHandles;
  previousThreadId?: string;
  inboxId?: string;
  completingThread?: boolean;
}
export interface DeleteEmailDraft {
  draftGeneration?: number;
  draftId: string;
  threadId?: string;
  inboxId?: string;
  completingThread?: boolean;
}
export interface SendEmailDraft {
  /** Frozen Send Later deadline; omitted uses the server Undo Send delay. */
  sendTime?: string;
  message: EmailDraft;
  clientHandles?: DraftClientHandles;
  /** The exact working-copy version persisted for this submission. */
  expectedLocalVersion?: Pick<LocalDraft, 'generation' | 'revision'>;
  attachmentIds?: string[];
  forwardedAttachmentIds?: string[];
  restoreBodyHtml?: string | null;
  restoreBodyText?: string | null;
  restoreBodyMacro?: string | null;
  inboxId?: string;
  completingThread?: boolean;
}
export interface UploadEmailAttachments {
  draftGeneration?: number;
  draftId: string;
  attachments: File[];
  inboxId?: string;
  onAttachmentAdded?: (file: File, id: string) => void;
  onAttachmentUploaded?: (file: File, id: string) => void;
  onAttachmentUploadFailed?: (file: File) => void;
}
export interface EmailAttachmentChange {
  draftGeneration?: number;
  draftId: string;
  attachmentId: string;
  inboxId?: string;
}

/** The server fenced every delayed commit; the original draft remains editable. */
export class DraftTransferAborted extends Error {}

export interface EmailDraftStorage {
  recoverSynchronization?(): Promise<void>;
  syncAvailability?():
    | 'ready'
    | 'recovering'
    | 'unavailable'
    | 'recovery-required';
  /** Explicit restoration may replace editor content; ordinary cache updates never do. */
  watchRestorations?(
    changed: (restoration: EmailDraftRestoration) => void
  ): () => void;
  /** Reload canonical provider content after an explicit conflict resolution. */
  reloadDraft?(
    draftId: string,
    threadId: string
  ): Promise<EmailMessage | undefined>;
  /** Local acceptance is separate from remote autosave and continues after rejection. */
  saveLocalDraft?(
    input: SaveEmailDraft & {
      attachments: readonly DraftFormAttachment[];
      expectedRevision?: number;
      expectedGeneration?: string;
    }
  ): Promise<LocalDraft>;
  retryDraft?(draftId: string): Promise<void>;
  /** Drop the working copy of a draft whose server row no longer exists. */
  forgetLocalDraft?(draftId: string): Promise<void>;
  /** Resolve durable local drafts before mounting an editor. */
  readDraft?(
    draftId: string,
    options?: { attachments?: boolean }
  ): Promise<
    | {
        /** Sent records retain mutation identity but never editable content. */
        draft?: EmailMessage;
        persistence: 'committed' | 'queued';
        mutationUuid?: string;
        local?: LocalDraft;
        attachments?: DraftFormAttachment[];
      }
    | undefined
  >;
  /** Notify mounted composers to refresh identity, without reseeding their content. */
  watchDrafts?(
    changed: (settlement?: {
      mutationUuid?: string;
      failed: boolean;
      code?: DraftPersistFailureCode;
    }) => void
  ): () => void;
  transferDraft(input: {
    draftGeneration?: number;
    operationId: string;
    draftId: string;
    sourceInboxId: string;
    destinationInboxId: string;
  }): Promise<{
    draftId: string;
    threadId: string;
    attachments: EmailMessage['attachments_draft'];
  }>;
  saveDraft(input: SaveEmailDraft): Promise<DraftSaveResult>;
  deleteDraft(input: DeleteEmailDraft): Promise<void>;
  restoreDraft(input: {
    draftId: string;
    threadId?: string;
    draft?: Omit<EmailDraft, 'body_html'>;
    html?: string;
    inboxId?: string;
  }): Promise<void>;
}

export interface EmailDraftRestoration {
  draftId: string;
  originalDraftId: string;
  threadId: string;
  inboxId?: string;
  replyingToId?: string | null;
  includeSignature?: boolean | null;
}

export interface EmailAttachmentStorage {
  completeAttachment(input: EmailAttachmentChange): Promise<void>;
  uploadAttachments(input: UploadEmailAttachments): Promise<void>;
  addForwardedAttachments(input: {
    draftGeneration?: number;
    draftId: string;
    attachments: { attachmentId: string }[];
    inboxId?: string;
  }): Promise<void>;
  removeAttachment(input: EmailAttachmentChange): Promise<void>;
  removeForwardedAttachment(input: EmailAttachmentChange): Promise<void>;
}

/** An approved immediate send the thread read may not show yet. */
export interface OutgoingEmail {
  sendAttemptId: string;
  /** The approved draft's handles and, once accepted, the server's message id. */
  messageIds: string[];
  threadIds: string[];
  inboxId: string;
  /** The provider confirmed delivery, so a fresh thread read shows it. */
  delivered: boolean;
  message: Pick<
    EmailMessage,
    | 'to'
    | 'cc'
    | 'bcc'
    | 'subject'
    | 'body_text'
    | 'body_macro'
    | 'body_html_sanitized'
    | 'replying_to_id'
  >;
}

/**
 * One queued send as this device's outbox last recorded it. `accepted` is
 * cancellable until the server's `undoUntil`; `pending` covers waiting,
 * delivering, and cancellation in progress. `untracked` means the send left
 * the outbox and the server could not say whether it was delivered.
 */
export type EmailSendProgress =
  | { state: 'pending' }
  | { state: 'accepted'; undoUntil: string }
  | { state: 'sent' }
  | { state: 'failed' }
  | { state: 'cancelled' }
  | { state: 'unconfirmed' }
  | { state: 'untracked' };

export interface EmailDelivery {
  /** Whether sends can be persisted and replayed without connectivity. */
  queueActive?: (inboxId?: string) => boolean;
  /** Persisted locks, scoped to the composing surface's owner. */
  sendLocked?: (draftId: string | undefined) => boolean;
  /** Durable sends on their way; cancelled, failed and scheduled sends are excluded. */
  outgoing?: () => OutgoingEmail[];
  /** Reports each change until the send is sent, fails, is cancelled, or leaves this device. */
  watchSend?(
    sendAttemptId: string,
    changed: (progress: EmailSendProgress) => void
  ): () => void;
  sendMessage(input: SendEmailDraft): Promise<PersistedEmailIdentity>;
  unschedule(input: {
    draftGeneration?: number;
    draftId: string;
    threadId?: string;
    inboxId?: string;
  }): Promise<void>;
  schedule(
    input: {
      draftId: string;
      threadId?: string;
      sendTime: string;
      draftGeneration?: number;
      includeSignature?: boolean;
    },
    inboxId?: string
  ): Promise<void>;
  archive(
    input: { threadId: string; value: boolean },
    inboxId?: string
  ): Promise<void>;
  undoSend(input: {
    sendAttemptId?: string;
    threadId?: string;
    draftId: string;
    inboxId: string | undefined;
    onUndone: (result?: { draftRestored: boolean }) => Promise<void> | void;
  }): Promise<void>;
}

export type EmailDraftLifecycleState =
  | {
      type: 'editing';
      draftId: string;
      threadId: string;
      inboxId: string;
      observedAt: number;
    }
  | {
      type: 'scheduled';
      draftId: string;
      threadId: string;
      inboxId: string;
      sendTime: string;
      deliveryStatus?: 'pending' | 'sending' | 'failed' | 'unconfirmed';
      observedAt: number;
    }
  | {
      type: 'sent';
      draftId: string;
      threadId: string;
      inboxId: string;
      observedAt: number;
    }
  | {
      type: 'missing';
      draftId: string;
      threadId: string;
      inboxId?: string;
      observedAt: number;
    };

export interface EmailDraftLifecycleSource {
  observe(input: {
    draftId: Accessor<string | null | undefined>;
    threadId: Accessor<string | null | undefined>;
    inboxId: Accessor<string | undefined>;
  }): {
    state: Accessor<EmailDraftLifecycleState | undefined>;
    /** Prior observations stay invalid after failure until a fresh read succeeds. */
    refresh(): Promise<EmailDraftLifecycleState | undefined>;
    /** Read one captured identity even if the observing composer has navigated away. */
    refreshIdentity?(input: {
      draftId: string;
      threadId: string;
      inboxId?: string;
    }): Promise<EmailDraftLifecycleState | undefined>;
  };
}

export interface EmailComposeFeedback {
  feedback: {
    success(
      message: string,
      options?: ComposeNoticeOptions
    ): number | undefined;
    failure(
      message: string,
      options?: ComposeNoticeOptions
    ): number | undefined;
    alert(message: string, options?: ComposeNoticeOptions): void;
    dismiss(id: number): void;
  };
  /** A modal notice with a single acknowledgement; resolves when dismissed. */
  blockingNotice(input: { title: string; body: string }): Promise<void>;
  /** A modal choice; resolves true only when the user confirms. */
  confirm(input: {
    title: string;
    body: string;
    confirmLabel: string;
  }): Promise<boolean>;
  reportError(error: unknown): void;
}

/** Best-effort device connectivity; a false negative surfaces as the guarded action's own failure. */
export interface EmailConnectivity {
  looksOffline(): boolean;
}

export interface EmailComposeAccounts {
  inboxes: Accessor<EmailInbox[]>;
  loading: Accessor<boolean>;
  failed: Accessor<boolean>;
  primaryId: Accessor<string | undefined>;
}

/** View wiring; controllers do not receive these presentation capabilities. */
export interface EmailComposePresentation {
  viewerLoading: Accessor<boolean>;
  onUpgrade(): void;
  prepareSignatureLinks(root: ShadowRoot): void;
  isTouch: Accessor<boolean>;
  isMobile: Accessor<boolean>;
  scheduleEnabled: boolean;
  signaturesEnabled: Accessor<boolean>;
}

/** A file stored as a Macro document, as a body link names it. */
export interface UploadedDocument {
  documentId: string;
  name: string;
  blockName: string;
}

export interface EmailEditorFiles {
  readDroppedFiles: import('./editor-capabilities').ComposeBodyActions['readDroppedFiles'];
  makePublic(id: string): void;
  /** Stores files as documents; resolves with the ones that succeeded after reporting the rest. */
  uploadDocuments(files: File[]): Promise<UploadedDocument[]>;
  uploadEditorFiles(input: {
    editor: LexicalEditor | undefined;
    sourceId?: string;
    files: FileSystemFileEntry[];
    directories: FileSystemDirectoryEntry[];
    dropEvent?: DragEvent;
    onUploaded(ids: string[]): void;
    /** Videos, which email clients drop from HTML; callers attach them instead of inlining. */
    onVideos?(files: File[]): void;
  }): void;
}

/** Opens a calendar event drafted from an email. */
export interface EmailCalendarEvents {
  enabled: Accessor<boolean>;
  open(email: { subject: string; guests: string[]; text: string }): boolean;
}

/** Production composition groups capabilities for views to wire into their consumers. */
export interface EmailComposeContext {
  /** Absent where the composer has no calendar, such as isolated tests. */
  calendarEvents?: EmailCalendarEvents;
  operations?: MessageOperationSourceFactory;
  drafts: EmailDraftStorage;
  attachmentStorage: EmailAttachmentStorage;
  delivery: EmailDelivery;
  draftLifecycle: EmailDraftLifecycleSource;
  notices: EmailComposeFeedback;
  accounts: EmailComposeAccounts;
  connectivity: EmailConnectivity;
  presentation: EmailComposePresentation;
  editorFiles: EmailEditorFiles;
  viewerEmail: Accessor<string | undefined>;
  recipients: Accessor<EmailRecipient[]>;
  recipientName(id: string): string;
  hasPaidAccess: Accessor<boolean>;
  recordMention(sourceId: string, targetId: string): void;
}

export interface ComposeNoticeOptions {
  subtext?: string;
  duration?: number;
  persistent?: boolean;
  /** `kind` picks the action's icon; actions default to undo. */
  actions?: { label: string; onClick: () => void; kind?: 'undo' | 'open' }[];
}
export interface EmailComposeHost {
  focusSibling?: (direction: 'next' | 'prev') => boolean | void;
  showThread?: (id: string) => void;
  showDraft?: (id: string) => void;
  /** A From switch moved the draft to a new id and thread; the old ones are gone. */
  showMovedDraft?: (moved: { draftId: string; threadId: string }) => void;
  /** The draft a reload should reopen, or undefined when there is none. */
  recordDraft?: (draftId: string | undefined) => void;
  goBack?: () => void;
  registerBack?: (handler: () => boolean) => void;
}
export interface EmailUndoHandle {
  id: string;
  undo(callbacks?: {
    onSuccess?: () => void;
    onError?: (error: Error) => void;
    onSettled?: () => void;
  }): Promise<void>;
  dispose(): void;
}