Skip to content

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

Rust

restore the stashed prompt after sending another prompt (#3313)

Sebastian Müller8a459cbaa7cf
diff --git a/.changes/unstash-on-send.md b/.changes/unstash-on-send.md
new file mode 100644
index 0000000000..bedfdf0960
--- /dev/null
+++ b/.changes/unstash-on-send.md
@@ -0,0 +1 @@
+- A prompt stashed with ctrl+s now returns to the empty prompt box after you send another prompt, as it did in the TypeScript version.
diff --git a/crates/pa-cli/tests/interactive_daemon_e2e.rs b/crates/pa-cli/tests/interactive_daemon_e2e.rs
index dbbebadb82..e9856c6c70 100644
--- a/crates/pa-cli/tests/interactive_daemon_e2e.rs
+++ b/crates/pa-cli/tests/interactive_daemon_e2e.rs
@@ -4325,8 +4325,9 @@ async fn tui_ctrl_s_stashes_and_restores_the_prompt_draft() {
/// with nothing stashed reports "No prompt to stash", and the key with a
/// draft while a stash is already held reports "Prompt stash already has
/// a draft" — the fresh draft STAYS in the editor (the manual stash never
-/// clobbers a held one), submits on Enter, and the held draft is still
-/// what the next key press restores.
+/// clobbers a held one), submits on Enter, and the admitted send
+/// restores the held draft into the emptied editor (TS
+/// `promptStashToRestore`).
#[tokio::test]
async fn tui_ctrl_s_stash_keeps_a_held_draft_and_reports_the_empty_editor() {
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
@@ -4413,13 +4414,13 @@ async fn tui_ctrl_s_stash_keeps_a_held_draft_and_reports_the_empty_editor() {
},
// The fresh draft stayed live: Enter submits it.
key(KeyCode::Enter, KeyModifiers::NONE),
- pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 30_000 },
- // The stash still holds the FIRST draft: the key restores it.
- key(KeyCode::Char('s'), KeyModifiers::CONTROL),
+ // The admitted submit returns the held FIRST draft to the emptied
+ // editor (TS `promptStashToRestore`, interactive-mode.ts:5752-5759).
pa_tui::interactive::HeadlessStep::WaitRender {
needle: "Restored stashed prompt".to_string(),
timeout_ms: 5_000,
},
+ pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 30_000 },
],
width: 100,
height: 30,
@@ -4440,7 +4441,7 @@ async fn tui_ctrl_s_stash_keeps_a_held_draft_and_reports_the_empty_editor() {
"the fresh draft stayed in the editor at the guard:\n{}",
frames[guard_index]
);
- // The stash still held the first draft: the final key restored it.
+ // The admitted send restored the held first draft into the editor.
let restore_index = frames
.iter()
.position(|frame| frame.contains("Restored stashed prompt"))
@@ -4449,7 +4450,7 @@ async fn tui_ctrl_s_stash_keeps_a_held_draft_and_reports_the_empty_editor() {
frames[restore_index..]
.iter()
.any(|frame| frame.contains("f24 guard draft")),
- "the held draft (not the fresh one) restored last"
+ "the admitted send restored the held draft into the editor"
);
// Daemon-side: the fresh draft submitted (it never left the editor).
diff --git a/crates/pa-tui/README.md b/crates/pa-tui/README.md
index 6d7d4c1b62..888db31581 100644
--- a/crates/pa-tui/README.md
+++ b/crates/pa-tui/README.md
@@ -3,7 +3,7 @@
The terminal UI.
## Scope
-Rendering (markdown, themes, layout, tool panels, custom-message decorated rows: the agent-message summary rows render the viewer-relative notice (the shared `Agent message` label, the ↑ sent/queued and ↓ received arrows from the row's actual direction, the counterpart agent's name only, no collapsed body preview — the operator's 2026-09-25 directive), and the ipython cell renders the sent/queued receipt rows below the code, and the RLM child rows render the outcome diamond rows — accent diamond, semantic label colors, the failure error and the cancellation reason as the expandable body; the skill-invocation card — TS `SkillInvocationMessageComponent`: a user message whose text is one `<skill ...>` block renders the `[skill] <name>` card collapsed, the `**<name>**` + content markdown expanded over the shared `pa_types::skill_blocks` parse, and the trailing invocation args as their own user block), the working loader row (activity label, TS `formatWorkingElapsed`, and the tool-owned working note during python-kernel boot, sourced from `starting` tool partials), image support (the terminal-image library: capability detection, Kitty/iTerm2 protocol encoders, dimension parsing; the image component with the fullscreen compose fallback; `terminal.showImages` gating of tool-result image rows; clipboard image paste behind `app.clipboard.pasteImage` with `[image #N]` editor markers, byte-budgeted registry, and wire-image attach), editor (cursor/kill-ring/undo/history/word ops, with the live prompt highlight: argument tokens in their TS colors on every line and the first line's slash-command token in accent for any recognized builtin command (sanctioned divergence, operator ruling 2026-09-29: TS accents argument-taking commands only) — suppressed while the cursor sits inside it, TS `CustomEditor.styleDisplayText`), the transcript prompt-highlight surfaces (TS `PromptTokenMask`: the user-message block masks its accent command segment and argument tokens to same-width private-use placeholders before the markdown layout and restores them after, TS `UserMessageComponent`; the session-command echo row styles the typed command the TS `SlashCommandMessageComponent` way — accent command segment, colored tokens, styled wrap), and the suspend-to-background cycle (`app.suspend`, default ctrl+z, TS `handleCtrlZ`: SIGINT ignored for the stopped window, the TUI stopped with the terminal handed to the shell, the process group SIGTSTP'd; the SIGCONT resume re-applies raw mode, the alternate screen, and SGR mouse tracking — the terminal modes a suspend cycle can lose), keybindings (user-editable via `~/.prime/agent/keybindings.json`: TS parse/migration/merge semantics — legacy id migration on load and at startup, malformed values dropped, empty-array disables, same-scope default eviction, conflicts, case/order-insensitive matching — the effective set wired into every hint, handler, and picker), autocomplete (slash commands, path completion, and the `@` fuzzy file search: a parallel `ignore` walk with fd's semantics, off the UI thread), fullscreen/scrollback (the wheel-scroll surface: SGR mouse-report decoding, `?1002`+`?1006` tracking enabled blind at the fullscreen surface's entry and released on exit/suspend — tmux never answers DECRQM, unsupporting terminals ignore the mode-sets — wheel turns scroll the transcript three lines, consumed without scrolling while a picker owns the frame or when the `terminal.fullscreenMouse` setting disabled tracking; in-frame click/drag selection stays unported), input handling, and the double-Ctrl+C force-quit guard (the exit contract: two in-window Ctrl+C presses end the process within 1.5s of the second press regardless of daemon or loop state; cleanup inside that window is best-effort). Interactive sessions attached through the daemon: the prompt stash (TS `prompt-stash-state.ts`: the client-owned per-session draft store shared across a TUI process's chat views — a draft left behind on a session switch returns to the editor when the session's chat reopens, its pasted images rehydrated behind their markers; the capture on the agents-view handoffs (`/resume`, the rebound `app.session.resume` key, the scoped view, `/resume <selector>`) and the in-place `/switch`, the restore on reopen/switch-back, and the queued-stash semantics for multi-switch chains; the manual `app.prompt.stash` capture (default ctrl+s, TS `handlePromptStash`): the key stashes the live draft and clears the editor, restores it on the next press, and a manually stashed draft returns only on that key — never on a reopen or a switch landing), the JSONL client socket (hello handshake, command envelopes, session-event loop), slim-attach snapshot reconstruction, the direct worker link loss path (a killed/crashed worker tears the link; the UI re-attaches through the supervisor with the TS reconnect surface - the `Daemon connection lost; reconnecting…` warning, the resync, `Daemon reconnected`, the 60s TS window with TS backoff, and the terminal `⚠ Error: Daemon reconnection failed: <last>` arm with dispatch blocked so the UI never rides a silent spinner), prompt submission with streamed assistant output, live session list and switch, the inline pickers (`/model`: the TS inline menu-panel - the bordered `Search models` field, `>`-marker rows with the effort-square cluster and `current · require sign in · provider` trailing, the price detail block, and the model/effort key hint - over the catalog the daemon's `get_model_catalog` refresh supplies (bundled + models.json fallback), with the TS sort chain, the scored fuzzy filter, left/right effort adjustment, and apply through the daemon `set_model` command (plus `set_thinking_level` for a user-edited effort) with the `Model: <id>` status row; `/effort`: the session's thinking levels from `get_state`, the unsupported-model note, and apply through `set_thinking_level`; `/mcp`: the inline connections view over the daemon's `get_mcp_connections` roster - the TS MCP-Connections-tab panel (bordered `Search MCP connections` field, `›` rows with the status flush right on connected entries, the selected connection's detail block with its tool listing, the navigate/select/close hint), Enter resolving to the selected connection's login command through the interactive loop's client-command seam, plus the api-key credential rows the same response serves (the stored keys, e.g. the web-search one; Enter runs the paste-the-key prompt, a rust-only surface - the operator's `/login`-is-providers-only ruling moved the key here, TS still serves it on its `/login` MCP tab); `/heartbeats`: the inline management view (TS `HeartbeatManagerComponent`, inline-picker style per the lane directive): the session-scoped user and agent heartbeat catalog from the selector-less supervisor `heartbeats_list` — scoped like TS `scopeHeartbeatsToSession` to this session and its roster descendants — with the TS count label, `›` rows with status-colored trailing, the selection's detail line, the actions pane (pause/resume/stop through `heartbeat_manage`), the fetch/action error rows, the `heartbeats_changed` broadcast refresh through the update channel, and the tray heartbeat label `N heartbeats · M paused (Ctrl+R)`; ctrl+r (`app.heartbeats.open`) opens it from anywhere), the TS `showStatus` back-to-back rewrite (a status emitted with nothing after the previous one rewrites it in place), the session export and share commands (`/export [path]`: the path-argument parse, the `.jsonl` branch switch, the daemon-side `export_html`/`export_jsonl` requests, and the `Session exported to:` row; `/share`: the gh auth gate, the temp export, the background `gh gist create` run behind the bordered `Creating gist...` loader with Esc cancel, and the `Share URL:`/`Gist:` rows - the gist provider is the GitHub CLI exactly like TS), the visible follow-up queue (TS `queuedMessagesContainer`): prompts parked behind a running turn render as dim preview rows above the prompt dock with the TS prompt-highlight styling (accent on a leading slash command's `/name` segment, `success`/`mdLink` on `@path`/`--flag` argument tokens — TS `styleQueuedMessagePreview`) — `Steering:`/`Follow-up:` labels with the `╰─ <key> to browse and edit queued messages` hint, re-synced from `state.sessionActions` on attach and kept live by `session_action_update`; the queued internal prompts (heartbeat fires, agent messages, goal contexts, background-command notices) condense into one counted row below the human previews — "1 agent message, 1 heartbeat, and 1 other internal prompt queued": each origin's own count, singular/plural-correct, zero-count origins omitted (sanctioned divergence, operator requests 2026-09-24 + 2026-09-25: TS renders every internal prompt as its own preview row; the browse/edit affordances still walk every queued item, so only the strip rows condense — the four TS-internal labels classify by preview string, TS `isLabeledQueuedPreview`, the queue wire carries no provenance for them, so a human-typed prompt that begins with one of the internal labels classifies internal for the strip too: it still delivers, and the browse/edit affordance walks and shows it; the parked RLM child status notices — the `[child-exited: ...]`/`[child-failed ...]` lifecycle rows the queue-fold operator bug 2026-09-25 flooded the strip with — classify by WIRE-TYPED provenance instead, never by their text: the worker's `sessionActions.rlmChildStatus` rider carries the parked injected rows' lane indices, they count as their own origin ("N child status notices"), and a user-typed lookalike stays a human row); the collapsed conversation view (operator directive 2026-09-28, the undo of the 2026-09-25 condensed-run summary block): the collapse mode renders every activity item exactly as `details` does - every tool card, every notice, every agent-message row - with ONLY the thinking blocks hidden (the TS fork's shape), a chat starts at that collapsed level, and the Ctrl+O cycle from there is the thinking-visibility toggle (overview -> details -> all -> overview unchanged; a card click toggles only the clicked card's own expansion - TS's per-component `expanded` - and the Ctrl+O cycle resets every card to the new level) - purely render-time over the unchanged transcript model (no session jsonl schema change, no stored-event change); the follow-up key (`app.message.followUp`, default alt+enter) parks a submission on the follow-up lane (`streamingBehavior: "followUp"` + `queueIfBusy`), Enter on the steering lane; the browse affordances TS gives the rows (TS `QueueSelection` port): alt+up/alt+down walk the parked messages newest-first with the editor draft stashed and restored, the dim browse header (lane, index, key hints) renders as the editor box header row, Enter steers the edit (replace/move to steering, empty deletes), the follow-up key re-parks it, ctrl+alt+arrows reorder through `mutate_queued_message` (mirrored locally like TS — the event can land after the response), the clear key restores the draft, and queue-change statuses surface the TS status rows verbatim; and the utility slash commands (TS `dispatch_client_command` arms): `/btw`+`/side` (the side-question pane over the daemon `start_side_question`/`abort_side_question` flow — the popup-surface turns with the `/btw` header, follow-up bubbles, the slash/image rejection notices, the running/return hint rows, Esc cancel; replies while the pane is open seed follow-ups from the answered turns), `/fast` (the priority-tier toggle with the TS eligibility check and unavailable status), `/rlm-max-depth` (view/set with the `--global` arm and the TS status rows), `/name`+`/rename` (the daemon `set_session_name` rename whose persisted `session_info` entry and `session_info_changed` broadcast the daemon owns), `/settings` (the TS `SettingsList` grouped into tabs — the spaced tab strip (white-bold active tab) over label/value rows with descriptions, ←/→/Enter/Space value cycling (the arrows step a row's options in place; Tab/Shift+Tab and the number keys move the tabs), the detail block's separator rule and description-matched hint padding, the thinking/theme/warnings/service-tier submenus with the theme's live preview and restore, type-to-search; daemon switches for autocompact/steering/follow-up/transport/thinking, the client-settings seam for the persisted preferences), and `/reload` (the TS guards, the bordered reload box, the daemon reload request, keybinding/theme/catalog re-reads, and the outcome row); `/thinking` rides the registry alias into `/effort`. The client-settings seam (`client_settings::ClientSettings`, implemented by the composition root) is how pa-tui persists user preferences without a pa-core dependency; the autocomplete listing drops `/fast` when the current model is not fast-mode-eligible (the pa-types `supports_fast_mode` helper), the subagent summary line under the tray (TS `SubagentSummaryLine`: live descendant counts from the roster subscription, the dock renders in every session, all-zero included (the operator's 2026-09-28 directive; TS renders nothing at zero, a sanctioned divergence), and its Subagents group opens the scoped agents view even with no children, which shows the view's `No sessions yet.` empty state, the focus hand-off from the editor — Down at the end of the prompt or `app.subagents.focus` — the focused key contract — confirm/open into the focused group's own view, left/right stepping every rendered group (an empty one included, wrapping at the row's ends — the operator's 2026-09-26 muscle-memory directive), up/cancel/back to the editor, expand keeping the focus, other keys releasing it into the editor path — and the scoped-view hand-off; every dock panel's exit (ESC/left from the heartbeats view, the bash view, the goal panel, or the scoped agents view's back keys) restores the dock's focus on the panel's own group instead of the prompt bar — the operator's 2026-09-26 panel-exit ruling; TS has no multi-group dock, its panels close to the editor, a sanctioned divergence); and the agents view (the unified live-roster +saved-catalog session list: Running/Idle/Inactive sections, inline search(TS query language: case-insensitive substring tokens, `"quoted phrases"`,
+Rendering (markdown, themes, layout, tool panels, custom-message decorated rows: the agent-message summary rows render the viewer-relative notice (the shared `Agent message` label, the ↑ sent/queued and ↓ received arrows from the row's actual direction, the counterpart agent's name only, no collapsed body preview — the operator's 2026-09-25 directive), and the ipython cell renders the sent/queued receipt rows below the code, and the RLM child rows render the outcome diamond rows — accent diamond, semantic label colors, the failure error and the cancellation reason as the expandable body; the skill-invocation card — TS `SkillInvocationMessageComponent`: a user message whose text is one `<skill ...>` block renders the `[skill] <name>` card collapsed, the `**<name>**` + content markdown expanded over the shared `pa_types::skill_blocks` parse, and the trailing invocation args as their own user block), the working loader row (activity label, TS `formatWorkingElapsed`, and the tool-owned working note during python-kernel boot, sourced from `starting` tool partials), image support (the terminal-image library: capability detection, Kitty/iTerm2 protocol encoders, dimension parsing; the image component with the fullscreen compose fallback; `terminal.showImages` gating of tool-result image rows; clipboard image paste behind `app.clipboard.pasteImage` with `[image #N]` editor markers, byte-budgeted registry, and wire-image attach), editor (cursor/kill-ring/undo/history/word ops, with the live prompt highlight: argument tokens in their TS colors on every line and the first line's slash-command token in accent for any recognized builtin command (sanctioned divergence, operator ruling 2026-09-29: TS accents argument-taking commands only) — suppressed while the cursor sits inside it, TS `CustomEditor.styleDisplayText`), the transcript prompt-highlight surfaces (TS `PromptTokenMask`: the user-message block masks its accent command segment and argument tokens to same-width private-use placeholders before the markdown layout and restores them after, TS `UserMessageComponent`; the session-command echo row styles the typed command the TS `SlashCommandMessageComponent` way — accent command segment, colored tokens, styled wrap), and the suspend-to-background cycle (`app.suspend`, default ctrl+z, TS `handleCtrlZ`: SIGINT ignored for the stopped window, the TUI stopped with the terminal handed to the shell, the process group SIGTSTP'd; the SIGCONT resume re-applies raw mode, the alternate screen, and SGR mouse tracking — the terminal modes a suspend cycle can lose), keybindings (user-editable via `~/.prime/agent/keybindings.json`: TS parse/migration/merge semantics — legacy id migration on load and at startup, malformed values dropped, empty-array disables, same-scope default eviction, conflicts, case/order-insensitive matching — the effective set wired into every hint, handler, and picker), autocomplete (slash commands, path completion, and the `@` fuzzy file search: a parallel `ignore` walk with fd's semantics, off the UI thread), fullscreen/scrollback (the wheel-scroll surface: SGR mouse-report decoding, `?1002`+`?1006` tracking enabled blind at the fullscreen surface's entry and released on exit/suspend — tmux never answers DECRQM, unsupporting terminals ignore the mode-sets — wheel turns scroll the transcript three lines, consumed without scrolling while a picker owns the frame or when the `terminal.fullscreenMouse` setting disabled tracking; in-frame click/drag selection stays unported), input handling, and the double-Ctrl+C force-quit guard (the exit contract: two in-window Ctrl+C presses end the process within 1.5s of the second press regardless of daemon or loop state; cleanup inside that window is best-effort). Interactive sessions attached through the daemon: the prompt stash (TS `prompt-stash-state.ts`: the client-owned per-session draft store shared across a TUI process's chat views — a draft left behind on a session switch returns to the editor when the session's chat reopens, its pasted images rehydrated behind their markers; the capture on the agents-view handoffs (`/resume`, the rebound `app.session.resume` key, the scoped view, `/resume <selector>`) and the in-place `/switch`, the restore on reopen/switch-back, and the queued-stash semantics for multi-switch chains; the manual `app.prompt.stash` capture (default ctrl+s, TS `handlePromptStash`): the key stashes the live draft and clears the editor, restores it on the next press, and a manually stashed draft returns on that key or after the next sent prompt is admitted — never on a reopen or a switch landing), the JSONL client socket (hello handshake, command envelopes, session-event loop), slim-attach snapshot reconstruction, the direct worker link loss path (a killed/crashed worker tears the link; the UI re-attaches through the supervisor with the TS reconnect surface - the `Daemon connection lost; reconnecting…` warning, the resync, `Daemon reconnected`, the 60s TS window with TS backoff, and the terminal `⚠ Error: Daemon reconnection failed: <last>` arm with dispatch blocked so the UI never rides a silent spinner), prompt submission with streamed assistant output, live session list and switch, the inline pickers (`/model`: the TS inline menu-panel - the bordered `Search models` field, `>`-marker rows with the effort-square cluster and `current · require sign in · provider` trailing, the price detail block, and the model/effort key hint - over the catalog the daemon's `get_model_catalog` refresh supplies (bundled + models.json fallback), with the TS sort chain, the scored fuzzy filter, left/right effort adjustment, and apply through the daemon `set_model` command (plus `set_thinking_level` for a user-edited effort) with the `Model: <id>` status row; `/effort`: the session's thinking levels from `get_state`, the unsupported-model note, and apply through `set_thinking_level`; `/mcp`: the inline connections view over the daemon's `get_mcp_connections` roster - the TS MCP-Connections-tab panel (bordered `Search MCP connections` field, `›` rows with the status flush right on connected entries, the selected connection's detail block with its tool listing, the navigate/select/close hint), Enter resolving to the selected connection's login command through the interactive loop's client-command seam, plus the api-key credential rows the same response serves (the stored keys, e.g. the web-search one; Enter runs the paste-the-key prompt, a rust-only surface - the operator's `/login`-is-providers-only ruling moved the key here, TS still serves it on its `/login` MCP tab); `/heartbeats`: the inline management view (TS `HeartbeatManagerComponent`, inline-picker style per the lane directive): the session-scoped user and agent heartbeat catalog from the selector-less supervisor `heartbeats_list` — scoped like TS `scopeHeartbeatsToSession` to this session and its roster descendants — with the TS count label, `›` rows with status-colored trailing, the selection's detail line, the actions pane (pause/resume/stop through `heartbeat_manage`), the fetch/action error rows, the `heartbeats_changed` broadcast refresh through the update channel, and the tray heartbeat label `N heartbeats · M paused (Ctrl+R)`; ctrl+r (`app.heartbeats.open`) opens it from anywhere), the TS `showStatus` back-to-back rewrite (a status emitted with nothing after the previous one rewrites it in place), the session export and share commands (`/export [path]`: the path-argument parse, the `.jsonl` branch switch, the daemon-side `export_html`/`export_jsonl` requests, and the `Session exported to:` row; `/share`: the gh auth gate, the temp export, the background `gh gist create` run behind the bordered `Creating gist...` loader with Esc cancel, and the `Share URL:`/`Gist:` rows - the gist provider is the GitHub CLI exactly like TS), the visible follow-up queue (TS `queuedMessagesContainer`): prompts parked behind a running turn render as dim preview rows above the prompt dock with the TS prompt-highlight styling (accent on a leading slash command's `/name` segment, `success`/`mdLink` on `@path`/`--flag` argument tokens — TS `styleQueuedMessagePreview`) — `Steering:`/`Follow-up:` labels with the `╰─ <key> to browse and edit queued messages` hint, re-synced from `state.sessionActions` on attach and kept live by `session_action_update`; the queued internal prompts (heartbeat fires, agent messages, goal contexts, background-command notices) condense into one counted row below the human previews — "1 agent message, 1 heartbeat, and 1 other internal prompt queued": each origin's own count, singular/plural-correct, zero-count origins omitted (sanctioned divergence, operator requests 2026-09-24 + 2026-09-25: TS renders every internal prompt as its own preview row; the browse/edit affordances still walk every queued item, so only the strip rows condense — the four TS-internal labels classify by preview string, TS `isLabeledQueuedPreview`, the queue wire carries no provenance for them, so a human-typed prompt that begins with one of the internal labels classifies internal for the strip too: it still delivers, and the browse/edit affordance walks and shows it; the parked RLM child status notices — the `[child-exited: ...]`/`[child-failed ...]` lifecycle rows the queue-fold operator bug 2026-09-25 flooded the strip with — classify by WIRE-TYPED provenance instead, never by their text: the worker's `sessionActions.rlmChildStatus` rider carries the parked injected rows' lane indices, they count as their own origin ("N child status notices"), and a user-typed lookalike stays a human row); the collapsed conversation view (operator directive 2026-09-28, the undo of the 2026-09-25 condensed-run summary block): the collapse mode renders every activity item exactly as `details` does - every tool card, every notice, every agent-message row - with ONLY the thinking blocks hidden (the TS fork's shape), a chat starts at that collapsed level, and the Ctrl+O cycle from there is the thinking-visibility toggle (overview -> details -> all -> overview unchanged; a card click toggles only the clicked card's own expansion - TS's per-component `expanded` - and the Ctrl+O cycle resets every card to the new level) - purely render-time over the unchanged transcript model (no session jsonl schema change, no stored-event change); the follow-up key (`app.message.followUp`, default alt+enter) parks a submission on the follow-up lane (`streamingBehavior: "followUp"` + `queueIfBusy`), Enter on the steering lane; the browse affordances TS gives the rows (TS `QueueSelection` port): alt+up/alt+down walk the parked messages newest-first with the editor draft stashed and restored, the dim browse header (lane, index, key hints) renders as the editor box header row, Enter steers the edit (replace/move to steering, empty deletes), the follow-up key re-parks it, ctrl+alt+arrows reorder through `mutate_queued_message` (mirrored locally like TS — the event can land after the response), the clear key restores the draft, and queue-change statuses surface the TS status rows verbatim; and the utility slash commands (TS `dispatch_client_command` arms): `/btw`+`/side` (the side-question pane over the daemon `start_side_question`/`abort_side_question` flow — the popup-surface turns with the `/btw` header, follow-up bubbles, the slash/image rejection notices, the running/return hint rows, Esc cancel; replies while the pane is open seed follow-ups from the answered turns), `/fast` (the priority-tier toggle with the TS eligibility check and unavailable status), `/rlm-max-depth` (view/set with the `--global` arm and the TS status rows), `/name`+`/rename` (the daemon `set_session_name` rename whose persisted `session_info` entry and `session_info_changed` broadcast the daemon owns), `/settings` (the TS `SettingsList` grouped into tabs — the spaced tab strip (white-bold active tab) over label/value rows with descriptions, ←/→/Enter/Space value cycling (the arrows step a row's options in place; Tab/Shift+Tab and the number keys move the tabs), the detail block's separator rule and description-matched hint padding, the thinking/theme/warnings/service-tier submenus with the theme's live preview and restore, type-to-search; daemon switches for autocompact/steering/follow-up/transport/thinking, the client-settings seam for the persisted preferences), and `/reload` (the TS guards, the bordered reload box, the daemon reload request, keybinding/theme/catalog re-reads, and the outcome row); `/thinking` rides the registry alias into `/effort`. The client-settings seam (`client_settings::ClientSettings`, implemented by the composition root) is how pa-tui persists user preferences without a pa-core dependency; the autocomplete listing drops `/fast` when the current model is not fast-mode-eligible (the pa-types `supports_fast_mode` helper), the subagent summary line under the tray (TS `SubagentSummaryLine`: live descendant counts from the roster subscription, the dock renders in every session, all-zero included (the operator's 2026-09-28 directive; TS renders nothing at zero, a sanctioned divergence), and its Subagents group opens the scoped agents view even with no children, which shows the view's `No sessions yet.` empty state, the focus hand-off from the editor — Down at the end of the prompt or `app.subagents.focus` — the focused key contract — confirm/open into the focused group's own view, left/right stepping every rendered group (an empty one included, wrapping at the row's ends — the operator's 2026-09-26 muscle-memory directive), up/cancel/back to the editor, expand keeping the focus, other keys releasing it into the editor path — and the scoped-view hand-off; every dock panel's exit (ESC/left from the heartbeats view, the bash view, the goal panel, or the scoped agents view's back keys) restores the dock's focus on the panel's own group instead of the prompt bar — the operator's 2026-09-26 panel-exit ruling; TS has no multi-group dock, its panels close to the editor, a sanctioned divergence); and the agents view (the unified live-roster +saved-catalog session list: Running/Idle/Inactive sections, inline search(TS query language: case-insensitive substring tokens, `"quoted phrases"`,
`re:` regex, capped fuzzy fallback; the corpus is deliberately restricted to
the session name, the durable session id, and the cwd — the TS corpus fields
(first/last messages, the capped saved transcript, and
diff --git a/crates/pa-tui/src/prompt_stash.rs b/crates/pa-tui/src/prompt_stash.rs
index 46d443a501..7de60688ae 100644
--- a/crates/pa-tui/src/prompt_stash.rs
+++ b/crates/pa-tui/src/prompt_stash.rs
@@ -66,8 +66,9 @@ impl PromptStashState {
/// Take the head draft whatever its restore semantics, promoting the
/// next queued draft to the head (TS `restorePromptStashIfEditorEmpty`
/// with the default `stash` argument — the manual `app.prompt.stash`
- /// arm: the key restores whatever draft the session holds, manual or
- /// auto). The caller owns the editor-empty condition.
+ /// arm and the post-submit restore: the key or an admitted submit
+ /// returns whatever draft the session holds, manual or auto). The
+ /// caller owns the editor-empty condition.
pub fn take_head(&mut self) -> Option<PromptStash> {
let head = self.stash.take();
self.stash = if self.queued_stashes.is_empty() {
diff --git a/crates/pa-tui/src/session_ui/prompt.rs b/crates/pa-tui/src/session_ui/prompt.rs
index 8fb673076f..45bdfc8d26 100644
--- a/crates/pa-tui/src/session_ui/prompt.rs
+++ b/crates/pa-tui/src/session_ui/prompt.rs
@@ -47,6 +47,9 @@ pub(crate) struct PromptSubmitNote {
/// the attachments rehydratable even after the editor cleared and the
/// registry could evict them.
pub(crate) stashed_images: Vec<(u64, LoadedImage)>,
+ /// The stash head this submit captured (TS `promptStashToRestore`): its
+ /// admitted outcome restores it if it is still the head.
+ pub(crate) stash_to_restore: Option<PromptStash>,
/// Whether the turn was already active at submit time (the
/// queued-input telemetry's lane gate; the inline path read the same
/// flag after its await, which nothing could move while the loop was
@@ -89,6 +92,7 @@ pub(crate) struct PromptOrder {
pub(crate) behavior: SubmitBehavior,
pub(crate) images: Option<serde_json::Value>,
pub(crate) stashed_images: Vec<(u64, LoadedImage)>,
+ pub(crate) stash_to_restore: Option<PromptStash>,
pub(crate) turn_was_active: bool,
pub(crate) expected_turn_end: u64,
pub(crate) generation: u64,
@@ -338,7 +342,8 @@ impl SessionUi {
/// `restorePromptStashOnOpen`'s gate) restores only an auto
/// restore-on-open head, while the manual `app.prompt.stash` key
/// restores whatever draft the session holds — a manual stash never
- /// lands on an open or a switch, only on its own key.
+ /// lands on an open or a switch, only on its own key or after the
+ /// next admitted send (TS `promptStashToRestore`).
pub(super) fn restore_prompt_stash_if_editor_empty(
&mut self,
view: &mut AgentView,
@@ -765,11 +770,19 @@ impl SessionUi {
.collect();
self.input_submission_generation += 1;
let generation = self.input_submission_generation;
+ let stash_to_restore = self
+ .prompt_stash
+ .lock()
+ .expect("prompt stash store poisoned")
+ .for_session(&self.stash_session_id)
+ .stash
+ .clone();
self.order_prompt_request(
text.to_string(),
behavior,
images,
stashed_images,
+ stash_to_restore,
true,
generation,
);
@@ -787,12 +800,14 @@ impl SessionUi {
/// one-rebind budget: the first attempt may re-attach and replay on
/// the unknown-session refusal, a replay may not rebind again (the
/// replay is the second and last attempt).
+ #[allow(clippy::too_many_arguments)]
fn order_prompt_request(
&mut self,
text: String,
behavior: SubmitBehavior,
images: Option<serde_json::Value>,
stashed_images: Vec<(u64, LoadedImage)>,
+ stash_to_restore: Option<PromptStash>,
rebind_available: bool,
generation: u64,
) {
@@ -813,6 +828,7 @@ impl SessionUi {
behavior,
images,
stashed_images,
+ stash_to_restore,
turn_was_active,
expected_turn_end,
generation,
@@ -877,6 +893,7 @@ impl SessionUi {
behavior: order.behavior,
images: order.images,
stashed_images: order.stashed_images,
+ stash_to_restore: order.stash_to_restore,
turn_was_active: order.turn_was_active,
expected_turn_end: order.expected_turn_end,
generation: order.generation,
@@ -987,6 +1004,23 @@ impl SessionUi {
self.start_loader(view);
self.dirty = true;
}
+ // TS `onSubmit`'s finally: the current submit's admitted prompt
+ // restores the stash head it captured, if that is still the head.
+ if note.generation == self.input_submission_generation {
+ if let Some(captured) = note.stash_to_restore {
+ let head_unchanged = self
+ .prompt_stash
+ .lock()
+ .expect("prompt stash store poisoned")
+ .for_session(&self.stash_session_id)
+ .stash
+ .as_ref()
+ == Some(&captured);
+ if head_unchanged {
+ self.restore_prompt_stash_if_editor_empty(view, false);
+ }
+ }
+ }
Ok(())
}
Err(error) => {
@@ -1031,6 +1065,7 @@ impl SessionUi {
note.behavior,
note.images.clone(),
note.stashed_images.clone(),
+ note.stash_to_restore.clone(),
false,
note.generation,
);