The Open Framework for Building Agents
feat(tui): cancel with one Esc press (#1514)
Casey Gowrie910805e8a825
diff --git a/.changeset/calm-ravens-escape.md b/.changeset/calm-ravens-escape.mdnew file mode 100644index 000000000..2b47ec416--- /dev/null+++ b/.changeset/calm-ravens-escape.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Make a single `Esc` cancel the running turn in the eve dev TUI when no message is queued. Queued messages still use `Esc` to steer the oldest message into the next turn.diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex c81263d1e..8362fb93a 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -86,7 +86,7 @@ In terminals that support bracketed paste, pasting multi-line text into chat orSending 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.+`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, one `Esc` cancels the turn immediately. 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.If a turn fails terminally (the server session dies or the connection drops), the TUI starts a fresh session and notes it inline so you can keep going. Server-side context resets with the old session. Messages still queued when a turn is interrupted or fails are restored into the next prompt's input instead of being sent blind.diff --git a/packages/eve/src/cli/dev/tui/message-queue.test.ts b/packages/eve/src/cli/dev/tui/message-queue.test.tsindex 87e352093..291cbc3cb 100644--- a/packages/eve/src/cli/dev/tui/message-queue.test.ts+++ b/packages/eve/src/cli/dev/tui/message-queue.test.ts@@ -39,28 +39,26 @@ describe("MessageQueue", () => {expect(queue.idle).toBe(true);});- it("re-reports steer (not armed) while a steer payload is staged", () => {+ it("re-reports steer while a steer payload is staged", () => {const queue = new MessageQueue();queue.enqueue("only");queue.handleEscape();expect(queue.handleEscape()).toBe("steer");- expect(queue.view().armed).toBe(false);+ expect(queue.view().cancelling).toBe(false);});- it("arms on the first empty-queue Esc and cancels on the second", () => {+ it("cancels on the first empty-queue Esc", () => {const queue = new MessageQueue();- expect(queue.handleEscape()).toBe("armed");- expect(queue.view().armed).toBe(true);expect(queue.handleEscape()).toBe("cancel");- expect(queue.view()).toMatchObject({ armed: true, cancelling: true });+ expect(queue.view().cancelling).toBe(true);});- it("disarms on other activity so a stale Esc cannot cancel", () => {+ it("keeps repeated empty-queue Esc cancellation idempotent", () => {const queue = new MessageQueue();- queue.handleEscape();- queue.disarm();- expect(queue.handleEscape()).toBe("armed");+ expect(queue.handleEscape()).toBe("cancel");+ expect(queue.handleEscape()).toBe("cancel");+ expect(queue.view().cancelling).toBe(true);});it("requests direct cancellation without consuming queued messages", () => {@@ -69,7 +67,7 @@ describe("MessageQueue", () => {queue.requestCancellation();- expect(queue.view()).toMatchObject({ armed: false, cancelling: true });+ expect(queue.view().cancelling).toBe(true);expect(queue.takePrompt()).toBe("follow-up");});@@ -96,7 +94,7 @@ describe("MessageQueue", () => {queue.handleEscape();queue.handleEscape();queue.beginTurn();- expect(queue.view()).toMatchObject({ armed: false, cancelling: false });+ expect(queue.view().cancelling).toBe(false);});});@@ -145,11 +143,8 @@ describe("renderMessageQueueRows", () => {expect(rows[1]).toContain("└ go south");});- it("teaches the second Esc after arming, and confirms cancellation", () => {+ it("confirms cancellation after one empty-queue Esc", () => {const queue = new MessageQueue();- queue.handleEscape();- expect(render(queue)).toEqual([expect.stringContaining("Press esc again to cancel the turn")]);-queue.handleEscape();expect(render(queue)).toEqual([expect.stringContaining("Cancelling turn…")]);});diff --git a/packages/eve/src/cli/dev/tui/message-queue.ts b/packages/eve/src/cli/dev/tui/message-queue.tsindex 18b1f2085..289002c10 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.- * `/cancel` requests cancellation directly. 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 cancels the+ * turn immediately 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.@@ -29,9 +29,7 @@ export type MessageQueueEscapeOutcome =* into the same staged steer payload and re-request cancellation.*/| "steer"- /** Queue empty: cancellation armed; the next Esc cancels. */- | "armed"- /** Second Esc on an empty queue — the caller should cancel the turn. */+ /** Empty queue — the caller should cancel the turn. */| "cancel";/** Read-only projection consumed by {@link renderMessageQueueRows}. */@@ -40,16 +38,13 @@ export interface MessageQueueView {readonly full: boolean;/** A popped message is staged and turn cancellation was requested. */readonly steering: boolean;- /** First Esc on an empty queue landed; the next one cancels. */- readonly armed: boolean;- /** Esc Esc on an empty queue landed; cancellation was requested. */+ /** Esc on an empty queue landed; cancellation was requested. */readonly cancelling: boolean;}export class MessageQueue {#messages: string[] = [];#steerMessage: string | undefined;- #escArmed = false;#cancelRequested = false;get size(): number {@@ -60,13 +55,10 @@ export class MessageQueue {return this.#messages.length >= MESSAGE_QUEUE_LIMIT;}- /** True when nothing is queued, staged, armed, or cancelling. */+ /** True when nothing is queued, staged, or cancelling. */get idle(): boolean {return (- this.#messages.length === 0 &&- this.#steerMessage === undefined &&- !this.#escArmed &&- !this.#cancelRequested+ this.#messages.length === 0 && this.#steerMessage === undefined && !this.#cancelRequested);}@@ -74,14 +66,13 @@ export class MessageQueue {enqueue(message: string): boolean {if (this.full) return false;this.#messages.push(message);- this.#escArmed = false;return true;}/*** Applies one Esc press. Pops the oldest queued message into the staged- * steer payload while any remain; with an empty queue, arms and then- * requests cancellation.+ * steer payload while any remain; with an empty queue, requests+ * cancellation immediately.*/handleEscape(): MessageQueueEscapeOutcome {const popped = this.#messages.shift();@@ -93,28 +84,17 @@ export class MessageQueue {// Already steering: re-request cancellation (idempotent server-side).return "steer";}- if (!this.#escArmed) {- this.#escArmed = true;- return "armed";- }this.#cancelRequested = true;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;- }-/** Clears per-turn Esc state when a new stream starts rendering. */beginTurn(): void {- this.#escArmed = false;this.#cancelRequested = false;}@@ -124,7 +104,6 @@ export class MessageQueue {* steered turn), otherwise the whole queue coalesced into one message.*/takePrompt(): string | undefined {- this.#escArmed = false;this.#cancelRequested = false;const steer = this.#steerMessage;if (steer !== undefined) {@@ -140,7 +119,6 @@ export class MessageQueue {* a clean boundary (interrupt, transport failure). Clears the queue.*/restoreDraft(): string | undefined {- this.#escArmed = false;this.#cancelRequested = false;const steer = this.#steerMessage;this.#steerMessage = undefined;@@ -150,7 +128,6 @@ export class MessageQueue {reset(): void {this.#messages = [];this.#steerMessage = undefined;- this.#escArmed = false;this.#cancelRequested = false;}@@ -159,7 +136,6 @@ export class MessageQueue {messages: [...this.#messages],full: this.full,steering: this.#steerMessage !== undefined,- armed: this.#escArmed,cancelling: this.#cancelRequested,};}@@ -206,14 +182,6 @@ export function renderMessageQueueRows(input: MessageQueuePanelRowsInput): strinif (view.cancelling) {return [clipVisible(`${lead}${c.yellow(g.dotActive)} ${c.dim("Cancelling turn…")}`, width)];}- if (view.armed) {- return [- clipVisible(- `${lead}${c.yellow(g.dotActive)} ${c.dim("Press esc again to cancel the turn")}`,- width,- ),- ];- }return [];}diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex f1712e87d..5c862669e 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -126,11 +126,11 @@ export type AgentTUIStreamResult = {abort?: () => void;/*** Requests cooperative server-side cancellation of the streaming turn- * (`/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` or Esc, which steers when a message is queued). 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;turnState?: AgentTUITurnState;@@ -2122,7 +2122,7 @@ async function* eveEventsToTUIStream(break;case "turn.cancelled":- // A cooperative cancel (Esc Esc or an Esc steer) — not a failure.+ // A cooperative cancel (`/cancel`, Esc, or an Esc steer) — not a failure.// `session.waiting` follows and finishes the stream normally.onTurnCancelled?.();yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.tsindex a7096a084..c4438a7c0 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts@@ -187,11 +187,11 @@ export class SubagentPump {/*** Settles every live run and stops its child stream. Called when the- * parent turn is cancelled (an Esc steer or Esc Esc): the server cancels- * the pending descendants, so their sections must close now — a child- * still flushing reasoning would otherwise keep painting stale sections- * into the next (steered) turn's transcript. Runs stay registered so a- * late parent `subagent.completed` settles as a no-op.+ * parent turn is cancelled (`/cancel`, an Esc steer, or an empty-queue+ * Esc): the server cancels the pending descendants, so their sections must+ * close now. A child still flushing reasoning would otherwise keep painting+ * stale sections into the next (steered) turn's transcript. Runs stay+ * registered so a late parent `subagent.completed` settles as a no-op.*/settleAll(): void {for (const callId of this.#runs.keys()) {diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex bcec80987..265dbf93d 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -1843,7 +1843,7 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});- it("arms on the first empty-queue Esc and cancels the turn on the second", async () => {+ it("cancels the turn on the first empty-queue Esc", async () => {const { screen, input, renderer } = makeRenderer();const escape = async () => {input.send("\x1b");@@ -1866,16 +1866,6 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(screen.snapshot()).toContain("›");});- await escape();- expect(cancel).not.toHaveBeenCalled();- expect(screen.snapshot()).toContain("Press esc again to cancel the turn");-- // Any other key backs out of the armed state.- input.left();- await escape();- expect(cancel).not.toHaveBeenCalled();- expect(screen.snapshot()).toContain("Press esc again to cancel the turn");-await escape();expect(cancel).toHaveBeenCalledTimes(1);expect(screen.snapshot()).toContain("Cancelling turn…");diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex 7d06f658c..ce69448ba 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -534,7 +534,7 @@ export class TerminalRenderer implements AgentTUIRenderer {/*** Messages submitted while a turn streams, pinned in a panel directly* above the input. Enter queues, `/cancel` cancels directly, and Esc- * pops-to-steer or (empty) arms and then cancels; the runner drains via+ * pops-to-steer or cancels immediately when empty; the runner drains via* {@link takeQueuedPrompt} at a clean turn boundary and {@link readPrompt}* restores any leftovers as a draft.*/@@ -551,7 +551,7 @@ export class TerminalRenderer implements AgentTUIRenderer {* the user block can carry its steer/queue gutter arrow.*/#nextSubmittedPromptOrigin?: "steer" | "queue";- /** True once an Esc in THIS stream requested cancellation (steer or Esc Esc). */+ /** True once this stream's prompt requested cancellation or steering. */#cancelRequestedByUser = false;/** The prompt submitted for the streaming turn, for external-cancel recovery. */#currentSubmittedPrompt?: string;@@ -2990,20 +2990,16 @@ export class TerminalRenderer implements AgentTUIRenderer {case "escape": {// Esc drives steering and cancellation: pop the oldest queued// message and cancel the running turn so the runner submits it as- // the replacement turn; with nothing queued, arm once and cancel on- // the second press. Without a cancel capability an empty queue- // leaves Esc inert — arming would promise a cancel that can't land.+ // the replacement turn; with nothing queued, cancel immediately.+ // Without a cancel capability an empty queue leaves Esc inert.if (this.#messageQueue.idle && this.#requestTurnCancel === undefined) break;- const outcome = this.#messageQueue.handleEscape();- if (outcome === "steer" || outcome === "cancel") {- this.#cancelRequestedByUser = true;- this.#requestTurnCancel?.();- }+ this.#messageQueue.handleEscape();+ this.#cancelRequestedByUser = true;+ this.#requestTurnCancel?.();this.#paint();break;}default: {- this.#messageQueue.disarm();const edited = applyLineEditorKey(this.#streamDraft, key, { multiline: true });if (edited !== undefined) {this.#streamDraft = edited;@@ -3376,9 +3372,9 @@ export class TerminalRenderer implements AgentTUIRenderer {break;case "turn-cancelled":- // The server settled the turn cooperatively (an Esc steer or- // Esc Esc); its in-flight tool calls get no further updates and are- // settled by the interrupted-blocks sweep at stream end.+ // The server settled the turn cooperatively (an Esc steer or an+ // empty-queue Esc); its in-flight tool calls get no further updates.+ // The interrupted-blocks sweep settles them at stream end.this.#turnCancelled = true;// A cancellation nobody asked for through THIS prompt — a stale// cancel from the previous turn landing late (the unguardeddiff --git a/packages/eve/test/tui-client/tui-queue-steer.ts b/packages/eve/test/tui-client/tui-queue-steer.tsindex 3a745ee20..3aa813069 100644--- a/packages/eve/test/tui-client/tui-queue-steer.ts+++ b/packages/eve/test/tui-client/tui-queue-steer.ts@@ -9,7 +9,7 @@ import { theme } from "./lib/theme.ts";/*** End-to-end proof of the mid-turn message queue, Esc steering, and- * cooperative cancellation against a live server:+ * single-Esc cooperative cancellation against a live server:** 1. Start a long turn, then submit two messages while it streams —* both must land in the pinned `↑ Queue n/5` panel, not the turn.@@ -20,6 +20,8 @@ import { theme } from "./lib/theme.ts";* 3. The remaining queued message auto-drains as the following turn.* 4. The steered echo carries the `↑` provenance arrow above its bar,* the queued one below, and the runner returns to an idle prompt.+ * 5. With no message queued, one Esc cancels another long turn, then a+ * follow-up succeeds on the preserved session.** The tokens prove delivery order end-to-end: each must appear twice* (the echoed user block and the model's reply).@@ -27,6 +29,7 @@ import { theme } from "./lib/theme.ts";const STEER_TOKEN = "STEER-MARKER-B7Q";const QUEUE_TOKEN = "QUEUE-MARKER-K4Z";+const CANCEL_FOLLOW_UP_TOKEN = "CANCEL-FOLLOW-UP-MARKER-P8N";process.env.EVE_TUI_UNICODE = "1";run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {@@ -102,6 +105,30 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {}console.log(theme.muted("[tui-queue-steer] provenance arrows rendered"));+ const cancellationOutputStart = screen.rawOutput().length;+ input.type("Write a story of about 500 words about lighthouses. Do not use any tools.");+ input.enter();+ await screen.waitForText("Working for", 30_000);++ // With no queued message, the first Esc cooperatively cancels the turn.+ input.emit("data", Buffer.from("\x1b"));+ await sleep(60);+ await waitForRawOutput(+ screen,+ "Cancelled",+ cancellationOutputStart,+ 30_000,+ "single-Esc cancellation",+ );+ await screen.waitForIdlePrompt(30_000);+ console.log(theme.muted("[tui-queue-steer] one empty-queue Esc cancelled the turn"));++ input.type(`Reply with one short sentence containing the token ${CANCEL_FOLLOW_UP_TOKEN}.`);+ input.enter();+ await waitForTwice(screen, CANCEL_FOLLOW_UP_TOKEN, 120_000, "post-cancellation follow-up");+ await screen.waitForIdlePrompt(60_000);+ console.log(theme.muted("[tui-queue-steer] preserved session answered after cancellation"));+input.ctrlC();await runPromise;});@@ -120,3 +147,18 @@ async function waitForTwice(}throw new Error(`Timed out waiting for: ${label}\n${screen.snapshot()}`);}++async function waitForRawOutput(+ screen: MockScreen,+ text: string,+ start: number,+ timeoutMs: number,+ label: string,+): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (screen.rawOutput().slice(start).includes(text)) return;+ await sleep(100);+ }+ throw new Error(`Timed out waiting for: ${label}\n${screen.snapshot()}`);+}