Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
11.7 KB
Raw Blame
"use client";

import { useState, type ReactNode } from "react";
import { toast } from "sonner";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@multica/ui/components/ui/dialog";
import { Button } from "@multica/ui/components/ui/button";
import { Spinner } from "@multica/ui/components/ui/spinner";
import type { IssueAssigneeType, IssueStatus, UpdateIssueRequest } from "@multica/core/types";
import { useUpdateIssue, useBatchUpdateIssues } from "@multica/core/issues/mutations";
import { useBatchResultToast } from "../issues/components/batch-result-toast";
import { errorCode } from "@multica/core/api";
import { useActorName } from "@multica/core/workspace/hooks";
import { useWorkspaceId } from "@multica/core/hooks";
import { useShortcut, shortcutMatchesEvent, isPlainShortcut } from "@multica/core/shortcuts";
import { isImeComposing } from "@multica/core/utils";
import { ShortcutKeycaps } from "../common/shortcut-keycaps";
import { useStatusLabel } from "../issues/utils/status-label";
import { useT } from "../i18n";

// i18next inlines {{name}} / {{status}} into the sentence, but their position
// varies by language ("{{name}} 会…" vs "Once assigned, {{name}} will…" vs
// "{{name}}'s leader…"). Fence each one with a sentinel so we can bold just
// those spans at render time without splitting copy into per-language
// prefix/suffix keys. Bolding is also what marks a custom status name as a
// status rather than an ordinary word ("Move this issue to Later.").
const FENCE = "\u0000";

const fenced = (value: string) => `${FENCE}${value}${FENCE}`;

function boldFenced(text: string): ReactNode {
  const parts = text.split(FENCE);
  // Every fenced span contributes one odd-indexed part; an unfenced string is
  // a single part and renders as-is.
  if (parts.length < 3) return text;
  return (
    <>
      {parts.map((part, i) =>
        i % 2 === 1 ? (
          <span key={i} className="font-semibold text-foreground">
            {part}
          </span>
        ) : (
          part
        ),
      )}
    </>
  );
}

interface RunConfirmData {
  issueIds?: string[];
  // The two issue writes that hand work to an agent, and the only two that
  // confirm. `assign` gives the issue an agent/squad owner; `promote` moves an
  // already-owned issue out of the backlog category, which starts the run on
  // its own (RunSourceStatus). Batch status changes still apply directly
  // (MUL-4155) — `promote` is the single-issue picker path only (MUL-6463).
  mode?: "assign" | "promote";
  /** promote only: the status KEY the issue is moving to. */
  status?: IssueStatus;
  assigneeType?: IssueAssigneeType;
  assigneeId?: string;
  assigneeName?: string;
  issueRevision?: number;
  /** Runs after every write applies; never on dismiss, failure, or a partial batch. */
  onApplied?: () => void;
}

/**
 * Handoff confirmation for the issue writes that start agent runs.
 *
 * The rule is "dialog = you are handing this to an agent", NOT "you are
 * confirming N runs" (MUL-5010). It therefore does no pre-flight prediction:
 * opening it fires no request, so the buttons are usable on the first frame.
 * Previously it called POST /api/issues/preview-trigger on open and blocked the
 * whole dialog behind a "检查中…" spinner; because that query is keyed per issue
 * id with staleTime 0, every new issue was a guaranteed cache miss and the wait
 * was unavoidable.
 *
 * Completion is silent: the assignee/status change and any run it starts
 * surface through the issue's normal updates, so the confirm adds no result
 * toast; only a batch the server applied partially warns with the real count.
 * Whether a run starts stays the server's existing decision at write
 * time. Dismissing the dialog (X / Esc / click-outside) cancels without any
 * write. Shared by single assign (1 id), batch assign (N ids), and the
 * single-issue promotion out of backlog.
 */
export function RunConfirmModal({
  open = true,
  onClose,
  onOpenChangeComplete,
  data,
}: {
  open?: boolean;
  onClose: () => void;
  onOpenChangeComplete?: (open: boolean) => void;
  data: Record<string, unknown> | null;
}) {
  const { t } = useT("modals");
  const { t: tIssues } = useT("issues");
  const { getActorName } = useActorName();
  const sendShortcut = useShortcut("send");
  const d = (data ?? {}) as RunConfirmData;
  const issueIds = d.issueIds ?? [];

  // Which footer action is in flight, so only the clicked button shows a
  // spinner (the write is not instant — the disabled-only state read as frozen).
  const [pendingAction, setPendingAction] = useState<"go" | "suppress" | null>(null);
  const submitting = pendingAction !== null;

  const updateIssue = useUpdateIssue();
  const batchUpdate = useBatchUpdateIssues();
  const { report: reportBatch } = useBatchResultToast();

  const wsId = useWorkspaceId();
  // Built-ins resolve through i18n, custom statuses through the catalog, so the
  // promotion headline reads the same way the picker the user just used does.
  const statusLabel = useStatusLabel(wsId);

  // A promotion carries the status and nothing else: the owner is already on
  // the issue, and re-sending the same assignee would turn a status write into
  // an assignee write on the server's side of the trigger predicate.
  const isPromote = d.mode === "promote" && !!d.status;

  const applyTo = (extra: Partial<UpdateIssueRequest>) => {
    const base: UpdateIssueRequest = isPromote
      ? { status: d.status }
      : {
          assignee_type: d.assigneeType ?? null,
          assignee_id: d.assigneeId ?? null,
        };
    return { ...base, ...extra };
  };

  // The copy names whoever the issue is handed to; for a squad that is the
  // squad itself, since its leader deciding who works is an internal detail.
  const assigneeName =
    d.assigneeName ??
    getActorName(d.assigneeType === "squad" ? "squad" : "agent", d.assigneeId ?? "");

  const submit = async (suppressRun: boolean) => {
    if (issueIds.length === 0 || submitting) return;
    setPendingAction(suppressRun ? "suppress" : "go");
    const payload = applyTo(suppressRun ? { suppress_run: true } : {});
    try {
      // Completion is silent, exactly as before: the assignee and any run show
      // up through the issue's normal assignee / run-status updates, so there is
      // no result toast to add here. Whether a run started is the server's
      // existing decision at write time, not something this dialog reports.
      if (issueIds.length === 1) {
        await updateIssue.mutateAsync({
          id: issueIds[0]!,
          ...payload,
        });
      } else {
        const response = await batchUpdate.mutateAsync({ ids: issueIds, updates: payload });
        // A partial batch still closes (the applied writes are real), but it
        // names the skipped issues and skips onApplied so the caller keeps
        // its selection for a retry.
        if (!reportBatch(response, issueIds.length, { successMessage: null })) {
          onClose();
          return;
        }
      }
      d.onApplied?.();
      onClose();
    } catch (err) {
      toast.error(
        errorCode(err) === "revision_conflict"
          ? tIssues(($) => $.revision.conflict)
          : err instanceof Error && err.message
            ? err.message
            : t(($) => $.run_confirm.toast_failed),
      );
      setPendingAction(null);
    }
  };

  /**
   * The configured `send` chord confirms the assignment, the same chord that
   * creates from the issue composer (MUL-5694).
   *
   * Bound on the dialog, not on a single control, because the chord means "run
   * the primary action" no matter which control has focus — and with only the
   * footer left to focus, that is precisely where the keycap on the confirm
   * button would otherwise be advertising a dead key.
   */
  const onDialogKeyDown = (e: React.KeyboardEvent) => {
    // A held chord submits once, and the Enter that commits an IME
    // composition is the user picking a candidate, never a confirmation.
    if (e.defaultPrevented || e.repeat || isImeComposing(e)) return;
    if (!shortcutMatchesEvent(sendShortcut, e.nativeEvent)) return;
    // Only a BARE Enter activates a focused button (Chromium fires no click
    // for ⌘/Ctrl+Enter), so a `send` remapped to plain Enter is the one case
    // where confirming here too would double-write — and on "Don't start yet"
    // the two writes would disagree about suppress_run. Every chord form
    // reaches the footer as a dead key without us, so it must not be skipped.
    const activatesFocusedButton =
      isPlainShortcut(sendShortcut, "Enter") &&
      e.target instanceof HTMLElement &&
      e.target.closest("button") !== null;
    if (activatesFocusedButton) return;
    e.preventDefault();
    void submit(false);
  };

  // States the action, not a prediction: the write is certain, the run is
  // conditional, so the copy names no run count. The promotion names the
  // status it is moving to by its workspace label — a custom status is only
  // recognisable by the name its admin gave it.
  const headline: ReactNode = boldFenced(
    isPromote
      ? t(($) => $.run_confirm.promote_single, {
          name: fenced(assigneeName),
          status: fenced(statusLabel(d.status ?? "")),
        })
      : issueIds.length > 1
        ? t(($) => $.run_confirm.assign_batch, {
            name: fenced(assigneeName),
            count: issueIds.length,
          })
        : t(($) => $.run_confirm.assign_single, { name: fenced(assigneeName) }),
  );

  return (
    <Dialog
      open={open}
      onOpenChange={(v) => { if (!v && !submitting) onClose(); }}
      onOpenChangeComplete={onOpenChangeComplete}
    >
      {/* Wider than the primitive's sm:max-w-sm: the two actions are long
          phrases, not "Cancel"/"Save". In French they measure ~435px with the
          send-shortcut keycaps against the 352px the default leaves, so the
          dialog's overflow-auto showed a horizontal scrollbar. */}
      <DialogContent className="sm:max-w-lg" onKeyDown={onDialogKeyDown}>
        <DialogHeader>
          <DialogTitle>
            {isPromote
              ? t(($) => $.run_confirm.title_promote)
              : t(($) => $.run_confirm.title_assign)}
          </DialogTitle>
          <DialogDescription>{headline}</DialogDescription>
        </DialogHeader>

        {/* The only spinner left is on the button the user just pressed, and it
            reflects the write in flight — never a pre-flight check. */}
        {/* flex-wrap keeps a longer translation, or a larger text size, from
            bringing the scrollbar back: the actions stack instead. */}
        <DialogFooter className="sm:flex-wrap">
          <Button type="button" variant="outline" disabled={submitting} onClick={() => submit(true)}>
            {pendingAction === "suppress" ? <Spinner className="size-4" /> : t(($) => $.run_confirm.dont_start)}
          </Button>
          <Button type="button" disabled={submitting} onClick={() => submit(false)}>
            {pendingAction === "go" ? (
              <Spinner className="size-4" />
            ) : (
              <>
                {isPromote
                  ? t(($) => $.run_confirm.confirm_promote)
                  : t(($) => $.run_confirm.confirm_assign)}
                {/* Decorative: the accessible name stays the button's own copy,
                    not "Confirm assignment Command Enter". Absent when `send`
                    is unbound. */}
                {sendShortcut ? (
                  <ShortcutKeycaps
                    shortcut={sendShortcut}
                    decorative
                    className="ml-1"
                  />
                ) : null}
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}