Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

feat(coding-agent): edit queued messages in place and preserve the queue on interrupt (#838)

Sebastian Müller71ca6cfd1a2f
diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md
index 565e7f742e..4a07d4de1f 100644
--- a/packages/coding-agent/README.md
+++ b/packages/coding-agent/README.md
@@ -192,9 +192,11 @@ Submit messages while the agent is working:
- **Enter** queues a *steering* message, delivered after the current assistant turn finishes executing its tool calls
- **Alt+Enter** queues a *follow-up* message, delivered only after the agent finishes all work
-- **Ctrl+C** interrupts active work and restores queued messages to the editor
+- **Ctrl+C** interrupts active work; queued messages are kept and resume after your next submit or edit
- **Escape** clears the input without interrupting active work
-- **Alt+Up** retrieves queued messages back to editor
+- **Alt+Up / Alt+Down** browse queued messages individually and return to the editor draft
+- While browsing, **Enter** applies the edit as steering input and **Alt+Enter** applies it as a follow-up; submitting an empty edit deletes the item
+- **Ctrl+Alt+Up / Ctrl+Alt+Down** move the selected item earlier or later within its queue
On Windows Terminal, `Alt+Enter` is fullscreen by default. Remap it in [docs/terminal-setup.md](docs/terminal-setup.md) so Prime Agent can receive the follow-up shortcut.
diff --git a/packages/coding-agent/docs/keybindings.md b/packages/coding-agent/docs/keybindings.md
index 1db87a4cd5..a2a492f7d2 100644
--- a/packages/coding-agent/docs/keybindings.md
+++ b/packages/coding-agent/docs/keybindings.md
@@ -132,7 +132,10 @@ Use `tab` to cycle forward and `shift+tab` to cycle backward through Providers,
| `app.tools.expand` | `ctrl+o` | Collapse or expand tool output |
| `app.messages.expand` | `ctrl+p` | Collapse or expand agent-to-agent messages |
| `app.message.followUp` | `alt+enter` | Queue follow-up message |
-| `app.message.dequeue` | `alt+up` | Restore queued messages to editor |
+| `app.message.navigateOlder` | `alt+up` | Select the next older pending message |
+| `app.message.navigateNewer` | `alt+down` | Select the next newer pending message or restore the draft |
+| `app.message.moveEarlier` | `ctrl+alt+up` | Move the selected pending message one place earlier in its queue |
+| `app.message.moveLater` | `ctrl+alt+down` | Move the selected pending message one place later in its queue |
### Tree Navigation
diff --git a/packages/coding-agent/docs/terminal-setup.md b/packages/coding-agent/docs/terminal-setup.md
index 8f823d3c54..964670e77c 100644
--- a/packages/coding-agent/docs/terminal-setup.md
+++ b/packages/coding-agent/docs/terminal-setup.md
@@ -104,3 +104,7 @@ The built-in terminal has limited escape sequence support. Shift+Enter cannot be
If you want the hardware cursor visible, set `PI_HARDWARE_CURSOR=1` before running `prime-agent` (disabled by default for compatibility).
Consider using a dedicated terminal emulator for the best experience.
+
+### macOS Control+Option+Arrow shortcuts
+
+Pending-message reordering defaults to `Control+Option+Up` and `Control+Option+Down`. Prime Agent accepts modern modified-arrow sequences and legacy Option-as-Meta wrapped Control+Arrow sequences. macOS VoiceOver uses Control+Option as its modifier, and system or terminal shortcuts can intercept these chords before they reach Prime Agent. If that happens, remap `app.message.moveEarlier` and `app.message.moveLater` in `~/.prime/agent/keybindings.json`.
diff --git a/packages/coding-agent/docs/usage.md b/packages/coding-agent/docs/usage.md
index 1f92916804..196ac8b9e5 100644
--- a/packages/coding-agent/docs/usage.md
+++ b/packages/coding-agent/docs/usage.md
@@ -68,9 +68,11 @@ You can submit messages while the agent is still working:
- **Enter** queues a steering message, delivered after the current assistant turn finishes executing its tool calls.
- **Alt+Enter** queues a follow-up message, delivered after the agent finishes all work.
-- **Ctrl+C** interrupts the current operation and briefly shows the exit hint; press it again while the hint is visible to exit.
+- **Ctrl+C** interrupts the current operation and briefly shows the exit hint; press it again while the hint is visible to exit. Queued messages are kept and resume after your next submit or edit.
- **Escape** clears the input bar without interrupting the agent.
-- **Alt+Up** retrieves queued messages back to the editor.
+- **Alt+Up / Alt+Down** browse queued messages one at a time and return to the untouched draft.
+- While browsing, **Enter** applies the edit as steering input and **Alt+Enter** applies it as a follow-up; submitting an empty edit deletes the item.
+- **Ctrl+Option+Up / Ctrl+Option+Down** move the selected item earlier or later within its queue.
On Windows Terminal, Alt+Enter is fullscreen by default. Remap it as described in [Terminal setup](terminal-setup.md) if you want Prime Agent to receive the shortcut.
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index e99462eabb..46d2bd4f8a 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -238,6 +238,10 @@ import {
canSelectSessionAction,
type DeliveryPolicy,
type DeliveryRecord,
+ type QueuedMessageLane,
+ type QueuedMessageMutation,
+ type QueuedMessageMutationStatus,
+ queuedMessageLaneDeliveryPolicy,
type RuntimeActivity,
type SessionAction,
type SessionActionSnapshot,
@@ -6103,6 +6107,78 @@ export class AgentSession {
return { steering: removedSteering, followUp: removedFollowUp };
}
+ /**
+ * Mutate a single visible queued message, addressed by its position in the same
+ * projection the session-action snapshot publishes. expectedText must match the
+ * item's current preview so clients never edit a shifted queue by accident.
+ */
+ mutateQueuedMessage(
+ lane: QueuedMessageLane,
+ index: number,
+ expectedText: string,
+ mutation: QueuedMessageMutation,
+ ): QueuedMessageMutationStatus {
+ const policy = queuedMessageLaneDeliveryPolicy(lane);
+ const projection = visibleSessionActionProjection(this._actionStore.queuedActions(policy));
+ const item = projection[index];
+ if (!item || queuedAgentMessagePreview(item) !== expectedText) return "rejected";
+ if (mutation.type === "delete") {
+ const error = new Error("Queued prompt was deleted before delivery.");
+ this._rejectAgentMessage(item.agentMessageId, error);
+ this._cancelSessionActions((candidate) => candidate === item, error);
+ this._emitQueueUpdate();
+ this.resumeQueuedWork();
+ return "applied";
+ }
+ if (mutation.type === "move") {
+ const neighbor = projection[index + mutation.direction];
+ if (!neighbor) return "rejected";
+ this._actionStore.swapQueued(item, neighbor);
+ this._emitQueueUpdate();
+ return "applied";
+ }
+ if (
+ item.payload.kind === "turn" &&
+ (item.payload.acceptedAgentMessage ||
+ item.payload.records.some((record) => record.role === "primary" && record.message.role !== "user"))
+ ) {
+ return "rejected";
+ }
+ const images = mutation.images?.map((image) => ({ ...image }));
+ if (item.payload.kind === "session_command") {
+ const command = parseSessionSlashCommand(mutation.text);
+ if (!command) return "invalid";
+ item.payload.text = mutation.text;
+ item.payload.command = command;
+ if (mutation.images !== undefined) item.payload.images = images?.length ? images : undefined;
+ } else {
+ item.payload.text = mutation.text;
+ const text = { type: "text" as const, text: mutation.text };
+ if (mutation.images !== undefined) {
+ item.payload.images = images?.length ? images : undefined;
+ item.payload.content = [text, ...(images?.map((image) => ({ ...image })) ?? [])];
+ } else if (item.payload.content) {
+ item.payload.content = [text, ...item.payload.content.filter((block) => block.type !== "text")];
+ }
+ item.payload.preview = undefined;
+ item.payload.prepared = undefined;
+ for (const record of item.payload.records) {
+ if (record.role === "primary" && record.message.role === "user") {
+ record.message.content = item.payload.content?.map((block) => ({ ...block })) ?? mutation.text;
+ }
+ }
+ }
+ const targetPolicy = queuedMessageLaneDeliveryPolicy(mutation.lane);
+ if (targetPolicy !== policy) {
+ item.queueKey = undefined;
+ item.wake = mutation.lane === "steering" ? "on_lower_boundary" : "external_resume";
+ this._actionStore.moveQueued(item, targetPolicy, this._actionStore.queuedActions(targetPolicy).length);
+ }
+ this.resumeQueuedWork();
+ this._emitQueueUpdate();
+ return "applied";
+ }
+
get queuedActionCount(): number {
return visibleSessionActionProjection(this._actionStore.queuedActions()).length;
}
@@ -6111,6 +6187,10 @@ export class AgentSession {
return this._actionStore.unfinishedActions().length;
}
+ get isQueuedWorkSuspended(): boolean {
+ return this._sessionInputPumpSuspended;
+ }
+
get isSessionActive(): boolean {
return (
this.isStreaming ||
diff --git a/packages/coding-agent/src/core/keybindings.ts b/packages/coding-agent/src/core/keybindings.ts
index 77a9a4912b..3a410340bd 100644
--- a/packages/coding-agent/src/core/keybindings.ts
+++ b/packages/coding-agent/src/core/keybindings.ts
@@ -29,7 +29,10 @@ export interface AppKeybindings {
"app.editor.external": true;
"app.prompt.stash": true;
"app.message.followUp": true;
- "app.message.dequeue": true;
+ "app.message.navigateOlder": true;
+ "app.message.navigateNewer": true;
+ "app.message.moveEarlier": true;
+ "app.message.moveLater": true;
"app.clipboard.pasteImage": true;
"app.clipboard.copyLoginUrl": true;
"app.session.new": true;
@@ -118,9 +121,21 @@ export const KEYBINDINGS = {
defaultKeys: "alt+enter",
description: "Queue follow-up message",
},
- "app.message.dequeue": {
+ "app.message.navigateOlder": {
defaultKeys: "alt+up",
- description: "Restore queued messages",
+ description: "Select older pending message",
+ },
+ "app.message.navigateNewer": {
+ defaultKeys: "alt+down",
+ description: "Select newer pending message or draft",
+ },
+ "app.message.moveEarlier": {
+ defaultKeys: "ctrl+alt+up",
+ description: "Move selected pending message earlier",
+ },
+ "app.message.moveLater": {
+ defaultKeys: "ctrl+alt+down",
+ description: "Move selected pending message later",
},
"app.clipboard.pasteImage": {
defaultKeys: process.platform === "win32" ? "alt+v" : "ctrl+v",
@@ -213,6 +228,7 @@ export const KEYBINDINGS = {
} as const satisfies KeybindingDefinitions;
const KEYBINDING_NAME_MIGRATIONS = {
+ "app.message.dequeue": "app.message.navigateOlder",
cursorUp: "tui.editor.cursorUp",
cursorDown: "tui.editor.cursorDown",
cursorLeft: "tui.editor.cursorLeft",
@@ -255,7 +271,7 @@ const KEYBINDING_NAME_MIGRATIONS = {
focusSubagents: "app.subagents.focus",
externalEditor: "app.editor.external",
followUp: "app.message.followUp",
- dequeue: "app.message.dequeue",
+ dequeue: "app.message.navigateOlder",
pasteImage: "app.clipboard.pasteImage",
newSession: "app.session.new",
tree: "app.session.tree",
diff --git a/packages/coding-agent/src/core/session-action-store.ts b/packages/coding-agent/src/core/session-action-store.ts
index fc7a815dcd..184841bdf3 100644
--- a/packages/coding-agent/src/core/session-action-store.ts
+++ b/packages/coding-agent/src/core/session-action-store.ts
@@ -1,5 +1,5 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
-import type { UserMessage } from "@earendil-works/pi-ai";
+import type { ImageContent, UserMessage } from "@earendil-works/pi-ai";
import type { InputSource } from "./extensions/index.js";
import type { CustomMessage } from "./messages.js";
import type { SessionSlashCommand } from "./slash-commands.js";
@@ -7,6 +7,18 @@ import type { SessionSlashCommand } from "./slash-commands.js";
export type DeliveryPolicy = "next_turn_boundary" | "when_run_idle";
export type WakePolicy = "immediate" | "on_lower_boundary" | "external_resume";
+export type QueuedMessageLane = "steering" | "followUp";
+
+export function queuedMessageLaneDeliveryPolicy(lane: QueuedMessageLane): DeliveryPolicy {
+ return lane === "steering" ? "next_turn_boundary" : "when_run_idle";
+}
+
+export type QueuedMessageMutation =
+ | { type: "delete" }
+ | { type: "move"; direction: -1 | 1 }
+ | { type: "replace"; text: string; images?: ImageContent[]; lane: QueuedMessageLane };
+export type QueuedMessageMutationStatus = "applied" | "rejected" | "invalid";
+
export interface SessionActionSnapshot {
queuedCount: number;
steering: readonly string[];
@@ -230,6 +242,30 @@ export class ActionStore<TAction extends SessionAction = SessionAction> {
transitionSessionAction(action, { state: "queued" }, { rollbackProof: proof });
}
+ swapQueued(left: TAction, right: TAction): void {
+ if (left.lifecycle.state !== "queued" || right.lifecycle.state !== "queued" || left.delivery !== right.delivery) {
+ throw new Error("Only queued actions in the same lane can be swapped");
+ }
+ const list = this.list(left.delivery);
+ const leftIndex = list.indexOf(left);
+ const rightIndex = list.indexOf(right);
+ if (leftIndex < 0 || rightIndex < 0) throw new Error("Queued action is not owned by this store");
+ [list[leftIndex], list[rightIndex]] = [right, left];
+ }
+
+ moveQueued(action: TAction, delivery: DeliveryPolicy, index: number): void {
+ if (action.lifecycle.state !== "queued") throw new Error("Only queued actions can be moved");
+ const source = this.list(action.delivery);
+ const sourceIndex = source.indexOf(action);
+ if (sourceIndex < 0) throw new Error(`Session action ${action.id} is not owned by this store`);
+ source.splice(sourceIndex, 1);
+ action.delivery = delivery;
+ const target = this.list(delivery);
+ const queued = target.filter((item) => item.lifecycle.state === "queued");
+ const before = queued[Math.max(0, Math.min(index, queued.length))];
+ target.splice(before ? target.indexOf(before) : target.length, 0, action);
+ }
+
queuedActions(policy?: DeliveryPolicy): readonly TAction[] {
return this.actions(policy).filter((action) => action.lifecycle.state === "queued");
}
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index f5805785ec..016a053279 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -59,6 +59,9 @@ import type {
AgentConnectionNavigateTreeResult,
AgentConnectionNewSessionOptions,
AgentConnectionPromptOptions,
+ AgentConnectionQueuedMessageLane,
+ AgentConnectionQueuedMessageMutation,
+ AgentConnectionQueuedMessageMutationStatus,
AgentConnectionQueueMode,
AgentConnectionQueueState,
AgentConnectionResourceSnapshot,
@@ -528,6 +531,24 @@ export class DaemonAgentConnection implements AgentConnection {
});
}
+ async mutateQueuedMessage(
+ lane: AgentConnectionQueuedMessageLane,
+ index: number,
+ expectedText: string,
+ mutation: AgentConnectionQueuedMessageMutation,
+ ): Promise<AgentConnectionQueuedMessageMutationStatus> {
+ if (!this.client.supportsServerCapability("queue_message_mutation")) return "unsupported";
+ const data = await this.requestData<{ status: AgentConnectionQueuedMessageMutationStatus }>({
+ type: "mutate_queued_message",
+ activeSessionId: this.activeSessionId,
+ lane,
+ index,
+ expectedText,
+ mutation,
+ });
+ return data.status;
+ }
+
async clearQueue(): Promise<AgentConnectionQueueState> {
return this.requestData<AgentConnectionQueueState>({
type: "clear_queue",
diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
index 552a910d9c..e8257b3fb1 100644
--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
@@ -43,6 +43,9 @@ import type {
AgentConnectionNavigateTreeResult,
AgentConnectionNewSessionOptions,
AgentConnectionPromptOptions,
+ AgentConnectionQueuedMessageLane,
+ AgentConnectionQueuedMessageMutation,
+ AgentConnectionQueuedMessageMutationStatus,
AgentConnectionQueueMode,
AgentConnectionQueueState,
AgentConnectionResourceSnapshot,
@@ -188,6 +191,15 @@ export class InProcessAgentConnection implements AgentConnection {
};
}
+ async mutateQueuedMessage(
+ lane: AgentConnectionQueuedMessageLane,
+ index: number,
+ expectedText: string,
+ mutation: AgentConnectionQueuedMessageMutation,
+ ): Promise<AgentConnectionQueuedMessageMutationStatus> {
+ return this.session.mutateQueuedMessage(lane, index, expectedText, mutation);
+ }
+
async clearQueue(): Promise<AgentConnectionQueueState> {
return this.session.clearQueue();
}
diff --git a/packages/coding-agent/src/modes/agent-connection/index.ts b/packages/coding-agent/src/modes/agent-connection/index.ts
index f8247c12ba..cea0218b65 100644
--- a/packages/coding-agent/src/modes/agent-connection/index.ts
+++ b/packages/coding-agent/src/modes/agent-connection/index.ts
@@ -28,6 +28,7 @@ export type {
AgentConnectionNewSessionOptions,
AgentConnectionParentMetadata,
AgentConnectionPromptOptions,
+ AgentConnectionQueuedMessageMutationStatus,
AgentConnectionQueueMode,
AgentConnectionQueueState,
AgentConnectionReplayInfo,
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index ff34a9298a..7e98f96681 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -18,7 +18,12 @@ import type { GoalState } from "../../core/goals.js";
import type { KernelSentAgentMessage } from "../../core/kernel/index.js";
import type { RefinementResult } from "../../core/refinement/index.js";
import type { RlmMaxDepthStatus, SetRlmMaxDepthResult } from "../../core/rlm-max-depth.js";
-import type { SessionActionSnapshot } from "../../core/session-action-store.js";
+import type {
+ QueuedMessageLane,
+ QueuedMessageMutation,
+ QueuedMessageMutationStatus,
+ SessionActionSnapshot,
+} from "../../core/session-action-store.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
import type { SessionStats } from "../../core/session-stats.js";
@@ -513,6 +518,11 @@ export interface AgentConnectionQueueState {
followUp: string[];
}
+export type AgentConnectionQueuedMessageLane = QueuedMessageLane;
+export type AgentConnectionQueuedMessageMutation = QueuedMessageMutation;
+/** "unsupported" is returned only by remote connections whose daemon predates queued-message mutation. */
+export type AgentConnectionQueuedMessageMutationStatus = QueuedMessageMutationStatus | "unsupported";
+
export interface AgentConnectionHeartbeat {
job: AgentCronJob;
sessionName?: string;
@@ -643,6 +653,12 @@ export interface AgentConnection {
callbacks?: AgentConnectionSessionListCallbacks,
): Promise<AgentConnectionSavedSessionInfo[]>;
getQueue(): Promise<AgentConnectionQueueState>;
+ mutateQueuedMessage(
+ lane: AgentConnectionQueuedMessageLane,
+ index: number,
+ expectedText: string,
+ mutation: AgentConnectionQueuedMessageMutation,
+ ): Promise<AgentConnectionQueuedMessageMutationStatus>;
clearQueue(): Promise<AgentConnectionQueueState>;
abortAndClearQueue(): Promise<AgentConnectionQueueState>;
listCronJobs(options?: { includeInactive?: boolean }): Promise<AgentCronJob[]>;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index dfebcdf61e..3443cd3f8c 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -280,6 +280,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"get_model_catalog",
"get_available_models",
"get_queue",
+ "mutate_queued_message",
"clear_queue",
"abort_and_clear_queue",
"cron_list",
@@ -4181,6 +4182,17 @@ export class AgentDaemon {
});
}
+ case "mutate_queued_message": {
+ const state = this.getSessionState(command.activeSessionId);
+ const status = state.runtime.session.mutateQueuedMessage(
+ command.lane,
+ command.index,
+ command.expectedText,
+ command.mutation,
+ );
+ return success(command.id, "mutate_queued_message", { status });
+ }
+
case "clear_queue": {
const state = this.getSessionState(command.activeSessionId);
return success(command.id, "clear_queue", state.runtime.session.clearQueue());
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 02b1ad5e4d..5ce29bf7ed 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -18,6 +18,7 @@ import type {
} from "../../core/cron-jobs.js";
import type { InputSource } from "../../core/extensions/types.js";
import type { CustomMessage } from "../../core/messages.js";
+import type { QueuedMessageLane, QueuedMessageMutation } from "../../core/session-action-store.js";
import type { SessionCwdIssue } from "../../core/session-cwd.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
import type {
@@ -57,8 +58,9 @@ export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;
// Revision 12 publishes idle-residency metadata on session summary rows.
// Revision 13 narrows agent-origin reach and roster wire shapes to the nuclear family.
// Revision 14 carries the client's monotonic telemetry opt-out on attach and reattach.
-export const DAEMON_SCHEMA_REVISION = 14;
-export const DAEMON_SCHEMA_ID = "protocol-7-schema-14-816309b1cd50";
+// Revision 15 adds the mutate_queued_message command and queue_message_mutation capability.
+export const DAEMON_SCHEMA_REVISION = 15;
+export const DAEMON_SCHEMA_ID = "protocol-7-schema-15-1bcb9e7f1a49";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -96,7 +98,8 @@ export type DaemonServerCapability =
// identity). Clients must check before sending.
| "transient_bash"
| "session_input_admission"
- | "prompt_admission_cancellation";
+ | "prompt_admission_cancellation"
+ | "queue_message_mutation";
export type DaemonReplayStatus = "complete" | "partial" | "unavailable";
@@ -134,6 +137,7 @@ export const DAEMON_DEFAULT_SERVER_CAPABILITIES: readonly DaemonServerCapability
"transient_bash",
"session_input_admission",
"prompt_admission_cancellation",
+ "queue_message_mutation",
];
export interface DaemonRuntimeIdentity {
@@ -508,6 +512,15 @@ export type DaemonCommand =
| { id?: string; type: "get_model_catalog"; activeSessionId: string }
| { id?: string; type: "get_available_models"; activeSessionId: string }
| { id?: string; type: "get_queue"; activeSessionId: string }
+ | {
+ id?: string;
+ type: "mutate_queued_message";
+ activeSessionId: string;
+ lane: QueuedMessageLane;
+ index: number;
+ expectedText: string;
+ mutation: QueuedMessageMutation;
+ }
| { id?: string; type: "clear_queue"; activeSessionId: string }
| { id?: string; type: "abort_and_clear_queue"; activeSessionId: string }
| { id?: string; type: "cron_list"; activeSessionId?: string; includeInactive?: boolean }
@@ -682,6 +695,7 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
get_model_catalog: { minProtocol: 7, capability: "model_catalog" },
get_available_models: LEGACY_DAEMON_COMMAND,
get_queue: LEGACY_DAEMON_COMMAND,
+ mutate_queued_message: { minProtocol: 7, minSchemaRevision: 15, capability: "queue_message_mutation" },
clear_queue: LEGACY_DAEMON_COMMAND,
abort_and_clear_queue: LEGACY_DAEMON_COMMAND,
cron_list: LEGACY_DAEMON_COMMAND,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 4b0d834ccc..b308219ba2 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -190,6 +190,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"get_model_catalog",
"get_available_models",
"get_queue",
+ "mutate_queued_message",
"clear_queue",
"abort_and_clear_queue",
"cron_list",
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 50207b73ea..b0585156ff 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -147,6 +147,7 @@ import type {
AgentConnectionHeartbeat,
AgentConnectionModel,
AgentConnectionModelCatalog,
+ AgentConnectionQueuedMessageMutationStatus,
AgentConnectionQueueState,
AgentConnectionResourceDiagnostic,
AgentConnectionResourceSnapshot,
@@ -244,6 +245,7 @@ import {
shouldRunPrimeCliOnboardingSplash,
} from "./onboarding.js";
import type { ClientPromptStashStore, PromptStash, PromptStashState } from "./prompt-stash-state.js";
+import { QueueSelection } from "./queue-selection.js";
import { formatResumeHint } from "./resume-hint.js";
import {
getAvailableThemes,
@@ -892,7 +894,6 @@ export class InteractiveMode {
private escapeRepeatAction: "tree" | "clear" | undefined;
private escapeRepeatExpiresAt = 0;
private escapeRepeatTimer: ReturnType<typeof setTimeout> | undefined = undefined;
- private isRestoringQueuedEditorText = false;
private anthropicSubscriptionWarningShown = false;
// Status line tracking (for mutating immediately-sequential status updates)
@@ -994,6 +995,10 @@ export class InteractiveMode {
// Session-owned queued messages mirrored from connection events.
private connectionQueue: AgentConnectionQueueState = { steering: [], followUp: [] };
+ private readonly queueSelection = new QueueSelection();
+ private isApplyingQueueSelectionText = false;
+ private queueMutationChain: Promise<void> = Promise.resolve();
+ private pendingQueueEdit: symbol | undefined;
// Shutdown state
private shutdownRequested = false;
@@ -1378,7 +1383,7 @@ export class InteractiveMode {
hint("app.prompt.stash", "to stash prompt"),
rawKeyHint("/", "for commands"),
hint("app.message.followUp", "to queue follow-up"),
- hint("app.message.dequeue", "to edit all queued messages"),
+ hint("app.message.navigateOlder", "to browse queued messages"),
hint("app.clipboard.pasteImage", "to paste image"),
rawKeyHint("drop files", "to attach"),
].join("\n")
@@ -2514,7 +2519,23 @@ export class InteractiveMode {
}
private async refreshConnectionQueue(): Promise<void> {
- this.connectionQueue = await this.agentConnection.getQueue();
+ this.replaceConnectionQueue(await this.agentConnection.getQueue());
+ }
+
+ private replaceConnectionQueue(queue: AgentConnectionQueueState): void {
+ this.connectionQueue = {
+ steering: [...queue.steering],
+ followUp: [...queue.followUp],
+ };
+ const dropped = this.queueSelection.sync(this.connectionQueue);
+ if (dropped !== undefined) {
+ const editorText = this.editor.getText();
+ if (editorText === dropped) {
+ this.setEditorTextFromQueueSelection(this.queueSelection.reset());
+ } else if (!this.pendingQueueEdit) {
+ this.queueSelection.replaceDraft(editorText);
+ }
+ }
this.updatePendingMessagesDisplay();
}
@@ -2817,6 +2838,10 @@ export class InteractiveMode {
this.pendingMessagesContainer.clear();
this.queuedMessagesContainer.clear();
this.connectionQueue = { steering: [], followUp: [] };
+ this.pendingQueueEdit = undefined;
+ // The selection and its stashed draft belong to the previous session;
+ // every editor draft is cleared below, so discard rather than restore.
+ this.queueSelection.reset();
this.featureHintSuppressedByQueue = false;
if (options?.clearPromptStash) {
this.promptStash = undefined;
@@ -4119,6 +4144,7 @@ export class InteractiveMode {
// =========================================================================
private setupKeyHandlers(): void {
+ this.defaultEditor.getHeaderLine = () => this.getQueueSelectionHeader();
// Set up handlers on defaultEditor - they use this.editor for text access
// so they work correctly regardless of which editor is active
this.defaultEditor.onEscape = () => {
@@ -4147,9 +4173,10 @@ export class InteractiveMode {
this.defaultEditor.onAction("app.editor.external", () => this.openExternalEditor());
this.defaultEditor.onAction("app.prompt.stash", () => this.handlePromptStash());
this.defaultEditor.onAction("app.message.followUp", () => this.handleFollowUp());
- this.defaultEditor.onAction("app.message.dequeue", () => {
- void this.handleDequeue();
- });
+ this.defaultEditor.onAction("app.message.navigateOlder", () => this.browseQueueSelection(-1));
+ this.defaultEditor.onAction("app.message.navigateNewer", () => this.browseQueueSelection(1));
+ this.defaultEditor.onAction("app.message.moveEarlier", () => this.moveQueueSelection(-1));
+ this.defaultEditor.onAction("app.message.moveLater", () => this.moveQueueSelection(1));
this.defaultEditor.onAction("app.session.new", () => this.handleClearCommand());
this.defaultEditor.onAction("app.session.tree", () => {
void this.showTreeSelector();
@@ -4164,10 +4191,10 @@ export class InteractiveMode {
this.defaultEditor.onMoveBelowPrompt = () => this.focusSubagentSummary();
this.defaultEditor.onChange = (text: string) => {
- if (text.length > 0) {
+ if (text.length > 0 && !this.isApplyingQueueSelectionText) {
this.latestEditorPromptStash = this.snapshotPromptStashFrom(this.editor, text);
}
- if (this.escapeRepeatAction && !this.isRestoringQueuedEditorText) {
+ if (this.escapeRepeatAction && !this.isApplyingQueueSelectionText) {
this.clearEscapeRepeat();
}
if (text.length > 0) {
@@ -4575,6 +4602,15 @@ export class InteractiveMode {
this.defaultEditor.onSubmit = async (text: string) => {
const streamingBehavior = this.submittedInputBehavior;
this.submittedInputBehavior = "steer";
+ if (this.queueSelection?.isBrowsing && !this.pendingQueueEdit) {
+ const targetLane = streamingBehavior === "followUp" ? "followUp" : "steering";
+ try {
+ if (await this.applyQueueSelection(text, targetLane)) return;
+ } catch (error) {
+ this.showError(error instanceof Error ? error.message : String(error));
+ return;
+ }
+ }
text = text.trim();
if (!text) return;
const submissionGeneration = ++this.inputSubmissionGeneration;
@@ -5318,14 +5354,14 @@ export class InteractiveMode {
this.ui.requestRender();
break;
- case "session_action_update":
- this.connectionQueue = {
+ case "session_action_update": {
+ this.replaceConnectionQueue({
steering: [...event.actions.steering],
followUp: [...event.actions.followUps],
- };
- this.updatePendingMessagesDisplay();
+ });
this.ui.requestRender();
break;
+ }
case "session_info_changed":
this.updateTerminalTitle();
@@ -6658,7 +6694,9 @@ export class InteractiveMode {
void this.agentConnection.abortBash();
}
if (this.isAgentStreaming()) {
- void this.restoreQueuedMessagesToEditor({ abort: true }).catch((error) => {
+ // The queue is preserved server-side; draining resumes on the next
+ // submit or queued-message edit.
+ void this.agentConnection.abort().catch((error) => {
this.showError(error instanceof Error ? error.message : String(error));
});
}
@@ -6900,6 +6938,12 @@ export class InteractiveMode {
private async handleFollowUp(): Promise<void> {
const editorText = this.editor.getText();
const text = (this.editor.getExpandedText?.() ?? editorText).trim();
+ if (this.queueSelection?.isBrowsing && !this.pendingQueueEdit) {
+ await this.applyQueueSelection(text, "followUp").catch((error) =>
+ this.showError(error instanceof Error ? error.message : String(error)),
+ );
+ return;
+ }
if (!text || !this.editor.onSubmit) return;
// Unlike Enter, Alt+Enter does not go through Editor.submitValue(), so
@@ -6923,15 +6967,227 @@ export class InteractiveMode {
}
}
- private async handleDequeue(): Promise<void> {
- const restored = await this.restoreQueuedMessagesToEditor();
- if (restored === 0) {
- this.showStatus("No queued messages to restore");
- } else {
- this.showStatus(`Restored ${restored} queued message${restored > 1 ? "s" : ""} to editor`);
+ private browseQueueSelection(direction: -1 | 1): void {
+ if (this.pendingQueueEdit) return;
+ const text = this.queueSelection.move(this.connectionQueue, this.editor.getText(), direction);
+ if (text === undefined) return;
+ this.setEditorTextFromQueueSelection(text);
+ this.ui.requestRender();
+ }
+
+ /** Serializes queue mutations so rapid keypresses never race each other or use stale indices. */
+ private enqueueQueueMutation<T>(run: () => Promise<T>): Promise<T> {
+ const next = this.queueMutationChain.then(run, run);
+ this.queueMutationChain = next.then(
+ () => undefined,
+ () => undefined,
+ );
+ return next;
+ }
+
+ private moveQueueSelection(direction: -1 | 1): void {
+ if (this.pendingQueueEdit) return;
+ const submittedSelection = this.queueSelection.selected;
+ if (!submittedSelection) return;
+ const sessionGeneration = this.sessionEventGeneration;
+ void this.enqueueQueueMutation(async () => {
+ if (sessionGeneration !== this.sessionEventGeneration) return;
+ const lane = this.connectionQueue[submittedSelection.lane];
+ const resolvedIndex =
+ lane[submittedSelection.index] === submittedSelection.text
+ ? submittedSelection.index
+ : lane.indexOf(submittedSelection.text);
+ if (resolvedIndex < 0) {
+ this.showStatus("Queue changed; reorder not applied");
+ return;
+ }
+ const selected = { ...submittedSelection, index: resolvedIndex };
+ const queueBefore = this.connectionQueue;
+ const status = await this.agentConnection.mutateQueuedMessage(selected.lane, selected.index, selected.text, {
+ type: "move",
+ direction,
+ });
+ if (sessionGeneration !== this.sessionEventGeneration) return;
+ if (status === "applied") {
+ // The queue event for this mutation can land before or after the
+ // response. Patch the mirror only when no event has replaced it
+ // meanwhile (events always assign a fresh object); patching an
+ // already-updated mirror would apply the mutation twice.
+ const lane = this.connectionQueue[selected.lane];
+ const target = selected.index + direction;
+ if (
+ this.connectionQueue === queueBefore &&
+ lane[selected.index] === selected.text &&
+ target >= 0 &&
+ target < lane.length
+ ) {
+ [lane[selected.index], lane[target]] = [lane[target] as string, selected.text];
+ this.queueSelection.sync(this.connectionQueue);
+ this.updatePendingMessagesDisplay();
+ this.ui.requestRender();
+ }
+ } else if (status === "unsupported") this.showStatus("Queue editing requires a newer daemon");
+ else this.showStatus("Queue changed; reorder not applied");
+ }).catch((error) => {
+ if (sessionGeneration === this.sessionEventGeneration) {
+ this.showError(error instanceof Error ? error.message : String(error));
+ }
+ });
+ }
+
+ /**
+ * Applies the edited text to the selected queued message. Returns true when
+ * the submission was consumed (the caller must not treat it as a new prompt).
+ * Empty text deletes; otherwise replaces, moving the item to `targetLane`.
+ */
+ private applyQueueSelection(text: string, targetLane: "steering" | "followUp"): Promise<boolean> {
+ if (this.pendingQueueEdit) return Promise.resolve(false);
+ const submittedSelection = this.queueSelection.selected;
+ if (!submittedSelection) return Promise.resolve(false);
+ const pendingQueueEdit = Symbol("pending-queue-edit");
+ this.pendingQueueEdit = pendingQueueEdit;
+ const sessionGeneration = this.sessionEventGeneration;
+ const submissionGeneration = this.inputSubmissionGeneration;
+ const trimmed = text.trim();
+ const mutation =
+ trimmed.length === 0
+ ? ({ type: "delete" } as const)
+ : ({
+ type: "replace",
+ text: trimmed,
+ images: this.collectQueueReplaceImages(trimmed),
+ lane: targetLane,
+ } as const);
+ const editorTextBefore = this.editor.getText();
+ const discardStaleSelection = (): boolean => {
+ if (sessionGeneration === this.sessionEventGeneration) return false;
+ if (this.pendingQueueEdit === pendingQueueEdit) {
+ this.pendingQueueEdit = undefined;
+ this.queueSelection.reset();
+ if (submissionGeneration === this.inputSubmissionGeneration && this.editor.getText() === editorTextBefore) {
+ this.setEditorTextFromQueueSelection("");
+ }
+ this.ui.requestRender();
+ }
+ return true;
+ };
+ return this.enqueueQueueMutation(async () => {
+ if (discardStaleSelection()) return true;
+ // Earlier serialized moves may have changed the selected item's index.
+ const lane = this.connectionQueue[submittedSelection.lane];
+ const resolvedIndex =
+ lane[submittedSelection.index] === submittedSelection.text
+ ? submittedSelection.index
+ : lane.indexOf(submittedSelection.text);
+ if (resolvedIndex < 0) {
+ this.queueSelection.sync(this.connectionQueue);
+ const editorUntouched =
+ submissionGeneration === this.inputSubmissionGeneration && this.editor.getText() === editorTextBefore;
+ if (editorUntouched) {
+ this.setEditorTextFromQueueSelection(text);
+ }
+ this.queueSelection.replaceDraft(editorUntouched ? text : this.editor.getText());
+ this.showStatus("Queue changed; edit kept in the editor");
+ this.updatePendingMessagesDisplay();
+ this.ui.requestRender();
+ return true;
+ }
+ const selected = { ...submittedSelection, index: resolvedIndex };
+ const queueBefore = this.connectionQueue;
+ let status: AgentConnectionQueuedMessageMutationStatus;
+ try {
+ status = await this.agentConnection.mutateQueuedMessage(
+ selected.lane,
+ selected.index,
+ selected.text,
+ mutation,
+ );
+ } catch (error) {
+ if (discardStaleSelection()) return true;
+ // The editor was already cleared by Enter; restore the edit before surfacing the error.
+ const editorUntouched =
+ submissionGeneration === this.inputSubmissionGeneration && this.editor.getText() === editorTextBefore;
+ if (editorUntouched) {
+ this.setEditorTextFromQueueSelection(text);
+ }
+ if (!this.queueSelection.isBrowsing) {
+ this.queueSelection.replaceDraft(editorUntouched ? text : this.editor.getText());
+ }
+ throw error;
+ }
+ if (discardStaleSelection()) return true;
+ const editorUntouched =
+ submissionGeneration === this.inputSubmissionGeneration && this.editor.getText() === editorTextBefore;
+ if (status === "applied") {
+ // Same optimistic patch as moveQueueSelection, and the same guard:
+ // skip when a queue event already replaced the mirror.
+ const lane = this.connectionQueue[selected.lane];
+ if (this.connectionQueue === queueBefore && lane[selected.index] === selected.text) {
+ if (!trimmed) lane.splice(selected.index, 1);
+ else if (targetLane === selected.lane) lane[selected.index] = trimmed;
+ else {
+ lane.splice(selected.index, 1);
+ this.connectionQueue[targetLane].push(trimmed);
+ }
+ }
+ if (trimmed) this.editor.addToHistory?.(trimmed);
+ const draft = this.queueSelection.reset();
+ if (editorUntouched) this.setEditorTextFromQueueSelection(draft);
+ } else {
+ this.queueSelection.sync(this.connectionQueue);
+ // Enter submissions clear the editor before onSubmit runs; restore the
+ // edit so a failed mutation never swallows it.
+ if (editorUntouched) this.setEditorTextFromQueueSelection(text);
+ if (!this.queueSelection.isBrowsing) {
+ this.queueSelection.replaceDraft(editorUntouched ? text : this.editor.getText());
+ }
+ if (status === "invalid")
+ this.showStatus("Edited command is not a valid session command; edit kept in the editor");
+ else if (status === "unsupported") this.showStatus("Queue editing requires a newer daemon");
+ else this.showStatus("Queue changed; edit kept in the editor");
+ }
+ this.updatePendingMessagesDisplay();
+ this.ui.requestRender();
+ return true;
+ }).finally(() => {
+ if (this.pendingQueueEdit === pendingQueueEdit) this.pendingQueueEdit = undefined;
+ });
+ }
+
+ /**
+ * Images for a queue replace: undefined preserves the server's images (some
+ * markers cannot be resolved by this client), [] clears, a list replaces.
+ */
+ private collectQueueReplaceImages(text: string): ImageContent[] | undefined {
+ const markers = [...new Set(imageMarkerIds(text))];
+ if (markers.length === 0) return [];
+ const resolved = markers.map((markerId) => this.pastedImages.get(markerId));
+ return resolved.every((image) => image !== undefined)
+ ? resolved.map((image) => ({ ...(image as ImageContent) }))
+ : undefined;
+ }
+
+ private setEditorTextFromQueueSelection(text: string): void {
+ this.isApplyingQueueSelectionText = true;
+ try {
+ this.editor.setText(text);
+ } finally {
+ this.isApplyingQueueSelectionText = false;
}
}
+ private getQueueSelectionHeader(): string | undefined {
+ const selected = this.queueSelection.selected;
+ if (!selected) return undefined;
+ const lane = selected.lane === "steering" ? "steering" : "follow-up";
+ const older = this.getAppKeyDisplay("app.message.navigateOlder");
+ const newer = this.getAppKeyDisplay("app.message.navigateNewer");
+ const earlier = this.getAppKeyDisplay("app.message.moveEarlier");
+ const later = this.getAppKeyDisplay("app.message.moveLater");
+ const queue = this.getAppKeyDisplay("app.message.followUp");
+ return `${lane} ${selected.index + 1} · ${older}/${newer} browse · ${earlier}/${later} reorder · enter steers · ${queue} queues · empty deletes`;
+ }
+
private updateEditorBorderColor(): void {
const editorTheme = getEditorTheme();
this.editor.borderColor = editorTheme.borderColor;
@@ -7101,14 +7357,12 @@ export class InteractiveMode {
// UI helpers
// =========================================================================
- clearEditor(): void {
- this.clearInputBar();
- }
-
private clearInputBar(): void {
this.clearEscapeRepeat();
this.clearCtrlCExitHint({ render: false });
- this.editor.setText("");
+ // Leaving browse mode restores the stashed draft instead of arming an
+ // accidental empty-submit delete of the selected queued message.
+ this.editor.setText(this.queueSelection.hasDraft ? this.queueSelection.reset() : "");
this.ui.requestRender();
}
@@ -7142,17 +7396,6 @@ export class InteractiveMode {
};
}
- /** Clear all session-owned queued messages and return their contents. */
- private async clearAllQueues(
- options: { abort?: boolean } = {},
- ): Promise<{ steering: string[]; followUp: string[] }> {
- const { steering, followUp } = options.abort
- ? await this.agentConnection.abortAndClearQueue()
- : await this.agentConnection.clearQueue();
- this.connectionQueue = { steering: [], followUp: [] };
- return { steering, followUp };
- }
-
private updatePendingMessagesDisplay(): void {
// pendingMessagesContainer holds only in-flight bash output for the current
// turn, so it stays above the execution indicator. clear() detaches the
@@ -7176,8 +7419,8 @@ export class InteractiveMode {
const text = styleQueuedMessagePreview(message, "Follow-up", (name) => this.isRecognizedSlashCommand(name));
this.queuedMessagesContainer.addChild(new TruncatedText(text, 1, 0));
}
- const dequeueHint = this.getAppKeyDisplay("app.message.dequeue");
- const hintText = theme.fg("dim", `╰─ ${dequeueHint} to edit all queued messages`);
+ const dequeueHint = this.getAppKeyDisplay("app.message.navigateOlder");
+ const hintText = theme.fg("dim", `╰─ ${dequeueHint} to browse and edit queued messages`);
this.queuedMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));
}
if (hasQueuedMessages && !this.featureHintSuppressedByQueue) {
@@ -7198,28 +7441,6 @@ export class InteractiveMode {
this.pendingBashComponents = [];
}
- private async restoreQueuedMessagesToEditor(options?: { abort?: boolean; currentText?: string }): Promise<number> {
- const { steering, followUp } = await this.clearAllQueues({ abort: options?.abort });
- const allQueued = [...steering, ...followUp];
- if (allQueued.length === 0) {
- this.updatePendingMessagesDisplay();
- return 0;
- }
- const queuedText = allQueued.join("\n\n");
- const currentText = options?.currentText ?? this.editor.getText();
- const combinedText = [queuedText, currentText].filter((t) => t.trim()).join("\n\n");
- // The image registry persists, so the restored `[image #N]` markers resolve
- // on resubmit without any re-registration here.
- this.isRestoringQueuedEditorText = true;
- try {
- this.editor.setText(combinedText);
- } finally {
- this.isRestoringQueuedEditorText = false;
- }
- this.updatePendingMessagesDisplay();
- return allQueued.length;
- }
-
// =========================================================================
// Selectors
// =========================================================================
@@ -9520,7 +9741,8 @@ ${shortcutsKey ? `\`${shortcutsKey}\` quick shortcuts · ` : ""}\`/hotkeys\` ful
const externalEditor = this.getAppKeyDisplay("app.editor.external");
const promptStash = this.getAppKeyDisplay("app.prompt.stash");
const followUp = this.getAppKeyDisplay("app.message.followUp");
- const dequeue = this.getAppKeyDisplay("app.message.dequeue");
+ const browseQueue = this.getAppKeyDisplay("app.message.navigateOlder");
+ const reorderQueue = `${this.getAppKeyDisplay("app.message.moveEarlier")} / ${this.getAppKeyDisplay("app.message.moveLater")}`;
const pasteImage = this.getAppKeyDisplay("app.clipboard.pasteImage");
const viewportPageUp = this.getEditorKeyDisplay("tui.viewport.pageUp");
const viewportPageDown = this.getEditorKeyDisplay("tui.viewport.pageDown");
@@ -9568,7 +9790,8 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shor
| \`${externalEditor}\` | Edit message in external editor |
| \`${promptStash}\` | Stash or restore draft prompt |
| \`${followUp}\` | Queue follow-up message |
-| \`${dequeue}\` | Restore queued messages |
+| \`${browseQueue}\` | Browse and edit queued messages |
+| \`${reorderQueue}\` | Reorder the selected queued message |
| \`${pasteImage}\` | Paste image from clipboard |
| \`/\` | Slash commands |
diff --git a/packages/coding-agent/src/modes/interactive/queue-selection.ts b/packages/coding-agent/src/modes/interactive/queue-selection.ts
new file mode 100644
index 0000000000..3954775449
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/queue-selection.ts
@@ -0,0 +1,99 @@
+import type { AgentConnectionQueueState } from "../agent-connection/index.js";
+
+export type QueueLane = "steering" | "followUp";
+
+export interface QueueSelectionItem {
+ lane: QueueLane;
+ index: number;
+ text: string;
+}
+
+/**
+ * Tracks which queued message the user is browsing/editing with alt+up/alt+down.
+ *
+ * Items are addressed by (lane, index, text): the text is the authoritative
+ * check when a mutation is applied, so no ids or revisions are needed. Browsing
+ * order is newest-first: draft -> last followUp -> ... -> first steering.
+ */
+export class QueueSelection {
+ private items: QueueSelectionItem[] = [];
+ private cursor = -1; // -1 = draft
+ private draft = "";
+ private hasStashedDraft = false;
+
+ get selected(): QueueSelectionItem | undefined {
+ return this.cursor >= 0 ? this.items[this.cursor] : undefined;
+ }
+
+ get isBrowsing(): boolean {
+ return this.cursor >= 0;
+ }
+
+ get hasDraft(): boolean {
+ return this.hasStashedDraft;
+ }
+
+ replaceDraft(draft: string): void {
+ this.draft = draft;
+ this.hasStashedDraft = true;
+ }
+
+ /** Move the cursor. -1 browses older, +1 newer. Returns the text to show, or undefined for a boundary noop. */
+ move(queue: AgentConnectionQueueState, draft: string, direction: -1 | 1): string | undefined {
+ if (this.cursor < 0) {
+ if (direction > 0) return undefined;
+ this.items = flatten(queue);
+ if (this.items.length === 0) return undefined;
+ // A drop (sync) keeps the previous draft stashed; do not overwrite it
+ // with the dropped item's text still sitting in the editor.
+ if (!this.hasStashedDraft) {
+ this.draft = draft;
+ this.hasStashedDraft = true;
+ }
+ this.cursor = this.items.length - 1;
+ return this.items[this.cursor]?.text;
+ }
+ const next = this.cursor + direction;
+ if (next < 0 || next > this.items.length) return undefined;
+ if (next === this.items.length) {
+ return this.reset();
+ }
+ this.cursor = next;
+ return this.items[next]?.text;
+ }
+
+ /**
+ * Track queue changes while browsing: keep the selection when its text is
+ * still present. Returns the dropped item's text when the selection could
+ * not be kept, so the caller can restore the stashed draft.
+ */
+ sync(queue: AgentConnectionQueueState): string | undefined {
+ const selected = this.selected;
+ this.items = flatten(queue);
+ if (!selected) return undefined;
+ const exact = this.items[selected.lane === "steering" ? selected.index : queue.steering.length + selected.index];
+ if (exact?.lane === selected.lane && exact.text === selected.text) {
+ this.cursor = this.items.indexOf(exact);
+ return undefined;
+ }
+ const retargeted = this.items.find((item) => item.lane === selected.lane && item.text === selected.text);
+ this.cursor = retargeted ? this.items.indexOf(retargeted) : -1;
+ return retargeted ? undefined : selected.text;
+ }
+
+ /** Called after a mutation or submit resolved the selection. Returns the stashed draft. */
+ reset(): string {
+ this.cursor = -1;
+ const draft = this.draft;
+ this.draft = "";
+ this.hasStashedDraft = false;
+ return draft;
+ }
+}
+
+function flatten(queue: AgentConnectionQueueState): QueueSelectionItem[] {
+ return [
+ ...queue.steering.map((text, index) => ({ lane: "steering" as const, index, text })),
+ ...queue.followUp.map((text, index) => ({ lane: "followUp" as const, index, text })),
+ ];
+}
diff --git a/packages/coding-agent/test/agent-session-queue-mutation.test.ts b/packages/coding-agent/test/agent-session-queue-mutation.test.ts
new file mode 100644
index 0000000000..b23d4a5981
--- /dev/null
+++ b/packages/coding-agent/test/agent-session-queue-mutation.test.ts
@@ -0,0 +1,295 @@
+/** Tests for AgentSession.mutateQueuedMessage: (lane, index, expectedText) queue edits. */
+
+import { existsSync, mkdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Agent } from "@earendil-works/pi-agent-core";
+import {
+ type AssistantMessage,
+ type AssistantMessageEvent,
+ EventStream,
+ getModel,
+ type ImageContent,
+} from "@earendil-works/pi-ai";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { AgentSession } from "../src/core/agent-session.js";
+import { AuthStorage } from "../src/core/auth-storage.js";
+import { ModelRegistry } from "../src/core/model-registry.js";
+import type { QueuedMessageMutation } from "../src/core/session-action-store.js";
+import { SessionManager } from "../src/core/session-manager.js";
+import { SettingsManager } from "../src/core/settings-manager.js";
+import { createTestResourceLoader } from "./utilities.js";
+
+class MockAssistantStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
+ constructor() {
+ super(
+ (event) => event.type === "done" || event.type === "error",
+ (event) => {
+ if (event.type === "done") return event.message;
+ if (event.type === "error") return event.error;
+ throw new Error("Unexpected event type");
+ },
+ );
+ }
+}
+
+const zeroUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
+
+function createAssistantMessage(text: string): AssistantMessage {
+ return {
+ role: "assistant",
+ content: [{ type: "text", text }],
+ api: "anthropic-messages",
+ provider: "anthropic",
+ model: "mock",
+ usage: { ...zeroUsage, totalTokens: 0, cost: zeroUsage },
+ stopReason: "stop",
+ timestamp: Date.now(),
+ };
+}
+
+describe("AgentSession queue mutation", () => {
+ let session: AgentSession;
+ let tempDir: string;
+
+ beforeEach(() => {
+ tempDir = join(tmpdir(), `pi-queue-mutation-test-${Date.now()}-${Math.random()}`);
+ mkdirSync(tempDir, { recursive: true });
+ });
+
+ afterEach(async () => {
+ if (session) session.dispose();
+ if (tempDir && existsSync(tempDir)) rmSync(tempDir, { recursive: true });
+ });
+
+ function createSession() {
+ const model = getModel("anthropic", "claude-sonnet-4-5")!;
+ const agent = new Agent({
+ getApiKey: () => "test-key",
+ initialState: { model, systemPrompt: "Test", tools: [] },
+ streamFn: (_model, _context, options) => {
+ const stream = new MockAssistantStream();
+ queueMicrotask(() => stream.push({ type: "start", partial: createAssistantMessage("") }));
+ options?.signal?.addEventListener("abort", () =>
+ stream.push({ type: "error", reason: "aborted", error: createAssistantMessage("Aborted") }),
+ );
+ return stream;
+ },
+ });
+ const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ session = new AgentSession({
+ agent,
+ sessionManager: SessionManager.inMemory(),
+ settingsManager: SettingsManager.create(tempDir, tempDir),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, tempDir),
+ resourceLoader: createTestResourceLoader(),
+ });
+ return session;
+ }
+
+ /** Start a never-finishing turn so later submissions stay queued; returns the prompt promise. */
+ async function blockSession(): Promise<{ running: Promise<void> }> {
+ const running = session.prompt("running");
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ return { running };
+ }
+
+ const mutate = (l: "steering" | "followUp", i: number, text: string, m: QueuedMessageMutation) =>
+ session.mutateQueuedMessage(l, i, text, m);
+ const queue = () => {
+ const snapshot = session.getSessionActionSnapshot();
+ return { steering: [...snapshot.steering], followUp: [...snapshot.followUps] };
+ };
+ const payloadOf = (text: string) =>
+ session.getSessionActionRecoverySnapshot().actions.find((action) => action.payload.text === text)?.payload;
+ const primaryContent = (text: string) => {
+ const payload = payloadOf(text);
+ if (payload?.kind !== "turn") throw new Error(`expected turn payload for ${text}`);
+ return payload.records[0]?.message.content;
+ };
+
+ it("addresses items in snapshot projection order and rejects stale addresses", async () => {
+ createSession();
+ const { running } = await blockSession();
+ await session.steer("s1");
+ await session.steer("s2");
+ await session.followUp("f1");
+ expect(queue()).toEqual({ steering: ["s1", "s2"], followUp: ["f1"] });
+ expect(session.queuedActionCount).toBe(3);
+ expect(mutate("steering", 0, "wrong", { type: "delete" })).toBe("rejected");
+ expect(mutate("steering", 3, "s1", { type: "delete" })).toBe("rejected");
+ expect(mutate("followUp", 0, "s1", { type: "delete" })).toBe("rejected"); // right text, wrong lane
+ expect(mutate("steering", 0, "s1", { type: "delete" })).toBe("applied");
+ expect(queue()).toEqual({ steering: ["s2"], followUp: ["f1"] });
+ expect(session.queuedActionCount).toBe(2);
+ await session.abort();
+ await running.catch(() => {});
+ });
+
+ it("moves within a lane, rejects boundary moves, and flips lanes to the target lane end", async () => {
+ createSession();
+ const { running } = await blockSession();
+ await session.steer("s1");
+ await session.steer("s2");
+ await session.followUp("f1");
+ expect(mutate("steering", 0, "s1", { type: "move", direction: 1 })).toBe("applied");
+ expect(queue().steering).toEqual(["s2", "s1"]);
+ expect(mutate("steering", 1, "s1", { type: "move", direction: 1 })).toBe("rejected");
+ expect(mutate("steering", 0, "s2", { type: "move", direction: -1 })).toBe("rejected");
+ expect(mutate("steering", 0, "s2", { type: "replace", text: "s2 flipped", lane: "followUp" })).toBe("applied");
+ expect(queue()).toEqual({ steering: ["s1"], followUp: ["f1", "s2 flipped"] });
+ expect(mutate("followUp", 1, "s2 flipped", { type: "replace", text: "s2 flipped", lane: "steering" })).toBe(
+ "applied",
+ );
+ expect(queue()).toEqual({ steering: ["s1", "s2 flipped"], followUp: ["f1"] });
+ await session.abort();
+ await running.catch(() => {});
+ });
+
+ it("replaces turn text in place across the image tri-state and rebuilds content and records", async () => {
+ createSession();
+ const { running } = await blockSession();
+ const original: ImageContent = { type: "image", data: "original", mimeType: "image/png" };
+ await session.prompt("edit me [image #1]", {
+ streamingBehavior: "steer",
+ images: [original],
+ content: [{ type: "text", text: "edit me" }, { type: "text", text: " [image #1]" }, original],
+ });
+ const edit = (expected: string, text: string, images?: ImageContent[]) =>
+ mutate("steering", 0, expected, { type: "replace", text, images, lane: "steering" });
+ // images undefined: preserve images, swap the text block, keep non-text blocks.
+ expect(edit("edit me [image #1]", "edited")).toBe("applied");
+ expect(payloadOf("edited")).toMatchObject({
+ images: [original],
+ content: [{ type: "text", text: "edited" }, original],
+ });
+ expect(primaryContent("edited")).toEqual([{ type: "text", text: "edited" }, original]);
+ // explicit images: content rebuilt from text + clones.
+ const replacement: ImageContent = { type: "image", data: "replacement", mimeType: "image/png" };
+ expect(edit("edited", "re-imaged", [replacement])).toBe("applied");
+ const reimaged = payloadOf("re-imaged");
+ expect(reimaged).toMatchObject({
+ images: [replacement],
+ content: [{ type: "text", text: "re-imaged" }, replacement],
+ });
+ expect(primaryContent("re-imaged")).toEqual([{ type: "text", text: "re-imaged" }, replacement]);
+ // empty images: clear to a bare text block.
+ expect(edit("re-imaged", "plain", [])).toBe("applied");
+ const cleared = payloadOf("plain");
+ expect(cleared).not.toHaveProperty("images");
+ expect(cleared?.kind === "turn" ? cleared.content : undefined).toEqual([{ type: "text", text: "plain" }]);
+ expect(primaryContent("plain")).toEqual([{ type: "text", text: "plain" }]);
+ await session.abort();
+ await running.catch(() => {});
+ });
+
+ it("validates session command text and protects accepted agent messages", async () => {
+ createSession();
+ const { running } = await blockSession();
+ await session.prompt("/compact focus on tools", { streamingBehavior: "steer" });
+ await session.acceptAgentMessagePrompt("agent item", { streamingBehavior: "followUp" });
+ expect(queue()).toEqual({ steering: ["/compact focus on tools"], followUp: ["agent item"] });
+ expect(
+ mutate("steering", 0, "/compact focus on tools", { type: "replace", text: "plain", lane: "steering" }),
+ ).toBe("invalid");
+ expect(
+ mutate("steering", 0, "/compact focus on tools", {
+ type: "replace",
+ text: "/compact revised focus",
+ lane: "followUp",
+ }),
+ ).toBe("applied");
+ expect(queue().steering).toEqual([]);
+ expect(payloadOf("/compact revised focus")).toMatchObject({
+ kind: "session_command",
+ command: { name: "compact", args: "revised focus" },
+ });
+ expect(mutate("followUp", 0, "agent item", { type: "replace", text: "hijacked", lane: "followUp" })).toBe(
+ "rejected",
+ );
+ expect(mutate("followUp", 0, "agent item", { type: "delete" })).toBe("applied");
+ expect(queue().followUp).toEqual(["/compact revised focus"]); // flipped command appended to the lane end
+ await session.abort();
+ await running.catch(() => {});
+ });
+
+ it("resumes suspended queued work after a successful replace", async () => {
+ createSession();
+ const { running } = await blockSession();
+ await session.followUp("f1");
+ await session.abort();
+ await running.catch(() => {});
+ expect(session.isQueuedWorkSuspended).toBe(true);
+ expect(queue().followUp).toEqual(["f1"]); // queue survives abort
+ expect(mutate("followUp", 0, "f1", { type: "replace", text: "f1 edited", lane: "followUp" })).toBe("applied");
+ expect(session.isQueuedWorkSuspended).toBe(false);
+ await session.abort();
+ });
+
+ it("resumes suspended queued work after a successful delete", async () => {
+ createSession();
+ const { running } = await blockSession();
+ await session.followUp("kept");
+ await session.followUp("deleted");
+ await session.abort();
+ await running.catch(() => {});
+ expect(session.isQueuedWorkSuspended).toBe(true);
+ expect(mutate("followUp", 1, "deleted", { type: "delete" })).toBe("applied");
+ expect(session.isQueuedWorkSuspended).toBe(false);
+ expect(queue().followUp).toEqual(["kept"]);
+ await session.abort();
+ });
+
+ it("settles the completion of a deleted promptAndWait turn", async () => {
+ createSession();
+ const { running } = await blockSession();
+ const waiting = session.promptAndWait("waited", { streamingBehavior: "steer" });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(queue().steering).toEqual(["waited"]);
+ expect(mutate("steering", 0, "waited", { type: "delete" })).toBe("applied");
+ await expect(waiting).rejects.toThrow("Queued prompt was deleted before delivery.");
+ await session.abort();
+ await running.catch(() => {});
+ });
+
+ it("rejects replacing an injected custom-message turn but allows deleting it", async () => {
+ createSession();
+ const { running } = await blockSession();
+ const injected = (
+ session as unknown as {
+ _promptInjectedMessage(
+ text: string,
+ message: unknown,
+ options?: { streamingBehavior?: "steer" },
+ ): Promise<void>;
+ }
+ )._promptInjectedMessage(
+ "injected",
+ { role: "custom", customType: "test", content: "injected", display: true, timestamp: Date.now() },
+ { streamingBehavior: "steer" },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ const [expected] = queue().steering;
+ expect(expected).toBeDefined();
+ expect(mutate("steering", 0, expected!, { type: "replace", text: "rewritten", lane: "steering" })).toBe(
+ "rejected",
+ );
+ expect(mutate("steering", 0, expected!, { type: "delete" })).toBe("applied");
+ await session.abort();
+ await Promise.allSettled([running, injected]);
+ });
+
+ it("updates the wake policy when flipping lanes", async () => {
+ createSession();
+ const { running } = await blockSession();
+ await session.followUp("f1");
+ expect(mutate("followUp", 0, "f1", { type: "replace", text: "f1", lane: "steering" })).toBe("applied");
+ const recovered = session.getSessionActionRecoverySnapshot().actions.find((a) => a.payload.text === "f1");
+ expect(recovered?.delivery).toBe("next_turn_boundary");
+ expect(recovered?.wake).toBe("on_lower_boundary");
+ await session.abort();
+ await running.catch(() => {});
+ });
+});
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index e8e6aed07b..fe278efdbd 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -8299,6 +8299,36 @@ describe("daemon mode helpers", () => {
});
});
+ it("routes queued message mutation to the active session", async () => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const mutateQueuedMessage = vi.fn(() => "applied" as const);
+ const state = makeState("active-1") as ActiveSessionState;
+ (state.runtime as { session: unknown }).session = { mutateQueuedMessage };
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ internals.sessions.set(state.activeSessionId, state);
+ const client = makeClient("client-1", state.activeSessionId);
+ const mutation = { type: "replace", text: "edited", lane: "followUp" } as const;
+ await expect(
+ internals.handleCommand(client, {
+ type: "mutate_queued_message",
+ activeSessionId: state.activeSessionId,
+ lane: "followUp",
+ index: 0,
+ expectedText: "edited",
+ mutation,
+ }),
+ ).resolves.toMatchObject({ success: true, data: { status: "applied" } });
+ expect(mutateQueuedMessage).toHaveBeenCalledWith("followUp", 0, "edited", mutation);
+ });
+
it("gets and sets RLM max depth directly on the active session", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index 4cf1e4c186..9781b474c8 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -84,6 +84,15 @@ describe("daemon protocol helpers", () => {
expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("model_catalog");
});
+ it("capability- and schema-gates queued message mutation at its introducing revision", () => {
+ expect(DAEMON_COMMAND_COMPATIBILITY.mutate_queued_message).toEqual({
+ minProtocol: 7,
+ minSchemaRevision: 15,
+ capability: "queue_message_mutation",
+ });
+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("queue_message_mutation");
+ });
+
it("schema-gates the RLM max depth commands at their introducing revision", () => {
expect(DAEMON_COMMAND_COMPATIBILITY.get_rlm_max_depth_status).toEqual({ minProtocol: 7, minSchemaRevision: 11 });
expect(DAEMON_COMMAND_COMPATIBILITY.set_rlm_max_depth).toEqual({ minProtocol: 7, minSchemaRevision: 11 });
diff --git a/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts b/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
index eaf202397c..21fa99890e 100644
--- a/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
+++ b/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
@@ -38,13 +38,15 @@ type FakeInteractiveMode = {
};
subagentSummaryLine: { invalidate: Mock };
ui: { requestRender: Mock; onDebug?: () => void };
- restoreQueuedMessagesToEditor: Mock;
updatePendingMessagesDisplay: Mock;
+ showError: Mock;
showTreeSelector: Mock;
shutdown: Mock;
updateEditorBorderColor: Mock;
+ queueSelection: { isBrowsing: boolean; reset: () => string };
defaultEditor?: {
onAction: Mock;
+ getHeaderLine?: () => string | undefined;
onEscape?: () => void;
onCtrlD?: () => void;
onPasteImage?: () => void;
@@ -108,8 +110,9 @@ function createInteractiveFake(options: {
},
subagentSummaryLine: { invalidate: vi.fn() },
ui: { requestRender: vi.fn() },
- restoreQueuedMessagesToEditor: vi.fn().mockResolvedValue(0),
+ queueSelection: { isBrowsing: false, reset: () => "" },
updatePendingMessagesDisplay: vi.fn(),
+ showError: vi.fn(),
showTreeSelector: vi.fn(),
shutdown: vi.fn().mockResolvedValue(undefined),
updateEditorBorderColor: vi.fn(),
@@ -135,7 +138,7 @@ describe("InteractiveMode interrupt shortcuts", () => {
Reflect.get(InteractiveMode.prototype, "handleCtrlC").call(mode);
- expect(mode.restoreQueuedMessagesToEditor).toHaveBeenCalledWith({ abort: true });
+ expect(mode.agentConnection.abort).toHaveBeenCalledTimes(1);
expect(mode.shutdown).not.toHaveBeenCalled();
expect(Reflect.get(InteractiveMode.prototype, "getTrayOverrideLabel").call(mode)).toBe(
"Press Ctrl+C again to exit",
@@ -148,7 +151,7 @@ describe("InteractiveMode interrupt shortcuts", () => {
Reflect.get(InteractiveMode.prototype, "handleCtrlC").call(mode);
expect(mode.agentConnection.abortBash).toHaveBeenCalledTimes(1);
- expect(mode.restoreQueuedMessagesToEditor).toHaveBeenCalledWith({ abort: true });
+ expect(mode.agentConnection.abort).toHaveBeenCalledTimes(1);
expect(mode.shutdown).not.toHaveBeenCalled();
});
@@ -167,21 +170,17 @@ describe("InteractiveMode interrupt shortcuts", () => {
expect(mode.shutdown).not.toHaveBeenCalled();
});
- it("restores queued messages through the atomic abort-and-clear path", async () => {
- const mode = createInteractiveFake({ editorText: "draft" });
- mode.agentConnection.abortAndClearQueue.mockResolvedValue({
- steering: ["steer"],
- followUp: ["follow"],
- });
+ it("preserves the queue and the draft when interrupting streaming", () => {
+ const mode = createInteractiveFake({ editorText: "draft", streaming: true });
+ mode.connectionQueue = { steering: ["steer"], followUp: ["follow"] };
- const restoreQueuedMessagesToEditor = Reflect.get(InteractiveMode.prototype, "restoreQueuedMessagesToEditor");
- const restored = await restoreQueuedMessagesToEditor.call(mode, { abort: true });
+ Reflect.get(InteractiveMode.prototype, "handleCtrlC").call(mode);
- expect(restored).toBe(2);
- expect(mode.agentConnection.abortAndClearQueue).toHaveBeenCalledTimes(1);
+ expect(mode.agentConnection.abort).toHaveBeenCalledTimes(1);
+ expect(mode.agentConnection.abortAndClearQueue).not.toHaveBeenCalled();
expect(mode.agentConnection.clearQueue).not.toHaveBeenCalled();
- expect(mode.agentConnection.abort).not.toHaveBeenCalled();
- expect(mode.editor.getText()).toBe("steer\n\nfollow\n\ndraft");
+ expect(mode.editor.getText()).toBe("draft");
+ expect(mode.connectionQueue).toEqual({ steering: ["steer"], followUp: ["follow"] });
});
it("exits on the second Ctrl+C while the hint is visible", () => {
@@ -191,7 +190,7 @@ describe("InteractiveMode interrupt shortcuts", () => {
handleCtrlC.call(mode);
handleCtrlC.call(mode);
- expect(mode.restoreQueuedMessagesToEditor).toHaveBeenCalledTimes(1);
+ expect(mode.agentConnection.abort).toHaveBeenCalledTimes(1);
expect(mode.shutdown).toHaveBeenCalledTimes(1);
});
@@ -217,7 +216,7 @@ describe("InteractiveMode interrupt shortcuts", () => {
Reflect.get(InteractiveMode.prototype, "handleCtrlC").call(mode);
expect(mode.editor.getText()).toBe("draft");
- expect(mode.restoreQueuedMessagesToEditor).not.toHaveBeenCalled();
+ expect(mode.agentConnection.abort).not.toHaveBeenCalled();
expect(mode.shutdown).not.toHaveBeenCalled();
});
@@ -238,7 +237,7 @@ describe("InteractiveMode interrupt shortcuts", () => {
Reflect.get(InteractiveMode.prototype, "setupKeyHandlers").call(mode);
expect(defaultEditor.onEscape).toBeDefined();
defaultEditor.onEscape?.();
- expect(mode.restoreQueuedMessagesToEditor).toHaveBeenCalledWith({ abort: true });
+ expect(mode.agentConnection.abort).toHaveBeenCalledTimes(1);
expect(mode.editor.getText()).toBe("draft");
mode.editor.setText("queued draft");
defaultEditor.onChange?.("queued draft");
@@ -249,7 +248,7 @@ describe("InteractiveMode interrupt shortcuts", () => {
expect(mode.shutdown).not.toHaveBeenCalled();
});
- it("preserves the tree repeat while restoring queued messages", async () => {
+ it("preserves the tree repeat while browsing into a queued message", () => {
const mode = createInteractiveFake({});
const defaultEditor: NonNullable<FakeInteractiveMode["defaultEditor"]> = {
onAction: vi.fn(),
@@ -258,6 +257,7 @@ describe("InteractiveMode interrupt shortcuts", () => {
defaultEditor,
keybindings: new KeybindingsManager(),
handleDebugCommand: vi.fn(),
+ isApplyingQueueSelectionText: false,
});
Reflect.get(InteractiveMode.prototype, "setupKeyHandlers").call(mode);
const setText = mode.editor.setText.bind(mode.editor);
@@ -267,11 +267,10 @@ describe("InteractiveMode interrupt shortcuts", () => {
};
mode.escapeRepeatAction = "tree";
mode.escapeRepeatExpiresAt = Date.now() + 500;
- mode.agentConnection.abortAndClearQueue.mockResolvedValue({ steering: ["queued"], followUp: [] });
- const restoreQueuedMessagesToEditor = Reflect.get(InteractiveMode.prototype, "restoreQueuedMessagesToEditor");
- await restoreQueuedMessagesToEditor.call(mode, { abort: true });
+ Reflect.get(InteractiveMode.prototype, "setEditorTextFromQueueSelection").call(mode, "queued item");
+ expect(mode.editor.getText()).toBe("queued item");
expect(mode.escapeRepeatAction).toBe("tree");
});
@@ -296,7 +295,7 @@ describe("InteractiveMode interrupt shortcuts", () => {
defaultEditor.onEscape?.();
expect(mode.editor.getText()).toBe("");
- expect(mode.restoreQueuedMessagesToEditor).not.toHaveBeenCalled();
+ expect(mode.agentConnection.abort).not.toHaveBeenCalled();
});
it("opens the tree on double Escape with an empty idle prompt", () => {
diff --git a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
index 4ca90388aa..c2443d1362 100644
--- a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
+++ b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, type Mock, vi } from "vitest";
import { KeybindingsManager } from "../src/core/keybindings.js";
import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
import { ClientPromptStashStore, type PromptStashState } from "../src/modes/interactive/prompt-stash-state.js";
+import { QueueSelection } from "../src/modes/interactive/queue-selection.js";
type FakePasteSnapshot = {
pastes: readonly (readonly [number, string])[];
@@ -55,6 +56,7 @@ type SharedPromptStashHarness = PromptStashHarness & {
};
type ResetHarness = PromptStashLiveMarkerHarness & {
+ queueSelection: QueueSelection;
chatContainer: { clear: Mock };
shortcutGuideContainer: { clear: Mock };
pendingMessagesContainer: { clear: Mock };
@@ -539,6 +541,7 @@ describe("InteractiveMode prompt stash", () => {
const mode: ResetHarness = {
...base,
defaultEditor: base.editor,
+ queueSelection: new QueueSelection(),
connectionQueue: { steering: ["old [image #2]"], followUp: [] },
chatContainer: { clear: vi.fn() },
shortcutGuideContainer: { clear: vi.fn() },
@@ -577,6 +580,7 @@ describe("InteractiveMode prompt stash", () => {
const mode: ResetHarness = {
...base,
defaultEditor: base.editor,
+ queueSelection: new QueueSelection(),
connectionQueue: { steering: [], followUp: [] },
chatContainer: { clear: vi.fn() },
shortcutGuideContainer: { clear: vi.fn() },
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index c2acc7aa7f..71081920ce 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -49,6 +49,7 @@ import type { AuthSelectorProvider } from "../src/modes/interactive/components/o
import type { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";
import { formatSplashCwd, InteractiveMode, truncatePathMiddle } from "../src/modes/interactive/interactive-mode.js";
import { ClientPromptStashStore, type PromptStashState } from "../src/modes/interactive/prompt-stash-state.js";
+import { QueueSelection } from "../src/modes/interactive/queue-selection.js";
import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";
function renderLastLine(container: Container, width = 120): string {
@@ -1125,8 +1126,11 @@ describe("InteractiveMode pending bash components", () => {
const editorStub = { clearHistory: vi.fn(), setText: vi.fn() };
const endFeatureHintRun = vi.fn();
+ const queueSelection = new QueueSelection();
+ queueSelection.move({ steering: ["s1"], followUp: [] }, "draft", -1);
const fakeThis = {
endFeatureHintRun,
+ queueSelection,
chatContainer: new Container(),
shortcutGuideContainer: new Container(),
pendingMessagesContainer: new Container(),
@@ -1159,6 +1163,10 @@ describe("InteractiveMode pending bash components", () => {
expect(loader.intervalId).toBeNull();
expect(endFeatureHintRun).toHaveBeenCalledOnce();
expect((fakeThis as unknown as { activeBashComponent: unknown }).activeBashComponent).toBeUndefined();
+ // Queue browsing is session-scoped: Enter in the next session must be a
+ // fresh prompt, and the previous session's stashed draft is discarded.
+ expect(queueSelection.isBrowsing).toBe(false);
+ expect(queueSelection.reset()).toBe("");
});
});
diff --git a/packages/coding-agent/test/interactive-queue-edit.test.ts b/packages/coding-agent/test/interactive-queue-edit.test.ts
new file mode 100644
index 0000000000..b53b21c975
--- /dev/null
+++ b/packages/coding-agent/test/interactive-queue-edit.test.ts
@@ -0,0 +1,453 @@
+import { describe, expect, it, vi } from "vitest";
+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+import { QueueSelection } from "../src/modes/interactive/queue-selection.js";
+
+type Harness = {
+ queueSelection: QueueSelection;
+ connectionQueue: { steering: string[]; followUp: string[] };
+ editor: { getText: () => string; setText: (text: string) => void; addToHistory?: (text: string) => void };
+ isApplyingQueueSelectionText: boolean;
+ pastedImages: Map<number, unknown>;
+ updatePendingMessagesDisplay: () => void;
+ showStatus: (message: string) => void;
+ showError: (message: string) => void;
+ ui: { requestRender: () => void };
+ agentConnection: {
+ mutateQueuedMessage: ReturnType<typeof vi.fn>;
+ getQueue: ReturnType<typeof vi.fn>;
+ abort?: ReturnType<typeof vi.fn>;
+ };
+ sessionEventGeneration: number;
+ inputSubmissionGeneration: number;
+ pendingQueueEdit: symbol | undefined;
+ queueMutationChain: Promise<void>;
+ enqueueQueueMutation: <T>(run: () => Promise<T>) => Promise<T>;
+ applyQueueSelection: (text: string, targetLane: "steering" | "followUp") => Promise<boolean>;
+ browseQueueSelection: (direction: -1 | 1) => void;
+ moveQueueSelection: (direction: -1 | 1) => void;
+ refreshConnectionQueue: () => Promise<void>;
+ replaceConnectionQueue: (queue: { steering: string[]; followUp: string[] }) => void;
+ setEditorTextFromQueueSelection: (text: string) => void;
+ collectQueueReplaceImages: (text: string) => unknown;
+};
+
+const proto = InteractiveMode.prototype as unknown as Record<string, (...args: unknown[]) => unknown>;
+
+function createHarness(queue: { steering: string[]; followUp: string[] }, mutateResult = "applied"): Harness {
+ let editorText = "";
+ const harness = {
+ queueSelection: new QueueSelection(),
+ connectionQueue: queue,
+ editor: {
+ getText: () => editorText,
+ setText: (text: string) => {
+ editorText = text;
+ },
+ addToHistory: vi.fn(),
+ },
+ isApplyingQueueSelectionText: false,
+ pastedImages: new Map(),
+ updatePendingMessagesDisplay: vi.fn(),
+ showStatus: vi.fn(),
+ showError: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ agentConnection: {
+ mutateQueuedMessage: vi.fn(async () => mutateResult),
+ getQueue: vi.fn(async () => ({ steering: [], followUp: [] })),
+ abort: vi.fn(async () => {}),
+ },
+ sessionEventGeneration: 0,
+ inputSubmissionGeneration: 0,
+ pendingQueueEdit: undefined,
+ queueMutationChain: Promise.resolve(),
+ enqueueQueueMutation: proto.enqueueQueueMutation,
+ applyQueueSelection: proto.applyQueueSelection,
+ browseQueueSelection: proto.browseQueueSelection,
+ moveQueueSelection: proto.moveQueueSelection,
+ refreshConnectionQueue: proto.refreshConnectionQueue,
+ replaceConnectionQueue: proto.replaceConnectionQueue,
+ setEditorTextFromQueueSelection: proto.setEditorTextFromQueueSelection,
+ collectQueueReplaceImages: proto.collectQueueReplaceImages,
+ } as unknown as Harness;
+ return harness;
+}
+
+describe("interactive queued-message editing", () => {
+ it("browses into the queue and applies an enter edit as steering", async () => {
+ const harness = createHarness({ steering: ["s1"], followUp: ["f1"] });
+ harness.editor.setText("draft");
+ harness.browseQueueSelection(-1);
+ expect(harness.editor.getText()).toBe("f1");
+
+ const consumed = await harness.applyQueueSelection("f1 edited", "steering");
+ expect(consumed).toBe(true);
+ expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenCalledWith("followUp", 0, "f1", {
+ type: "replace",
+ text: "f1 edited",
+ images: [],
+ lane: "steering",
+ });
+ expect(harness.editor.getText()).toBe("draft"); // draft restored after apply
+ expect(harness.editor.addToHistory).toHaveBeenCalledWith("f1 edited");
+ });
+
+ it("applies an alt+enter edit to the follow-up lane and deletes on empty text", async () => {
+ const harness = createHarness({ steering: ["s1"], followUp: [] });
+ harness.browseQueueSelection(-1);
+ await harness.applyQueueSelection("kept follow-up", "followUp");
+ expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenCalledWith("steering", 0, "s1", {
+ type: "replace",
+ text: "kept follow-up",
+ images: [],
+ lane: "followUp",
+ });
+
+ harness.connectionQueue = { steering: ["s1"], followUp: [] };
+ harness.browseQueueSelection(-1);
+ await harness.applyQueueSelection(" ", "steering");
+ expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenLastCalledWith("steering", 0, "s1", {
+ type: "delete",
+ });
+ });
+
+ it("restores the edited text when the mutation is rejected after enter cleared the editor", async () => {
+ const harness = createHarness({ steering: ["s1"], followUp: [] }, "rejected");
+ harness.editor.setText("draft");
+ harness.browseQueueSelection(-1);
+ harness.editor.setText(""); // Editor.submitValue clears before onSubmit runs.
+ await harness.applyQueueSelection("s1 edited", "steering");
+ expect(harness.editor.getText()).toBe("s1 edited");
+ expect(harness.showStatus).toHaveBeenCalledWith("Queue changed; edit kept in the editor");
+ });
+
+ it("reports when the daemon does not support queue editing", async () => {
+ const harness = createHarness({ steering: ["s1"], followUp: [] }, "unsupported");
+ harness.browseQueueSelection(-1);
+ await harness.applyQueueSelection("s1 edited", "steering");
+ expect(harness.showStatus).toHaveBeenCalledWith("Queue editing requires a newer daemon");
+ });
+
+ it("does not consume submissions when nothing is selected", async () => {
+ const harness = createHarness({ steering: [], followUp: [] });
+ expect(await harness.applyQueueSelection("new prompt", "steering")).toBe(false);
+ expect(harness.agentConnection.mutateQueuedMessage).not.toHaveBeenCalled();
+ });
+
+ it("moves the selected item within its lane", async () => {
+ const harness = createHarness({ steering: ["s1", "s2"], followUp: [] });
+ harness.browseQueueSelection(-1);
+ harness.moveQueueSelection(-1);
+ await vi.waitFor(() =>
+ expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenCalledWith("steering", 1, "s2", {
+ type: "move",
+ direction: -1,
+ }),
+ );
+ });
+
+ it("does not clobber typing that happened while the mutation was in flight", async () => {
+ let resolveMutation: (status: string) => void = () => {};
+ const harness = createHarness({ steering: ["s1"], followUp: [] });
+ harness.agentConnection.mutateQueuedMessage.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveMutation = resolve;
+ }),
+ );
+ harness.editor.setText("draft");
+ harness.browseQueueSelection(-1);
+ harness.editor.setText(""); // Enter cleared the editor
+ const pending = harness.applyQueueSelection("s1 edited", "steering");
+ await vi.waitFor(() => expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenCalled());
+ harness.editor.setText("newer typing");
+ resolveMutation("rejected");
+ await pending;
+ expect(harness.editor.getText()).toBe("newer typing");
+ });
+
+ it.each([
+ ["replace", "queued edited"],
+ ["delete", " "],
+ ])("restores the stashed draft when a %s queue event lands before the response", async (_operation, text) => {
+ let resolveMutation: (status: string) => void = () => {};
+ const harness = createHarness({ steering: ["queued"], followUp: [] });
+ harness.agentConnection.mutateQueuedMessage.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveMutation = resolve;
+ }),
+ );
+ harness.editor.setText("draft");
+ harness.browseQueueSelection(-1);
+ harness.editor.setText("");
+ const pending = harness.applyQueueSelection(text, "steering");
+ await vi.waitFor(() => expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenCalledOnce());
+
+ harness.replaceConnectionQueue({
+ steering: text.trim() ? [text.trim()] : [],
+ followUp: [],
+ });
+ resolveMutation("applied");
+ await pending;
+
+ expect(harness.editor.getText()).toBe("draft");
+ });
+
+ it("routes another submission as new while a queue edit is pending", async () => {
+ let resolveMutation: (status: string) => void = () => {};
+ const harness = createHarness({ steering: ["queued"], followUp: [] });
+ harness.agentConnection.mutateQueuedMessage.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveMutation = resolve;
+ }),
+ );
+ harness.browseQueueSelection(-1);
+ harness.editor.setText("");
+ const pending = harness.applyQueueSelection("edited", "steering");
+ expect(harness.queueSelection.isBrowsing).toBe(true);
+ await expect(harness.applyQueueSelection("new prompt", "steering")).resolves.toBe(false);
+ harness.inputSubmissionGeneration++;
+ harness.editor.setText("");
+ resolveMutation("applied");
+ await pending;
+ expect(harness.editor.getText()).toBe("");
+ });
+
+ it.each(["rejected", "invalid", "unsupported"])(
+ "keeps the selection and stashed draft when a queue edit is %s",
+ async (status) => {
+ const harness = createHarness({ steering: ["queued"], followUp: [] }, status);
+ harness.editor.setText("draft");
+ harness.browseQueueSelection(-1);
+ harness.editor.setText("");
+
+ await harness.applyQueueSelection("edited", "steering");
+
+ expect(harness.queueSelection.selected).toEqual({ lane: "steering", index: 0, text: "queued" });
+ expect(harness.queueSelection.hasDraft).toBe(true);
+ expect(harness.editor.getText()).toBe("edited");
+ },
+ );
+
+ it("keeps the selection and stashed draft when a queue edit request fails", async () => {
+ const harness = createHarness({ steering: ["queued"], followUp: [] });
+ harness.agentConnection.mutateQueuedMessage.mockRejectedValue(new Error("connection lost"));
+ harness.editor.setText("draft");
+ harness.browseQueueSelection(-1);
+ harness.editor.setText("");
+
+ await expect(harness.applyQueueSelection("edited", "steering")).rejects.toThrow("connection lost");
+
+ expect(harness.queueSelection.selected).toEqual({ lane: "steering", index: 0, text: "queued" });
+ expect(harness.queueSelection.hasDraft).toBe(true);
+ expect(harness.editor.getText()).toBe("edited");
+ });
+
+ it("restores the submitted edit when its queue item vanishes before the mutation starts", async () => {
+ let releaseMutationChain: () => void = () => {};
+ const harness = createHarness({ steering: ["queued"], followUp: [] });
+ harness.queueMutationChain = new Promise<void>((resolve) => {
+ releaseMutationChain = resolve;
+ });
+ harness.editor.setText("draft");
+ harness.browseQueueSelection(-1);
+ harness.editor.setText("");
+ const pending = harness.applyQueueSelection("edited", "steering");
+ harness.replaceConnectionQueue({ steering: ["remaining"], followUp: [] });
+ releaseMutationChain();
+ await pending;
+ expect(harness.agentConnection.mutateQueuedMessage).not.toHaveBeenCalled();
+ expect(harness.editor.getText()).toBe("edited");
+ expect(harness.queueSelection.hasDraft).toBe(true);
+ expect(harness.showStatus).toHaveBeenCalledWith("Queue changed; edit kept in the editor");
+
+ harness.browseQueueSelection(-1);
+ expect(harness.editor.getText()).toBe("remaining");
+ harness.browseQueueSelection(1);
+ expect(harness.editor.getText()).toBe("edited");
+ });
+
+ it("does not reset queue browsing in a replacement session when an old mutation completes", async () => {
+ let resolveMutation: (status: string) => void = () => {};
+ const harness = createHarness({ steering: ["old queued"], followUp: [] });
+ harness.agentConnection.mutateQueuedMessage.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveMutation = resolve;
+ }),
+ );
+ harness.editor.setText("old draft");
+ harness.browseQueueSelection(-1);
+ harness.editor.setText(""); // Enter cleared the old session's editor.
+ const pending = harness.applyQueueSelection("old edited", "steering");
+ await vi.waitFor(() => expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenCalled());
+
+ // A session replacement resets queue state, then the user starts browsing
+ // the replacement session before the old daemon response arrives.
+ harness.sessionEventGeneration++;
+ harness.pendingQueueEdit = undefined;
+ harness.queueSelection.reset();
+ harness.connectionQueue = { steering: ["new queued"], followUp: [] };
+ harness.editor.setText("new draft");
+ harness.browseQueueSelection(-1);
+
+ resolveMutation("applied");
+ await pending;
+ expect(harness.queueSelection.selected).toEqual({ lane: "steering", index: 0, text: "new queued" });
+ expect(harness.editor.getText()).toBe("new queued");
+ });
+
+ it("discards an old queue selection when the session changes before its mutation completes", async () => {
+ let resolveMutation: (status: string) => void = () => {};
+ const harness = createHarness({ steering: ["old queued"], followUp: [] });
+ harness.agentConnection.mutateQueuedMessage.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveMutation = resolve;
+ }),
+ );
+ harness.browseQueueSelection(-1);
+ harness.editor.setText("");
+ const pending = harness.applyQueueSelection("old edited", "steering");
+ await vi.waitFor(() => expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenCalledOnce());
+
+ // session_replaced advances the generation before its queued render reset.
+ harness.sessionEventGeneration++;
+ resolveMutation("applied");
+ await pending;
+
+ expect(harness.pendingQueueEdit).toBeUndefined();
+ expect(harness.queueSelection.isBrowsing).toBe(false);
+ await expect(harness.applyQueueSelection("new session prompt", "steering")).resolves.toBe(false);
+ expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenCalledOnce();
+ });
+
+ it("serializes rapid moves and addresses the second with the post-move index before any queue event", async () => {
+ // The daemon's session_action_update can arrive after the mutation response,
+ // so the local mirror must be updated optimistically between chained moves.
+ const harness = createHarness({ steering: ["s1", "s2", "s3"], followUp: [] });
+ harness.browseQueueSelection(-1); // s3 at index 2
+ harness.moveQueueSelection(-1);
+ harness.moveQueueSelection(-1);
+ await harness.queueMutationChain;
+ expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenNthCalledWith(1, "steering", 2, "s3", {
+ type: "move",
+ direction: -1,
+ });
+ expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenNthCalledWith(2, "steering", 1, "s3", {
+ type: "move",
+ direction: -1,
+ });
+ expect(harness.connectionQueue.steering).toEqual(["s3", "s1", "s2"]);
+ });
+
+ it("preserves a queued reorder when an edit immediately exits browse mode", async () => {
+ const harness = createHarness({ steering: ["s1", "s2"], followUp: [] });
+ harness.browseQueueSelection(-1);
+ harness.moveQueueSelection(-1);
+ const edited = harness.applyQueueSelection("s2 edited", "steering");
+ await harness.queueMutationChain;
+ await edited;
+
+ expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenNthCalledWith(1, "steering", 1, "s2", {
+ type: "move",
+ direction: -1,
+ });
+ expect(harness.agentConnection.mutateQueuedMessage).toHaveBeenNthCalledWith(2, "steering", 0, "s2", {
+ type: "replace",
+ text: "s2 edited",
+ images: [],
+ lane: "steering",
+ });
+ });
+
+ it("optimistically updates the local queue mirror on replace and delete", async () => {
+ const harness = createHarness({ steering: ["s1", "s2"], followUp: ["f1"] });
+ harness.browseQueueSelection(-1); // f1
+ await harness.applyQueueSelection("f1 edited", "followUp");
+ // An immediate browse must see the new text before the queue event arrives.
+ expect(harness.connectionQueue).toEqual({ steering: ["s1", "s2"], followUp: ["f1 edited"] });
+
+ harness.browseQueueSelection(-1); // f1 edited
+ await harness.applyQueueSelection(" ", "followUp");
+ expect(harness.connectionQueue).toEqual({ steering: ["s1", "s2"], followUp: [] });
+ });
+
+ it("does not double-apply a delete when the queue event lands before the response", async () => {
+ const harness = createHarness({ steering: [], followUp: ["dup", "dup"] });
+ harness.agentConnection.mutateQueuedMessage.mockImplementation(async () => {
+ // The server's session_action_update arrives before the response
+ // resolves: the mirror is replaced and the selection retargets to
+ // the remaining same-text item.
+ harness.connectionQueue = { steering: [], followUp: ["dup"] };
+ harness.queueSelection.sync(harness.connectionQueue);
+ return "applied";
+ });
+ harness.browseQueueSelection(-1); // dup at followUp index 1
+ await harness.applyQueueSelection(" ", "followUp");
+ expect(harness.connectionQueue).toEqual({ steering: [], followUp: ["dup"] });
+ });
+
+ it("moves the item across lanes in the local mirror on a lane-changing replace", async () => {
+ const harness = createHarness({ steering: ["s1"], followUp: [] });
+ harness.browseQueueSelection(-1); // s1
+ await harness.applyQueueSelection("now follow-up", "followUp");
+ expect(harness.connectionQueue).toEqual({ steering: [], followUp: ["now follow-up"] });
+ });
+
+ it("restores the stashed draft when the browsed item is consumed externally", () => {
+ const harness = createHarness({ steering: [], followUp: ["f1"] });
+ harness.editor.setText("draft");
+ harness.browseQueueSelection(-1);
+ expect(harness.editor.getText()).toBe("f1");
+ // The item is delivered: the queue update drops the selection.
+ harness.connectionQueue = { steering: [], followUp: [] };
+ const dropped = harness.queueSelection.sync(harness.connectionQueue);
+ expect(dropped).toBe("f1");
+ if (dropped !== undefined && harness.editor.getText() === dropped) {
+ harness.setEditorTextFromQueueSelection(harness.queueSelection.reset());
+ }
+ expect(harness.editor.getText()).toBe("draft");
+ });
+
+ it("synchronizes queue browsing when a reconnect refresh replaces the queue", async () => {
+ const harness = createHarness({ steering: [], followUp: ["queued"] });
+ harness.editor.setText("draft");
+ harness.browseQueueSelection(-1);
+ harness.agentConnection.getQueue.mockResolvedValue({ steering: [], followUp: [] });
+
+ await harness.refreshConnectionQueue();
+
+ expect(harness.queueSelection.isBrowsing).toBe(false);
+ expect(harness.editor.getText()).toBe("draft");
+ });
+
+ it("deduplicates repeated image markers in a replace", () => {
+ const harness = createHarness({ steering: [], followUp: [] });
+ harness.pastedImages.set(1, { type: "image", data: "a", mimeType: "image/png" });
+ expect(harness.collectQueueReplaceImages("[image #1] and again [image #1]")).toEqual([
+ { type: "image", data: "a", mimeType: "image/png" },
+ ]);
+ });
+});
+
+describe("interactive interrupt preserves the queue", () => {
+ it("aborts without clearing or restoring queued messages", () => {
+ const abort = vi.fn(async () => {});
+ const harness = {
+ traceUploadAllAbortController: undefined,
+ sideQuestionEvent: undefined,
+ getRetryAttempt: () => 0,
+ isAgentCompacting: () => false,
+ isBashRunning: () => false,
+ isAgentStreaming: () => true,
+ agentConnection: { abort },
+ showError: vi.fn(),
+ editor: { getText: () => "", setText: vi.fn() },
+ };
+ (proto.interruptOrClearInput as (this: unknown) => void).call(harness);
+ expect(abort).toHaveBeenCalledOnce();
+ expect(harness.editor.setText).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/coding-agent/test/keybindings-migration.test.ts b/packages/coding-agent/test/keybindings-migration.test.ts
index ef0e257586..b94f5208b0 100644
--- a/packages/coding-agent/test/keybindings-migration.test.ts
+++ b/packages/coding-agent/test/keybindings-migration.test.ts
@@ -26,6 +26,7 @@ describe("keybindings migration", () => {
const agentDir = createAgentDir({
cursorUp: ["up", "ctrl+p"],
expandTools: "ctrl+x",
+ "app.message.dequeue": "alt+u",
});
const previousAgentDir = process.env[ENV_AGENT_DIR];
process.env[ENV_AGENT_DIR] = agentDir;
@@ -43,6 +44,7 @@ describe("keybindings migration", () => {
expect(migrated).toEqual({
"tui.editor.cursorUp": ["up", "ctrl+p"],
"app.tools.expand": "ctrl+x",
+ "app.message.navigateOlder": "alt+u",
});
});
diff --git a/packages/coding-agent/test/queue-selection.test.ts b/packages/coding-agent/test/queue-selection.test.ts
new file mode 100644
index 0000000000..c45d453bdd
--- /dev/null
+++ b/packages/coding-agent/test/queue-selection.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+import { QueueSelection } from "../src/modes/interactive/queue-selection.js";
+
+const queue = { steering: ["s1", "s2"], followUp: ["f1", "f2"] };
+
+describe("QueueSelection", () => {
+ it("browses newest-first from the draft and back", () => {
+ const selection = new QueueSelection();
+ expect(selection.move(queue, "draft", 1)).toBeUndefined();
+ expect(selection.move(queue, "draft", -1)).toBe("f2");
+ expect(selection.selected).toEqual({ lane: "followUp", index: 1, text: "f2" });
+ expect(selection.move(queue, "", -1)).toBe("f1");
+ expect(selection.move(queue, "", -1)).toBe("s2");
+ expect(selection.move(queue, "", -1)).toBe("s1");
+ expect(selection.move(queue, "", -1)).toBeUndefined();
+ expect(selection.selected).toEqual({ lane: "steering", index: 0, text: "s1" });
+ for (const expected of ["s2", "f1", "f2", "draft"]) {
+ expect(selection.move(queue, "", 1)).toBe(expected);
+ }
+ expect(selection.isBrowsing).toBe(false);
+ });
+
+ it("does not enter browse mode when the queue is empty", () => {
+ const selection = new QueueSelection();
+ expect(selection.move({ steering: [], followUp: [] }, "draft", -1)).toBeUndefined();
+ expect(selection.isBrowsing).toBe(false);
+ });
+
+ it("keeps, retargets, or drops the selection when the queue changes", () => {
+ const selection = new QueueSelection();
+ selection.move(queue, "draft", -1);
+ selection.move(queue, "", -1);
+ selection.move(queue, "", -1); // s2
+ expect(selection.sync({ steering: ["s1", "s2"], followUp: ["f2"] })).toBeUndefined();
+ expect(selection.selected).toEqual({ lane: "steering", index: 1, text: "s2" });
+ expect(selection.sync({ steering: ["s0", "s2"], followUp: [] })).toBeUndefined(); // retarget by text
+ expect(selection.selected).toEqual({ lane: "steering", index: 1, text: "s2" });
+ expect(selection.sync({ steering: ["s0"], followUp: ["s2"] })).toBe("s2"); // same text, other lane: drop
+ expect(selection.isBrowsing).toBe(false);
+ });
+
+ it("keeps the stashed draft across an external selection drop", () => {
+ const selection = new QueueSelection();
+ selection.move(queue, "my draft", -1); // editing f2
+ selection.sync({ steering: [], followUp: [] }); // f2 delivered: selection dropped
+ expect(selection.isBrowsing).toBe(false);
+ selection.move({ steering: ["s9"], followUp: [] }, "f2 leftover text", -1);
+ expect(selection.reset()).toBe("my draft");
+ });
+
+ it("reset returns the stashed draft once", () => {
+ const selection = new QueueSelection();
+ selection.move(queue, "my draft", -1);
+ expect(selection.reset()).toBe("my draft");
+ expect(selection.isBrowsing).toBe(false);
+ expect(selection.reset()).toBe("");
+ });
+});
diff --git a/packages/tui/src/keys.ts b/packages/tui/src/keys.ts
index e80f171503..c34801fafc 100644
--- a/packages/tui/src/keys.ts
+++ b/packages/tui/src/keys.ts
@@ -818,6 +818,18 @@ function parseKeyId(
* @param keyId - Key identifier (e.g., "ctrl+c", "escape", Key.ctrl("c"))
*/
export function matchesKey(data: string, keyId: KeyId): boolean {
+ // Legacy macOS terminals encode Option as an extra ESC prefix around the
+ // sequence for the remaining modifiers (for example ESC + Ctrl+Up).
+ if (data.startsWith("\x1b\x1b[") || data.startsWith("\x1b\x1bO")) {
+ const parsedLegacyMeta = parseKeyId(keyId);
+ if (parsedLegacyMeta?.alt) {
+ const withoutAlt = keyId
+ .split("+")
+ .filter((part) => part !== "alt")
+ .join("+") as KeyId;
+ if (matchesKey(data.slice(1), withoutAlt)) return true;
+ }
+ }
const parsed = parseKeyId(keyId);
if (!parsed) return false;
diff --git a/packages/tui/test/keys.test.ts b/packages/tui/test/keys.test.ts
index 42e00e212c..bf3c87e0d6 100644
--- a/packages/tui/test/keys.test.ts
+++ b/packages/tui/test/keys.test.ts
@@ -614,4 +614,28 @@ describe("parseKey", () => {
assert.strictEqual(parseKey("\x1b[[5~"), "pageUp");
});
});
+
+ describe("combined modified arrows", () => {
+ // xterm encodes modifiers as a 1-based parameter: 1 + shift(1) + alt(2) + ctrl(4).
+ // Ctrl+Alt is therefore parameter 7, and parameter 8 is Shift+Ctrl+Alt.
+ it("matches xterm and Kitty Ctrl+Alt arrows", () => {
+ assert.equal(matchesKey("\x1b[1;7A", "ctrl+alt+up"), true);
+ assert.equal(matchesKey("\x1b[1;7B", "ctrl+alt+down"), true);
+ assert.equal(matchesKey("\x1b[57419;7u", "ctrl+alt+up"), true);
+ assert.equal(matchesKey("\x1b[57420;7u", "ctrl+alt+down"), true);
+ });
+
+ it("does not alias Shift+Ctrl+Alt arrows onto Ctrl+Alt", () => {
+ assert.equal(matchesKey("\x1b[1;8A", "shift+ctrl+alt+up"), true);
+ assert.equal(matchesKey("\x1b[1;8A", "ctrl+alt+up"), false);
+ assert.equal(matchesKey("\x1b[1;8B", "ctrl+alt+down"), false);
+ });
+
+ it("matches legacy Option-as-Meta wrapped Ctrl arrows", () => {
+ assert.equal(matchesKey("\x1b\x1b[1;5A", "ctrl+alt+up"), true);
+ assert.equal(matchesKey("\x1b\x1b[1;5B", "ctrl+alt+down"), true);
+ assert.equal(matchesKey("\x1b\x1bOa", "ctrl+alt+up"), true);
+ assert.equal(matchesKey("\x1b\x1bOb", "ctrl+alt+down"), true);
+ });
+ });
});