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.

15.6 KB
Raw Blame
import { CalendarDraftComposer } from '@core/component/AI/component/tool/calendar/DraftComposer';
import { EmailDraftComposer } from '@core/component/AI/component/tool/email/DraftComposer';
import type { UserToolReviewSink } from '@core/component/AI/component/tool/user-tool-review';
import { fireAndForget } from '@core/util/fireAndForget';
import type {
  CreateCalendarEvent_Deserialize,
  SendEmail,
} from '@service-agent-reviews/generated/types';
import { Button } from '@ui/components/Button';
import { ConfirmDialog } from '@ui/components/ConfirmDialog';
import { createEffect, createSignal, on, Show } from 'solid-js';
import { match } from 'ts-pattern';
import { ReviewDeck } from '../components/review-deck';
import {
  ReviewNavigation,
  type ReviewSummary,
} from '../components/review-navigation';
import type {
  Review,
  ReviewActions,
  ReviewDraft,
  ReviewItem,
} from '../core/review';
import { createReviewController } from '../primitives/review-controller';

type EmailDraft = SendEmail;
type CalendarDraft = CreateCalendarEvent_Deserialize;

/** Saved drafts reuse the same composers as chat, with a deck only for batches. */
export function ReviewStack(props: {
  review: Review;
  canAct: boolean;
  actions: ReviewActions;
}) {
  const controller = createReviewController(() => props.review, props.actions);
  const [index, setIndex] = createSignal(0);
  const [generation, setGeneration] = createSignal(0);
  const [preparing, setPreparing] = createSignal(false);
  const [navigating, setNavigating] = createSignal(false);
  const [submittedBatch, setSubmittedBatch] = createSignal<string[]>();
  const [confirmingBatch, setConfirmingBatch] = createSignal<string[]>([]);
  const [confirmationOpen, setConfirmationOpen] = createSignal(false);
  const record = controller.record;
  const current = () => record().items[index()];
  const isBatch = () => record().items.length > 1;
  let readDraft: (() => ReviewDraft | undefined) | undefined;
  let readSubmit: (() => Promise<ReviewDraft | undefined>) | undefined;
  let section: HTMLElement | undefined;
  const working = () => controller.busy() || preparing() || navigating();
  const locked = () =>
    !props.canAct ||
    working() ||
    Boolean(controller.error()) ||
    controller.stale() ||
    record().presentedAt == null ||
    record().items.some((item) => item.status === 'submitting');

  function capture(): boolean {
    if (locked() || current()?.status !== 'pending') return true;
    const draft = readDraft?.();
    if (draft === undefined) return false;
    controller.edit(current().id, draft);
    return true;
  }
  function select(next: number) {
    if (next === index()) return;
    readDraft = undefined;
    readSubmit = undefined;
    setIndex(next);
  }
  // Submission acknowledges the batch before execution finishes. Poll updates
  // move focus once, after this component's submitted items have settled.
  createEffect(
    on([record, submittedBatch], ([review, submitted]) => {
      if (!submitted) return;
      const items = review.items.filter((item) => submitted.includes(item.id));
      if (items.some((item) => item.status === 'submitting')) return;
      setSubmittedBatch(undefined);
      const attention = review.items.findIndex(
        (item) =>
          submitted.includes(item.id) &&
          (item.status === 'unknown' ||
            (item.status === 'pending' && Boolean(item.error)))
      );
      if (attention >= 0) {
        select(attention);
        section?.focus({ preventScroll: true });
      }
    })
  );
  async function navigate(next: number) {
    if (
      working() ||
      next < 0 ||
      next >= record().items.length ||
      next === index()
    )
      return;
    if (!capture()) return;
    setNavigating(true);
    try {
      if (await controller.flush()) select(next);
    } finally {
      setNavigating(false);
    }
  }
  async function reload() {
    if (!(await controller.reload())) return;
    readDraft = undefined;
    readSubmit = undefined;
    setIndex(Math.min(index(), Math.max(0, record().items.length - 1)));
    setGeneration((value) => value + 1);
  }
  async function submitAll(items: string[]) {
    if (locked() || pending() === 0) return;
    setPreparing(true);
    try {
      if (current()?.status === 'pending') {
        if (!readSubmit) return;
        const draft = await readSubmit();
        if (draft === undefined) return;
        controller.edit(current().id, draft);
      }
      if (await controller.decide('submit', items)) setSubmittedBatch(items);
    } finally {
      setPreparing(false);
    }
  }
  async function decideItem(action: 'submit' | 'dismiss', id: string) {
    const done = await controller.decide(action, [id]);
    if (!done) return false;
    const items = record().items;
    const next = items.findIndex(
      (item, position) => position > index() && item.status === 'pending'
    );
    const remaining =
      next >= 0
        ? next
        : items.findIndex(
            (item) => item.id !== id && item.status === 'pending'
          );
    if (remaining >= 0) {
      select(remaining);
      section?.focus({ preventScroll: true });
    }
    return true;
  }
  const sink = <T,>(
    id: string,
    toDraft: (draft: T) => ReviewDraft
  ): UserToolReviewSink<T> => ({
    canAct: () =>
      !locked() &&
      record().items.find((item) => item.id === id)?.status === 'pending',
    lockedNotice: () =>
      !props.canAct
        ? 'Only the person whose account this review uses can submit it.'
        : undefined,
    onEdit: (draft) => {
      controller.edit(id, toDraft(draft));
    },
    onExecute: async (draft) => {
      controller.edit(id, toDraft(draft));
      return decideItem('submit', id);
    },
    onReject: () => decideItem('dismiss', id),
  });
  const pending = () =>
    record().items.filter((item) => item.status === 'pending').length;
  const completed = () =>
    record().items.filter((item) => item.status === 'completed').length;
  const dismissed = () =>
    record().items.filter((item) => item.status === 'dismissed').length;
  const needsAttention = () =>
    record().items.filter(
      (item) =>
        item.status === 'unknown' ||
        (item.status === 'pending' && Boolean(item.error))
    ).length;
  const progress = () =>
    [
      completed() > 0
        ? `${completed()} ${reviewWording(record().kind).done.toLowerCase()}`
        : '',
      dismissed() > 0 ? `${dismissed()} dismissed` : '',
      needsAttention() > 0
        ? `${needsAttention()} ${needsAttention() === 1 ? 'needs' : 'need'} attention`
        : '',
      pending() > 0 ? `${pending()} remaining` : '',
    ]
      .filter(Boolean)
      .join(' · ');
  const mountKey = () => `${current()?.id}:${generation()}`;
  return (
    <section
      ref={section}
      tabIndex={-1}
      class="my-3 min-w-0"
      aria-label={record().title}
    >
      <Show when={isBatch()}>
        <ReviewNavigation
          title={record().title}
          items={record().items.map((item, position) =>
            reviewSummary(item, record(), position)
          )}
          index={index()}
          disabled={working()}
          onNavigate={navigate}
        />
        <span class="sr-only" role="status">
          Draft {index() + 1} of {record().items.length}
        </span>
      </Show>
      <Show when={record().presentedAt == null}>
        <p role="status" class="mb-2 text-xs text-ink-muted">
          Preparing saved review…
        </p>
      </Show>
      <Show when={controller.error()}>
        <p role="alert" class="mb-2 text-sm text-failure">
          {controller.error()}
        </p>
      </Show>
      <Show when={controller.stale() || controller.error()}>
        <div class="mb-3 flex flex-wrap items-center gap-2">
          <Button
            variant="secondary"
            size="sm"
            disabled={working()}
            onClick={() => fireAndForget(reload(), 'agent-reviews')}
          >
            Reload saved review
          </Button>
          <span class="text-xs text-ink-muted">
            Reloading replaces unsaved edits with the saved draft.
          </span>
        </div>
      </Show>
      <Show when={controller.validation()}>
        <p role="alert" class="mb-2 text-sm text-failure">
          {controller.validation()}
        </p>
      </Show>
      <Show when={current()?.error}>
        <p role="alert" class="mb-2 text-sm text-failure">
          {current()?.error}
        </p>
      </Show>
      <Show when={current()?.status !== 'pending'}>
        <p role="status" class="mb-2 px-1 text-xs text-ink-muted">
          {statusLabel(current()?.status, record().kind)}
        </p>
      </Show>
      <Show when={startedByAgent(record(), current())}>
        <p class="mb-2 px-1 text-xs text-ink-muted">
          Started by the agent at your request
        </p>
      </Show>
      <ReviewDeck
        count={record().items.length}
        email={record().kind === 'email'}
      >
        <Show when={mountKey()} keyed>
          {(_key) => {
            const readOnly = current()?.status !== 'pending';
            // A review's kind is fixed when it is saved.
            return match(record())
              .with({ kind: 'email' }, (review) => {
                const item = review.items[index()];
                if (!item) return null;
                const toDraft = (draft: EmailDraft): ReviewDraft => ({
                  kind: 'email',
                  draft,
                });
                return (
                  <EmailDraftComposer
                    initialData={item.draft}
                    sink={sink(item.id, toDraft)}
                    debugName={`review-${item.id}`}
                    readOnly={readOnly}
                    registerDraftReader={(reader) => {
                      readDraft = () => mapDraft(reader(), toDraft);
                    }}
                    registerSubmitReader={(reader) => {
                      readSubmit = async () =>
                        mapDraft(await reader(), toDraft);
                    }}
                  />
                );
              })
              .with({ kind: 'calendar' }, (review) => {
                const item = review.items[index()];
                if (!item) return null;
                const toDraft = (draft: CalendarDraft): ReviewDraft => ({
                  kind: 'calendar',
                  draft,
                });
                return (
                  <CalendarDraftComposer
                    initialData={item.draft}
                    sink={sink(item.id, toDraft)}
                    previewKey={item.id}
                    registerDraftReader={(reader) => {
                      readDraft = () => mapDraft(reader(), toDraft);
                    }}
                    registerSubmitReader={(reader) => {
                      readSubmit = async () =>
                        mapDraft(await reader(), toDraft);
                    }}
                  />
                );
              })
              .with({ kind: 'import' }, () => null)
              .exhaustive();
          }}
        </Show>
      </ReviewDeck>
      <Show when={isBatch()}>
        <footer class="mt-3 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 px-1">
          <span class="min-w-0 text-xs text-ink-muted" role="status">
            {progress()}
          </span>
          <Button
            variant="secondary"
            size="sm"
            class="ml-auto"
            disabled={locked() || pending() === 0}
            onClick={() => {
              setConfirmingBatch(
                record()
                  .items.filter((item) => item.status === 'pending')
                  .map((item) => item.id)
              );
              setConfirmationOpen(true);
            }}
          >
            {reviewWording(record().kind).verb} all ({pending()})
          </Button>
        </footer>
        <ConfirmDialog
          open={confirmationOpen()}
          onOpenChange={setConfirmationOpen}
          title={`${batchLabel(record().kind, confirmingBatch().length)}?`}
          body={reviewWording(record().kind).batchBody}
          confirmLabel={batchLabel(record().kind, confirmingBatch().length)}
          onConfirm={() => {
            const items = confirmingBatch();
            if (items.length === 0 || !confirmationOpen()) return;
            setConfirmationOpen(false);
            fireAndForget(submitAll(items), 'agent-reviews');
          }}
        />
      </Show>
    </section>
  );
}
function startedByAgent(review: Review, item: ReviewItem | undefined) {
  return (
    review.decision?.via === 'chat' &&
    (item?.status === 'submitting' || item?.status === 'completed')
  );
}
function mapDraft<T>(
  draft: T | undefined,
  toDraft: (draft: T) => ReviewDraft
): ReviewDraft | undefined {
  return draft === undefined ? undefined : toDraft(draft);
}
function reviewWording(kind: Review['kind']) {
  return match(kind)
    .with('email', () => ({
      verb: 'Send',
      noun: 'email',
      working: 'Sending…',
      done: 'Sent',
      batchBody:
        'Each email will be sent to the recipients shown in its draft.',
    }))
    .with('calendar', () => ({
      verb: 'Create',
      noun: 'event',
      working: 'Creating…',
      done: 'Created',
      batchBody:
        'These events will be created and guests will receive invitations.',
    }))
    .with('import', () => ({
      verb: 'Import',
      noun: 'import',
      working: 'Importing…',
      done: 'Imported',
      batchBody: 'These imports will start right away.',
    }))
    .exhaustive();
}
function batchLabel(kind: Review['kind'], count: number): string {
  const wording = reviewWording(kind);
  return `${wording.verb} ${count} ${wording.noun}${count === 1 ? '' : 's'}`;
}
function statusLabel(
  status: ReviewItem['status'] | undefined,
  kind: Review['kind']
): string {
  return match(status)
    .with('submitting', () => reviewWording(kind).working)
    .with('completed', () => reviewWording(kind).done)
    .with('dismissed', () => 'Dismissed')
    .with(
      'unknown',
      () => 'Outcome unknown — check the destination before trying again.'
    )
    .with('pending', undefined, () => 'Draft')
    .exhaustive();
}
function reviewSummary(
  item: ReviewItem,
  review: Review,
  index: number
): ReviewSummary {
  const summary = {
    id: item.id,
    title: 'Import plan',
    description: '',
    status: item.error
      ? 'Needs attention'
      : item.status === 'unknown'
        ? 'Check status'
        : statusLabel(item.status, review.kind),
    needsAttention: Boolean(item.error) || item.status === 'unknown',
  };
  return match(review)
    .with({ kind: 'email' }, (review) => {
      const email = review.items[index]?.draft;
      if (!email) return summary;
      return {
        ...summary,
        title: email.subject || '(No subject)',
        description:
          email.to
            .map((recipient) =>
              recipient.name
                ? `${recipient.name} <${recipient.email}>`
                : recipient.email
            )
            .join(', ') || 'No recipients',
      };
    })
    .with({ kind: 'calendar' }, (review) => {
      const event = review.items[index]?.draft;
      if (!event) return summary;
      const time = event.time;
      const description =
        time.kind === 'allDay'
          ? `${time.startDate} · All day`
          : new Date(time.startsAt).toLocaleString(undefined, {
              month: 'short',
              day: 'numeric',
              hour: 'numeric',
              minute: '2-digit',
              timeZoneName: 'short',
            });
      return {
        ...summary,
        title: event.title || '(Untitled event)',
        description,
      };
    })
    .with({ kind: 'import' }, () => summary)
    .exhaustive();
}