diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 408e46c2a..0e401130a 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -811,7 +811,8 @@ impl AgentManager { Ok(task) } - /// Creates the task (and its worktree) and sends `req.prompt` as its first message. + /// Creates the task (and its worktree) and sends `req.prompt` as its first message, unless + /// `req.idle`. pub async fn create(&self, req: NewAgentTask) -> IdeResult { let spec = self .shared @@ -886,7 +887,7 @@ impl AgentManager { title, provider: spec.id.clone(), model: model_of(&config), - status: AgentStatus::Starting, + status: if req.idle { AgentStatus::Ready } else { AgentStatus::Starting }, isolation: req.isolation, cwd: IpcPath(cwd), branch, @@ -920,11 +921,13 @@ impl AgentManager { title_renamed: false, }; let handle = Task::restore(file, self.shared.clone()); - handle.state.lock().busy = true; + handle.state.lock().busy = !req.idle; self.tasks.write().insert(task.id.clone(), handle.clone()); handle.emit_task(); handle.persist(); - self.shared.runtime.spawn(async move { handle.run(prompt).await }); + if !req.idle { + self.shared.runtime.spawn(async move { handle.run(prompt).await }); + } Ok(task) } diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index b407bc1bd..e08be1378 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -633,6 +633,10 @@ pub struct NewAgentTask { /// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). #[serde(default)] pub mcp_overrides: BTreeMap, + /// Creates the task without sending `prompt` (it only names the task): the composer's + /// `!` command runs in it first. + #[serde(default)] + pub idle: bool, } /// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 393c94930..c644cf44f 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -1420,6 +1420,32 @@ async fn shell_commands_show_in_the_conversation_and_go_with_the_next_message() assert_eq!(sent.pointer("/0/text").and_then(Value::as_str), Some("again")); } +#[tokio::test(flavor = "multi_thread")] +async fn an_idle_task_starts_no_turn_until_its_first_message() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + let mgr = manager(tmp.path(), agent.clone()); + let task = mgr + .create(NewAgentTask { + prompt: text("! echo first"), + provider: "claude".into(), + isolation: Isolation::Local, + idle: true, + ..Default::default() + }) + .await + .unwrap(); + assert_eq!((task.status, task.title.as_str()), (AgentStatus::Ready, "! echo first")); + + mgr.run_shell(&task.id, "echo first", ide_core::CancellationToken::new()).await.unwrap(); + assert!(agent.prompts.lock().is_empty(), "an idle task starts no turn"); + mgr.prompt(&task.id, text("again"), false).await.unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + let sent = agent.prompts.lock().last().cloned().unwrap(); + assert!(sent.pointer("/0/text").and_then(Value::as_str).is_some_and(|t| t.contains("echo first"))); + assert_eq!(sent.pointer("/1/text").and_then(Value::as_str), Some("again")); +} + #[tokio::test(flavor = "multi_thread")] async fn send_now_interrupts_the_turn_when_steering_is_refused() { let tmp = tempfile::tempdir().unwrap(); @@ -4377,6 +4403,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() { isolation: Isolation::Local, base: None, mcp_overrides: BTreeMap::from([("slack".into(), false)]), + idle: false, }) .await .unwrap(); @@ -4504,6 +4531,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() isolation: Isolation::Local, base: None, mcp_overrides: BTreeMap::new(), + idle: false, }) .await .unwrap(); @@ -4528,6 +4556,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() isolation: Isolation::Local, base: None, mcp_overrides: BTreeMap::new(), + idle: false, }) .await .unwrap(); diff --git a/src/bindings.ts b/src/bindings.ts index fd0192e92..24b844d93 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -8685,6 +8685,11 @@ export type NewAgentTask = { base: string | null, /** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). */ mcpOverrides?: { [key in string]: boolean }, + /** + * Creates the task without sending `prompt` (it only names the task): the composer's + * `!` command runs in it first. + */ + idle?: boolean, }; /** The approvals new agent tasks start with. */ diff --git a/src/features/agents/Composer.tsx b/src/features/agents/Composer.tsx index 8128be63c..cdd5a7b03 100644 --- a/src/features/agents/Composer.tsx +++ b/src/features/agents/Composer.tsx @@ -48,6 +48,7 @@ import { atEdgeLine, isMentioned, isPathQuery, + shellHistoryMatches, mergeMatches, referenceOf, resolveTyped, @@ -91,6 +92,8 @@ type Item = | { kind: "command"; command: AgentCommand } | { kind: "context"; source: AgentContextSource } | { kind: "symbol"; symbol: SymbolMatch; path: string; rel: string } + /** A `!` command line's completion: an earlier command, or a path for the word at the caret. */ + | { kind: "shell"; text: string; dir?: boolean; history?: boolean } | { kind: "section"; source: Section }; const isSection = (item: Item) => item.kind === "section"; @@ -453,8 +456,49 @@ export function Composer(props: ComposerProps) { }; }, [completion?.kind, completion?.query, root, refOf]); + // `!` completion: paths under the task's folder for the word being typed. + // Every task's `!` commands, for a conversation that hasn't run one yet. + const recentCommands = useAgents((s) => s.history); + const [shellFound, setShellFound] = useState<{ query: string; items: Item[] } | null>(null); + const shellQuery = completion?.kind === "shell" && completion.query ? completion.query : null; + useEffect(() => { + if (shellQuery === null) return; + let alive = true; + const typed = /(^|\/)\.\.?$/.test(shellQuery) ? `${shellQuery}/` : shellQuery; + const dirPart = typed.slice(0, typed.lastIndexOf("/") + 1); + const last = typed.slice(dirPart.length); + const timer = setTimeout(() => { + call(commands.pathCompletions(`${typed.startsWith("/") ? "" : root}/_`, typed)) + .then((found) => { + if (!alive) return; + setShellFound({ + query: shellQuery, + items: found + .filter((f) => f.name.startsWith(last) && `${dirPart}${f.name}` !== shellQuery) + .slice(0, MAX_ITEMS) + .map((f) => ({ kind: "shell", text: `${dirPart}${f.name}`, dir: f.dir })), + }); + }) + .catch(() => alive && setShellFound({ query: shellQuery, items: [] })); + }, 60); + return () => { + alive = false; + clearTimeout(timer); + }; + }, [shellQuery, root]); + const items: Item[] = useMemo(() => { if (!completion) return []; + if (completion.kind === "shell") { + const earlier: Item[] = completion.command + ? shellHistoryMatches([...props.history, ...recentCommands], completion.query, MAX_ITEMS).map((text) => ({ + kind: "shell", + text, + history: true, + })) + : []; + return shellFound?.query === shellQuery ? [...earlier, ...shellFound.items] : earlier; + } if (completion.kind === "file") { const q = completion.query.toLowerCase(); if (q.startsWith("#") || isPathQuery(q)) return files; @@ -492,7 +536,7 @@ export function Composer(props: ComposerProps) { out.push({ kind: "command", command }); } return out; - }, [completion, files, props.commands, props.onOpenMcp, tx]); + }, [completion, files, shellFound, shellQuery, recentCommands, props.history, props.commands, props.onOpenMcp, tx]); const activeIndex = items[active] && !isSection(items[active]!) ? active : firstSelectable(items, isSection); const open = !!completion && items.some((item) => !isSection(item)); const anchorAt = open ? completion.to : null; @@ -544,6 +588,20 @@ export function Composer(props: ComposerProps) { ); return; } + if (item.kind === "shell") { + if (item.history) { + setText(`!${item.text}`, item.text.length + 1); + } else if (item.dir) { + // A folder keeps completing inside it, as a shell's Tab does. + replace(completion.from, completion.to, `${item.text}/`); + return; + } else { + const next = applyCompletion(current, completion, item.text); + setText(next.text, next.caret); + } + setCompletion(null); + return; + } if (item.kind === "symbol") { const rel = item.rel; const line = item.symbol.range.start.line + 1; @@ -900,7 +958,8 @@ export function Composer(props: ComposerProps) { if (next !== null) setActive(next); return handled(); } - if (e.key === "Enter" || e.key === "Tab") { + // In a `!` command line Enter runs the command; Tab completes, as in a shell. + if (e.key === "Tab" || (e.key === "Enter" && completion?.kind !== "shell")) { accept(items[activeIndex], e.key === "Tab"); return handled(); } @@ -1034,11 +1093,13 @@ export function Composer(props: ComposerProps) { ? `section:${item.source}` : item.kind === "file" ? item.path - : item.kind === "context" - ? `context:${item.source.id}` - : item.kind === "symbol" - ? `symbol:${item.path}:${item.symbol.range.start.line}:${item.symbol.name}` - : `${item.command.source ?? "command"}:${item.command.name}` + : item.kind === "shell" + ? `shell:${item.history ? "history" : "path"}:${item.text}` + : item.kind === "context" + ? `context:${item.source.id}` + : item.kind === "symbol" + ? `symbol:${item.path}:${item.symbol.range.start.line}:${item.symbol.name}` + : `${item.command.source ?? "command"}:${item.command.name}` } isSection={isSection} renderSection={(item) => item.kind === "section" && tx(SECTION_TITLES[item.source])} @@ -1072,6 +1133,28 @@ export function Composer(props: ComposerProps) { ); + if (item.kind === "shell") { + if (item.history) + return ( + <> + + {item.text} + + ); + const name = basename(item.text); + return ( + <> + + + {name} + {item.dir && "/"} + + + {item.text.slice(0, item.text.length - name.length).replace(/\/$/, "")} + + + ); + } if (item.kind === "command") return ( <> @@ -1099,9 +1182,15 @@ export function Composer(props: ComposerProps) { ↑ ↓ {tx("Navigate")} - - ↵ {tx(completion.kind === "file" ? "Reference" : "Insert")} - + {completion.kind === "shell" ? ( + + ⇥ {tx("Insert")} + + ) : ( + + ↵ {tx(completion.kind === "file" ? "Reference" : "Insert")} + + )} {completion.kind === "file" && items.some((i) => i.kind === "file" && i.dir) && ( ⇥ {tx("Enter Folder")} diff --git a/src/features/agents/composerCommands.test.tsx b/src/features/agents/composerCommands.test.tsx index 1e781fb7f..bf1b3066f 100644 --- a/src/features/agents/composerCommands.test.tsx +++ b/src/features/agents/composerCommands.test.tsx @@ -299,6 +299,24 @@ describe("New Task composer commands", () => { fireEvent.keyDown(box, { key: "Enter" }); expect(useAgents.getState().composers.get(HOME)?.text).toBe("fix the failing build /triage "); }); + + it("completes a `!` command from earlier ones with Tab and runs it with Enter", async () => { + agentCommands.mockResolvedValue({ status: "ok", data: [] }); + useAgents.setState({ history: ["!git status", "fix it"] }); + render(); + await waitFor(() => expect(agentCommands).toHaveBeenCalled()); + const box = screen.getByRole("textbox"); + typeIn(box, "!gi"); + expect(await screen.findByRole("option")).toHaveTextContent("git status"); + fireEvent.keyDown(box, { key: "Tab" }); + expect(textOf(box)).toBe("!git status"); + + typeIn(box, "!gi"); + await screen.findByRole("option"); + fireEvent.keyDown(box, { key: "Enter" }); + await waitFor(() => expect(agentCreate).toHaveBeenCalled()); + expect(agentCreate.mock.calls[0]![0]).toMatchObject({ idle: true, prompt: { text: "!gi" } }); + }); }); describe("New Task composer paste", () => { diff --git a/src/features/agents/composerModel.ts b/src/features/agents/composerModel.ts index 964568a8a..6f6543bcb 100644 --- a/src/features/agents/composerModel.ts +++ b/src/features/agents/composerModel.ts @@ -60,11 +60,22 @@ export function messageTokens(text: string): MessageToken[] { export type Completion = | { kind: "file"; query: string; from: number; to: number } - | { kind: "command"; query: string; from: number; to: number }; + | { kind: "command"; query: string; from: number; to: number } + /** A word of a `!` command line: its first word (`command`) or an argument. */ + | { kind: "shell"; query: string; from: number; to: number; command: boolean }; -/** The `@file` or `/command` being typed at `caret`, if any; both may follow other text. */ +/** + * The `@file` or `/command` being typed at `caret`, if any; both may follow other text. In a + * `!` command line, the word at `caret` instead. + */ export function completionAt(text: string, caret: number): Completion | null { const before = text.slice(0, caret); + if (text.startsWith("!") && caret > 0) { + if (before.includes("\n")) return null; + const query = /\S*$/.exec(before.slice(1))![0]; + const from = caret - query.length; + return { kind: "shell", query, from, to: caret, command: !before.slice(1, from).trim() }; + } const word = /(^|\s)([@/])([^\s@]*)$/.exec(before); if (!word) return null; const from = caret - word[3]!.length - 1; @@ -76,6 +87,20 @@ export function completionAt(text: string, caret: number): Completion | null { }; } +/** + * The earlier `!` commands (newest first, without the `!`) that extend `query`, each once. + */ +export function shellHistoryMatches(history: readonly string[], query: string, max: number): string[] { + const out: string[] = []; + for (const line of history) { + if (!line.startsWith("!") || line.includes("\n")) continue; + const command = line.slice(1).trim(); + if (command && command !== query.trim() && command.startsWith(query) && !out.includes(command)) out.push(command); + if (out.length >= max) break; + } + return out; +} + /** Replaces the completion with `insert` plus a space; returns the text and the caret after it. */ export function applyCompletion(text: string, c: Completion, insert: string): { text: string; caret: number } { const after = text.slice(c.to); diff --git a/src/features/agents/composerShell.test.ts b/src/features/agents/composerShell.test.ts index 8c07101ad..a2022e838 100644 --- a/src/features/agents/composerShell.test.ts +++ b/src/features/agents/composerShell.test.ts @@ -1,24 +1,31 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { AgentTask } from "@/bindings"; -import { emptyDraft, shellCommand } from "./composerModel"; -import { composerDraft, sendMessage, stopTask, updateComposer, useAgents } from "./store"; +import { completionAt, emptyDraft, shellCommand, shellHistoryMatches } from "./composerModel"; +import { HOME, composerDraft, sendMessage, startTask, stopTask, updateComposer, useAgents } from "./store"; const backend = vi.hoisted(() => ({ shell: vi.fn(), prompt: vi.fn(), cancelRequest: vi.fn(), cancel: vi.fn(), + create: vi.fn(), })); vi.mock("@/platform/ipc", async (original) => ({ ...(await original()), commands: { agentShell: backend.shell, agentPrompt: backend.prompt, + agentCreate: backend.create, agentCancel: backend.cancel, cancelRequest: backend.cancelRequest, }, })); +vi.mock("@/workbench/contributions", async (original) => ({ + ...(await original()), + editorService: () => ({ openInput: vi.fn(), closeInput: async () => true, openTabs: () => [] }), +})); + const ok = { status: "ok" as const, data: null }; beforeEach(() => { @@ -53,6 +60,8 @@ describe("`!` commands in the composer", () => { const [task, command, request] = backend.shell.mock.calls[0]!; expect([task, command]).toEqual(["t", "git status"]); expect(composerDraft("t").text).toBe(""); + // Offered again in every composer's `!` completion. + expect(useAgents.getState().history[0]).toBe("!git status"); expect(useAgents.getState().shellRunning.has("t")).toBe(true); await stopTask("t"); @@ -72,3 +81,52 @@ describe("`!` commands in the composer", () => { expect(backend.shell).not.toHaveBeenCalled(); }); }); + +describe("a `!` command from the new task composer", () => { + it("creates the task without a turn and runs the command in it", async () => { + backend.create.mockResolvedValue({ status: "ok", data: { id: "n", status: "ready" } as AgentTask }); + backend.shell.mockResolvedValue(ok); + useAgents.setState({ providers: [], draft: { provider: "codex", config: {}, isolation: "local", base: null } }); + updateComposer(HOME, { text: "!ls -la" }); + await startTask("local"); + expect(backend.create.mock.calls[0]![0]).toMatchObject({ idle: true, prompt: { text: "!ls -la" } }); + await vi.waitFor(() => expect(backend.shell).toHaveBeenCalled()); + expect(backend.shell.mock.calls[0]!.slice(0, 2)).toEqual(["n", "ls -la"]); + expect(composerDraft(HOME).text).toBe(""); + }); + + it("leaves a message to start a turn", async () => { + backend.create.mockResolvedValue({ status: "ok", data: { id: "m", status: "starting" } as AgentTask }); + useAgents.setState({ providers: [], draft: { provider: "codex", config: {}, isolation: "local", base: null } }); + updateComposer(HOME, { text: "list the files" }); + await startTask("local"); + expect(backend.create.mock.calls[0]![0]).toMatchObject({ idle: false }); + expect(backend.shell).not.toHaveBeenCalled(); + }); +}); + +describe("`!` completion", () => { + it("completes the word at the caret, the first one as a command", () => { + expect(completionAt("!", 1)).toEqual({ kind: "shell", query: "", from: 1, to: 1, command: true }); + expect(completionAt("!gi", 3)).toEqual({ kind: "shell", query: "gi", from: 1, to: 3, command: true }); + expect(completionAt("!cat src/ma", 11)).toEqual({ + kind: "shell", + query: "src/ma", + from: 5, + to: 11, + command: false, + }); + // `/` and `@` are path characters here, not commands or references. + expect(completionAt("!ls /us", 7)).toMatchObject({ kind: "shell", query: "/us" }); + expect(completionAt("!echo @a", 8)).toMatchObject({ kind: "shell", query: "@a" }); + expect(completionAt("/re", 3)).toMatchObject({ kind: "command" }); + }); + + it("offers earlier commands, newest first and each once", () => { + const history = ["!git status", "fix it", "!git log -3", "!git status", "!ls"]; + expect(shellHistoryMatches(history, "git", 10)).toEqual(["git status", "git log -3"]); + expect(shellHistoryMatches(history, "", 2)).toEqual(["git status", "git log -3"]); + // The command typed out in full has nothing to add. + expect(shellHistoryMatches(history, "ls", 10)).toEqual([]); + }); +}); diff --git a/src/features/agents/session/Folds.tsx b/src/features/agents/session/Folds.tsx index 4c2054e9b..43c904f0e 100644 --- a/src/features/agents/session/Folds.tsx +++ b/src/features/agents/session/Folds.tsx @@ -20,6 +20,7 @@ export function Fold({ id, className, open, + defaultOpen, summary, children, }: { @@ -27,13 +28,15 @@ export function Fold({ id?: string; className?: string; open?: boolean; + /** Starts open; the reader can still fold it. */ + defaultOpen?: boolean; summary: ReactElement; children: ReactNode; }) { const always = useContext(FoldedContent); const remembered = useContext(OpenFolds); const reveal = useContext(RevealFold); - const [expanded, setExpanded] = useState(() => !!open || (!!id && !!remembered?.get(id))); + const [expanded, setExpanded] = useState(() => !!open || !!defaultOpen || (!!id && !!remembered?.get(id))); const ref = useRef(null); const opened = useRef(false); // Once its content is laid out, so its height is known. @@ -46,7 +49,7 @@ export function Fold({
{ const now = e.currentTarget.open; opened.current = now; diff --git a/src/features/agents/session/toolEntries.tsx b/src/features/agents/session/toolEntries.tsx index 1fd7d3ab4..910f105ee 100644 --- a/src/features/agents/session/toolEntries.tsx +++ b/src/features/agents/session/toolEntries.tsx @@ -126,6 +126,8 @@ export const ToolEntry = memo(function ToolEntry({ diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index 95013c00b..457a11d98 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -1172,6 +1172,7 @@ export async function startTask( const composer = composerDraft(HOME); if (!canSend(composer)) return; const started = generation; + const command = shellCommand(composer); const options = draftConfig( providers.find((p) => p.id === draft.provider), draft, @@ -1206,6 +1207,8 @@ export async function startTask( isolation, base: isolation === "worktree" ? draft.base : null, mcpOverrides: draft.mcpOverrides ?? {}, + // A `!` command runs in the new task before the agent hears anything. + idle: command !== null, }), ); if (generation !== started) return; @@ -1219,6 +1222,10 @@ export async function startTask( clearSubmittedComposer(HOME, composer, started); const closed = await editorService().closeInput?.(HOME_KEY); if (generation === started && closed !== false) openTask(task.id); + if (command !== null && generation === started) + void execShell(task.id, command).catch((e: unknown) => + notifications().notify({ level: "error", title: "Couldn't send the message", body: String(e) }), + ); } catch (e) { if (generation === started) throw e; } @@ -1363,9 +1370,14 @@ function trackShell(task: string, request: RequestId, running: boolean) { /** Runs a `!` line in the task's folder; its output reaches the agent with the next message. */ async function runShell(task: string, composer: ComposerDraft, command: string) { + clearSubmittedComposer(task, composer, generation); + remember(`!${command}`); + await execShell(task, command); +} + +async function execShell(task: string, command: string) { const request = nextRequestId(); trackShell(task, request, true); - clearSubmittedComposer(task, composer, generation); try { await call(commands.agentShell(task, command, request)); } finally {