The Open Framework for Building Agents
feat(tui): add /cancel command (#1512)
Casey Gowrieac7d3c66f8c4
diff --git a/.changeset/quiet-taxis-cancel.md b/.changeset/quiet-taxis-cancel.mdnew file mode 100644index 000000000..d029af1eb--- /dev/null+++ b/.changeset/quiet-taxis-cancel.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add `/cancel` to the eve dev TUI. The command cooperatively cancels a running turn from either the live streaming input or the idle prompt while preserving the session and settled context.diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex 74227f528..c81263d1e 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -42,6 +42,7 @@ Each command echoes as an invocation line, asks through a bordered panel that ta| `/loglevel` | Switches which logs the transcript shows. See [Control what logs show](#control-what-logs-show). || `/traces` | Opens the full-screen local trace viewer. See [Inspect traces](#inspect-traces). || `/new` | Starts a fresh session. |+| `/cancel` | Cooperatively cancels the running turn while preserving the session and settled context. || `/clear` | Clears model-message history while preserving the current session and its durable resources. || `/compact` | Queues context compaction for the current session without sending a message. || `/exit` | Quits the TUI. |@@ -83,7 +84,7 @@ In terminals that support bracketed paste, pasting multi-line text into chat or### Queue and steer while the agent works-Sending a message while a turn is still running does not interrupt it — the message joins a queue of up to five, pinned in a panel directly above the input with one line per message. When the turn ends, the queued messages coalesce into the next turn's message.+Sending a message while a turn is still running does not interrupt it — the message joins a queue of up to five, pinned in a panel directly above the input with one line per message. When the turn ends, the queued messages coalesce into the next turn's message. Submit `/cancel` during a turn to cancel it immediately without queueing the command as model input; `/cancel` also works from the idle prompt when a prior stream disconnected while its server turn may still be running.`Esc` steers instead of waiting: it pops the oldest queued message, cancels the running turn cooperatively, and submits the popped message as the replacement turn. In the transcript, a steered message carries an accent `↑` on its own line above its gutter bar; a queued message that waited for the boundary carries it below. Any remaining messages stay queued behind it. With nothing queued, the first `Esc` arms cancellation and a second `Esc` cancels the turn. Unlike `Ctrl+C` — which drops the stream client-side — a cancelled turn ends cleanly on the server and the session keeps its context; the conversation picks up at the next prompt.diff --git a/packages/eve/src/cli/dev/tui/message-queue.test.ts b/packages/eve/src/cli/dev/tui/message-queue.test.tsindex 58bfd3650..87e352093 100644--- a/packages/eve/src/cli/dev/tui/message-queue.test.ts+++ b/packages/eve/src/cli/dev/tui/message-queue.test.ts@@ -63,6 +63,16 @@ describe("MessageQueue", () => {expect(queue.handleEscape()).toBe("armed");});+ it("requests direct cancellation without consuming queued messages", () => {+ const queue = new MessageQueue();+ queue.enqueue("follow-up");++ queue.requestCancellation();++ expect(queue.view()).toMatchObject({ armed: false, cancelling: true });+ expect(queue.takePrompt()).toBe("follow-up");+ });+it("drains the whole queue as one coalesced prompt at a turn boundary", () => {const queue = new MessageQueue();queue.enqueue("first");diff --git a/packages/eve/src/cli/dev/tui/message-queue.ts b/packages/eve/src/cli/dev/tui/message-queue.tsindex ad35afa00..18b1f2085 100644--- a/packages/eve/src/cli/dev/tui/message-queue.ts+++ b/packages/eve/src/cli/dev/tui/message-queue.ts@@ -7,8 +7,8 @@* the next turn's message. Esc pops the oldest message to steer the* conversation instead of waiting: the renderer requests cooperative turn* cancellation and the runner submits the popped message as the next turn.- * Esc on an empty queue arms cancellation; a second Esc cancels the turn- * without a replacement message.+ * `/cancel` requests cancellation directly. Esc on an empty queue arms+ * cancellation; a second Esc cancels the turn without a replacement message.** The renderer owns lifecycle (keys, cancel requests, when the runner drains* the queue); this module only holds the queue state machine and paints rows.@@ -101,6 +101,12 @@ export class MessageQueue {return "cancel";}+ /** Marks a direct cancellation request without consuming queued messages. */+ requestCancellation(): void {+ this.#escArmed = false;+ this.#cancelRequested = true;+ }+/** Any non-Esc activity backs out of the armed press-again state. */disarm(): void {this.#escArmed = false;diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.test.ts b/packages/eve/src/cli/dev/tui/prompt-commands.test.tsindex a551d0c1c..ff11b9eb9 100644--- a/packages/eve/src/cli/dev/tui/prompt-commands.test.ts+++ b/packages/eve/src/cli/dev/tui/prompt-commands.test.ts@@ -13,6 +13,10 @@ describe("parsePromptCommand", () => {expect(parsePromptCommand("/new")).toEqual({ type: "new" });});+ it("parses /cancel", () => {+ expect(parsePromptCommand("/cancel")).toEqual({ type: "cancel" });+ });+it("parses /exit and its /quit alias", () => {expect(parsePromptCommand("/exit")).toEqual({ type: "exit" });expect(parsePromptCommand("/quit")).toEqual({ type: "exit" });diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.ts b/packages/eve/src/cli/dev/tui/prompt-commands.tsindex ce5b91d10..9422cf079 100644--- a/packages/eve/src/cli/dev/tui/prompt-commands.ts+++ b/packages/eve/src/cli/dev/tui/prompt-commands.ts@@ -5,6 +5,7 @@ type PromptCommandTarget = "local" | "remote";/** The slash commands the prompt accepts. */export type PromptCommand =| { type: "new" }+ | { type: "cancel" }| { type: "clear" }| { type: "compact" }| { type: "exit" }@@ -60,6 +61,14 @@ const PROMPT_COMMAND_DEFINITIONS = [build: () => ({ type: "new" }),targets: ["local", "remote"],},+ {+ name: "cancel",+ aliases: [],+ description: "Cancel the running turn",+ takesArgument: false,+ build: () => ({ type: "cancel" }),+ targets: ["local", "remote"],+ },{name: "clear",aliases: [],@@ -165,9 +174,11 @@ export function isPromptCommandAvailableFor(/*** Recognizes the slash commands the prompt accepts. `/new` clears the- * session and transcript; `/clear` clears context; `/compact` queues context compaction; `/exit` (and `/quit`) terminate the TUI like- * Ctrl+C; extension commands are dispatched outside the runner. Anything- * else — including unknown `/text` — is a normal message.+ * session and transcript; `/cancel` stops the running turn; `/clear` clears+ * context; `/compact` queues context compaction; `/exit` (and `/quit`)+ * terminate the TUI like Ctrl+C; extension commands are dispatched outside+ * the runner. Anything else — including unknown `/text` — is a normal+ * message.*/export function parsePromptCommand(prompt: string): PromptCommand | null {const trimmed = prompt.trim();diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 0040d0748..1a8518019 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -197,8 +197,9 @@ describe("parsePromptCommand", () => {});});- it("recognizes /new, /clear, /compact, /exit, and /quit", () => {+ it("recognizes /new, /cancel, /clear, /compact, /exit, and /quit", () => {expect(parsePromptCommand("/new")).toEqual({ type: "new" });+ expect(parsePromptCommand("/cancel")).toEqual({ type: "cancel" });expect(parsePromptCommand("/clear")).toEqual({ type: "clear" });expect(parsePromptCommand("/compact")).toEqual({ type: "compact" });expect(parsePromptCommand("/exit")).toEqual({ type: "exit" });@@ -737,6 +738,71 @@ describe("EveTUIRunner development session continuity", () => {expect(results).toEqual(["Context clear requested."]);});+ it("cancels an active turn without sending a prompt", async () => {+ const session = stubClient().session({+ continuationToken: "eve:test",+ sessionId: "session_1",+ streamIndex: 0,+ });+ const cancel = vi+ .spyOn(session, "cancel")+ .mockResolvedValue({ sessionId: "session_1", status: "accepted" });+ const send = vi.spyOn(session, "send");+ const stream = vi.spyOn(session, "stream").mockReturnValue(+ (async function* () {+ yield stampTestEvent(+ {+ data: { continuationToken: "eve:test", wait: "next-user-message" },+ type: "session.waiting",+ },+ 0,+ );+ })(),+ );+ const results: string[] = [];+ const prompts: Array<string | undefined> = ["/cancel", undefined];+ const runner = new EveTUIRunner({+ name: "Weather Agent",+ renderer: fakeRenderer({+ readPrompt: vi.fn(async () => prompts.shift()),+ renderCommandResult: (message) => results.push(message),+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events) {+ void event;+ }+ }),+ }),+ session,+ });++ await runner.run();++ expect(cancel).toHaveBeenCalledOnce();+ expect(stream).toHaveBeenCalledOnce();+ expect(send).not.toHaveBeenCalled();+ expect(results).toEqual(["Turn cancellation requested."]);+ });++ it("does not call the cancel API before a session has started", async () => {+ const session = stubSession();+ const cancel = vi.spyOn(session, "cancel");+ const results: string[] = [];+ const prompts: Array<string | undefined> = ["/cancel", undefined];+ const runner = new EveTUIRunner({+ name: "Weather Agent",+ renderer: fakeRenderer({+ readPrompt: vi.fn(async () => prompts.shift()),+ renderCommandResult: (message) => results.push(message),+ }),+ session,+ });++ await runner.run();++ expect(cancel).not.toHaveBeenCalled();+ expect(results).toEqual(["No active turn to cancel."]);+ });+it("keeps the current transcript and session when /new cannot reset the owner", async () => {const session = sessionYielding([]);const reset = vi.spyOn(session, "reset").mockRejectedValue(new Error("World unavailable"));diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 4b2a3c202..f1712e87d 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -126,10 +126,10 @@ export type AgentTUIStreamResult = {abort?: () => void;/*** Requests cooperative server-side cancellation of the streaming turn- * (Esc Esc, or an Esc steer pop). Unlike {@link abort} — which drops the- * client stream and forces a fresh session — the server settles the turn- * as `turn.cancelled` → `session.waiting`, so the stream reaches its- * boundary normally and the session keeps its context. Best-effort and+ * (`/cancel`, Esc Esc, or an Esc steer pop). Unlike {@link abort} — which+ * drops the client stream and forces a fresh session — the server settles+ * the turn as `turn.cancelled` → `session.waiting`, so the stream reaches+ * its boundary normally and the session keeps its context. Best-effort and* idempotent; scoped to the turn the user observed when its id is known.*/cancel?: () => void;@@ -789,6 +789,43 @@ export class EveTUIRunner {return;}+ if (command?.type === "cancel") {+ if (this.#session.state.sessionId === undefined) {+ this.#renderCommandOutcome("No active turn to cancel.");+ pendingInputResponses = undefined;+ followCurrentSession = false;+ streamWithoutPrompt = false;+ prompt = undefined;+ continue;+ }+ try {+ const result = await this.#session.cancel();+ this.#renderCommandOutcome(+ result.status === "accepted"+ ? "Turn cancellation requested."+ : "No active turn to cancel.",+ );+ if (result.status === "no_active_turn") {+ pendingInputResponses = undefined;+ followCurrentSession = false;+ streamWithoutPrompt = false;+ prompt = undefined;+ continue;+ }+ } catch (error) {+ this.#renderCommandOutcome(`Couldn't cancel the turn: ${toErrorMessage(error)}`);+ pendingInputResponses = undefined;+ followCurrentSession = false;+ streamWithoutPrompt = false;+ prompt = undefined;+ continue;+ }+ pendingInputResponses = undefined;+ followCurrentSession = true;+ streamWithoutPrompt = false;+ prompt = undefined;+ }+if (command?.type === "new") {if (!(await this.#resetCurrentSession())) {pendingInputResponses = undefined;diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex 60b217217..bcec80987 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -1757,6 +1757,44 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});+ it("runs a mid-turn /cancel as a control instead of queueing it", async () => {+ const { screen, input, renderer } = makeRenderer();+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;+ const cancel = vi.fn();+ const rendering = renderer.renderStream(+ {+ cancel,+ events: new ReadableStream<AgentTUIStreamEvent>({+ start(controller) {+ streamController = controller;+ },+ }),+ },+ { submittedPrompt: "long task", continueSession: true },+ );++ await vi.waitFor(() => {+ expect(screen.snapshot()).toContain("›");+ });+ input.type("/cancel");+ input.enter();++ await vi.waitFor(() => {+ expect(cancel).toHaveBeenCalledOnce();+ expect(screen.snapshot()).toContain("/cancel");+ expect(screen.snapshot()).toContain("Turn cancellation requested.");+ expect(screen.snapshot()).toContain("Cancelling turn…");+ });++ streamController?.enqueue({ type: "turn-cancelled" });+ streamController?.close();+ await rendering;++ expect(renderer.takeQueuedPrompt()).toBeUndefined();+ expect(screen.snapshot()).toContain("Cancelled");+ renderer.shutdown();+ });+it("pops the oldest queued message on Esc, cancels the turn, and stages the steer prompt", async () => {const { screen, input, renderer } = makeRenderer();const escape = async () => {diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex 907415037..7d06f658c 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -533,9 +533,10 @@ export class TerminalRenderer implements AgentTUIRenderer {#todoCommittedSignature?: string;/*** Messages submitted while a turn streams, pinned in a panel directly- * above the input. Enter queues, Esc pops-to-steer or (empty) arms and- * then cancels; the runner drains via {@link takeQueuedPrompt} at a clean- * turn boundary and {@link readPrompt} restores any leftovers as a draft.+ * above the input. Enter queues, `/cancel` cancels directly, and Esc+ * pops-to-steer or (empty) arms and then cancels; the runner drains via+ * {@link takeQueuedPrompt} at a clean turn boundary and {@link readPrompt}+ * restores any leftovers as a draft.*/readonly #messageQueue = new MessageQueue();/** The streaming result's cooperative cancel, armed for Esc while it renders. */@@ -2962,11 +2963,24 @@ export class TerminalRenderer implements AgentTUIRenderer {}break;case "enter": {+ const message = this.#streamDraft.text;+ if (message.trim().length === 0) break;+ if (+ parsePromptCommand(message)?.type === "cancel" &&+ this.#requestTurnCancel !== undefined+ ) {+ this.#streamDraft = EMPTY_LINE;+ this.#messageQueue.requestCancellation();+ this.#cancelRequestedByUser = true;+ this.renderCommandInvocation(message.trim());+ this.renderCommandResult("Turn cancellation requested.");+ this.#requestTurnCancel();+ this.#paint();+ break;+ }// Mid-turn Enter queues the draft as a message for the next turn// (or for an Esc steer pop). A full queue keeps the draft in place —// the panel header says why — rather than silently dropping input.- const message = this.#streamDraft.text;- if (message.trim().length === 0) break;if (this.#messageQueue.enqueue(message)) {this.#streamDraft = EMPTY_LINE;}