Skip to content

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

Rust

persist stashed prompts across agent navigation (#441)

kt6087397bb47b
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index d4aedf8b9e..378d115863 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -5,6 +5,7 @@
- Changed shell commands to use discoverable agent, schedule, package, model, session, update, doctor, and full-shutdown verbs without exposing the background daemon hierarchy ([ENG-4538](https://linear.app/primeintellect/issue/ENG-4538/standardize-bash-command-conventions-and-improve-command-discovery)).
- Fixed unsupported Node versions crashing before startup by requiring Node 22.8.0 or newer and showing upgrade guidance before loading the CLI ([ENG-4260](https://linear.app/primeintellect/issue/ENG-4260/incorrect-node-version-breaks-first-launch)).
- Added `@` file-path autocomplete to new-agent and reply prompts in the Agents View.
+- Fixed stashed prompts being lost when leaving and reopening a session from the Agents View ([ENG-4659](https://linear.app/primeintellect/issue/ENG-4659/stashed-prompts-should-persist)).
- Added a combined heartbeat indicator and manager for pausing, resuming, or stopping user and agent heartbeats ([ENG-4536](https://linear.app/primeintellect/issue/ENG-4536/add-heartbeat-observability-and-management-ui)).
## [0.3.1] - 2026-07-15
diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts
index f1a847d5e4..b76eaf3a61 100644
--- a/packages/coding-agent/src/index.ts
+++ b/packages/coding-agent/src/index.ts
@@ -284,6 +284,7 @@ export {
} from "./modes/agent-connection/index.js";
// Run modes for programmatic SDK usage
export {
+ ClientPromptStashStore,
createInteractiveModeLocalSessionHost,
createInteractiveModeUiServices,
createInteractiveModeUiServicesFromServices,
@@ -320,6 +321,8 @@ export {
type InteractiveModeUiServices,
type ModelInfo,
type PrintModeOptions,
+ type PromptStash,
+ type PromptStashState,
RpcClient,
type RpcClientOptions,
type RpcCommand,
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index 5c5c3cb213..293a8278da 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -75,6 +75,7 @@ import {
} from "./modes/daemon/daemon-worker-protocol.js";
import {
type AgentConnection,
+ ClientPromptStashStore,
createInteractiveModeLocalSessionHost,
createInteractiveModeUiServicesFromServices,
DaemonAgentConnection,
@@ -1334,6 +1335,7 @@ export async function main(args: string[], options?: MainOptions) {
console.log(chalk.dim(`Model scope: ${modelList} ${chalk.gray("(Ctrl+P to cycle)")}`));
}
+ const promptStashStore = new ClientPromptStashStore();
const daemonUiServices = createInteractiveModeUiServicesFromServices({
services,
sessionManager,
@@ -1365,6 +1367,7 @@ export async function main(args: string[], options?: MainOptions) {
},
migratedProviders,
modelFallbackMessage: startupModel.modelFallbackMessage,
+ promptStashStore,
startupModelId: startupModel.model?.id,
...(includeInitialPrompts ? { initialMessage, initialImages, initialMessages: parsed.messages } : {}),
verbose: parsed.verbose,
@@ -1413,6 +1416,8 @@ export async function main(args: string[], options?: MainOptions) {
const interactiveMode = new InteractiveMode({
agentConnection,
uiServices: daemonUiServices,
+ promptStashStore,
+ promptStashSessionId: summary.sessionId,
bindLocalSessionExtensions: false,
migratedProviders,
modelFallbackMessage: attachModelFallbackMessage,
@@ -1521,6 +1526,8 @@ export async function main(args: string[], options?: MainOptions) {
const interactiveMode = new InteractiveMode({
agentConnection: new InProcessAgentConnection(runtime),
localSessionHost: createInteractiveModeLocalSessionHost(runtime),
+ promptStashStore: new ClientPromptStashStore(),
+ promptStashSessionId: session.sessionId,
bindLocalSessionExtensions: true,
migratedProviders,
modelFallbackMessage,
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
index fcb970ac05..721d679ddb 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
@@ -57,6 +57,7 @@ import { SessionPickerScreen } from "../interactive/components/session-picker-sc
import { type SessionListCallbacks, SessionSelectorComponent } from "../interactive/components/session-selector.js";
import { BrandSplashHeader, InteractiveMode } from "../interactive/interactive-mode.js";
import type { InteractiveModeUiServices } from "../interactive/interactive-mode-services.js";
+import { ClientPromptStashStore } from "../interactive/prompt-stash-state.js";
import {
getEditorTheme,
initTheme,
@@ -123,6 +124,7 @@ export interface AgentsViewModeOptions {
verbose?: boolean;
recoverDaemon?: () => Promise<void>;
reconnectTimeoutMs?: number;
+ promptStashStore?: ClientPromptStashStore;
}
type AgentsViewRunResult =
@@ -347,6 +349,7 @@ function isUnknownActiveSessionError(error: unknown): boolean {
export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise<void> {
const persistentState: AgentsViewPersistentState = {};
+ const promptStashStore = options.promptStashStore ?? new ClientPromptStashStore();
while (true) {
const view = new AgentsViewMode(options, persistentState);
@@ -376,6 +379,8 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promise
const interactiveMode = new InteractiveMode({
agentConnection: opened.connection,
uiServices,
+ promptStashStore,
+ promptStashSessionId: opened.summary.sessionId,
bindLocalSessionExtensions: false,
migratedProviders: options.migratedProviders,
modelFallbackMessage: resolveAttachModelFallbackMessage(opened.summary, options.modelFallbackMessage),
diff --git a/packages/coding-agent/src/modes/index.ts b/packages/coding-agent/src/modes/index.ts
index 2c3d54b2fd..ea68df9064 100644
--- a/packages/coding-agent/src/modes/index.ts
+++ b/packages/coding-agent/src/modes/index.ts
@@ -76,6 +76,11 @@ export {
type InteractiveModeLocalSessionHost,
type InteractiveModeUiServices,
} from "./interactive/interactive-mode-services.js";
+export {
+ ClientPromptStashStore,
+ type PromptStash,
+ type PromptStashState,
+} from "./interactive/prompt-stash-state.js";
export { type PrintModeOptions, runPrintMode } from "./print-mode.js";
export { type ModelInfo, RpcClient, type RpcClientOptions, type RpcEventListener } from "./rpc/rpc-client.js";
export { runRpcMode } from "./rpc/rpc-mode.js";
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 2cbae0681d..99d1c532d9 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -23,7 +23,6 @@ import type {
AutocompleteItem,
AutocompleteProvider,
EditorComponent,
- EditorPasteSnapshot,
Keybinding,
KeyId,
MarkdownTheme,
@@ -202,6 +201,7 @@ import type {
InteractiveModeUiServices,
} from "./interactive-mode-services.js";
import { type OnboardingStartupState, shouldRunOnboarding, shouldRunPrimeCliOnboardingSplash } from "./onboarding.js";
+import type { ClientPromptStashStore, PromptStash, PromptStashState } from "./prompt-stash-state.js";
import { formatResumeHint } from "./resume-hint.js";
import {
getAvailableThemes,
@@ -226,12 +226,6 @@ interface Expandable {
setExpanded(expanded: boolean): void;
}
-type PromptStash = {
- text: string;
- expandedText?: string;
- pasteSnapshot?: EditorPasteSnapshot;
-};
-
interface PendingToolCallRenderInput {
id: string;
name: string;
@@ -652,6 +646,10 @@ export interface InteractiveModeOptions {
agentsViewOwnsStartupNotices?: boolean;
/** Open the read-only detail view for this subagent node right after startup. */
initialSubagentNodeId?: string;
+ /** Client-owned stash store shared across chat views in this TUI process. */
+ promptStashStore?: ClientPromptStashStore;
+ /** Initial stable session id used to scope prompt stash state. */
+ promptStashSessionId?: string;
}
export type InteractiveModeRunResult = "agents_view";
@@ -673,7 +671,9 @@ export class InteractiveMode {
private sideQuestionContainer: Container;
private defaultEditor: CustomEditor;
private editor: EditorComponent;
- private promptStash: PromptStash | undefined;
+ private readonly promptStashStore: ClientPromptStashStore | undefined;
+ private promptStashSessionId: string | undefined;
+ private promptStashState: PromptStashState;
private editorComponentFactory: EditorFactory | undefined;
private autocompleteProvider: AutocompleteProvider | undefined;
private autocompleteProviderWrappers: AutocompleteProviderFactory[] = [];
@@ -864,6 +864,13 @@ export class InteractiveMode {
}
this.uiServices = uiServices;
this.agentConnection = options.agentConnection;
+ this.promptStashStore = options.promptStashStore;
+ this.promptStashSessionId = options.promptStashSessionId;
+ this.promptStashState =
+ this.promptStashStore && this.promptStashSessionId
+ ? this.promptStashStore.forSession(this.promptStashSessionId)
+ : {};
+ this.hydratePromptStash();
this.localSessionHost = options.localSessionHost;
this.bindLocalSessionExtensions = options.bindLocalSessionExtensions ?? options.localSessionHost !== undefined;
if (this.bindLocalSessionExtensions && !options.localSessionHost) {
@@ -944,6 +951,43 @@ export class InteractiveMode {
initTheme(this.settingsManager.getTheme(), true);
}
+ private get promptStash(): PromptStash | undefined {
+ return this.promptStashState.stash;
+ }
+
+ private set promptStash(stash: PromptStash | undefined) {
+ this.promptStashState.stash = stash;
+ }
+
+ private hydratePromptStash(): void {
+ const stash = this.promptStash;
+ if (!stash) {
+ return;
+ }
+ for (const [markerId, image] of stash.images ?? []) {
+ this.pastedImages.set(markerId, image);
+ }
+ for (const markerId of imageMarkerIds(stash.text)) {
+ this.nextImageMarkerId = Math.max(this.nextImageMarkerId, markerId + 1);
+ }
+ }
+
+ private bindPromptStashSession(sessionId: string): void {
+ if (!this.promptStashStore || this.promptStashSessionId === sessionId) {
+ return;
+ }
+ this.releasePromptStashSession();
+ this.promptStashSessionId = sessionId;
+ this.promptStashState = this.promptStashStore.forSession(sessionId);
+ this.hydratePromptStash();
+ }
+
+ private releasePromptStashSession(): void {
+ if (this.promptStashStore && this.promptStashSessionId) {
+ this.promptStashStore.release(this.promptStashSessionId, this.promptStashState);
+ }
+ }
+
private getAutocompleteSourceTag(sourceInfo?: AgentConnectionSourceInfo): string | undefined {
if (!sourceInfo) {
return undefined;
@@ -2253,6 +2297,7 @@ export class InteractiveMode {
}
private applyConnectionStateSnapshot(state: AgentConnectionState): void {
+ this.bindPromptStashSession(state.sessionId);
this.connectionState = state;
// Don't touch contextUsageTokenBaseline: a mid-stream snapshot reflects only completed
// turns (the in-flight message isn't persisted yet), so the in-flight delta must keep
@@ -3675,10 +3720,12 @@ export class InteractiveMode {
return;
}
const pasteSnapshot = this.editor.getPasteSnapshot?.();
+ const images = this.getPromptStashImages(text);
this.promptStash = {
text,
expandedText: pasteSnapshot ? (this.editor.getExpandedText?.() ?? text) : undefined,
pasteSnapshot,
+ ...(images.length > 0 ? { images } : {}),
};
this.editor.setText("");
this.showStatus("Stashed prompt");
@@ -3702,6 +3749,17 @@ export class InteractiveMode {
return true;
}
+ private getPromptStashImages(text: string): readonly (readonly [number, ImageContent])[] {
+ const images: Array<readonly [number, ImageContent]> = [];
+ for (const markerId of imageMarkerIds(text)) {
+ const image = this.pastedImages.get(markerId);
+ if (image) {
+ images.push([markerId, image]);
+ }
+ }
+ return images;
+ }
+
private async handleClipboardImagePaste(): Promise<void> {
try {
const image = await readClipboardImage();
@@ -4226,7 +4284,7 @@ export class InteractiveMode {
this.resetSideQuestion();
this.resetExtensionUI();
this.applyConnectionStateSnapshot(event.state);
- this.resetCurrentSessionRenderState({ clearPromptStash: true });
+ this.resetCurrentSessionRenderState();
await this.rebindCurrentSession();
await this.renderInitialMessages();
this.ui.requestRender();
@@ -6031,6 +6089,7 @@ export class InteractiveMode {
*/
async teardownSessionUi(options: { preserveAltScreen?: boolean } = {}): Promise<void> {
await this.ui.terminal.drainInput(1000).catch(() => undefined);
+ this.releasePromptStashSession();
this.stop({ preserveAltScreen: options.preserveAltScreen });
stopThemeWatcher();
}
diff --git a/packages/coding-agent/src/modes/interactive/prompt-stash-state.ts b/packages/coding-agent/src/modes/interactive/prompt-stash-state.ts
new file mode 100644
index 0000000000..87705eaa97
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/prompt-stash-state.ts
@@ -0,0 +1,32 @@
+import type { ImageContent } from "@earendil-works/pi-ai";
+import type { EditorPasteSnapshot } from "@earendil-works/pi-tui";
+
+export interface PromptStash {
+ text: string;
+ expandedText?: string;
+ pasteSnapshot?: EditorPasteSnapshot;
+ images?: readonly (readonly [number, ImageContent])[];
+}
+
+export interface PromptStashState {
+ stash?: PromptStash;
+}
+
+export class ClientPromptStashStore {
+ private readonly states = new Map<string, PromptStashState>();
+
+ forSession(sessionId: string): PromptStashState {
+ let state = this.states.get(sessionId);
+ if (!state) {
+ state = {};
+ this.states.set(sessionId, state);
+ }
+ return state;
+ }
+
+ release(sessionId: string, state: PromptStashState): void {
+ if (state.stash === undefined && this.states.get(sessionId) === state) {
+ this.states.delete(sessionId);
+ }
+ }
+}
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 2335e181eb..1b5c91cfe5 100644
--- a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
+++ b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
@@ -1,6 +1,8 @@
+import type { ImageContent } from "@earendil-works/pi-ai";
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";
type FakePasteSnapshot = {
pastes: readonly (readonly [number, string])[];
@@ -11,6 +13,7 @@ type PromptStash = {
text: string;
expandedText?: string;
pasteSnapshot?: FakePasteSnapshot;
+ images?: readonly (readonly [number, ImageContent])[];
};
type FakeEditor = {
@@ -42,6 +45,14 @@ type PromptStashLiveMarkerHarness = PromptStashHarness & {
connectionQueue: { steering: string[]; followUp: string[] };
};
+type SharedPromptStashHarness = PromptStashHarness & {
+ promptStashStore: ClientPromptStashStore;
+ promptStashSessionId: string;
+ promptStashState: PromptStashState;
+ pastedImages: Map<number, ImageContent>;
+ nextImageMarkerId: number;
+};
+
type ResetHarness = PromptStashLiveMarkerHarness & {
chatContainer: { clear: Mock };
shortcutGuideContainer: { clear: Mock };
@@ -77,8 +88,10 @@ type SubmitHarness = PromptStashHarness & {
};
type PromptStashMethods = {
+ bindPromptStashSession: (this: SharedPromptStashHarness, sessionId: string) => void;
handleFollowUp: (this: SubmitHarness) => Promise<void>;
handlePromptStash: (this: PromptStashHarness) => void;
+ hydratePromptStash: (this: SharedPromptStashHarness) => void;
resetCurrentSessionRenderState: (this: ResetHarness, options?: { clearPromptStash?: boolean }) => void;
restorePromptStashIfEditorEmpty: (this: PromptStashHarness, stash?: PromptStash) => boolean;
liveImageMarkerIds: (this: PromptStashLiveMarkerHarness) => Set<number>;
@@ -140,6 +153,30 @@ function createPromptStashHarness(
return harness;
}
+function createSharedPromptStashHarness(
+ store: ClientPromptStashStore,
+ sessionId: string,
+ options: {
+ text?: string;
+ expandedText?: string;
+ pasteSnapshot?: FakePasteSnapshot;
+ pastedImages?: readonly (readonly [number, ImageContent])[];
+ } = {},
+): SharedPromptStashHarness {
+ const harness = {
+ promptStashStore: store,
+ promptStashSessionId: sessionId,
+ promptStashState: store.forSession(sessionId),
+ editor: createEditor(options),
+ showStatus: vi.fn(),
+ clearShortcutGuide: vi.fn(),
+ pastedImages: new Map(options.pastedImages),
+ nextImageMarkerId: 1,
+ } as SharedPromptStashHarness;
+ 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();
@@ -147,6 +184,64 @@ describe("InteractiveMode prompt stash", () => {
expect(keybindings.getKeys("app.prompt.stash")).toEqual(["ctrl+s"]);
});
+ it("isolates stashes for separate TUI clients attached to the same session", () => {
+ const firstClient = new ClientPromptStashStore();
+ const secondClient = new ClientPromptStashStore();
+ const firstState = firstClient.forSession("shared-session");
+ firstState.stash = { text: "first client draft" };
+
+ expect(firstClient.forSession("shared-session")).toBe(firstState);
+ expect(secondClient.forSession("shared-session").stash).toBeUndefined();
+
+ const emptyState = firstClient.forSession("empty-session");
+ firstClient.release("empty-session", emptyState);
+ expect(firstClient.forSession("empty-session")).not.toBe(emptyState);
+ });
+
+ it("restores a session stash after recreating its interactive mode", () => {
+ const store = new ClientPromptStashStore();
+ const pasteSnapshot: FakePasteSnapshot = {
+ pastes: [[1, "line one\nline two"]],
+ pasteCounter: 1,
+ };
+ const image: ImageContent = { type: "image", data: "aW1hZ2U=", mimeType: "image/png" };
+ const firstMode = createSharedPromptStashHarness(store, "session-a", {
+ text: "draft [image #7] [paste #1 +2 lines]",
+ expandedText: "draft [image #7] line one\nline two",
+ pasteSnapshot,
+ pastedImages: [[7, image]],
+ });
+
+ interactiveModeMethods.handlePromptStash.call(firstMode);
+
+ const reopenedMode = createSharedPromptStashHarness(store, "session-a");
+ interactiveModeMethods.hydratePromptStash.call(reopenedMode);
+
+ expect(reopenedMode.promptStash?.text).toBe("draft [image #7] [paste #1 +2 lines]");
+ expect(reopenedMode.pastedImages.get(7)).toBe(image);
+ expect(reopenedMode.nextImageMarkerId).toBe(8);
+
+ interactiveModeMethods.restorePromptStashIfEditorEmpty.call(reopenedMode);
+
+ expect(reopenedMode.editor.getText()).toBe("draft [image #7] [paste #1 +2 lines]");
+ expect(reopenedMode.editor.restoredPasteSnapshot).toBe(pasteSnapshot);
+ expect(reopenedMode.promptStashState.stash).toBeUndefined();
+ });
+
+ it("rebinds prompt stash state when the connected session changes", () => {
+ const store = new ClientPromptStashStore();
+ const firstState = store.forSession("session-a");
+ const secondState = store.forSession("session-b");
+ firstState.stash = { text: "session a draft" };
+ secondState.stash = { text: "session b draft" };
+ const mode = createSharedPromptStashHarness(store, "session-a");
+
+ interactiveModeMethods.bindPromptStashSession.call(mode, "session-b");
+
+ expect(mode.promptStash?.text).toBe("session b draft");
+ expect(firstState.stash?.text).toBe("session a draft");
+ });
+
it("stashes editor text without expanding paste markers", () => {
const pasteSnapshot: FakePasteSnapshot = {
pastes: [[1, "line one\nline two"]],
@@ -374,7 +469,7 @@ describe("InteractiveMode prompt stash", () => {
expect(mode.pastedImages.has(2)).toBe(false);
});
- it("clears stashed prompt state on external session replacement resets", () => {
+ it("clears stashed prompt state when explicitly requested", () => {
const base = createPromptStashHarness({ stash: "drop [image #1]" });
const mode: ResetHarness = {
...base,
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index 5a5b840180..b067b98204 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -751,7 +751,7 @@ describe("InteractiveMode connection events", () => {
expect(resetRenderOrder).toBeLessThan(rebindOrder);
expect(rebindOrder).toBeLessThan(renderMessagesOrder);
expect(fakeThis.applyConnectionStateSnapshot).toHaveBeenCalledWith(state);
- expect(fakeThis.resetCurrentSessionRenderState).toHaveBeenCalledWith({ clearPromptStash: true });
+ expect(fakeThis.resetCurrentSessionRenderState).toHaveBeenCalledWith();
expect(fakeThis.rebindCurrentSession).toHaveBeenCalledWith();
expect(fakeThis.renderInitialMessages).toHaveBeenCalledWith();
expect(fakeThis.ui.requestRender).toHaveBeenCalledWith();