Skip to content

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

Rust

pa-tui: the agents-view reply composer (TS app.agents.reply, space) (#3170)

Sebastian Müller24285eb03dc6
diff --git a/crates/pa-cli/src/interactive_mode.rs b/crates/pa-cli/src/interactive_mode.rs
index 460fe3898a..27f35cacf6 100644
--- a/crates/pa-cli/src/interactive_mode.rs
+++ b/crates/pa-cli/src/interactive_mode.rs
@@ -302,6 +302,9 @@ async fn run_agents_view_flow(
// dismissed incident never comes back, and the poll does not
// re-read consumed bytes).
incident_notice_state: incident_notice_state.take(),
+ // TS `AgentsViewModeOptions.config`: the flow's own create
+ // config — the base a saved reply's resume derives from.
+ create_config: base.create_config(),
};
let view_run = pa_tui::agents_view::run_agents_view(
view_options,
diff --git a/crates/pa-cli/tests/agents_view_anchor_e2e.rs b/crates/pa-cli/tests/agents_view_anchor_e2e.rs
index f612846a86..7da27f97b9 100644
--- a/crates/pa-cli/tests/agents_view_anchor_e2e.rs
+++ b/crates/pa-cli/tests/agents_view_anchor_e2e.rs
@@ -194,6 +194,7 @@ async fn entry_anchor_selects_the_left_session() {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let plan = AgentsHeadlessPlan {
steps: vec![
@@ -283,6 +284,7 @@ async fn continue_recent_view_preselects_the_candidate_and_renders_the_notice()
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let plan = AgentsHeadlessPlan {
steps: vec![
@@ -356,6 +358,7 @@ async fn rename_saved_session_renames_the_row_and_the_file() {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let plan = AgentsHeadlessPlan {
steps: vec![
diff --git a/crates/pa-cli/tests/agents_view_flash_e2e.rs b/crates/pa-cli/tests/agents_view_flash_e2e.rs
index b975bf6acb..3505bc21b0 100644
--- a/crates/pa-cli/tests/agents_view_flash_e2e.rs
+++ b/crates/pa-cli/tests/agents_view_flash_e2e.rs
@@ -343,6 +343,7 @@ fn view_options(socket: &Path, session_dir: &Path) -> AgentsViewOptions {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}
diff --git a/crates/pa-cli/tests/agents_view_refusal_panel_e2e.rs b/crates/pa-cli/tests/agents_view_refusal_panel_e2e.rs
index 72d74530ff..109c6805a0 100644
--- a/crates/pa-cli/tests/agents_view_refusal_panel_e2e.rs
+++ b/crates/pa-cli/tests/agents_view_refusal_panel_e2e.rs
@@ -116,6 +116,7 @@ fn view_options(socket: &Path, session_dir: &Path, notice: Option<String>) -> Ag
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}
diff --git a/crates/pa-cli/tests/agents_view_reply_e2e.rs b/crates/pa-cli/tests/agents_view_reply_e2e.rs
new file mode 100644
index 0000000000..967630a9ee
--- /dev/null
+++ b/crates/pa-cli/tests/agents_view_reply_e2e.rs
@@ -0,0 +1,471 @@
+// The Tier-C/D ruling (fleet-uniform, 2026-09-28): stack-resident futures
+// by design on hot paths (boxing 130 fns is allocation-churn with zero
+// correctness gain); the fn-length threshold is a style gate, not
+// correctness (the harness fns are intentionally linear); 64-bit targets -
+// the narrowing sits at OS/protocol boundaries where the values are
+// bounded (pid syscalls, epoch/elapsed milliseconds, calendar math,
+// guarded parses), and checked conversions would add panic paths where
+// silent wrap was deliberate.
+#![allow(
+ clippy::large_futures,
+ clippy::too_many_lines,
+ clippy::cast_possible_truncation,
+ clippy::cast_possible_wrap,
+ clippy::cast_sign_loss,
+ clippy::cast_precision_loss
+)]
+
+//! End-to-end verifier for the agents-view reply composer (TS
+//! `sendReply` through the real daemon): the space-armed composer sends
+//! a live session's reply through the UNATTACHED roster client (the
+//! view never attaches — the supervisor must route the prompt), and a
+//! saved fixture row resumes into a fresh session whose file carries the
+//! reply — `create` with the session path, then the prompt.
+#![cfg(unix)]
+
+use std::fmt::Write as _;
+use std::io::{BufRead, BufReader, Write};
+use std::os::unix::net::UnixStream;
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::time::{Duration, Instant};
+
+use pa_tui::agents_view::{AgentsHeadlessPlan, AgentsStep, AgentsViewOptions, AgentsViewUiMode};
+
+struct Supervisor {
+ child: Child,
+ #[allow(dead_code)]
+ socket: PathBuf,
+}
+
+impl Drop for Supervisor {
+ fn drop(&mut self) {
+ graceful_shutdown(&self.socket);
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ let _ = std::fs::remove_file(&self.socket);
+ }
+}
+
+/// Stop the daemon on `socket` by protocol; kill the child when it fails.
+fn graceful_shutdown(socket: &Path) {
+ let Ok(stream) = UnixStream::connect(socket) else {
+ return;
+ };
+ let Ok(write_half) = stream.try_clone() else {
+ return;
+ };
+ let mut reader = BufReader::new(stream);
+ let mut writer = write_half;
+ let mut hello = String::new();
+ let _ = reader.read_line(&mut hello); // daemon_hello
+ let command = serde_json::json!({
+ "type": "command",
+ "id": "test-shutdown",
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "command": { "type": "shutdown" },
+ });
+ let Ok(mut line) = serde_json::to_string(&command) else {
+ return;
+ };
+ line.push('\n');
+ let _ = writer.write_all(line.as_bytes());
+ let _ = writer.flush();
+ let _ = reader
+ .get_ref()
+ .set_read_timeout(Some(Duration::from_secs(5)));
+ let mut response = String::new();
+ let _ = reader.read_line(&mut response);
+}
+
+#[allow(clippy::zombie_processes)]
+fn spawn_supervisor(dir: &Path) -> Supervisor {
+ let socket = dir.join("daemon.sock");
+ let agent_dir = dir.join("agent");
+ std::fs::create_dir_all(&agent_dir).expect("agent dir");
+ let mut command = Command::new(env!("CARGO_BIN_EXE_prime-agent"));
+ command
+ .args(["--mode", "daemon", "--daemon-socket"])
+ .arg(&socket)
+ .env("PRIME_AGENT_CODING_AGENT_DIR", &agent_dir)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ for var in [
+ pa_daemon::worker::WORKER_ROLE_ENV,
+ pa_daemon::worker::WORKER_TOKEN_ENV,
+ pa_daemon::worker::WORKER_ACTIVE_SESSION_ID_ENV,
+ pa_daemon::worker::WORKER_RECOVERY_JOURNAL_ENV,
+ pa_daemon::worker::WORKER_SUPERVISOR_SOCKET_ENV,
+ pa_daemon::worker::WORKER_SOCKET_ENV,
+ pa_daemon::worker::WORKER_INSTANCE_ID_ENV,
+ pa_daemon::worker::WORKER_SCRIPT_ENV,
+ ] {
+ command.env_remove(var);
+ }
+ command.env(
+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
+ "15000",
+ );
+ let child = command.spawn().expect("spawn prime-agent --mode daemon");
+ let deadline = Instant::now() + Duration::from_secs(15);
+ while Instant::now() < deadline {
+ if socket.exists() {
+ return Supervisor { child, socket };
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ panic!("supervisor socket never appeared");
+}
+
+/// One saved-session fixture: header, display name, and a user/assistant
+/// exchange.
+fn write_fixture(dir: &Path, id: &str, name: &str, turns: &[(&str, &str)]) -> PathBuf {
+ let path = dir.join(format!("{id}.jsonl"));
+ let mut content = format!(
+ "{{\"type\":\"session\",\"version\":3,\"id\":\"{id}\",\"timestamp\":\"2024-01-01T00:00:00.000Z\",\"cwd\":\"/tmp\"}}\n"
+ );
+ let _ = writeln!(content,
+ "{{\"type\":\"session_info\",\"id\":\"{id}-info\",\"timestamp\":\"2024-01-01T00:00:00.000Z\",\"name\":\"{name}\"}}"
+ );
+ for (index, (user, assistant)) in turns.iter().enumerate() {
+ let _ = writeln!(content,
+ "{{\"type\":\"message\",\"id\":\"{id}-m{index}u\",\"timestamp\":\"2024-01-01T00:00:0{index}.000Z\",\"message\":{{\"role\":\"user\",\"content\":\"{user}\",\"timestamp\":{}}}}}",
+ index * 1000
+ );
+ let _ = writeln!(content,
+ "{{\"type\":\"message\",\"id\":\"{id}-m{index}a\",\"timestamp\":\"2024-01-01T00:00:0{index}.000Z\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"text\",\"text\":\"{assistant}\"}}],\"timestamp\":{}}}}}",
+ index * 1000 + 1
+ );
+ }
+ std::fs::write(&path, content).expect("write fixture");
+ path
+}
+
+/// The daemon-connection ask behind one raw command: the hello-greeting
+/// envelope, the request, and the response line.
+fn ask(socket: &Path, command: &serde_json::Value) -> Option<serde_json::Value> {
+ let stream = UnixStream::connect(socket).ok()?;
+ let write_half = stream.try_clone().ok()?;
+ let mut reader = BufReader::new(stream);
+ let mut writer = write_half;
+ let mut hello = String::new();
+ reader.read_line(&mut hello).ok()?;
+ let mut line = serde_json::to_string(&serde_json::json!({
+ "type": "command",
+ "id": "reply-e2e-ask",
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "command": command,
+ }))
+ .ok()?;
+ line.push('\n');
+ writer.write_all(line.as_bytes()).ok()?;
+ writer.flush().ok()?;
+ reader
+ .get_ref()
+ .set_read_timeout(Some(Duration::from_secs(10)))
+ .ok()?;
+ let mut response = String::new();
+ reader.read_line(&mut response).ok()?;
+ serde_json::from_str(&response).ok()
+}
+
+/// The create config with the faux engine's script file (the daemon
+/// worker's verification seam: `{"engine": "faux", ...}` drives the
+/// REAL agent engine over the scripted provider, so the send path has a
+/// real worker with real session persistence behind it — the resumed
+/// fixture file gains the reply's user message exactly like a live
+/// session would).
+fn faux_engine_config(dir: &Path, responses: &[&str]) -> serde_json::Value {
+ let script = dir.join("faux-engine.json");
+ std::fs::write(
+ &script,
+ serde_json::json!({
+ "engine": "faux",
+ "responses": responses
+ .iter()
+ .map(|text| serde_json::json!({ "text": text }))
+ .collect::<Vec<_>>(),
+ })
+ .to_string(),
+ )
+ .expect("write faux script");
+ serde_json::json!({ "script": script.to_string_lossy() })
+}
+
+fn view_options(socket: &Path, session_dir: &Path, config: serde_json::Value) -> AgentsViewOptions {
+ AgentsViewOptions {
+ socket_path: socket.to_path_buf(),
+ cwd: std::env::temp_dir(),
+ session_dir: Some(session_dir.to_path_buf()),
+ theme: "prime".to_string(),
+ version: "0.0.0".to_string(),
+ anchor_session_id: None,
+ scope: None,
+ query: None,
+ expanded_ancestors: Vec::new(),
+ selected_row_identity: None,
+ selected_key: None,
+ status_message: None,
+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),
+ show_hardware_cursor: false,
+ incident_notice_state: None,
+ create_config: config,
+ }
+}
+
+/// The reply composer against a LIVE session: the space arm, the typed
+/// reply, and Enter deliver the prompt through the view's UNATTACHED
+/// roster client (the supervisor routes it — the verification item),
+/// the status reports the send, and the session's own transcript holds
+/// the reply.
+#[tokio::test]
+async fn reply_to_live_session_delivers_the_prompt() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let agent_dir = dir.path().join("agent");
+ let session_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("session dir");
+ let supervisor = spawn_supervisor(dir.path());
+ // Two scripted responses: the warm-up turn consumes the first, the
+ // view's reply the second.
+ let config = faux_engine_config(dir.path(), &["warm reply", "the reply landed"]);
+
+ // Create the live session through the daemon itself (the roster row
+ // the view lists).
+ let created = ask(
+ &supervisor.socket,
+ &serde_json::json!({ "type": "create", "config": config }),
+ )
+ .expect("the create answered")
+ .get("data")
+ .cloned()
+ .expect("the create returned the summary");
+ let active = created
+ .get("activeSessionId")
+ .and_then(serde_json::Value::as_str)
+ .expect("the created session is live")
+ .to_string();
+ // The raw roster must carry the fresh worker before the view runs
+ // (the view's rows come from roster_subscribe's snapshot).
+ let roster_carries = |tries: usize| {
+ (0..tries).any(|attempt| {
+ if attempt > 0 {
+ std::thread::sleep(Duration::from_millis(200));
+ }
+ ask(
+ &supervisor.socket,
+ &serde_json::json!({ "type": "roster_subscribe" }),
+ )
+ .is_some_and(|response| {
+ response
+ .get("data")
+ .and_then(|data| data.get("roster"))
+ .and_then(serde_json::Value::as_array)
+ .is_some_and(|roster| {
+ roster.iter().any(|entry| {
+ entry
+ .get("summary")
+ .and_then(|summary| summary.get("activeSessionId"))
+ .and_then(serde_json::Value::as_str)
+ == Some(active.as_str())
+ })
+ })
+ })
+ })
+ };
+ assert!(
+ roster_carries(50),
+ "the raw roster never carried the created session"
+ );
+ // Warm the session up (one prompt turn through the daemon): a
+ // message-less top-level draft (lifecycle "draft") never surfaces as
+ // a roster row (TS `shouldShowAgentsViewSession`), so the view's
+ // reply target needs the session live with a first exchange — and
+ // the warm-up turn must COMPLETE before the view runs.
+ let warmed = ask(
+ &supervisor.socket,
+ &serde_json::json!({
+ "type": "prompt",
+ "activeSessionId": active,
+ "message": "warm up",
+ }),
+ );
+ assert!(
+ warmed.is_some_and(|r| r.get("success") == Some(&serde_json::json!(true))),
+ "the warm-up prompt ran"
+ );
+ let session_is_live = |tries: usize| {
+ (0..tries).any(|attempt| {
+ if attempt > 0 {
+ std::thread::sleep(Duration::from_millis(200));
+ }
+ ask(
+ &supervisor.socket,
+ &serde_json::json!({ "type": "roster_subscribe" }),
+ )
+ .is_some_and(|response| {
+ response
+ .get("data")
+ .and_then(|data| data.get("roster"))
+ .and_then(serde_json::Value::as_array)
+ .is_some_and(|roster| {
+ roster.iter().any(|entry| {
+ entry.get("summary").is_some_and(|summary| {
+ summary
+ .get("activeSessionId")
+ .and_then(serde_json::Value::as_str)
+ == Some(active.as_str())
+ && summary.get("lifecycle").and_then(serde_json::Value::as_str)
+ == Some("live")
+ })
+ })
+ })
+ })
+ })
+ };
+ assert!(
+ session_is_live(50),
+ "the warm-up never made the session live"
+ );
+
+ let options = view_options(&supervisor.socket, &session_dir, config);
+ let plan = AgentsHeadlessPlan {
+ steps: vec![
+ AgentsStep::WaitSettle { timeout_ms: 1000 },
+ // The live row sits at the top of the Idle section.
+ AgentsStep::Key("space".to_string()),
+ AgentsStep::Type("ping".to_string()),
+ AgentsStep::Key("enter".to_string()),
+ AgentsStep::WaitRender {
+ needle: "Reply sent".to_string(),
+ timeout_ms: 10_000,
+ },
+ ],
+ width: 120,
+ height: 36,
+ };
+ let outcome =
+ pa_tui::agents_view::run_agents_view(options, AgentsViewUiMode::Headless(plan), None)
+ .await
+ .expect("agents view run")
+ .outcome;
+ let rendered = outcome.frames.join("\n");
+ assert!(
+ rendered.contains("Reply sent"),
+ "the send's status rendered ({} frames):\n{rendered}",
+ outcome.frames.len()
+ );
+ // The reply ran on the targeted session: its last assistant text
+ // echoes the prompt through the faux script.
+ // The reply's turn runs behind the send's ack: poll the session's
+ // last assistant text until the reply's scripted answer lands.
+ let mut last = String::new();
+ let reply_landed = (0..50).any(|attempt| {
+ if attempt > 0 {
+ std::thread::sleep(Duration::from_millis(200));
+ }
+ last = ask(
+ &supervisor.socket,
+ &serde_json::json!({ "type": "get_last_assistant_text", "activeSessionId": active }),
+ )
+ .and_then(|response| {
+ response
+ .get("data")
+ .and_then(|data| data.get("text"))
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string)
+ })
+ .unwrap_or_default();
+ last.contains("the reply landed")
+ });
+ assert!(
+ reply_landed,
+ "the reply delivered to the live session (last assistant: {last:?})"
+ );
+}
+
+/// The reply composer against a SAVED row: the space arm shows the
+/// resume placeholder, Enter resumes the fixture into a live session
+/// (`create` with the session path) and delivers the reply, and the
+/// fixture file on disk gains the reply's user message.
+#[tokio::test]
+async fn reply_to_saved_session_resumes_and_sends() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let agent_dir = dir.path().join("agent");
+ let session_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("session dir");
+ let supervisor = spawn_supervisor(dir.path());
+ let config = faux_engine_config(dir.path(), &["resumed and heard"]);
+
+ let fixture = write_fixture(
+ &session_dir,
+ "resume-01",
+ "resume target",
+ &[("first turn", "first reply")],
+ );
+
+ let options = view_options(&supervisor.socket, &session_dir, config);
+ let plan = AgentsHeadlessPlan {
+ steps: vec![
+ AgentsStep::WaitSettle { timeout_ms: 1000 },
+ // The saved row lists in the Inactive section; it is the
+ // only row.
+ AgentsStep::Key("space".to_string()),
+ AgentsStep::WaitRender {
+ needle: "Write a prompt to resume this session".to_string(),
+ timeout_ms: 5000,
+ },
+ AgentsStep::Type("resume me".to_string()),
+ AgentsStep::Key("enter".to_string()),
+ AgentsStep::WaitRender {
+ needle: "Reply sent".to_string(),
+ timeout_ms: 15_000,
+ },
+ ],
+ width: 120,
+ height: 36,
+ };
+ let outcome =
+ pa_tui::agents_view::run_agents_view(options, AgentsViewUiMode::Headless(plan), None)
+ .await
+ .expect("agents view run")
+ .outcome;
+ let rendered = outcome.frames.join("\n");
+ assert!(
+ rendered.contains("Reply sent"),
+ "the resume's status rendered:\n{rendered}"
+ );
+ // The fixture file carries the reply: the resumed session appended
+ // the user message to the SAME durable file (the turn persists
+ // behind the send's ack — poll until it lands).
+ let mut content = String::new();
+ let reply_persisted = (0..50).any(|attempt| {
+ if attempt > 0 {
+ std::thread::sleep(Duration::from_millis(200));
+ }
+ content = std::fs::read_to_string(&fixture).unwrap_or_default();
+ content.contains("resume me")
+ });
+ assert!(
+ reply_persisted,
+ "the resumed session's file holds the reply:\n{content}"
+ );
+ // The resumed session is live on the daemon.
+ let list = ask(&supervisor.socket, &serde_json::json!({ "type": "list" }))
+ .expect("the list answered")
+ .get("data")
+ .and_then(|data| data.get("sessions"))
+ .and_then(serde_json::Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ let live_for_fixture = list.iter().any(|session| {
+ session
+ .get("sessionFile")
+ .and_then(serde_json::Value::as_str)
+ == Some(fixture.to_string_lossy().as_ref())
+ });
+ assert!(
+ live_for_fixture,
+ "the fixture resumed into a live session (list: {list:?})"
+ );
+}
diff --git a/crates/pa-cli/tests/agents_view_search_e2e.rs b/crates/pa-cli/tests/agents_view_search_e2e.rs
index 2accdfeebd..d6fe185bcc 100644
--- a/crates/pa-cli/tests/agents_view_search_e2e.rs
+++ b/crates/pa-cli/tests/agents_view_search_e2e.rs
@@ -246,6 +246,7 @@ async fn search_matches_names_ids_and_cwd_never_transcripts() {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let plan = AgentsHeadlessPlan {
steps: vec![
@@ -398,6 +399,7 @@ async fn ranked_hits_sort_by_relevance_then_recency() {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let plan = AgentsHeadlessPlan {
steps: vec![
diff --git a/crates/pa-cli/tests/agents_view_subagents_e2e.rs b/crates/pa-cli/tests/agents_view_subagents_e2e.rs
index b86292a660..15e8fd5c22 100644
--- a/crates/pa-cli/tests/agents_view_subagents_e2e.rs
+++ b/crates/pa-cli/tests/agents_view_subagents_e2e.rs
@@ -215,6 +215,7 @@ fn view_options(
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}
diff --git a/crates/pa-cli/tests/chat_agents_chat_roundtrip_e2e.rs b/crates/pa-cli/tests/chat_agents_chat_roundtrip_e2e.rs
index e156f73742..34f4e2ea70 100644
--- a/crates/pa-cli/tests/chat_agents_chat_roundtrip_e2e.rs
+++ b/crates/pa-cli/tests/chat_agents_chat_roundtrip_e2e.rs
@@ -275,6 +275,7 @@ async fn the_roundtrip_reentry_renders_the_same_transcript() {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let view_run = pa_tui::agents_view::run_agents_view(
view_options,
@@ -430,6 +431,7 @@ async fn a_post_turn_sojourn_reentry_still_serves_the_held_packs() {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let view_run = pa_tui::agents_view::run_agents_view(
view_options,
diff --git a/crates/pa-cli/tests/dock_scope_exit_focus_e2e.rs b/crates/pa-cli/tests/dock_scope_exit_focus_e2e.rs
index e6b286ba85..a101ecc0bb 100644
--- a/crates/pa-cli/tests/dock_scope_exit_focus_e2e.rs
+++ b/crates/pa-cli/tests/dock_scope_exit_focus_e2e.rs
@@ -322,6 +322,7 @@ async fn scope_exit_keeps_the_subagents_item(exit_key: &'static str) {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let view_plan = AgentsHeadlessPlan {
steps: vec![
diff --git a/crates/pa-cli/tests/kitty_exit_routes_e2e/child.rs b/crates/pa-cli/tests/kitty_exit_routes_e2e/child.rs
index 99628b06e2..0cc5c37b12 100644
--- a/crates/pa-cli/tests/kitty_exit_routes_e2e/child.rs
+++ b/crates/pa-cli/tests/kitty_exit_routes_e2e/child.rs
@@ -49,6 +49,7 @@ pub(super) fn child_run(route: &str, socket: PathBuf) {
keybindings: options.keybindings.clone(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let view_run = run_agents_view(view_options, AgentsViewUiMode::Terminal, None)
.await
@@ -84,6 +85,7 @@ pub(super) fn child_run(route: &str, socket: PathBuf) {
keybindings: options.keybindings.clone(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let view_run = run_agents_view(view_options, AgentsViewUiMode::Terminal, None)
.await
diff --git a/crates/pa-cli/tests/kitty_release_handoff_e2e.rs b/crates/pa-cli/tests/kitty_release_handoff_e2e.rs
index d49838505e..a3802d7d75 100644
--- a/crates/pa-cli/tests/kitty_release_handoff_e2e.rs
+++ b/crates/pa-cli/tests/kitty_release_handoff_e2e.rs
@@ -117,6 +117,7 @@ fn kitty_child_mode() {
keybindings: options.keybindings.clone(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let view_run = pa_tui::agents_view::run_agents_view(
view_options,
diff --git a/crates/pa-cli/tests/subagent_panel_nav_e2e.rs b/crates/pa-cli/tests/subagent_panel_nav_e2e.rs
index fac82b86d2..ac11aae46c 100644
--- a/crates/pa-cli/tests/subagent_panel_nav_e2e.rs
+++ b/crates/pa-cli/tests/subagent_panel_nav_e2e.rs
@@ -366,6 +366,7 @@ async fn down_arrow_focuses_the_dock_and_enter_opens_the_scoped_agents_view() {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
};
let view_plan = AgentsHeadlessPlan {
steps: vec![
diff --git a/crates/pa-cli/tests/terminal_state_differential_e2e/harness.rs b/crates/pa-cli/tests/terminal_state_differential_e2e/harness.rs
index 890fbf2fba..dfd4d3e993 100644
--- a/crates/pa-cli/tests/terminal_state_differential_e2e/harness.rs
+++ b/crates/pa-cli/tests/terminal_state_differential_e2e/harness.rs
@@ -703,5 +703,6 @@ pub(crate) fn view_options(socket: PathBuf, anchor: Option<String>) -> AgentsVie
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}
diff --git a/crates/pa-tui/src/agents_view.rs b/crates/pa-tui/src/agents_view.rs
index eac622d315..b0e4c3f45e 100644
--- a/crates/pa-tui/src/agents_view.rs
+++ b/crates/pa-tui/src/agents_view.rs
@@ -53,6 +53,14 @@ use delete::{spawn_delete_dispatch, DeleteAction, PendingDelete};
mod rename;
use rename::{spawn_rename_dispatch, Rename};
+mod reply;
+use reply::{
+ spawn_headline_fetch, spawn_kill_dispatch, spawn_reply_dispatch, KillRequest, ReplyRequest,
+};
+
+mod status;
+use status::{Status, StatusTone};
+
/// Options for one agents-view run.
#[derive(Debug, Clone)]
pub struct AgentsViewOptions {
@@ -105,6 +113,11 @@ pub struct AgentsViewOptions {
/// never comes back and the poll does not re-read consumed bytes.
/// `None` on the first run creates a fresh state.
pub incident_notice_state: Option<crate::incident_notices::IncidentNoticeState>,
+ /// The flow's own `create` config (TS `AgentsViewModeOptions.config`):
+ /// the base a saved reply's resume derives its config from (the
+ /// view's runtime config with the session's own cwd removed, or the
+ /// view's cwd when the saved directory no longer exists).
+ pub create_config: serde_json::Value,
}
/// The open action the run ended with (TS `AgentsViewRunResult`'s
@@ -248,6 +261,10 @@ fn saved_catalog_timeout_ms() -> u64 {
enum UiInput {
Key(String),
+ /// One paste (bracketed, or the paste-aware reader's coalesced
+ /// marker-less burst): the armed composer's editor takes it; the
+ /// search field ignores it.
+ Paste(String),
/// The headless plan's `WaitRender` barrier: the loop holds the
/// queued plan batch behind it until a frame rendered after arming
/// contains the needle (the interactive harness's condition-wait
@@ -272,9 +289,11 @@ enum UiInput {
error: String,
},
/// One stop-or-delete dispatch landed (the ctrl+x flow): the status
- /// line reports the outcome.
+ /// line reports the outcome in the tone the dispatch classified it
+ /// with (success muted, a no-effect stop warning, a failure error).
DeleteResult {
message: String,
+ tone: StatusTone,
/// The deleted saved session's path (the catalog key for the
/// immediate row removal); `None` for the other arms.
deleted_saved_path: Option<String>,
@@ -285,6 +304,28 @@ enum UiInput {
rename: Rename,
outcome: Result<(), String>,
},
+ /// The armed target's last-assistant headline landed (or failed):
+ /// the header renders it; a re-targeted or disarmed composer drops
+ /// it.
+ HeadlineResult {
+ key: String,
+ result: Result<Option<String>, String>,
+ },
+ /// The saved-resume path's mid-send status (TS `sendReply`: the
+ /// "Sending reply..." after "Resuming session..." — the loop paints
+ /// each as it lands, never both at once).
+ ReplyProgress(String),
+ /// One reply send landed: the resumed summary and the sticky cwd
+ /// notice on success, the wire's error on failure.
+ ReplyResult {
+ key: String,
+ outcome: Result<reply::ReplySent, String>,
+ },
+ /// One `/kill` view-command dispatch landed.
+ KillResult {
+ key: String,
+ outcome: Result<(), String>,
+ },
}
/// The flow's roster connection (TS `AgentsViewPersistentState.rosterClient`):
@@ -352,7 +393,10 @@ struct AgentsViewMode {
rows: Vec<AgentsViewRow>,
selected: usize,
query: String,
- status: Option<String>,
+ /// The status line (TS `statusMessage` + `statusMessageTone` + the
+ /// 4.5s timer): rendered at the bottom hint row in its tone, expired
+ /// by the loop's deadline arm, sticky lines cleared by the next key.
+ status: Option<Status>,
/// A multi-line notice from the previous run (a daemon refusal whose
/// ways out span lines, like the cross-product lease hold): rendered
/// as a dismissible panel above the hint line instead of the one-line
@@ -371,6 +415,17 @@ struct AgentsViewMode {
/// `pending_delete_action` shape: the wire call runs off the key
/// loop with the client).
pending_rename: Option<Rename>,
+ /// The submitted reply the run loop dispatches (the reply flow's
+ /// same shape): the send runs off the key loop with the client, and
+ /// its keyed outcome re-enters as a `ReplyResult`.
+ pending_reply: Option<ReplyRequest>,
+ /// One `/kill` view command the run loop dispatches (the reply
+ /// flow's shape): the keyed outcome re-enters as a `KillResult`.
+ pending_kill: Option<KillRequest>,
+ /// The armed target whose headline fetch runs (its key and active
+ /// id): the loop dispatches the fetch, detached — its keyed result
+ /// drops when the composer is gone or re-targeted.
+ pending_headline: Option<(String, String)>,
/// The executed delete the run loop takes (the dispatch runs off the
/// key loop with the client, the saved-catalog fetch's pattern).
pending_delete_action: Option<DeleteAction>,
@@ -501,11 +556,14 @@ struct PressedMouseClick {
/// The prompt's composition state (TS the editor's composer modes): the
/// plain search field, or one action's composer that owns the prompt
-/// and the key routing. The reply composer (C3) adds its variant here.
-#[derive(Debug, Clone, PartialEq, Eq)]
+/// and the key routing. Each composer owns its [`Editor`] — the text,
+/// the provider, and the history can never leak between modes, and an
+/// editor while searching cannot be represented. [`Box`] keeps the
+/// variant against the unit `Search` under clippy's large-enum-variant.
enum Composer {
Search,
- Rename(Rename),
+ Rename(Box<rename::RenameComposer>),
+ Reply(Box<reply::ReplyComposer>),
}
impl AgentsViewMode {
@@ -517,7 +575,10 @@ impl AgentsViewMode {
// status.
let (status, notice) = match options.status_message.clone() {
Some(message) if message.contains('\n') => (None, Some(message)),
- status => (status, None),
+ // TS seeds the run's status with the carried line through
+ // `setStatusMessage` (the default tone rule and the timer
+ // apply to it, exactly like any later line).
+ status => (status.as_deref().map(Status::transient), None),
};
let pending_ancestors =
(!options.expanded_ancestors.is_empty()).then(|| options.expanded_ancestors.clone());
@@ -559,6 +620,9 @@ impl AgentsViewMode {
pending_delete: None,
composer: Composer::Search,
pending_rename: None,
+ pending_reply: None,
+ pending_kill: None,
+ pending_headline: None,
pending_delete_action: None,
deleted_saved_paths: std::collections::HashSet::default(),
scope_depth: None,
@@ -939,8 +1003,7 @@ async fn run_agents_view_surface(
// needle itself — the note renders into frames, and
// quoting the needle would satisfy the very
// condition that failed).
- mode.status =
- Some("timed out waiting for the headless render condition".to_string());
+ mode.set_status("timed out waiting for the headless render condition");
redraw = true;
continue;
}
@@ -968,6 +1031,10 @@ async fn run_agents_view_surface(
match input {
UiInput::Key(key) => {
mode.handle_key(&key);
+ // The composer's parked suggestion request
+ // materializes once the key's edits landed (TS's
+ // editor materializes after the keystroke batch).
+ mode.materialize_composer_autocomplete();
// TS `queryChanged` -> `armSavedSearchFetch`: a failed
// saved-catalog fetch re-arms on the next query change,
// so the Inactive section gets one honest retry behind
@@ -1008,12 +1075,39 @@ async fn run_agents_view_surface(
rename,
));
}
+ // The reply composer's dispatches (the send and the
+ // `/kill` view command): the 2s exit drain covers an
+ // Enter-then-exit the same way it covers a confirmed
+ // stop-or-delete.
+ if let Some(request) = mode.pending_reply.take() {
+ action_dispatches.push(spawn_reply_dispatch(
+ &client,
+ ui_tx.clone(),
+ request,
+ ));
+ }
+ if let Some(request) = mode.pending_kill.take() {
+ action_dispatches.push(spawn_kill_dispatch(
+ &client,
+ ui_tx.clone(),
+ request,
+ ));
+ }
+ // The armed target's headline fetch: detached (the
+ // exit never waits on it), and its keyed result
+ // drops when the composer is gone or re-targeted.
+ if let Some((key, active_session_id)) = mode.pending_headline.take() {
+ spawn_headline_fetch(&client, ui_tx.clone(), key, active_session_id);
+ }
}
// A plain click opens the row under it (the Enter
// action); drags and wheel turns are consumed inside.
UiInput::Mouse(event) => {
mode.handle_mouse(&event);
}
+ UiInput::Paste(text) => {
+ mode.handle_paste(&text);
+ }
// `Settled` is the plan's own settle no-op;
// `WaitRender` never reaches the batch pop (the
// pre-pass at the loop head owns it — an armed hold
@@ -1021,13 +1115,30 @@ async fn run_agents_view_surface(
UiInput::Resize | UiInput::Settled | UiInput::WaitRender { .. } => {}
UiInput::DeleteResult {
message,
+ tone,
deleted_saved_path,
} => {
- mode.delete_result(message, deleted_saved_path);
+ mode.delete_result(&message, tone, deleted_saved_path);
}
UiInput::RenameResult { rename, outcome } => {
mode.rename_result(rename, outcome);
}
+ UiInput::HeadlineResult { key, result } => {
+ mode.headline_result(&key, result);
+ }
+ // The saved-resume path's own status (TS's mid-send
+ // "Sending reply..."): it lands between the resume and
+ // the prompt like any set_status, never queued behind
+ // the result it precedes.
+ UiInput::ReplyProgress(text) => {
+ mode.set_status(&text);
+ }
+ UiInput::ReplyResult { key, outcome } => {
+ mode.reply_result(&key, outcome);
+ }
+ UiInput::KillResult { key, outcome } => {
+ mode.kill_result(&key, outcome);
+ }
// The saved-catalog scan landed (TS `armSavedSearchFetch`
// applying its result): the Inactive section builds now.
UiInput::SavedLoaded { sessions } => {
@@ -1048,8 +1159,7 @@ async fn run_agents_view_surface(
// must not keep reporting an unavailable catalog after
// it loaded).
if mode
- .status
- .as_deref()
+ .status_text()
.is_some_and(|status| status.starts_with("Saved sessions unavailable"))
{
mode.status = None;
@@ -1081,7 +1191,10 @@ async fn run_agents_view_surface(
catalog_request = None;
mode.settle_anchor_wait_on_saved_failure();
mode.saved_fetch_failed = true;
- mode.status = Some(format!("Saved sessions unavailable: {error}"));
+ mode.set_status_tone(
+ &format!("Saved sessions unavailable: {error}"),
+ StatusTone::Error,
+ );
}
// The headless plan ended: the run stops here (the
// interactive harness's `HeadlessDone` contract). A plan
@@ -1096,88 +1209,105 @@ async fn run_agents_view_surface(
}
redraw = true;
} else {
- // The batch window's deadline, copied out of the loop state:
- // select evaluates EVERY branch expression whether or not its
- // precondition passes, so the flush arm below must never
- // unwrap the Option itself.
+ // The batch window's and the status line's deadlines, copied
+ // out of the loop state: select evaluates EVERY branch
+ // expression whether or not its precondition passes, so the
+ // arms below must never unwrap an Option themselves.
let flush_at = saved_flush;
+ let status_at = mode.status_expiry(std::time::Instant::now());
tokio::select! {
- maybe_event = events.recv() => {
- match maybe_event {
- Some(DaemonClientEvent::RosterUpdate { changed, removed, resync }) => {
- mode.apply_roster_update(changed, removed, resync);
- redraw = true;
- }
- // The saved-catalog scan streams its rows while it
- // runs (newest first): the view buffers the live
- // fetch's frames and flushes them in one rebuild
- // per batch window, so the Inactive section (and
- // the entry anchor's row) appears progressively
- // instead of after the whole scan (TS
- // `refreshSavedSessions`'s `onSession` batching).
- Some(DaemonClientEvent::SessionListItem { session, request_id }) => {
- if catalog_request.as_deref() == Some(request_id.as_str()) {
- mode.buffer_saved_stream_item(session);
- if saved_flush.is_none() {
- saved_flush = Some(
- tokio::time::Instant::now()
- + Duration::from_millis(
- SAVED_CATALOG_RECONCILE_INTERVAL_MS,
- ),
- );
+ maybe_event = events.recv() => {
+ match maybe_event {
+ Some(DaemonClientEvent::RosterUpdate { changed, removed, resync }) => {
+ mode.apply_roster_update(changed, removed, resync);
+ redraw = true;
+ }
+ // The saved-catalog scan streams its rows while it
+ // runs (newest first): the view buffers the live
+ // fetch's frames and flushes them in one rebuild
+ // per batch window, so the Inactive section (and
+ // the entry anchor's row) appears progressively
+ // instead of after the whole scan (TS
+ // `refreshSavedSessions`'s `onSession` batching).
+ Some(DaemonClientEvent::SessionListItem { session, request_id }) => {
+ if catalog_request.as_deref() == Some(request_id.as_str()) {
+ mode.buffer_saved_stream_item(session);
+ if saved_flush.is_none() {
+ saved_flush = Some(
+ tokio::time::Instant::now()
+ + Duration::from_millis(
+ SAVED_CATALOG_RECONCILE_INTERVAL_MS,
+ ),
+ );
+ }
}
}
+ Some(_) => {}
+ None => {
+ mode.set_status_tone("the daemon connection closed",
+ StatusTone::Error
+ );
+ mode.running = false;
+ redraw = true;
+ }
}
- Some(_) => {}
- None => {
- mode.status = Some("the daemon connection closed".to_string());
- mode.running = false;
- redraw = true;
- }
- }
- }
- maybe_input = ui_rx.recv() => {
- if let Some(input) = maybe_input {
- pending.push(input);
- continue;
}
- }
- // Only a running row needs a periodic frame. The timer
- // stays tied to the last pulse across unrelated inputs.
- () = tokio::time::sleep_until(last_pulse + Duration::from_millis(PULSE_INTERVAL_MS)),
- if mode.rows.iter().any(|row| row.section == Section::Running) => {}
- // The streamed-catalog batch window: the buffered rows
- // flush as one rebuild. A closed window pends forever
- // (the copied deadline is None) instead of unwrapping.
- () = async {
- match flush_at {
- Some(at) => tokio::time::sleep_until(at).await,
- None => std::future::pending().await,
+ maybe_input = ui_rx.recv() => {
+ if let Some(input) = maybe_input {
+ pending.push(input);
+ continue;
+ }
}
- } => {
- if mode.flush_saved_stream() {
- redraw = true;
+ // Only a running row needs a periodic frame. The timer
+ // stays tied to the last pulse across unrelated inputs.
+ () = tokio::time::sleep_until(last_pulse + Duration::from_millis(PULSE_INTERVAL_MS)),
+ if mode.rows.iter().any(|row| row.section == Section::Running) => {}
+ // The streamed-catalog batch window: the buffered rows
+ // flush as one rebuild. A closed window pends forever
+ // (the copied deadline is None) instead of unwrapping.
+ () = async {
+ match flush_at {
+ Some(at) => tokio::time::sleep_until(at).await,
+ None => std::future::pending().await,
+ }
+ } => {
+ if mode.flush_saved_stream() {
+ redraw = true;
+ }
+ saved_flush = None;
}
- saved_flush = None;
+ // The incident-notice poll's wake-up: the deadline drain
+ // below the select does the refresh, so the arm only ends
+ // the wait (the pulse arm's shape).
+ () = tokio::time::sleep_until(incident_poll_at) => {}
+ // The render barrier's deadline: an armed hold whose
+ // needle never lands still pops here — the plan proceeds
+ // and the assertion then reports the actual frame — so a
+ // quiet daemon (a catalog answer that never comes)
+ // cannot wedge the loop waiting on events that never
+ // arrive.
+ () = async {
+ match wait_render_deadline {
+ Some(at) => tokio::time::sleep_until(at).await,
+ None => std::future::pending().await,
+ }
+ } => {}
+ // The status line's expiry wake (TS `setStatusMessage`'s
+ // timer): the line clears at its deadline even on a quiet
+ // view, and the expiry check below repaints it away.
+ () = async {
+ match status_at.map(tokio::time::Instant::from_std) {
+ Some(at) => tokio::time::sleep_until(at).await,
+ None => std::future::pending().await,
+ }
+ } => {}
}
- // The incident-notice poll's wake-up: the deadline drain
- // below the select does the refresh, so the arm only ends
- // the wait (the pulse arm's shape).
- () = tokio::time::sleep_until(incident_poll_at) => {}
- // The render barrier's deadline: an armed hold whose
- // needle never lands still pops here — the plan proceeds
- // and the assertion then reports the actual frame — so a
- // quiet daemon (a catalog answer that never comes)
- // cannot wedge the loop waiting on events that never
- // arrive.
- () = async {
- match wait_render_deadline {
- Some(at) => tokio::time::sleep_until(at).await,
- None => std::future::pending().await,
- }
- } => {}
- }
}
+ // The status line's timer (TS's `setTimeout`): an expired line
+ // clears here after every arm — the wake's own and any input's —
+ // so a status that aged out mid-batch never survives the
+ // redraw that follows.
+ redraw |= mode.expire_status(std::time::Instant::now());
// Coalesce a due animation pulse with the input or roster frame,
// and a due incident poll behind a busy input stream (the TS
// interval fires between turns regardless).
@@ -1243,13 +1373,32 @@ async fn run_agents_view_surface(
match input {
UiInput::DeleteResult {
message,
+ tone,
deleted_saved_path,
} => {
- mode.delete_result(message, deleted_saved_path);
+ mode.delete_result(&message, tone, deleted_saved_path);
}
UiInput::RenameResult { rename, outcome } => {
mode.rename_result(rename, outcome);
}
+ // The reply outcomes apply on the exit path too (an
+ // Enter-then-exit): the statuses paint nothing on a run
+ // that ended, but the adoption actions (`reply_sent`,
+ // `killed`) must still reach the outcome — and a `/name`
+ // result still disarms or restores the composer's draft for
+ // the run's final state.
+ UiInput::HeadlineResult { key, result } => {
+ mode.headline_result(&key, result);
+ }
+ UiInput::ReplyProgress(text) => {
+ mode.set_status(&text);
+ }
+ UiInput::ReplyResult { key, outcome } => {
+ mode.reply_result(&key, outcome);
+ }
+ UiInput::KillResult { key, outcome } => {
+ mode.kill_result(&key, outcome);
+ }
_ => {}
}
}
@@ -1339,6 +1488,10 @@ fn is_daemon_answer(input: &UiInput) -> bool {
| UiInput::SavedFailed { .. }
| UiInput::DeleteResult { .. }
| UiInput::RenameResult { .. }
+ | UiInput::HeadlineResult { .. }
+ | UiInput::ReplyProgress(_)
+ | UiInput::ReplyResult { .. }
+ | UiInput::KillResult { .. }
)
}
diff --git a/crates/pa-tui/src/agents_view/data_input.rs b/crates/pa-tui/src/agents_view/data_input.rs
index d0dae096bb..280523a309 100644
--- a/crates/pa-tui/src/agents_view/data_input.rs
+++ b/crates/pa-tui/src/agents_view/data_input.rs
@@ -39,9 +39,7 @@ impl AgentsViewMode {
} else {
self.scope_depth = None;
self.scope_dropped = true;
- self.status = Some(
- "Scope is no longer available; returned to the global view".to_string(),
- );
+ self.set_status("Scope is no longer available; returned to the global view");
None
}
}
@@ -258,6 +256,9 @@ impl AgentsViewMode {
let next = (current as isize + delta).clamp(0, selectable.len() as isize - 1) as usize;
self.selected = selectable[next];
self.sync_selected_row_state();
+ // TS `moveSelection` (:1487-1493): the reply stays armed only
+ // while the selection sits on the targeted agent row.
+ self.disarm_reply_off_selected();
}
/// Jump the selection to the first or last selectable row
@@ -281,6 +282,9 @@ impl AgentsViewMode {
}
.unwrap_or(0);
self.sync_selected_row_state();
+ // The list-edge jumps are moves like TS's `moveSelection`: the
+ // reply disarms when the selection leaves the targeted row.
+ self.disarm_reply_off_selected();
}
/// Open the selected row (TS `openSelected`): the summary row toggles
@@ -405,7 +409,7 @@ impl AgentsViewMode {
/// catalog-failure message included — instead of a stale loading
/// message.
pub(super) fn clear_anchor_loading_hint(&mut self) {
- if self.status.as_deref() == Some(ANCHOR_LOADING_HINT) {
+ if self.status_text() == Some(ANCHOR_LOADING_HINT) {
self.status = None;
}
}
@@ -424,6 +428,9 @@ impl AgentsViewMode {
/// `keybindings.json` override moves both the handler and the hint —
/// the same contract as the session view (#184).
pub(super) fn handle_key(&mut self, key: &str) {
+ // TS `handleInput`'s first call: a sticky line clears on any
+ // keypress (the transient lines ride their own expiry).
+ self.clear_sticky_status();
let was_armed = self.exit_armed;
// The notice panel: any key closes it (the refusal's ways out
// stay copy-pasteable while it is up), except the exit key,
@@ -441,12 +448,20 @@ impl AgentsViewMode {
self.exit_armed = false;
let was_delete_armed = self.pending_delete.take();
let has_query = !self.query.is_empty();
- // TS `handleInput`'s rename branch (:1119-1126): the rename
- // composer owns every key before the app-level handlers. The
- // draft comes out owned; a non-rename composer parks Search.
- if let Composer::Rename(rename) = std::mem::replace(&mut self.composer, Composer::Search) {
- self.handle_rename_key(rename, key);
- return;
+ // TS `handleInput`'s composer branches (:1119-1126 and the
+ // armed-reply gates before `editor.handleInput`): the armed
+ // composer owns every key before the app-level handlers — the
+ // draft comes out owned, and an unarmed Search parks nothing.
+ match std::mem::replace(&mut self.composer, Composer::Search) {
+ Composer::Rename(rename) => {
+ self.handle_rename_key(rename, key);
+ return;
+ }
+ Composer::Reply(reply) => {
+ self.handle_reply_key(reply, was_delete_armed, key);
+ return;
+ }
+ Composer::Search => {}
}
// TS `app.clear` (default ctrl+c): the first press arms the exit
// hint, a second press while armed exits the view (TS
@@ -494,23 +509,14 @@ impl AgentsViewMode {
// `hasLiveWork`), the second press on the same row executes, and
// any other key clears the arm.
if !has_query && self.keybindings.matches(key, "app.agents.delete") {
- if was_delete_armed.as_ref().is_some_and(|pending| {
- self.rows.get(self.selected).is_some_and(|row| {
- row.identity == pending.identity
- // The armed word must still match the row's live
- // work: a row that settled between the presses
- // (running -> idle) re-arms rather than executing
- // the stale word (the hint said stop; the row now
- // deletes - the confirm rides the CURRENT state).
- && Self::delete_arm_word(row) == pending.stop
- })
- }) {
- if let Some(action) = self.delete_action_for_selected() {
- self.pending_delete_action = Some(action);
- }
- } else if let Some(pending) = self.delete_arm_target() {
- self.pending_delete = Some(pending);
- }
+ self.confirm_delete_for_selected(was_delete_armed);
+ return;
+ }
+ // TS `app.agents.reply` (default space, empty editor only —
+ // TS :1164): arm the reply composer over the selected agent row;
+ // the same target disarms. A space with a query is search text.
+ if !has_query && self.keybindings.matches(key, "app.agents.reply") {
+ self.toggle_reply();
return;
}
// TS `app.agents.new` (default ctrl+n): start a session; a plain
@@ -638,13 +644,52 @@ impl AgentsViewMode {
self.rebuild_rows();
return;
}
- if key.chars().count() == 1 {
- self.query.push_str(key);
+ // The printable decode the editor uses (`decode_printable`):
+ // the space arrives as the `space` key id (TS parseKey maps the
+ // raw space there), and the shift+letter ids decode to their
+ // characters.
+ if let Some(text) = crate::editor::decode_printable(key) {
+ self.query.push_str(&text);
self.note_query_changed();
self.rebuild_rows();
}
}
+ /// Materialize the armed composer's parked suggestion request (TS's
+ /// editor contract: `getSuggestions` resolves after the keystroke
+ /// batch, so the host materializes it — the chat's
+ /// `materialize_editor_autocomplete`). The search field and the
+ /// provider-less editors park nothing.
+ pub(super) fn materialize_composer_autocomplete(&mut self) {
+ match &mut self.composer {
+ Composer::Search => {}
+ Composer::Rename(rename) => rename.editor.materialize_autocomplete(),
+ Composer::Reply(reply) => reply.editor.materialize_autocomplete(),
+ }
+ }
+
+ /// One paste (bracketed, or the paste-aware reader's coalesced
+ /// marker-less burst — tmux ≤3.2 forwards pastes without markers,
+ /// and Enter submits in the composers, so a burst typed line by
+ /// line would submit per line): the armed composer's editor takes
+ /// it through TS's paste path (inline, or an atomic marker for a
+ /// large one); the search field ignores it, exactly as before.
+ pub(super) fn handle_paste(&mut self, text: &str) {
+ match std::mem::replace(&mut self.composer, Composer::Search) {
+ Composer::Search => {}
+ Composer::Rename(mut rename) => {
+ rename.editor.handle_paste(text);
+ let _ = rename.editor.take_events();
+ self.composer = Composer::Rename(rename);
+ }
+ Composer::Reply(mut reply) => {
+ reply.editor.handle_paste(text);
+ let _ = reply.editor.take_events();
+ self.composer = Composer::Reply(reply);
+ }
+ }
+ }
+
/// One mouse report (the session surface's click grammar, scoped to
/// the view's rows): a plain left press always re-records the row
/// under it (a release lost to a focus change or a touch cancel
@@ -738,6 +783,11 @@ impl AgentsViewMode {
self.anchor_selection_pending = false;
self.clear_anchor_loading_hint();
self.sync_selected_row_state();
+ // The click moves the selection like a direction key, so the
+ // keyboard rule applies before the open: a toggle-click (a
+ // subagent summary or code row) stays in the view, and the
+ // composer never stays armed against a row the highlight left.
+ self.disarm_reply_off_selected();
self.open_selected();
}
}
diff --git a/crates/pa-tui/src/agents_view/delete.rs b/crates/pa-tui/src/agents_view/delete.rs
index 6054ef4fc3..919fb3eade 100644
--- a/crates/pa-tui/src/agents_view/delete.rs
+++ b/crates/pa-tui/src/agents_view/delete.rs
@@ -2,7 +2,8 @@
//! `pendingKillSubagent`), the wire dispatch the confirm executes, and
//! the no-effect outcome summary (moved with its concern).
use super::{
- mpsc, AgentsViewMode, AgentsViewRow, DaemonClient, DaemonCommand, RowKind, UiInput, Value,
+ mpsc, AgentsViewMode, AgentsViewRow, DaemonClient, DaemonCommand, RowKind, StatusTone, UiInput,
+ Value,
};
/// The armed stop-or-delete row (TS `pendingDeleteAgent` /
@@ -167,23 +168,35 @@ pub(super) fn spawn_delete_dispatch(
}
}
};
- let outcome = match client.request(request).await {
+ // The outcome's tone (TS `setStatusMessage`'s explicit tones):
+ // a success reads muted, a no-effect stop warning, a failure
+ // error — the status line never re-derives it from the text.
+ let (outcome, tone) = match client.request(request).await {
Ok(response) if response.success && action.effect_happened(&response) => {
- action.success_message()
+ (action.success_message(), StatusTone::Muted)
}
Ok(response) if response.success => {
// The wire ran but changed nothing: the status carries
// what the wire said, never the button's hope.
let summary = no_effect_summary(response.data.as_ref());
- format!("{} did not change anything: {summary}", action.fail_word())
+ (
+ format!("{} did not change anything: {summary}", action.fail_word()),
+ StatusTone::Warning,
+ )
}
Ok(response) => {
let error = response
.error
.unwrap_or_else(|| "the command failed".into());
- format!("{} failed: {error}", action.fail_word())
+ (
+ format!("{} failed: {error}", action.fail_word()),
+ StatusTone::Error,
+ )
}
- Err(error) => format!("{} failed: {error}", action.fail_word()),
+ Err(error) => (
+ format!("{} failed: {error}", action.fail_word()),
+ StatusTone::Error,
+ ),
};
let deleted_saved_path = match &action {
DeleteAction::DeleteSavedSession { session_path, .. }
@@ -198,12 +211,32 @@ pub(super) fn spawn_delete_dispatch(
};
let _ = ui_tx.send(UiInput::DeleteResult {
message: outcome,
+ tone,
deleted_saved_path,
});
})
}
impl AgentsViewMode {
+ /// The ctrl+x two-press grammar (TS `handleDeleteSelected`'s confirm
+ /// arms): a second press on the same row — with the same live-work
+ /// word it armed with — executes the stop-or-delete dispatch;
+ /// anything else (re-)arms the confirm over the selected row.
+ pub(super) fn confirm_delete_for_selected(&mut self, was_armed: Option<PendingDelete>) {
+ let executes = was_armed.is_some_and(|pending| {
+ self.rows.get(self.selected).is_some_and(|row| {
+ row.identity == pending.identity && Self::delete_arm_word(row) == pending.stop
+ })
+ });
+ if executes {
+ if let Some(action) = self.delete_action_for_selected() {
+ self.pending_delete_action = Some(action);
+ }
+ } else if let Some(pending) = self.delete_arm_target() {
+ self.pending_delete = Some(pending);
+ }
+ }
+
pub(super) fn delete_arm_target(&self) -> Option<PendingDelete> {
let row = self.rows.get(self.selected)?;
let stop = Self::delete_arm_word(row);
@@ -390,8 +423,13 @@ impl AgentsViewMode {
/// One landed stop-or-delete outcome: the status line reports it,
/// and a deleted saved row leaves the catalog immediately (the live
/// roster push covers the other arms; saved rows have no push).
- pub(super) fn delete_result(&mut self, message: String, deleted_saved_path: Option<String>) {
- self.status = Some(message);
+ pub(super) fn delete_result(
+ &mut self,
+ message: &str,
+ tone: StatusTone,
+ deleted_saved_path: Option<String>,
+ ) {
+ self.set_status_tone(message, tone);
// A deleted saved row leaves the catalog by its own path (the
// key the daemon deleted), never by the display name.
if let Some(path) = deleted_saved_path {
diff --git a/crates/pa-tui/src/agents_view/open_incident.rs b/crates/pa-tui/src/agents_view/open_incident.rs
index 18ca3d641d..833d0231e0 100644
--- a/crates/pa-tui/src/agents_view/open_incident.rs
+++ b/crates/pa-tui/src/agents_view/open_incident.rs
@@ -11,7 +11,7 @@ use super::{
impl AgentsViewMode {
pub(super) fn open_selected(&mut self) {
if self.anchor_selection_pending && self.options.scope.is_none() {
- self.status = Some(ANCHOR_LOADING_HINT.to_string());
+ self.set_status(ANCHOR_LOADING_HINT);
return;
}
let Some(row) = self.rows.get(self.selected).cloned() else {
@@ -59,7 +59,7 @@ impl AgentsViewMode {
_ => None,
};
let Some(target) = target else {
- self.status = Some("No program recorded for these subagents".to_string());
+ self.set_status("No program recorded for these subagents");
return;
};
// TS :1709-1717: the program only renders inside the expanded
@@ -117,9 +117,7 @@ impl AgentsViewMode {
// the child row selected, and surface why.
let root = self.find_subagent_root_row(row);
let Some(root) = root else {
- self.status = Some(
- "Cannot open agent without an active runtime or saved session file".to_string(),
- );
+ self.set_status("Cannot open agent without an active runtime or saved session file");
return;
};
let root = root.clone();
@@ -197,8 +195,7 @@ impl AgentsViewMode {
);
return;
}
- self.status =
- Some("Cannot open agent without an active runtime or saved session file".to_string());
+ self.set_status("Cannot open agent without an active runtime or saved session file");
}
/// Record the open outcome (TS the run result the loop consumes): the
@@ -309,7 +306,7 @@ impl AgentsViewMode {
{
return false;
}
- self.status = Some("Incident notice dismissed".to_string());
+ self.set_status("Incident notice dismissed");
true
}
diff --git a/crates/pa-tui/src/agents_view/rename.rs b/crates/pa-tui/src/agents_view/rename.rs
index c54d5828c7..03f84bb647 100644
--- a/crates/pa-tui/src/agents_view/rename.rs
+++ b/crates/pa-tui/src/agents_view/rename.rs
@@ -6,19 +6,27 @@ use serde_json::Value;
use super::{AgentsViewMode, Composer, DaemonClient, UiInput};
use crate::agents_view_forest::RowKind;
+use crate::editor::{Editor, EditorEvent};
use pa_types::daemon::DaemonCommand;
use tokio::sync::mpsc;
-/// One rename request (TS `renameTarget`'s summary fields): the target
-/// session and the name. The same value is the draft (the `name` buffer
-/// while composing) and the dispatched request (the trimmed `name` at
-/// confirm time).
+/// One rename request (TS `confirmRename`'s trimmed value): the target
+/// session and the name the dispatch carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Rename {
pub(super) target: RenameTarget,
pub(super) name: String,
}
+/// The rename composer's state (TS `renameTarget` + the editor): the
+/// editor owns the draft — the full cursor/word/kill/undo grammar, no
+/// autocomplete (TS's provider answers only while a reply is armed)
+/// — and the confirm dispatches the trimmed text.
+pub(super) struct RenameComposer {
+ pub(super) target: RenameTarget,
+ pub(super) editor: Editor,
+}
+
/// Which session a rename targets (TS `renameSession`'s order: the live
/// session through `rename`, the saved file through
/// `rename_saved_session`).
@@ -81,20 +89,26 @@ impl AgentsViewMode {
.get(self.selected)
.is_some_and(|row| row.kind == RowKind::Agent)
{
- self.status = Some("This session cannot be renamed".to_string());
+ self.set_status("This session cannot be renamed");
}
return;
};
- self.composer = Composer::Rename(Rename { target, name });
+ let mut editor = Editor::new();
+ editor.set_keybindings(self.keybindings.clone());
+ editor.set_text(&name);
+ editor.clear_autocomplete_provider();
+ self.composer = Composer::Rename(Box::new(RenameComposer { target, editor }));
}
/// The rename-mode key routing (TS `handleInput`'s rename branch,
- /// :1119-1126): the cancel key exits back to search, the confirm key
- /// submits the trimmed name, and every other key edits the buffer —
- /// the same grammar the search field supports — or is swallowed, as
- /// TS's editor swallows it. The draft comes in owned (the caller
- /// hands it over) and goes back only where the mode continues.
- pub(super) fn handle_rename_key(&mut self, mut rename: Rename, key: &str) {
+ /// :1119-1126): the cancel key exits back to search, the editor's
+ /// submit (Enter) dispatches the trimmed, paste-expanded draft,
+ /// and every other key goes to the editor's own grammar (TS's
+ /// `editor.handleInput` — the full cursor/word/kill/undo editing,
+ /// not the search field's subset).
+ /// The composer comes in owned (the caller hands it over) and goes
+ /// back only where the mode continues.
+ pub(super) fn handle_rename_key(&mut self, mut rename: Box<RenameComposer>, key: &str) {
// Every ctrl+c in rename mode counts as handled for the force-quit guard;
// the default cancel binding includes ctrl+c.
if key == "ctrl+c" {
@@ -103,31 +117,29 @@ impl AgentsViewMode {
if self.keybindings.matches(key, "tui.select.cancel") {
return;
}
- if self.keybindings.matches(key, "tui.select.confirm") {
- let name = rename.name.trim().to_string();
- if !name.is_empty() {
- self.status = Some("Renaming agent...".to_string());
+ // The editor owns Enter (TS `editor.handleInput` -> `confirmRename`):
+ // its submit hands over the trimmed, paste-expanded draft; an empty
+ // name exits (TS `exitRenameMode`). Its other events have no host here.
+ rename.editor.handle_input(key);
+ let submitted = rename
+ .editor
+ .take_events()
+ .into_iter()
+ .find_map(|event| match event {
+ EditorEvent::Submitted(text) => Some(text),
+ _ => None,
+ });
+ match submitted {
+ Some(name) if !name.is_empty() => {
+ self.set_status("Renaming agent...");
self.pending_rename = Some(Rename {
target: rename.target,
name,
});
}
- return;
- }
- if self
- .keybindings
- .matches(key, "tui.editor.deleteCharBackward")
- {
- rename.name.pop();
- } else if self
- .keybindings
- .matches(key, "tui.editor.deleteToLineStart")
- {
- rename.name.clear();
- } else if key.chars().count() == 1 {
- rename.name.push_str(key);
+ Some(_) => {}
+ None => self.composer = Composer::Rename(rename),
}
- self.composer = Composer::Rename(rename);
}
/// One landed rename outcome (TS `renameSession`'s report): the
@@ -136,9 +148,32 @@ impl AgentsViewMode {
/// get no push; a live row's roster flush rides the rename's
/// `session_info_changed` broadcast).
pub(super) fn rename_result(&mut self, rename: Rename, outcome: Result<(), String>) {
+ // The reply composer's `/name` view command (TS
+ // `runAgentsViewCommand`'s name arm): the in-flight draft marks
+ // the composer that dispatched the rename (TS's
+ // `armedAtStart === replyTarget` object guard — a re-armed
+ // composer carries no in-flight draft). Success disarms it
+ // (`disarmIfUnchanged`, no editor check); failure restores the
+ // draft under the empty-editor guard.
+ if let Composer::Reply(reply) = &mut self.composer {
+ if reply.in_flight.is_some() {
+ match &outcome {
+ Ok(()) => {
+ self.disarm_reply();
+ }
+ Err(_) => {
+ if reply.editor.get_text().is_empty() {
+ if let Some(draft) = reply.in_flight.take() {
+ reply.editor.set_text(&draft);
+ }
+ }
+ }
+ }
+ }
+ }
match outcome {
Ok(()) => {
- self.status = Some(format!("Renamed to {}", rename.name));
+ self.set_status(&format!("Renamed to {}", rename.name));
self.actions.push("renamed");
if let RenameTarget::Saved { session_path } = rename.target {
if let Some(saved) = self.saved.iter_mut().find(|saved| {
@@ -150,7 +185,7 @@ impl AgentsViewMode {
}
}
Err(error) => {
- self.status = Some(format!("Failed to rename agent: {error}"));
+ self.set_status(&format!("Failed to rename agent: {error}"));
}
}
}
diff --git a/crates/pa-tui/src/agents_view/render.rs b/crates/pa-tui/src/agents_view/render.rs
index 80103a05fb..2a9b604a6e 100644
--- a/crates/pa-tui/src/agents_view/render.rs
+++ b/crates/pa-tui/src/agents_view/render.rs
@@ -18,7 +18,6 @@ impl AgentsViewMode {
// The frame height feeds the page step (TS reads
// `ui.terminal.rows` live at key time instead).
self.last_height = height;
- let theme = &self.theme;
let mut lines: Vec<Line> = Vec::new();
// TS `getAgentCountsText` rides the splash as extra metadata. Like
// TS `countRowsBySection`, it counts agent-kind rows only — nested
@@ -41,6 +40,7 @@ impl AgentsViewMode {
if let Some(depth) = self.scope_depth {
extra_metadata.push(("depth".to_string(), depth.to_string()));
}
+ let theme = &self.theme;
let chrome = crate::chrome::ChromeState {
version: self.options.version.clone(),
cwd: self.options.cwd.to_string_lossy().to_string(),
@@ -75,12 +75,16 @@ impl AgentsViewMode {
}
}
- // TS `renderPrompt`: header lines go above the prompt row, before the
- // cursor row is taken.
- let (header, prompt, cursor_col) = self.render_prompt(theme, width);
+ // TS `renderPrompt`: the composer's header lines go above the box,
+ // before the cursor row is taken; the box's own rows follow, and
+ // the cursor rides inside them. The prompt's editor mutates its
+ // own scroll state, so the theme borrow above ends here and the
+ // frame re-borrows it for the list below.
+ let (header, prompt_rows, box_cursor) = self.render_prompt(width);
lines.extend(header);
- let cursor = Some((lines.len(), cursor_col));
- lines.push(prompt);
+ let prompt_start = lines.len();
+ lines.extend(prompt_rows);
+ let cursor = box_cursor.map(|(row, col)| (prompt_start + row, col));
lines.push(vec![]);
// The notice panel (a multi-line refusal from the previous run)
@@ -127,13 +131,14 @@ impl AgentsViewMode {
/// The prompt block (TS `renderPrompt`, :2917-2926): the search
/// composer renders the transparent editor shape (the muted `> `
/// prefix, the dim "Search sessions" placeholder) over the plain
- /// surface; the rename composer renders the non-inline shape — the
- /// warning header line above, the buffer in the text color on the
- /// editor background (TS `getEditorBackgroundColor`), the dim
- /// placeholder while empty. Returns the header lines (above the
- /// prompt), the prompt row, and the cursor column.
- fn render_prompt(&self, theme: &Theme, width: usize) -> (Vec<Line>, Line, usize) {
- match &self.composer {
+ /// surface; the rename composer renders the real editor box (TS
+ /// `Editor.render` with the background) — the warning header block
+ /// inside it, the draft in the text color, the dim placeholder
+ /// while empty. Returns the lines above the box, the box's rows,
+ /// and the cursor's row within the box and its column.
+ fn render_prompt(&mut self, width: usize) -> (Vec<Line>, Vec<Line>, Option<(usize, usize)>) {
+ let theme = &self.theme;
+ match &mut self.composer {
Composer::Search => {
let mut prompt: Line = vec![crate::Span::styled(
" > ".to_string(),
@@ -153,51 +158,54 @@ impl AgentsViewMode {
}
(
Vec::new(),
- prompt,
+ vec![prompt],
// The cursor caps at the same width the query
// displays (`truncate_text` keeps width - 5, the
- // rename arm's own cap): a longer query would
+ // editor box's own cap): a longer query would
// otherwise park the caret past the last rendered
// cell, where the terminal frame skips it.
- 4 + str_width(&self.query).min(width.saturating_sub(5)),
+ Some((0, 4 + str_width(&self.query).min(width.saturating_sub(5)))),
)
}
+ // The reply composer's real editor box (the rename box's
+ // shape): the target's header line rides INSIDE the box, the
+ // placeholder names the action by the target's state, and
+ // the cursor comes from the box. An open completion renders
+ // its overlay panel above the box — the chat's stacking (TS
+ // draws the same dropdown through the editor's TUI overlay,
+ // editor.ts `showOverlay`, anchored over the box).
+ Composer::Reply(reply) => {
+ let overlay = crate::view::editor_surface::overlay(&reply.editor, theme, width);
+ let header = reply.header_line(theme);
+ let placeholder = reply.placeholder();
+ let surface = crate::view::editor_surface::render(
+ &mut reply.editor,
+ theme,
+ width,
+ u16::try_from(self.last_height).unwrap_or(u16::MAX),
+ Some(header),
+ Some(placeholder),
+ );
+ (overlay, surface.rows, surface.cursor)
+ }
+ // The rename composer's real editor box (TS `CustomEditor.render`
+ // over `Editor.render`): the warning header rides INSIDE the box
+ // (the header block under the top row, TS `getHeaderLine` via
+ // `renderHeaderContentLine`), the draft renders through the
+ // editor's own surface, and the cursor comes from the box —
+ // the #3117 SF1 2-row shape closes.
Composer::Rename(rename) => {
- let header = vec![vec![
- // TS v0.9.7's renderPrompt header padding (the parity
- // run's a2 frame): the header indents two spaces.
- theme.fg(ThemeColor::Warning, " Rename agent session".to_string()),
- ]];
- let mut prompt: Line = vec![crate::Span::styled(
- " > ".to_string(),
- theme.fg_style(ThemeColor::Muted),
- )];
- prompt.push(crate::Span::styled(
- truncate_text(&rename.name, width.saturating_sub(5).max(1)),
- theme.fg_style(ThemeColor::Text),
- ));
- if rename.name.is_empty() {
- prompt.push(crate::Span::styled(
- " ".to_string(),
- theme.fg_style(ThemeColor::Muted),
- ));
- prompt.push(crate::Span::styled(
- "Name this agent session".to_string(),
- theme.fg_style(ThemeColor::Dim),
- ));
- }
- let prompt = theme.bg_paint(
- crate::theme::ThemeBg::UserMessageBg,
- pad_line(prompt, width),
+ let header =
+ vec![theme.fg(ThemeColor::Warning, "Rename agent session".to_string())];
+ let surface = crate::view::editor_surface::render(
+ &mut rename.editor,
+ theme,
+ width,
+ u16::try_from(self.last_height).unwrap_or(u16::MAX),
+ Some(header),
+ Some("Name this agent session"),
);
- // The caret parks after the same clipped text budget it
- // renders (a name that fills the field parks the caret on
- // the last visible cell, never one past the frame edge).
- (
- header,
- prompt,
- 4 + str_width(&rename.name).min(width.saturating_sub(5).max(1)),
- )
+ (Vec::new(), surface.rows, surface.cursor)
}
}
}
@@ -634,11 +642,58 @@ impl AgentsViewMode {
);
return truncate_line(&vec![theme.fg(ThemeColor::Muted, hint)], width);
}
- if let Some(status) = status_override.or(self.status.as_deref()) {
- return truncate_line(
- &vec![theme.fg(ThemeColor::Error, status.to_string())],
- width,
- );
+ // TS `renderHints`: the status renders in its own tone (a
+ // failure reads error, a plain report muted). The truncation
+ // keeps the style: the row is one span, clipped to the width
+ // (`truncate_line` re-wraps plain text and would strip it — the
+ // tone is the row's whole point, the #3117 SF6 divergence).
+ if let Some(status) = self.status.as_ref() {
+ return vec![theme.fg(status.tone().color(), truncate_text(status.text(), width))];
+ }
+ // The notice fallback (the degenerate pane's first refusal
+ // line) is the error family it always was.
+ if let Some(status) = status_override {
+ return vec![theme.fg(ThemeColor::Error, truncate_text(status, width))];
+ }
+ // The reply composer's hints (TS `renderReplyComposerHints`,
+ // :2964-2978): the confirm key's word by the target's CURRENT
+ // state (steer while it streams, send live, resume & send
+ // saved), the queue hint while the draft has text, and cancel
+ // over the cancel binding's every key.
+ if let Composer::Reply(reply) = &self.composer {
+ let current = self.current_reply_summary(&reply.target);
+ let live = current
+ .get("activeSessionId")
+ .and_then(serde_json::Value::as_str)
+ .is_some();
+ let streaming = live
+ && current
+ .get("isStreaming")
+ .and_then(serde_json::Value::as_bool)
+ == Some(true);
+ let word = if streaming {
+ "steer"
+ } else if live {
+ "send"
+ } else {
+ "resume & send"
+ };
+ let mut hints = vec![format!(
+ "{} {word}",
+ self.keybindings.key_text("tui.select.confirm")
+ )];
+ if !reply.editor.get_text().trim().is_empty() {
+ hints.push(format!(
+ "{} queue",
+ self.keybindings.key_text("app.message.followUp")
+ ));
+ }
+ hints.push(format!(
+ "{} cancel",
+ self.keybindings.key_text("tui.select.cancel")
+ ));
+ let hint = hints.join(" ");
+ return truncate_line(&vec![theme.fg(ThemeColor::Muted, hint)], width);
}
// The rename composer's hint (TS :2942-2944): save/cancel over
// the confirm/cancel bindings' every key (`keyText` — TS shows
@@ -704,6 +759,12 @@ impl AgentsViewMode {
{
segments.push(format!("{keys} rename"));
}
+ // The reply slot (the operator's completeness directive: TS
+ // shows none — the space arm is undiscoverable without it):
+ // only while the selected row is replyable.
+ if let Some(keys) = all("app.agents.reply").filter(|_| self.reply_target().is_some()) {
+ segments.push(format!("{keys} reply"));
+ }
if let Some(pending) = self.delete_arm_target() {
if let Some(keys) = all("app.agents.delete") {
let word = if pending.stop { "stop" } else { "delete" };
@@ -827,35 +888,58 @@ impl Renderer {
// Ctrl+C pairs for the exit guard: this thread stays alive
// when the view loop is wedged in a daemon request, so the
// force-quit contract holds regardless of loop state.
- crate::input::spawn_terminal_reader(move |event| match event {
- crossterm::event::Event::Key(key) => {
- exit_guard.observe_key(&key);
- // The id door filters the way every session handler
- // does (`let Some(id) = key_event_to_id(&key)`): kitty
- // Release events and unmappable keys map to no id, and
- // a forwarded empty id would run handle_key's "any
- // other key" arm — clearing the armed exit hint
- // between the presses of a double Ctrl+C, so the
- // second press re-arms instead of exiting.
- let Some(id) = crate::keys::key_event_to_id(&key) else {
- return true;
- };
- ui_tx.send(UiInput::Key(id)).is_ok()
+ // The paste-aware variant (the session surface's reader):
+ // a marker-less multi-line keystroke burst coalesces into
+ // one paste — Enter submits in the composers, so a burst
+ // typed line by line would submit per line.
+ crate::input::spawn_paste_aware_reader(move |input| match input {
+ crate::input::ReaderInput::BurstPaste(text) => {
+ ui_tx.send(UiInput::Paste(text)).is_ok()
}
- crossterm::event::Event::Mouse(mouse) => {
- // Mouse reports are consumed even when tracking is
- // off (terminal noise downstream); an active surface
- // decodes and dispatches them.
- let report = crate::mouse_tracking::active()
- .then(|| crate::mouse::from_crossterm(mouse))
- .flatten();
- match report {
- Some(event) => ui_tx.send(UiInput::Mouse(event)).is_ok(),
- None => true,
+ // A report the guard reassembled from a sequence the
+ // reader split at a committed-`ESC` boundary: the same
+ // contract as the terminal's own mouse events below —
+ // consumed unless tracking is active.
+ crate::input::ReaderInput::Mouse(report) => {
+ if crate::mouse_tracking::active() {
+ ui_tx.send(UiInput::Mouse(report)).is_ok()
+ } else {
+ true
}
}
- crossterm::event::Event::Resize(..) => ui_tx.send(UiInput::Resize).is_ok(),
- _ => true,
+ crate::input::ReaderInput::Event(event) => match event {
+ crossterm::event::Event::Key(key) => {
+ exit_guard.observe_key(&key);
+ // The id door filters the way every session handler
+ // does (`let Some(id) = key_event_to_id(&key)`): kitty
+ // Release events and unmappable keys map to no id, and
+ // a forwarded empty id would run handle_key's "any
+ // other key" arm — clearing the armed exit hint
+ // between the presses of a double Ctrl+C, so the
+ // second press re-arms instead of exiting.
+ let Some(id) = crate::keys::key_event_to_id(&key) else {
+ return true;
+ };
+ ui_tx.send(UiInput::Key(id)).is_ok()
+ }
+ crossterm::event::Event::Paste(text) => {
+ ui_tx.send(UiInput::Paste(text)).is_ok()
+ }
+ crossterm::event::Event::Mouse(mouse) => {
+ // Mouse reports are consumed even when tracking is
+ // off (terminal noise downstream); an active surface
+ // decodes and dispatches them.
+ let report = crate::mouse_tracking::active()
+ .then(|| crate::mouse::from_crossterm(mouse))
+ .flatten();
+ match report {
+ Some(event) => ui_tx.send(UiInput::Mouse(event)).is_ok(),
+ None => true,
+ }
+ }
+ crossterm::event::Event::Resize(..) => ui_tx.send(UiInput::Resize).is_ok(),
+ _ => true,
+ },
});
let terminal = ratatui::Terminal::new(crate::hyperlinks::stdout_backend())?;
// The adopted buffer still holds the previous view's frame;
diff --git a/crates/pa-tui/src/agents_view/reply.rs b/crates/pa-tui/src/agents_view/reply.rs
new file mode 100644
index 0000000000..967ee67064
--- /dev/null
+++ b/crates/pa-tui/src/agents_view/reply.rs
@@ -0,0 +1,1023 @@
+//! The reply flow (TS `toggleReplyTarget`/`setReplyTarget`/`sendReply`,
+//! agents-view-mode.ts:1585-2108): the space-key composer over the
+//! prompt, its arm/disarm and key routing, the headline fetch the arm
+//! fires, the send/resume/kill dispatches, and the landed outcomes'
+//! statuses — moved with its concern.
+use serde_json::Value;
+
+use super::delete::PendingDelete;
+use super::rename::{Rename, RenameTarget};
+use super::status::{Status, StatusTone};
+use super::{AgentsViewMode, Composer, DaemonClient, UiInput};
+use crate::agents_view_forest::RowKind;
+use crate::editor::{Editor, EditorEvent};
+use crate::theme::{Theme, ThemeColor};
+use crate::{Line, Span};
+use pa_types::daemon::{DaemonCommand, PromptInput, StreamingBehavior};
+use pa_types::slash_commands::{
+ is_session_slash_command_name, parse_slash_command, SlashCommandRegistry,
+ SESSION_SLASH_COMMAND_NAMES,
+};
+use tokio::sync::mpsc;
+
+/// The row-targeted view commands (TS `AGENTS_VIEW_COMMAND_NAMES`): the
+/// one name list the parser, the rejection rule, and the autocomplete
+/// entries all read.
+pub(super) const VIEW_COMMAND_NAMES: [&str; 2] = ["name", "kill"];
+
+/// TS `AGENTS_VIEW_COMMAND_DESCRIPTIONS` (the autocomplete entries'
+/// labels): the view commands' own descriptions, `/name`'s argument
+/// hint, and its takes-argument.
+const VIEW_COMMAND_DESCRIPTIONS: [(&str, &str, Option<&str>, bool); 2] = [
+ ("name", "Set session display name", Some("<name>"), true),
+ (
+ "kill",
+ "Stop this agent's runtime (session stays resumable)",
+ None,
+ false,
+ ),
+];
+
+/// TS `createReplyComposerAutocompleteProvider` (:813-824): the
+/// session-owned builtins plus the view commands, path completion
+/// based at the target's own cwd (the reply runs in the target's
+/// directory, not the view's).
+fn reply_autocomplete_provider(
+ summary: &Value,
+ fallback_cwd: &std::path::Path,
+) -> Box<dyn crate::autocomplete::AutocompleteProvider + Send> {
+ let registry = SlashCommandRegistry::builtin_cached();
+ let mut commands: Vec<crate::autocomplete::SlashCommandEntry> = SESSION_SLASH_COMMAND_NAMES
+ .iter()
+ .filter_map(|name| registry.get(name))
+ .map(|command| crate::autocomplete::SlashCommandEntry {
+ name: command.name.to_string(),
+ aliases: command.aliases.iter().map(ToString::to_string).collect(),
+ description: Some(command.description.to_string()),
+ argument_hint: command.argument_hint.map(str::to_string),
+ takes_argument: command.takes_argument,
+ source_tag: None,
+ })
+ .collect();
+ for (name, description, argument_hint, takes_argument) in VIEW_COMMAND_DESCRIPTIONS {
+ let builtin = registry.get(name);
+ commands.push(crate::autocomplete::SlashCommandEntry {
+ name: name.to_string(),
+ aliases: builtin
+ .map(|command| command.aliases.to_vec())
+ .unwrap_or_default()
+ .iter()
+ .map(ToString::to_string)
+ .collect(),
+ description: Some(description.to_string()),
+ argument_hint: argument_hint.map(str::to_string),
+ takes_argument,
+ source_tag: None,
+ });
+ }
+ let base = summary
+ .get("cwd")
+ .and_then(Value::as_str)
+ .filter(|cwd| !cwd.is_empty())
+ .map_or_else(|| fallback_cwd.to_path_buf(), std::path::PathBuf::from);
+ Box::new(crate::autocomplete::CombinedAutocompleteProvider::new(
+ commands, base,
+ ))
+}
+
+/// The reply target (TS `replyTarget`): the row's key
+/// (`activeSessionId ?? id`) plus the summary captured at arm.
+#[derive(Debug, Clone, PartialEq)]
+pub(super) struct ReplyTarget {
+ pub(super) key: String,
+ pub(super) summary: Value,
+}
+
+/// The header's headline state (TS `replyLastAssistantText` +
+/// `replyLastAssistantTextLoading`).
+#[derive(Debug, Clone, PartialEq)]
+pub(super) enum Headline {
+ /// The live fetch runs (the dim "Loading last response..." line).
+ Loading,
+ /// The fetch landed, or the saved target's recap: `None` renders
+ /// the dim "No response yet" line.
+ Loaded(Option<String>),
+}
+
+/// The reply composer's state: the target, the editor owning the draft,
+/// the header's headline and time, and the submitted draft while a
+/// send or view command is out (restored on failure, TS's
+/// `editor.setText(value)` under the same-target-empty-editor guard).
+pub(super) struct ReplyComposer {
+ pub(super) target: ReplyTarget,
+ pub(super) editor: Editor,
+ pub(super) headline: Headline,
+ /// The relative age at arm (TS `replyHeaderTime`).
+ pub(super) time: String,
+ pub(super) in_flight: Option<String>,
+}
+
+impl ReplyComposer {
+ /// The composer's placeholder (TS `setReplyTarget`'s editor
+ /// placeholder switch): the live target replies, the saved target
+ /// resumes.
+ pub(super) fn placeholder(&self) -> &'static str {
+ if self.target.summary.get("activeSessionId").is_some() {
+ "Write a reply to this agent"
+ } else {
+ "Write a prompt to resume this session"
+ }
+ }
+
+ /// The header line (TS `renderReplyHeaderLine`, :1950-1961): the
+ /// warning time and the headline — the first non-empty,
+ /// whitespace-collapsed line of the last assistant text — or the
+ /// dim loading/no-response line.
+ pub(super) fn header_line(&self, theme: &Theme) -> Line {
+ let headline = match &self.headline {
+ Headline::Loaded(Some(text)) => reply_headline(text).map_or_else(
+ || theme.fg(ThemeColor::Dim, "No response yet".to_string()),
+ Span::raw,
+ ),
+ Headline::Loaded(None) => theme.fg(ThemeColor::Dim, "No response yet".to_string()),
+ Headline::Loading => theme.fg(ThemeColor::Dim, "Loading last response...".to_string()),
+ };
+ if self.time.is_empty() {
+ vec![headline]
+ } else {
+ vec![
+ theme.fg(ThemeColor::Warning, self.time.clone()),
+ Span::raw(" ".to_string()),
+ headline,
+ ]
+ }
+ }
+}
+
+/// The first non-empty line with its whitespace collapsed (TS
+/// `createAgentsViewReplyHeadline`).
+fn reply_headline(text: &str) -> Option<String> {
+ text.lines()
+ .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
+ .find(|line| !line.is_empty())
+}
+
+/// The replyable row's key (TS `toggleReplyTarget`'s
+/// `activeSessionId ?? id` — the same derivation `moveSelection`'s
+/// disarm guard compares against).
+fn reply_key(summary: &Value) -> String {
+ summary
+ .get("activeSessionId")
+ .and_then(Value::as_str)
+ .or_else(|| summary.get("id").and_then(Value::as_str))
+ .unwrap_or_default()
+ .to_string()
+}
+
+/// A successful send's landed facts (TS `sendReply`'s return): the
+/// resumed summary when the send resumed a saved session (the
+/// composer's selection follows it), and the sticky cwd notice when
+/// the resume fell back to a directory that still exists.
+#[derive(Debug, Clone, PartialEq)]
+pub(super) struct ReplySent {
+ pub(super) resumed: Option<Value>,
+ pub(super) cwd_notice: Option<String>,
+}
+
+/// One reply send the run loop dispatches (TS `submit`'s send arm): the
+/// CURRENT summary the send resolves to (`resolveCurrentReplyTargetSummary`),
+/// the submitted text, the streaming behavior, and the resume config
+/// the saved path's create carries.
+#[derive(Debug, Clone, PartialEq)]
+pub(super) struct ReplyRequest {
+ pub(super) key: String,
+ pub(super) summary: Value,
+ pub(super) text: String,
+ pub(super) behavior: Option<StreamingBehavior>,
+ pub(super) resume_config: Value,
+ /// The missing-directory notice the resume config carries (TS
+ /// `resolveAgentsViewOpenCwd`): the sticky status on success.
+ pub(super) cwd_notice: Option<String>,
+}
+
+/// One `/kill` view command the run loop dispatches.
+#[derive(Debug, Clone, PartialEq)]
+pub(super) struct KillRequest {
+ pub(super) key: String,
+ pub(super) active_session_id: String,
+}
+
+impl AgentsViewMode {
+ /// The selected row's reply target (TS `toggleReplyTarget`'s gates:
+ /// a top-level agent with a live session or a saved file, never the
+ /// row an armed delete sits on) — the arm key and the hint slot's
+ /// one "replyable" predicate.
+ pub(super) fn reply_target(&self) -> Option<ReplyTarget> {
+ let row = self
+ .rows
+ .get(self.selected)
+ .filter(|row| row.kind == RowKind::Agent)?;
+ if self
+ .pending_delete
+ .as_ref()
+ .is_some_and(|pending| pending.identity == row.identity)
+ {
+ return None;
+ }
+ let summary = &row.summary;
+ let active = summary
+ .get("activeSessionId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty());
+ let file = summary
+ .get("sessionFile")
+ .and_then(Value::as_str)
+ .filter(|path| !path.is_empty());
+ if active.is_none() && file.is_none() {
+ return None;
+ }
+ Some(ReplyTarget {
+ key: reply_key(summary),
+ summary: summary.clone(),
+ })
+ }
+
+ /// Whether the composer is armed on the given key.
+ fn reply_armed_on(&self, key: &str) -> bool {
+ matches!(&self.composer, Composer::Reply(reply) if reply.target.key == key)
+ }
+
+ /// TS `toggleReplyTarget` (:1795-1838): arm the reply composer over
+ /// the selected agent row — the same target disarms.
+ pub(super) fn toggle_reply(&mut self) {
+ let Some(target) = self.reply_target() else {
+ return;
+ };
+ if self.reply_armed_on(&target.key) {
+ self.disarm_reply();
+ return;
+ }
+ self.arm_reply(target);
+ }
+
+ /// TS `setReplyTarget(target)`: the composer owns a fresh editor
+ /// (the search field's query stays untouched — the filter keeps it,
+ /// exactly as TS filters on its saved query); a live target arms the
+ /// headline fetch, a saved one starts from its recap; the header's
+ /// time is the summary's relative age at arm.
+ fn arm_reply(&mut self, target: ReplyTarget) {
+ let mut editor = Editor::new();
+ editor.set_keybindings(self.keybindings.clone());
+ // TS `setReplyTarget` swaps the editor's provider for the
+ // reply one (the session commands + the view commands, the
+ // target's cwd behind `@` completion).
+ editor.set_autocomplete_provider(reply_autocomplete_provider(
+ &target.summary,
+ &self.options.cwd,
+ ));
+ let active = target
+ .summary
+ .get("activeSessionId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty())
+ .map(str::to_string);
+ let headline = match &active {
+ Some(_) => Headline::Loading,
+ None => Headline::Loaded(
+ target
+ .summary
+ .get("summary")
+ .or_else(|| target.summary.get("firstMessage"))
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ ),
+ };
+ if let Some(active) = active {
+ // The headline fetch dispatches off the key loop (the
+ // mode holds no client); its result is keyed, and a
+ // re-targeted or disarmed composer drops it.
+ self.pending_headline = Some((target.key.clone(), active));
+ }
+ let time = crate::agents_view_state::relative_age(
+ target
+ .summary
+ .get("modified")
+ .or_else(|| target.summary.get("created"))
+ .and_then(Value::as_str),
+ crate::agents_view_state::now_ms(),
+ );
+ self.composer = Composer::Reply(Box::new(ReplyComposer {
+ target,
+ editor,
+ headline,
+ time,
+ in_flight: None,
+ }));
+ }
+
+ /// TS `setReplyTarget(undefined)`: the composer drops (its editor
+ /// with it) and the rows rebuild.
+ pub(super) fn disarm_reply(&mut self) {
+ self.composer = Composer::Search;
+ self.rebuild_rows();
+ }
+
+ /// TS `moveSelection`'s reply guard (:1487-1493): the reply stays
+ /// armed only while the selection sits on the targeted agent row —
+ /// a move off it (a nested row, another agent, a re-keyed runtime)
+ /// disarms.
+ pub(super) fn disarm_reply_off_selected(&mut self) {
+ let on_target = match (&self.composer, self.rows.get(self.selected)) {
+ (Composer::Reply(reply), Some(row)) => {
+ row.kind == RowKind::Agent && reply_key(&row.summary) == reply.target.key
+ }
+ _ => false,
+ };
+ if !on_target && matches!(self.composer, Composer::Reply(_)) {
+ self.disarm_reply();
+ }
+ }
+
+ /// The target's CURRENT summary at send time (TS
+ /// `resolveCurrentReplyTargetSummary`, :826-842): the unified
+ /// records by identity/alias, then the live roster by active id,
+ /// then the captured summary — with its stale runtime id dropped
+ /// when a persisted target left the live catalog but still has its
+ /// file.
+ pub(super) fn current_reply_summary(&self, target: &ReplyTarget) -> Value {
+ let identity = crate::agents_view_forest::summary_identity(&target.summary);
+ if let Some(record) = self
+ .records()
+ .into_iter()
+ .find(|record| record.identity == identity || record.aliases.contains(&identity))
+ {
+ // TS `summaryForUnifiedRecord`: the merged summary a row
+ // acts on — the live summary with saved fields filling the
+ // gaps, saved-only records in their synthesized archived
+ // shape (the raw catalog row carries `path`, not
+ // `sessionFile`).
+ return crate::agents_view_state::summary_for_record(&record);
+ }
+ let active = target
+ .summary
+ .get("activeSessionId")
+ .and_then(Value::as_str);
+ if let Some(summary) = active.and_then(|active| {
+ self.roster
+ .iter()
+ .filter_map(|entry| entry.get("summary"))
+ .find(|summary| {
+ summary.get("activeSessionId").and_then(Value::as_str) == Some(active)
+ })
+ }) {
+ return summary.clone();
+ }
+ let mut summary = target.summary.clone();
+ if summary.get("sessionFile").is_some() && summary.get("activeSessionId").is_some() {
+ // A persisted target missing from the live catalog can still
+ // resume from its captured file, but its captured runtime id
+ // is stale (TS drops it with the archived lifecycle) — the key
+ // leaves entirely, so the presence checks (the steer gate, the
+ // resuming status) read it as saved.
+ if let Some(object) = summary.as_object_mut() {
+ object.remove("activeSessionId");
+ }
+ summary["lifecycle"] = serde_json::json!("archived");
+ summary["activity"] = serde_json::json!("idle");
+ }
+ summary
+ }
+
+ /// The reply-mode key routing (TS `handleInput`'s gates while armed,
+ /// :1127-1200, plus the editor's own app checks): the cancel keys
+ /// disarm, the empty-editor gates run the view's row actions, the
+ /// follow-up key queues, and every other key (Enter included) goes
+ /// to the editor, whose submit dispatches. The composer comes in owned
+ /// (the caller hands it over) and goes back only where the mode continues.
+ pub(super) fn handle_reply_key(
+ &mut self,
+ mut reply: Box<ReplyComposer>,
+ was_delete_armed: Option<PendingDelete>,
+ key: &str,
+ ) {
+ // Every ctrl+c while armed counts as handled for the force-quit
+ // guard: the composer's cancel and clear keys include it.
+ if key == "ctrl+c" {
+ self.exit_guard.note_ctrl_c_handled();
+ }
+ // TS `app.clear` (ctrl+c) disarms — the composer's hints
+ // advertise it as cancel, so it never starts the exit flow.
+ if self.keybindings.matches(key, "app.clear") {
+ self.disarm_reply();
+ return;
+ }
+ let empty = reply.editor.get_text().is_empty();
+ if empty {
+ // TS :1153: the rename gate disarms first (:1880), then
+ // enters the rename composer.
+ if self.keybindings.matches(key, "app.agents.rename") {
+ self.enter_rename_mode();
+ return;
+ }
+ // TS :1157: the stop-or-delete two-press grammar — the
+ // reply stays armed behind the confirm (TS's gates never
+ // touch the reply target).
+ if self.keybindings.matches(key, "app.agents.delete") {
+ self.confirm_delete_for_selected(was_delete_armed);
+ self.composer = Composer::Reply(reply);
+ return;
+ }
+ // TS :1164: the reply key toggles — the same target disarms.
+ if self.keybindings.matches(key, "app.agents.reply") {
+ self.composer = Composer::Reply(reply);
+ self.toggle_reply();
+ return;
+ }
+ // TS :1176: the program toggle — the reply stays armed.
+ if self.keybindings.matches(key, "app.agents.program") {
+ self.cycle_program_for_selected();
+ self.composer = Composer::Reply(reply);
+ return;
+ }
+ }
+ // TS :1168: alt+enter queues the reply as a follow-up (the blank
+ // draft is a no-op, `handleReplyFollowUp`).
+ if self.keybindings.matches(key, "app.message.followUp") {
+ // Unlike Enter, this path skips the editor's clear — the
+ // send arm clears the buffer itself (TS `handleReplyFollowUp`
+ // expands the paste markers here and submits).
+ let text = reply.editor.get_expanded_text();
+ if text.trim().is_empty() {
+ self.composer = Composer::Reply(reply);
+ } else {
+ self.submit_reply(reply, text, Some(StreamingBehavior::FollowUp));
+ }
+ return;
+ }
+ // The editor's own app checks (TS `CustomEditor.handleInput`,
+ // :194-224): agents-back disarms before the editor's cursor
+ // motions — Left never moves the cursor in the TS reply composer
+ // (a surprising TS behavior, ported for parity) — and escape
+ // disarms (the editor's `onEscape`).
+ if self.keybindings.matches(key, "app.agents.back") {
+ self.disarm_reply();
+ return;
+ }
+ if self.keybindings.matches(key, "app.input.clear") {
+ self.disarm_reply();
+ return;
+ }
+ // TS :1171 (the editor's `onCtrlD`): exit on an empty draft;
+ // a draft in flight keeps the editor's delete-char reading.
+ if empty && self.keybindings.matches(key, "app.exit") {
+ self.running = false;
+ return;
+ }
+ // The editor owns Enter (TS `editor.handleInput` -> `onSubmit`): it
+ // applies an open completion (a typed-exact command falls through and
+ // submits), turns a trailing backslash into a newline, and a submit
+ // clears the buffer and hands over the trimmed, paste-expanded text.
+ // The other events (change/autocomplete/clipboard) have no host here.
+ reply.editor.handle_input(key);
+ let submitted = reply
+ .editor
+ .take_events()
+ .into_iter()
+ .find_map(|event| match event {
+ EditorEvent::Submitted(text) => Some(text),
+ _ => None,
+ });
+ match submitted {
+ Some(value) => self.submit_reply(reply, value, None),
+ None => self.composer = Composer::Reply(reply),
+ }
+ }
+
+ /// TS `submit` (the reply arm, :1585-1631): the trimmed text routes
+ /// through the view commands (`/name`, `/kill`), the rejection, or
+ /// the send. `behavior` is the queued follow-up (`None` resolves
+ /// steer from the target's streaming state, TS `sendReply`'s
+ /// ladder).
+ fn submit_reply(
+ &mut self,
+ mut reply: Box<ReplyComposer>,
+ value: String,
+ follow_up: Option<StreamingBehavior>,
+ ) {
+ let text = value.trim().to_string();
+ // TS `parseAgentsViewCommand` (the builtin alias resolution over
+ // the one view-command name list): the submitted `value` restores
+ // on the command's own failures (TS restores `value`, not `text`).
+ if let Some((name, args)) = parse_view_command(&text) {
+ if name == "name" {
+ self.submit_name_command(&mut reply, &value, &args);
+ } else {
+ self.submit_kill_command(&mut reply, &value);
+ }
+ self.composer = Composer::Reply(reply);
+ return;
+ }
+ // TS `getReplyComposerCommandRejection`: a builtin that is
+ // neither session-owned nor a view command never goes to the
+ // model as prompt text; the draft stays.
+ if let Some(rejection) = reply_command_rejection(&text) {
+ self.set_status_tone(&rejection, StatusTone::Warning);
+ restore_reply_draft(&mut reply, &value);
+ self.composer = Composer::Reply(reply);
+ return;
+ }
+ if text.is_empty() {
+ self.composer = Composer::Reply(reply);
+ return;
+ }
+ reply.editor.set_text("");
+ let key = reply.target.key.clone();
+ let current = self.current_reply_summary(&reply.target);
+ let behavior = follow_up.or_else(|| {
+ (current.get("activeSessionId").is_some()
+ && current.get("isStreaming").and_then(Value::as_bool) == Some(true))
+ .then_some(StreamingBehavior::Steer)
+ });
+ let (resume_config, cwd_notice) = self.resume_config(&current);
+ if current.get("activeSessionId").is_none() {
+ self.set_status("Resuming session...");
+ }
+ reply.in_flight = Some(value);
+ self.pending_reply = Some(ReplyRequest {
+ key,
+ summary: current,
+ text,
+ behavior,
+ resume_config,
+ cwd_notice,
+ });
+ self.composer = Composer::Reply(reply);
+ }
+
+ /// The `/name` view command (TS `runAgentsViewCommand`'s name arm):
+ /// the rename flow against the CURRENT summary — the wire statuses
+ /// ride the rename dispatch; on success the reply disarms, on
+ /// failure the draft restores.
+ fn submit_name_command(&mut self, reply: &mut Box<ReplyComposer>, value: &str, args: &str) {
+ let name = args.trim().to_string();
+ if name.is_empty() {
+ self.set_status_tone("Usage: /name <session name>", StatusTone::Warning);
+ restore_reply_draft(reply, value);
+ return;
+ }
+ let current = self.current_reply_summary(&reply.target);
+ let Some(target) = rename_target_from_summary(&current) else {
+ self.set_status_tone("This session cannot be renamed", StatusTone::Warning);
+ restore_reply_draft(reply, value);
+ return;
+ };
+ reply.in_flight = Some(value.to_string());
+ self.set_status("Renaming agent...");
+ self.pending_rename = Some(Rename { target, name });
+ }
+
+ /// The `/kill` view command (TS `runAgentsViewCommand`'s kill arm):
+ /// an inactive target warns; a live one dispatches the kill — an
+ /// already-finished agent counts as stopped.
+ fn submit_kill_command(&mut self, reply: &mut Box<ReplyComposer>, value: &str) {
+ let current = self.current_reply_summary(&reply.target);
+ let Some(active) = current
+ .get("activeSessionId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty())
+ else {
+ self.set_status_tone(
+ "/kill needs a running agent; this session is inactive",
+ StatusTone::Warning,
+ );
+ restore_reply_draft(reply, value);
+ return;
+ };
+ reply.in_flight = Some(value.to_string());
+ self.pending_kill = Some(KillRequest {
+ key: reply.target.key.clone(),
+ active_session_id: active.to_string(),
+ });
+ }
+
+ /// TS `createAgentsViewResumeConfig` + `resolveAgentsViewOpenCwd`
+ /// (:225-236 + :493-504): the view's create config with the saved
+ /// session's cwd removed — or overridden with the view's cwd (and
+ /// its notice) when the saved directory no longer exists.
+ fn resume_config(&self, summary: &Value) -> (Value, Option<String>) {
+ let mut config = self.options.create_config.clone();
+ let saved_cwd = summary
+ .get("cwd")
+ .and_then(Value::as_str)
+ .filter(|cwd| !cwd.is_empty());
+ let exists = saved_cwd.is_some_and(|cwd| std::path::Path::new(cwd).exists());
+ let fallback = self.options.cwd.to_string_lossy().to_string();
+ let notice = if saved_cwd.is_none_or(|_| exists) {
+ None
+ } else {
+ Some(format!(
+ "Original directory is missing ({}); opened in {fallback} instead.",
+ saved_cwd.unwrap_or_default()
+ ))
+ };
+ let override_cwd = notice.is_some().then_some(fallback);
+ if let Some(override_cwd) = override_cwd {
+ config["cwd"] = serde_json::json!(override_cwd);
+ } else if let Some(object) = config.as_object_mut() {
+ object.remove("cwd");
+ }
+ (config, notice)
+ }
+
+ /// One landed headline (TS `toggleReplyTarget`'s fetch arms): the
+ /// header renders the first line of the fetched text — a
+ /// re-targeted or disarmed composer drops the result (the key
+ /// comparison, TS's `replyTarget?.key === key` guard).
+ pub(super) fn headline_result(&mut self, key: &str, result: Result<Option<String>, String>) {
+ if !self.reply_armed_on(key) {
+ return;
+ }
+ match result {
+ Ok(text) => {
+ if let Composer::Reply(reply) = &mut self.composer {
+ reply.headline = Headline::Loaded(text);
+ }
+ }
+ Err(error) => {
+ if let Composer::Reply(reply) = &mut self.composer {
+ reply.headline = Headline::Loaded(None);
+ }
+ self.set_status(&format!("Failed to load latest response: {error}"));
+ }
+ }
+ }
+
+ /// One landed reply send (TS `sendReply`'s outcomes): the sticky
+ /// cwd notice or "Reply sent" on success (the resumed summary
+ /// selects when the composer still targets it, and the composer
+ /// disarms under TS's unchanged-target-empty-editor guard), the
+ /// failure status and the draft restore on error.
+ pub(super) fn reply_result(&mut self, key: &str, outcome: Result<ReplySent, String>) {
+ match outcome {
+ Ok(sent) => {
+ self.actions.push("reply_sent");
+ if let Some(notice) = sent.cwd_notice {
+ self.status = Some(Status::sticky(&notice));
+ } else {
+ self.set_status("Reply sent");
+ }
+ // The selection follows the resumed summary, and the
+ // composer disarms, both under TS's unchanged-composer
+ // guard (`this.replyTarget === target`): a re-armed
+ // composer carries no in-flight draft, so a late result
+ // never disarms over the user's fresh compose.
+ if self.reply_in_flight(key) {
+ if let Some(resumed) = sent.resumed {
+ self.select_summary_row(&resumed);
+ }
+ if self.reply_editor_empty(key) {
+ self.disarm_reply();
+ }
+ }
+ }
+ Err(error) => {
+ self.set_status(&format!("Failed to send reply: {error}"));
+ if self.reply_in_flight(key) && self.reply_editor_empty(key) {
+ self.restore_reply_draft(key);
+ }
+ }
+ }
+ }
+
+ /// One landed `/kill` (TS `runAgentsViewCommand`'s kill arm): the
+ /// composer disarms under the unchanged-target guard, the status
+ /// reports the stop, and the roster push refreshes the rows behind
+ /// it (the live row leaves the Running section on the next push).
+ pub(super) fn kill_result(&mut self, key: &str, outcome: Result<(), String>) {
+ match outcome {
+ Ok(()) => {
+ self.actions.push("killed");
+ // TS's kill arm disarms the unchanged composer with no
+ // editor check (`disarmIfUnchanged`); the in-flight
+ // draft marks it.
+ if self.reply_in_flight(key) {
+ self.disarm_reply();
+ }
+ self.set_status("Agent stopped");
+ }
+ Err(error) => {
+ self.set_status(&format!("Failed to run /kill: {error}"));
+ if self.reply_in_flight(key) && self.reply_editor_empty(key) {
+ self.restore_reply_draft(key);
+ }
+ }
+ }
+ }
+
+ /// The composer that dispatched the in-flight send or view command
+ /// (TS's object-identity guard `this.replyTarget === target`: a
+ /// re-armed composer on the same target carries no in-flight draft,
+ /// so a late result never disarms or restores over the user's fresh
+ /// compose).
+ fn reply_in_flight(&self, key: &str) -> bool {
+ matches!(&self.composer, Composer::Reply(reply)
+ if reply.target.key == key && reply.in_flight.is_some())
+ }
+
+ /// The armed composer's editor is empty (TS's
+ /// `this.editor.getText().length === 0` guard).
+ fn reply_editor_empty(&self, key: &str) -> bool {
+ matches!(&self.composer, Composer::Reply(reply)
+ if reply.target.key == key && reply.editor.get_text().is_empty())
+ }
+
+ /// TS's draft-restore guard: the in-flight draft goes back only when
+ /// the composer is still armed on the same target with an empty
+ /// editor (the user did not re-arm elsewhere or start typing).
+ fn restore_reply_draft(&mut self, key: &str) {
+ if let Composer::Reply(reply) = &mut self.composer {
+ if reply.target.key == key && reply.editor.get_text().is_empty() {
+ if let Some(draft) = reply.in_flight.take() {
+ reply.editor.set_text(&draft);
+ }
+ }
+ }
+ }
+
+ /// TS `selectSummary`: land the selection on the resumed session's
+ /// row (the identity the rebuild's restore reads).
+ fn select_summary_row(&mut self, summary: &Value) {
+ let identity = crate::agents_view_forest::summary_identity(summary);
+ if let Some(index) = self.rows.iter().position(|row| row.identity == identity) {
+ self.selected = index;
+ self.sync_selected_row_state();
+ }
+ }
+}
+
+/// TS's immediate draft restore (the editor the submit cleared): the
+/// draft goes back when the composer still sits empty.
+fn restore_reply_draft(reply: &mut Box<ReplyComposer>, value: &str) {
+ if reply.editor.get_text().is_empty() {
+ reply.editor.set_text(value);
+ }
+}
+
+/// TS `parseAgentsViewCommand`: the row-targeted view commands, through
+/// the builtin alias resolution.
+fn parse_view_command(text: &str) -> Option<(String, String)> {
+ let (typed, args) = parse_slash_command(text)?;
+ let registry = SlashCommandRegistry::builtin_cached();
+ let name = registry
+ .resolve_name(&typed)
+ .unwrap_or(typed.as_str())
+ .to_string();
+ VIEW_COMMAND_NAMES
+ .contains(&name.as_str())
+ .then_some((name, args))
+}
+
+/// TS `getReplyComposerCommandRejection`: a parsed slash command that
+/// resolves to a builtin that is neither session-owned nor a view
+/// command never goes to the model as plain prompt text.
+fn reply_command_rejection(text: &str) -> Option<String> {
+ let (typed, _args) = parse_slash_command(text)?;
+ let registry = SlashCommandRegistry::builtin_cached();
+ let name = registry
+ .resolve_name(&typed)
+ .unwrap_or(typed.as_str())
+ .to_string();
+ if is_session_slash_command_name(&name) {
+ return None;
+ }
+ if VIEW_COMMAND_NAMES.contains(&name.as_str()) {
+ return None;
+ }
+ if !registry.is_builtin(&typed) {
+ return None;
+ }
+ Some(format!(
+ "/{typed} is not available here; open the session to run it"
+ ))
+}
+
+/// The rename target a `/name` dispatches against (TS `renameSession`'s
+/// order: the live session first, the saved file second): the CURRENT
+/// summary's runtime or file — `None` is the cannot-rename warning.
+fn rename_target_from_summary(summary: &Value) -> Option<RenameTarget> {
+ let active = summary
+ .get("activeSessionId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty());
+ if let Some(active) = active {
+ return Some(super::rename::RenameTarget::Live {
+ active_session_id: active.to_string(),
+ });
+ }
+ let file = summary
+ .get("sessionFile")
+ .and_then(Value::as_str)
+ .filter(|path| !path.is_empty())?;
+ Some(super::rename::RenameTarget::Saved {
+ session_path: file.to_string(),
+ })
+}
+
+/// One headline fetch (TS `getLastAssistantText`): the call runs off the
+/// key loop with a client clone, detached — the exit drain never waits
+/// on it, and its keyed result drops when the composer is gone or
+/// re-targeted.
+pub(super) fn spawn_headline_fetch(
+ client: &DaemonClient,
+ ui_tx: mpsc::UnboundedSender<UiInput>,
+ key: String,
+ active_session_id: String,
+) {
+ let client = client.clone();
+ tokio::spawn(async move {
+ let result = match client
+ .request(DaemonCommand::GetLastAssistantText {
+ id: None,
+ active_session_id: active_session_id.clone(),
+ rest: serde_json::Map::default(),
+ })
+ .await
+ {
+ Ok(response) if response.success => Ok(response
+ .data
+ .as_ref()
+ .and_then(|data| data.get("text"))
+ .cloned()
+ .and_then(|text| text.as_str().map(str::to_string))),
+ Ok(response) => Err(response
+ .error
+ .unwrap_or_else(|| "the command failed".into())),
+ Err(error) => Err(format!("{error:#}")),
+ };
+ let _ = ui_tx.send(UiInput::HeadlineResult {
+ key,
+ result: match result {
+ Ok(text) => Ok(text),
+ Err(error) => Err(error),
+ },
+ });
+ });
+}
+
+/// One reply send (TS `sendReply`, :1981-2026): the saved target resumes
+/// into the daemon first (`create` with the resume config), then the
+/// prompt delivers through the same path as a live reply — the
+/// "Sending reply..." progress rides the wire between the two.
+pub(super) fn spawn_reply_dispatch(
+ client: &DaemonClient,
+ ui_tx: mpsc::UnboundedSender<UiInput>,
+ request: ReplyRequest,
+) -> tokio::task::JoinHandle<()> {
+ let client = client.clone();
+ let key = request.key.clone();
+ tokio::spawn(async move {
+ let outcome = send_reply(client, &ui_tx, request).await;
+ let _ = ui_tx.send(UiInput::ReplyResult { key, outcome });
+ })
+}
+
+async fn send_reply(
+ client: DaemonClient,
+ ui_tx: &mpsc::UnboundedSender<UiInput>,
+ request: ReplyRequest,
+) -> Result<ReplySent, String> {
+ let mut sent = ReplySent {
+ resumed: None,
+ cwd_notice: None,
+ };
+ let mut active_session_id = request
+ .summary
+ .get("activeSessionId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty())
+ .map(str::to_string);
+ if active_session_id.is_none() {
+ // TS `resumeSavedAgentsViewSession`: the create carries the
+ // view's resume config and the saved file; the fresh summary is
+ // the authoritative target for the prompt.
+ let Some(session_path) = request
+ .summary
+ .get("sessionFile")
+ .and_then(Value::as_str)
+ .filter(|path| !path.is_empty())
+ .map(str::to_string)
+ else {
+ return Err("Cannot resume a session without a saved session file".to_string());
+ };
+ let telemetry_disabled = request
+ .resume_config
+ .get("telemetryDisabled")
+ .and_then(Value::as_bool)
+ .filter(|disabled| *disabled)
+ .map(|_| true);
+ let created = client
+ .request(DaemonCommand::Create {
+ id: None,
+ session_path: Some(session_path),
+ continue_recent: None,
+ no_session: None,
+ name: None,
+ config: Some(request.resume_config.clone()),
+ telemetry_disabled,
+ runtime_metadata: None,
+ lifecycle: None,
+ env: None,
+ launch_env: None,
+ rest: serde_json::Map::default(),
+ })
+ .await;
+ let summary = match created {
+ Ok(response) if response.success => response.data.unwrap_or(Value::Null),
+ Ok(response) => {
+ return Err(response
+ .error
+ .unwrap_or_else(|| "the command failed".into()))
+ }
+ Err(error) => return Err(format!("{error:#}")),
+ };
+ let Some(active) = summary
+ .get("activeSessionId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty())
+ .map(str::to_string)
+ else {
+ return Err("Daemon returned a session without an active session id".to_string());
+ };
+ sent.cwd_notice = request.cwd_notice.clone();
+ sent.resumed = Some(summary);
+ active_session_id = Some(active);
+ }
+ // TS's mid-send status (after the resume, before the prompt).
+ let _ = ui_tx.send(UiInput::ReplyProgress("Sending reply...".to_string()));
+ let prompt = client
+ .request(DaemonCommand::Prompt {
+ id: None,
+ active_session_id: active_session_id.unwrap_or_default(),
+ message: request.text,
+ input: PromptInput {
+ content: None,
+ images: None,
+ streaming_behavior: request.behavior,
+ queue_if_busy: None,
+ expand_prompt_templates: None,
+ source: None,
+ agent_message_id: None,
+ custom_message: None,
+ queue_key: None,
+ prefix_messages: None,
+ admission_id: None,
+ rlm_notice_nonce: None,
+ },
+ rest: serde_json::Map::default(),
+ })
+ .await;
+ match prompt {
+ Ok(response) if response.success => Ok(sent),
+ Ok(response) => Err(response
+ .error
+ .unwrap_or_else(|| "the command failed".into())),
+ Err(error) => Err(format!("{error:#}")),
+ }
+}
+
+/// One `/kill` dispatch (TS `runAgentsViewCommand`'s kill arm): an
+/// `Unknown active session:` refusal counts as stopped (the agent
+/// already finished, TS `isUnknownActiveSessionError`).
+pub(super) fn spawn_kill_dispatch(
+ client: &DaemonClient,
+ ui_tx: mpsc::UnboundedSender<UiInput>,
+ request: KillRequest,
+) -> tokio::task::JoinHandle<()> {
+ let client = client.clone();
+ let key = request.key.clone();
+ tokio::spawn(async move {
+ let outcome = match client
+ .request(DaemonCommand::Kill {
+ id: None,
+ active_session_id: request.active_session_id,
+ rest: serde_json::Map::default(),
+ })
+ .await
+ {
+ Ok(response) if response.success => Ok(()),
+ Ok(response)
+ if response
+ .error
+ .as_deref()
+ .is_some_and(|error| error.starts_with("Unknown active session:")) =>
+ {
+ Ok(())
+ }
+ Ok(response) => Err(response
+ .error
+ .unwrap_or_else(|| "the command failed".into())),
+ Err(error) => Err(format!("{error:#}")),
+ };
+ let _ = ui_tx.send(UiInput::KillResult { key, outcome });
+ })
+}
diff --git a/crates/pa-tui/src/agents_view/status.rs b/crates/pa-tui/src/agents_view/status.rs
new file mode 100644
index 0000000000..9e9c866237
--- /dev/null
+++ b/crates/pa-tui/src/agents_view/status.rs
@@ -0,0 +1,167 @@
+//! The status line's presentation (TS `setStatusMessage`,
+//! agents-view-mode.ts:1436-1473): the text with its tone and lifetime.
+//! The line renders one hint row at the bottom of the frame, in the
+//! tone's color, and clears itself after
+//! [`STATUS_MESSAGE_DURATION_MS`](Self::DURATION) — TS arms a timer; the
+//! view's run loop holds the expiry deadline instead (no thread, no
+//! sleep, the chat's ctrl-c-hint deadline pattern).
+use std::time::Duration;
+
+/// The line's color (TS `statusMessageTone`, rendered through
+/// `theme.fg(tone, ...)`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum StatusTone {
+ Muted,
+ Warning,
+ Error,
+}
+
+impl StatusTone {
+ /// The theme color the tone renders in (the one-line status row).
+ pub(super) fn color(self) -> crate::theme::ThemeColor {
+ match self {
+ StatusTone::Muted => crate::theme::ThemeColor::Muted,
+ StatusTone::Warning => crate::theme::ThemeColor::Warning,
+ StatusTone::Error => crate::theme::ThemeColor::Error,
+ }
+ }
+}
+
+/// One status line: the collapsed text, its tone, and its lifetime.
+#[derive(Debug, Clone)]
+pub(super) struct Status {
+ text: String,
+ tone: StatusTone,
+ /// Sticky lines stay up until the next keypress instead of expiring
+ /// (TS `statusMessageSticky`).
+ sticky: bool,
+ /// The expiry instant while the line is transient (TS's
+ /// `STATUS_MESSAGE_DURATION_MS` timer); `None` while sticky.
+ expires: Option<std::time::Instant>,
+}
+
+impl Status {
+ /// TS `STATUS_MESSAGE_DURATION_MS`.
+ const DURATION: Duration = Duration::from_millis(4500);
+
+ /// The text with its whitespace collapsed (TS
+ /// `formatAgentsViewStatusLine`: one line, never the message's own
+ /// line breaks).
+ fn collapse(text: &str) -> String {
+ text.split_whitespace().collect::<Vec<_>>().join(" ")
+ }
+
+ /// TS's tone rule (explicit tone wins, then the `Failed` prefix,
+ /// else muted — `setStatusMessage`'s `options.tone ??`).
+ fn default_tone(text: &str) -> StatusTone {
+ if text.starts_with("Failed") {
+ StatusTone::Error
+ } else {
+ StatusTone::Muted
+ }
+ }
+
+ /// TS `setStatusMessage(message)`: the default tone, the expiry armed.
+ #[must_use]
+ pub(super) fn transient(text: &str) -> Self {
+ let text = Self::collapse(text);
+ let tone = Self::default_tone(&text);
+ Self::with(text, tone, false)
+ }
+
+ /// TS `setStatusMessage(message, { tone })`: the explicit tone and
+ /// the expiry armed.
+ #[must_use]
+ pub(super) fn with_tone(text: &str, tone: StatusTone) -> Self {
+ Self::with(Self::collapse(text), tone, false)
+ }
+
+ /// TS `setStatusMessage(message, { sticky: true })`: the default tone
+ /// rule, no expiry — the line stays until the next keypress.
+ #[must_use]
+ pub(super) fn sticky(text: &str) -> Self {
+ let text = Self::collapse(text);
+ let tone = Self::default_tone(&text);
+ Self::with(text, tone, true)
+ }
+
+ fn with(text: String, tone: StatusTone, sticky: bool) -> Self {
+ Self {
+ expires: (!sticky).then(|| std::time::Instant::now() + Self::DURATION),
+ text,
+ tone,
+ sticky,
+ }
+ }
+
+ /// The line's collapsed text.
+ pub(super) fn text(&self) -> &str {
+ &self.text
+ }
+
+ /// The line's tone.
+ pub(super) fn tone(&self) -> StatusTone {
+ self.tone
+ }
+
+ /// Whether the line waits for the next keypress instead of the timer.
+ pub(super) fn is_sticky(&self) -> bool {
+ self.sticky
+ }
+
+ /// The expiry instant while the window is still open at `now` (the
+ /// loop's wake arm reads this the same way the chat arms its ctrl-c
+ /// hint deadline).
+ pub(super) fn expiry(&self, now: std::time::Instant) -> Option<std::time::Instant> {
+ self.expires.filter(|at| now < *at)
+ }
+}
+
+impl super::AgentsViewMode {
+ /// TS `setStatusMessage(message)`: the default tone rule, the
+ /// expiry armed.
+ pub(super) fn set_status(&mut self, text: &str) {
+ self.status = Some(Status::transient(text));
+ }
+
+ /// TS `setStatusMessage(message, { tone })`: the explicit tone, the
+ /// expiry armed.
+ pub(super) fn set_status_tone(&mut self, text: &str, tone: StatusTone) {
+ self.status = Some(Status::with_tone(text, tone));
+ }
+
+ /// The status line's text (the renderers' and tests' view of it).
+ pub(super) fn status_text(&self) -> Option<&str> {
+ self.status.as_ref().map(Status::text)
+ }
+
+ /// The armed expiry the loop wakes at (a sticky line arms none):
+ /// TS's timer cleared the line; here the deadline branch repaints it
+ /// away.
+ pub(super) fn status_expiry(&self, now: std::time::Instant) -> Option<std::time::Instant> {
+ self.status.as_ref().and_then(|status| status.expiry(now))
+ }
+
+ /// The timer's callback (TS clears the line only when nothing
+ /// replaced it — a replaced line carries its own new deadline):
+ /// clear the status once its window passed at `now`, and report
+ /// whether the frame must repaint.
+ pub(super) fn expire_status(&mut self, now: std::time::Instant) -> bool {
+ let expired = self
+ .status
+ .as_ref()
+ .is_some_and(|status| status.expiry(now).is_none() && !status.is_sticky());
+ if expired {
+ self.status = None;
+ }
+ expired
+ }
+
+ /// TS `clearStickyStatusMessage`: a sticky line clears on any
+ /// keypress (the transient timer never covered it).
+ pub(super) fn clear_sticky_status(&mut self) {
+ if self.status.as_ref().is_some_and(Status::is_sticky) {
+ self.status = None;
+ }
+ }
+}
diff --git a/crates/pa-tui/src/agents_view/tests.rs b/crates/pa-tui/src/agents_view/tests.rs
index d42719fe4d..7b7a586f0f 100644
--- a/crates/pa-tui/src/agents_view/tests.rs
+++ b/crates/pa-tui/src/agents_view/tests.rs
@@ -19,6 +19,7 @@ mod hover_band;
mod key_bindings;
mod notices;
mod render_pulse;
+mod reply;
mod running_lines;
mod saved_catalog;
mod selection_churn;
@@ -43,6 +44,7 @@ fn mode_with_row(title: &str, model: &str) -> (AgentsViewMode, usize) {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
let row = |title: &str| AgentsViewRow {
section: Section::Idle,
@@ -151,6 +153,7 @@ fn mode_with_parent_and_child() -> AgentsViewMode {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = vec![
roster_entry("p", "idle", &parent_summary("p")),
@@ -179,6 +182,7 @@ fn mode_with_anchor(anchor: Option<&str>, roster: Vec<serde_json::Value>) -> Age
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = roster;
mode.rebuild_rows();
@@ -209,6 +213,7 @@ fn mode_with_user_bindings(bindings: &[(&str, &str)]) -> AgentsViewMode {
keybindings: crate::keybindings::KeybindingsManager::with_user_bindings(cfg),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = vec![
roster_entry("p", "idle", &parent_summary("p")),
@@ -235,6 +240,7 @@ fn fresh_mode(roster: Vec<serde_json::Value>) -> AgentsViewMode {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = roster;
mode.rebuild_rows();
diff --git a/crates/pa-tui/src/agents_view/tests/delete_stop.rs b/crates/pa-tui/src/agents_view/tests/delete_stop.rs
index 8101c63e0d..a53193f17c 100644
--- a/crates/pa-tui/src/agents_view/tests/delete_stop.rs
+++ b/crates/pa-tui/src/agents_view/tests/delete_stop.rs
@@ -326,7 +326,8 @@ fn a_deleted_path_survives_a_late_catalog_apply() {
)];
mode.rebuild_rows();
mode.delete_result(
- "Deleted session a deleted session".to_string(),
+ "Deleted session a deleted session",
+ StatusTone::Muted,
Some("/x/gone.jsonl".to_string()),
);
assert!(mode.saved.is_empty());
@@ -422,7 +423,8 @@ fn a_deleted_saved_row_leaves_the_catalog_by_path() {
];
mode.rebuild_rows();
mode.delete_result(
- "Deleted session a deleted session".to_string(),
+ "Deleted session a deleted session",
+ StatusTone::Muted,
Some("/x/gone.jsonl".to_string()),
);
assert!(
@@ -441,7 +443,8 @@ fn a_deleted_saved_row_leaves_the_catalog_by_path() {
// The name-matching trap: a path that never appears in any
// display name still matches by its own key.
mode.delete_result(
- "Deleted session Some Other Name".to_string(),
+ "Deleted session Some Other Name",
+ StatusTone::Muted,
Some("/x/stays.jsonl".to_string()),
);
assert!(
diff --git a/crates/pa-tui/src/agents_view/tests/drill_down.rs b/crates/pa-tui/src/agents_view/tests/drill_down.rs
index e8eb85bf30..4a981a4084 100644
--- a/crates/pa-tui/src/agents_view/tests/drill_down.rs
+++ b/crates/pa-tui/src/agents_view/tests/drill_down.rs
@@ -58,6 +58,7 @@ fn pending_ancestors_expand_and_selection_restores_after_reentry() {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = vec![
roster_entry("p", "idle", &parent_summary("p")),
@@ -93,6 +94,7 @@ fn scoped_left_returns_the_root_and_pops_the_scope() {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = vec![
roster_entry("p", "idle", &parent_summary("p")),
diff --git a/crates/pa-tui/src/agents_view/tests/entry_anchor.rs b/crates/pa-tui/src/agents_view/tests/entry_anchor.rs
index 29ccbe048c..a644a897ff 100644
--- a/crates/pa-tui/src/agents_view/tests/entry_anchor.rs
+++ b/crates/pa-tui/src/agents_view/tests/entry_anchor.rs
@@ -48,23 +48,23 @@ fn open_waits_out_the_entry_anchor() {
assert!(mode.anchor_selection_pending);
mode.handle_key("enter");
assert!(mode.opened.is_none(), "the default row did not open");
- assert!(mode.status.is_some(), "the wait explains itself");
+ assert!(mode.status_text().is_some(), "the wait explains itself");
mode.roster
.push(roster_entry("s2", "idle", &parent_summary("s2")));
mode.rebuild_rows();
assert!(!mode.anchor_selection_pending);
assert!(
- mode.status.is_none(),
+ mode.status_text().is_none(),
"the anchor landing drops the loading hint"
);
// The user's first move ends the wait the same way: the hint it
// left behind clears too.
mode.anchor_selection_pending = true;
- mode.status = Some(ANCHOR_LOADING_HINT.to_string());
+ mode.set_status(ANCHOR_LOADING_HINT);
mode.handle_key("down");
assert!(!mode.anchor_selection_pending);
assert!(
- mode.status.is_none(),
+ mode.status_text().is_none(),
"the canceling move drops the loading hint as well"
);
mode.handle_key("enter");
@@ -134,15 +134,15 @@ fn a_click_cancels_the_anchor_wait_and_opens_the_clicked_row() {
!mode.anchor_selection_pending,
"the click ends the entry anchor's wait"
);
+ assert!(
+ mode.status_text().is_none(),
+ "the click drops the loading hint with the wait"
+ );
let opened = mode.opened.expect("the click opened the row");
assert_eq!(
opened.selection,
SessionSelection::Attach("s3-live".to_string())
);
- assert!(
- mode.status.is_none(),
- "the click drops the loading hint with the wait"
- );
crate::mouse_tracking::disable(&mut std::io::stdout()).expect("disable");
}
@@ -157,14 +157,14 @@ fn a_saved_catalog_failure_settles_the_anchor_wait() {
Some("s2"),
vec![roster_entry("s1", "idle", &parent_summary("s1"))],
);
- mode.status = Some(ANCHOR_LOADING_HINT.to_string());
+ mode.set_status(ANCHOR_LOADING_HINT);
mode.settle_anchor_wait_on_saved_failure();
assert!(
!mode.anchor_selection_pending,
"the wait ends with the failed catalog"
);
assert_ne!(
- mode.status.as_deref(),
+ mode.status_text(),
Some(ANCHOR_LOADING_HINT),
"the loading hint drops with the wait"
);
@@ -177,7 +177,7 @@ fn a_saved_catalog_failure_settles_the_anchor_wait() {
"the settled view opens the default row instead of re-arming the hint"
);
assert_ne!(
- mode.status.as_deref(),
+ mode.status_text(),
Some(ANCHOR_LOADING_HINT),
"no re-armed loading hint behind the failure"
);
@@ -247,31 +247,29 @@ fn a_noop_edit_on_an_empty_query_never_rearms() {
#[test]
fn a_successful_load_retires_the_failure_status() {
let mut mode = mode_with_anchor(None, Vec::new());
- mode.status = Some("Saved sessions unavailable: scan failed".to_string());
+ mode.set_status("Saved sessions unavailable: scan failed");
mode.saved_fetch_failed = true;
mode.saved = Vec::new();
// The load arm's own logic (the loop's SavedLoaded handler): the
// failure flag clears and the fetch's own status retires.
mode.saved_fetch_failed = false;
if mode
- .status
- .as_deref()
+ .status_text()
.is_some_and(|status| status.starts_with("Saved sessions unavailable"))
{
mode.status = None;
}
- assert_eq!(mode.status, None, "the stale failure status retired");
+ assert_eq!(mode.status_text(), None, "the stale failure status retired");
// An unrelated status (the flow's own notice) survives a load.
- mode.status = Some("Session s1 is no longer running".to_string());
+ mode.set_status("Session s1 is no longer running");
if mode
- .status
- .as_deref()
+ .status_text()
.is_some_and(|status| status.starts_with("Saved sessions unavailable"))
{
mode.status = None;
}
assert_eq!(
- mode.status.as_deref(),
+ mode.status_text(),
Some("Session s1 is no longer running"),
"an unrelated status is never clobbered by the load"
);
@@ -337,6 +335,7 @@ fn carried_selection_wins_over_the_entry_anchor() {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = vec![
roster_entry("s1", "idle", &parent_summary("s1")),
diff --git a/crates/pa-tui/src/agents_view/tests/hints_render.rs b/crates/pa-tui/src/agents_view/tests/hints_render.rs
index f4890f05aa..9994022ba7 100644
--- a/crates/pa-tui/src/agents_view/tests/hints_render.rs
+++ b/crates/pa-tui/src/agents_view/tests/hints_render.rs
@@ -11,14 +11,14 @@ fn hints_render_the_effective_bindings() {
let mode = mode_with_parent_and_child();
assert_eq!(
flat(&mode.render_hints(120, None)),
- "\u{2191}/\u{2193} navigate Home/End first/last Enter/\u{2192} open Ctrl+R rename Ctrl+X stop Ctrl+N new"
+ "\u{2191}/\u{2193} navigate Home/End first/last Enter/\u{2192} open Ctrl+R rename Space reply Ctrl+X stop Ctrl+N new"
);
// A user override moves the hint with the handler.
let mode = mode_with_user_bindings(&[("app.agents.new", "ctrl+t")]);
let hints = flat(&mode.render_hints(120, None));
assert_eq!(
hints,
- "\u{2191}/\u{2193} navigate Home/End first/last Enter/\u{2192} open Ctrl+R rename Ctrl+X stop Ctrl+T new"
+ "\u{2191}/\u{2193} navigate Home/End first/last Enter/\u{2192} open Ctrl+R rename Space reply Ctrl+X stop Ctrl+T new"
);
assert!(!hints.contains("Ctrl+N"), "the default new hint is gone");
// An override on the delete binding moves its slot too.
diff --git a/crates/pa-tui/src/agents_view/tests/key_bindings.rs b/crates/pa-tui/src/agents_view/tests/key_bindings.rs
index 88edb884bc..10c9595aa0 100644
--- a/crates/pa-tui/src/agents_view/tests/key_bindings.rs
+++ b/crates/pa-tui/src/agents_view/tests/key_bindings.rs
@@ -122,7 +122,7 @@ fn program_key_shows_and_hides_the_spawn_program() {
mode.selected = 0;
mode.handle_key("ctrl+o");
assert_eq!(
- mode.status.as_deref(),
+ mode.status_text(),
Some("No program recorded for these subagents")
);
}
@@ -131,8 +131,9 @@ fn program_key_shows_and_hides_the_spawn_program() {
/// default ctrl+r): the composer owns the prompt and the key routing —
/// the header and the save/cancel hint render, the prefill is the
/// session's name, the editing grammar matches the search field, Enter
-/// submits the trimmed name with the live target, Esc exits with the
-/// query untouched, and a child row never enters.
+/// submits the trimmed name with the live target, a large paste saves
+/// expanded, Esc exits with the query untouched, and a child row never
+/// enters.
#[test]
fn rename_key_composes_edits_and_dispatches() {
let mut mode = mode_with_parent_and_child();
@@ -140,26 +141,45 @@ fn rename_key_composes_edits_and_dispatches() {
let Composer::Rename(rename) = &mode.composer else {
panic!("the composer entered rename mode");
};
- assert_eq!(rename.name, "p name", "the prefill is the session name");
- // The rendered frame: the header; the hint: save/cancel.
+ assert_eq!(
+ rename.editor.get_text(),
+ "p name",
+ "the prefill is the session name"
+ );
+ // The rendered frame: the real editor box (TS SF1 closes: the
+ // warning header rides INSIDE the box, top and bottom bg rows
+ // included); the hint: save/cancel.
let (frame, _) = mode.render_frame(120, 20);
let rendered: Vec<String> = frame.iter().map(flat).collect();
+ let header_row = rendered
+ .iter()
+ .position(|row| row.starts_with(" Rename agent session"))
+ .expect("the rename header rendered with TS's two-space indent");
assert!(
- rendered
- .iter()
- .any(|row| row.starts_with(" Rename agent session")),
- "the rename header rendered with TS's two-space indent:
-{}",
+ rendered[header_row - 1].trim().is_empty(),
+ "the box's top bg row rides above the header"
+ );
+ assert!(
+ rendered.iter().any(|row| row.contains("p name")),
+ "the prefilled draft renders in the box:\n{}",
rendered.join("\n")
);
assert_eq!(
flat(&mode.render_hints(120, None)),
"Enter save Esc/Ctrl+C cancel"
);
- // The editing grammar (the search field's): ctrl+u clears, the typed
- // characters land, Enter submits the trimmed name with the live
- // target.
+ // The editing grammar (the editor's own, TS's `editor.handleInput`):
+ // ctrl+u clears to the dim placeholder, the typed characters land,
+ // Enter submits the trimmed name with the live target.
mode.handle_key("ctrl+u");
+ let (frame, _) = mode.render_frame(120, 20);
+ assert!(
+ frame
+ .iter()
+ .map(flat)
+ .any(|row| row.contains("Name this agent session")),
+ "the cleared editor shows the placeholder"
+ );
mode.handle_key("n");
mode.handle_key("e");
mode.handle_key("w");
@@ -175,23 +195,33 @@ fn rename_key_composes_edits_and_dispatches() {
}),
"the confirmed rename dispatches"
);
- assert_eq!(mode.status.as_deref(), Some("Renaming agent..."));
+ assert_eq!(mode.status_text(), Some("Renaming agent..."));
// The landed outcome reports TS's row (the dispatched request itself).
mode.rename_result(rename.expect("the dispatched rename"), Ok(()));
- assert_eq!(mode.status.as_deref(), Some("Renamed to new"));
+ assert_eq!(mode.status_text(), Some("Renamed to new"));
// Esc exits back to search; the query stays untouched. Ctrl+C
// cancels too (TS :1120 — the default cancel binding includes it;
// the force-quit guard's handled note rides the routing).
mode.handle_key("ctrl+r");
mode.handle_key("escape");
- assert_eq!(mode.composer, Composer::Search);
+ assert!(matches!(mode.composer, Composer::Search));
mode.handle_key("ctrl+r");
mode.handle_key("ctrl+c");
- assert_eq!(
- mode.composer,
- Composer::Search,
+ assert!(
+ matches!(mode.composer, Composer::Search),
"ctrl+c cancels rename mode (TS :1120)"
);
+ // A large paste shows as a marker; the save expands it (TS
+ // `submitValue`).
+ mode.handle_key("ctrl+r");
+ mode.handle_key("ctrl+u");
+ let pasted = "x".repeat(1200);
+ mode.handle_paste(&pasted);
+ mode.handle_key("enter");
+ assert_eq!(
+ mode.pending_rename.take().map(|rename| rename.name),
+ Some(pasted)
+ );
// A subagent row never enters rename mode (TS :1871: only
// top-level agents rename). Expand the list so the child row is
// the selection's landing.
@@ -200,7 +230,7 @@ fn rename_key_composes_edits_and_dispatches() {
mode.handle_key("down");
assert_eq!(mode.rows[mode.selected].kind, RowKind::Subagent);
mode.handle_key("ctrl+r");
- assert_eq!(mode.composer, Composer::Search);
+ assert!(matches!(mode.composer, Composer::Search));
}
#[test]
diff --git a/crates/pa-tui/src/agents_view/tests/notices.rs b/crates/pa-tui/src/agents_view/tests/notices.rs
index 8832bb9711..55fcfc7d89 100644
--- a/crates/pa-tui/src/agents_view/tests/notices.rs
+++ b/crates/pa-tui/src/agents_view/tests/notices.rs
@@ -21,6 +21,7 @@ fn mode_with_notice(notice: &str) -> AgentsViewMode {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.rebuild_rows();
mode
@@ -80,7 +81,87 @@ fn a_single_line_notice_keeps_the_status_line() {
let mode = mode_with_notice("Saved sessions unavailable: no such directory");
assert!(mode.notice.is_none());
assert_eq!(
- mode.status.as_deref(),
+ mode.status_text(),
Some("Saved sessions unavailable: no such directory")
);
}
+
+/// TS `setStatusMessage`'s tone rule: the explicit tone wins, the
+/// `Failed` prefix reads error, everything else reads muted — and the
+/// rendered hint row carries the tone's color (the #3117 SF6
+/// divergence: every status used to render as an error).
+#[test]
+fn the_status_line_carries_its_tone() {
+ let mut mode = mode_with_parent_and_child();
+ mode.set_status("Renamed to new");
+ assert_eq!(
+ mode.status.as_ref().map(Status::tone),
+ Some(StatusTone::Muted)
+ );
+ // The Failed prefix is an error without an explicit tone.
+ mode.set_status("Failed to rename agent: nope");
+ assert_eq!(
+ mode.status.as_ref().map(Status::tone),
+ Some(StatusTone::Error)
+ );
+ // An explicit tone wins over the prefix rule, and the text
+ // collapses to one line (TS `formatAgentsViewStatusLine`).
+ mode.set_status_tone("Saved sessions\n unavailable", StatusTone::Error);
+ assert_eq!(mode.status_text(), Some("Saved sessions unavailable"));
+ assert_eq!(
+ mode.status.as_ref().map(Status::tone),
+ Some(StatusTone::Error)
+ );
+ // The rendered row paints in the tone's color, not the fixed
+ // error color: a muted report renders muted.
+ mode.set_status("Renaming agent...");
+ let span = mode
+ .render_hints(120, None)
+ .last()
+ .expect("the status span")
+ .clone();
+ assert_eq!(span.content, "Renaming agent...");
+ assert_eq!(span.style, mode.theme.fg_style(StatusTone::Muted.color()));
+ // An explicit error renders error.
+ mode.set_status_tone("Saved sessions unavailable: gone", StatusTone::Error);
+ let span = mode
+ .render_hints(120, None)
+ .last()
+ .expect("the status span")
+ .clone();
+ assert_eq!(span.style, mode.theme.fg_style(StatusTone::Error.color()));
+}
+
+/// TS's 4.5s status timer, through the accessors the loop drives: the
+/// line arms its expiry, holds before the deadline, clears after it —
+/// and a line that REPLACED an expired one keeps its own new window
+/// (TS's unchanged-line guard).
+#[test]
+fn the_status_expires_through_the_loop_deadline() {
+ let mut mode = mode_with_parent_and_child();
+ mode.set_status("Reply sent");
+ let now = std::time::Instant::now();
+ assert!(
+ mode.status_expiry(now).is_some(),
+ "a fresh line arms its timer"
+ );
+ assert!(
+ !mode.expire_status(now),
+ "before the deadline the line holds"
+ );
+ assert_eq!(mode.status_text(), Some("Reply sent"));
+ // The deadline passed (the loop's wake arm fires at the expiry):
+ // the line clears and repaints.
+ let after = now + std::time::Duration::from_millis(4500);
+ assert!(mode.status_expiry(after).is_none(), "the deadline passed");
+ assert!(mode.expire_status(after), "the expired line clears");
+ assert_eq!(mode.status_text(), None, "the cleared line renders nothing");
+ // The unchanged-line guard: a replacement line's own deadline is
+ // fresh again at the expired line's wake.
+ mode.set_status("Reply sent again");
+ assert!(
+ !mode.expire_status(after),
+ "the replacement keeps its own new window"
+ );
+ assert_eq!(mode.status_text(), Some("Reply sent again"));
+}
diff --git a/crates/pa-tui/src/agents_view/tests/reply.rs b/crates/pa-tui/src/agents_view/tests/reply.rs
new file mode 100644
index 0000000000..d1080ca441
--- /dev/null
+++ b/crates/pa-tui/src/agents_view/tests/reply.rs
@@ -0,0 +1,540 @@
+//! The reply composer family (TS `toggleReplyTarget`/`sendReply`/the
+//! armed key routing): the arm and its headline, the guards, the submit
+//! paths, the view commands, and the hint rows.
+
+use super::*;
+use crate::agents_view::rename::{Rename, RenameTarget};
+use crate::agents_view::reply::{KillRequest, ReplyRequest, ReplySent};
+use pa_types::daemon::StreamingBehavior;
+
+/// One armed composer over the fixture's live parent row.
+fn armed_live() -> AgentsViewMode {
+ let mut mode = mode_with_parent_and_child();
+ mode.handle_key("space");
+ assert!(
+ matches!(&mode.composer, Composer::Reply(_)),
+ "the composer armed on the live row"
+ );
+ mode
+}
+
+/// One armed composer over a saved fixture row (the resume target).
+fn armed_saved() -> AgentsViewMode {
+ let mut mode = mode_with_anchor(None, Vec::new());
+ mode.saved = vec![saved_catalog_row(
+ "/x/saved.jsonl",
+ "saved-1",
+ "a saved session",
+ )];
+ mode.rebuild_rows();
+ mode.selected = mode
+ .rows
+ .iter()
+ .position(|row| row.identity.contains("saved.jsonl"))
+ .expect("the saved row");
+ mode.handle_key("space");
+ assert!(
+ matches!(&mode.composer, Composer::Reply(_)),
+ "the composer armed on the saved row"
+ );
+ mode
+}
+
+/// The flat text of one rendered frame.
+fn frame_text(mode: &mut AgentsViewMode) -> String {
+ let (frame, _) = mode.render_frame(120, 24);
+ frame.iter().map(flat).collect::<Vec<_>>().join("\n")
+}
+
+/// The arm: space on the live parent arms the composer, fires the
+/// headline fetch, and renders the loading header; the landed headline
+/// renders its first line (TS `createAgentsViewReplyHeadline`).
+#[test]
+fn space_arms_the_live_reply_and_fetches_the_headline() {
+ let mut mode = armed_live();
+ assert_eq!(
+ mode.pending_headline,
+ Some(("p-live".to_string(), "p-live".to_string())),
+ "the headline fetch targets the live session"
+ );
+ assert!(
+ frame_text(&mut mode).contains("Loading last response..."),
+ "the live header shows the loading line"
+ );
+ // The landed headline renders its first line; a re-targeted or
+ // disarmed composer drops a late result (the key guard).
+ mode.headline_result("p-live", Ok(Some("line one\nline two".to_string())));
+ let frame = frame_text(&mut mode);
+ assert!(
+ frame.contains("line one") && !frame.contains("line two"),
+ "the header renders the first collapsed line only:\n{frame}"
+ );
+ // A result for another key drops.
+ mode.headline_result("other", Ok(Some("nope".to_string())));
+ assert!(frame_text(&mut mode).contains("line one"));
+}
+
+/// The saved arm starts from the recap: no fetch, the placeholder names
+/// the resume, and the header's time is the row's relative age.
+#[test]
+fn space_arms_the_saved_reply_from_the_recap() {
+ let mut mode = armed_saved();
+ assert_eq!(mode.pending_headline, None, "the saved arm fetches nothing");
+ let frame = frame_text(&mut mode);
+ assert!(
+ frame.contains("Write a prompt to resume this session"),
+ "the saved placeholder:\n{frame}"
+ );
+ assert!(
+ frame.contains("a saved session"),
+ "the saved recap rides the header (the firstMessage):\n{frame}"
+ );
+}
+
+/// The keys while armed (TS `handleInput`'s gates over the editor):
+/// down goes to the editor (the selection never moves), ctrl+n is
+/// inert, the cancel keys disarm without touching the query, and the
+/// exit hint never arms from the composer's cancel.
+#[test]
+fn armed_keys_route_to_the_editor_and_the_cancels_disarm() {
+ let mut mode = armed_live();
+ let selected = mode.selected;
+ mode.handle_key("down");
+ assert_eq!(mode.selected, selected, "down never moves the selection");
+ assert!(matches!(&mode.composer, Composer::Reply(_)));
+ // ctrl+n (the new-session action) is disabled while armed.
+ mode.handle_key("ctrl+n");
+ assert!(matches!(&mode.composer, Composer::Reply(_)));
+ assert!(!mode.new_session);
+ // Esc disarms; the query stays untouched (the composer never owned
+ // it).
+ mode.handle_key("escape");
+ assert!(matches!(mode.composer, Composer::Search));
+ // Re-arm; left disarms (TS: onAgentsBack runs before the editor's
+ // cursor motions, so Left never moves the cursor while armed).
+ mode.handle_key("space");
+ mode.handle_key("left");
+ assert!(matches!(mode.composer, Composer::Search));
+ // Re-arm; ctrl+c disarms without arming the exit hint, and the
+ // force-quit guard saw the handled press.
+ mode.handle_key("space");
+ mode.handle_key("ctrl+c");
+ assert!(matches!(mode.composer, Composer::Search));
+ assert!(
+ !mode.exit_armed,
+ "the composer's cancel never arms the exit"
+ );
+}
+
+/// A selection move off the targeted row disarms (TS `moveSelection`'s
+/// guard, :1487-1493). The guard rides the move itself, not the key:
+/// while armed the composer owns the navigation keys (they edit the
+/// draft, exactly like TS's gated list navigation), so the drive calls
+/// the production move directly — the shape a future move path takes.
+#[test]
+fn a_selection_move_off_the_target_disarms() {
+ let mut mode = armed_live();
+ mode.move_selection(1);
+ assert!(
+ matches!(mode.composer, Composer::Search),
+ "the move disarms the reply"
+ );
+ // The move back onto the row does not re-arm (the arm is the space
+ // key's act, never a selection side effect).
+ mode.move_selection(-1);
+ assert!(matches!(mode.composer, Composer::Search));
+}
+
+/// The submit: Enter on a typed draft dispatches the whole-object
+/// request; alt+enter queues the follow-up; a streaming target steers;
+/// the failure restores the draft, the success disarms and reports.
+#[test]
+fn enter_submits_the_reply_and_the_outcomes_land() {
+ let mut mode = armed_live();
+ // A trailing backslash + Enter is the editor's newline (TS's
+ // shift+enter workaround), not a send; the plain Enter sends.
+ for key in ["f", "o", "o", "\\", "enter", "b", "a", "r", "enter"] {
+ mode.handle_key(key);
+ }
+ let request = mode.pending_reply.take().expect("the send dispatched");
+ assert_eq!(
+ request,
+ ReplyRequest {
+ key: "p-live".to_string(),
+ summary: parent_summary("p"),
+ text: "foo\nbar".to_string(),
+ behavior: None,
+ resume_config: serde_json::json!({}),
+ cwd_notice: None,
+ },
+ "the live send dispatches against the current summary"
+ );
+ // The failure restores the draft and reports; a re-armed composer on
+ // the same key keeps its fresh compose (the in-flight guard).
+ mode.reply_result("p-live", Err("daemon down".to_string()));
+ assert_eq!(
+ mode.status_text(),
+ Some("Failed to send reply: daemon down")
+ );
+ assert!(
+ matches!(&mode.composer, Composer::Reply(reply) if reply.editor.get_text() == "foo\nbar"),
+ "the failure restores the draft"
+ );
+ // The success disarms (the empty-editor guard) and reports; the
+ // adoption action rides the outcome.
+ mode.handle_key("enter");
+ assert!(
+ mode.pending_reply.take().is_some(),
+ "the re-armed draft resubmits"
+ );
+ mode.reply_result(
+ "p-live",
+ Ok(ReplySent {
+ resumed: None,
+ cwd_notice: None,
+ }),
+ );
+ assert_eq!(mode.status_text(), Some("Reply sent"));
+ assert!(
+ matches!(mode.composer, Composer::Search),
+ "the success disarms"
+ );
+ assert_eq!(mode.actions.last(), Some(&"reply_sent"));
+}
+
+/// The follow-up key and the streaming behavior (TS `sendReply`'s
+/// ladder): alt+enter queues, a streaming target steers, and the saved
+/// path resolves the resume config with its missing-directory notice.
+#[test]
+fn the_follow_up_queues_and_streaming_steers() {
+ let mut mode = armed_live();
+ // TS `handleReplyFollowUp`: the blank draft is a no-op — nothing
+ // dispatches and the composer stays armed.
+ mode.handle_key("alt+enter");
+ assert!(mode.pending_reply.is_none());
+ assert!(matches!(&mode.composer, Composer::Reply(_)));
+ for ch in "hello".chars() {
+ mode.handle_key(ch.to_string().as_str());
+ }
+ mode.handle_key("alt+enter");
+ assert_eq!(
+ mode.pending_reply
+ .take()
+ .expect("the follow-up dispatched")
+ .behavior,
+ Some(StreamingBehavior::FollowUp)
+ );
+ // The live target streams: the plain Enter steers.
+ let mut streaming = mode_with_parent_and_child();
+ streaming.roster[0]["summary"]["isStreaming"] = serde_json::json!(true);
+ streaming.rebuild_rows();
+ streaming.handle_key("space");
+ for ch in "hi".chars() {
+ streaming.handle_key(ch.to_string().as_str());
+ }
+ streaming.handle_key("enter");
+ assert_eq!(
+ streaming.pending_reply.take().expect("the send").behavior,
+ Some(StreamingBehavior::Steer)
+ );
+ // The saved target resumes: the config drops the cwd, or overrides
+ // it with the notice when the saved directory is gone (the catalog
+ // row's cwd points at a path that does not exist — the submit
+ // resolves the CURRENT summary from the records).
+ let mut saved = mode_with_anchor(None, Vec::new());
+ let mut row = saved_catalog_row("/x/saved.jsonl", "saved-1", "a saved session");
+ row["cwd"] = serde_json::json!("/nonexistent-reply-e2e");
+ saved.saved = vec![row];
+ saved.rebuild_rows();
+ saved.selected = saved
+ .rows
+ .iter()
+ .position(|row| row.identity.contains("saved.jsonl"))
+ .expect("the saved row");
+ saved.handle_key("space");
+ for ch in "resume me".chars() {
+ saved.handle_key(ch.to_string().as_str());
+ }
+ saved.handle_key("enter");
+ let request = saved.pending_reply.take().expect("the resume send");
+ assert!(
+ request.cwd_notice.is_some(),
+ "the missing cwd carries its notice"
+ );
+ assert!(
+ request.resume_config.get("cwd").is_some(),
+ "the override replaces the removed cwd"
+ );
+ assert_eq!(request.behavior, None, "a fresh resume never steers");
+}
+
+/// The view commands and the rejection (TS `parseAgentsViewCommand` +
+/// `getReplyComposerCommandRejection`): `/name` reuses the rename flow,
+/// `/kill` refuses an inactive target, and a client builtin never goes
+/// to the model as prompt text.
+#[test]
+fn view_commands_route_and_reject() {
+ let mut mode = armed_live();
+ for ch in "/tree".chars() {
+ mode.handle_key(ch.to_string().as_str());
+ }
+ mode.handle_key("enter");
+ assert_eq!(
+ mode.status_text(),
+ Some("/tree is not available here; open the session to run it")
+ );
+ assert!(
+ matches!(&mode.composer, Composer::Reply(reply) if reply.editor.get_text() == "/tree"),
+ "the rejected command keeps its draft"
+ );
+ // /name with no args: the usage warning, the draft stays (the
+ // restored old draft clears first — the editor kept the rejected
+ // command, TS's restore).
+ mode.handle_key("ctrl+u");
+ for ch in "/name".chars() {
+ mode.handle_key(ch.to_string().as_str());
+ }
+ mode.handle_key("enter");
+ assert_eq!(mode.status_text(), Some("Usage: /name <session name>"));
+ assert!(
+ mode.pending_rename.is_none(),
+ "the usage warning dispatches nothing"
+ );
+ // /name with args dispatches the rename against the live target.
+ mode.handle_key(" ");
+ for ch in "new".chars() {
+ mode.handle_key(ch.to_string().as_str());
+ }
+ mode.handle_key("enter");
+ assert_eq!(
+ mode.pending_rename,
+ Some(Rename {
+ target: RenameTarget::Live {
+ active_session_id: "p-live".to_string()
+ },
+ name: "new".to_string(),
+ }),
+ "the /name dispatch reuses the rename flow"
+ );
+ // /kill on the saved row: the inactive warning.
+ let mut saved = armed_saved();
+ for ch in "/kill".chars() {
+ saved.handle_key(ch.to_string().as_str());
+ }
+ saved.handle_key("enter");
+ assert_eq!(
+ saved.status_text(),
+ Some("/kill needs a running agent; this session is inactive")
+ );
+ // The run loop materializes the completion between keys: Enter on
+ // the typed-exact `/kill` falls through the open popup and submits.
+ let mut live = armed_live();
+ for ch in "/kill".chars() {
+ live.handle_key(ch.to_string().as_str());
+ live.materialize_composer_autocomplete();
+ }
+ assert!(
+ matches!(&live.composer, Composer::Reply(reply) if reply.editor.is_showing_autocomplete())
+ );
+ live.handle_key("enter");
+ assert_eq!(
+ live.pending_kill,
+ Some(KillRequest {
+ key: "p-live".to_string(),
+ active_session_id: "p-live".to_string(),
+ })
+ );
+ live.kill_result("p-live", Ok(()));
+ assert!(
+ matches!(live.composer, Composer::Search),
+ "the stopped target disarms"
+ );
+ assert_eq!(live.status_text(), Some("Agent stopped"));
+ assert_eq!(live.actions.last(), Some(&"killed"));
+}
+
+/// The hint rows (TS `renderReplyComposerHints`): the confirm word by
+/// the target's state, the queue hint while the draft has text, and
+/// cancel over the whole cancel binding.
+#[test]
+fn the_reply_hints_follow_the_target_state() {
+ let mode = armed_live();
+ assert_eq!(
+ flat(&mode.render_hints(120, None)),
+ "Enter send Esc/Ctrl+C cancel",
+ "the live idle hint"
+ );
+ let mut streaming = mode_with_parent_and_child();
+ streaming.roster[0]["summary"]["isStreaming"] = serde_json::json!(true);
+ streaming.rebuild_rows();
+ streaming.handle_key("space");
+ assert_eq!(
+ flat(&streaming.render_hints(120, None)),
+ "Enter steer Esc/Ctrl+C cancel"
+ );
+ let mut with_text = armed_live();
+ with_text.handle_key("h");
+ assert_eq!(
+ flat(&with_text.render_hints(120, None)),
+ "Enter send Alt+Enter queue Esc/Ctrl+C cancel"
+ );
+ let saved = armed_saved();
+ assert_eq!(
+ flat(&saved.render_hints(120, None)),
+ "Enter resume & send Esc/Ctrl+C cancel"
+ );
+}
+
+/// The reply autocomplete (TS `createReplyComposerAutocompleteProvider`):
+/// only the armed composer completes — the session-owned builtins plus
+/// the view commands, never the client builtins (the rejection family).
+#[test]
+fn the_reply_completion_lists_session_and_view_commands() {
+ let mut mode = armed_live();
+ mode.handle_key("/");
+ mode.materialize_composer_autocomplete();
+ let Composer::Reply(reply) = &mode.composer else {
+ panic!("armed");
+ };
+ let labels: Vec<String> = reply
+ .editor
+ .autocomplete_state()
+ .map(|state| state.items.iter().map(|item| item.label.clone()).collect())
+ .unwrap_or_default();
+ assert!(
+ labels.iter().any(|label| label.contains("compact")),
+ "the session commands suggest: {labels:?}"
+ );
+ for expected in ["kill", "name"] {
+ assert!(
+ labels.iter().any(|label| label.contains(expected)),
+ "the view commands suggest: {labels:?}"
+ );
+ }
+ assert!(
+ !labels
+ .iter()
+ .any(|label| label.contains("tree") || label.contains("model")),
+ "the client builtins never suggest: {labels:?}"
+ );
+}
+
+/// An open completion owns Enter (TS's editor applies the selected
+/// item; the typed-exact fall-through is what submits): typing `/`
+/// completes into the buffer instead of submitting the partial.
+#[test]
+fn an_open_completion_owns_enter() {
+ let mut mode = armed_live();
+ mode.handle_key("/");
+ mode.materialize_composer_autocomplete();
+ assert!(
+ matches!(&mode.composer, Composer::Reply(reply)
+ if reply.editor.is_showing_autocomplete()),
+ "the typed slash opens the completion"
+ );
+ mode.handle_key("enter");
+ let Composer::Reply(reply) = &mode.composer else {
+ panic!("the composer stays armed");
+ };
+ assert!(
+ reply.editor.get_text().starts_with('/'),
+ "Enter applied the completion instead of submitting:\n{:?}",
+ reply.editor.get_text()
+ );
+ assert!(
+ mode.pending_reply.is_none() && mode.pending_kill.is_none(),
+ "nothing dispatched behind the popup"
+ );
+}
+
+/// A persisted target that left the live catalog resumes as saved: the
+/// stale runtime id leaves the summary (TS drops it with the archived
+/// lifecycle), so the steer gate and the resuming status read it as
+/// saved even when the captured summary still says streaming.
+#[test]
+fn a_target_gone_from_the_catalog_submits_as_a_resume() {
+ let mut mode = mode_with_parent_and_child();
+ mode.roster[0]["summary"]["isStreaming"] = serde_json::json!(true);
+ mode.rebuild_rows();
+ mode.handle_key("space");
+ assert!(matches!(&mode.composer, Composer::Reply(_)));
+ mode.roster = Vec::new();
+ mode.rebuild_rows();
+ for ch in "hi".chars() {
+ mode.handle_key(ch.to_string().as_str());
+ }
+ mode.handle_key("enter");
+ let request = mode.pending_reply.take().expect("the send dispatched");
+ assert_eq!(request.behavior, None, "an archived target never steers");
+ assert!(
+ request.summary.get("activeSessionId").is_none(),
+ "the stale runtime id left the summary"
+ );
+ assert_eq!(mode.status_text(), Some("Resuming session..."));
+}
+
+/// A paste never opens the completion (TS `handlePaste` cancels
+/// autocomplete and inserts without a new request, editor.ts:1301);
+/// the menu waits for the next keystroke.
+#[test]
+fn a_pasted_slash_never_opens_the_completion() {
+ let mut mode = armed_live();
+ mode.handle_paste("/");
+ mode.materialize_composer_autocomplete();
+ let Composer::Reply(reply) = &mode.composer else {
+ panic!("armed");
+ };
+ assert!(
+ reply.editor.autocomplete_state().is_none(),
+ "the paste leaves the completion closed"
+ );
+}
+
+/// The open completion renders its panel above the box (the chat's
+/// stacking; TS shows the same dropdown through the editor's TUI
+/// overlay).
+#[test]
+fn the_open_completion_renders_the_overlay_panel() {
+ let mut mode = armed_live();
+ mode.handle_key("/");
+ mode.materialize_composer_autocomplete();
+ let frame = frame_text(&mut mode);
+ assert!(
+ frame.contains("compact"),
+ "the completion panel renders above the box:\n{frame}"
+ );
+}
+
+/// A click that moves the selection runs the keyboard rule (TS
+/// `moveSelection`'s reply guard): a toggle-click on a nested row stays
+/// in the view, and the composer never stays armed against a row the
+/// highlight left.
+#[test]
+fn a_click_off_the_target_disarms_like_a_key_move() {
+ let _guard = match crate::mouse_tracking::STATE_TEST_LOCK.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ crate::mouse_tracking::enable(&mut std::io::stdout()).expect("enable");
+ let mut mode = armed_live();
+ mode.render_frame(120, 24);
+ let clicked = mode
+ .rows
+ .iter()
+ .position(|row| row.kind != RowKind::Agent)
+ .expect("a nested row renders");
+ let (row, _) = mode
+ .click_rows
+ .iter()
+ .find(|(_, index)| *index == clicked)
+ .copied()
+ .expect("the nested row is on screen");
+ mode.handle_mouse(&mouse_report(row, true, false));
+ mode.handle_mouse(&mouse_report(row, false, false));
+ assert_eq!(mode.selected, clicked, "the click selected the nested row");
+ assert!(
+ matches!(mode.composer, Composer::Search),
+ "the click off the target disarms the composer"
+ );
+ crate::mouse_tracking::disable(&mut std::io::stdout()).expect("disable");
+}
diff --git a/crates/pa-tui/src/agents_view/tests/running_lines.rs b/crates/pa-tui/src/agents_view/tests/running_lines.rs
index a3e1af0bc8..0043a3267c 100644
--- a/crates/pa-tui/src/agents_view/tests/running_lines.rs
+++ b/crates/pa-tui/src/agents_view/tests/running_lines.rs
@@ -28,6 +28,7 @@ fn scoped_view_keeps_the_first_row_default() {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = vec![
roster_entry("p", "idle", &parent_summary("p")),
@@ -73,6 +74,7 @@ fn childless_scope() -> AgentsViewMode {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = vec![roster_entry("p", "idle", &parent_summary("p"))];
mode.rebuild_rows();
@@ -187,6 +189,7 @@ fn mode_with_mixed_children() -> AgentsViewMode {
keybindings: crate::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
});
mode.roster = vec![
roster_entry("p", "idle", &parent_summary("p")),
diff --git a/crates/pa-tui/src/agents_view/tests/saved_catalog.rs b/crates/pa-tui/src/agents_view/tests/saved_catalog.rs
index acb4986df4..f2816992f2 100644
--- a/crates/pa-tui/src/agents_view/tests/saved_catalog.rs
+++ b/crates/pa-tui/src/agents_view/tests/saved_catalog.rs
@@ -28,7 +28,7 @@ fn streamed_catalog_rows_land_progressively_and_settle_the_anchor() {
mode.opened.is_some(),
"the anchor opens without waiting for the scan's end"
);
- assert_ne!(mode.status.as_deref(), Some(ANCHOR_LOADING_HINT));
+ assert_ne!(mode.status_text(), Some(ANCHOR_LOADING_HINT));
}
/// The streamed upsert never duplicates: a row re-streamed by a
diff --git a/crates/pa-tui/src/autocomplete.rs b/crates/pa-tui/src/autocomplete.rs
index ae7f3dd3ea..5e98d78de9 100644
--- a/crates/pa-tui/src/autocomplete.rs
+++ b/crates/pa-tui/src/autocomplete.rs
@@ -785,10 +785,11 @@ pub struct CombinedAutocompleteProvider {
}
impl CombinedAutocompleteProvider {
- /// Build the provider from the shared builtin registry (pa-types).
+ /// The shared builtin registry's completion entries (pa-types): every
+ /// command, its aliases, and its argument hints.
#[must_use]
- pub fn from_registry(base: std::path::PathBuf) -> Self {
- let commands = SlashCommandRegistry::builtin()
+ pub fn builtin_entries() -> Vec<SlashCommandEntry> {
+ SlashCommandRegistry::builtin()
.all()
.iter()
.map(|command| SlashCommandEntry {
@@ -799,7 +800,20 @@ impl CombinedAutocompleteProvider {
takes_argument: command.takes_argument,
source_tag: None,
})
- .collect();
+ .collect()
+ }
+
+ /// Build the provider from the shared builtin registry (pa-types).
+ #[must_use]
+ pub fn from_registry(base: std::path::PathBuf) -> Self {
+ Self::new(Self::builtin_entries(), base)
+ }
+
+ /// Build the provider from an explicit command list (TS
+ /// `new CombinedAutocompleteProvider(commands, cwd)`): the reply
+ /// composer's session-owned subset plus its view commands.
+ #[must_use]
+ pub fn new(commands: Vec<SlashCommandEntry>, base: std::path::PathBuf) -> Self {
Self {
commands,
skill_commands: Vec::new(),
diff --git a/crates/pa-tui/src/config_selector.rs b/crates/pa-tui/src/config_selector.rs
index 062f52a861..e4243741a3 100644
--- a/crates/pa-tui/src/config_selector.rs
+++ b/crates/pa-tui/src/config_selector.rs
@@ -213,7 +213,7 @@ impl ConfigSelector {
if kb.matches(key, "app.clear") {
return Some(SelectorAction::Exit);
}
- if key == " " || kb.matches(key, "tui.select.confirm") {
+ if key == "space" || kb.matches(key, "tui.select.confirm") {
return self.toggle_selected();
}
if key == "backspace" {
@@ -703,7 +703,7 @@ mod tests {
);
let mut selector = ConfigSelector::new(rows());
assert_eq!(
- selector.handle_key(" ", &kb()),
+ selector.handle_key("space", &kb()),
Some(SelectorAction::Toggle {
key: "kernel".to_string(),
enabled: false
diff --git a/crates/pa-tui/src/editor/mod.rs b/crates/pa-tui/src/editor/mod.rs
index 3ff2b3171a..854c8fa6be 100644
--- a/crates/pa-tui/src/editor/mod.rs
+++ b/crates/pa-tui/src/editor/mod.rs
@@ -32,6 +32,7 @@ mod text_utils;
mod wrap;
pub use kill_ring::KillRing;
+pub(crate) use text_utils::decode_printable;
pub use text_utils::normalize_text;
pub use wrap::{is_atomic_marker, word_wrap_line, LayoutLine, Segment, TextChunk, VisualLine};
@@ -227,6 +228,14 @@ impl Editor {
self.autocomplete_provider = Some(provider);
}
+ /// Drop the installed autocomplete provider (TS `setAutocompleteProvider(undefined)`):
+ /// an editor that must not complete (`Editor::new()` installs the
+ /// builtin registry by default) answers nothing.
+ pub fn clear_autocomplete_provider(&mut self) {
+ self.cancel_autocomplete();
+ self.autocomplete_provider = None;
+ }
+
#[must_use]
pub fn autocomplete_state(&self) -> Option<&crate::autocomplete::AutocompleteState> {
self.autocomplete.as_ref()
diff --git a/crates/pa-tui/src/input.rs b/crates/pa-tui/src/input.rs
index f927185d29..f22d27d2d4 100644
--- a/crates/pa-tui/src/input.rs
+++ b/crates/pa-tui/src/input.rs
@@ -5,18 +5,19 @@
//! chains open one session after another. crossterm events are process
//! global, so two concurrent reader threads race for the same bytes; the
//! losing (older) thread can read a keypress after its channel is gone and
-//! drop it — the user's key vanishes. [`spawn_terminal_reader`] joins the
-//! still-running reader from the previous surface before starting the next
-//! one, so exactly one reader is alive at any time.
+//! drop it — the user's key vanishes. The reader joins the still-running
+//! reader from the previous surface before starting the next one, so
+//! exactly one reader is alive at any time.
//!
-//! [`spawn_paste_aware_reader`] layers the TS `StdinBuffer` raw-paste
-//! heuristic on top for the editor-bearing session surface: a keystroke
-//! burst that arrives in one chunk shaped like multi-line text (text,
-//! newline, text — tmux 3.2 and older forward pastes without bracketed
-//! markers) is coalesced into one paste instead of submitting line by
-//! line. A zero-timeout poll after each read marks the chunk boundary:
-//! crossterm serves the rest of the same OS read without blocking, so a
-//! burst is exactly the events one terminal write carried.
+//! [`spawn_paste_aware_reader`] runs the TS `StdinBuffer` raw-paste
+//! heuristic for the editor-bearing surfaces (the session surface and the
+//! agents view's composers): a keystroke burst that arrives in one chunk
+//! shaped like multi-line text (text, newline, text — tmux 3.2 and older
+//! forward pastes without bracketed markers) is coalesced into one paste
+//! instead of submitting line by line. A zero-timeout poll after each
+//! read marks the chunk boundary: crossterm serves the rest of the same
+//! OS read without blocking, so a burst is exactly the events one
+//! terminal write carried.
//!
//! Both readers also run the [`SequenceGuard`] (TS `StdinBuffer`'s
//! partial-sequence hold, ported in [`crate::sequence_guard`]):
@@ -84,10 +85,10 @@ pub(crate) fn stop_reader() {
/// flagged reader observes the flag at its loop top, so the wake is what
/// turns a parked (indefinite) poll into a prompt exit. The teardown
/// paths call this BEFORE any drain that polls crossterm directly (the
-/// drain must own the reader lock), and the next surface's
-/// [`spawn_terminal_reader`] joins the already-exited thread, so a
-/// surface switch never waits on a poll tick and a dying reader cannot
-/// steal a keypress aimed at the new surface.
+/// drain must own the reader lock), and the next surface's reader spawn
+/// joins the already-exited thread, so a surface switch never waits on a
+/// poll tick and a dying reader cannot steal a keypress aimed at the new
+/// surface.
pub(crate) fn request_reader_stop() {
let guard = PREVIOUS_READER
.lock()
@@ -117,45 +118,29 @@ pub(crate) enum ReaderInput {
BurstPaste(String),
}
-/// Start the terminal input reader. `on_event` runs for every crossterm
-/// event; returning `false` stops the reader (the caller stops it when its
-/// channel dies). The reader from the previous surface is stopped and joined
-/// first so it cannot steal events from the new one.
-pub(crate) fn spawn_terminal_reader<F>(mut on_event: F)
-where
- F: FnMut(Event) -> bool + Send + 'static,
-{
- spawn_reader(false, move |input| match input {
- ReaderInput::Event(event) => on_event(event),
- // Surfaces without a mouse dispatch consume reports; a
- // reassembled report is terminal noise they must not type.
- ReaderInput::Mouse(_) | ReaderInput::BurstPaste(_) => true,
- });
-}
-
-/// The paste-aware variant for the interactive session surface: whole
-/// terminal writes that look like multi-line pastes (a marker-less burst
-/// with text on both sides of a newline) are delivered as one
-/// [`ReaderInput::BurstPaste`]; everything else arrives event by event.
+/// Start the terminal input reader: whole terminal writes that look like
+/// multi-line pastes (a marker-less burst with text on both sides of a
+/// newline) are delivered as one [`ReaderInput::BurstPaste`]; everything
+/// else arrives event by event. `on_input` returning `false` stops the
+/// reader (the caller stops it when its channel dies). The reader from the
+/// previous surface is stopped and joined first so it cannot steal events
+/// from the new one.
pub(crate) fn spawn_paste_aware_reader<F>(on_input: F)
where
F: FnMut(ReaderInput) -> bool + Send + 'static,
{
- spawn_reader(true, on_input);
+ spawn_reader(on_input);
}
/// The shared reader body: one reader per process, joined across surfaces.
-/// `paste_aware` selects the burst coalescing; a plain reader forwards
-/// every event unchanged (surfaces without the editor's paste path would
-/// lose a coalesced burst they cannot consume). Each chunk — one
-/// terminal write — is repaired and classified before any of it reaches
-/// the surface: the macOS-Terminal meta repair
+/// Each chunk — one terminal write — is repaired and classified before
+/// any of it reaches the surface: the macOS-Terminal meta repair
/// ([`merge_legacy_meta_escapes`]) rewrites the wrapped double-ESC
/// shapes first (the [`SequenceGuard`] would otherwise hold their `Esc`
/// head), the guard reassembles partial sequences into mouse reports
/// and key events, and [`forward`] passes the TS dispatch filters
/// ([`filter_enhanced_key_events`]) when it delivers.
-fn spawn_reader<F>(paste_aware: bool, mut on_input: F)
+fn spawn_reader<F>(mut on_input: F)
where
F: FnMut(ReaderInput) -> bool + Send + 'static,
{
@@ -204,11 +189,7 @@ where
});
match crossterm::event::poll_opt(timeout) {
Ok(false) => {
- if !forward(
- guard.flush_expired(Instant::now()),
- paste_aware,
- &mut on_input,
- ) {
+ if !forward(guard.flush_expired(Instant::now()), &mut on_input) {
return;
}
}
@@ -253,7 +234,7 @@ where
for event in events {
outputs.extend(guard.feed(event, Instant::now()));
}
- if !forward(outputs, paste_aware, &mut on_input) {
+ if !forward(outputs, &mut on_input) {
return;
}
}
@@ -274,12 +255,8 @@ where
/// else — plain events and reassembled mouse reports alike — passes the
/// TS dispatch filters ([`filter_enhanced_key_events`]) and forwards
/// input by input. Returns `false` when the surface stopped the reader.
-fn forward(
- outputs: Vec<GuardOutput>,
- paste_aware: bool,
- on_input: &mut dyn FnMut(ReaderInput) -> bool,
-) -> bool {
- if paste_aware && !outputs.is_empty() {
+fn forward(outputs: Vec<GuardOutput>, on_input: &mut dyn FnMut(ReaderInput) -> bool) -> bool {
+ if !outputs.is_empty() {
let mut text = String::new();
let mut burst_is_plain_text = true;
for output in &outputs {
@@ -873,7 +850,7 @@ mod tests {
/// `forward` against a capturing sink (the paste-aware surface).
fn collect_forwarded(outputs: Vec<GuardOutput>) -> Vec<ReaderInput> {
let mut inputs = Vec::new();
- let ok = forward(outputs, true, &mut |input| {
+ let ok = forward(outputs, &mut |input| {
inputs.push(input);
true
});
diff --git a/crates/pa-tui/src/interactive.rs b/crates/pa-tui/src/interactive.rs
index 1cb2525789..65082b7511 100644
--- a/crates/pa-tui/src/interactive.rs
+++ b/crates/pa-tui/src/interactive.rs
@@ -437,8 +437,11 @@ impl std::fmt::Debug for InteractiveOptions {
}
impl InteractiveOptions {
- /// The `create` config carried on every new-session request.
- pub(crate) fn create_config(&self) -> Value {
+ /// The `create` config carried on every new-session request (the
+ /// agents view reuses it as the base of a resume's config — TS's
+ /// `AgentsViewModeOptions.config`).
+ #[must_use]
+ pub fn create_config(&self) -> Value {
let mut config = json!({ "cwd": self.cwd.display().to_string() });
if let Some(session_dir) = &self.session_dir {
config["sessionDir"] = json!(session_dir.display().to_string());
@@ -463,6 +466,11 @@ impl InteractiveOptions {
if let Some(models) = &self.models {
config["models"] = json!(models);
}
+ // TS main.ts's `telemetryDisabled` rides the runtime config: a
+ // resume's create reads it back (the agents view's saved reply).
+ if self.telemetry_disabled == Some(true) {
+ config["telemetryDisabled"] = json!(true);
+ }
config
}
}
diff --git a/crates/pa-tui/src/keys.rs b/crates/pa-tui/src/keys.rs
index ec3a044483..abee0ef354 100644
--- a/crates/pa-tui/src/keys.rs
+++ b/crates/pa-tui/src/keys.rs
@@ -121,8 +121,14 @@ pub fn key_event_to_id(key: &KeyEvent) -> Option<KeyId> {
"tab".into()
});
}
- if c == ' ' && shift {
- return Some("shift+space".into());
+ if c == ' ' {
+ // TS parseKey maps the raw space to the `space` key id
+ // (keys.ts:1280) — the printable decoders (`decode_printable`)
+ // map it back for text surfaces.
+ if shift {
+ return Some("shift+space".into());
+ }
+ return Some("space".into());
}
return Some(c.to_string());
}
diff --git a/crates/pa-tui/src/settings_menu/mod.rs b/crates/pa-tui/src/settings_menu/mod.rs
index 5cd8bf9b6a..8d92ff3706 100644
--- a/crates/pa-tui/src/settings_menu/mod.rs
+++ b/crates/pa-tui/src/settings_menu/mod.rs
@@ -483,7 +483,7 @@ impl SettingsMenu {
}
return SettingsMenuAction::None;
}
- if key == " " || kb.matches(key, "tui.select.confirm") {
+ if key == "space" || kb.matches(key, "tui.select.confirm") {
return self.activate_selected();
}
if kb.matches(key, "tui.select.cancel") || key == "ctrl+c" {
@@ -591,7 +591,7 @@ impl SettingsMenu {
}
return SettingsMenuAction::None;
}
- if kb.matches(key, "tui.select.confirm") || key == " " {
+ if kb.matches(key, "tui.select.confirm") || key == "space" {
let row_id = self.rows[sub.row].id;
let value = match &sub.kind {
SettingsSubmenu::Thinking { levels } => {
diff --git a/crates/pa-tui/src/view.rs b/crates/pa-tui/src/view.rs
index 206ca9df3d..6d80ae4c28 100644
--- a/crates/pa-tui/src/view.rs
+++ b/crates/pa-tui/src/view.rs
@@ -12,6 +12,7 @@ use crate::theme::Theme;
use crate::Line;
pub(crate) mod click;
+pub(crate) mod editor_surface;
mod expansion;
mod flush;
mod frame;
diff --git a/crates/pa-tui/src/view/click.rs b/crates/pa-tui/src/view/click.rs
index 91a6a45f9d..61b7eb244b 100644
--- a/crates/pa-tui/src/view/click.rs
+++ b/crates/pa-tui/src/view/click.rs
@@ -72,8 +72,9 @@ pub(crate) struct EditorClickSurface {
pub(crate) dock_row: usize,
/// Content rows the surface shows.
pub(crate) rows: usize,
- /// Rows the queue-selection header inserts above the content.
- pub(crate) queue_header_rows: usize,
+ /// Rows the header block inserts above the content (the queue-browse
+ /// header, an action composer's header; TS `getContentLineOffset`).
+ pub(crate) content_offset: usize,
/// The rendered prompt's visible width (`> `, `! `, `!! `).
pub(crate) prompt_width: usize,
/// The width the editor's layout wrapped at.
@@ -265,7 +266,7 @@ impl AgentView {
// The content rows follow the surface's top border and the
// queue-selection header (TS `getClickRegions`'s line base).
let content_row = dock_row
- .checked_sub(editor.dock_row + 1 + editor.queue_header_rows)
+ .checked_sub(editor.dock_row + 1 + editor.content_offset)
.filter(|row| *row < editor.rows)?;
Some(ClickAction::PlaceCaret {
row: content_row,
diff --git a/crates/pa-tui/src/view/editor_surface.rs b/crates/pa-tui/src/view/editor_surface.rs
new file mode 100644
index 0000000000..323be809ca
--- /dev/null
+++ b/crates/pa-tui/src/view/editor_surface.rs
@@ -0,0 +1,275 @@
+//! The editor box: the shared renderer for every editor-bearing surface —
+//! the chat's prompt dock and the agents view's action composers. This
+//! module owns "the editor box" (TS `Editor.render` on its background
+//! surface, plus `CustomEditor.render`'s header-block and placeholder
+//! insertions); the surfaces compose it with their own headers,
+//! placeholders, and click regions.
+//!
+//! The box's row shape (TS `Editor.render` with a background surface):
+//! the top bg row (a scroll indicator once content hides above), the
+//! header block's two rows (the caller's header line plus its blank
+//! companion, TS `getHeaderLine` via `renderHeaderContentLine`), the
+//! content rows (`> ` prompt, styled text, the reverse-video cursor),
+//! and the trailing bg row (a `↓ N more` indicator once content hides
+//! below). An empty editor with a placeholder shows the placeholder row
+//! in place of the first content row (TS `renderPlaceholderLine`: the
+//! cursor cell, then the dim placeholder).
+
+use super::chunk_selection;
+use super::flush::split_at_chars;
+use super::frame::{indicator_row, pad_row};
+use crate::editor::Editor;
+use crate::prompt_highlight::{
+ command_token, editor_chunk_highlights, editor_text_spans, find_arg_tokens, ArgTokenSpan,
+};
+use crate::theme::{Theme, ThemeBg, ThemeColor};
+use crate::width::{str_width, truncate_to_width};
+use crate::{Line, Span};
+use pa_types::slash_commands::SlashCommandRegistry;
+use ratatui::style::Modifier;
+
+/// The composed editor box plus the geometry its caller records: the
+/// click surface's metrics and the cursor's cell.
+pub(crate) struct EditorBox {
+ /// The box's rows, top bg row first.
+ pub(crate) rows: Vec<Line>,
+ /// The cursor's row within the box and its column (`None` while the
+ /// editor's window shows no cursor).
+ pub(crate) cursor: Option<(usize, usize)>,
+ /// The rows between the box's top row and its first content row (TS
+ /// `getContentLineOffset`): a header block inserts its two.
+ pub(crate) content_offset: usize,
+ /// The rendered prompt's visible width (`> `, `! `, `!! `).
+ pub(crate) prompt_width: usize,
+ /// The width the editor's layout wrapped at.
+ pub(crate) content_width: usize,
+ /// The content rows the box shows.
+ pub(crate) visible_rows: usize,
+}
+
+/// Compose one editor box (TS `Editor.render` + `CustomEditor.render`'s
+/// insertions). `header` carries the caller's header line (the chat's
+/// queue-browse header, an action composer's own header): it renders as
+/// the two-row block under the top row. `placeholder` replaces the first
+/// content row while the editor is empty (TS `renderPlaceholderLine`, the
+/// placeholder dim).
+pub(crate) fn render(
+ editor: &mut Editor,
+ theme: &Theme,
+ width: usize,
+ terminal_rows: u16,
+ header: Option<Line>,
+ placeholder: Option<&str>,
+) -> EditorBox {
+ let bg = crate::chrome::editor_background(theme);
+ let border = theme.fg_style(ThemeColor::BorderMuted);
+ let padding_x = 2usize;
+ let content_width = width.saturating_sub(padding_x * 2).max(1);
+ // TS `getPromptPrefix` + `getRenderMetrics`: a bang first line
+ // swaps the `> ` for the `! `/`!! ` prompt (styled through the
+ // editor border color, `formatPromptPrefix`), which also narrows
+ // the input width.
+ let bash_prompt = editor.bash_prompt_prefix();
+ let prompt = bash_prompt.unwrap_or("> ");
+ let prompt_width = str_width(prompt);
+ let input_width = content_width.saturating_sub(prompt_width).max(1);
+ let layout_width = input_width;
+ let (visible, scroll_offset, _hidden_above, hidden_below) =
+ editor.visible_window(layout_width, terminal_rows);
+ let content_offset = usize::from(header.is_some()) * 2;
+ let mut rows: Vec<Line> = Vec::new();
+ if scroll_offset > 0 {
+ let indicator = format!(" \u{2191} {scroll_offset} more");
+ rows.push(indicator_row(&indicator, bg, border, width));
+ } else {
+ rows.push(vec![Span::styled(" ".repeat(width), bg)]);
+ }
+ // The header block (TS `renderHeaderContentLine`): the caller's line
+ // on the editor background, padded and truncated to the content
+ // width, plus its empty companion row — the box grows by two rows
+ // while a header shows (TS `getContentLineOffset` shifts the click
+ // regions with it).
+ if let Some(header) = header {
+ let mut row: Line = vec![Span::styled(" ".repeat(padding_x), bg)];
+ row.extend(crate::width::truncate_line(&header, content_width, "..."));
+ let used = crate::width::line_width(&row);
+ row.push(Span::styled(" ".repeat(width.saturating_sub(used)), bg));
+ rows.push(row);
+ rows.push(vec![Span::styled(" ".repeat(width), bg)]);
+ }
+ // TS `CustomEditor.render`: a bare `--` separator highlights only
+ // while the first line opens with an argument-taking slash command.
+ let selection = editor.selection_range();
+ let editor_lines = editor.get_lines();
+ let registry = SlashCommandRegistry::builtin_cached();
+ let include_bare_separator = editor_lines
+ .first()
+ .and_then(|first| command_token(first))
+ .is_some_and(|token| registry.takes_argument(&token.name));
+ let arg_token_spans: Vec<Vec<ArgTokenSpan>> = editor_lines
+ .iter()
+ .map(|line| find_arg_tokens(line, 0, include_bare_separator))
+ .collect();
+ let mut cursor: Option<(usize, usize)> = None;
+ // The placeholder row (TS `renderPlaceholderLine`): while the editor
+ // is empty, the first content row is the cursor cell followed by the
+ // dim placeholder (the placeholder color is the agents view's dim,
+ // `placeholderColor`).
+ let placeholder_row = placeholder.filter(|_| editor.get_text().is_empty());
+ for (index, line) in visible.iter().enumerate() {
+ if index == 0 && placeholder_row.is_some() {
+ let mut row: Line = vec![Span::styled(" ".to_string(), bg)];
+ let style = if bash_prompt.is_some() { border } else { bg };
+ row.push(Span::styled(prompt.to_string(), style));
+ row.push(Span::styled(" ".to_string(), bg));
+ let placeholder_width = input_width.saturating_sub(1);
+ let text = truncate_to_width(placeholder_row.unwrap_or(""), placeholder_width, "");
+ let fill = " ".repeat(placeholder_width.saturating_sub(str_width(&text)));
+ row.push(Span::styled(
+ " ".to_string(),
+ bg.add_modifier(Modifier::REVERSED),
+ ));
+ row.push(Span::styled(
+ text,
+ bg.patch(theme.fg_style(ThemeColor::Dim)),
+ ));
+ row.push(Span::styled(fill, bg));
+ row.push(Span::styled(" ".repeat(padding_x), bg));
+ rows.push(row);
+ cursor = Some((1 + content_offset, prompt_width + 2));
+ continue;
+ }
+ let mut row: Line = vec![Span::styled(" ".to_string(), bg)];
+ // The `> ` prompt prefix renders plain on the surface
+ // background; the `!` bash prompts render through the editor
+ // border color (TS `formatPromptPrefix`).
+ if index == 0 {
+ let style = if bash_prompt.is_some() { border } else { bg };
+ row.push(Span::styled(prompt.to_string(), style));
+ } else {
+ row.push(Span::styled(" ".repeat(prompt_width), bg));
+ }
+ row.push(Span::styled(" ".to_string(), bg));
+ let text: &str = &line.text;
+ let cursor_pos = line
+ .has_cursor
+ .then(|| line.cursor_pos.min(text.chars().count()));
+ // The prompt-highlight spans of this chunk: argument tokens, and
+ // the command token of the first layout line in accent unless
+ // the cursor sits inside it (TS `styleDisplayText`).
+ let command = (scroll_offset + index == 0)
+ .then(|| command_token(text))
+ .flatten();
+ let highlights = editor_chunk_highlights(
+ text,
+ arg_token_spans
+ .get(line.source_line)
+ .map_or(&[][..], |spans| spans),
+ line.source_start,
+ command.as_ref(),
+ cursor_pos,
+ );
+ row.extend(editor_text_spans(
+ theme,
+ text,
+ &highlights,
+ chunk_selection(selection, line.source_line, line.source_start, text),
+ cursor_pos,
+ bg,
+ ));
+ let mut used = str_width(text);
+ if cursor_pos == Some(text.chars().count()) {
+ // The end-of-line cursor appends one reversed cell.
+ used += 1;
+ }
+ if let Some(position) = cursor_pos {
+ let head = split_at_chars(text, position).0;
+ cursor = Some((
+ 1 + content_offset + index,
+ str_width(head) + prompt_width + 2,
+ ));
+ }
+ row.push(Span::styled(
+ " ".repeat(input_width.saturating_sub(used)),
+ bg,
+ ));
+ row.push(Span::styled(" ".repeat(padding_x), bg));
+ rows.push(row);
+ }
+ if hidden_below > 0 {
+ rows.push(indicator_row(
+ &format!(" \u{2193} {hidden_below} more"),
+ bg,
+ border,
+ width,
+ ));
+ } else {
+ rows.push(vec![Span::styled(" ".repeat(width), bg)]);
+ }
+ EditorBox {
+ rows,
+ cursor,
+ content_offset,
+ prompt_width,
+ content_width: layout_width,
+ visible_rows: visible.len(),
+ }
+}
+
+/// The autocomplete dropdown, mounted just above the editor surface (TS
+/// anchors the overlay immediately above the cursor row; the editor's
+/// first content row carries the cursor in the common single-line
+/// case). The panel opens with the one full-width muted rule every
+/// inline menu panel opens with (the operator's 2026-09-26 top-border
+/// directive), its rows pad to the input width and float on the popup
+/// background between the editor's left padding and prompt prefix, and
+/// the selected row's wash spans the panel's full width like the
+/// `/model` picker's selected row.
+pub(crate) fn overlay(editor: &Editor, theme: &Theme, width: usize) -> Vec<Line> {
+ let Some(state) = editor.autocomplete_state() else {
+ return Vec::new();
+ };
+ let bg = theme.bg_style(ThemeBg::ToolPanelBg);
+ let selection = theme.soft_selection_style();
+ let padding_x = 2usize;
+ // The overlay anchors against the live prompt prefix (TS
+ // `getRenderMetrics`'s `promptPrefixWidth`, the `!`/`!!` prompts
+ // included).
+ let prompt_width = str_width(editor.bash_prompt_prefix().unwrap_or("> "));
+ let content_width = width.saturating_sub(padding_x * 2).max(1);
+ let input_width = content_width.saturating_sub(prompt_width).max(1);
+ // The panel's top border: the muted `─` rule that separates an
+ // inline menu panel from the rows above it, drawn on the panel
+ // surface.
+ let border = theme.fg_style(ThemeColor::BorderMuted).patch(bg);
+ let mut rows: Vec<Line> = vec![vec![Span::styled("\u{2500}".repeat(width.max(1)), border)]];
+ let mut overlay = Vec::new();
+ overlay.extend(state.render(theme, input_width));
+ overlay.push(Vec::new());
+ for mut line in overlay {
+ // The shared menu rows pad to the full input width with
+ // unstyled spans, so the remaining-width fill below never
+ // lands: the popup background must ride on every span the
+ // row left unstyled. The selected row is the one whose spans
+ // carry the selection band: its edge padding washes with the
+ // selection too, so the band spans the panel's full width
+ // instead of stopping at the input's edges.
+ let selected = line.iter().any(|span| span.style.bg.is_some());
+ for span in &mut line {
+ if span.style.bg.is_none() {
+ span.style = span.style.patch(bg);
+ }
+ }
+ let used: usize = line.iter().map(|s| str_width(&s.content)).sum();
+ let edge = if selected { bg.patch(selection) } else { bg };
+ let mut row: Line = vec![Span::styled(" ".repeat(padding_x + prompt_width), edge)];
+ row.extend(line);
+ row.push(Span::styled(
+ " ".repeat(input_width.saturating_sub(used)),
+ edge,
+ ));
+ row.push(Span::styled(" ".repeat(padding_x), edge));
+ rows.push(pad_row(row, width));
+ }
+ rows
+}
diff --git a/crates/pa-tui/src/view/panels.rs b/crates/pa-tui/src/view/panels.rs
index 4dd37bcf4c..cf33c5458a 100644
--- a/crates/pa-tui/src/view/panels.rs
+++ b/crates/pa-tui/src/view/panels.rs
@@ -3,19 +3,12 @@
//! subagent summary box (TS `SubagentSummaryLine`) — plus the share
//! loader and reload-box panels that replace the editor in flight.
-use super::chunk_selection;
use super::click::{ClickAction, DockClickRegion, EditorClickSurface};
-use super::flush::split_at_chars;
-use super::frame::{indicator_row, pad_row};
+use super::editor_surface;
use super::{AgentView, ShareLoader};
use crate::chrome::{render_prompt_context, render_tray_with_hint};
-use crate::prompt_highlight::{
- command_token, editor_chunk_highlights, editor_text_spans, find_arg_tokens, ArgTokenSpan,
-};
-use crate::theme::{ThemeBg, ThemeColor};
-use crate::width::str_width;
+use crate::theme::ThemeColor;
use crate::{Line, Span};
-use pa_types::slash_commands::SlashCommandRegistry;
use ratatui::style::Style;
impl AgentView {
@@ -92,53 +85,7 @@ impl AgentView {
/// the selected row's wash spans the panel's full width like the
/// `/model` picker's selected row.
fn render_autocomplete_overlay(&mut self, width: usize) -> Vec<Line> {
- let Some(state) = self.editor.autocomplete_state() else {
- return Vec::new();
- };
- let theme = &self.theme;
- let bg = self.theme.bg_style(ThemeBg::ToolPanelBg);
- let selection = self.theme.soft_selection_style();
- let padding_x = 2usize;
- // The overlay anchors against the live prompt prefix (TS
- // `getRenderMetrics`'s `promptPrefixWidth`, the `!`/`!!` prompts
- // included).
- let prompt_width = str_width(self.editor.bash_prompt_prefix().unwrap_or("> "));
- let content_width = width.saturating_sub(padding_x * 2).max(1);
- let input_width = content_width.saturating_sub(prompt_width).max(1);
- // The panel's top border: the muted `─` rule that separates an
- // inline menu panel from the rows above it, drawn on the panel
- // surface.
- let border = theme.fg_style(ThemeColor::BorderMuted).patch(bg);
- let mut rows: Vec<Line> = vec![vec![Span::styled("\u{2500}".repeat(width.max(1)), border)]];
- let mut overlay = Vec::new();
- overlay.extend(state.render(theme, input_width));
- overlay.push(Vec::new());
- for mut line in overlay {
- // The shared menu rows pad to the full input width with
- // unstyled spans, so the remaining-width fill below never
- // lands: the popup background must ride on every span the
- // row left unstyled. The selected row is the one whose spans
- // carry the selection band: its edge padding washes with the
- // selection too, so the band spans the panel's full width
- // instead of stopping at the input's edges.
- let selected = line.iter().any(|span| span.style.bg.is_some());
- for span in &mut line {
- if span.style.bg.is_none() {
- span.style = span.style.patch(bg);
- }
- }
- let used: usize = line.iter().map(|s| str_width(&s.content)).sum();
- let edge = if selected { bg.patch(selection) } else { bg };
- let mut row: Line = vec![Span::styled(" ".repeat(padding_x + prompt_width), edge)];
- row.extend(line);
- row.push(Span::styled(
- " ".repeat(input_width.saturating_sub(used)),
- edge,
- ));
- row.push(Span::styled(" ".repeat(padding_x), edge));
- rows.push(pad_row(row, width));
- }
- rows
+ editor_surface::overlay(&self.editor, &self.theme, width)
}
/// The editor surface (TS `Editor.render` with a background): a blank
@@ -149,44 +96,10 @@ impl AgentView {
width: usize,
dock_row: usize,
) -> (Vec<Line>, Option<(usize, usize)>) {
- let bg = crate::chrome::editor_background(&self.theme);
- let border = self.theme.fg_style(ThemeColor::BorderMuted);
- let padding_x = 2usize;
- let content_width = width.saturating_sub(padding_x * 2).max(1);
- // TS `getPromptPrefix` + `getRenderMetrics`: a bang first line
- // swaps the `> ` for the `! `/`!! ` prompt (styled through the
- // editor border color, `formatPromptPrefix`), which also narrows
- // the input width.
- let bash_prompt = self.editor.bash_prompt_prefix();
- let prompt = bash_prompt.unwrap_or("> ");
- let prompt_width = str_width(prompt);
- let input_width = content_width.saturating_sub(prompt_width).max(1);
- let layout_width = input_width;
- let (visible, scroll_offset, _hidden_above, hidden_below) =
- self.editor.visible_window(layout_width, self.terminal_rows);
- // The content rows' click surface (view/click.rs): the TS editor
- // registers one region over its visible content rows, shifted by
- // the queue-selection header's rows (TS `getContentLineOffset`).
- self.click.record_editor(EditorClickSurface {
- dock_row,
- rows: visible.len(),
- queue_header_rows: usize::from(self.queue_selected.is_some()) * 2,
- prompt_width,
- content_width: layout_width,
- });
- let mut rows: Vec<Line> = Vec::new();
- if scroll_offset > 0 {
- let indicator = format!(" \u{2191} {scroll_offset} more");
- rows.push(indicator_row(&indicator, bg, border, width));
- } else {
- rows.push(vec![Span::styled(" ".repeat(width), bg)]);
- }
- if let Some(selected) = &self.queue_selected {
- // TS `getQueueSelectionHeader` (the editor's header line while a
- // parked message is selected): `CustomEditor.render` inserts the
- // dim header row plus an empty companion row BELOW the top row,
- // so the editor box grows by two rows while a message is selected
- // (TS `getContentLineOffset` shifts the click regions with it).
+ // TS `getQueueSelectionHeader` (the editor's header line while a
+ // parked message is selected): the dim browse text on the editor
+ // background, rendered by the shared box's header block.
+ let header = self.queue_selected.as_ref().map(|selected| {
let keys = {
let kb = self.editor.keybindings();
let display =
@@ -199,99 +112,32 @@ impl AgentView {
follow_up: display("app.message.followUp"),
}
};
- // Dim text on the editor background (the header line renders
- // inside the editor box like the `> ` rows): the dim
- // foreground patched over the editor background style.
- let dim = bg.patch(self.theme.fg_style(ThemeColor::Dim));
- let header = crate::queued::browse_header_text(selected, &keys);
- let mut row: Line = vec![Span::styled(" ".repeat(padding_x), bg)];
- let line: Line = vec![Span::styled(header, dim)];
- row.extend(crate::width::truncate_line(&line, content_width, "..."));
- let used = crate::width::line_width(&row);
- row.push(Span::styled(" ".repeat(width.saturating_sub(used)), bg));
- rows.push(row);
- rows.push(vec![Span::styled(" ".repeat(width), bg)]);
- }
- // TS `CustomEditor.render`: a bare `--` separator highlights only
- // while the first line opens with an argument-taking slash command.
- let selection = self.editor.selection_range();
- let editor_lines = self.editor.get_lines();
- let registry = SlashCommandRegistry::builtin_cached();
- let include_bare_separator = editor_lines
- .first()
- .and_then(|first| command_token(first))
- .is_some_and(|token| registry.takes_argument(&token.name));
- let arg_token_spans: Vec<Vec<ArgTokenSpan>> = editor_lines
- .iter()
- .map(|line| find_arg_tokens(line, 0, include_bare_separator))
- .collect();
- let mut cursor: Option<(usize, usize)> = None;
- for (index, line) in visible.iter().enumerate() {
- let mut row: Line = vec![Span::styled(" ".to_string(), bg)];
- // The `> ` prompt prefix renders plain on the surface
- // background; the `!` bash prompts render through the editor
- // border color (TS `formatPromptPrefix`).
- if index == 0 {
- let style = if bash_prompt.is_some() { border } else { bg };
- row.push(Span::styled(prompt.to_string(), style));
- } else {
- row.push(Span::styled(" ".repeat(prompt_width), bg));
- }
- row.push(Span::styled(" ".to_string(), bg));
- let text: &str = &line.text;
- let cursor_pos = line
- .has_cursor
- .then(|| line.cursor_pos.min(text.chars().count()));
- // The prompt-highlight spans of this chunk: argument tokens, and
- // the command token of the first layout line in accent unless
- // the cursor sits inside it (TS `styleDisplayText`).
- let command = (scroll_offset + index == 0)
- .then(|| command_token(text))
- .flatten();
- let highlights = editor_chunk_highlights(
- text,
- arg_token_spans
- .get(line.source_line)
- .map_or(&[][..], |spans| spans),
- line.source_start,
- command.as_ref(),
- cursor_pos,
- );
- row.extend(editor_text_spans(
- &self.theme,
- text,
- &highlights,
- chunk_selection(selection, line.source_line, line.source_start, text),
- cursor_pos,
- bg,
- ));
- let mut used = str_width(text);
- if cursor_pos == Some(text.chars().count()) {
- // The end-of-line cursor appends one reversed cell.
- used += 1;
- }
- if let Some(position) = cursor_pos {
- let head = split_at_chars(text, position).0;
- cursor = Some((index + 1, str_width(head) + prompt_width + 2));
- }
- row.push(Span::styled(
- " ".repeat(input_width.saturating_sub(used)),
- bg,
- ));
- row.push(Span::styled(" ".repeat(padding_x), bg));
- rows.push(row);
- }
- if hidden_below > 0 {
- rows.push(indicator_row(
- &format!(" \u{2193} {hidden_below} more"),
- bg,
- border,
- width,
- ));
- } else {
- rows.push(vec![Span::styled(" ".repeat(width), bg)]);
- }
- (rows, cursor)
+ let dim = crate::chrome::editor_background(&self.theme)
+ .patch(self.theme.fg_style(ThemeColor::Dim));
+ vec![Span::styled(
+ crate::queued::browse_header_text(selected, &keys),
+ dim,
+ )]
+ });
+ let surface = editor_surface::render(
+ &mut self.editor,
+ &self.theme,
+ width,
+ self.terminal_rows,
+ header,
+ None,
+ );
+ // The content rows' click surface (view/click.rs): the TS editor
+ // registers one region over its visible content rows, shifted by
+ // the header block's rows (TS `getContentLineOffset`).
+ self.click.record_editor(EditorClickSurface {
+ dock_row,
+ rows: surface.visible_rows,
+ content_offset: surface.content_offset,
+ prompt_width: surface.prompt_width,
+ content_width: surface.content_width,
+ });
+ (surface.rows, surface.cursor)
}
/// The `/share` loader rows (TS `BorderedLoader` + `CancellableLoader`):
diff --git a/crates/pa-tui/tests/agents_view_catalog_settle_carry.rs b/crates/pa-tui/tests/agents_view_catalog_settle_carry.rs
index 12fe406fff..087221ac45 100644
--- a/crates/pa-tui/tests/agents_view_catalog_settle_carry.rs
+++ b/crates/pa-tui/tests/agents_view_catalog_settle_carry.rs
@@ -288,6 +288,7 @@ fn view_options(socket: &std::path::Path, anchor: Option<&str>) -> AgentsViewOpt
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}
diff --git a/crates/pa-tui/tests/agents_view_click_headless.rs b/crates/pa-tui/tests/agents_view_click_headless.rs
index c2e3b32a5e..677845f997 100644
--- a/crates/pa-tui/tests/agents_view_click_headless.rs
+++ b/crates/pa-tui/tests/agents_view_click_headless.rs
@@ -221,6 +221,7 @@ fn view_options(socket: &std::path::Path) -> AgentsViewOptions {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}
diff --git a/crates/pa-tui/tests/agents_view_hover_headless.rs b/crates/pa-tui/tests/agents_view_hover_headless.rs
index d9ebe67228..fc9146569b 100644
--- a/crates/pa-tui/tests/agents_view_hover_headless.rs
+++ b/crates/pa-tui/tests/agents_view_hover_headless.rs
@@ -259,6 +259,7 @@ fn view_options(socket: &std::path::Path) -> AgentsViewOptions {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}
diff --git a/crates/pa-tui/tests/agents_view_incident_notice_e2e.rs b/crates/pa-tui/tests/agents_view_incident_notice_e2e.rs
index d233e2f1a2..7b13f6f176 100644
--- a/crates/pa-tui/tests/agents_view_incident_notice_e2e.rs
+++ b/crates/pa-tui/tests/agents_view_incident_notice_e2e.rs
@@ -254,6 +254,7 @@ fn view_options(socket: &std::path::Path) -> AgentsViewOptions {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}
diff --git a/crates/pa-tui/tests/agents_view_saved_catalog_failure.rs b/crates/pa-tui/tests/agents_view_saved_catalog_failure.rs
index f54a84f200..0e26718478 100644
--- a/crates/pa-tui/tests/agents_view_saved_catalog_failure.rs
+++ b/crates/pa-tui/tests/agents_view_saved_catalog_failure.rs
@@ -213,6 +213,7 @@ fn view_options(socket: &std::path::Path) -> AgentsViewOptions {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}
diff --git a/crates/pa-tui/tests/agents_view_wait_render_barrier.rs b/crates/pa-tui/tests/agents_view_wait_render_barrier.rs
index 75f7db03f0..6e0e20774b 100644
--- a/crates/pa-tui/tests/agents_view_wait_render_barrier.rs
+++ b/crates/pa-tui/tests/agents_view_wait_render_barrier.rs
@@ -278,6 +278,7 @@ fn view_options(socket: &std::path::Path) -> AgentsViewOptions {
keybindings: pa_tui::keybindings::KeybindingsManager::new(),
show_hardware_cursor: false,
incident_notice_state: None,
+ create_config: serde_json::json!({}),
}
}