Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): queue, steer, and cancel turns in the dev TUI (#1119)

Ruibbba07378068
diff --git a/.changeset/dev-tui-queue-steer-cancel.md b/.changeset/dev-tui-queue-steer-cancel.md
new file mode 100644
index 000000000..77db240ff
--- /dev/null
+++ b/.changeset/dev-tui-queue-steer-cancel.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The dev TUI supports queueing, steering, and cooperative turn cancellation. Pressing Enter while a turn is running queues the message (up to 5) in a pinned panel directly above the input — one line per message — and the queue coalesces into the next turn's message when the turn ends. Esc steers: it pops the oldest queued message, cancels the running turn cooperatively (`turn.cancelled` → `session.waiting`, keeping the session's context), and submits the popped message as the replacement turn. With nothing queued, Esc twice cancels the turn. Cancellation requests retry while the turn is live, so an Esc that lands in the turn-dispatch window (before the server has armed the turn's cancel hook) is no longer silently lost. Cancelling a turn mid-delegation settles its subagent sections and stops their child streams, so stale subagent output cannot paint into the steered turn. Messages still queued when a turn is interrupted or fails restore into the next prompt's input, and a turn cancelled from outside the prompt (a stale cancel or another client's `/cancel`) restores its submitted message the same way. On exit, the parting line names the server session id (`☰eve v0.27.0 · session ses_…`) so the conversation can be found again.
diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.md
index b97f6aab5..12df1d99d 100644
--- a/docs/guides/dev-tui.md
+++ b/docs/guides/dev-tui.md
@@ -71,7 +71,8 @@ Chat and freeform `ask_question` inputs behave like a shell line editor.
| Key | Action |
| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
-| `Enter` | Submit the message or question response. |
+| `Enter` | Submit the message or question response. While a turn is running, queue the message for the next turn. |
+| `Esc` | While a turn runs: pop the oldest queued message and steer with it; with nothing queued, press twice to cancel. |
| `Shift+Enter` | Insert a newline without sending (needs a terminal that reports modified keys). |
| `Ctrl+C` | Interrupt a running turn. At the chat or freeform-question prompt, clear non-empty input; when empty, quit. |
| `↑` / `↓` | Move between input lines; at a chat-buffer edge, navigate messages you have sent this session. |
@@ -82,7 +83,13 @@ Chat and freeform `ask_question` inputs behave like a shell line editor.
In terminals that support bracketed paste, pasting multi-line text into chat or a freeform question inserts it intact and renders one row per line rather than submitting at the first line. `Shift+Enter` adds a line by hand. The input grows down to the available terminal height, then scrolls to keep the caret visible; `Enter` submits the whole response.
-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.
+### 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.
+
+`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.
+
+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.
## Answer the agent inline
diff --git a/packages/eve/src/cli/dev/tui/blocks.test.ts b/packages/eve/src/cli/dev/tui/blocks.test.ts
index 8bb79ac47..3e9b6cec6 100644
--- a/packages/eve/src/cli/dev/tui/blocks.test.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.test.ts
@@ -204,6 +204,50 @@ describe("renderBlockLines", () => {
expect(lines).toEqual([" ※ subagent(self:4)"]);
});
+ it("marks steered and queued user messages with a gutter arrow", () => {
+ const steered = render({
+ kind: "user",
+ body: "need to be\n\nsuper accurate",
+ promptOrigin: "steer",
+ });
+ expect(steered).toEqual(["↑", "│ need to be", "│ ", "│ super accurate"]);
+
+ const queued = render({ kind: "user", body: "later then", promptOrigin: "queue" });
+ expect(queued).toEqual(["│ later then", "↑"]);
+
+ // An ordinary typed prompt keeps its bare bar.
+ expect(render({ kind: "user", body: "hello" })).toEqual(["│ hello"]);
+ });
+
+ it("colors the provenance arrow with the user bar's accent", () => {
+ const colorTheme = createTheme({ color: true, unicode: true });
+ const rows = renderBlockLines(
+ { kind: "user", body: "go", promptOrigin: "steer" },
+ 80,
+ colorTheme,
+ { activityPulse: "▪" },
+ );
+ // Same cyan as the `│` gutter bar.
+ expect(rows[0]).toBe("\x1b[36m↑\x1b[39m");
+ expect(rows[1]).toContain("\x1b[36m│\x1b[39m");
+ });
+
+ it("pulses the in-progress subagent mark by intensity, with a quiet label", () => {
+ const colorTheme = createTheme({ color: true, unicode: true });
+ const running = { kind: "subagent", title: "echo-marker", live: true } as const;
+ const onBeat = renderBlockLines(running, 80, colorTheme, { activityPulse: "▪" })[0] ?? "";
+ const offBeat = renderBlockLines(running, 80, colorTheme, { activityPulse: " " })[0] ?? "";
+
+ // The mark rides the shared beat: orange on, dim off — the glyph never
+ // blanks, so the section keeps its anchor.
+ expect(onBeat).toContain("\x1b[38;5;208m※");
+ expect(offBeat).toContain("\x1b[2m※");
+ expect(stripAnsi(offBeat)).toBe(" ※ subagent(echo-marker)");
+
+ // The label stays quiet — no bold anywhere in the header.
+ expect(onBeat).not.toContain("\x1b[1m");
+ });
+
it("collapses a child message to its first line inside the section", () => {
const lines = render({
kind: "subagent-step",
diff --git a/packages/eve/src/cli/dev/tui/blocks.ts b/packages/eve/src/cli/dev/tui/blocks.ts
index 18ac322a1..3a699d584 100644
--- a/packages/eve/src/cli/dev/tui/blocks.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.ts
@@ -71,6 +71,13 @@ export interface Block {
subtitle?: string;
/** Main multi-line content (markdown for prose, plain for logs). */
body?: string;
+ /**
+ * User blocks only: how a mid-turn message reached the transcript. A
+ * steered message (Esc pop, displacing the running turn) marks itself
+ * with the accent arrow above its bar; a queued one (drained at the turn
+ * boundary) carries the arrow below. Absent for ordinary typed prompts.
+ */
+ promptOrigin?: "steer" | "queue";
/** Reasoning trace shown above `body` (subagent steps). */
reasoning?: string;
/** One-line summarized result shown after a tool resolves. */
@@ -239,7 +246,7 @@ function renderBody(
case "log":
return renderLog(block, width, theme);
case "subagent":
- return renderSubagentHeader(block, width, theme);
+ return renderSubagentHeader(block, width, theme, context);
case "subagent-close": {
// Closes the section's rail. A completed section's corner carries
// the collapsed activity footnote instead of railed children.
@@ -262,7 +269,14 @@ function renderBody(
function renderUser(block: Block, width: number, theme: Theme): string[] {
const bar = theme.colors.cyan(theme.glyph.user);
const lines = wrap(block.body ?? "", width - 2);
- return lines.map((line) => `${bar} ${line}`);
+ const rows = lines.map((line) => `${bar} ${line}`);
+ // Mid-turn provenance rides the gutter in the bar's own accent: a steered
+ // message pushed itself ahead of the running turn (arrow above), a queued
+ // one waited for the boundary (arrow below).
+ const arrow = theme.colors.cyan(theme.glyph.arrowUp);
+ if (block.promptOrigin === "steer") return [arrow, ...rows];
+ if (block.promptOrigin === "queue") return [...rows, arrow];
+ return rows;
}
function renderProse(block: Block, width: number, theme: Theme): string[] {
@@ -564,7 +578,12 @@ function renderTurnStats(block: Block, width: number, theme: Theme): string[] {
return [theme.colors.dim(truncatePlain(line, Math.max(1, width)))];
}
-function renderSubagentHeader(block: Block, width: number, theme: Theme): string[] {
+function renderSubagentHeader(
+ block: Block,
+ width: number,
+ theme: Theme,
+ context: RenderBlockContext,
+): string[] {
// `subagent(<name>)`; the generic self-delegation tool (literally named
// `agent`) reads as `subagent(self)`. Only the `※` mark carries orange —
// lead, rails, and name stay quiet around it.
@@ -574,14 +593,18 @@ function renderSubagentHeader(block: Block, width: number, theme: Theme): string
const lead = TOOL_COLUMN_LEAD;
// The ordinal rides inside the parens (`subagent(self:4)`) in every
// state. Completion reports on the closing corner (`└ Done…`); the
- // header only flips its mark from working orange to done green.
+ // header only settles its mark: an in-progress section pulses the `※`
+ // on the shared activity beat — by intensity (orange ↔ dim), so the
+ // glyph keeps anchoring the section — and a done one holds green.
const isOrdinal = block.subtitle !== undefined && block.subtitle.startsWith("#");
const ordinal = isOrdinal ? `:${block.subtitle!.slice(1)}` : "";
const mark =
block.status === "done"
? theme.colors.green(theme.glyph.subagent)
- : theme.colors.orange(theme.glyph.subagent);
- let header = `${lead}${mark} ${theme.colors.bold(`subagent(${name}${ordinal})`)}`;
+ : context.activityPulse.trim().length > 0
+ ? theme.colors.orange(theme.glyph.subagent)
+ : theme.colors.dim(theme.glyph.subagent);
+ let header = `${lead}${mark} subagent(${name}${ordinal})`;
if (!isOrdinal && block.subtitle !== undefined && block.subtitle.length > 0) {
header += ` ${theme.colors.dim(block.subtitle)}`;
}
diff --git a/packages/eve/src/cli/dev/tui/message-queue.test.ts b/packages/eve/src/cli/dev/tui/message-queue.test.ts
new file mode 100644
index 000000000..58bfd3650
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/message-queue.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it } from "vitest";
+
+import { MESSAGE_QUEUE_LIMIT, MessageQueue, renderMessageQueueRows } from "./message-queue.js";
+import { createTheme } from "./theme.js";
+
+const theme = createTheme({ color: false, unicode: true });
+
+describe("MessageQueue", () => {
+ it("queues up to the limit and refuses further messages", () => {
+ const queue = new MessageQueue();
+ for (let index = 0; index < MESSAGE_QUEUE_LIMIT; index += 1) {
+ expect(queue.enqueue(`message ${String(index)}`)).toBe(true);
+ }
+ expect(queue.full).toBe(true);
+ expect(queue.enqueue("one too many")).toBe(false);
+ expect(queue.size).toBe(MESSAGE_QUEUE_LIMIT);
+ });
+
+ it("pops the oldest message into the steer payload on Esc", () => {
+ const queue = new MessageQueue();
+ queue.enqueue("first");
+ queue.enqueue("second");
+
+ expect(queue.handleEscape()).toBe("steer");
+ expect(queue.view()).toMatchObject({ steering: true, messages: ["second"] });
+ expect(queue.takePrompt()).toBe("first");
+ // The remaining message stays queued for the steered turn.
+ expect(queue.view().messages).toEqual(["second"]);
+ });
+
+ it("coalesces repeated Esc pops into one staged steer payload", () => {
+ const queue = new MessageQueue();
+ queue.enqueue("first");
+ queue.enqueue("second");
+
+ expect(queue.handleEscape()).toBe("steer");
+ expect(queue.handleEscape()).toBe("steer");
+ expect(queue.takePrompt()).toBe("first\n\nsecond");
+ expect(queue.idle).toBe(true);
+ });
+
+ it("re-reports steer (not armed) 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);
+ });
+
+ it("arms on the first empty-queue Esc and cancels on the second", () => {
+ 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 });
+ });
+
+ it("disarms on other activity so a stale Esc cannot cancel", () => {
+ const queue = new MessageQueue();
+ queue.handleEscape();
+ queue.disarm();
+ expect(queue.handleEscape()).toBe("armed");
+ });
+
+ it("drains the whole queue as one coalesced prompt at a turn boundary", () => {
+ const queue = new MessageQueue();
+ queue.enqueue("first");
+ queue.enqueue("second");
+ expect(queue.takePrompt()).toBe("first\n\nsecond");
+ expect(queue.takePrompt()).toBeUndefined();
+ });
+
+ it("restores staged and queued messages into one draft", () => {
+ const queue = new MessageQueue();
+ queue.enqueue("first");
+ queue.enqueue("second");
+ queue.handleEscape();
+
+ expect(queue.restoreDraft()).toBe("first\n\nsecond");
+ expect(queue.idle).toBe(true);
+ });
+
+ it("clears per-turn esc state when a new turn begins", () => {
+ const queue = new MessageQueue();
+ queue.handleEscape();
+ queue.handleEscape();
+ queue.beginTurn();
+ expect(queue.view()).toMatchObject({ armed: false, cancelling: false });
+ });
+});
+
+describe("renderMessageQueueRows", () => {
+ const render = (queue: MessageQueue, working = true) =>
+ renderMessageQueueRows({ view: queue.view(), width: 80, theme, working });
+
+ it("renders nothing while idle", () => {
+ expect(render(new MessageQueue())).toEqual([]);
+ });
+
+ it("renders one clipped line per message under a counted header", () => {
+ const queue = new MessageQueue();
+ queue.enqueue("first message\nwith a second line that never shows");
+ queue.enqueue("second message");
+
+ const rows = render(queue);
+ expect(rows[0]).toContain("↑ Queue 2/5");
+ expect(rows[0]).toContain("esc steers with the next message");
+ expect(rows[1]).toContain("│ first message");
+ expect(rows[1]).not.toContain("second line");
+ expect(rows[2]).toContain("└ second message");
+ });
+
+ it("marks a full queue", () => {
+ const queue = new MessageQueue();
+ for (let index = 0; index < MESSAGE_QUEUE_LIMIT; index += 1) queue.enqueue("m");
+ expect(render(queue)[0]).toContain("queue full");
+ });
+
+ it("drops the esc hint when no turn is streaming", () => {
+ const queue = new MessageQueue();
+ queue.enqueue("waiting");
+ expect(render(queue, false)[0]).not.toContain("esc");
+ });
+
+ it("shows the steering header while cancellation is in flight", () => {
+ const queue = new MessageQueue();
+ queue.enqueue("go north");
+ queue.enqueue("go south");
+ queue.handleEscape();
+
+ const rows = render(queue);
+ expect(rows[0]).toContain("Steering — cancelling the running turn…");
+ expect(rows[0]).toContain("1/5 still queued");
+ expect(rows[1]).toContain("└ go south");
+ });
+
+ it("teaches the second Esc after arming, and confirms cancellation", () => {
+ 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.ts
new file mode 100644
index 000000000..ad35afa00
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/message-queue.ts
@@ -0,0 +1,240 @@
+/**
+ * The pinned message-queue panel: client-side state and pure rendering for
+ * messages submitted while a turn is still streaming.
+ *
+ * Enter queues the draft (up to {@link MESSAGE_QUEUE_LIMIT}); each queued
+ * message waits for the turn to end, where the whole queue coalesces into
+ * 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.
+ *
+ * The renderer owns lifecycle (keys, cancel requests, when the runner drains
+ * the queue); this module only holds the queue state machine and paints rows.
+ */
+
+import type { Theme } from "./theme.js";
+import { TOOL_COLUMN_LEAD } from "./rail.js";
+import { clipVisible, stripTerminalControls } from "#cli/ui/terminal-text.js";
+
+/** Most messages the queue holds; Enter on a full queue keeps the draft. */
+export const MESSAGE_QUEUE_LIMIT = 5;
+
+/** What one Esc press did to the queue state. */
+export type MessageQueueEscapeOutcome =
+ /**
+ * A message is (now) staged for steering — the caller should request
+ * cooperative turn cancellation. Repeated presses pop further messages
+ * 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. */
+ | "cancel";
+
+/** Read-only projection consumed by {@link renderMessageQueueRows}. */
+export interface MessageQueueView {
+ readonly messages: readonly string[];
+ 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. */
+ readonly cancelling: boolean;
+}
+
+export class MessageQueue {
+ #messages: string[] = [];
+ #steerMessage: string | undefined;
+ #escArmed = false;
+ #cancelRequested = false;
+
+ get size(): number {
+ return this.#messages.length;
+ }
+
+ get full(): boolean {
+ return this.#messages.length >= MESSAGE_QUEUE_LIMIT;
+ }
+
+ /** True when nothing is queued, staged, armed, or cancelling. */
+ get idle(): boolean {
+ return (
+ this.#messages.length === 0 &&
+ this.#steerMessage === undefined &&
+ !this.#escArmed &&
+ !this.#cancelRequested
+ );
+ }
+
+ /** Queues one message; returns false (draft stays put) when full. */
+ 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.
+ */
+ handleEscape(): MessageQueueEscapeOutcome {
+ const popped = this.#messages.shift();
+ if (popped !== undefined) {
+ this.#steerMessage = joinMessages(this.#steerMessage, popped);
+ return "steer";
+ }
+ if (this.#steerMessage !== undefined) {
+ // Already steering: re-request cancellation (idempotent server-side).
+ return "steer";
+ }
+ if (!this.#escArmed) {
+ this.#escArmed = true;
+ return "armed";
+ }
+ this.#cancelRequested = true;
+ return "cancel";
+ }
+
+ /** 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;
+ }
+
+ /**
+ * The next prompt to submit after a turn boundary: the staged steer
+ * message when one exists (remaining queued messages stay queued for the
+ * 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) {
+ this.#steerMessage = undefined;
+ return steer;
+ }
+ return this.#takeAllMessages();
+ }
+
+ /**
+ * Everything still held — staged steer payload plus queued messages —
+ * coalesced for restoring into the prompt editor when a turn ends without
+ * 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;
+ return joinOptionalMessages(steer, this.#takeAllMessages());
+ }
+
+ reset(): void {
+ this.#messages = [];
+ this.#steerMessage = undefined;
+ this.#escArmed = false;
+ this.#cancelRequested = false;
+ }
+
+ view(): MessageQueueView {
+ return {
+ messages: [...this.#messages],
+ full: this.full,
+ steering: this.#steerMessage !== undefined,
+ armed: this.#escArmed,
+ cancelling: this.#cancelRequested,
+ };
+ }
+
+ #takeAllMessages(): string | undefined {
+ if (this.#messages.length === 0) return undefined;
+ const combined = this.#messages.reduce<string | undefined>(joinOptionalMessages, undefined);
+ this.#messages = [];
+ return combined;
+ }
+}
+
+function joinMessages(existing: string | undefined, appended: string): string {
+ return existing === undefined ? appended : `${existing}\n\n${appended}`;
+}
+
+function joinOptionalMessages(a: string | undefined, b: string | undefined): string | undefined {
+ if (b === undefined) return a;
+ return joinMessages(a, b);
+}
+
+export interface MessageQueuePanelRowsInput {
+ readonly view: MessageQueueView;
+ readonly width: number;
+ readonly theme: Theme;
+ /** True while a turn streams — the only state in which Esc steers. */
+ readonly working: boolean;
+}
+
+/**
+ * Paints the pinned queue panel, indented so its marks share the tool
+ * column. Queued messages ride a `│` rail under the header (one clipped
+ * line each) and the last closes it with `└`. The header carries the Esc
+ * affordance — the panel is where steering and cancellation are taught.
+ */
+export function renderMessageQueueRows(input: MessageQueuePanelRowsInput): string[] {
+ const { view, width, theme, working } = input;
+ const c = theme.colors;
+ const g = theme.glyph;
+ const lead = TOOL_COLUMN_LEAD;
+
+ if (view.messages.length === 0 && !view.steering) {
+ if (!working) return [];
+ if (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 [];
+ }
+
+ const rows = [
+ clipVisible(`${lead}${c.gray(g.arrowUp)} ${headerBody(view, working, theme)}`, width),
+ ];
+ for (const [index, message] of view.messages.entries()) {
+ const rail = index === view.messages.length - 1 ? g.corner : g.rule;
+ const body = firstLine(stripTerminalControls(message));
+ rows.push(clipVisible(`${lead}${c.dim(rail)} ${c.dim(body)}`, width));
+ }
+ return rows;
+}
+
+function headerBody(view: MessageQueueView, working: boolean, theme: Theme): string {
+ const c = theme.colors;
+ const dot = ` ${theme.glyph.dot} `;
+ const count = `${String(view.messages.length)}/${String(MESSAGE_QUEUE_LIMIT)}`;
+ if (view.steering) {
+ const remaining = view.messages.length > 0 ? `${dot}${count} still queued` : "";
+ return c.dim(`Steering — cancelling the running turn…${remaining}`);
+ }
+ const fullness = view.full ? `${dot}queue full` : "";
+ const hint = working ? `${dot}esc steers with the next message` : "";
+ return `${c.bold("Queue")} ${c.dim(`${count}${fullness}${hint}`)}`;
+}
+
+function firstLine(text: string): string {
+ return text.split(/\r?\n/u, 1)[0] ?? "";
+}
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 510355625..76ad8337f 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -2710,3 +2710,273 @@ describe("EveTUIRunner command outcome rendering", () => {
expect(notices).toEqual([]);
});
});
+
+describe("EveTUIRunner mid-turn message queue", () => {
+ it("submits the queued prompt as the next turn without reading the prompt", async () => {
+ const session = sessionYielding([{ type: "session.waiting" }]);
+ const queued: Array<string | undefined> = ["queued follow-up", undefined];
+ const prompts: Array<string | undefined> = ["hello", undefined];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<unknown>) {
+ void event;
+ }
+ }),
+ takeQueuedPrompt: vi.fn(() => queued.shift()),
+ });
+
+ const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });
+ await runner.run();
+
+ expect(session.send).toHaveBeenCalledTimes(2);
+ expect(session.send).toHaveBeenNthCalledWith(1, expect.objectContaining({ message: "hello" }));
+ expect(session.send).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ message: "queued follow-up" }),
+ );
+ // The drained prompt bypasses the interactive prompt read entirely.
+ expect(renderer.readPrompt).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not drain the queue when the stream ends without a turn boundary", async () => {
+ const session = sessionYielding([]);
+ const takeQueuedPrompt = vi.fn(() => "should stay queued");
+ const prompts: Array<string | undefined> = ["hello", undefined];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<unknown>) {
+ void event;
+ }
+ }),
+ takeQueuedPrompt,
+ });
+
+ const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });
+ await runner.run();
+
+ // The lost-stream turn keeps queued input for the prompt's draft restore.
+ expect(takeQueuedPrompt).not.toHaveBeenCalled();
+ expect(session.send).toHaveBeenCalledTimes(1);
+ });
+
+ it("retries a cancel that raced turn dispatch and scopes it once the turn id is known", async () => {
+ const gate = createDeferred<void>();
+ const session = stubSession();
+ vi.spyOn(session, "send").mockImplementation(
+ async () =>
+ new MessageResponse({
+ continuationToken: "eve:test",
+ createStream: async function* () {
+ yield { type: "turn.started", data: { turnId: "turn-1", sequence: 1 } } as never;
+ // Hold the stream mid-turn until the retry loop has proven both
+ // attempts, then settle the turn as cancelled.
+ await gate.promise;
+ yield { type: "turn.cancelled", data: { turnId: "turn-1", sequence: 2 } } as never;
+ yield { type: "session.waiting" } as never;
+ },
+ sessionId: "session_test",
+ }),
+ );
+ const cancelCalls: Array<{ turnId?: string } | undefined> = [];
+ vi.spyOn(session, "cancel").mockImplementation(async (options?: { turnId?: string }) => {
+ cancelCalls.push(options);
+ if (cancelCalls.length >= 2) {
+ gate.resolve();
+ return { sessionId: "session_test", status: "accepted" as const };
+ }
+ // The first request raced the dispatch window: the turn workflow has
+ // not claimed its cancel hook yet, so the server reports no turn.
+ return { sessionId: "session_test", status: "no_active_turn" as const };
+ });
+ const prompts: Array<string | undefined> = ["hello", undefined];
+ const seen: string[] = [];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ // Esc lands before the first stream event arrives.
+ result.cancel?.();
+ for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {
+ seen.push(event.type);
+ }
+ }),
+ });
+
+ const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });
+ await runner.run();
+
+ // `turn.cancelled` reaches the renderer as its own stream event.
+ expect(seen).toContain("turn-cancelled");
+ expect(cancelCalls).toHaveLength(2);
+ // First attempt fired before `turn.started` named the turn; the retry
+ // carries the observed id so it can never cancel a later turn.
+ expect(cancelCalls[0]).toBeUndefined();
+ expect(cancelCalls[1]).toEqual({ turnId: "turn-1" });
+ });
+
+ it("drops a cancel request that arrives after the turn boundary", async () => {
+ const session = sessionYielding([
+ { type: "turn.started", data: { turnId: "turn-1", sequence: 1 } },
+ { type: "session.waiting" },
+ ]);
+ const cancel = vi
+ .spyOn(session, "cancel")
+ .mockResolvedValue({ sessionId: "session_test", status: "accepted" });
+ const prompts: Array<string | undefined> = ["hello", undefined];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<unknown>) {
+ void event;
+ }
+ // An Esc landing exactly as the boundary settles has nothing left
+ // to cancel — and must not reach the next turn.
+ result.cancel?.();
+ }),
+ });
+
+ const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });
+ await runner.run();
+
+ expect(cancel).not.toHaveBeenCalled();
+ });
+});
+
+describe("EveTUIRunner session id reporting", () => {
+ it("pushes the accepted session id and keeps it sticky across /new", async () => {
+ const session = sessionYielding([{ type: "session.waiting" }]);
+ vi.spyOn(session, "state", "get").mockReturnValue({
+ sessionId: "session_test",
+ streamIndex: 0,
+ });
+ const reported: string[] = [];
+ const prompts: Array<string | undefined> = ["hello", "/new", undefined];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<unknown>) {
+ void event;
+ }
+ }),
+ setSessionId: vi.fn((sessionId: string) => reported.push(sessionId)),
+ });
+
+ const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });
+ await runner.run();
+
+ // Named once the turn's send is accepted. `/new` (and interrupt
+ // recovery, which shares #startNewSession) must NOT clear it: the
+ // parting line names the last session this TUI talked to, and the
+ // replacement session has no id until its first turn is accepted.
+ expect(reported).toEqual(["session_test"]);
+ });
+
+ it("keeps the interrupted session's id for the parting line after Ctrl-C recovery", async () => {
+ // A stream that never settles: the user interrupts it client-side.
+ const gate = createDeferred<void>();
+ const session = stubSession();
+ vi.spyOn(session, "send").mockImplementation(
+ async () =>
+ new MessageResponse({
+ continuationToken: "eve:test",
+ createStream: async function* () {
+ yield { type: "turn.started", data: { turnId: "turn-1", sequence: 1 } } as never;
+ await gate.promise;
+ },
+ sessionId: "session_interrupted",
+ }),
+ );
+ vi.spyOn(session, "state", "get").mockReturnValue({
+ sessionId: "session_interrupted",
+ streamIndex: 0,
+ });
+ const reported: string[] = [];
+ const notices: string[] = [];
+ const prompts: Array<string | undefined> = ["hello", undefined];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ // Ctrl-C: abort the turn without draining the stream.
+ result.abort?.();
+ gate.resolve();
+ }),
+ renderNotice: (text) => notices.push(text),
+ setSessionId: vi.fn((sessionId: string) => reported.push(sessionId)),
+ });
+
+ const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });
+ await runner.run();
+
+ // The abort recovery replaces the session but the reported id — what
+ // the parting line prints — survives.
+ expect(reported).toEqual(["session_interrupted"]);
+ expect(notices.some((text) => text.includes("started a new session"))).toBe(true);
+ });
+});
+
+describe("EveTUIRunner cancelled-turn subagent settling", () => {
+ it("settles subagent sections when the turn is cancelled by a steer", async () => {
+ // A child stream that never ends on its own — it only stops when the
+ // pump aborts it (the settleAll path under test).
+ const childStream = (options?: { signal?: AbortSignal }) => ({
+ [Symbol.asyncIterator](): AsyncIterator<unknown> {
+ return {
+ next: () =>
+ new Promise((resolve) => {
+ options?.signal?.addEventListener(
+ "abort",
+ () => resolve({ done: true, value: undefined }),
+ { once: true },
+ );
+ }),
+ };
+ },
+ });
+ const client = stubClient();
+ vi.spyOn(client, "session").mockReturnValue({
+ stream: (options?: { signal?: AbortSignal }) => childStream(options),
+ } as never);
+
+ const session = sessionYielding([
+ {
+ type: "subagent.called",
+ data: {
+ callId: "call-1",
+ childSessionId: "child-1",
+ name: "researcher",
+ sequence: 1,
+ turnId: "turn-1",
+ },
+ },
+ { type: "turn.cancelled", data: { turnId: "turn-1", sequence: 2 } },
+ { type: "session.waiting" },
+ ]);
+ const view = {
+ begin: vi.fn(),
+ upsertStep: vi.fn(),
+ upsertTool: vi.fn(),
+ removeTool: vi.fn(),
+ complete: vi.fn(),
+ markChildToolCallId: vi.fn(),
+ };
+ const prompts: Array<string | undefined> = ["hello", undefined];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<unknown>) {
+ void event;
+ }
+ }),
+ subagents: view,
+ });
+
+ const runner = new EveTUIRunner({ session, client, renderer, name: "Weather Agent" });
+ await runner.run();
+
+ expect(view.begin).toHaveBeenCalledWith({ callId: "call-1", name: "researcher" });
+ // `subagent.completed` never arrives for a cancelled delegation — the
+ // cancellation itself must close the section.
+ expect(view.complete).toHaveBeenCalledWith({ callId: "call-1" });
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index 0720625cb..850e7973e 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -103,10 +103,33 @@ export { parsePromptCommand, type PromptCommand } from "./prompt-commands.js";
const defaultAssistantResponseStats: AssistantResponseStatsMode = "tokensPerSecond";
const idleRuntimeArtifactPollMs = 500;
+/**
+ * Cooperative-cancel retry cadence: 8 × 250ms covers the turn-dispatch
+ * window (locally the cancel hook is claimed well under a second after the
+ * send is accepted) without hammering the cancel route.
+ */
+const turnCancelRetryDelayMs = 250;
+const turnCancelAttempts = 8;
+
+async function delayMs(ms: number): Promise<void> {
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, ms);
+ timer.unref?.();
+ });
+}
export type AgentTUIStreamResult = {
events: AsyncIterable<AgentTUIStreamEvent> | ReadableStream<AgentTUIStreamEvent>;
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
+ * idempotent; scoped to the turn the user observed when its id is known.
+ */
+ cancel?: () => void;
turnState?: AgentTUITurnState;
};
@@ -129,6 +152,7 @@ export type AgentTUIStreamEvent =
| { type: "tool-error"; toolCallId: string; errorText: string }
| { type: "tool-rejected"; toolCallId: string; reason: string }
| { type: "error"; errorText: string; hint?: string; detail?: string }
+ | { type: "turn-cancelled" }
| { type: "finish"; usage?: AgentTUIStreamUsage };
export type AgentTUITurnState = {
@@ -137,6 +161,10 @@ export type AgentTUITurnState = {
pendingApprovals: AgentTUIToolApprovalRequest[];
pendingQuestions: InputRequest[];
sawSessionFailure: boolean;
+ /** Id of the streaming turn, once `turn.started` names it. Scopes cancels. */
+ turnId?: string;
+ /** True while a cooperative-cancel request loop is running for this turn. */
+ cancelInFlight?: boolean;
};
export type AgentTUISessionOptions = {
@@ -229,6 +257,24 @@ export type AgentTUIRenderer = {
renderCommandResult?(text: string): void;
readonly setupFlow?: SetupFlowRenderer;
readPrompt?(options?: AgentTUISessionOptions): Promise<string | undefined>;
+ /**
+ * Consumes the next prompt produced by mid-turn input: the Esc-popped
+ * steering message when one is staged, otherwise every message queued
+ * during the turn coalesced into one. The runner calls this at a clean
+ * turn boundary and submits the result as the next turn without reading
+ * the prompt. Optional — renderers without mid-turn input never queue.
+ */
+ takeQueuedPrompt?(): string | undefined;
+ /**
+ * Reports the server session id backing the conversation — pushed by the
+ * runner once a send is accepted, and overwritten when a later session's
+ * turn is accepted. Deliberately sticky across `/new` and interrupt
+ * recovery: the terminal renderer echoes the LAST session this TUI talked
+ * to in the parting line on exit, so an interrupted conversation (whose
+ * replacement session never ran a turn) can still be found again
+ * (`eve logs`, the session store). Optional.
+ */
+ setSessionId?(sessionId: string): void;
readToolApproval?(
request: AgentTUIToolApprovalRequest,
options?: AgentTUISessionOptions,
@@ -765,6 +811,12 @@ export class EveTUIRunner {
prompt: streamWithoutPrompt ? undefined : prompt,
inputResponses: pendingInputResponses,
});
+ // The session id becomes known once the send is accepted; keep the
+ // renderer's copy fresh so the parting line can name the session.
+ const acceptedSessionId = this.#session.state.sessionId;
+ if (acceptedSessionId !== undefined) {
+ this.#renderer.setSessionId?.(acceptedSessionId);
+ }
let submittedPrompt = prompt;
let respondedToInputRequest = false;
@@ -878,6 +930,19 @@ export class EveTUIRunner {
pendingInputResponses = undefined;
prompt = undefined;
+ // A staged Esc steer message, or messages queued during the turn,
+ // submit immediately as the next turn — but only across a clean turn
+ // boundary. A failed session or a lost stream keeps them; the renderer
+ // restores them into the next prompt's editable buffer instead of
+ // firing them into a session whose state the user hasn't seen.
+ const boundaryEvent = result.turnState?.boundaryEvent;
+ if (
+ !this.#sessionFailed &&
+ (boundaryEvent === "session.waiting" || boundaryEvent === "session.completed")
+ ) {
+ prompt = this.#renderer.takeQueuedPrompt?.();
+ }
+
// The session ended terminally this turn (session.failed, a dispatch
// failure, or a user interrupt). Replace it with a fresh one so the
// next prompt isn't sent into a dead session, but keep the transcript
@@ -1031,6 +1096,49 @@ export class EveTUIRunner {
return this.#createTUIStreamResult(response, () => abortController.abort());
}
+ /**
+ * Requests cooperative cancellation of the streaming turn and retries
+ * while the turn stays live. An Esc that lands in the dispatch window —
+ * after the turn was sent but before the turn workflow claims its cancel
+ * hook (i.e. before `turn.started` reaches the client) — resolves as a
+ * benign `no_active_turn` and would otherwise be silently lost, leaving
+ * the TUI showing "Cancelling…" while the turn runs to completion.
+ * Retrying until the stream reaches its boundary closes that window.
+ *
+ * Once `turn.started` names the turn, each retry carries its id, so a
+ * GUARDED retry that outlives the boundary is a benign no-op. An
+ * UNGUARDED attempt (turnId not yet known) has a residual race: if this
+ * turn's boundary, the queue drain, and the next turn's dispatch all
+ * complete while the request is in flight, the cancel can land on the
+ * next turn. Closing it needs turn-scoped cancel admission server-side
+ * (the #867 ledger); until then the renderer backstops it — a
+ * `turn.cancelled` arriving without an Esc in that stream restores the
+ * submitted message into the prompt instead of losing it.
+ * Single-flight per turn: repeated Esc presses join the running loop.
+ */
+ async #requestTurnCancellation(turnState: AgentTUITurnState): Promise<void> {
+ if (turnState.cancelInFlight === true) return;
+ turnState.cancelInFlight = true;
+ try {
+ for (let attempt = 0; attempt < turnCancelAttempts; attempt += 1) {
+ if (turnState.boundaryEvent !== undefined || turnState.aborted === true) return;
+ const turnId = turnState.turnId;
+ try {
+ const result = await this.#session.cancel(turnId === undefined ? undefined : { turnId });
+ // Accepted means the turn's cancellation hook consumed the
+ // request; the turn settles at its next safe boundary.
+ if (result.status === "accepted") return;
+ } catch {
+ // No accepted session yet or a transport failure — retry below;
+ // Ctrl+C remains the hard client-side interrupt.
+ }
+ await delayMs(turnCancelRetryDelayMs);
+ }
+ } finally {
+ turnState.cancelInFlight = false;
+ }
+ }
+
/**
* Follows the same session after an interactive authorization callback.
* `send()` stops at the parked `session.waiting` boundary; the callback's
@@ -1054,12 +1162,19 @@ export class EveTUIRunner {
turnState.aborted = true;
abort();
},
+ cancel: () => {
+ void this.#requestTurnCancellation(turnState);
+ },
events: eveEventsToTUIStream({
events,
pendingInputRequests: this.#pendingInputRequests,
turnState,
onSubagentCalled: (called) => this.#subagentPump.begin(called),
onSubagentCompleted: (callId) => this.#subagentPump.settle(callId),
+ // A cancelled turn cancels its pending descendants server-side;
+ // settle their sections and stop their child streams so stale
+ // subagent output cannot paint into the next (steered) turn.
+ onTurnCancelled: () => this.#subagentPump.settleAll(),
onConnectionAuthRequired: (event) => this.#handleConnectionAuthRequired(event),
onConnectionAuthCompleted: (event) => this.#handleConnectionAuthCompleted(event),
onTerminalFailure: () => {
@@ -1490,6 +1605,7 @@ type EveStreamTranslatorInput = {
turnState: AgentTUITurnState;
onSubagentCalled?: (event: SubagentCalledStreamEvent) => void;
onSubagentCompleted?: (callId: string) => void;
+ onTurnCancelled?: () => void;
onConnectionAuthRequired?: (event: AuthorizationRequiredStreamEvent) => void;
onConnectionAuthCompleted?: (event: AuthorizationCompletedStreamEvent) => void;
onTerminalFailure?: (event: SessionFailedStreamEvent) => void;
@@ -1515,6 +1631,7 @@ async function* eveEventsToTUIStream(
turnState,
onSubagentCalled,
onSubagentCompleted,
+ onTurnCancelled,
onConnectionAuthRequired,
onConnectionAuthCompleted,
onTerminalFailure,
@@ -1545,11 +1662,17 @@ async function* eveEventsToTUIStream(
switch (event.type) {
case "session.started":
- case "turn.started":
case "message.received":
// Boundary / metadata events with no direct UI surface.
break;
+ case "turn.started":
+ // Recorded so Esc-driven cancellation can scope its request to the
+ // turn the user is watching; a cancel that arrives after the
+ // boundary then no-ops instead of hitting the next turn.
+ turnState.turnId = event.data.turnId;
+ break;
+
case "step.started":
stepEpoch += 1;
yield { type: "step-start" };
@@ -1831,6 +1954,15 @@ async function* eveEventsToTUIStream(
yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
break;
+ case "turn.cancelled":
+ // A cooperative cancel (Esc Esc or an Esc steer) — not a failure.
+ // `session.waiting` follows and finishes the stream normally.
+ onTurnCancelled?.();
+ yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
+ yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
+ yield { type: "turn-cancelled" };
+ break;
+
case "subagent.called": {
// Run creation (idempotent for SSE-resume re-entries) lives in the
// pump's begin().
diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts
new file mode 100644
index 000000000..d425c5089
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { Client, type HandleMessageStreamEvent } from "#client/index.js";
+import type { SubagentCalledStreamEvent } from "#protocol/message.js";
+
+import { SubagentPump, type SubagentView } from "./subagent-pump.js";
+
+function fakeView(): SubagentView {
+ return {
+ begin: vi.fn(),
+ upsertStep: vi.fn(),
+ upsertTool: vi.fn(),
+ removeTool: vi.fn(),
+ complete: vi.fn(),
+ markChildToolCallId: vi.fn(),
+ };
+}
+
+/**
+ * A hand-pumped child event stream: events pushed after `settleAll` aborts
+ * the pump must never reach the view.
+ */
+function pushableChildStream() {
+ const queue: HandleMessageStreamEvent[] = [];
+ let wake: (() => void) | undefined;
+ let aborted = false;
+
+ return {
+ push(event: HandleMessageStreamEvent) {
+ queue.push(event);
+ wake?.();
+ wake = undefined;
+ },
+ stream(options?: { signal?: AbortSignal }): AsyncIterable<HandleMessageStreamEvent> {
+ const signal = options?.signal;
+ return {
+ async *[Symbol.asyncIterator]() {
+ while (true) {
+ if (signal?.aborted) {
+ aborted = true;
+ return;
+ }
+ const next = queue.shift();
+ if (next !== undefined) {
+ yield next;
+ continue;
+ }
+ await new Promise<void>((resolve) => {
+ wake = resolve;
+ signal?.addEventListener("abort", () => resolve(), { once: true });
+ });
+ }
+ },
+ };
+ },
+ get aborted() {
+ return aborted;
+ },
+ };
+}
+
+function subagentCalled(callId: string): SubagentCalledStreamEvent {
+ return {
+ type: "subagent.called",
+ data: {
+ callId,
+ childSessionId: `child_${callId}`,
+ name: "researcher",
+ sequence: 1,
+ turnId: "turn-1",
+ },
+ } as SubagentCalledStreamEvent;
+}
+
+function reasoningEvent(delta: string): HandleMessageStreamEvent {
+ return {
+ type: "reasoning.appended",
+ data: {
+ reasoningDelta: delta,
+ reasoningSoFar: delta,
+ sequence: 2,
+ stepIndex: 0,
+ turnId: "child-turn",
+ },
+ } as HandleMessageStreamEvent;
+}
+
+async function settleAsyncWork(): Promise<void> {
+ for (let i = 0; i < 8; i += 1) await Promise.resolve();
+}
+
+describe("SubagentPump.settleAll", () => {
+ it("closes live sections and stops stale child output after a cancelled turn", async () => {
+ const child = pushableChildStream();
+ const client = new Client({ host: "http://localhost:3000" });
+ vi.spyOn(client, "session").mockReturnValue({
+ stream: (options?: { signal?: AbortSignal }) => child.stream(options),
+ } as never);
+ const view = fakeView();
+ const pump = new SubagentPump({ client, view, formatActionResultError: () => "failed" });
+
+ pump.begin(subagentCalled("call-1"));
+ child.push(reasoningEvent("**Searching for current events**"));
+ await settleAsyncWork();
+ expect(view.upsertStep).toHaveBeenCalledWith(
+ expect.objectContaining({ callId: "call-1", finalized: false }),
+ );
+
+ // The parent turn is cancelled: sections settle and the stream stops.
+ pump.settleAll();
+ expect(view.complete).toHaveBeenCalledWith({ callId: "call-1" });
+ expect(view.upsertStep).toHaveBeenCalledWith(
+ expect.objectContaining({ callId: "call-1", finalized: true }),
+ );
+
+ // A child still flushing output after the cancel paints nothing.
+ const updatesAfterSettle = vi.mocked(view.upsertStep).mock.calls.length;
+ child.push(reasoningEvent("stale output"));
+ await settleAsyncWork();
+ expect(vi.mocked(view.upsertStep).mock.calls.length).toBe(updatesAfterSettle);
+
+ // The parent's late `subagent.completed` fallback settles as a no-op.
+ const completions = vi.mocked(view.complete).mock.calls.length;
+ pump.settle("call-1");
+ expect(vi.mocked(view.complete).mock.calls.length).toBe(completions);
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.ts
index be56e1967..9fa8d4205 100644
--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts
+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts
@@ -178,6 +178,24 @@ export class SubagentPump {
this.#runs.clear();
}
+ /**
+ * 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.
+ */
+ settleAll(): void {
+ for (const callId of this.#runs.keys()) {
+ this.#finalizeRun(callId);
+ }
+ for (const controller of this.#pumps.values()) {
+ controller.abort();
+ }
+ this.#pumps.clear();
+ }
+
/**
* Opens a parallel stream over the child session and folds its events into
* nested subagent blocks.
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
index afe52441f..3ee0071da 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -168,6 +168,30 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(idle.screen.snapshot()).not.toContain("☰eve");
});
+ it("names the session in the parting line once the runner reports it", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ renderer.setSessionId("ses_0123456789");
+ const prompt = renderer.readPrompt();
+ input.ctrlC();
+ await expect(prompt).rejects.toThrow("Interrupted");
+ renderer.shutdown();
+
+ const lines = screen.snapshot().trimEnd().split("\n");
+ expect(lines.at(-1)).toMatch(/^☰eve {2}v\d+\.\d+\.\d+ · session ses_0123456789$/u);
+
+ // Repeated reports keep the latest id; a renderer that never received
+ // one prints the bare tag.
+ const latest = makeRenderer();
+ latest.renderer.setSessionId("ses_first");
+ latest.renderer.setSessionId("ses_second");
+ const latestPrompt = latest.renderer.readPrompt();
+ latest.input.ctrlC();
+ await expect(latestPrompt).rejects.toThrow("Interrupted");
+ latest.renderer.shutdown();
+ expect(latest.screen.snapshot()).toContain("session ses_second");
+ expect(latest.screen.snapshot()).not.toContain("ses_first");
+ });
+
it("renders the brand line with the agent name and a tip", () => {
const { screen, renderer } = makeRenderer();
renderer.renderAgentHeader({
@@ -1652,7 +1676,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
}
});
- it("keeps the prompt in place during a turn with Enter inert, carrying the draft", async () => {
+ it("queues a mid-turn Enter into the pinned panel and drains it as the next prompt", async () => {
const { screen, input, renderer } = makeRenderer();
let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
const rendering = renderer.renderStream(
@@ -1672,20 +1696,344 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(screen.snapshot()).toContain("›");
});
input.type("follow-up question");
- // Enter is inert mid-turn — nothing submits, the draft stays.
+ // Enter mid-turn queues the draft into the panel and clears the buffer.
input.enter();
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("❯ follow-up question");
+ expect(screen.snapshot()).toContain("Queue 1/5");
+ expect(screen.snapshot()).toContain("└ follow-up question");
+ });
+
+ streamController?.close();
+ await rendering;
+
+ // The runner drains the queue as the next turn's prompt.
+ expect(renderer.takeQueuedPrompt()).toBe("follow-up question");
+ expect(renderer.takeQueuedPrompt()).toBeUndefined();
+ 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 () => {
+ input.send("\x1b");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ };
+ 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("go north");
+ input.enter();
+ input.type("go south");
+ input.enter();
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("Queue 2/5");
+ });
+
+ await escape();
+ expect(cancel).toHaveBeenCalledTimes(1);
+ expect(screen.snapshot()).toContain("Steering — cancelling the running turn…");
+ expect(screen.snapshot()).toContain("1/5 still queued");
+
+ // The server settles the cancelled turn and the stream reaches its boundary.
+ streamController?.enqueue({ type: "turn-cancelled" });
+ streamController?.close();
+ await rendering;
+ expect(screen.snapshot()).toContain("Cancelled");
+
+ // The popped message steers; the remaining one stays queued behind it.
+ expect(renderer.takeQueuedPrompt()).toBe("go north");
+ expect(renderer.takeQueuedPrompt()).toBe("go south");
+ renderer.shutdown();
+ });
+
+ it("arms on the first empty-queue Esc and cancels the turn on the second", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const escape = async () => {
+ input.send("\x1b");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ };
+ 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("›");
});
+ 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…");
+
+ streamController?.enqueue({ type: "turn-cancelled" });
streamController?.close();
await rendering;
+ expect(screen.snapshot()).toContain("Cancelled");
+ renderer.shutdown();
+ });
- // The draft seeds the next prompt instead of being lost.
+ it("restores the submitted message when the turn is cancelled without an Esc", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "go north", continueSession: true },
+ );
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("│ go north");
+ });
+
+ // A stale cancel from a previous turn (or /cancel from another client)
+ // lands on this turn — no Esc was pressed in this stream.
+ streamController?.enqueue({ type: "turn-cancelled" });
+ streamController?.close();
+ await rendering;
+
+ expect(screen.snapshot()).toContain("cancelled from outside this prompt");
const prompt = renderer.readPrompt();
- expect(screen.snapshot()).toContain("❯ follow-up question");
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("❯ go north");
+ });
+ input.enter();
+ expect(await prompt).toBe("go north");
+ renderer.shutdown();
+ });
+
+ it("does not restore the message when the user's own Esc cancelled the turn", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const escape = async () => {
+ input.send("\x1b");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ };
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ cancel: vi.fn(),
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "go north", continueSession: true },
+ );
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("│ go north");
+ });
+
+ await escape();
+ await escape();
+ streamController?.enqueue({ type: "turn-cancelled" });
+ streamController?.close();
+ await rendering;
+
+ expect(screen.snapshot()).not.toContain("cancelled from outside this prompt");
+ renderer.shutdown();
+ });
+
+ it("marks drained prompts with the provenance arrow — above for steer, below for queue", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const escape = async () => {
+ input.send("\x1b");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ };
+ const closedStream = () =>
+ new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ controller.close();
+ },
+ });
+
+ // Steer: queue a message mid-turn and pop it with Esc.
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const first = renderer.renderStream(
+ {
+ cancel: vi.fn(),
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "long task", continueSession: true },
+ );
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("›");
+ });
+ input.type("go north");
+ input.enter();
+ await escape();
+ streamController?.enqueue({ type: "turn-cancelled" });
+ streamController?.close();
+ await first;
+
+ const steered = renderer.takeQueuedPrompt();
+ expect(steered).toBe("go north");
+ await renderer.renderStream(
+ { events: closedStream() },
+ { submittedPrompt: steered, continueSession: true },
+ );
+ let lines = screen.snapshot().split("\n");
+ const steerIndex = lines.findIndex((line) => line.includes("│ go north"));
+ expect(lines[steerIndex - 1]?.trim()).toBe("↑");
+
+ // Queue: a message that waited for the natural boundary.
+ let secondController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const second = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ secondController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "another task", continueSession: true },
+ );
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("Working for");
+ });
+ input.type("go south");
+ input.enter();
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("Queue 1/5");
+ });
+ secondController?.close();
+ await second;
+
+ const queued = renderer.takeQueuedPrompt();
+ expect(queued).toBe("go south");
+ await renderer.renderStream(
+ { events: closedStream() },
+ { submittedPrompt: queued, continueSession: true },
+ );
+ lines = screen.snapshot().split("\n");
+ const queueIndex = lines.findIndex((line) => line.includes("│ go south"));
+ expect(lines[queueIndex + 1]?.trim()).toBe("↑");
+
+ // The ordinary typed prompts carry no arrow.
+ const typedIndex = lines.findIndex((line) => line.includes("│ long task"));
+ expect(lines[typedIndex - 1]?.trim()).not.toBe("↑");
+ expect(lines[typedIndex + 1]?.trim()).not.toBe("↑");
+ renderer.shutdown();
+ });
+
+ it("keeps the draft in place when the queue is full", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "long task", continueSession: true },
+ );
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("›");
+ });
+
+ for (let index = 1; index <= 5; index += 1) {
+ input.type(`message ${index}`);
+ input.enter();
+ }
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("Queue 5/5");
+ expect(screen.snapshot()).toContain("queue full");
+ });
+
+ input.type("overflow");
+ input.enter();
+ // The sixth message is refused, not swallowed — it stays as the draft.
+ expect(screen.snapshot()).toContain("overflow");
+
+ streamController?.close();
+ await rendering;
+ expect(renderer.takeQueuedPrompt()).toBe(
+ "message 1\n\nmessage 2\n\nmessage 3\n\nmessage 4\n\nmessage 5",
+ );
+ renderer.shutdown();
+ });
+
+ it("restores undrained queued messages into the next prompt's buffer", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const abort = vi.fn();
+ const rendering = renderer.renderStream(
+ {
+ abort,
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "long task", continueSession: true },
+ );
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("›");
+ });
+ input.type("first");
+ input.enter();
+ input.type("second");
+ input.enter();
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("Queue 2/5");
+ });
+
+ // A client-side interrupt skips the runner's queue drain…
+ input.ctrlC();
+ await rendering;
+ expect(abort).toHaveBeenCalledTimes(1);
+ void streamController;
+
+ // …so the prompt folds the undelivered messages back into the buffer.
+ const prompt = renderer.readPrompt();
+ await vi.waitFor(() => {
+ expect(screen.snapshot()).toContain("first");
+ expect(screen.snapshot()).toContain("second");
+ });
input.enter();
- expect(await prompt).toBe("follow-up question");
+ expect(await prompt).toBe("first\n\nsecond");
renderer.shutdown();
});
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index 06ee5d74d..d8d5c1804 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -144,6 +144,7 @@ import {
renderTodoPanelRows,
type TodoPanelItem,
} from "./todo-panel.js";
+import { MessageQueue, renderMessageQueueRows } from "./message-queue.js";
import { formatStoredDiagnostic, presentDiagnostic } from "./diagnostic-presentation.js";
import { reduceSetupSelectInput, setupSelectionIntent } from "./setup-selection-input.js";
import {
@@ -208,9 +209,14 @@ function moveActionCursor(
return (cursor + delta + actionCount) % actionCount;
}
-function completedTurnStatus(interrupted: boolean, continueSession: boolean): string {
- if (interrupted) return "Interrupted";
- if (continueSession) return "Ready";
+function completedTurnStatus(input: {
+ interrupted: boolean;
+ cancelled: boolean;
+ continueSession: boolean;
+}): string {
+ if (input.interrupted) return "Interrupted";
+ if (input.cancelled) return "Cancelled";
+ if (input.continueSession) return "Ready";
return "Done";
}
@@ -511,6 +517,29 @@ export class TerminalRenderer implements AgentTUIRenderer {
* so committing must be idempotent per list content.
*/
#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.
+ */
+ readonly #messageQueue = new MessageQueue();
+ /** The streaming result's cooperative cancel, armed for Esc while it renders. */
+ #requestTurnCancel?: () => void;
+ /** Set by the `turn-cancelled` stream event: settle in-flight tool blocks. */
+ #turnCancelled = false;
+ /** Server session id backing the conversation; named in the parting line. */
+ #sessionId?: string;
+ /**
+ * Provenance of the next runner-submitted prompt, remembered between
+ * {@link takeQueuedPrompt} and the echo in {@link #addSubmittedPrompt} so
+ * 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). */
+ #cancelRequestedByUser = false;
+ /** The prompt submitted for the streaming turn, for external-cancel recovery. */
+ #currentSubmittedPrompt?: string;
/** Armed by {@link SetupFlowRenderer.waitForInterrupt}; fired by the idle key trap. */
#flowInterrupt?: () => void;
/** The installed working-state key consumer, so re-arming and disposal can recognize it. */
@@ -594,10 +623,25 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#turnIndicator = { kind: "idle" };
this.#status = "";
// A draft typed during the turn carries into the prompt; an explicit
- // initial draft (`eve dev --input`) wins over it.
- let editor: LineState = lineOf(
- stripPromptControlCharacters(options?.initialDraft ?? this.#streamDraft.text),
+ // initial draft (`eve dev --input`) wins over it. Queued messages the
+ // runner never drained (an interrupted or failed turn) fold back in
+ // ahead of the draft instead of vanishing — sanitized per line so the
+ // blank-line seams between restored messages survive.
+ const undelivered = this.#messageQueue
+ .restoreDraft()
+ ?.split("\n")
+ .map(stripPromptControlCharacters)
+ .join("\n");
+ const carriedDraft = stripPromptControlCharacters(
+ options?.initialDraft ?? this.#streamDraft.text,
);
+ const seededDraft =
+ undelivered === undefined
+ ? carriedDraft
+ : carriedDraft.length === 0
+ ? undelivered
+ : `${undelivered}\n\n${carriedDraft}`;
+ let editor: LineState = lineOf(seededDraft);
this.#streamDraft = EMPTY_LINE;
this.#promptHistory.begin(editor.text);
this.#syncInput(editor);
@@ -756,6 +800,21 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#inputCursor = state.cursor;
}
+ /**
+ * Consumes the next prompt produced by mid-turn input — the staged Esc
+ * steer message, or the whole queue coalesced into one. The runner calls
+ * this at a clean turn boundary and submits the result directly; the
+ * remembered origin marks the echoed user block with its gutter arrow.
+ */
+ takeQueuedPrompt(): string | undefined {
+ const steering = this.#messageQueue.view().steering;
+ const prompt = this.#messageQueue.takePrompt();
+ if (prompt !== undefined) {
+ this.#nextSubmittedPromptOrigin = steering ? "steer" : "queue";
+ }
+ return prompt;
+ }
+
async renderStream(
result: AgentTUIStreamResult,
options?: AgentTUISessionOptions,
@@ -778,6 +837,11 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#turnClock.arm();
}
this.#interrupted = false;
+ this.#turnCancelled = false;
+ this.#cancelRequestedByUser = false;
+ this.#currentSubmittedPrompt = options?.submittedPrompt;
+ this.#messageQueue.beginTurn();
+ this.#requestTurnCancel = result.cancel;
this.#totalTokens = undefined;
this.#promptTokens = undefined;
this.#assistantOutputTokens = undefined;
@@ -824,20 +888,25 @@ export class TerminalRenderer implements AgentTUIRenderer {
} finally {
this.#resolveStreamInterrupt = undefined;
if (this.#interrupted) result.abort?.();
+ this.#requestTurnCancel = undefined;
this.#detachInput();
this.#stopTicker();
this.#streamDraftActive = false;
if (this.#turnIndicator.kind === "waiting") {
this.#turnIndicator = { kind: "idle" };
}
- this.#status = completedTurnStatus(this.#interrupted, options?.continueSession === true);
+ this.#status = completedTurnStatus({
+ interrupted: this.#interrupted,
+ cancelled: this.#turnCancelled,
+ continueSession: options?.continueSession === true,
+ });
// Placeholders whose call never materialized (interrupted mid-input)
// must vanish rather than commit.
this.#sweepPreparingToolBlocks(turnState);
- // An interrupted turn gets no terminal updates for its in-flight
- // calls; a block left `running` would keep the settled prefix wedged
- // and freeze scrollback for the rest of the session.
- if (this.#interrupted) this.#settleInterruptedToolBlocks();
+ // An interrupted or cancelled turn gets no terminal updates for its
+ // in-flight calls; a block left `running` would keep the settled
+ // prefix wedged and freeze scrollback for the rest of the session.
+ if (this.#interrupted || this.#turnCancelled) this.#settleInterruptedToolBlocks();
this.#finalizeAllBlocks();
this.#diagnostics?.reportStats();
this.#paint();
@@ -1461,6 +1530,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#subagentCallsByName.clear();
this.#todoItems = undefined;
this.#todoCommittedSignature = undefined;
+ this.#messageQueue.reset();
+ this.#nextSubmittedPromptOrigin = undefined;
this.#fileContents.clear();
this.#turnClock.reset();
}
@@ -2468,16 +2539,24 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
}
+ /** Last server session id the runner reported; named in the parting line. */
+ setSessionId(sessionId: string): void {
+ this.#sessionId = sessionId;
+ }
+
shutdown(): void {
this.#stop();
// The parting line: the boot banner's dim counterpart, written after the
// terminal is restored so it lands as the session's last scrollback row.
// Gated on the session having ever gone live (Ctrl-C stops the terminal
// inside the reader long before the runner's teardown reaches here) and
- // printed at most once.
+ // printed at most once. Carries the session id so the conversation the
+ // user just left can be found again.
if (this.#everInteractive && !this.#partingLinePrinted) {
this.#partingLinePrinted = true;
- this.#output.write(`${this.#theme.colors.dim(eveVersionTag())}\n`);
+ const session =
+ this.#sessionId === undefined ? "" : ` ${this.#theme.glyph.dot} session ${this.#sessionId}`;
+ this.#output.write(`${this.#theme.colors.dim(`${eveVersionTag()}${session}`)}\n`);
}
}
@@ -2671,11 +2750,35 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
}
break;
- case "enter":
- // Inert while the turn streams — no mid-turn submits yet. The draft
- // carries into the next prompt instead.
+ case "enter": {
+ // 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;
+ }
+ this.#paint();
+ break;
+ }
+ 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.
+ if (this.#messageQueue.idle && this.#requestTurnCancel === undefined) break;
+ const outcome = this.#messageQueue.handleEscape();
+ if (outcome === "steer" || outcome === "cancel") {
+ 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;
@@ -2786,11 +2889,15 @@ export class TerminalRenderer implements AgentTUIRenderer {
#addSubmittedPrompt(prompt: string | undefined) {
if (prompt == null) return;
+ const origin = this.#nextSubmittedPromptOrigin;
+ this.#nextSubmittedPromptOrigin = undefined;
if (this.#pendingEchoedPrompt === prompt) {
this.#pendingEchoedPrompt = undefined;
return;
}
- this.#pushBlock({ kind: "user", body: stripTerminalControls(prompt), live: false });
+ const block: Block = { kind: "user", body: stripTerminalControls(prompt), live: false };
+ if (origin !== undefined) block.promptOrigin = origin;
+ this.#pushBlock(block);
}
#addErrorBlock(
@@ -3043,6 +3150,27 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#addErrorBlock("Error", event.errorText, { detail: event.detail, hint: event.hint });
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.
+ this.#turnCancelled = true;
+ // A cancellation nobody asked for through THIS prompt — a stale
+ // cancel from the previous turn landing late (the unguarded
+ // dispatch-window race), or `/cancel` from another client — must
+ // not eat the submitted message: hand it back as the next draft.
+ if (
+ !this.#cancelRequestedByUser &&
+ this.#currentSubmittedPrompt !== undefined &&
+ this.#streamDraft.text.length === 0
+ ) {
+ this.#streamDraft = lineOf(this.#currentSubmittedPrompt);
+ this.renderNotice(
+ "The turn was cancelled from outside this prompt — the message was restored to the input.",
+ );
+ }
+ break;
+
case "finish":
this.#applyUsage(event.usage);
this.#paint();
@@ -3543,6 +3671,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
return rows;
}
+ // The setup attention line rides above the pinned panels as a live
+ // element, so resolving its issue clears it instead of leaving it stale
+ // in scrollback.
+ if (this.#setupAttention !== undefined) {
+ rows.push(...renderAttentionRows(this.#setupAttention, width, this.#theme), "");
+ }
+
// The pinned todo panel holds its place above the prompt, updated in
// place by each `todo` tool call rather than scrolling with the stream.
if (this.#todoItems !== undefined) {
@@ -3561,11 +3696,16 @@ export class TerminalRenderer implements AgentTUIRenderer {
);
}
- // The setup attention line rides just above the prompt as a live element,
- // so resolving its issue clears it instead of leaving it stale in scrollback.
- if (this.#setupAttention !== undefined) {
- rows.push(...renderAttentionRows(this.#setupAttention, width, this.#theme), "");
- }
+ // The message-queue panel takes the slot directly above the input —
+ // ahead of the todo panel — because it holds the user's own undelivered
+ // words and carries the Esc steering/cancel affordance.
+ const queueRows = renderMessageQueueRows({
+ view: this.#messageQueue.view(),
+ width,
+ theme: this.#theme,
+ working: this.#streamDraftActive,
+ });
+ if (queueRows.length > 0) rows.push(...queueRows, "");
if (this.#inputActive) {
// A complete command name with a single match collapses the dropdown into
diff --git a/packages/eve/test/tui-client/tui-queue-steer.ts b/packages/eve/test/tui-client/tui-queue-steer.ts
new file mode 100644
index 000000000..3a745ee20
--- /dev/null
+++ b/packages/eve/test/tui-client/tui-queue-steer.ts
@@ -0,0 +1,122 @@
+import { Buffer } from "node:buffer";
+import { setTimeout as sleep } from "node:timers/promises";
+
+import { Client } from "eve/client";
+import { EveTUIRunner, MockScreen, MockUserInput } from "./lib/tui.ts";
+
+import { run } from "./lib/run.ts";
+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:
+ *
+ * 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.
+ * 2. Esc pops the oldest queued message: the panel flips to Steering,
+ * the running turn settles as `turn.cancelled` → `session.waiting`
+ * (cooperative — the session keeps its context), and the popped
+ * message runs as the replacement turn.
+ * 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.
+ *
+ * The tokens prove delivery order end-to-end: each must appear twice
+ * (the echoed user block and the model's reply).
+ */
+
+const STEER_TOKEN = "STEER-MARKER-B7Q";
+const QUEUE_TOKEN = "QUEUE-MARKER-K4Z";
+process.env.EVE_TUI_UNICODE = "1";
+
+run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
+ const client = new Client({ host: target.baseUrl });
+ const session = client.session();
+ const screen = new MockScreen({ columns: 110, rows: 44 });
+ const input = new MockUserInput();
+ const runner = new EveTUIRunner({
+ session,
+ client,
+ screen,
+ userInput: input,
+ name: "TUI queue/steer smoke",
+ });
+
+ const runPromise = runner.run().catch((error: unknown) => {
+ if (error instanceof Error && error.message === "Interrupted") {
+ return;
+ }
+ throw error;
+ });
+
+ await screen.waitForIdlePrompt(5_000);
+
+ // A long first turn holds the stream open while messages queue behind it.
+ input.type("Write a short story of about 150 words about tides. Do not use any tools.");
+ input.enter();
+ await screen.waitForText("Working for", 30_000);
+
+ input.type(`Reply with one short sentence containing the token ${STEER_TOKEN}.`);
+ input.enter();
+ await screen.waitForText("Queue 1/5", 10_000);
+ input.type(`Reply with one short sentence containing the token ${QUEUE_TOKEN}.`);
+ input.enter();
+ await screen.waitForText("Queue 2/5", 10_000);
+ console.log(theme.muted("[tui-queue-steer] two messages queued behind the running turn"));
+
+ // Esc pops the oldest message and cooperatively cancels the running turn.
+ input.emit("data", Buffer.from("\x1b"));
+ await sleep(60); // the decoder holds a lone ESC briefly (escape-vs-sequence)
+ await screen.waitForText("Steering", 10_000);
+ console.log(theme.muted("[tui-queue-steer] steering engaged, cancelling the turn"));
+
+ await waitForTwice(screen, STEER_TOKEN, 120_000, "steered turn echo + reply");
+ console.log(theme.muted("[tui-queue-steer] steered message answered"));
+
+ await waitForTwice(screen, QUEUE_TOKEN, 120_000, "auto-drained turn echo + reply");
+ console.log(theme.muted("[tui-queue-steer] remaining queue auto-drained"));
+
+ await screen.waitForIdlePrompt(60_000);
+
+ // Provenance arrows: steered above its bar, queued below.
+ const lines = screen.snapshot().split("\n");
+ const steerEcho = lines.findIndex((line) =>
+ line.includes(`│ Reply with one short sentence containing the token ${STEER_TOKEN}`),
+ );
+ if (steerEcho <= 0 || lines[steerEcho - 1]?.trim() !== "↑") {
+ throw new Error(
+ `Steered echo is missing its ↑ marker above the bar:\n${lines
+ .slice(Math.max(0, steerEcho - 2), steerEcho + 1)
+ .join("\n")}`,
+ );
+ }
+ const queueEcho = lines.findIndex((line) =>
+ line.includes(`│ Reply with one short sentence containing the token ${QUEUE_TOKEN}`),
+ );
+ if (queueEcho < 0 || lines[queueEcho + 1]?.trim() !== "↑") {
+ throw new Error(
+ `Queued echo is missing its ↑ marker below the bar:\n${lines
+ .slice(queueEcho, queueEcho + 3)
+ .join("\n")}`,
+ );
+ }
+ console.log(theme.muted("[tui-queue-steer] provenance arrows rendered"));
+
+ input.ctrlC();
+ await runPromise;
+});
+
+/** Waits until `token` appears at least twice: the echoed prompt and the reply. */
+async function waitForTwice(
+ screen: MockScreen,
+ token: string,
+ timeoutMs: number,
+ label: string,
+): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (screen.snapshot().split(token).length > 2) return;
+ await sleep(100);
+ }
+ throw new Error(`Timed out waiting for: ${label}\n${screen.snapshot()}`);
+}