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.

28.9 KB
Raw Blame
/** Agent tasks of the open project, mirrored from `ide-agent` through `agentSubscribe`. */
import { Channel } from "@tauri-apps/api/core";
import { useEffect, useState } from "react";
import { create } from "zustand";
import type {
  AgentChange,
  AgentCommand,
  AgentConfigOption,
  AgentEntry,
  AgentEvent,
  AgentImage,
  AgentLimit,
  AgentProvider,
  AgentTask,
  Isolation,
} from "@/bindings";
import { useProject } from "@/platform/project";
import { defaultTaskProject } from "./project";
import { call, commands, isTauri } from "@/platform/ipc";
import { editorService, notifications, notifyTabTitlesChanged, toolWindowService } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { confirm } from "@/workbench/messages";
import { bypassDefaults, canSend, emptyDraft, toPrompt, type ComposerDraft, type FileRef } from "./composerModel";
import { withQuote } from "./conversation";
import {
  HOME_KEY,
  HOME_KIND,
  SESSION_KIND,
  TOOL_WINDOW,
  attentionChange,
  entriesKey,
  isBusy,
  sessionKey,
  upsertEntry,
} from "./model";

/** New Task page settings (its text lives in the `HOME` composer). */
export interface Draft {
  projectRoot?: string | null;
  provider: string;
  /** Settings chosen for the next task, by option id (reset when the agent changes). */
  config: Record<string, string>;
  /** Thinking-level choices by model value for this provider. */
  thoughtLevels?: Record<string, Record<string, string>>;
  isolation: Isolation;
  /** The user picked `isolation`: otherwise a task runs in the local checkout. */
  isolationChosen?: boolean;
  /** `null`: the current branch. */
  base: string | null;
}

/** Composer key of the New Task page; sessions use their task id. */
export const HOME = "home";

export type SessionLocation = "editor" | "toolWindow";

interface AgentsState {
  loaded: boolean;
  /** Why the tasks could not be loaded. */
  error: string | null;
  tasks: Map<string, AgentTask>;
  /** Tasks with unseen replies or status changes in this project. */
  unread: Set<string>;
  /** Entries of the tasks (and subagents) opened in this window, by `entriesKey`. */
  entries: Map<string, AgentEntry[]>;
  entryLoads: Map<string, { error: string | null }>;
  changes: Map<string, AgentChange[]>;
  /** Scroll position and follow-output preference by conversation, shared by both hosts. */
  scrollPositions: Map<string, { top: number; stick: boolean }>;
  providers: AgentProvider[];
  /** The usage limits each agent last reported for its account, by provider. */
  limits: Map<string, AgentLimit[]>;
  draft: Draft;
  composers: Map<string, ComposerDraft>;
  /** The composer typed in last: where "Send to Agent" adds references. */
  lastComposer: string;
  /** First messages of past tasks, newest first (New Task page ↑). */
  history: string[];
  /** The composer asked to take focus (`seq` tells repeated requests apart). */
  focus: { key: string; seq: number } | null;
  /** Task shown inside the Agents tool window instead of an editor tab. */
  docked: string | null;
  sessionLocation: SessionLocation;
  lastTask: string | null;
  homeOpen: boolean;
}

const DRAFT_KEY = "openidea.agents.draft.v2";
const HISTORY_KEY = "openidea.agents.history.v1";
const HISTORY_SIZE = 50;
const SESSION_LOCATION_KEY = "openidea.agents.sessionLocation.v1";

function load<T>(key: string, fallback: T): T {
  try {
    const saved = JSON.parse(globalThis.localStorage?.getItem(key) ?? "null") as T | null;
    return saved ?? fallback;
  } catch {
    return fallback;
  }
}

function save(key: string, value: unknown) {
  try {
    globalThis.localStorage?.setItem(key, JSON.stringify(value));
  } catch {
    /* storage unavailable */
  }
}

const fallbackDraft: Draft = { provider: "claude", config: {}, isolation: "local", base: null };

/**
 * The saved New Task settings. A worktree is used only when the user picked it: drafts
 * saved before that choice was recorded carried the old default (`worktree`) instead.
 */
export function savedDraft(saved: Partial<Draft>): Draft {
  const draft = { ...fallbackDraft, ...saved };
  return draft.isolationChosen ? draft : { ...draft, isolation: "local" };
}

export const useAgents = create<AgentsState>(() => ({
  loaded: false,
  error: null,
  tasks: new Map(),
  unread: new Set(),
  entries: new Map(),
  entryLoads: new Map(),
  changes: new Map(),
  providers: [],
  limits: new Map(),
  draft: savedDraft(load<Partial<Draft>>(DRAFT_KEY, {})),
  composers: new Map(),
  lastComposer: HOME,
  history: load<string[]>(HISTORY_KEY, []),
  focus: null,
  docked: null,
  sessionLocation: load<unknown>(SESSION_LOCATION_KEY, null) === "toolWindow" ? "toolWindow" : "editor",
  lastTask: null,
  homeOpen: false,
  scrollPositions: new Map(),
}));

export function updateDraft(patch: Partial<Draft>) {
  const current = useAgents.getState().draft;
  const draft = {
    ...current,
    ...(patch.provider && patch.provider !== current.provider ? { thoughtLevels: {} } : {}),
    ...patch,
  };
  useAgents.setState({ draft });
  save(DRAFT_KEY, draft);
}

/** Config for the selected model, with only supported draft choices applied. */
export function draftConfig(provider: AgentProvider | undefined, draft: Draft): AgentConfigOption[] {
  const config = (provider?.config ?? [])
    .filter((o) => o.category !== "thought_level")
    .map((o) => {
      const choice = draft.config[o.id];
      return { ...o, current: choice !== undefined && o.values.some((v) => v.value === choice) ? choice : o.current };
    });
  const model = config.find((o) => o.category === "model")?.current;
  if (model) {
    config.push(
      ...(provider?.thoughtLevels?.[model] ?? []).map((o) => {
        const choice = draft.thoughtLevels?.[model]?.[o.id];
        return { ...o, current: choice !== undefined && o.values.some((v) => v.value === choice) ? choice : o.current };
      }),
    );
  }
  return config;
}

export function setDraftOption(id: string, value: string) {
  const { draft, providers } = useAgents.getState();
  const config = draftConfig(
    providers.find((p) => p.id === draft.provider),
    draft,
  );
  const model = config.find((o) => o.category === "model")?.current;
  if (model && config.find((o) => o.id === id)?.category === "thought_level") {
    updateDraft({
      thoughtLevels: { ...draft.thoughtLevels, [model]: { ...draft.thoughtLevels?.[model], [id]: value } },
    });
  } else {
    updateDraft({ config: { ...draft.config, [id]: value } });
  }
}

export const composerDraft = (key: string) => useAgents.getState().composers.get(key) ?? emptyDraft();

export function updateComposer(key: string, patch: Partial<ComposerDraft>) {
  useAgents.setState((s) => ({
    composers: new Map(s.composers).set(key, { ...(s.composers.get(key) ?? emptyDraft()), ...patch }),
    lastComposer: key,
  }));
}

/** Session tabs on screen; a task can be shown in more than one split. */
const visible = new Map<string, number>();
const windowFocused = () => document.visibilityState !== "hidden" && document.hasFocus();
const viewing = (task: string) => visible.has(task) && windowFocused();

function setUnread(task: string, value: boolean) {
  const s = useAgents.getState();
  if (s.unread.has(task) === value) return;
  const unread = new Set(s.unread);
  if (value) unread.add(task);
  else unread.delete(task);
  useAgents.setState({ unread });
}

function markUnread(task: string) {
  const current = useAgents.getState().tasks.get(task);
  if (current && current.status !== "archived" && !viewing(task)) setUnread(task, true);
}

export function markVisible(task: string): () => void {
  visible.set(task, (visible.get(task) ?? 0) + 1);
  const read = () => {
    if (viewing(task)) setUnread(task, false);
  };
  read();
  window.addEventListener("focus", read);
  document.addEventListener("visibilitychange", read);
  return () => {
    const count = (visible.get(task) ?? 1) - 1;
    if (count) visible.set(task, count);
    else visible.delete(task);
    window.removeEventListener("focus", read);
    document.removeEventListener("visibilitychange", read);
  };
}

let generation = 0;

/** Subscribes this window to the project's agents (again after the project changed). */
export async function connect(): Promise<void> {
  if (!isTauri()) return;
  const gen = ++generation;
  const channel = new Channel<AgentEvent>();
  channel.onmessage = (e) => {
    if (gen === generation) onEvent(e);
  };
  let tasks: AgentTask[], providers: AgentProvider[];
  try {
    [tasks, providers] = await Promise.all([
      call(commands.agentSubscribe(channel)),
      useProject.getState().project?.trusted === false
        ? Promise.resolve([] as AgentProvider[])
        : call(commands.agentProviders()),
    ]);
  } catch (e) {
    if (gen === generation) useAgents.setState({ loaded: true, error: e instanceof Error ? e.message : String(e) });
    return;
  }
  if (gen !== generation) return;
  useAgents.setState({
    loaded: true,
    error: null,
    tasks: new Map(tasks.map((t) => [t.id, t])),
    entries: new Map(),
    entryLoads: new Map(),
    changes: new Map(),
    providers,
  });
  notifyTabTitlesChanged();
  // Restored tabs of tasks deleted meanwhile close, like editors of deleted files.
  const editors = editorService();
  for (const t of editors.openTabs?.() ?? []) {
    const task = (t.input.data as { task?: string } | undefined)?.task;
    if (t.input.kind === SESSION_KIND && task && !useAgents.getState().tasks.has(task))
      await editors.closeInput?.(t.input.key);
  }
}

export function disconnect() {
  generation++;
  useAgents.setState({
    loaded: false,
    error: null,
    tasks: new Map(),
    unread: new Set(),
    entries: new Map(),
    entryLoads: new Map(),
    changes: new Map(),
    docked: null,
    lastTask: null,
    homeOpen: false,
    scrollPositions: new Map(),
  });
}

function onEvent(e: AgentEvent) {
  const s = useAgents.getState();
  switch (e.type) {
    case "task": {
      const prev = s.tasks.get(e.task.id);
      useAgents.setState({ tasks: new Map(s.tasks).set(e.task.id, e.task) });
      if (prev && (prev.title !== e.task.title || prev.status !== e.task.status)) notifyTabTitlesChanged();
      if (e.task.status === "archived") setUnread(e.task.id, false);
      else if (attentionChange(prev?.status, e.task.status)) markUnread(e.task.id);
      notifyChange(prev, e.task);
      if (prev?.status !== e.task.status && !isBusy(e.task.status)) {
        void refreshChanges(e.task.id);
        void refreshProviders();
      }
      break;
    }
    case "removed": {
      const tasks = new Map(s.tasks);
      tasks.delete(e.id);
      const composers = new Map(s.composers);
      composers.delete(e.id);
      const unread = new Set(s.unread);
      unread.delete(e.id);
      useAgents.setState({ tasks, composers, unread, ...(s.docked === e.id ? { docked: null } : {}) });
      void editorService().closeInput?.(sessionKey(e.id));
      break;
    }
    case "truncated": {
      const current = s.entries.get(e.task);
      if (current) useAgents.setState({ entries: new Map(s.entries).set(e.task, current.slice(0, e.length)) });
      scheduleChanges(e.task);
      break;
    }
    case "providers": {
      void refreshProviders();
      break;
    }
    case "limits": {
      useAgents.setState({ limits: new Map(s.limits).set(e.provider, e.limits) });
      break;
    }
    case "entry": {
      if (
        !e.subagent &&
        ((e.entry.type === "agent" && e.entry.text.trim()) ||
          e.entry.type === "error" ||
          (e.entry.type === "permission" && e.entry.chosen === null))
      ) {
        markUnread(e.task);
      }
      const key = entriesKey(e.task, e.subagent);
      const current = s.entries.get(key);
      if (!current) return;
      const next = upsertEntry(current, e.index, e.entry);
      if (next) useAgents.setState({ entries: new Map(s.entries).set(key, next) });
      else void loadEntries(e.task, e.subagent);
      if (e.entry.type === "tool" && e.entry.status === "completed" && e.entry.diffs.length) {
        scheduleChanges(e.task);
      }
      break;
    }
  }
}

function notifyChange(prev: AgentTask | undefined, task: AgentTask) {
  const change = attentionChange(prev?.status, task.status);
  if (!change) return;
  if (viewing(task.id)) return;
  const body =
    change === "input"
      ? "Waiting for your answer"
      : change === "failed"
        ? (task.error ?? "The agent stopped")
        : "Finished";
  notifications().notify({
    level: change === "failed" ? "error" : "info",
    title: task.title,
    body,
    key: `agent:${task.id}`,
    group: "tools",
    sticky: change !== "finished",
    actions: [{ label: change === "finished" ? "Review" : "Open", run: () => openTask(task.id) }],
  });
}

/** Loads the entries of the task's conversation, or of its subagent `subagent`'s. */
export async function loadEntries(task: string, subagent: string | null = null): Promise<void> {
  const key = entriesKey(task, subagent);
  if (useAgents.getState().entryLoads.get(key)?.error === null) return;
  const load = { error: null };
  useAgents.setState((s) => ({ entryLoads: new Map(s.entryLoads).set(key, load) }));
  let timer: ReturnType<typeof setTimeout> | undefined;
  try {
    const entries = await Promise.race([
      call(commands.agentEntries(task, subagent)),
      new Promise<never>((_, reject) => {
        timer = setTimeout(() => reject(new Error(tx("Loading the conversation timed out. Try again."))), 35_000);
      }),
    ]);
    if (useAgents.getState().entryLoads.get(key) !== load) return;
    useAgents.setState((s) => {
      const entryLoads = new Map(s.entryLoads);
      entryLoads.delete(key);
      return { entries: new Map(s.entries).set(key, entries), entryLoads };
    });
  } catch (e) {
    if (useAgents.getState().entryLoads.get(key) !== load) return;
    const error = (e instanceof Error ? e.message : String(e)).trim() || tx("Unknown error");
    useAgents.setState((s) => ({ entryLoads: new Map(s.entryLoads).set(key, { error }) }));
  } finally {
    clearTimeout(timer);
  }
}

export async function refreshChanges(task: string): Promise<void> {
  try {
    const changes = await call(commands.agentChanges(task));
    useAgents.setState((s) => ({ changes: new Map(s.changes).set(task, changes) }));
  } catch {
    // The worktree is gone or not a repository: nothing to list.
    useAgents.setState((s) => ({ changes: new Map(s.changes).set(task, []) }));
  }
}

const pendingChanges = new Map<string, ReturnType<typeof setTimeout>>();
function scheduleChanges(task: string) {
  if (pendingChanges.has(task)) return;
  pendingChanges.set(
    task,
    setTimeout(() => {
      pendingChanges.delete(task);
      void refreshChanges(task);
    }, 500),
  );
}

/** Reloads the agent list (custom and registry agents are re-read). */
export async function refreshProviders() {
  const providers = await call(commands.agentProviders()).catch(() => null);
  if (providers) useAgents.setState({ providers });
}

export const NO_COMMANDS: readonly AgentCommand[] = [];

/**
 * Slash commands to complete: what the agent offered (`offered`; fetched again when it
 * changes) plus, for Claude Code, the skills and custom commands on disk. Without `task`,
 * those of the project.
 */
export function useAgentCommands(
  provider: string | undefined,
  task: string | null,
  offered: readonly AgentCommand[],
): readonly AgentCommand[] {
  const [found, setFound] = useState<{ for: unknown[]; list: readonly AgentCommand[] } | null>(null);
  useEffect(() => {
    if (!provider || !isTauri()) return;
    let alive = true;
    call(commands.agentCommands(provider, task))
      .then((list) => alive && setFound({ for: [provider, task, offered], list }))
      .catch(() => {});
    return () => {
      alive = false;
    };
  }, [provider, task, offered]);
  // Until the list for these arguments arrives, what the agent offered.
  const current = found && found.for[0] === provider && found.for[1] === task && found.for[2] === offered;
  return current ? found.list : offered;
}

export function openTask(task: string) {
  if (useAgents.getState().sessionLocation === "toolWindow") {
    showDockedTask(task);
    return;
  }
  useAgents.setState({ lastTask: task, homeOpen: false, lastComposer: task });
  openTaskInEditor(task);
}

function openTaskInEditor(task: string) {
  // The title rides along so a restored tab has it before the tasks load.
  const title = useAgents.getState().tasks.get(task)?.title;
  void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus: true });
}

function showDockedTask(task: string) {
  useAgents.setState({ docked: task, lastTask: task, homeOpen: false, lastComposer: task });
  toolWindowService().show(TOOL_WINDOW, true);
  void editorService().closeInput?.(sessionKey(task));
}

function saveSessionLocation(location: SessionLocation) {
  useAgents.setState({ sessionLocation: location });
  save(SESSION_LOCATION_KEY, location);
  if (location === "toolWindow") {
    for (const { input } of editorService().openTabs?.() ?? []) {
      if (input.kind === SESSION_KIND || input.kind === HOME_KIND) void editorService().closeInput?.(input.key);
    }
  }
}

/** Conversation placement is an Agents-wide preference, shared by every task. */
export function setSessionLocation(location: SessionLocation) {
  const s = useAgents.getState();
  if (s.sessionLocation === location) return;
  const active = editorService().activeInput?.();
  const activeTask = active?.kind === SESSION_KIND ? (active.data as { task: string }).task : null;
  const home = s.homeOpen || active?.kind === HOME_KIND;
  const task =
    s.docked ??
    activeTask ??
    (s.lastTask && s.tasks.has(s.lastTask) ? s.lastTask : null) ??
    [...s.tasks.values()]
      .filter((t) => t.status !== "archived")
      .sort((a, b) => (b.updatedMs ?? b.createdMs ?? 0) - (a.updatedMs ?? a.createdMs ?? 0))[0]?.id;
  saveSessionLocation(location);
  useAgents.setState({ docked: null, homeOpen: false });
  if (home) {
    openHome();
  } else if (task) {
    openTask(task);
  } else if (location === "toolWindow") {
    openHome();
  }
}

/** Dragging a session into the tool window selects the same placement for other tasks. */
export function dockTask(task: string) {
  saveSessionLocation("toolWindow");
  showDockedTask(task);
}

export function undockTask() {
  setSessionLocation("editor");
}

/** An explicit editor drop also updates where subsequent sessions open. */
export function openTaskInEditorLocation(task: string) {
  saveSessionLocation("editor");
  useAgents.setState({ docked: null, homeOpen: false });
  openTask(task);
}

/** Opens the New Task page; `prompt` pre-fills it. */
export function openHome(prompt?: string) {
  const project = useProject.getState().project;
  useAgents.setState({ lastComposer: HOME });
  if (project?.workspace) {
    const previous = useAgents.getState().draft.projectRoot;
    const projectRoot = defaultTaskProject(project, editorService().activePath(), previous);
    updateDraft({ projectRoot, ...(projectRoot !== previous ? { base: null } : {}) });
  }
  if (prompt !== undefined) updateComposer(HOME, { text: prompt });
  if (useAgents.getState().sessionLocation === "toolWindow") {
    useAgents.setState({ docked: null, homeOpen: true });
    toolWindowService().show(TOOL_WINDOW, true);
    void editorService().closeInput?.(HOME_KEY);
    return;
  }
  void editorService().openInput({ kind: HOME_KIND, key: HOME_KEY, data: {} }, { focus: true });
}

/** `isolation` overrides the draft's (a project without git can only use the local checkout). */
export async function startTask(
  isolation: Isolation = useAgents.getState().draft.isolation,
  projectRoot: string | null = null,
): Promise<void> {
  const { draft, providers } = useAgents.getState();
  const composer = composerDraft(HOME);
  if (!canSend(composer)) return;
  const options = draftConfig(
    providers.find((p) => p.id === draft.provider),
    draft,
  );
  const defaults = bypassDefaults(options);
  const config = options.flatMap((o) => {
    const value =
      o.category === "model" || o.category === "thought_level"
        ? o.current
        : (draft.config[o.id] ?? defaults[o.id] ?? null);
    return value !== null && o.values.some((v) => v.value === value) ? [{ id: o.id, value }] : [];
  });
  const task = await call(
    commands.agentCreate({
      projectRoot,
      prompt: toPrompt(composer),
      provider: draft.provider,
      config,
      isolation,
      base: isolation === "worktree" ? draft.base : null,
    }),
  );
  // Its events can arrive before this reply: keep the newer state they carried.
  useAgents.setState((s) => ({
    tasks: s.tasks.has(task.id) ? s.tasks : new Map(s.tasks).set(task.id, task),
    entries: new Map(s.entries).set(task.id, s.entries.get(task.id) ?? []),
  }));
  updateDraft({ projectRoot });
  remember(composer.text.trim());
  updateComposer(HOME, emptyDraft());
  if ((await editorService().closeInput?.(HOME_KEY)) !== false) openTask(task.id);
}

function remember(text: string) {
  if (!text) return;
  const history = [text, ...useAgents.getState().history.filter((h) => h !== text)].slice(0, HISTORY_SIZE);
  useAgents.setState({ history });
  save(HISTORY_KEY, history);
}

/** Sends the session composer's message: queued while the agent works, or with `now` interrupting it. */
export async function sendMessage(task: string, now: boolean): Promise<void> {
  const composer = composerDraft(task);
  if (!canSend(composer)) return;
  await call(commands.agentPrompt(task, toPrompt(composer), now));
  updateComposer(task, emptyDraft());
}

/** Moves the caret to the end of composer `key`. */
export function focusComposer(key: string) {
  useAgents.setState((s) => ({ focus: { key, seq: (s.focus?.seq ?? 0) + 1 } }));
}

/** Quotes `text` (a selection of the conversation) in the task's composer, to reply to it. */
export function quoteInComposer(task: string, text: string) {
  updateComposer(task, { text: withQuote(composerDraft(task).text, text) });
  focusComposer(task);
}

/** Copies the task's conversation into a new task (up to its first `turns` turns) and opens it. */
export async function forkTask(task: string, turns: number | null): Promise<void> {
  const copy = await call(commands.agentFork(task, turns));
  useAgents.setState((s) => ({
    tasks: s.tasks.has(copy.id) ? s.tasks : new Map(s.tasks).set(copy.id, copy),
  }));
  openTask(copy.id);
}

/** Puts a message back in the task's composer, above anything typed meanwhile. */
function restoreComposer(task: string, text: string, images: AgentImage[]) {
  const current = composerDraft(task);
  updateComposer(task, {
    text: current.text ? `${text}\n${current.text}` : text,
    images: [...images, ...current.images],
  });
  focusComposer(task);
}

/** Waits until a running turn has stopped, so it can be dropped. */
async function stopForEdit(task: string) {
  const busy = () => isBusy(useAgents.getState().tasks.get(task)?.status ?? "ready");
  if (!busy()) return;
  await cancelTask(task);
  await settled(task);
  if (busy()) throw new Error(tx("The agent is still stopping. Try again once it has stopped."));
}

/**
 * Runs the conversation again from turn `turn` with `text` as its message: the agent is
 * stopped if it works, that turn and the later ones are dropped, then `text` is sent.
 * Whatever fails, the message is kept in the composer so it can be sent again.
 */
export async function rerunFrom(task: string, turn: number, text: string, images: AgentImage[] = []): Promise<boolean> {
  if (
    turn === 0 &&
    !(await confirm({
      title: "Start a Fresh Agent Session",
      message:
        "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.",
      ok: "Start Fresh",
      icon: "warning",
    }))
  )
    return false;
  try {
    await stopForEdit(task);
    await call(commands.agentRollback(task, turn));
    await call(commands.agentPrompt(task, { text, files: [], images }, false));
  } catch (e) {
    restoreComposer(task, text, images);
    throw e;
  }
  return true;
}

/** Drops `turn` and the later turns, and puts the message back in the composer to edit. */
export async function retractFrom(task: string, turn: number, text: string, images: AgentImage[] = []): Promise<void> {
  try {
    await stopForEdit(task);
    const prompt = await call(commands.agentRollback(task, turn));
    // The agent only hands back the text; the images come from the message itself.
    restoreComposer(task, prompt?.text ?? text, images);
  } catch (e) {
    restoreComposer(task, text, images);
    throw e;
  }
}

/** Resolves once the task's turn has ended (or after a while). */
function settled(task: string, timeoutMs = 15_000): Promise<void> {
  const done = () => !isBusy(useAgents.getState().tasks.get(task)?.status ?? "ready");
  if (done()) return Promise.resolve();
  return new Promise((resolve) => {
    const finish = () => {
      stop();
      clearTimeout(timer);
      resolve();
    };
    const stop = useAgents.subscribe(() => done() && finish());
    const timer = setTimeout(finish, timeoutMs);
  });
}

/** Sends an earlier message again (queued while the agent works). */
export const resendMessage = (task: string, text: string) =>
  call(commands.agentPrompt(task, { text, files: [], images: [] }, false));

/** Takes a queued message back into the composer to edit it. */
export async function editQueued(task: string, queued: string): Promise<void> {
  const item = await call(commands.agentUnqueue(task, queued));
  const current = composerDraft(task);
  const cwd = useAgents.getState().tasks.get(task)?.cwd ?? "";
  const files: FileRef[] = item.prompt.files.map((path) => ({
    path,
    rel: path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path,
  }));
  updateComposer(task, {
    text: current.text ? `${item.prompt.text}\n${current.text}` : item.prompt.text,
    files: [...files, ...current.files],
    images: [...item.prompt.images, ...current.images],
  });
}

export const removeQueued = (task: string, queued: string) => call(commands.agentUnqueue(task, queued));
export const sendQueuedNow = (task: string, queued: string) => call(commands.agentSendQueuedNow(task, queued));
export const setTaskConfig = (task: string, option: string, value: string) =>
  call(commands.agentSetConfig(task, option, value));

/** The composer the user is looking at: the Agents surface on show, else the one typed in last. */
function activeComposerKey(): string {
  const s = useAgents.getState();
  // The tool window shows one conversation at a time; its inline New Task page wins.
  if (s.sessionLocation === "toolWindow") {
    if (s.homeOpen) return HOME;
    if (s.docked && s.tasks.has(s.docked)) return s.docked;
  }
  const active = editorService().activeInput?.();
  if (active?.kind === HOME_KIND) return HOME;
  if (active?.kind === SESSION_KIND) {
    const task = (active.data as { task?: unknown } | undefined)?.task;
    if (typeof task === "string" && s.tasks.has(task)) return task;
  }
  // No agent tab has focus (the Project view has it): the one used last wins.
  for (const tab of editorService().openTabs?.() ?? []) {
    if (tab.input.kind === HOME_KIND) return HOME;
    if (tab.input.kind === SESSION_KIND) {
      const task = (tab.input.data as { task?: unknown } | undefined)?.task;
      if (typeof task === "string" && s.tasks.has(task)) return task;
    }
  }
  return s.lastComposer !== HOME && s.tasks.has(s.lastComposer) ? s.lastComposer : HOME;
}

/**
 * Adds `@file` references (with an optional line range) to the composer on show (else the one
 * typed in last) and shows it: IDEA-style "send this to the chat".
 */
export function addReferences(refs: Array<{ path: string; rel: string; mention: string }>) {
  const s = useAgents.getState();
  const key = activeComposerKey();
  const task = key === HOME ? null : s.tasks.get(key)!;
  const current = composerDraft(key);
  // A worktree task sees the same files under its own directory.
  const root = task?.isolation === "worktree" ? task.cwd : null;
  const files: FileRef[] = refs.map((r) => ({ path: root ? `${root}/${r.rel}` : r.path, rel: r.rel }));
  const mentions = refs.map((r) => r.mention).join(" ");
  const text =
    current.text && !/\s$/.test(current.text) ? `${current.text} ${mentions} ` : `${current.text}${mentions} `;
  updateComposer(key, { text, files: [...current.files, ...files] });
  if (task) openTask(task.id);
  else openHome();
}

/** Stops the task's turn, or with `subagent` only that subagent's work. */
export const cancelTask = (task: string, subagent: string | null = null) => call(commands.agentCancel(task, subagent));
export const stopBackgroundTask = (task: string, background: string) =>
  call(commands.agentStopBackground(task, background));
export const respond = (task: string, permission: number, option: string | null) =>
  call(commands.agentRespond(task, permission, option));
export const unarchiveTask = (task: string) => call(commands.agentUnarchive(task));
export const renameTask = (task: string, title: string) => call(commands.agentRename(task, title));
export const archiveTask = (task: string) => call(commands.agentArchive(task));
export const deleteTask = (task: string, removeWorktree: boolean) => call(commands.agentDelete(task, removeWorktree));