Skip to content

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

Rust

add prompt stashing for draft prompts (#321)

ktf95226095111
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 9e82366e82..f78b382ac9 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -5,6 +5,7 @@
- Added daemon-backed user orchestration with agent-to-agent messaging and read-only observation of active sessions.
- Added an orchestration heartbeat skill for compact multi-session progress, blocker, and action summaries.
- Added an opt-in auto-refine review hook that can ask whether `/refine` should run after turn intervals or compaction checkpoints.
+- Added prompt stashing so a draft can be temporarily saved, a separate prompt or command can run, and the draft is restored afterward.
## [0.2.4] - 2026-07-01
diff --git a/packages/coding-agent/src/core/keybindings.ts b/packages/coding-agent/src/core/keybindings.ts
index 8d64d60451..c011beb773 100644
--- a/packages/coding-agent/src/core/keybindings.ts
+++ b/packages/coding-agent/src/core/keybindings.ts
@@ -23,6 +23,7 @@ export interface AppKeybindings {
"app.subagents.focus": true;
"app.session.toggleNamedFilter": true;
"app.editor.external": true;
+ "app.prompt.stash": true;
"app.message.followUp": true;
"app.message.dequeue": true;
"app.clipboard.pasteImage": true;
@@ -96,6 +97,10 @@ export const KEYBINDINGS = {
defaultKeys: "ctrl+g",
description: "Open external editor",
},
+ "app.prompt.stash": {
+ defaultKeys: "ctrl+s",
+ description: "Stash or restore draft prompt",
+ },
"app.message.followUp": {
defaultKeys: "alt+enter",
description: "Queue follow-up message",
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 7c9ddd7e4b..176586ac6c 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -21,6 +21,7 @@ import type {
AutocompleteItem,
AutocompleteProvider,
EditorComponent,
+ EditorPasteSnapshot,
Keybinding,
KeyId,
MarkdownTheme,
@@ -200,6 +201,12 @@ interface Expandable {
setExpanded(expanded: boolean): void;
}
+type PromptStash = {
+ text: string;
+ expandedText?: string;
+ pasteSnapshot?: EditorPasteSnapshot;
+};
+
interface PendingToolCallRenderInput {
id: string;
name: string;
@@ -501,6 +508,7 @@ export class InteractiveMode {
private queuedMessagesContainer: Container;
private defaultEditor: CustomEditor;
private editor: EditorComponent;
+ private promptStash: PromptStash | undefined;
private editorComponentFactory: EditorFactory | undefined;
private autocompleteProvider: AutocompleteProvider | undefined;
private autocompleteProviderWrappers: AutocompleteProviderFactory[] = [];
@@ -949,6 +957,7 @@ export class InteractiveMode {
hint("app.thinking.toggle", "to expand thinking"),
hint("app.subagents.focus", "to inspect subagents"),
hint("app.editor.external", "for external editor"),
+ 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"),
@@ -2274,24 +2283,29 @@ export class InteractiveMode {
process.exit(1);
}
- private resetCurrentSessionRenderState(): void {
+ private resetCurrentSessionRenderState(options?: { clearPromptStash?: boolean }): void {
this.chatContainer.clear();
this.pendingMessagesContainer.clear();
this.queuedMessagesContainer.clear();
this.compactionQueuedMessages = [];
- // Pasted images belong to the session being torn down; drop them so markers
- // in a newly loaded session can't resolve to the previous session's bytes.
- // Clear every editor's prompt history and draft text alongside them so no
- // `[image #N]` marker survives without a backing image. nextImageMarkerId
- // stays monotonic so a new paste never reuses an id that may still appear in
- // restored text.
- this.pastedImages.clear();
+ this.connectionQueue = { steering: [], followUp: [] };
+ if (options?.clearPromptStash) {
+ this.promptStash = undefined;
+ }
+ // Clear every editor's prompt history, draft text, and queues, then prune
+ // any pasted images no longer referenced by the remaining stashed draft.
this.defaultEditor.clearHistory?.();
this.defaultEditor.setText("");
if (this.editor !== this.defaultEditor) {
this.editor.clearHistory?.();
this.editor.setText("");
}
+ const keepImageIds = this.liveImageMarkerIds();
+ for (const markerId of this.pastedImages.keys()) {
+ if (!keepImageIds.has(markerId)) {
+ this.pastedImages.delete(markerId);
+ }
+ }
this.streamingComponent = undefined;
this.streamingMessage = undefined;
// The discarded component's loader interval keeps firing otherwise; no
@@ -3362,6 +3376,7 @@ export class InteractiveMode {
this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());
this.defaultEditor.onAction("app.subagents.focus", () => this.focusChildAgentSummary());
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();
@@ -3397,6 +3412,46 @@ export class InteractiveMode {
};
}
+ private handlePromptStash(): void {
+ const text = this.editor.getText();
+ if (!text.trim()) {
+ if (!this.restorePromptStashIfEditorEmpty()) {
+ this.showStatus("No prompt to stash");
+ }
+ return;
+ }
+ if (this.promptStash !== undefined) {
+ this.showStatus("Prompt stash already has a draft");
+ return;
+ }
+ const pasteSnapshot = this.editor.getPasteSnapshot?.();
+ this.promptStash = {
+ text,
+ expandedText: pasteSnapshot ? (this.editor.getExpandedText?.() ?? text) : undefined,
+ pasteSnapshot,
+ };
+ this.editor.setText("");
+ this.showStatus("Stashed prompt");
+ }
+
+ private restorePromptStashIfEditorEmpty(stash = this.promptStash): boolean {
+ if (stash === undefined || this.editor.getText().trim()) {
+ return false;
+ }
+ if (this.promptStash !== stash) {
+ return false;
+ }
+ this.promptStash = undefined;
+ const canRestorePasteSnapshot =
+ stash.pasteSnapshot === undefined || this.editor.restorePasteSnapshot !== undefined;
+ this.editor.setText(canRestorePasteSnapshot ? stash.text : (stash.expandedText ?? stash.text));
+ if (stash.pasteSnapshot && this.editor.restorePasteSnapshot) {
+ this.editor.restorePasteSnapshot(stash.pasteSnapshot);
+ }
+ this.showStatus("Restored stashed prompt");
+ return true;
+ }
+
private async handleClipboardImagePaste(): Promise<void> {
try {
const image = await readClipboardImage();
@@ -3460,6 +3515,9 @@ export class InteractiveMode {
}
};
add(this.editor.getText());
+ if (this.promptStash !== undefined) {
+ add(this.promptStash.text);
+ }
for (const entry of this.editor.getHistory?.() ?? []) {
add(entry);
}
@@ -3496,265 +3554,274 @@ export class InteractiveMode {
this.defaultEditor.onSubmit = async (text: string) => {
text = text.trim();
if (!text) return;
+ const promptStashToRestore = this.promptStash;
- const slashCommand = parseSlashCommand(text);
- const commandName = slashCommand ? resolveBuiltinSlashCommandName(slashCommand.name) : undefined;
- const commandArgs = slashCommand?.args ?? "";
- const canonicalCommandText = commandName ? `/${commandName}${commandArgs ? ` ${commandArgs}` : ""}` : text;
-
- // Handle commands
- if (commandName === "settings" && !commandArgs) {
- await this.showSettingsSelector();
- this.editor.setText("");
- return;
- }
- if (commandName === "scoped-models" && !commandArgs) {
- this.editor.setText("");
- await this.showModelsSelector();
- return;
- }
- if (commandName === "model") {
- const searchTerm = commandArgs || undefined;
- this.editor.setText("");
- await this.handleModelCommand(searchTerm);
- return;
- }
- if (commandName === "effort") {
- this.editor.setText("");
- this.handleEffortCommand(commandArgs);
- return;
- }
- if (commandName === "export") {
- await this.handleExportCommand(canonicalCommandText);
- this.editor.setText("");
- return;
- }
- if (commandName === "import") {
- await this.handleImportCommand(canonicalCommandText);
- this.editor.setText("");
- return;
- }
- if (commandName === "share" && !commandArgs) {
- await this.handleShareCommand();
- this.editor.setText("");
- return;
- }
- if (commandName === "copy" && !commandArgs) {
- await this.handleCopyCommand();
- this.editor.setText("");
- return;
- }
- if (commandName === "name") {
- await this.handleNameCommand(canonicalCommandText);
- this.editor.setText("");
- return;
- }
- if (commandName === "session" && !commandArgs) {
- this.echoLocalCommand(text);
- await this.handleSessionCommand();
- this.editor.setText("");
- return;
- }
- if (commandName === "system-prompt" && !commandArgs) {
- this.echoLocalCommand(text);
- await this.handleSystemPromptCommand();
- this.editor.setText("");
- return;
- }
- if (commandName === "traces") {
- await this.handleTracesCommand(canonicalCommandText);
- this.editor.setText("");
- return;
- }
- if (commandName === "context" && !commandArgs) {
- this.echoLocalCommand(text);
- await this.handleContextCommand();
- this.editor.setText("");
- return;
- }
- if (commandName === "logs" && !commandArgs) {
- this.echoLocalCommand(text);
- this.handleLogsCommand();
- this.editor.setText("");
- return;
- }
- if (commandName === "goal" && (!commandArgs || commandArgs === "status")) {
- this.echoLocalCommand(text);
- this.handleGoalStatusCommand();
- this.editor.setText("");
- return;
- }
- if (commandName === "heartbeat") {
- await this.handleHeartbeatCommand(canonicalCommandText);
- this.editor.setText("");
- return;
- }
- if (commandName === "changelog" && !commandArgs) {
- this.echoLocalCommand(text);
- this.handleChangelogCommand();
- this.editor.setText("");
- return;
- }
- if (commandName === "hotkeys" && !commandArgs) {
- this.echoLocalCommand(text);
- this.handleHotkeysCommand();
- this.editor.setText("");
- return;
- }
- if (commandName === "fork" && !commandArgs) {
- void this.showUserMessageSelector();
- this.editor.setText("");
- return;
- }
- if (commandName === "clone" && !commandArgs) {
- this.editor.setText("");
- await this.handleCloneCommand();
- return;
- }
- if (commandName === "tree" && !commandArgs) {
- void this.showTreeSelector();
- this.editor.setText("");
- return;
- }
- if (commandName === "login" && !commandArgs) {
- this.editor.setText("");
- await this.showOAuthSelector("login");
- return;
- }
- if (commandName === "logout" && !commandArgs) {
- this.editor.setText("");
- await this.showOAuthSelector("logout");
- return;
- }
- if (commandName === "mcp") {
- this.editor.setText("");
- await this.handleMcpCommand(commandArgs);
- return;
- }
- if (commandName === "new" && !commandArgs) {
- this.editor.setText("");
- await this.handleClearCommand();
- return;
- }
- if (commandName === "compact") {
- const customInstructions = commandArgs || undefined;
- this.editor.setText("");
- await this.handleCompactCommand(customInstructions);
- return;
- }
- if (commandName === "refine") {
- const refineArgs = commandArgs || undefined;
- this.editor.setText("");
- await this.handleRefineCommand(refineArgs);
- return;
- }
- if (commandName === "reload" && !commandArgs) {
- this.editor.setText("");
- await this.handleReloadCommand();
- return;
- }
- if (commandName === "fullscreen") {
- this.editor.setText("");
- const arg = commandArgs?.trim().toLowerCase();
- if (arg && arg !== "on" && arg !== "off") {
- this.showError("Usage: /fullscreen [on|off]");
+ try {
+ const slashCommand = parseSlashCommand(text);
+ const commandName = slashCommand ? resolveBuiltinSlashCommandName(slashCommand.name) : undefined;
+ const commandArgs = slashCommand?.args ?? "";
+ const canonicalCommandText = commandName ? `/${commandName}${commandArgs ? ` ${commandArgs}` : ""}` : text;
+
+ // Handle commands
+ if (commandName === "settings" && !commandArgs) {
+ await this.showSettingsSelector();
+ this.editor.setText("");
return;
}
- const enable = arg === "on" ? true : arg === "off" ? false : !this.fullscreenEnabled;
- this.setFullscreenMode(enable);
- return;
- }
- if (commandName === "debug" && !commandArgs) {
- await this.handleDebugCommand();
- this.editor.setText("");
- return;
- }
- if (text === "/arminsayshi") {
- this.handleArminSaysHi();
- this.editor.setText("");
- return;
- }
- if (text === "/dementedelves") {
- this.handleDementedDelves();
- this.editor.setText("");
- return;
- }
- if (text === "/resume") {
- void this.showSessionSelector();
- this.editor.setText("");
- return;
- }
- if (text === "/quit") {
- this.editor.setText("");
- await this.shutdown();
- return;
- }
-
- // Handle bash command (! for normal, !! for excluded from context)
- if (text.startsWith("!")) {
- const isExcluded = text.startsWith("!!");
- const command = isExcluded ? text.slice(2).trim() : text.slice(1).trim();
- if (!command) {
- // Bare ! / !! is bash mode with nothing to run; don't send it as a prompt
+ if (commandName === "scoped-models" && !commandArgs) {
+ this.editor.setText("");
+ await this.showModelsSelector();
return;
}
- if (this.isBashRunning()) {
- this.showWarning(`A bash command is already running. Press ${keyText("app.clear")} to cancel it first.`);
+ if (commandName === "model") {
+ const searchTerm = commandArgs || undefined;
+ this.editor.setText("");
+ await this.handleModelCommand(searchTerm);
return;
}
- this.editor.addToHistory?.(text);
- this.editor.setText("");
- // Optimistic: bash_start only fires after extension dispatch, and the
- // clear key must already route to abortBash in that window.
- this.patchConnectionState({ isBashRunning: true });
- try {
- await this.agentConnection.executeBash(command, { excludeFromContext: isExcluded });
- } catch (error) {
- // Re-sync rather than assume idle: the rejection may mean another
- // client's bash run already holds the slot.
- try {
- const state = await this.agentConnection.getState();
- this.patchConnectionState({ isBashRunning: state.isBashRunning });
- } catch {
- this.patchConnectionState({ isBashRunning: false });
+ if (commandName === "effort") {
+ this.editor.setText("");
+ this.handleEffortCommand(commandArgs);
+ return;
+ }
+ if (commandName === "export") {
+ await this.handleExportCommand(canonicalCommandText);
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "import") {
+ await this.handleImportCommand(canonicalCommandText);
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "share" && !commandArgs) {
+ await this.handleShareCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "copy" && !commandArgs) {
+ await this.handleCopyCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "name") {
+ await this.handleNameCommand(canonicalCommandText);
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "session" && !commandArgs) {
+ this.echoLocalCommand(text);
+ await this.handleSessionCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "system-prompt" && !commandArgs) {
+ this.echoLocalCommand(text);
+ await this.handleSystemPromptCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "traces") {
+ await this.handleTracesCommand(canonicalCommandText);
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "context" && !commandArgs) {
+ this.echoLocalCommand(text);
+ await this.handleContextCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "logs" && !commandArgs) {
+ this.echoLocalCommand(text);
+ this.handleLogsCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "goal" && (!commandArgs || commandArgs === "status")) {
+ this.echoLocalCommand(text);
+ this.handleGoalStatusCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "heartbeat") {
+ await this.handleHeartbeatCommand(canonicalCommandText);
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "changelog" && !commandArgs) {
+ this.echoLocalCommand(text);
+ this.handleChangelogCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "hotkeys" && !commandArgs) {
+ this.echoLocalCommand(text);
+ this.handleHotkeysCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (commandName === "fork" && !commandArgs) {
+ this.editor.setText("");
+ await this.showUserMessageSelector();
+ return;
+ }
+ if (commandName === "clone" && !commandArgs) {
+ this.editor.setText("");
+ await this.handleCloneCommand();
+ return;
+ }
+ if (commandName === "tree" && !commandArgs) {
+ this.editor.setText("");
+ await this.showTreeSelector();
+ return;
+ }
+ if (commandName === "login" && !commandArgs) {
+ this.editor.setText("");
+ await this.showOAuthSelector("login");
+ return;
+ }
+ if (commandName === "logout" && !commandArgs) {
+ this.editor.setText("");
+ await this.showOAuthSelector("logout");
+ return;
+ }
+ if (commandName === "mcp") {
+ this.editor.setText("");
+ await this.handleMcpCommand(commandArgs);
+ return;
+ }
+ if (commandName === "new" && !commandArgs) {
+ this.editor.setText("");
+ await this.handleClearCommand();
+ return;
+ }
+ if (commandName === "compact") {
+ const customInstructions = commandArgs || undefined;
+ this.editor.setText("");
+ await this.handleCompactCommand(customInstructions);
+ return;
+ }
+ if (commandName === "refine") {
+ const refineArgs = commandArgs || undefined;
+ this.editor.setText("");
+ await this.handleRefineCommand(refineArgs);
+ return;
+ }
+ if (commandName === "reload" && !commandArgs) {
+ this.editor.setText("");
+ await this.handleReloadCommand();
+ return;
+ }
+ if (commandName === "fullscreen") {
+ this.editor.setText("");
+ const arg = commandArgs?.trim().toLowerCase();
+ if (arg && arg !== "on" && arg !== "off") {
+ this.showError("Usage: /fullscreen [on|off]");
+ return;
}
- this.showError(error instanceof Error ? error.message : String(error));
+ const enable = arg === "on" ? true : arg === "off" ? false : !this.fullscreenEnabled;
+ this.setFullscreenMode(enable);
+ return;
+ }
+ if (commandName === "debug" && !commandArgs) {
+ await this.handleDebugCommand();
+ this.editor.setText("");
+ return;
+ }
+ if (text === "/arminsayshi") {
+ this.handleArminSaysHi();
+ this.editor.setText("");
+ return;
+ }
+ if (text === "/dementedelves") {
+ this.handleDementedDelves();
+ this.editor.setText("");
+ return;
+ }
+ if (text === "/resume") {
+ this.editor.setText("");
+ await this.showSessionSelector();
+ return;
+ }
+ if (text === "/quit") {
+ this.editor.setText("");
+ await this.shutdown();
+ return;
}
- return;
- }
- // Queue input during compaction (extension commands execute immediately)
- if (this.isAgentCompacting()) {
- if (this.isExtensionCommand(text)) {
+ // Handle bash command (! for normal, !! for excluded from context)
+ if (text.startsWith("!")) {
+ const isExcluded = text.startsWith("!!");
+ const command = isExcluded ? text.slice(2).trim() : text.slice(1).trim();
+ if (!command) {
+ // Bare ! / !! is bash mode with nothing to run; don't send it as a prompt
+ return;
+ }
+ if (this.isBashRunning()) {
+ this.showWarning(
+ `A bash command is already running. Press ${keyText("app.clear")} to cancel it first.`,
+ );
+ return;
+ }
this.editor.addToHistory?.(text);
this.editor.setText("");
- await this.agentConnection.prompt(text, { images: this.collectImagesFor(text) });
- } else {
- this.queueCompactionMessage(text, "steer");
+ // Optimistic: bash_start only fires after extension dispatch, and the
+ // clear key must already route to abortBash in that window.
+ this.patchConnectionState({ isBashRunning: true });
+ try {
+ await this.agentConnection.executeBash(command, { excludeFromContext: isExcluded });
+ } catch (error) {
+ // Re-sync rather than assume idle: the rejection may mean another
+ // client's bash run already holds the slot.
+ try {
+ const state = await this.agentConnection.getState();
+ this.patchConnectionState({ isBashRunning: state.isBashRunning });
+ } catch {
+ this.patchConnectionState({ isBashRunning: false });
+ }
+ this.showError(error instanceof Error ? error.message : String(error));
+ }
+ return;
}
- return;
- }
- // If streaming, use prompt() with steer behavior
- // This handles extension commands (execute immediately), prompt template expansion, and queueing
- if (this.isAgentStreaming()) {
- const images = this.collectImagesFor(text);
- this.editor.addToHistory?.(text);
- this.editor.setText("");
- await this.agentConnection.prompt(text, { streamingBehavior: "steer", images });
- this.updatePendingMessagesDisplay();
- this.ui.requestRender();
- return;
- }
+ // Queue input during compaction (extension commands execute immediately)
+ if (this.isAgentCompacting()) {
+ if (this.isExtensionCommand(text)) {
+ this.editor.addToHistory?.(text);
+ this.editor.setText("");
+ await this.agentConnection.prompt(text, { images: this.collectImagesFor(text) });
+ } else {
+ this.queueCompactionMessage(text, "steer");
+ }
+ return;
+ }
+
+ // If streaming, use prompt() with steer behavior
+ // This handles extension commands (execute immediately), prompt template expansion, and queueing
+ if (this.isAgentStreaming()) {
+ const images = this.collectImagesFor(text);
+ this.editor.addToHistory?.(text);
+ this.editor.setText("");
+ await this.agentConnection.prompt(text, { streamingBehavior: "steer", images });
+ this.updatePendingMessagesDisplay();
+ this.ui.requestRender();
+ return;
+ }
- // Normal message submission
- // First, move any pending bash components to chat
- this.flushPendingBashComponents();
+ // Normal message submission
+ // First, move any pending bash components to chat
+ this.flushPendingBashComponents();
- if (this.onInputCallback) {
- this.onInputCallback(text);
+ if (this.onInputCallback) {
+ this.onInputCallback(text);
+ }
+ this.editor.addToHistory?.(text);
+ } finally {
+ if (promptStashToRestore !== undefined) {
+ this.restorePromptStashIfEditorEmpty(promptStashToRestore);
+ }
}
- this.editor.addToHistory?.(text);
};
}
@@ -3771,7 +3838,7 @@ export class InteractiveMode {
} else if (event.type === "session_replaced") {
this.resetExtensionUI();
this.applyConnectionStateSnapshot(event.state);
- this.resetCurrentSessionRenderState();
+ this.resetCurrentSessionRenderState({ clearPromptStash: true });
await this.rebindCurrentSession();
await this.renderInitialMessages();
this.ui.requestRender();
@@ -5441,33 +5508,53 @@ export class InteractiveMode {
private async handleFollowUp(): Promise<void> {
const text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();
if (!text) return;
+ const promptStashToRestore = this.promptStash;
+ let clearedSubmittedText: string | undefined;
- // Queue input during compaction (extension commands execute immediately)
- if (this.isAgentCompacting()) {
- if (this.isExtensionCommand(text)) {
+ try {
+ // Queue input during compaction (extension commands execute immediately)
+ if (this.isAgentCompacting()) {
+ if (this.isExtensionCommand(text)) {
+ this.editor.addToHistory?.(text);
+ clearedSubmittedText = text;
+ this.editor.setText("");
+ await this.agentConnection.prompt(text, { images: this.collectImagesFor(text) });
+ clearedSubmittedText = undefined;
+ } else {
+ this.queueCompactionMessage(text, "followUp");
+ }
+ return;
+ }
+
+ // Alt+Enter queues a follow-up message (waits until agent finishes)
+ // This handles extension commands (execute immediately), prompt template expansion, and queueing
+ if (this.isAgentStreaming()) {
+ const images = this.collectImagesFor(text);
this.editor.addToHistory?.(text);
+ clearedSubmittedText = text;
this.editor.setText("");
- await this.agentConnection.prompt(text, { images: this.collectImagesFor(text) });
- } else {
- this.queueCompactionMessage(text, "followUp");
+ await this.agentConnection.prompt(text, { streamingBehavior: "followUp", images });
+ clearedSubmittedText = undefined;
+ this.updatePendingMessagesDisplay();
+ this.ui.requestRender();
+ }
+ // If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)
+ else if (this.editor.onSubmit) {
+ clearedSubmittedText = text;
+ this.editor.setText("");
+ await this.editor.onSubmit(text);
+ clearedSubmittedText = undefined;
+ }
+ } catch (error) {
+ if (clearedSubmittedText !== undefined) {
+ this.editor.setText(clearedSubmittedText);
+ this.promptStash = promptStashToRestore;
+ }
+ throw error;
+ } finally {
+ if (promptStashToRestore !== undefined && clearedSubmittedText === undefined) {
+ this.restorePromptStashIfEditorEmpty(promptStashToRestore);
}
- return;
- }
-
- // Alt+Enter queues a follow-up message (waits until agent finishes)
- // This handles extension commands (execute immediately), prompt template expansion, and queueing
- if (this.isAgentStreaming()) {
- const images = this.collectImagesFor(text);
- this.editor.addToHistory?.(text);
- this.editor.setText("");
- await this.agentConnection.prompt(text, { streamingBehavior: "followUp", images });
- this.updatePendingMessagesDisplay();
- this.ui.requestRender();
- }
- // If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)
- else if (this.editor.onSubmit) {
- this.editor.setText("");
- this.editor.onSubmit(text);
}
}
@@ -7599,6 +7686,7 @@ export class InteractiveMode {
const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");
const focusSubagents = this.getAppKeyDisplay("app.subagents.focus");
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 pasteImage = this.getAppKeyDisplay("app.clipboard.pasteImage");
@@ -7647,6 +7735,7 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}| \`${
| \`${toggleThinking}\` | Toggle thinking block visibility |
| \`${focusSubagents}\` | Open subagent inspector |
| \`${externalEditor}\` | Edit message in external editor |
+| \`${promptStash}\` | Stash or restore draft prompt |
| \`${followUp}\` | Queue follow-up message |
| \`${dequeue}\` | Restore queued messages |
| \`${pasteImage}\` | Paste image from clipboard |
diff --git a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
new file mode 100644
index 0000000000..aa8fd52dd7
--- /dev/null
+++ b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
@@ -0,0 +1,427 @@
+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";
+
+type FakePasteSnapshot = {
+ pastes: readonly (readonly [number, string])[];
+ pasteCounter: number;
+};
+
+type PromptStash = {
+ text: string;
+ expandedText?: string;
+ pasteSnapshot?: FakePasteSnapshot;
+};
+
+type FakeEditor = {
+ text: string;
+ expandedText: string;
+ history: string[];
+ pasteSnapshot?: FakePasteSnapshot;
+ restoredPasteSnapshot?: FakePasteSnapshot;
+ onSubmit?: (text: string) => void | Promise<void>;
+ clearHistory?: Mock;
+ getText: () => string;
+ getExpandedText: () => string;
+ getPasteSnapshot: () => FakePasteSnapshot | undefined;
+ restorePasteSnapshot?: (snapshot: FakePasteSnapshot) => void;
+ setText: (text: string) => void;
+ addToHistory: Mock;
+ getHistory: () => readonly string[];
+};
+
+type PromptStashHarness = {
+ promptStash?: PromptStash;
+ editor: FakeEditor;
+ showStatus: Mock;
+};
+
+type PromptStashLiveMarkerHarness = PromptStashHarness & {
+ compactionQueuedMessages: Array<{ text: string; mode: "steer" | "followUp" }>;
+ connectionQueue: { steering: string[]; followUp: string[] };
+};
+
+type ResetHarness = PromptStashLiveMarkerHarness & {
+ chatContainer: { clear: Mock };
+ pendingMessagesContainer: { clear: Mock };
+ queuedMessagesContainer: { clear: Mock };
+ defaultEditor: FakeEditor;
+ pastedImages: Map<number, unknown>;
+ streamingComponent?: unknown;
+ streamingMessage?: unknown;
+ activeBashComponent?: { setComplete: Mock };
+ pendingBashComponents: unknown[];
+ activityTracker: { reset: Mock };
+ contextUsageTokenBaseline: number;
+ resetPendingToolState: Mock;
+ resetChildAgentInspector: Mock;
+ setGoalAnnouncementBaseline: Mock;
+ getGoalState: Mock<() => unknown>;
+ syncGoalTray: Mock;
+};
+
+type SubmitHarness = PromptStashHarness & {
+ defaultEditor: { onSubmit?: (text: string) => void | Promise<void> };
+ isAgentCompacting: () => boolean;
+ isAgentStreaming: () => boolean;
+ flushPendingBashComponents: Mock;
+ onInputCallback: Mock;
+};
+
+type PromptStashMethods = {
+ handleFollowUp: (this: SubmitHarness) => Promise<void>;
+ handlePromptStash: (this: PromptStashHarness) => void;
+ resetCurrentSessionRenderState: (this: ResetHarness, options?: { clearPromptStash?: boolean }) => void;
+ restorePromptStashIfEditorEmpty: (this: PromptStashHarness, stash?: PromptStash) => boolean;
+ liveImageMarkerIds: (this: PromptStashLiveMarkerHarness) => Set<number>;
+ setupEditorSubmitHandler: (this: SubmitHarness) => void;
+};
+
+const interactiveModeMethods = InteractiveMode.prototype as unknown as PromptStashMethods;
+
+function createEditor(
+ options: { text?: string; expandedText?: string; history?: string[]; pasteSnapshot?: FakePasteSnapshot } = {},
+): FakeEditor {
+ const editor: FakeEditor = {
+ text: options.text ?? "",
+ expandedText: options.expandedText ?? options.text ?? "",
+ history: options.history ?? [],
+ pasteSnapshot: options.pasteSnapshot,
+ getText() {
+ return this.text;
+ },
+ getExpandedText() {
+ return this.expandedText;
+ },
+ getPasteSnapshot() {
+ return this.pasteSnapshot;
+ },
+ restorePasteSnapshot(snapshot: FakePasteSnapshot) {
+ this.restoredPasteSnapshot = snapshot;
+ this.pasteSnapshot = snapshot;
+ },
+ setText(nextText: string) {
+ this.text = nextText;
+ this.expandedText = nextText;
+ },
+ addToHistory: vi.fn(),
+ getHistory() {
+ return this.history;
+ },
+ clearHistory: vi.fn(function (this: FakeEditor) {
+ this.history = [];
+ }),
+ };
+ return editor;
+}
+
+function createPromptStashHarness(
+ options: { text?: string; expandedText?: string; stash?: string; pasteSnapshot?: FakePasteSnapshot } = {},
+) {
+ const harness: PromptStashHarness = {
+ promptStash: options.stash ? { text: options.stash, pasteSnapshot: options.pasteSnapshot } : undefined,
+ editor: createEditor({
+ text: options.text,
+ expandedText: options.expandedText,
+ pasteSnapshot: options.pasteSnapshot,
+ }),
+ showStatus: vi.fn(),
+ };
+ Object.setPrototypeOf(harness, InteractiveMode.prototype);
+ return harness;
+}
+
+describe("InteractiveMode prompt stash", () => {
+ it("uses Ctrl+S as the default configurable stash keybinding", () => {
+ const keybindings = new KeybindingsManager();
+
+ expect(keybindings.getKeys("app.prompt.stash")).toEqual(["ctrl+s"]);
+ });
+
+ it("stashes editor text without expanding paste markers", () => {
+ const pasteSnapshot: FakePasteSnapshot = {
+ pastes: [[1, "line one\nline two"]],
+ pasteCounter: 1,
+ };
+ const mode = createPromptStashHarness({
+ text: "[paste #1 +12 lines]",
+ expandedText: "line one\nline two",
+ pasteSnapshot,
+ });
+
+ interactiveModeMethods.handlePromptStash.call(mode);
+
+ expect(mode.promptStash).toEqual({
+ text: "[paste #1 +12 lines]",
+ expandedText: "line one\nline two",
+ pasteSnapshot,
+ });
+ expect(mode.editor.getText()).toBe("");
+ expect(mode.showStatus).toHaveBeenCalledWith("Stashed prompt");
+
+ interactiveModeMethods.restorePromptStashIfEditorEmpty.call(mode);
+
+ expect(mode.editor.getText()).toBe("[paste #1 +12 lines]");
+ expect(mode.editor.restoredPasteSnapshot).toBe(pasteSnapshot);
+ });
+
+ it("restores expanded paste text when paste snapshots are unsupported", () => {
+ const pasteSnapshot: FakePasteSnapshot = {
+ pastes: [[1, "line one\nline two"]],
+ pasteCounter: 1,
+ };
+ const mode = createPromptStashHarness({
+ text: "[paste #1 +12 lines]",
+ expandedText: "line one\nline two",
+ pasteSnapshot,
+ });
+
+ interactiveModeMethods.handlePromptStash.call(mode);
+ mode.editor.restorePasteSnapshot = undefined;
+
+ const restored = interactiveModeMethods.restorePromptStashIfEditorEmpty.call(mode);
+
+ expect(restored).toBe(true);
+ expect(mode.editor.getText()).toBe("line one\nline two");
+ expect(mode.editor.restoredPasteSnapshot).toBeUndefined();
+ });
+
+ it("restores a stashed prompt when the editor is empty", () => {
+ const mode = createPromptStashHarness({ stash: "half-written draft" });
+
+ interactiveModeMethods.handlePromptStash.call(mode);
+
+ expect(mode.promptStash).toBeUndefined();
+ expect(mode.editor.getText()).toBe("half-written draft");
+ expect(mode.showStatus).toHaveBeenCalledWith("Restored stashed prompt");
+ });
+
+ it("does not restore an older captured stash after a newer stash is created", () => {
+ const mode = createPromptStashHarness({ stash: "older draft" });
+ const olderStash = mode.promptStash;
+ const newerStash = { text: "newer draft" };
+ mode.promptStash = newerStash;
+
+ const restored = interactiveModeMethods.restorePromptStashIfEditorEmpty.call(mode, olderStash);
+
+ expect(restored).toBe(false);
+ expect(mode.promptStash).toBe(newerStash);
+ expect(mode.editor.getText()).toBe("");
+ expect(mode.showStatus).not.toHaveBeenCalledWith("Restored stashed prompt");
+ });
+
+ it("does not overwrite an existing stash", () => {
+ const mode = createPromptStashHarness({ text: "second draft", stash: "first draft" });
+
+ interactiveModeMethods.handlePromptStash.call(mode);
+
+ expect(mode.promptStash?.text).toBe("first draft");
+ expect(mode.editor.getText()).toBe("second draft");
+ expect(mode.showStatus).toHaveBeenCalledWith("Prompt stash already has a draft");
+ });
+
+ it("restores a stashed prompt after normal message submission clears the editor", async () => {
+ const mode: SubmitHarness = {
+ ...createPromptStashHarness({ stash: "half-written draft" }),
+ defaultEditor: {},
+ isAgentCompacting: () => false,
+ isAgentStreaming: () => false,
+ flushPendingBashComponents: vi.fn(),
+ onInputCallback: vi.fn(),
+ };
+ Object.setPrototypeOf(mode, InteractiveMode.prototype);
+ interactiveModeMethods.setupEditorSubmitHandler.call(mode);
+
+ await mode.defaultEditor.onSubmit?.("temporary prompt");
+
+ expect(mode.onInputCallback).toHaveBeenCalledWith("temporary prompt");
+ expect(mode.editor.addToHistory).toHaveBeenCalledWith("temporary prompt");
+ expect(mode.promptStash).toBeUndefined();
+ expect(mode.editor.getText()).toBe("half-written draft");
+ });
+
+ it("restores a stashed prompt after a session reset clears prompt state", async () => {
+ let mode: SubmitHarness & { handleClearCommand: Mock<() => Promise<void>> };
+ mode = {
+ ...createPromptStashHarness({ stash: "half-written draft" }),
+ defaultEditor: {},
+ isAgentCompacting: () => false,
+ isAgentStreaming: () => false,
+ flushPendingBashComponents: vi.fn(),
+ onInputCallback: vi.fn(),
+ handleClearCommand: vi.fn(async () => {
+ mode.editor.setText("");
+ }),
+ };
+ Object.setPrototypeOf(mode, InteractiveMode.prototype);
+ interactiveModeMethods.setupEditorSubmitHandler.call(mode);
+
+ await mode.defaultEditor.onSubmit?.("/new");
+
+ expect(mode.handleClearCommand).toHaveBeenCalled();
+ expect(mode.promptStash).toBeUndefined();
+ expect(mode.editor.getText()).toBe("half-written draft");
+ });
+
+ it("waits for async session selectors before restoring a stashed prompt", async () => {
+ let resolveSelector: () => void = () => {};
+ const selectorDone = new Promise<void>((resolve) => {
+ resolveSelector = resolve;
+ });
+ let mode: SubmitHarness & { showUserMessageSelector: Mock<() => Promise<void>> };
+ mode = {
+ ...createPromptStashHarness({ stash: "half-written draft" }),
+ defaultEditor: {},
+ isAgentCompacting: () => false,
+ isAgentStreaming: () => false,
+ flushPendingBashComponents: vi.fn(),
+ onInputCallback: vi.fn(),
+ showUserMessageSelector: vi.fn(async () => {
+ await selectorDone;
+ mode.editor.setText("");
+ }),
+ };
+ Object.setPrototypeOf(mode, InteractiveMode.prototype);
+ interactiveModeMethods.setupEditorSubmitHandler.call(mode);
+
+ const submit = mode.defaultEditor.onSubmit?.("/fork");
+ await Promise.resolve();
+ resolveSelector();
+ await submit;
+
+ expect(mode.showUserMessageSelector).toHaveBeenCalled();
+ expect(mode.promptStash).toBeUndefined();
+ expect(mode.editor.getText()).toBe("half-written draft");
+ });
+
+ it("restores a stashed prompt after idle follow-up slash commands clear the editor", async () => {
+ let resolveSettings: () => void = () => {};
+ const settingsDone = new Promise<void>((resolve) => {
+ resolveSettings = resolve;
+ });
+ const mode: SubmitHarness & { showSettingsSelector: Mock<() => Promise<void>> } = {
+ ...createPromptStashHarness({ text: "/settings", stash: "half-written draft" }),
+ defaultEditor: {},
+ isAgentCompacting: () => false,
+ isAgentStreaming: () => false,
+ flushPendingBashComponents: vi.fn(),
+ onInputCallback: vi.fn(),
+ showSettingsSelector: vi.fn(() => settingsDone),
+ };
+ Object.setPrototypeOf(mode, InteractiveMode.prototype);
+ interactiveModeMethods.setupEditorSubmitHandler.call(mode);
+ mode.editor.onSubmit = mode.defaultEditor.onSubmit;
+
+ const followUp = interactiveModeMethods.handleFollowUp.call(mode);
+ await Promise.resolve();
+ resolveSettings();
+ await followUp;
+
+ expect(mode.showSettingsSelector).toHaveBeenCalled();
+ expect(mode.promptStash).toBeUndefined();
+ expect(mode.editor.getText()).toBe("half-written draft");
+ });
+
+ it("drops queued image references from old sessions while keeping stashed images", () => {
+ const base = createPromptStashHarness({ stash: "keep [image #1]" });
+ const mode: ResetHarness = {
+ ...base,
+ defaultEditor: base.editor,
+ compactionQueuedMessages: [],
+ connectionQueue: { steering: ["old [image #2]"], followUp: [] },
+ chatContainer: { clear: vi.fn() },
+ pendingMessagesContainer: { clear: vi.fn() },
+ queuedMessagesContainer: { clear: vi.fn() },
+ pastedImages: new Map<number, unknown>([
+ [1, {}],
+ [2, {}],
+ ]),
+ pendingBashComponents: [],
+ activityTracker: { reset: vi.fn() },
+ contextUsageTokenBaseline: 1,
+ resetPendingToolState: vi.fn(),
+ resetChildAgentInspector: vi.fn(),
+ setGoalAnnouncementBaseline: vi.fn(),
+ getGoalState: vi.fn(() => undefined),
+ syncGoalTray: vi.fn(),
+ };
+ Object.setPrototypeOf(mode, InteractiveMode.prototype);
+
+ interactiveModeMethods.resetCurrentSessionRenderState.call(mode);
+
+ expect(mode.connectionQueue).toEqual({ steering: [], followUp: [] });
+ expect(mode.promptStash?.text).toBe("keep [image #1]");
+ expect(mode.pastedImages.has(1)).toBe(true);
+ expect(mode.pastedImages.has(2)).toBe(false);
+ });
+
+ it("clears stashed prompt state on external session replacement resets", () => {
+ const base = createPromptStashHarness({ stash: "drop [image #1]" });
+ const mode: ResetHarness = {
+ ...base,
+ defaultEditor: base.editor,
+ compactionQueuedMessages: [],
+ connectionQueue: { steering: [], followUp: [] },
+ chatContainer: { clear: vi.fn() },
+ pendingMessagesContainer: { clear: vi.fn() },
+ queuedMessagesContainer: { clear: vi.fn() },
+ pastedImages: new Map<number, unknown>([[1, {}]]),
+ pendingBashComponents: [],
+ activityTracker: { reset: vi.fn() },
+ contextUsageTokenBaseline: 1,
+ resetPendingToolState: vi.fn(),
+ resetChildAgentInspector: vi.fn(),
+ setGoalAnnouncementBaseline: vi.fn(),
+ getGoalState: vi.fn(() => undefined),
+ syncGoalTray: vi.fn(),
+ };
+ Object.setPrototypeOf(mode, InteractiveMode.prototype);
+
+ interactiveModeMethods.resetCurrentSessionRenderState.call(mode, { clearPromptStash: true });
+
+ expect(mode.promptStash).toBeUndefined();
+ expect(mode.pastedImages.has(1)).toBe(false);
+ });
+
+ it("restores failed follow-up text without dropping the stashed prompt", async () => {
+ const error = new Error("send failed");
+ const mode: SubmitHarness & {
+ agentConnection: { prompt: Mock<() => Promise<void>> };
+ collectImagesFor: Mock;
+ updatePendingMessagesDisplay: Mock;
+ ui: { requestRender: Mock };
+ } = {
+ ...createPromptStashHarness({ text: "quick follow-up", stash: "half-written draft" }),
+ defaultEditor: {},
+ isAgentCompacting: () => false,
+ isAgentStreaming: () => true,
+ flushPendingBashComponents: vi.fn(),
+ onInputCallback: vi.fn(),
+ agentConnection: {
+ prompt: vi.fn(async () => {
+ throw error;
+ }),
+ },
+ collectImagesFor: vi.fn(),
+ updatePendingMessagesDisplay: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ };
+ Object.setPrototypeOf(mode, InteractiveMode.prototype);
+
+ await expect(interactiveModeMethods.handleFollowUp.call(mode)).rejects.toThrow(error);
+
+ expect(mode.editor.getText()).toBe("quick follow-up");
+ expect(mode.promptStash?.text).toBe("half-written draft");
+ });
+
+ it("keeps image markers in a stashed prompt live", () => {
+ const mode: PromptStashLiveMarkerHarness = {
+ ...createPromptStashHarness({ stash: "look at [image #7]" }),
+ compactionQueuedMessages: [],
+ connectionQueue: { steering: [], followUp: [] },
+ };
+ Object.setPrototypeOf(mode, InteractiveMode.prototype);
+
+ expect(interactiveModeMethods.liveImageMarkerIds.call(mode)).toEqual(new Set([7]));
+ });
+});
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index f4cbf2c98d..1f21e784d6 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -480,6 +480,7 @@ describe("InteractiveMode pending bash components", () => {
queuedMessagesContainer: new Container(),
compactionQueuedMessages: [],
pastedImages: new Map(),
+ liveImageMarkerIds: () => new Set(),
defaultEditor: editorStub,
editor: editorStub,
streamingComponent: undefined,
diff --git a/packages/tui/src/components/editor.ts b/packages/tui/src/components/editor.ts
index 1f9b27efbc..84874e763a 100644
--- a/packages/tui/src/components/editor.ts
+++ b/packages/tui/src/components/editor.ts
@@ -1,4 +1,5 @@
import type { AutocompleteProvider, AutocompleteSuggestions } from "../autocomplete.js";
+import type { EditorPasteSnapshot } from "../editor-component.js";
import { getKeybindings } from "../keybindings.js";
import { decodePrintableKey, matchesKey } from "../keys.js";
import { KillRing } from "../kill-ring.js";
@@ -215,6 +216,11 @@ interface EditorState {
cursorCol: number;
}
+interface EditorUndoSnapshot extends EditorState {
+ pastes: Map<number, string>;
+ pasteCounter: number;
+}
+
interface LayoutLine {
text: string;
hasCursor: boolean;
@@ -309,7 +315,13 @@ export class Editor implements Component, Focusable {
private snappedFromCursorCol: number | null = null;
// Undo support
- private undoStack = new UndoStack<EditorState>();
+ private undoStack = new UndoStack<EditorUndoSnapshot>((snapshot) => ({
+ lines: [...snapshot.lines],
+ cursorLine: snapshot.cursorLine,
+ cursorCol: snapshot.cursorCol,
+ pastes: new Map(snapshot.pastes),
+ pasteCounter: snapshot.pasteCounter,
+ }));
public onSubmit?: (text: string) => void;
public onChange?: (text: string) => void;
@@ -1065,6 +1077,18 @@ export class Editor implements Component, Focusable {
return this.expandPasteMarkers(this.state.lines.join("\n"));
}
+ getPasteSnapshot(): EditorPasteSnapshot {
+ return {
+ pastes: [...this.pastes],
+ pasteCounter: this.pasteCounter,
+ };
+ }
+
+ restorePasteSnapshot(snapshot: EditorPasteSnapshot): void {
+ this.pastes = new Map(snapshot.pastes);
+ this.pasteCounter = snapshot.pasteCounter;
+ }
+
getLines(): string[] {
return [...this.state.lines];
}
@@ -2088,14 +2112,26 @@ export class Editor implements Component, Focusable {
}
private pushUndoSnapshot(): void {
- this.undoStack.push(this.state);
+ this.undoStack.push({
+ lines: this.state.lines,
+ cursorLine: this.state.cursorLine,
+ cursorCol: this.state.cursorCol,
+ pastes: this.pastes,
+ pasteCounter: this.pasteCounter,
+ });
}
private undo(): void {
this.historyIndex = -1; // Exit history browsing mode
const snapshot = this.undoStack.pop();
if (!snapshot) return;
- Object.assign(this.state, snapshot);
+ this.state = {
+ lines: snapshot.lines,
+ cursorLine: snapshot.cursorLine,
+ cursorCol: snapshot.cursorCol,
+ };
+ this.pastes = new Map(snapshot.pastes);
+ this.pasteCounter = snapshot.pasteCounter;
this.lastAction = null;
this.preferredVisualCol = null;
if (this.onChange) {
diff --git a/packages/tui/src/editor-component.ts b/packages/tui/src/editor-component.ts
index 6748c59f44..1678fc85f4 100644
--- a/packages/tui/src/editor-component.ts
+++ b/packages/tui/src/editor-component.ts
@@ -1,6 +1,11 @@
import type { AutocompleteProvider } from "./autocomplete.js";
import type { Component } from "./tui.js";
+export interface EditorPasteSnapshot {
+ pastes: readonly (readonly [number, string])[];
+ pasteCounter: number;
+}
+
/**
* Interface for custom editor components.
*
@@ -58,6 +63,10 @@ export interface EditorComponent extends Component {
*/
getExpandedText?(): string;
+ getPasteSnapshot?(): EditorPasteSnapshot;
+
+ restorePasteSnapshot?(snapshot: EditorPasteSnapshot): void;
+
// =========================================================================
// Autocomplete support (optional)
// =========================================================================
diff --git a/packages/tui/src/index.ts b/packages/tui/src/index.ts
index c1f3ea7c83..641df72e00 100644
--- a/packages/tui/src/index.ts
+++ b/packages/tui/src/index.ts
@@ -28,7 +28,7 @@ export { Spacer } from "./components/spacer.js";
export { Text } from "./components/text.js";
export { TruncatedText } from "./components/truncated-text.js";
// Editor component interface (for custom editors)
-export type { EditorComponent } from "./editor-component.js";
+export type { EditorComponent, EditorPasteSnapshot } from "./editor-component.js";
// Fullscreen (alternate-screen) viewport
export { FullscreenViewport, type ScrollInfo } from "./fullscreen.js";
// Fuzzy matching
diff --git a/packages/tui/src/undo-stack.ts b/packages/tui/src/undo-stack.ts
index 5b9a7e9cee..db6bbfb113 100644
--- a/packages/tui/src/undo-stack.ts
+++ b/packages/tui/src/undo-stack.ts
@@ -1,15 +1,17 @@
/**
* Generic undo stack with clone-on-push semantics.
*
- * Stores deep clones of state snapshots. Popped snapshots are returned
- * directly (no re-cloning) since they are already detached.
+ * Stores cloned state snapshots. Popped snapshots are returned directly
+ * since they are already detached.
*/
export class UndoStack<S> {
private stack: S[] = [];
- /** Push a deep clone of the given state onto the stack. */
+ constructor(private readonly clone: (state: S) => S = structuredClone) {}
+
+ /** Push a clone of the given state onto the stack. */
push(state: S): void {
- this.stack.push(structuredClone(state));
+ this.stack.push(this.clone(state));
}
/** Pop and return the most recent snapshot, or undefined if empty. */
diff --git a/packages/tui/test/editor.test.ts b/packages/tui/test/editor.test.ts
index 6d58d046d2..415e3bf352 100644
--- a/packages/tui/test/editor.test.ts
+++ b/packages/tui/test/editor.test.ts
@@ -3658,6 +3658,85 @@ describe("Editor component", () => {
assert.strictEqual(editor.getExpandedText(), pastedText);
});
+ it("restores expanded pasted content from a paste snapshot", () => {
+ const editor = new Editor(createTestTUI(), defaultEditorTheme);
+ const pastedText = [
+ "line 1",
+ "line 2",
+ "line 3",
+ "line 4",
+ "line 5",
+ "line 6",
+ "line 7",
+ "line 8",
+ "line 9",
+ "line 10",
+ "line 11",
+ ].join("\n");
+ let submitted = "";
+ editor.onSubmit = (text) => {
+ submitted = text;
+ };
+
+ editor.handleInput(`\x1b[200~${pastedText}\x1b[201~`);
+ const markerText = editor.getText();
+ const snapshot = editor.getPasteSnapshot();
+ editor.handleInput("\r");
+
+ const restored = new Editor(createTestTUI(), defaultEditorTheme);
+ restored.setText(markerText);
+ restored.restorePasteSnapshot(snapshot);
+
+ assert.match(markerText, /\[paste #\d+ \+\d+ lines\]/);
+ assert.strictEqual(submitted, pastedText);
+ assert.strictEqual(restored.getExpandedText(), pastedText);
+ });
+
+ it("restores paste snapshot state on undo", () => {
+ const editor = new Editor(createTestTUI(), defaultEditorTheme);
+ const originalText = [
+ "original 1",
+ "original 2",
+ "original 3",
+ "original 4",
+ "original 5",
+ "original 6",
+ "original 7",
+ "original 8",
+ "original 9",
+ "original 10",
+ "original 11",
+ ].join("\n");
+ const restoredText = [
+ "restored 1",
+ "restored 2",
+ "restored 3",
+ "restored 4",
+ "restored 5",
+ "restored 6",
+ "restored 7",
+ "restored 8",
+ "restored 9",
+ "restored 10",
+ "restored 11",
+ "restored 12",
+ ].join("\n");
+ const restoredSource = new Editor(createTestTUI(), defaultEditorTheme);
+
+ editor.handleInput(`\x1b[200~${originalText}\x1b[201~`);
+ const originalMarker = editor.getText();
+ restoredSource.handleInput(`\x1b[200~${restoredText}\x1b[201~`);
+
+ editor.setText(restoredSource.getText());
+ editor.restorePasteSnapshot(restoredSource.getPasteSnapshot());
+ assert.strictEqual(editor.getExpandedText(), restoredText);
+
+ editor.handleInput("\x1b[45;5u");
+
+ assert.strictEqual(editor.getText(), originalMarker);
+ assert.strictEqual(editor.getExpandedText(), originalText);
+ });
+
it("snaps to the paste marker start when navigating down into it", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);