Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

7.2 KB
Raw Blame
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import type { MenuItem } from "@/ui";
import { showError, confirmChecked } from "@/workbench/messages";
import { promptInput } from "@/workbench/inputDialogs";
import { isBusy } from "./model";
import {
  archiveTask,
  unarchiveTask,
  deleteTask,
  dockTask,
  forkTask,
  loadEntries,
  openTask,
  openTaskInEditorLocation,
  renameTask,
  setSessionLocation,
  undockTask,
  useAgents,
} from "./store";

const canArchive = (task: AgentTask) => !isBusy(task.status) && task.status !== "archived";
const canFork = (task: AgentTask) => canArchive(task) && !!task.capabilities?.fork;

function resolveTasks(arg: unknown): AgentTask[] {
  if (!Array.isArray(arg)) return [];
  return [...new Set(arg)].flatMap((id: unknown) => {
    const task = typeof id === "string" ? useAgents.getState().tasks.get(id) : undefined;
    return task ? [task] : [];
  });
}

async function runTasks(tasks: AgentTask[], run: (task: AgentTask) => Promise<unknown>, title: string) {
  const errors: string[] = [];
  for (const task of tasks) {
    try {
      await run(task);
    } catch (error) {
      errors.push(`${task.title}: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  if (errors.length) await showError(title, errors.join("\n"));
}

async function confirmDelete(tasks: AgentTask[]) {
  if (!tasks.length) return;
  const task = tasks[0]!;
  const multiple = tasks.length > 1;
  const worktree = tasks.some((t) => t.isolation === "worktree");
  const r = await confirmChecked({
    title: multiple ? "Delete Agent Tasks" : "Delete Agent Task",
    message: multiple
      ? tx`Delete ${tasks.length} agent tasks? Their branches and files outside worktrees are kept.`
      : worktree
        ? tx`Delete “${task.title}”? Its branch ${task.branch ?? ""} is kept.`
        : tx`Delete “${task.title}”? Files it changed are kept.`,
    ok: "Delete",
    icon: "warning",
    checkbox: worktree
      ? multiple
        ? "Also remove their worktree folders"
        : "Also remove its worktree folder"
      : undefined,
    checked: worktree,
  });
  if (r)
    await runTasks(
      tasks,
      (t) => deleteTask(t.id, t.isolation === "worktree" && r.checked),
      tx("Cannot delete agent tasks"),
    );
}

export const taskActions: Action[] = [
  {
    id: "agents.retryConversation",
    title: "Retry Loading Conversation",
    category: "Agents",
    hidden: true,
    run: ({ arg }) => {
      const request = arg as { task?: unknown; subagent?: unknown } | null;
      if (typeof request?.task === "string" && (request.subagent == null || typeof request.subagent === "string"))
        return loadEntries(request.task, request.subagent ?? null);
    },
  },
  {
    id: "agents.useToolWindow",
    title: "Chat in Tool Window",
    category: "Agents",
    icon: "open-in-tool-window",
    run: () => setSessionLocation("toolWindow"),
  },
  {
    id: "agents.useEditor",
    title: "Chat in Editor",
    category: "Agents",
    icon: "editor-only",
    run: () => setSessionLocation("editor"),
  },
  {
    id: "agents.openTaskInEditor",
    title: "Open Agent Task in Editor",
    category: "Agents",
    hidden: true,
    run: ({ arg }) => {
      if (typeof arg === "string") openTaskInEditorLocation(arg);
    },
  },
  {
    id: "agents.openTask",
    title: "Open Agent Task",
    category: "Agents",
    hidden: true,
    run: ({ arg }) => {
      if (typeof arg === "string") openTask(arg);
    },
  },
  {
    id: "agents.dockTask",
    title: "Open Agent Task in Tool Window",
    category: "Agents",
    hidden: true,
    run: ({ arg }) => {
      if (typeof arg === "string") dockTask(arg);
    },
  },
  {
    id: "agents.undockTask",
    title: "Open Agent Task in Editor",
    category: "Agents",
    hidden: true,
    run: () => undockTask(),
  },
  {
    id: "agents.renameTask",
    title: "Rename Agent Task",
    category: "Agents",
    hidden: true,
    run: async ({ arg }) => {
      const task = resolveTasks([arg])[0];
      if (!task) return;
      const title = await promptInput({
        title: "Rename Agent Task",
        label: "Name",
        initial: task.title,
        okLabel: "Rename",
      });
      if (title !== null)
        await renameTask(task.id, title).catch((e: unknown) => showError(tx("Couldn't rename the task"), String(e)));
    },
  },
  {
    id: "agents.forkTask",
    title: "Copy Agent Task to a New Task",
    category: "Agents",
    hidden: true,
    run: ({ arg }) => {
      const task = resolveTasks([arg])[0];
      if (task && canFork(task))
        return forkTask(task.id, null).catch((e: unknown) => showError(tx("Couldn't copy the task"), String(e)));
    },
  },
  {
    id: "agents.archiveTasks",
    title: "Archive Agent Tasks",
    category: "Agents",
    hidden: true,
    run: ({ arg }) =>
      runTasks(resolveTasks(arg).filter(canArchive), (task) => archiveTask(task.id), tx("Cannot archive agent tasks")),
  },
  {
    id: "agents.unarchiveTasks",
    title: "Unarchive Agent Tasks",
    category: "Agents",
    hidden: true,
    run: ({ arg }) =>
      runTasks(
        resolveTasks(arg).filter((task) => task.status === "archived"),
        (task) => unarchiveTask(task.id),
        tx("Cannot unarchive agent tasks"),
      ),
  },
  {
    id: "agents.deleteTasks",
    title: "Delete Agent Tasks",
    category: "Agents",
    hidden: true,
    run: ({ arg }) => confirmDelete(resolveTasks(arg)),
  },
];

export function taskMenu(tasks: AgentTask[]): MenuItem[] {
  if (!tasks.length) return [];
  const ids = tasks.map((task) => task.id);
  const task = tasks[0]!;
  const multiple = tasks.length > 1;
  const archived = tasks.filter((task) => task.status === "archived").length;
  const archivable = tasks.filter(canArchive).length;
  return [
    ...(!multiple
      ? ([
          { kind: "action", action: "agents.openTask", label: "Open", arg: task.id },
          { kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
          { kind: "action", action: "terminal.openAt", label: "Open in Terminal", icon: "terminal", arg: task.cwd },
          ...(task.capabilities?.fork && task.status !== "archived"
            ? ([
                {
                  kind: "action",
                  action: "agents.forkTask",
                  label: "Copy to a New Task",
                  icon: "branch",
                  arg: task.id,
                  disabled: !canFork(task),
                },
              ] satisfies MenuItem[])
            : []),
          { kind: "separator" },
        ] satisfies MenuItem[])
      : []),
    ...(archived
      ? ([
          {
            kind: "action",
            action: "agents.unarchiveTasks",
            label: multiple ? tx`Unarchive (${archived})` : "Unarchive",
            arg: ids,
          },
        ] satisfies MenuItem[])
      : []),
    {
      kind: "action",
      action: "agents.archiveTasks",
      label: multiple ? tx`Archive (${archivable})` : "Archive",
      arg: ids,
      disabled: !archivable,
    },
    {
      kind: "action",
      action: "agents.deleteTasks",
      label: multiple ? tx`Delete (${tasks.length})…` : "Delete…",
      arg: ids,
    },
  ];
}