Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

7.1 KB
Raw Blame
import { useEffect, useRef, useState } from "react";
import { useBlockingOverlay } from "../lib/blocking-overlay";
import { portalToBody } from "../lib/portal-visibility";
import { useTranslation } from "react-i18next";
import { ErrorCodes } from "@pi-desktop/shared";
import { useAppStore } from "../stores/app-store";
import { OverlayBackdrop, Button, TooltipButton } from "./ui";
import { IconCircleAlert, IconClose, IconStop, IconTrash } from "./icons";

/**
 * Second confirmation for deleting a project. The store action removes the
 * project record and its stored sessions; the folder on disk is never touched.
 */
export function ProjectDeleteDialog({
  project,
  runningSessionIds,
  onClose,
  onDeleted,
  onError,
}: {
  project: { name: string; path: string; sessionCount: number };
  /**
   * Sessions of this project whose turn is still live. The host refuses the
   * bulk delete (and the single session delete) while one exists, so the dialog
   * names them and stops them as the explicit step its confirm label promises.
   */
  runningSessionIds: string[];
  onClose: () => void;
  onDeleted: () => void | Promise<void>;
  onError: (error: unknown) => void;
}) {
  useBlockingOverlay();
  const { t } = useTranslation();
  const deleteProject = useAppStore((s) => s.deleteProject);
  const abortSession = useAppStore((s) => s.abortSession);
  const [busy, setBusy] = useState(false);
  const busyRef = useRef(false);
  const dialogRef = useRef<HTMLDivElement | null>(null);
  // The surfaces that own this dialog subscribe to `runningSessions`, so a turn
  // that starts or finishes while the dialog is open is reflected here before
  // the user confirms.
  const runningCount = runningSessionIds.length;

  useEffect(() => {
    const previouslyFocused = document.activeElement as HTMLElement | null;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    requestAnimationFrame(() => dialogRef.current?.focus());

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        if (!busyRef.current) onClose();
        return;
      }
      if (event.key !== "Tab") return;
      const focusable = dialogRef.current?.querySelectorAll<HTMLElement>(
        "button:not([disabled])",
      );
      if (!focusable?.length) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };

    window.addEventListener("keydown", onKeyDown);
    return () => {
      window.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = previousOverflow;
      if (previouslyFocused?.isConnected) previouslyFocused.focus();
    };
  }, [onClose]);

  const confirm = async () => {
    if (busyRef.current) return;
    busyRef.current = true;
    setBusy(true);
    try {
      // A live turn still owns its session's tools and transcript, so the host
      // refuses the bulk delete until every attached session is idle. Stopping
      // the listed sessions is the step the confirm button names; a turn that
      // starts after this loop still makes the host refuse with CONFLICT below,
      // which is why the refusal path stays reachable.
      for (const sessionId of runningSessionIds) {
        await abortSession(sessionId);
      }
      await deleteProject(project.path);
      await onDeleted();
    } catch (error) {
      // The host refuses the delete while a task of this project is running;
      // show the same localized explanation the menu guard used to show.
      if ((error as { errorCode?: unknown } | null)?.errorCode === ErrorCodes.CONFLICT) {
        onError(new Error(t("project.deleteRunningBlocked")));
        return;
      }
      onError(error);
    } finally {
      busyRef.current = false;
      setBusy(false);
    }
  };

  const dialog = (
    <OverlayBackdrop
      className="overlay project-instructions-dialog-overlay"
      role="presentation"
      onClick={(event) => {
        if (event.target === event.currentTarget && !busyRef.current) onClose();
      }}
    >
      <div
        ref={dialogRef}
        className="dialog project-instructions-dialog project-delete-dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="project-delete-dialog-title"
        aria-describedby={`project-delete-dialog-description project-delete-dialog-sessions project-delete-dialog-folder-kept${
          runningCount > 0 ? " project-delete-dialog-running" : ""
        }`}
        tabIndex={-1}
        onClick={(event) => event.stopPropagation()}
      >
        <div className="project-instructions-dialog-head">
          <div>
            <h2 id="project-delete-dialog-title" className="project-instructions-dialog-title">
              <IconCircleAlert size={17} aria-hidden />
              {t("project.deleteTitle")}
            </h2>
            <div className="project-instructions-dialog-project">{project.name}</div>
          </div>
          <TooltipButton
            type="button"
            className="project-instructions-dialog-close"
            tooltip={t("project.deleteCancel")}
            ariaLabel={t("project.deleteCancel")}
            disabled={busy}
            onClick={onClose}
          >
            <IconClose size={16} />
          </TooltipButton>
        </div>
        <div className="project-delete-dialog-body">
          <p id="project-delete-dialog-description" className="project-memory-dialog-description">
            {t("project.deleteDescription", { name: project.name })}
          </p>
          <p id="project-delete-dialog-sessions" className="project-delete-dialog-warning">
            <IconTrash size={14} aria-hidden />
            <span>{t("project.deleteSessions", { count: project.sessionCount })}</span>
          </p>
          {runningCount > 0 ? (
            <p id="project-delete-dialog-running" className="project-delete-dialog-running">
              <IconStop size={14} aria-hidden />
              <span>{t("project.deleteRunning", { count: runningCount })}</span>
            </p>
          ) : null}
          <p id="project-delete-dialog-folder-kept" className="project-memory-dialog-hint">
            {t("project.deleteFolderKept")}
          </p>
        </div>
        <div className="project-instructions-dialog-actions">
          <Button type="button" variant="ghost" disabled={busy} onClick={onClose}>
            {t("project.deleteCancel")}
          </Button>
          <Button
            type="button"
            variant="primary"
            className="project-delete-dialog-confirm"
            disabled={busy}
            onClick={() => void confirm()}
          >
            {busy
              ? t("project.deleting")
              : runningCount > 0
                ? t("project.deleteRunningConfirm")
                : t("project.deleteConfirm")}
          </Button>
        </div>
      </div>
    </OverlayBackdrop>
  );

  return typeof document === "undefined" ? dialog : portalToBody(dialog);
}