Skip to content

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

Go
10.1 KB
Raw Blame
"use client";

import { useState, type ReactNode } from "react";
import {
  AlertCircle,
  Archive,
  Copy,
  ExternalLink,
  RotateCcw,
  Settings2,
  Square,
} from "@multica/ui/icons";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import type { Agent } from "@multica/core/types";
import type { AgentPresenceDetail } from "@multica/core/agents";
import { isArchivableAgent, isMikaAgent } from "@multica/core/onboarding";
import { api } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { workspaceKeys } from "@multica/core/workspace/queries";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@multica/ui/components/ui/alert-dialog";
import {
  DropdownMenuItem,
  DropdownMenuSeparator,
} from "@multica/ui/components/ui/dropdown-menu";
import { useT } from "../../i18n";
import { AppLink, useIntentNavigate } from "../../navigation";
import { CollectionRowMenu } from "../../layout/collection-list";

interface AgentRowActionsProps {
  agent: Agent;
  presence: AgentPresenceDetail | null | undefined;
  // True when the current user can manage this agent (owner of agent or
  // workspace admin/owner). Mirrors the back-end's canManageAgent check —
  // the server is still the source of truth, this only hides UI for ops
  // the user can't perform.
  canManage: boolean;
  // Destination of "Duplicate" — the manual create form, pre-populated with
  // this agent's config as a template. A href rather than a callback so the
  // menu item is a real link (modifier-click opens it in a new tab).
  duplicateHref: string;
  /** Items for the top of the menu, for actions only one surface offers. */
  leading?: ReactNode;
  /** For rows that open the menu only on right-click. */
  triggerHidden?: boolean;
}

/**
 * Per-row dropdown menu for the agents list. The set of actions is derived
 * from (a) the agent's lifecycle state (active vs archived) and (b) the
 * caller's permission level. "Open in new tab" applies to every row, so the
 * trigger always renders. The same items open on right-click.
 */
export function AgentRowActions({
  agent,
  presence,
  canManage,
  duplicateHref,
  leading,
  triggerHidden,
}: AgentRowActionsProps) {
  const { t } = useT("agents");
  const { t: tCommon } = useT("common");
  const paths = useWorkspacePaths();
  const intentNavigate = useIntentNavigate();
  const wsId = useWorkspaceId();
  const qc = useQueryClient();

  const [confirmArchive, setConfirmArchive] = useState(false);
  const [confirmCancel, setConfirmCancel] = useState(false);

  const isArchived = !!agent.archived_at;
  const runningCount = presence?.runningCount ?? 0;
  const queuedCount = presence?.queuedCount ?? 0;
  const hasActiveWork = runningCount + queuedCount > 0;

  // Derive which menu items to render. Doing this once here keeps the JSX
  // below a flat list of conditionals rather than a tangle of role/state
  // branches.
  const showStop = canManage && !isArchived && hasActiveWork;
  const showDuplicate = !isArchived; // any workspace member can duplicate
  const showArchive = canManage && !isArchived && isArchivableAgent(agent);
  const showRestore = canManage && isArchived;

  const invalidateAgents = () => {
    qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
  };

  const handleArchive = async () => {
    try {
      await api.archiveAgent(agent.id);
      invalidateAgents();
      toast.success(t(($) => $.row_actions.agent_archived_toast));
    } catch (e) {
      toast.error(e instanceof Error ? e.message : t(($) => $.row_actions.archive_failed_toast));
    }
  };

  const handleRestore = async () => {
    try {
      await api.restoreAgent(agent.id);
      invalidateAgents();
      toast.success(t(($) => $.row_actions.agent_restored_toast));
    } catch (e) {
      toast.error(e instanceof Error ? e.message : t(($) => $.row_actions.restore_failed_toast));
    }
  };

  const handleCancelTasks = async () => {
    try {
      const { cancelled } = await api.cancelAgentTasks(agent.id);
      invalidateAgents();
      toast.success(
        cancelled === 0
          ? t(($) => $.row_actions.no_tasks_to_cancel_toast)
          : t(($) => $.row_actions.cancelled_tasks_toast, { count: cancelled }),
      );
    } catch (e) {
      toast.error(e instanceof Error ? e.message : t(($) => $.row_actions.cancel_failed_toast));
    }
  };

  return (
    <>
      <CollectionRowMenu
        label={t(($) => $.row.actions_aria)}
        contentClassName="w-auto"
        triggerHidden={triggerHidden}
      >
        {leading && (
          <>
            {leading}
            <DropdownMenuSeparator />
          </>
        )}
        {/* Same shape as every other entity row menu: an explicit CTA is a
            foreground open executed through the adapter (an anchor-based
            item would depend on native activation surviving the menu
            closing under it). */}
        <DropdownMenuItem
          onClick={() =>
            intentNavigate(
              paths.agentDetail(agent.id),
              "foreground-tab",
              agent.name,
            )
          }
        >
          <ExternalLink className="h-3.5 w-3.5" />
          {tCommon(($) => $.navigation.open_in_new_tab)}
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem
          onClick={() =>
            intentNavigate(`${paths.agentDetail(agent.id)}?view=general`, "push")
          }
        >
          <Settings2 className="h-3.5 w-3.5" />
          {t(($) => $.detail.settings)}
        </DropdownMenuItem>
        {showStop && (
          <DropdownMenuItem
            onClick={() => setConfirmCancel(true)}
          >
            <Square className="h-3.5 w-3.5" />
            {t(($) => $.row_actions.cancel_all_tasks)}
          </DropdownMenuItem>
        )}
        {showDuplicate && (
          <DropdownMenuItem render={<AppLink href={duplicateHref} />}>
            <Copy className="h-3.5 w-3.5" />
            {t(($) => $.row_actions.duplicate)}
          </DropdownMenuItem>
        )}
        {showRestore && (
          <DropdownMenuItem onClick={handleRestore}>
            <RotateCcw className="h-3.5 w-3.5" />
            {t(($) => $.row_actions.restore)}
          </DropdownMenuItem>
        )}
        {showArchive && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              variant="destructive"
              onClick={() => setConfirmArchive(true)}
            >
              <Archive className="h-3.5 w-3.5" />
              {t(($) => $.row_actions.archive)}
            </DropdownMenuItem>
          </>
        )}
      </CollectionRowMenu>

      {confirmCancel && (
        <AlertDialog
          open
          onOpenChange={(v) => {
            if (!v) setConfirmCancel(false);
          }}
        >
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>
                {t(($) => $.row_actions.cancel_dialog_title, { name: agent.name })}
              </AlertDialogTitle>
              <AlertDialogDescription>
                {describeCancelImpact(runningCount, queuedCount, t)}
                {runningCount > 0 && t(($) => $.row_actions.cancel_dialog_running_note)}
                {t(($) => $.row_actions.cancel_dialog_irreversible)}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>{t(($) => $.row_actions.cancel_dialog_keep)}</AlertDialogCancel>
              <AlertDialogAction
                variant="destructive"
                onClick={() => {
                  setConfirmCancel(false);
                  void handleCancelTasks();
                }}
              >
                {t(($) => $.row_actions.cancel_dialog_confirm)}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      )}

      {confirmArchive && (
        <AlertDialog
          open
          onOpenChange={(v) => {
            if (!v) setConfirmArchive(false);
          }}
        >
          <AlertDialogContent>
            <AlertDialogHeader>
              <div className="flex items-start gap-3">
                <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-destructive/10">
                  <AlertCircle className="h-5 w-5 text-destructive" />
                </div>
                <div className="min-w-0 flex-1">
                  <AlertDialogTitle className="break-all">
                    {t(($) => $.row_actions.archive_dialog_title, { name: agent.name })}
                  </AlertDialogTitle>
                  <AlertDialogDescription>
                    {t(($) => $.row_actions.archive_dialog_description)}
                    {isMikaAgent(agent) && t(($) => $.row_actions.archive_dialog_mika_note)}
                  </AlertDialogDescription>
                </div>
              </div>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>{t(($) => $.row_actions.archive_dialog_cancel)}</AlertDialogCancel>
              <AlertDialogAction
                variant="destructive"
                onClick={() => {
                  setConfirmArchive(false);
                  void handleArchive();
                }}
              >
                {t(($) => $.row_actions.archive_dialog_confirm)}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      )}
    </>
  );
}

type AgentsT = ReturnType<typeof useT<"agents">>["t"];

export function describeCancelImpact(running: number, queued: number, t: AgentsT): string {
  if (running === 0 && queued === 0) {
    return t(($) => $.row_actions.cancel_dialog_no_tasks);
  }
  const parts: string[] = [];
  if (running > 0) parts.push(t(($) => $.row_actions.cancel_dialog_running, { count: running }));
  if (queued > 0) parts.push(t(($) => $.row_actions.cancel_dialog_queued, { count: queued }));
  return t(($) => $.row_actions.cancel_dialog_impact, {
    summary: parts.join(" + "),
    count: running + queued,
  });
}