A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
input goes live at first paint (#3353)
kt41e1f41c072e
diff --git a/crates/pa-cli/tests/input_live_open_pty_e2e.rs b/crates/pa-cli/tests/input_live_open_pty_e2e.rsnew file mode 100644index 0000000000..7ec05415df--- /dev/null+++ b/crates/pa-cli/tests/input_live_open_pty_e2e.rs@@ -0,0 +1,657 @@+// The Tier-C/D ruling (fleet-uniform, 2026-09-28): stack-resident futures+// by design on hot paths; 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).+#![allow(+ clippy::large_futures,+ clippy::too_many_lines,+ clippy::cast_possible_truncation,+ clippy::cast_possible_wrap,+ clippy::cast_sign_loss,+ clippy::cast_precision_loss+)]++//! Real-pty e2e for the input-latency contract (the operator's+//! "first page fast, time-to-type slow" report + AGENTS.md+//! "Performance and the critical path"): a NEW session's interactive+//! surface must accept keystrokes the moment its startup chrome is+//! mounted — the session open (create, attach, the dock folds, every+//! daemon readiness behind them) runs in the background, so the echo+//! never waits on it (TS `init()`: `ui.start()` is live before+//! `rebindCurrentSession()` awaits). The mock supervisor stalls the+//! `attach` response far past the echo deadline, so an open-gated input+//! path cannot fake a pass.+//!+//! The typed-ahead contract rides the same run: text typed during the+//! stall plus an Enter queued behind the open must submit once the+//! session lands — never lost, never errored.++#![cfg(unix)]++use std::io::{BufRead, BufReader, Read, Write};+use std::os::fd::{AsRawFd, OwnedFd};+use std::os::unix::process::CommandExt;+use std::path::PathBuf;+use std::process::{Child, Command, Stdio};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use nix::fcntl::{fcntl, FcntlArg::F_SETFL, OFlag};+use nix::pty::{openpty, Winsize};+use serde_json::{json, Value};++use pa_tui::interactive::{+ run_interactive, InteractiveOptions, ModelSelection, SessionSelection, UiMode,+};++/// The child-mode socket: set (with the socket path) only when this very+/// binary is re-executed as the product-under-test.+const CHILD_SOCKET_ENV: &str = "PA_INPUT_LIVE_CHILD_SOCKET";++/// How long the mock supervisor holds the `attach` response: far past the+/// echo deadline below, so the open is provably still in flight while the+/// keystrokes are expected to echo.+const OPEN_STALL_MS: u64 = 2_500;++/// The echo deadline: the keystroke echo must land while the attach is+/// still stalled, well inside the stall window.+const ECHO_DEADLINE_MS: u64 = 1_500;++/// The pty window the child renders into (a 0x0 pty renders nothing; the+/// grid the echo oracle reads matches the window the child lays out).+const PTY_ROWS: usize = 24;+const PTY_COLS: usize = 80;++/// The child half of the e2e: runs the real interactive loop in terminal+/// mode against the parent's mock supervisor. A plain `cargo test` run+/// (no `CHILD_SOCKET_ENV`) passes trivially — only the parent test drives+/// the real path.+#[test]+fn input_live_open_child_mode() {+ let Ok(socket) = std::env::var(CHILD_SOCKET_ENV) else {+ return;+ };+ let options = child_options(PathBuf::from(socket));+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .expect("tokio runtime");+ let _ = runtime.block_on(run_interactive(options, UiMode::Terminal));+}++/// The pty harnesses serialize: each drives a raw pty; concurrent+/// byte-level waits flake on the shared sandbox CPUs.+static HARNESS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++/// A keystroke echoes into the rendered surface while the session open is+/// still in flight (the attach is stalled for `OPEN_STALL_MS`), and the+/// typed-ahead text plus the queued Enter submit once the open lands.+#[test]+fn typing_echoes_while_the_session_open_is_stalled() {+ if !session_runner() {+ return;+ }+ match nix::unistd::setsid() {+ Ok(_) => {}+ Err(error) => panic!("the harness could not start a fresh session: {error}"),+ }+ let _lock = match HARNESS_LOCK.lock() {+ Ok(guard) => guard,+ Err(poisoned) => poisoned.into_inner(),+ };+ let commands = Arc::new(Mutex::new(Vec::new()));+ let mut harness = InputLiveHarness::start(Arc::clone(&commands));++ // The startup chrome (the new chat's brand splash) paints first: the+ // surface is mounted and in raw mode by then.+ harness.wait_from_start("prime agent", "the startup chrome painted");++ // Type while the open is still stalled. The echo must land inside the+ // echo deadline — far inside the attach's stall window.+ harness.type_text("zzq");+ let echo_at = harness.wait_from_start("zzq", "the keystroke echoed while the open was stalled");++ // The queued submit: the typed-ahead text plus Enter ride the opening+ // phase's queue and dispatch once the session lands.+ harness.type_text("\r");++ // Let the stalled attach land and the fold run.+ let content_at = harness.wait_from_start(+ "openprobe settled answer",+ "the attach's content frame painted",+ );++ // The red-first oracle, ordering-based (load-robust where a wall+ // clock is not): the keystroke echo must have painted while the+ // attach was still stalled, so it became visible strictly BEFORE the+ // attach's content frame in the byte stream. An open-gated input path+ // cannot fake this — its first echo frame can only follow the+ // stalled open, the same event that paints the content frame.+ assert!(+ echo_at < content_at,+ "the keystroke echo (byte {echo_at}) painted only after the attach's content frame (byte {content_at}): the input path was open-gated"+ );++ // The typed-ahead submit was delivered: the mock supervisor saw the+ // prompt carrying the typed text.+ let deadline = Instant::now() + Duration::from_secs(10);+ let submitted = loop {+ if let Some(found) = find_prompt_with(&commands, "zzq") {+ break found;+ }+ if Instant::now() > deadline {+ let seen = commands.lock().expect("commands").clone();+ panic!("the typed-ahead submit never reached the daemon; commands seen: {seen:?}");+ }+ std::thread::sleep(Duration::from_millis(50));+ };+ let _ = submitted;++ // The harness drops here: the child dies with the test on every path.+}++/// Whether this runner is attached to a controlling-terminal session (the+/// child re-exec needs a session it can leave and re-enter safely).+fn session_runner() -> bool {+ // SAFETY: tcgetpgrp only queries the fd's foreground process group.+ let foreground = unsafe { libc::tcgetpgrp(0) };+ if foreground < 0 {+ eprintln!(+ "no controlling-terminal session on the runner (tcgetpgrp(fd 0) \+ failed); skipping the input-live open e2e — it needs a \+ controlling-terminal session to drive the pty child"+ );+ return false;+ }+ true+}++/// One pty-backed product child plus the mock supervisor it opens against.+struct InputLiveHarness {+ child: Child,+ server: Option<std::thread::JoinHandle<()>>,+ /// Whether the mock's `accept` landed: `Drop` joins the serve thread+ /// only then, so a child that dies before connecting cannot hang the+ /// teardown on the still-accepting listener.+ connected: Arc<std::sync::atomic::AtomicBool>,+ master: PtyReader,+}++impl InputLiveHarness {+ fn start(commands: Arc<Mutex<Vec<String>>>) -> InputLiveHarness {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("tui.sock");+ let connected = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let supervisor = MockSupervisor::bind(&socket);+ let server = {+ let connected = Arc::clone(&connected);+ Some(std::thread::spawn(move || {+ supervisor.serve(&commands, &connected);+ }))+ };+ let pty = openpty(+ Some(&Winsize {+ ws_row: 24,+ ws_col: 80,+ ws_xpixel: 0,+ ws_ypixel: 0,+ }),+ None,+ )+ .expect("open pty");+ let child = spawn_child(&socket, &pty.slave);+ // Leak the temp dir's socket path on purpose: the child needs the+ // socket for the lifetime of the test, and the whole tree dies+ // with the child at teardown.+ std::mem::forget(dir);+ InputLiveHarness {+ child,+ server,+ connected,+ master: PtyReader::new(pty.master),+ }+ }++ fn type_text(&mut self, text: &str) {+ // The typed bytes must land on the child's stdin (the pty slave):+ // write to the master.+ self.master.write_typed(text);+ }++ /// Wait for a needle in the rendered grid; returns the raw byte+ /// offset at which it first became visible (the ordering oracle).+ fn wait_from_start(&mut self, needle: &str, what: &str) -> usize {+ self.master+ .wait_for(needle, what, ECHO_DEADLINE_MS * 3 + OPEN_STALL_MS * 2)+ }+}++impl Drop for InputLiveHarness {+ fn drop(&mut self) {+ // The teardown runs on every exit path — including the panic+ // unwinds the oracles below produce — so no product child ever+ // outlives the test that spawned it. The child's death ends the+ // mock's read loop (the serve thread joins only when its accept+ // landed; a child that died pre-connect leaves the listener+ // thread to the process exit instead of hanging the drop).+ let _ = self.child.kill();+ let _ = self.child.wait();+ if self.connected.load(std::sync::atomic::Ordering::SeqCst) {+ if let Some(server) = self.server.take() {+ let _ = server.join();+ }+ }+ }+}++/// The rendered screen (a minimal ANSI grid renderer, the probe doc's+/// detection method): the TUI draws char-by-char with cursor moves, so a+/// needle must be matched against the RENDERED grid — a raw byte search+/// false-negatives whenever the wordmark, a name, or an editor echo is+/// painted glyph-by-glyph with cursor hops between them.+struct PtyReader {+ file: std::fs::File,+ /// The raw byte stream (kept for the panic dump).+ output: Vec<u8>,+ rows: usize,+ cols: usize,+ grid: Vec<Vec<char>>,+ row: usize,+ col: usize,+}++impl PtyReader {+ fn new(master: OwnedFd) -> PtyReader {+ let fd = master.as_raw_fd();+ fcntl(fd, F_SETFL(OFlag::O_NONBLOCK)).expect("pty master non-blocking");+ PtyReader {+ file: master.into(),+ output: Vec::new(),+ rows: PTY_ROWS,+ cols: PTY_COLS,+ grid: vec![vec![' '; PTY_COLS]; PTY_ROWS],+ row: 0,+ col: 0,+ }+ }++ fn write_typed(&mut self, text: &str) {+ self.file.write_all(text.as_bytes()).expect("type text");+ }++ fn put(&mut self, ch: char) {+ if self.row < self.rows && self.col < self.cols {+ self.grid[self.row][self.col] = ch;+ }+ self.col = (self.col + 1).min(self.cols - 1);+ }++ /// Feed the raw bytes through the grid: text lands at the cursor, CSI+ /// cursor/erase sequences move or clear it, and every other escape+ /// (SGR, private modes, OSC) is consumed.+ fn feed(&mut self, data: &[u8]) {+ let bytes = data;+ let mut i = 0;+ while i < bytes.len() {+ let byte = bytes[i];+ if byte == 0x1b {+ match bytes.get(i + 1) {+ Some(b'[') => {+ // CSI: consume the parameter bytes, then the final.+ let mut j = i + 2;+ let start = j;+ while j < bytes.len() && !(0x40..=0x7e).contains(&bytes[j]) {+ j += 1;+ }+ if j >= bytes.len() {+ break;+ }+ self.csi(&String::from_utf8_lossy(&bytes[start..j]), bytes[j]);+ i = j + 1;+ }+ Some(b']') => {+ // OSC: consumed through its BEL or ST terminator+ // (a fresh ESC starts a new sequence instead).+ let mut j = i + 2;+ let mut consumed = false;+ while j < bytes.len() {+ if bytes[j] == 0x07 {+ i = j + 1;+ consumed = true;+ break;+ }+ if bytes[j] == 0x1b {+ let terminator = bytes.get(j + 1) == Some(&b'\\');+ i = if terminator { j + 2 } else { j };+ consumed = true;+ break;+ }+ j += 1;+ }+ if !consumed {+ i = j;+ }+ }+ // A two-byte escape the grid does not model (ESC (, ESC =,+ // ...): skip the pair.+ Some(_) => i += 2,+ None => break,+ }+ continue;+ }+ match byte {+ b'\n' => {+ self.row = (self.row + 1).min(self.rows - 1);+ i += 1;+ }+ b'\r' => {+ self.col = 0;+ i += 1;+ }+ byte if byte < 0x20 => i += 1,+ byte if byte < 0x80 => {+ self.put(byte as char);+ i += 1;+ }+ _ => {+ // Multi-byte UTF-8: decode the full code point.+ let len = if byte < 0xe0 {+ 2+ } else if byte < 0xf0 {+ 3+ } else {+ 4+ };+ let end = (i + len).min(bytes.len());+ if let Ok(text) = std::str::from_utf8(&bytes[i..end]) {+ if let Some(ch) = text.chars().next() {+ self.put(ch);+ }+ }+ i = end;+ }+ }+ }+ }++ fn csi(&mut self, params: &str, final_byte: u8) {+ let params = params.trim_start_matches(['?', '>', '<', '=']);+ let number = |index: usize, default: usize| -> usize {+ params+ .split(';')+ .nth(index)+ .and_then(|value| value.parse::<usize>().ok())+ .unwrap_or(default)+ };+ match final_byte {+ b'H' | b'f' => {+ self.row = number(0, 1).saturating_sub(1).min(self.rows - 1);+ self.col = number(1, 1).saturating_sub(1).min(self.cols - 1);+ }+ b'A' => self.row = self.row.saturating_sub(number(0, 1)),+ b'B' => self.row = (self.row + number(0, 1)).min(self.rows - 1),+ b'C' => self.col = (self.col + number(0, 1)).min(self.cols - 1),+ b'D' => self.col = self.col.saturating_sub(number(0, 1)),+ b'G' => self.col = number(0, 1).saturating_sub(1).min(self.cols - 1),+ b'J' => {+ let mode = number(0, 0);+ if mode == 2 || mode == 3 {+ self.grid = vec![vec![' '; self.cols]; self.rows];+ }+ }+ _ => {}+ }+ }++ /// The rendered grid as text (trailing blanks trimmed per row).+ fn rendered(&self) -> String {+ self.grid+ .iter()+ .map(|row| row.iter().collect::<String>())+ .collect::<Vec<_>>()+ .join("\n")+ }++ /// Drain the master until the needle appears in the RENDERED grid,+ /// bounded by the given window; returns the raw byte offset at which+ /// the needle first became visible (the ordering oracle's evidence).+ fn wait_for(&mut self, needle: &str, what: &str, window_ms: u64) -> usize {+ let deadline = Instant::now() + Duration::from_millis(window_ms);+ let mut seen_at = None;+ loop {+ if seen_at.is_none() && self.rendered().contains(needle) {+ seen_at = Some(self.output.len());+ }+ if let Some(at) = seen_at {+ return at;+ }+ let mut buffer = [0u8; 8192];+ match self.file.read(&mut buffer) {+ Ok(0) | Err(_) => {}+ Ok(n) => {+ self.output.extend_from_slice(&buffer[..n]);+ self.feed(&buffer[..n]);+ }+ }+ if Instant::now() > deadline {+ let screen = self.rendered();+ let stream = String::from_utf8_lossy(&self.output);+ panic!("timeout waiting for {what} (needle {needle:?}); rendered screen:\n{screen}\npty stream:\n{stream}");+ }+ std::thread::sleep(Duration::from_millis(20));+ }+ }+}++/// The mock's recorded commands: one line per received command envelope.+fn find_prompt_with(commands: &Arc<Mutex<Vec<String>>>, text: &str) -> Option<String> {+ commands+ .lock()+ .expect("commands")+ .iter()+ .find(|line| line.contains("\"prompt\"") && line.contains(text))+ .cloned()+}++/// A child process group of this very binary, re-executed in child mode+/// with the pty slave as its terminal and no tmux.+fn spawn_child(socket: &std::path::Path, slave: &OwnedFd) -> Child {+ fn make_process_group() -> std::io::Result<()> {+ nix::unistd::setpgid(nix::unistd::Pid::from_raw(0), nix::unistd::Pid::from_raw(0))?;+ Ok(())+ }+ let mut command = Command::new(std::env::current_exe().expect("test binary"));+ command+ .arg("--exact")+ .arg("input_live_open_child_mode")+ .env(CHILD_SOCKET_ENV, socket)+ .env_remove("TMUX")+ .stdin(slave_as_stdio(slave))+ .stdout(slave_as_stdio(slave))+ .stderr(slave_as_stdio(slave));+ // SAFETY: the pre_exec hook is the supported std seam for+ // process-group setup; it runs post-fork pre-exec in the child only+ // and cannot disturb this process.+ unsafe { command.pre_exec(make_process_group) };+ command.spawn().expect("spawn child")+}++fn slave_as_stdio(slave: &OwnedFd) -> Stdio {+ slave.try_clone().expect("clone pty slave").into()+}++fn child_options(socket: PathBuf) -> InteractiveOptions {+ InteractiveOptions {+ models: None,+ socket_path: socket,+ cwd: PathBuf::from("/tmp"),+ session_dir: None,+ script_path: None,+ model_selection: ModelSelection::default(),+ model_catalog: Vec::new(),+ model_configured_providers: std::collections::HashSet::default(),+ model_recent_models: Vec::new(),+ default_thinking_level: None,+ no_session: false,+ // The fresh-launch flow: a NEW session, so the startup chrome+ // mounts before the open (the exact surface the report measured).+ session: SessionSelection::New,+ initial_message: None,+ show_images: true,+ fullscreen_mouse: true,+ theme: "prime".to_string(),+ code_block_indent: " ".to_string(),+ tree_filter_mode: String::new(),+ branch_summary_skip_prompt: false,+ version: "0.0.0".to_string(),+ onboarding: None,+ telemetry_disabled: None,+ client_auth: None,+ traces: None,+ provider_auth: None,+ update_commands: None,+ telemetry: None,+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),+ session_rlm_depth: None,+ prompt_stash: std::sync::Arc::default(),+ session_has_children: false,+ restore_dock_focus: false,+ client_settings: None,+ }+}++/// The supervisor stand-in: the `create` answers immediately, the+/// `attach` stalls past the echo deadline, everything else answers+/// generically. Every received command is recorded for the typed-ahead+/// submit assertion.+struct MockSupervisor {+ listener: std::os::unix::net::UnixListener,+ socket_path: std::path::PathBuf,+}++impl MockSupervisor {+ fn bind(socket: &std::path::Path) -> MockSupervisor {+ MockSupervisor {+ listener: std::os::unix::net::UnixListener::bind(socket).expect("bind mock socket"),+ socket_path: socket.to_path_buf(),+ }+ }++ fn serve(self, commands: &Arc<Mutex<Vec<String>>>, connected: &std::sync::atomic::AtomicBool) {+ let (stream, _) = self.listener.accept().expect("accept");+ connected.store(true, std::sync::atomic::Ordering::SeqCst);+ let write_stream = stream.try_clone().expect("clone mock socket");+ let mut writer = write_stream;+ let mut reader = BufReader::new(stream);++ let hello = json!({+ "type": "daemon_hello",+ "socketPath": self.socket_path.display().to_string(),+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "serverCapabilities": ["kernel_bash_activity"],+ "clientId": "mock",+ });+ write_json(&mut writer, &hello);++ let mut line = String::new();+ loop {+ line.clear();+ match reader.read_line(&mut line) {+ Ok(0) | Err(_) => break,+ Ok(_) => {}+ }+ let Ok(envelope) = serde_json::from_str::<Value>(line.trim()) else {+ continue;+ };+ let id = envelope.get("id").and_then(Value::as_str).unwrap_or("");+ let command = envelope.get("command").cloned().unwrap_or(Value::Null);+ let command_type = command+ .get("type")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ commands+ .lock()+ .expect("commands")+ .push(format!("{command_type}: {command}"));+ match command_type.as_str() {+ "create" => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "create",+ "success": true,+ "data": { "activeSessionId": "s1", "sessionId": "sess-1" },+ }),+ );+ }+ "attach" => {+ // The stall: the open is provably in flight while the+ // keystrokes are expected to echo.+ std::thread::sleep(Duration::from_millis(OPEN_STALL_MS));+ write_json(&mut writer, &attach_data(id));+ }+ _ => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": command_type,+ "success": true,+ "data": {},+ }),+ );+ }+ }+ }+ }+}++fn write_json(writer: &mut std::os::unix::net::UnixStream, value: &Value) {+ let mut line = serde_json::to_string(value).expect("serialize mock frame");+ line.push('\n');+ writer.write_all(line.as_bytes()).expect("write mock frame");+ writer.flush().expect("flush mock frame");+}++/// The attach result: one live session whose transcript carries a marker+/// row — the content frame the fold paints once the stall ends.+fn attach_data(id: &str) -> Value {+ json!({+ "type": "response",+ "id": id,+ "command": "attach",+ "success": true,+ "data": {+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "activeSessionId": "s1",+ "snapshot": {+ "activeSessionId": "s1",+ "summary": { "id": "s1", "cwd": "/tmp" },+ "state": {+ "activeSessionId": "s1",+ "cwd": "/tmp",+ "sessionId": "sess-1",+ "sessionName": "input live probe",+ "model": "faux-1",+ "isStreaming": false,+ "isCompacting": false,+ "sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },+ },+ "messages": [+ { "role": "user", "content": "openprobe marker question", "timestamp": 1 },+ { "role": "assistant", "content": "openprobe settled answer", "provider": "scripted", "model": "faux-1", "timestamp": 2 },+ ],+ "lastEventSequence": 0,+ "lastEventCursor": null,+ },+ "client": { "id": "mock", "capabilities": [] },+ "lastEventSequence": 0,+ "lastEventCursor": null,+ },+ })+}diff --git a/crates/pa-core/src/kernel/manager/events.rs b/crates/pa-core/src/kernel/manager/events.rsindex 024c24d384..662a0222e7 100644--- a/crates/pa-core/src/kernel/manager/events.rs+++ b/crates/pa-core/src/kernel/manager/events.rs@@ -109,6 +109,14 @@ impl Inner {let _ = waiter.send(fields);return;}+ // The MCP status lane (the eager settle and the connections+ // view) resolves the same way: its ids are fresh UUIDs, so+ // the done event settles the listing without ever touching+ // the active execution's slot.+ if let Some(waiter) = lock(&self.guarded).mcp_status_waiters.remove(&id) {+ let _ = waiter.send(fields);+ return;+ }let status = fields.get("status").and_then(Value::as_str)diff --git a/crates/pa-core/src/kernel/manager/mod.rs b/crates/pa-core/src/kernel/manager/mod.rsindex 0e7023f9a4..7884f1490c 100644--- a/crates/pa-core/src/kernel/manager/mod.rs+++ b/crates/pa-core/src/kernel/manager/mod.rs@@ -43,6 +43,11 @@ use crate::kernel::state_snapshot::{const READY_TIMEOUT_MS: u64 = 30_000;const REPAIR_STEP_TIMEOUT_MS: u64 = 30_000;+/// The MCP status lane's settle margin over the per-server timeout (the+/// kernel lists every server concurrently): the reply always settles+/// inside the bound, and a wedged reply errors instead of hanging the+/// caller.+const MCP_STATUS_SETTLE_MARGIN_MS: u64 = 5_000;/// Largest legit frame is an attachment display event, base64 capped at/// `MAX_ATTACHMENT_DATA_CHARS`; a line that cannot complete within this ceiling/// is corruption the protocol repair owns, not output worth buffering until OOM.@@ -352,6 +357,11 @@ struct Guarded {/// Resolvers for out-of-band `factory_activity` done events (the/// factory bridge's lane; ids never collide with cell requests).factory_activity_waiters: HashMap<String, oneshot::Sender<Value>>,+ /// Resolvers for out-of-band `mcp_status` done events (the MCP+ /// status lane; ids never collide with cell requests — the eager+ /// settle and the connections view ride it, and a slow server must+ /// never hold the execution queue a python cell needs).+ mcp_status_waiters: HashMap<String, oneshot::Sender<Value>>,host_inflight: Vec<tokio::task::JoinHandle<()>>,active_execution: Option<Arc<ActiveExecution>>,/// Source of the most recently started cell, retained after it finishes so@@ -496,6 +506,7 @@ impl ReplKernelManager {pending_done_waiters: HashMap::new(),bash_activity_waiters: HashMap::new(),factory_activity_waiters: HashMap::new(),+ mcp_status_waiters: HashMap::new(),host_inflight: Vec::new(),active_execution: None,last_cell_code: None,@@ -893,6 +904,16 @@ impl ReplKernelManager {/// The listing opens each not-yet-connected server (bounded by/// `per_server_timeout_ms`), so the call can take seconds; callers/// bound it with their own deadline.+ ///+ /// The request rides the dedicated MCP status lane (the eager+ /// background settle and the connections view are its callers): the+ /// done event settles by request id, so the listing NEVER occupies+ /// the manager's execution queue — a slow or unreachable server+ /// would otherwise park the user's first python cell behind its+ /// handshake for up to the per-server timeout (the pre-bar review's+ /// finding). The kernel runtime's own dedicated lane keeps its+ /// serve loop free the same way, and the registry's per-server locks+ /// still join an early user call onto the same in-flight open.pub async fn mcp_tool_listing(&self,servers: &[String],@@ -904,36 +925,49 @@ impl ReplKernelManager {if servers.is_empty() {return Some(Vec::new());}- let opts = ExecuteOptions {- internal: true,- ..ExecuteOptions::default()- };- let request = Request::McpStatus {- servers: servers.to_vec(),- timeout_ms: per_server_timeout_ms,+ let request_id = uuid::Uuid::new_v4().to_string();+ let (tx, rx) = oneshot::channel();+ lock(&self.inner.guarded)+ .mcp_status_waiters+ .insert(request_id.clone(), tx);+ let frame = json!({+ "type": "mcp_status",+ "id": request_id,+ "servers": servers,+ "timeout_ms": per_server_timeout_ms,+ });+ if let Err(error) = self.inner.write_line(&frame).await {+ lock(&self.inner.guarded)+ .mcp_status_waiters+ .remove(&request_id);+ self.inner+ .append_diagnostic(&format!("mcp tool listing error: {error:#}"));+ return None;+ }+ // The kernel lists every server concurrently, each bounded by the+ // per-server timeout, so the settle bound is one timeout plus the+ // serve work's margin — a wedged reply never hangs the caller.+ let bound_ms = per_server_timeout_ms.saturating_add(MCP_STATUS_SETTLE_MARGIN_MS);+ let Ok(Ok(fields)) = tokio::time::timeout(Duration::from_millis(bound_ms), rx).await else {+ lock(&self.inner.guarded)+ .mcp_status_waiters+ .remove(&request_id);+ self.inner+ .append_diagnostic("mcp tool listing did not settle inside the per-server bound");+ return None;};- match self.enqueue_request(request, "", opts, None).await {- Ok(r) if r.result.status == ExecuteStatus::Ok => {- let connections = r- .done_fields- .as_ref()- .and_then(|fields| fields.get("connections"))- .and_then(Value::as_array)- .cloned();+ match fields.get("status").and_then(Value::as_str) {+ Some("ok") => {+ let connections = fields.get("connections").and_then(Value::as_array).cloned();Some(connections.unwrap_or_default())}- Ok(r) => {+ status => {self.inner.append_diagnostic(&format!("mcp tool listing failed: {}",- describe_failure(&r.result)+ status.unwrap_or("unset status")));None}- Err(error) => {- self.inner- .append_diagnostic(&format!("mcp tool listing error: {error:#}"));- None- }}}diff --git a/crates/pa-core/src/kernel/manager/teardown.rs b/crates/pa-core/src/kernel/manager/teardown.rsindex db4bc60254..4e28721e67 100644--- a/crates/pa-core/src/kernel/manager/teardown.rs+++ b/crates/pa-core/src/kernel/manager/teardown.rs@@ -156,6 +156,7 @@ impl Inner {g.pending_done_waiters.clear();g.bash_activity_waiters.clear();g.factory_activity_waiters.clear();+ g.mcp_status_waiters.clear();let had_background_work = !g.background_bash_handles.is_empty();g.background_bash_handles.clear();// Stale pre-teardown background output must not surface after a restart.diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex 2b73a2fe7b..fb8a53ab23 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -17,6 +17,12 @@ use crate::skills::PromptTemplate;use super::{AgentSession, PromptOptions, PromptOutcome};+/// The background MCP settle's per-server open bound (the kernel's+/// `mcp_status` listing opens each not-yet-connected server bounded per+/// server; the settle is off every user-visible path, so the bound only+/// keeps the background task from outliving a wedged server forever).+const MCP_SETTLE_PER_SERVER_TIMEOUT_MS: u64 = 10_000;+/// Everything needed to assemble a session.#[derive(Default)]pub struct SessionEngineConfig {@@ -516,6 +522,27 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S&& active_tool_names.iter().any(|name| name == "ipython"){provisioner.prewarm();+ // The MCP settle rides the same background posture (the+ // parallel-startup rule: nothing user-visible waits on the MCP+ // spawn/settle; the join point is first use): once the kernel is+ // up, the configured generic servers open in the background via+ // the bounded `mcp_status` listing the connections view uses, so+ // tool discovery is warm by the first turn. A tool call or+ // listing that arrives first is never raced to an error — the+ // runtime's registry serializes per-server opens on its lock and+ // then reuses the open connection, so the earliest user of a+ // server joins the settle's in-flight open and succeeds.+ let settle_servers = generic_mcp_servers.clone();+ let settle_provisioner = provisioner.clone();+ tokio::spawn(async move {+ if settle_provisioner.ensure(None, None).await.is_ok() {+ if let Some(manager) = settle_provisioner.manager() {+ let _ = manager+ .mcp_tool_listing(&settle_servers, MCP_SETTLE_PER_SERVER_TIMEOUT_MS)+ .await;+ }+ }+ });}let prompt_guidelines = config.prompt_guidelines.clone();diff --git a/crates/pa-core/tests/kernel_mcp_settle.rs b/crates/pa-core/tests/kernel_mcp_settle.rsnew file mode 100644index 0000000000..102fe781e9--- /dev/null+++ b/crates/pa-core/tests/kernel_mcp_settle.rs@@ -0,0 +1,517 @@+// The Tier-C/D ruling (fleet-uniform, 2026-09-28) - this target's own+// crate root: the same bounded-boundary disposition as src/lib.rs+// (large_futures/too_many_lines/the cast family; details there).+#![allow(+ clippy::large_futures,+ clippy::too_many_lines,+ clippy::cast_possible_truncation,+ clippy::cast_possible_wrap,+ clippy::cast_sign_loss,+ clippy::cast_precision_loss+)]++//! Verifier for the input-latency lane's kernel/MCP posture (the operator+//! rulings of 2026-10-03: "kernel spawns eagerly at startup, fully+//! background; nothing user-visible waits; kernel-needing ops await the+//! in-flight boot handle robustly" and "MCP spawn/settle also non-blocking+//! for time-to-textbox; eager background spawn, joined only at first use"),+//! driven in-process through `create_session` against a REAL kernel:+//!+//! - a kernel-needing op that arrives while the eager boot is still in+//! flight waits for that boot and then succeeds (the join memo: one+//! boot, never a second build);+//! - the configured generic MCP servers settle in the BACKGROUND once the+//! kernel is up — the server process spawns with no user use anywhere+//! (red on a lane-less tree: nothing else opens it) — and the FIRST+//! use, issued while the settle's open is still in flight, waits for+//! that open and succeeds instead of erroring.+#![cfg(unix)]++use std::path::PathBuf;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use pa_agent::scripted::{tool_call_turn_steps, ScriptedProvider, ScriptedTurn};+use pa_core::kernel::shared::{ExecuteOptions, ExecuteStatus};+use pa_core::session_engine::engine::{create_session, SessionEngineConfig};+use pa_core::session_engine::PromptOutcome;+use serde_json::json;++/// The two tests share the process env (the kernel-python override is+/// process-global), so they serialize through this lock.+static LIVE_KERNEL_LOCK: Mutex<()> = Mutex::new(());++/// The kernel Python with prime-agent-runtime installed (the interpreter+/// the session-path provisioner resolves). Skipped (with a note) on+/// machines without a live install; set `PA_CORE_KERNEL_PYTHON` to point+/// at an explicit interpreter instead.+fn kernel_python() -> Option<PathBuf> {+ if let Some(explicit) = std::env::var_os("PA_CORE_KERNEL_PYTHON") {+ let explicit = PathBuf::from(explicit);+ assert!(+ explicit.exists(),+ "PA_CORE_KERNEL_PYTHON {} not found",+ explicit.display()+ );+ return Some(explicit);+ }+ let candidate = PathBuf::from(std::env::var("HOME").map_or_else(+ |_| "/home/ubuntu/.prime/agent/kernel-venv/bin/python".to_string(),+ |home| format!("{home}/.prime/agent/kernel-venv/bin/python"),+ ));+ if candidate.exists() {+ return Some(candidate);+ }+ eprintln!(+ "kernel python {} not found; skipping live kernel test",+ candidate.display()+ );+ None+}++/// Scoped process-env overrides: applied on construction, restored on drop.+/// The tests hold [`LIVE_KERNEL_LOCK`], so nothing races the env.+struct EnvOverride {+ saved: Vec<(String, Option<String>)>,+}++impl EnvOverride {+ fn apply(pairs: &[(&str, Option<String>)]) -> Self {+ let saved = pairs+ .iter()+ .map(|(key, _)| ((*key).to_string(), std::env::var(key).ok()))+ .collect();+ for (key, value) in pairs {+ match value {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ EnvOverride { saved }+ }+}++impl Drop for EnvOverride {+ fn drop(&mut self) {+ for (key, value) in &self.saved {+ match value {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ }+}++/// The agent-loop model shape the engine config takes.+fn scripted_model() -> pa_agent::types::Model {+ serde_json::from_value(json!({+ "id": "faux-1", "name": "Faux", "api": "test", "provider": "faux",+ "baseUrl": "http://localhost", "reasoning": false,+ "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },+ "contextWindow": 200_000, "maxTokens": 4_000+ }))+ .expect("faux loop model")+}++/// Wait for the eager boot to land (a background task).+async fn wait_for_kernel_boot(+ provisioner: &Arc<pa_core::kernel::provisioner::IpythonKernelProvisioner>,+) {+ let deadline = Instant::now() + Duration::from_secs(120);+ loop {+ if provisioner.has_running_kernel() {+ return;+ }+ assert!(+ Instant::now() < deadline,+ "the eagerly booted kernel never came up"+ );+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+}++/// A kernel-needing op (the model's `ipython` tool call) that arrives while+/// the eager boot is still in flight waits for THAT boot and succeeds: the+/// join memo serves one boot, never a second build, and the cell runs.+#[tokio::test]+// The std Mutex guard for LIVE_KERNEL_LOCK rides the awaits on purpose+// (the lock's own doc above): the kernel-python env is process-global, so+// the tests serialize their whole kernel lifetimes, not just their setup.+#[allow(clippy::await_holding_lock)]+async fn a_kernel_needing_op_mid_boot_joins_the_in_flight_build_and_succeeds() {+ let Some(kernel_python) = kernel_python() else {+ return;+ };+ let _lock = LIVE_KERNEL_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let dir = tempfile::tempdir().expect("temp dir");+ let agent_dir = dir.path().join("agent");+ let cwd = dir.path().join("project");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");+ std::fs::create_dir_all(&cwd).expect("cwd");++ // Hermeticity: the kernel runs on the ambient product venv, and no+ // ambient agent state leaks in.+ let _env = EnvOverride::apply(&[+ (+ "PRIME_AGENT_KERNEL_PYTHON",+ Some(kernel_python.display().to_string()),+ ),+ ("PRIME_AGENT_CODING_AGENT_DIR", None),+ ("PRIME_API_KEY", None),+ ]);++ let model = scripted_model();+ let provider = Arc::new(ScriptedProvider::new(model.clone()));+ // One turn: the model calls the kernel cell, then the turn settles.+ provider.push_turn(ScriptedTurn::Events(tool_call_turn_steps(+ &model,+ Some("calling the kernel"),+ vec![(+ "cell-1",+ "ipython",+ json!({ "code": "print('JOINED_BOOT_OK')" }),+ )],+ )));+ provider.push_text_turn("the turn settles");++ let engine = create_session(SessionEngineConfig {+ cwd,+ agent_dir,+ model: Some(model),+ stream_fn: Some(provider.stream_fn()),+ tools: Vec::new(),+ prewarm_ipython_kernel: Some(true),+ ..Default::default()+ })+ .await+ .expect("create the session");++ // The mid-boot premise: the eager boot the create spawned is still in+ // flight, so the create itself never waited on it.+ let provisioner = engine+ .kernel_provisioner_weak()+ .upgrade()+ .expect("the session carries its kernel provisioner");+ assert!(+ !provisioner.has_running_kernel(),+ "the create must return with the eager boot still in flight"+ );++ // The kernel-needing op, issued mid-boot: it joins the in-flight build+ // (the memoized startup), waits it out, and the cell succeeds.+ let outcome = engine+ .prompt(+ "run the cell",+ pa_core::session_engine::PromptOptions::default(),+ )+ .await+ .expect("prompt");+ assert_eq!(outcome, PromptOutcome::Prompt);+ engine.session.agent().wait_for_idle().await;++ let serialized = {+ let entries = engine.session.entries().await;+ serde_json::to_string(&entries).expect("entries json")+ };+ assert!(+ serialized.contains("JOINED_BOOT_OK"),+ "the mid-boot tool call never ran its cell: {serialized}"+ );+ assert!(+ provisioner.has_running_kernel(),+ "the joined boot must be the running kernel"+ );+}++/// The stdio MCP server fixture: it records its spawn to `marker`, delays+/// its handshake by [`SETTLE_SERVER_OPEN_DELAY_MS`], then serves one echo+/// tool. The delay is what keeps the settle's open in flight when the+/// test's first use arrives.+const SETTLE_SERVER_OPEN_DELAY_MS: u64 = 1_500;++/// The queue-contention fixture's handshake delay: long enough that a+/// python cell queued behind the listing can never meet the test's+/// bound (the listing holds the kernel's execution queue for the whole+/// handshake on a runtime without the dedicated MCP lane).+const HANGING_SERVER_OPEN_DELAY_MS: u64 = 8_000;++/// The cell's completion bound: half the hanging server's handshake, so+/// a queued shape (the cell waiting out the handshake) fails by seconds+/// while the dedicated-lane shape (the cell never touching the MCP+/// work) passes with margin.+const CELL_COMPLETION_BOUND_MS: u64 = 4_000;++fn slow_echo_server_code(handshake_delay_ms: u64) -> String {+ r#"import sys+import time+from pathlib import Path++Path(sys.argv[1]).write_text("started", encoding="utf-8")+time.sleep({HANDSHAKE_DELAY_MS} / 1000)++from mcp.server.mcpserver import MCPServer++server = MCPServer("settle-fixture")+++def echo(text: str) -> str:+ """Echo the text back."""+ return text+++server.run()+"#+ .replace("{HANDSHAKE_DELAY_MS}", &handshake_delay_ms.to_string())+}++/// The configured generic MCP servers settle in the background once the+/// kernel is up (the fixture server's process spawns with no user use+/// anywhere — red on a tree without the settle), and the first use,+/// issued while the settle's open is still mid-handshake, waits for that+/// open and succeeds instead of erroring (the registry's per-server lock+/// joins both callers onto one open).+#[tokio::test]+// LIVE_KERNEL_LOCK held across the awaits on purpose (the lock's own doc+// above): the kernel-python env is process-global, so the tests serialize+// their whole kernel lifetimes.+#[allow(clippy::await_holding_lock)]+async fn generic_mcp_servers_settle_in_the_background_and_first_use_joins_the_open() {+ let Some(kernel_python) = kernel_python() else {+ return;+ };+ let _lock = LIVE_KERNEL_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let dir = tempfile::tempdir().expect("temp dir");+ let agent_dir = dir.path().join("agent");+ let cwd = dir.path().join("project");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");+ std::fs::create_dir_all(&cwd).expect("cwd");+ let marker = dir.path().join("settle-server-started");+ let server_script = dir.path().join("slow_echo_server.py");+ std::fs::write(+ &server_script,+ slow_echo_server_code(SETTLE_SERVER_OPEN_DELAY_MS),+ )+ .expect("server script");++ // The user-declared stdio server the kernel's generic MCP surface+ // resolves through the `mcp.config` host request.+ std::fs::write(+ agent_dir.join("settings.json"),+ json!({+ "mcpServers": {+ "settle-fixture": {+ "type": "stdio",+ "command": kernel_python.display().to_string(),+ "args": [+ server_script.display().to_string(),+ marker.display().to_string(),+ ],+ },+ },+ })+ .to_string(),+ )+ .expect("settings");++ let _env = EnvOverride::apply(&[+ (+ "PRIME_AGENT_KERNEL_PYTHON",+ Some(kernel_python.display().to_string()),+ ),+ ("PRIME_AGENT_CODING_AGENT_DIR", None),+ ("PRIME_API_KEY", None),+ ]);++ let model = scripted_model();+ let provider = Arc::new(ScriptedProvider::new(model.clone()));+ let engine = create_session(SessionEngineConfig {+ cwd,+ agent_dir,+ model: Some(model),+ stream_fn: Some(provider.stream_fn()),+ tools: Vec::new(),+ prewarm_ipython_kernel: Some(true),+ ..Default::default()+ })+ .await+ .expect("create the session");++ let provisioner = engine+ .kernel_provisioner_weak()+ .upgrade()+ .expect("the session carries its kernel provisioner");+ wait_for_kernel_boot(&provisioner).await;++ // The settle, with no user use anywhere: the fixture server's process+ // spawns in the background once the kernel is up. On a tree without+ // the settle this wait times out — nothing else opens the server.+ let deadline = Instant::now() + Duration::from_secs(20);+ while !marker.exists() {+ assert!(+ Instant::now() < deadline,+ "the generic MCP server never settled in the background"+ );+ tokio::time::sleep(Duration::from_millis(25)).await;+ }++ // First use, while the settle's open is still mid-handshake (the+ // fixture's spawn delay): the call joins the in-flight open on the+ // registry's per-server lock, waits it out, and succeeds.+ let manager = provisioner.manager().expect("the booted kernel's manager");+ let result = manager+ .execute(+ "result = await mcp.call_tool('settle-fixture', 'echo', {'text': 'probe'})\nresult",+ ExecuteOptions::default(),+ )+ .await+ .expect("the mcp cell must execute");+ assert_eq!(+ result.status,+ ExecuteStatus::Ok,+ "the first use must wait for the settle's open and succeed; stderr: {}",+ result.stderr+ );+ let echoed = result.result.unwrap_or_default();+ assert!(+ echoed.contains("probe"),+ "the echo tool's answer must come back; got {echoed:?} (stdout {})",+ result.stdout+ );+}++/// The eager MCP settle must never contend with the user's first-turn+/// path (the pre-bar review's finding: the eager `mcp_status` used to+/// ride the kernel's single execution queue, so a hanging server's+/// handshake parked the first `ipython` cell behind it for up to the+/// per-server timeout). The kernel runtime's dedicated MCP lane keeps+/// status/open work off the cell queue: with the settle's listing+/// provably in flight (the fixture server spawned, its handshake still+/// holding the listing), the user's first python cell must complete+/// without waiting out the handshake.+///+/// Red on a runtime without the lane (the cell queues behind the+/// listing); green with it.+#[tokio::test]+// LIVE_KERNEL_LOCK held across the awaits on purpose (the lock's own doc+// above): the kernel-python env is process-global, so the tests serialize+// their whole kernel lifetimes.+#[allow(clippy::await_holding_lock)]+async fn the_first_python_cell_never_waits_behind_the_eager_mcp_status() {+ let Some(kernel_python) = kernel_python() else {+ return;+ };+ let _lock = LIVE_KERNEL_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let dir = tempfile::tempdir().expect("temp dir");+ let agent_dir = dir.path().join("agent");+ let cwd = dir.path().join("project");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");+ std::fs::create_dir_all(&cwd).expect("cwd");+ let marker = dir.path().join("hanging-server-started");+ let server_script = dir.path().join("hanging_echo_server.py");+ std::fs::write(+ &server_script,+ slow_echo_server_code(HANGING_SERVER_OPEN_DELAY_MS),+ )+ .expect("server script");++ std::fs::write(+ agent_dir.join("settings.json"),+ json!({+ "mcpServers": {+ "hanging-fixture": {+ "type": "stdio",+ "command": kernel_python.display().to_string(),+ "args": [+ server_script.display().to_string(),+ marker.display().to_string(),+ ],+ },+ },+ })+ .to_string(),+ )+ .expect("settings");++ let _env = EnvOverride::apply(&[+ (+ "PRIME_AGENT_KERNEL_PYTHON",+ Some(kernel_python.display().to_string()),+ ),+ ("PRIME_AGENT_CODING_AGENT_DIR", None),+ ("PRIME_API_KEY", None),+ ]);++ let model = scripted_model();+ let provider = Arc::new(ScriptedProvider::new(model.clone()));+ // One turn: the model runs a python cell, then the turn settles.+ provider.push_turn(ScriptedTurn::Events(tool_call_turn_steps(+ &model,+ Some("running the cell"),+ vec![("cell-1", "ipython", json!({ "code": "print('CELL_OK')" }))],+ )));+ provider.push_text_turn("the turn settles");++ let engine = create_session(SessionEngineConfig {+ cwd,+ agent_dir,+ model: Some(model),+ stream_fn: Some(provider.stream_fn()),+ tools: Vec::new(),+ prewarm_ipython_kernel: Some(true),+ ..Default::default()+ })+ .await+ .expect("create the session");++ let provisioner = engine+ .kernel_provisioner_weak()+ .upgrade()+ .expect("the session carries its kernel provisioner");+ wait_for_kernel_boot(&provisioner).await;++ // The settle is provably in flight: the fixture server spawned (its+ // process marker landed), and its handshake still holds the listing.+ let deadline = Instant::now() + Duration::from_secs(20);+ while !marker.exists() {+ assert!(+ Instant::now() < deadline,+ "the eager MCP settle never reached the hanging server"+ );+ tokio::time::sleep(Duration::from_millis(25)).await;+ }++ // The user's first python cell, issued with the listing in flight:+ // it must complete inside the bound — a cell queued behind the+ // handshake cannot.+ let cell_started = Instant::now();+ let outcome = engine+ .prompt(+ "run the cell",+ pa_core::session_engine::PromptOptions::default(),+ )+ .await+ .expect("prompt");+ assert_eq!(outcome, PromptOutcome::Prompt);+ engine.session.agent().wait_for_idle().await;+ let cell_elapsed = cell_started.elapsed();+ assert!(+ cell_elapsed < Duration::from_millis(CELL_COMPLETION_BOUND_MS),+ "the first python cell waited {cell_elapsed:?} behind the eager MCP status — the settle must never contend with the user's first-turn path"+ );++ let serialized = {+ let entries = engine.session.entries().await;+ serde_json::to_string(&entries).expect("entries json")+ };+ assert!(+ serialized.contains("CELL_OK"),+ "the cell never ran: {serialized}"+ );+}diff --git a/crates/pa-daemon/src/scheduling_catalog.rs b/crates/pa-daemon/src/scheduling_catalog.rsindex f82257e496..577da2687e 100644--- a/crates/pa-daemon/src/scheduling_catalog.rs+++ b/crates/pa-daemon/src/scheduling_catalog.rs@@ -243,6 +243,39 @@ impl Supervisor {});}+ /// Warm the passive scheduled-jobs snapshot at daemon boot (the+ /// input-latency lane): the first selector-less catalog read after boot+ /// would otherwise run the whole session-artifacts scan inline — the+ /// operator's 289-partition tree measured ~835ms inside the client's+ /// open, past the interactive surface's dock fold — while the boot+ /// itself has idle time before the first client arrives. The warmup is+ /// the same shared scan a cold read runs (one scan, generation-stamped,+ /// stored by the identical rules); every later invalidation, mutation,+ /// and stale-while-revalidate refresh keeps its semantics. A client+ /// that connects before the scan lands joins it exactly as today.+ pub(crate) fn spawn_passive_catalog_warmup(self: &Arc<Self>) {+ let supervisor = Arc::clone(self);+ tokio::spawn(async move {+ let _ = supervisor.shared_passive_scan().await;+ });+ }++ /// The boot warmup's adopt-pass ordering (serve's watch dance,+ /// lifted here for the pin below): the warmup only starts once the+ /// boot's adopt pass has settled the registry (or its signal sender+ /// is gone — the fail-open path: a degraded boot keeps the+ /// pre-warmup cold-read behavior, never a colder one).+ pub(crate) async fn wait_for_adoption_signal(signal: &mut tokio::sync::watch::Receiver<bool>) {+ loop {+ if *signal.borrow() {+ return;+ }+ if signal.changed().await.is_err() {+ return;+ }+ }+ }+/// Invalidate the passive snapshot (TS #2487/// `invalidatePassiveScheduledJobs`): claim the publish epoch so an/// in-flight scan can no longer store, then drop the snapshot — every@@ -858,3 +891,176 @@ impl Supervisor {)}}++#[cfg(test)]+mod tests {+ use super::*;++ /// The passive-catalog warmup (the input-latency lane): the boot's+ /// warm scan stores the snapshot with NO read anywhere, and the first+ /// catalog read serves that stored snapshot instead of scanning the+ /// artifacts tree inline. The second half is the discriminating+ /// observable: after the warm snapshot lands, the fixture's+ /// `scheduled-jobs.json` is deleted behind the daemon's back, and the+ /// first read STILL answers the warm row — a read that scanned inline+ /// at that moment would see the deleted fixture and answer nothing.+ #[tokio::test]+ async fn the_passive_catalog_warms_at_boot_and_the_first_read_serves_the_snapshot() {+ let dir = tempfile::tempdir().expect("temp dir");+ let agent_dir = dir.path().join("agent");+ let sessions_dir = agent_dir.join("sessions");+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");+ let session_file = sessions_dir.join("warm-1.jsonl");+ let session_lines = [+ json!({+ "type": "session", "version": 3, "id": "warm-1",+ "timestamp": "2026-10-04T00:00:00.000Z", "cwd": "/c",+ }),+ json!({+ "type": "session_state", "id": "warm-1",+ "timestamp": "2026-10-04T00:00:01.000Z",+ "state": { "status": "active" },+ }),+ ];+ std::fs::write(+ &session_file,+ session_lines+ .iter()+ .map(std::string::ToString::to_string)+ .collect::<Vec<_>>()+ .join("\n")+ + "\n",+ )+ .expect("session file");+ let artifacts = agent_dir.join("session-artifacts").join("warm-1");+ std::fs::create_dir_all(&artifacts).expect("artifacts partition");+ std::fs::write(+ artifacts.join("scheduled-jobs.json"),+ json!({+ "jobs": [{+ "id": "hb-1",+ "status": "active",+ "activeSessionId": "warm-1",+ "sessionId": "warm-1",+ "sessionFile": session_file.display().to_string(),+ "cwd": dir.path().display().to_string(),+ "prompt": "the warm heartbeat",+ "schedule": { "kind": "interval", "expression": "", "intervalMs": 60000 },+ "createdAt": "2026-10-04T00:00:02.000Z",+ "updatedAt": "2026-10-04T00:00:02.000Z",+ "nextRunAt": "2026-10-04T00:01:02.000Z",+ }],+ })+ .to_string(),+ )+ .expect("scheduled jobs");++ let supervisor = Arc::new(+ Supervisor::new(crate::supervisor::SupervisorOptions {+ socket_path: dir.path().join("daemon.sock"),+ agent_dir: agent_dir.clone(),+ })+ .expect("supervisor"),+ );++ // The boot warmup (what `serve` spawns beside its other boot+ // passes): the scan runs with no catalog read anywhere.+ supervisor.spawn_passive_catalog_warmup();++ // The warm snapshot lands on its own: one row, the fixture's+ // heartbeat. No `heartbeats_list`/`cron_list` was issued.+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ loop {+ let warm_rows = supervisor+ .passive_catalog+ .lock()+ .unwrap()+ .as_ref()+ .map(|snapshot| snapshot.rows.len());+ if warm_rows == Some(1) {+ break;+ }+ assert!(+ std::time::Instant::now() < deadline,+ "the boot warmup never stored the passive snapshot"+ );+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }++ // The first read must serve the stored snapshot, not a fresh+ // scan: the fixture's artifact vanishes behind the daemon's back+ // (no mutation was issued, so no invalidation owes a re-scan),+ // and the read still answers the warm row.+ std::fs::remove_file(artifacts.join("scheduled-jobs.json")).expect("delete fixture");+ let rows = supervisor.passive_catalog_rows(false).await;+ assert_eq!(+ rows.len(),+ 1,+ "the first read must serve the warm snapshot instead of rescanning"+ );+ assert_eq!(rows[0].job.id, "hb-1");+ assert_eq!(rows[0].job.session_file, session_file.display().to_string());+ }++ /// The boot warmup's adopt-pass ordering (the pre-bar review's race+ /// finding): the warmup's scan consults the registry's live-worker+ /// filter, so it must wait out the boot's adopt pass — a scan that+ /// raced adoption would cache the just-adopted worker's artifacts as+ /// a passive row and serve the stale row for the snapshot's refresh+ /// window (adoption never invalidates the catalog). The pin: with the+ /// adopt signal unfired the snapshot never lands; once the signal+ /// fires, it does.+ #[tokio::test]+ async fn the_boot_warmup_waits_out_the_adopt_pass_before_scanning() {+ let dir = tempfile::tempdir().expect("temp dir");+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(agent_dir.join("sessions")).expect("sessions dir");+ let supervisor = Arc::new(+ Supervisor::new(crate::supervisor::SupervisorOptions {+ socket_path: dir.path().join("daemon.sock"),+ agent_dir: agent_dir.clone(),+ })+ .expect("supervisor"),+ );++ let (adoption_tx, adoption_rx) = tokio::sync::watch::channel(false);++ // The negative pin is on the WAITER itself, not on the scan's+ // downstream effect: with the signal unfired the helper must stay+ // pending for the whole window (a helper that returned early+ // would finish in microseconds — the window catches it+ // deterministically; a correct helper can only return on the+ // signal or the sender's death, neither of which happens here).+ let mut waiter = {+ let supervisor = Arc::clone(&supervisor);+ let mut adoption_rx = adoption_rx;+ tokio::spawn(async move {+ Supervisor::wait_for_adoption_signal(&mut adoption_rx).await;+ supervisor.spawn_passive_catalog_warmup();+ })+ };+ let still_waiting =+ tokio::time::timeout(std::time::Duration::from_millis(150), &mut waiter).await;+ assert!(+ still_waiting.is_err(),+ "the warmup helper returned before the adopt pass signaled"+ );++ // The adopt pass settles: the waiter completes and the scan+ // lands (the positive pin is a poll with a real deadline — a+ // failure names the missing snapshot).+ adoption_tx.send(true).expect("signal adoption");+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ while supervisor.passive_catalog.lock().unwrap().is_none() {+ assert!(+ std::time::Instant::now() < deadline,+ "the warmup never scanned after the adopt pass signaled"+ );+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ tokio::time::timeout(std::time::Duration::from_secs(5), waiter)+ .await+ .expect("the warmup waiter never completed")+ .expect("the warmup task");+ }+}diff --git a/crates/pa-daemon/src/supervisor.rs b/crates/pa-daemon/src/supervisor.rsindex a3bff131ce..015aa10a33 100644--- a/crates/pa-daemon/src/supervisor.rs+++ b/crates/pa-daemon/src/supervisor.rs@@ -472,6 +472,10 @@ impl Supervisor {// awaits this task (spec §6 step 2's create-or-adopt order: kept// workers relaunch from their descriptors first, the roster covers// the rest).+ // The adopt pass's completion signal: the passive-catalog warmup+ // waits on it (see below) while the restore pass keeps awaiting+ // the task handle itself.+ let (adoption_tx, adoption_signal) = tokio::sync::watch::channel(false);let adoption = {let supervisor = Arc::clone(&self);let boot = match roster.as_ref() {@@ -488,6 +492,7 @@ impl Supervisor {};tokio::spawn(async move {supervisor.adopt_persisted_workers(boot).await;+ let _ = adoption_tx.send(true);})};{@@ -497,6 +502,30 @@ impl Supervisor {});}+ // Warm the passive scheduled-jobs snapshot (the input-latency+ // lane): the first selector-less `heartbeats_list`/`cron_list`+ // after boot would otherwise scan the whole session-artifacts tree+ // inline while the interactive client's open waits on it. The scan+ // waits out the boot's adopt pass first (the pre-bar review's+ // race finding): the scan's live-worker filter consults the+ // registry, so a scan that raced the adopt pass would cache the+ // just-adopted worker's artifacts as a passive row and serve the+ // stale row for the snapshot's whole refresh window — adoption+ // never invalidates the catalog. After the signal (a plain+ // startup's adopt pass is ms-scale) the scan still lands well+ // before the first client read; every invalidation and refresh+ // rule is unchanged. The signal is fail-open: an adopt pass that+ // died without signaling still warms (a degraded boot keeps the+ // pre-warmup cold-read behavior, never a colder one).+ {+ let supervisor = Arc::clone(&self);+ let mut adopted = adoption_signal;+ tokio::spawn(async move {+ Supervisor::wait_for_adoption_signal(&mut adopted).await;+ supervisor.spawn_passive_catalog_warmup();+ });+ }+// Session-archive sweep (roadmap: the sessions directory must not// grow forever): boot sweep, then the periodic re-sweep at the TS// idle-eviction cadence. Housekeeping only — it never gates serving.diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rsindex fe5af5ee99..d622e471b6 100644--- a/crates/pa-tui/src/interactive/run.rs+++ b/crates/pa-tui/src/interactive/run.rs@@ -350,12 +350,19 @@ async fn run_interactive_surface(// clear rides the first draw's single flush, which carries the// complete frame — no splash flash, no panel appearing late over a// half-open view.- if !headless+ //+ // The same predicate names the surface the opening phase below may+ // repaint: a NEW chat's chrome already mounted (its echo frames+ // paint at the frame scheduler's cadence), while a held surface+ // (a direct open into an existing session) and headless capture+ // runs never paint during the open — the first draw stays the+ // open's content frame.+ let opening_paints = !headless&& matches!(&options.session,SessionSelection::New | SessionSelection::NewChild { .. }- )- {+ );+ if opening_paints {if let Some(renderer) = renderer.is_terminal_mut() {crate::app::draw(renderer, &mut view)?;}@@ -368,63 +375,296 @@ async fn run_interactive_surface(// single attempt. The first attempt reuses the pre-mount connection; a// retry reconnects fresh. Only the open waits — once the session is up,// the reconnect loop owns the mid-chat restart window.+ //+ // The open runs as a BACKGROUND task: the opening phase below serves+ // keystrokes while it completes. TS `init()` runs `ui.start()` (the+ // input surface is live) and awaits `rebindCurrentSession()` on an+ // already-serving event loop; the port's old shape ran the whole open+ // pipeline before the run loop took its first input, so time-to-type+ // waited on the create, the attach, the dock folds, and every daemon+ // readiness behind them (the operator's input-latency report: first+ // frame 40-52ms, keystroke echo ~250ms later warm, ~0.6-1.6s cold).let mut first_connection = Some((client, events));- let open_outcome = crate::update_restart_wait::wait_through_update_restart(- route == SessionOpenRoute::AgentsView,- crate::update_restart_wait::DAEMON_UPDATE_RESTART_OPEN_WAIT_MS,- crate::update_restart_wait::DAEMON_UPDATE_RESTART_OPEN_RETRY_MS,- || {- // The attempt future owns everything it touches (an `async- // move` over clones taken here): an `FnMut` closure's captures- // may not escape into the returned future, so the synchronous- // body moves the pieces out instead.- let first = first_connection.take();- let options = options.clone();- let notes_tx = notes_tx.clone();- let compaction_abort_tx = compaction_abort_tx.clone();- let prompt_tx = prompt_tx.clone();- let share_tx = share_tx.clone();- let reload_tx = reload_tx.clone();- let traces_upload_tx = traces_upload_tx.clone();- let update_tx = update_tx.clone();- let catalog_tx = catalog_tx.clone();- let auth_panel_tx = auth_panel_tx.clone();- let heartbeats_tx = heartbeats_tx.clone();- let bash_tx = bash_tx.clone();- let factory_tx = factory_tx.clone();- let commands_tx = commands_tx.clone();- async move {- let (client, events) = match first {- Some(first) => first,- None => DaemonClient::connect(&options.socket_path)- .await- .with_context(|| "the interactive UI could not attach to the daemon")?,+ let mut open_task = {+ let options = options.clone();+ let notes_tx = notes_tx.clone();+ let compaction_abort_tx = compaction_abort_tx.clone();+ let prompt_tx = prompt_tx.clone();+ let share_tx = share_tx.clone();+ let reload_tx = reload_tx.clone();+ let traces_upload_tx = traces_upload_tx.clone();+ let update_tx = update_tx.clone();+ let catalog_tx = catalog_tx.clone();+ let auth_panel_tx = auth_panel_tx.clone();+ let heartbeats_tx = heartbeats_tx.clone();+ let bash_tx = bash_tx.clone();+ let factory_tx = factory_tx.clone();+ let commands_tx = commands_tx.clone();+ let waits_through_update_restart = route == SessionOpenRoute::AgentsView;+ tokio::spawn(async move {+ crate::update_restart_wait::wait_through_update_restart(+ waits_through_update_restart,+ crate::update_restart_wait::DAEMON_UPDATE_RESTART_OPEN_WAIT_MS,+ crate::update_restart_wait::DAEMON_UPDATE_RESTART_OPEN_RETRY_MS,+ || {+ // The attempt future owns everything it touches (an+ // `async move` over clones taken here): an `FnMut`+ // closure's captures may not escape into the returned+ // future, so the synchronous body moves the pieces out+ // instead.+ let first = first_connection.take();+ let options = options.clone();+ let notes_tx = notes_tx.clone();+ let compaction_abort_tx = compaction_abort_tx.clone();+ let prompt_tx = prompt_tx.clone();+ let share_tx = share_tx.clone();+ let reload_tx = reload_tx.clone();+ let traces_upload_tx = traces_upload_tx.clone();+ let update_tx = update_tx.clone();+ let catalog_tx = catalog_tx.clone();+ let auth_panel_tx = auth_panel_tx.clone();+ let heartbeats_tx = heartbeats_tx.clone();+ let bash_tx = bash_tx.clone();+ let factory_tx = factory_tx.clone();+ let commands_tx = commands_tx.clone();+ async move {+ let (client, events) = match first {+ Some(first) => first,+ None => DaemonClient::connect(&options.socket_path)+ .await+ .with_context(|| {+ "the interactive UI could not attach to the daemon"+ })?,+ };+ let session = SessionUi::open(+ client,+ &options,+ notes_tx,+ compaction_abort_tx,+ prompt_tx,+ share_tx,+ reload_tx,+ update_tx,+ traces_upload_tx,+ catalog_tx,+ auth_panel_tx,+ crate::session_ui::ActivityUpdates {+ heartbeats: heartbeats_tx,+ bash: bash_tx,+ factory: factory_tx,+ commands: commands_tx,+ },+ )+ .await?;+ Ok((events, session))+ }+ },+ )+ .await+ })+ };+ // The opening phase: the input surface serves keystrokes while the+ // open task runs (AGENTS.md "Performance and the critical path": the+ // input box mounts and accepts keystrokes without waiting on+ // daemon/kernel/config readiness that is not user-visible work).+ // Editor-level keys echo into the mounted startup chrome at the frame+ // scheduler's cadence; everything else (submits, commands, overlay+ // keys) queues in `pending` — the same deque the run loop drains —+ // so typed-ahead is delivered, in order, the moment the open lands:+ // never lost, never errored. The open's own result (success or the+ // daemon-refusal arms below) is unchanged; only the WAIT moved off+ // the input path.+ //+ // ORDERING (the contract the headless plans pin): the editor always+ // holds a PREFIX of the user's input stream. The first input that+ // must queue (a submit, an overlay key, a mouse report) parks the+ // echo path for the rest of the phase — every later input queues+ // behind it, so a typed `H` can never land in the editor ahead of a+ // queued `ctrl+home` the user pressed first.+ let mut pending: VecDeque<UiInput> = VecDeque::new();+ // Base parity for the stash restore (finding #3): a session-reopen+ // launch (Resume/Attach — the shape that can carry a stashed draft)+ // never accepts typed-ahead into the editor during the open. The+ // fold's `restore_prompt_stash_on_open` gates on the editor being+ // EMPTY, so echoing into it pre-restore would silently consume the+ // restore (the draft stays stashed while the typed-ahead sits in its+ // place). A reopen's typed-ahead queues instead and dispatches+ // through the editor AFTER the fold's restore — base ordering+ // exactly. A NEW session owns no stash, so its launches keep the+ // echo path (headless new-session plans included: no stash exists to+ // protect).+ let mut echoing = matches!(+ &options.session,+ SessionSelection::New | SessionSelection::NewChild { .. }+ );+ let mut ui_input_closed = false;+ let mut last_render_at: Option<Instant> = None;+ let mut render_deadline: Option<Instant> = None;+ let mut opening_dirty = false;+ // A first-run onboarding task owns the pane BEFORE the chat surface:+ // the phase below consumes `ui_rx` itself once the open lands (it+ // needs the session, so it cannot run during the opening phase). The+ // opening loop must therefore not touch the channel on an onboarding+ // launch — the login/trace dialogs' keystrokes stay queued in the+ // channel for the phase to consume in order, exactly the base+ // ordering for this flow (the editor-level echo service below is the+ // chat chrome's surface, the pane a New chat's open actually mounts).+ let opening_serves_input = options.onboarding.is_none();+ let open_outcome = loop {+ tokio::select! {+ // The open completing is the phase's exit; the failure arms+ // below run against the same error exactly as before.+ open_result = &mut open_task => {+ break match open_result {+ Ok(outcome) => outcome,+ Err(join_error) => Err(anyhow::anyhow!(+ "the session open task failed: {join_error}"+ )),};- let session = SessionUi::open(- client,- &options,- notes_tx,- compaction_abort_tx,- prompt_tx,- share_tx,- reload_tx,- update_tx,- traces_upload_tx,- catalog_tx,- auth_panel_tx,- crate::session_ui::ActivityUpdates {- heartbeats: heartbeats_tx,- bash: bash_tx,- factory: factory_tx,- commands: commands_tx,+ }+ maybe_input = async {+ if ui_input_closed {+ std::future::pending::<Option<UiInput>>().await+ } else {+ ui_rx.recv().await+ }+ }, if opening_serves_input => {+ match maybe_input {+ None => {+ // The reader side is gone: park the arm instead of+ // hot-spinning on the instantly-ready closed+ // channel while the open task still runs.+ ui_input_closed = true;+ }+ Some(input) => match input {+ UiInput::Key(key) => {+ if let Some(id) = crate::keys::key_event_to_id(&key) {+ // `app.exit` on the empty editor (default+ // ctrl+d) is the one exit that must not+ // wait out the open: hand the terminal+ // back now (the open task dies with the+ // runtime; the daemon-side create, if it+ // already ran, leaves a resumable session+ // exactly like an exit right after the+ // open). A queue already holding input+ // keeps the exit's ordering instead: the+ // exit dispatches with the rest.+ if view+ .editor+ .keybindings()+ .matches(&id, "app.exit")+ && view.editor.get_text().is_empty()+ && echoing+ {+ exit_guard.arm_for_exit();+ renderer.finish(&mut view, false);+ return Ok(InteractiveOutcome {+ frames: Vec::new(),+ ..Default::default()+ });+ }+ // Pure editor keys echo now (the TS+ // editor path) while the stream is still a+ // clean prefix — but only when the+ // effective keymap leaves the key to the+ // editor fallback (finding #1): a key the+ // post-open dispatch would claim for an+ // app/session action keeps its normal+ // route, queued behind the open and+ // dispatched through the full+ // keymap-aware ladder at the fold, instead+ // of becoming a stray editor motion (the+ // misroute: default `left` on the empty+ // editor is `app.agents.back`, and a+ // user-bound space or single char runs its+ // bound action). The first queue parks+ // the echo path so later keys cannot jump+ // it.+ let editor_motion = matches!(+ id.as_str(),+ "backspace" | "delete" | "left" | "right" | "space"+ ) || id.chars().count() == 1;+ if echoing+ && editor_motion+ && !crate::session_ui::opening_echo_key_claimed(+ view.editor.keybindings(),+ &id,+ &view.editor,+ )+ {+ view.editor.handle_input(&id);+ opening_dirty = true;+ } else {+ echoing = false;+ pending.push_back(UiInput::Key(key));+ }+ }+ }+ UiInput::Paste(text) => {+ if echoing {+ let _ = view.editor.handle_paste(&text);+ opening_dirty = true;+ } else {+ pending.push_back(UiInput::Paste(text));+ }+ }+ UiInput::Resize => {+ // Geometry is order-insensitive, so the resize+ // always applies now: the same update the run+ // loop's resize arm performs, so the editor lays+ // its window out against the new row count and+ // the echo frames below paint at the new+ // geometry instead of the stale one.+ if let Ok((_width, height)) = crossterm::terminal::size() {+ view.set_terminal_rows(height);+ }+ opening_dirty = true;+ }+ other => {+ echoing = false;+ pending.push_back(other);+ }},- )- .await?;- Ok((events, session))+ }+ // The echo frame coalesces on the run loop's own+ // MIN_RENDER_INTERVAL: a typing burst paints as one+ // frame, a lone key paints immediately.+ if opening_paints && opening_dirty {+ let now = Instant::now();+ if last_render_at+ .is_none_or(|at| now.duration_since(at) >= MIN_RENDER_INTERVAL)+ {+ if let Some(renderer) = renderer.is_terminal_mut() {+ crate::app::draw(renderer, &mut view)?;+ }+ last_render_at = Some(now);+ opening_dirty = false;+ render_deadline = None;+ } else {+ render_deadline =+ last_render_at.map(|at| at + MIN_RENDER_INTERVAL);+ }+ }}- },- )- .await;+ // The coalesced echo frame's deadline (armed only while a+ // dirty frame waits out the render interval).+ () = async {+ match render_deadline {+ Some(deadline) => {+ tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await;+ }+ None => std::future::pending::<()>().await,+ }+ }, if render_deadline.is_some() => {+ render_deadline = None;+ if let Some(renderer) = renderer.is_terminal_mut() {+ crate::app::draw(renderer, &mut view)?;+ }+ last_render_at = Some(Instant::now());+ opening_dirty = false;+ }+ }+ };let ((mut events, mut session), waited_for_update_restart) = match open_outcome {Ok(opened) => opened,Err(error) => {@@ -665,7 +905,23 @@ async fn run_interactive_surface(.await?;}- let mut pending: VecDeque<UiInput> = VecDeque::new();+ // The fold's first frame must land before the opening phase's+ // typed-ahead queue dispatches: base painted it between the fold and+ // the first input (the select round-trip owns one frame per+ // iteration), and a pre-loaded queue would otherwise starve it — the+ // queued inputs would paint only their own deltas over a state the+ // verifier never saw rendered.+ if !pending.is_empty() && session.dirty {+ if let Some(renderer) = renderer.is_terminal_mut() {+ crate::app::draw(renderer, &mut view)?;+ } else {+ renderer.render_headless(&mut session, &mut view);+ }+ session.dirty = false;+ }++ // `pending` rides in from the opening phase: typed-ahead inputs+ // queued behind the open dispatch first, in order.let mut last_bash_refresh = Instant::now();let mut last_factory_refresh = Instant::now();// The enhanced-key modes settle once (kitty answer or fallback) anddiff --git a/crates/pa-tui/src/session_ui.rs b/crates/pa-tui/src/session_ui.rsindex 5da5cfc4ba..1b6e3d4c7a 100644--- a/crates/pa-tui/src/session_ui.rs+++ b/crates/pa-tui/src/session_ui.rs@@ -28,6 +28,10 @@ use bash::{ResyncBash, SideBashRun};pub(crate) use factory::FactoryUpdate;use heartbeats::paused_heartbeat_count;pub(crate) use heartbeats::HeartbeatsUpdate;+/// The opening phase's echo gate (run.rs): the fresh-state projection of+/// `handle_key`'s keymap-aware ladder — a claimed key queues behind the+/// session open instead of echoing into the editor.+pub(crate) use keys::opening_echo_key_claimed;use keys::SelectionAutoScroll;pub(crate) use model_picker::picker_viewport_rows;pub(crate) use model_picker::ModelCatalogUpdate;diff --git a/crates/pa-tui/src/session_ui/keys.rs b/crates/pa-tui/src/session_ui/keys.rsindex e4b82797f2..a46f8342cc 100644--- a/crates/pa-tui/src/session_ui/keys.rs+++ b/crates/pa-tui/src/session_ui/keys.rs@@ -1180,3 +1180,229 @@ impl SessionUi {Ok(())}}++/// The opening phase's echo gate: whether the post-open key dispatch+/// ([`SessionUi::handle_key`]'s ladder) would consume this key BEFORE its+/// editor fallback, in the state a fresh session's opening can be in — no+/// dock focus, no mounted picker or panel, no turn. This is the fresh-state+/// projection of the ladder: the always-fire arms in registration order,+/// the empty-editor arms, and the two editor-context arms; keep it in+/// lockstep with the ladder above.+///+/// A key claimed here takes its normal route — queued behind the session+/// open and dispatched through the full keymap-aware ladder once the+/// session lands — instead of echoing into the editor as a stray motion+/// (the misroute: a user-bound `left`/`space`/single-char action must run+/// its action, and default `left` on the empty editor is `app.agents.back`,+/// not a cursor move).+pub(crate) fn opening_echo_key_claimed(+ kb: &crate::keybindings::KeybindingsManager,+ id: &str,+ editor: &crate::editor::Editor,+) -> bool {+ // The always-fire arms: the transcript viewport, the image paste, the+ // escape ladder, the interrupt family, suspend, the model picker and+ // cycles, the detail cycle, the dock focus, the external editor, the+ // stash, the session-level commands, the queue browse, and the+ // follow-up key.+ if kb.matches(id, "tui.viewport.pageUp")+ || kb.matches(id, "tui.viewport.pageDown")+ || kb.matches(id, "tui.viewport.top")+ || kb.matches(id, "tui.viewport.follow")+ || kb.matches(id, "app.clipboard.pasteImage")+ || kb.matches(id, "app.input.clear")+ || kb.matches(id, "app.interrupt")+ || kb.matches(id, "app.clear")+ || kb.matches(id, "app.suspend")+ || kb.matches(id, "app.model.select")+ || kb.matches(id, "app.model.cycleForward")+ || kb.matches(id, "app.model.cycleBackward")+ || kb.matches(id, "app.tools.expand")+ || kb.matches(id, "app.subagents.focus")+ || kb.matches(id, "app.editor.external")+ || kb.matches(id, "app.prompt.stash")+ || kb.matches(id, "app.session.new")+ || kb.matches(id, "app.session.resume")+ || kb.matches(id, "app.message.navigateOlder")+ || kb.matches(id, "app.message.navigateNewer")+ || kb.matches(id, "app.message.moveEarlier")+ || kb.matches(id, "app.message.moveLater")+ || kb.matches(id, "app.message.followUp")+ {+ return true;+ }+ // The empty-editor arms (`app.exit` is the opening loop's own immediate+ // exit and never reaches the queue).+ if editor.get_text().trim().is_empty()+ && (kb.matches(id, "app.agents.back")+ || kb.matches(id, "app.session.tree")+ || kb.matches(id, "app.session.fork"))+ {+ return true;+ }+ // The editor-context arms: Tab into a picker-command argument (the+ // `/model`/`/mcp` partial), and Down's move-below-prompt dock handoff.+ if kb.matches(id, "tui.input.tab")+ && !editor.is_showing_autocomplete()+ && editor.picker_argument_context().is_some()+ {+ return true;+ }+ kb.matches(id, "tui.editor.cursorDown")+ && !editor.is_showing_autocomplete()+ && !editor.is_history_navigation_active()+ && editor.is_cursor_at_end()+}++#[cfg(test)]+mod opening_echo_claim_tests {+ use super::opening_echo_key_claimed;+ use crate::editor::Editor;+ use crate::keybindings::{KeybindingsConfig, KeybindingsManager};+ use std::collections::BTreeMap;++ fn manager(bindings: &[(&str, &str)]) -> KeybindingsManager {+ let config: KeybindingsConfig = bindings+ .iter()+ .map(|(action, key)| (action.to_string(), vec![key.to_string()]))+ .collect::<BTreeMap<_, _>>();+ KeybindingsManager::with_user_bindings(config)+ }++ fn editor_with(text: &str) -> Editor {+ let mut editor = Editor::new();+ if !text.is_empty() {+ editor.set_text(text);+ }+ editor+ }++ /// Default `left` on the EMPTY editor is `app.agents.back` — the+ /// misroute the gate exists for: the key must queue (its action+ /// runs at the fold), never echo as an editor cursor move.+ #[test]+ fn default_left_on_the_empty_editor_is_claimed() {+ let kb = KeybindingsManager::new();+ let editor = editor_with("");+ assert!(+ opening_echo_key_claimed(&kb, "left", &editor),+ "left on the empty editor is app.agents.back, not an editor motion"+ );+ }++ /// Default `left` with text in the editor stays the editor's cursor+ /// motion (the agents-back guard fires only on the empty editor), so+ /// the gate leaves it to the editor fallback.+ #[test]+ fn default_left_with_text_is_not_claimed() {+ let kb = KeybindingsManager::new();+ let editor = editor_with("draft");+ assert!(+ !opening_echo_key_claimed(&kb, "left", &editor),+ "left with text is the editor's cursor motion"+ );+ }++ /// The plain typing keys the opening loop echoes (space, backspace,+ /// single chars) stay unclaimed under the default bindings.+ #[test]+ fn plain_editor_keys_stay_unclaimed_by_default() {+ let kb = KeybindingsManager::new();+ for (id, text) in [+ ("space", ""),+ ("backspace", ""),+ ("delete", ""),+ ("right", ""),+ ("a", ""),+ ("z", "draft"),+ ] {+ let editor = editor_with(text);+ assert!(+ !opening_echo_key_claimed(&kb, id, &editor),+ "{id} must stay the editor fallback under default bindings"+ );+ }+ }++ /// A user-bound single-char action is claimed (the reviewer's+ /// user-binding case): the bound action routes through the post-open+ /// dispatch, never into the editor as text.+ #[test]+ fn a_user_bound_single_char_action_is_claimed() {+ let kb = manager(&[("app.session.new", "a")]);+ let editor = editor_with("");+ assert!(+ opening_echo_key_claimed(&kb, "a", &editor),+ "a user-bound 'a' must run its action, not type an 'a'"+ );+ }++ /// A user-bound space action is claimed the same way; with the+ /// binding moved off space, space returns to the editor fallback.+ #[test]+ fn a_user_bound_space_action_is_claimed() {+ let kb = manager(&[("app.session.new", "space")]);+ let editor = editor_with("");+ assert!(+ opening_echo_key_claimed(&kb, "space", &editor),+ "a user-bound space must run its action"+ );+ let unbound = manager(&[("app.session.new", "f9")]);+ assert!(!opening_echo_key_claimed(&unbound, "space", &editor));+ }++ /// `app.agents.back` rebound off `left` returns `left` to the editor+ /// fallback (the gate reads the EFFECTIVE keymap, not the default).+ #[test]+ fn a_rebound_agents_back_frees_left_for_the_editor() {+ let kb = manager(&[("app.agents.back", "alt+left")]);+ let editor = editor_with("");+ assert!(+ !opening_echo_key_claimed(&kb, "left", &editor),+ "with agents.back rebound, left is the editor's cursor motion"+ );+ }++ /// The always-fire app arms are claimed regardless of the editor's+ /// text: the escape ladder, the interrupt family, suspend, the+ /// model picker, the stash, the session commands, and the queue+ /// browse keys.+ #[test]+ fn the_always_fire_arms_are_claimed() {+ let kb = KeybindingsManager::new();+ let editor = editor_with("draft");+ for id in [+ "escape",+ "ctrl+c",+ "ctrl+z",+ "ctrl+l",+ "alt+m",+ "ctrl+o",+ "alt+a",+ "ctrl+g",+ "ctrl+s",+ "alt+up",+ "alt+down",+ "alt+enter",+ ] {+ assert!(+ opening_echo_key_claimed(&kb, id, &editor),+ "{id} is an always-fire app arm and must be claimed"+ );+ }+ }++ /// The empty-editor session arms (`app.session.tree`, `app.session.fork`+ /// user-bound here — they carry no default key) are claimed only on+ /// the empty editor.+ #[test]+ fn the_empty_editor_session_arms_claim_only_when_empty() {+ let kb = manager(&[("app.session.tree", "ctrl+t")]);+ assert!(opening_echo_key_claimed(&kb, "ctrl+t", &editor_with("")));+ assert!(!opening_echo_key_claimed(+ &kb,+ "ctrl+t",+ &editor_with("draft")+ ));+ }+}diff --git a/crates/pa-tui/tests/stash_restore_before_typed_ahead_headless.rs b/crates/pa-tui/tests/stash_restore_before_typed_ahead_headless.rsnew file mode 100644index 0000000000..c2e8b79df7--- /dev/null+++ b/crates/pa-tui/tests/stash_restore_before_typed_ahead_headless.rs@@ -0,0 +1,345 @@+//! Headless e2e for the opening phase's stash ordering (the pre-bar+//! review's finding: the stash restore must precede typed-ahead+//! acceptance AND exit-arm evaluation on a session-reopen launch).+//!+//! The two-run shape reproduces the operator's exact reopen flow: the+//! first run opens the session, types a draft, and leaves for the agents+//! view (the draft auto-stashes as the session's restore-on-open head);+//! the second run reopens the SAME session against a supervisor whose+//! attach stalls, and presses Ctrl+D — the `app.exit` key — while the+//! open is still in flight.+//!+//! The contract: base restores the stashed draft BEFORE consuming any+//! input, so Ctrl+D lands on a NONEMPTY editor (a delete-forward, not an+//! exit) and the typed-ahead dispatches after the restore. An opening+//! loop that evaluates the exit arm against the pre-restore EMPTY+//! editor exits the session silently instead — the run ends with no+//! restore, no draft, no frames.+#![cfg(unix)]+#![allow(clippy::too_many_lines, clippy::large_futures)]++use std::io::{BufRead, BufReader, Write};+use std::os::unix::net::{UnixListener, UnixStream};+use std::path::PathBuf;++use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+use pa_tui::interactive::{+ run_interactive, HeadlessPlan, HeadlessStep, InteractiveOptions, ModelSelection,+ SessionSelection, UiMode,+};+use serde_json::{json, Value};++/// How long the reopen's attach stalls: far past the plan's first step,+/// so the Ctrl+D provably lands while the open is still in flight.+const REOPEN_ATTACH_STALL_MS: u64 = 1_500;++/// Ctrl+D (the default `app.exit` key).+fn ctrl_d() -> KeyEvent {+ KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)+}++/// Ctrl+Q (user-bound to `app.session.resume` for the first run's way+/// out to the agents view — the action that fires with a draft in the+/// editor, unlike agents-back's empty-editor gate).+fn ctrl_q() -> KeyEvent {+ KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL)+}++struct MockSupervisor {+ listener: UnixListener,+}++impl MockSupervisor {+ fn bind(socket: &std::path::Path) -> Self {+ MockSupervisor {+ listener: UnixListener::bind(socket).expect("bind mock socket"),+ }+ }++ /// Serve the two connections of the flow: the first open (fast+ /// attach) then the reopen (stalled attach). Each connection is+ /// served to EOF, so the runs sequence naturally.+ fn serve(self) {+ let (first, _) = self.listener.accept().expect("accept first");+ serve_connection(first, false);+ let (second, _) = self.listener.accept().expect("accept second");+ serve_connection(second, true);+ }+}++fn serve_connection(stream: UnixStream, stall_attach: bool) {+ let write_stream = stream.try_clone().expect("clone mock socket");+ let mut writer = write_stream;+ let mut reader = BufReader::new(stream);++ let hello = json!({+ "type": "daemon_hello",+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "serverCapabilities": ["kernel_bash_activity"],+ "clientId": "mock",+ });+ write_json(&mut writer, &hello);++ let mut line = String::new();+ loop {+ line.clear();+ match reader.read_line(&mut line) {+ Ok(0) | Err(_) => break,+ Ok(_) => {}+ }+ let Ok(envelope) = serde_json::from_str::<Value>(line.trim()) else {+ continue;+ };+ let id = envelope.get("id").and_then(Value::as_str).unwrap_or("");+ let command = envelope.get("command").cloned().unwrap_or(Value::Null);+ let command_type = command+ .get("type")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ match command_type.as_str() {+ "attach" => {+ if stall_attach {+ std::thread::sleep(std::time::Duration::from_millis(REOPEN_ATTACH_STALL_MS));+ }+ write_json(&mut writer, &attach_data(id));+ }+ "heartbeats_list" => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "heartbeats_list",+ "success": true,+ "data": { "heartbeats": [] },+ }),+ );+ }+ "list_kernel_bash" => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "list_kernel_bash",+ "success": true,+ "data": { "activities": [] },+ }),+ );+ }+ "get_session_stats" => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "get_session_stats",+ "success": true,+ "data": {+ "contextUsage": { "tokens": 1200, "contextWindow": 200_000 },+ "cost": 0.01,+ },+ }),+ );+ }+ _ => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": command_type,+ "success": true,+ "data": {},+ }),+ );+ }+ }+ }+}++fn write_json(writer: &mut UnixStream, value: &Value) {+ let mut line = serde_json::to_string(value).expect("serialize mock frame");+ line.push('\n');+ writer.write_all(line.as_bytes()).expect("write mock frame");+ writer.flush().expect("flush mock frame");+}++/// The attach result: one live session with an empty transcript.+fn attach_data(id: &str) -> Value {+ json!({+ "type": "response",+ "id": id,+ "command": "attach",+ "success": true,+ "data": {+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "activeSessionId": "s1",+ "snapshot": {+ "activeSessionId": "s1",+ "summary": { "id": "s1", "cwd": "/tmp" },+ "state": {+ "activeSessionId": "s1",+ "cwd": "/tmp",+ "sessionId": "sess-1",+ "sessionName": "stash reopen probe",+ "model": "faux-1",+ "isStreaming": false,+ "isCompacting": false,+ "sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },+ },+ "messages": [],+ "lastEventSequence": 0,+ "lastEventCursor": null,+ },+ "client": { "id": "mock", "capabilities": [] },+ "lastEventSequence": 0,+ "lastEventCursor": null,+ },+ })+}++fn options(+ socket: PathBuf,+ keybindings: pa_tui::keybindings::KeybindingsManager,+) -> InteractiveOptions {+ InteractiveOptions {+ models: None,+ socket_path: socket,+ cwd: PathBuf::from("/tmp"),+ session_dir: None,+ script_path: None,+ model_selection: ModelSelection::default(),+ model_catalog: Vec::new(),+ model_configured_providers: std::collections::HashSet::default(),+ model_recent_models: Vec::new(),+ default_thinking_level: None,+ no_session: false,+ session: SessionSelection::Attach("s1".to_string()),+ initial_message: None,+ show_images: true,+ fullscreen_mouse: true,+ theme: "prime".to_string(),+ code_block_indent: " ".to_string(),+ tree_filter_mode: String::new(),+ branch_summary_skip_prompt: false,+ version: "0.0.0".to_string(),+ onboarding: None,+ telemetry_disabled: None,+ client_auth: None,+ traces: None,+ provider_auth: None,+ update_commands: None,+ telemetry: None,+ keybindings,+ session_rlm_depth: None,+ prompt_stash: std::sync::Arc::default(),+ session_has_children: false,+ restore_dock_focus: false,+ client_settings: None,+ }+}++/// The stashed-draft reopen flow: the draft typed in the first run+/// returns in the second run's editor BEFORE the reopen's queued Ctrl+D+/// is evaluated — so the exit key is a delete-forward on the restored+/// draft, never a silent session exit.+///+/// Red on the pre-wave head: the opening loop evaluated `app.exit`+/// against the pre-restore empty editor and exited the run during the+/// stalled attach (no restore, no draft, empty frames).+#[test]+fn the_reopen_restores_the_stash_before_the_queued_exit_key_evaluates() {+ std::env::remove_var("TMUX");+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("tui.sock");+ let supervisor = MockSupervisor::bind(&socket);+ let handle = std::thread::spawn(move || supervisor.serve());++ // The shared stash store: the first run's auto-stash is the second+ // run's restore-on-open head.+ let stash: std::sync::Arc<std::sync::Mutex<pa_tui::prompt_stash::PromptStashStore>> =+ std::sync::Arc::default();++ let runtime = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .build()+ .expect("tokio runtime");++ // Run one: type the draft, then leave for the agents view — the draft+ // auto-stashes as the session's restore-on-open head on the way out.+ let mut first = options(socket.clone(), agents_view_exit_bindings());+ first.prompt_stash = std::sync::Arc::clone(&stash);+ let first_plan = HeadlessPlan {+ steps: vec![+ HeadlessStep::Type("the stashed draft".to_string()),+ HeadlessStep::Key(ctrl_q()),+ ],+ width: 100,+ height: 30,+ };+ let first_outcome = runtime+ .block_on(run_interactive(first, UiMode::Headless(first_plan)))+ .expect("first interactive run");++ // Run two: reopen the SAME session against the stalled attach and+ // press Ctrl+D while the open is still in flight.+ let mut second = options(socket, pa_tui::keybindings::KeybindingsManager::new());+ second.prompt_stash = std::sync::Arc::clone(&stash);+ let second_plan = HeadlessPlan {+ steps: vec![+ HeadlessStep::Key(ctrl_d()),+ HeadlessStep::WaitRender {+ needle: "the stashed draft".to_string(),+ timeout_ms: 8_000,+ },+ HeadlessStep::WaitRender {+ needle: "Restored stashed prompt".to_string(),+ timeout_ms: 8_000,+ },+ ],+ width: 100,+ height: 30,+ };+ let second_outcome = runtime+ .block_on(run_interactive(second, UiMode::Headless(second_plan)))+ .expect("second interactive run");+ handle.join().expect("mock supervisor finished");++ let frames = second_outcome.frames.join("\n");+ assert!(+ frames.contains("the stashed draft"),+ "the stashed draft must return to the reopened editor before any \+ queued input dispatches; frames:\n{frames}"+ );+ assert!(+ frames.contains("Restored stashed prompt"),+ "the restore notice must land with the restored draft; frames:\n{frames}"+ );+ // The run itself must NOT be the Ctrl+D exit: the exit path returns+ // the outcome with no frames at all, so non-empty frames prove the+ // exit key was consumed as the editor's delete-forward instead.+ assert!(+ !second_outcome.frames.is_empty(),+ "the run exited during the stalled reopen instead of restoring the draft"+ );+ // The first run must have taken the agents-view way out (the handoff+ // that auto-stashes): the draft rode the shared store into run two.+ assert!(+ first_outcome.return_to_agents_view,+ "the first run must hand off to the agents view so its draft \+ auto-stashes as the restore-on-open head"+ );+}++/// `app.session.resume` user-bound to Ctrl+Q: the one agents-view way+/// out that fires with a draft in the editor (agents-back's+/// empty-editor gate would turn the exit key into a cursor motion).+fn agents_view_exit_bindings() -> pa_tui::keybindings::KeybindingsManager {+ use std::collections::BTreeMap;+ let config = [("app.session.resume".to_string(), vec!["ctrl+q".to_string()])]+ .into_iter()+ .collect::<BTreeMap<_, _>>();+ pa_tui::keybindings::KeybindingsManager::with_user_bindings(config)+}diff --git a/prime-agent-runtime/src/rlm/repl.py b/prime-agent-runtime/src/rlm/repl.pyindex 5fd0cdaa9d..5293a30913 100644--- a/prime-agent-runtime/src/rlm/repl.py+++ b/prime-agent-runtime/src/rlm/repl.py@@ -90,6 +90,13 @@ _pending_host: dict[str, "asyncio.Future[dict[str, Any]]"] = {}# host reply can arrive after that, so waiting (and future) host_request calls fail._host_closed = False+# In-flight dedicated-lane MCP status requests (the eager settle and the+# connections view ride this lane): the serve loop hands them off instead of+# awaiting them inline, so a hanging server bounds its own request while the+# execution queue stays free for the user's cells. Shutdown cancels the set+# before closing the MCP registry.+_mcp_status_tasks: "set[asyncio.Task[None]]" = set()+# Interrupt bookkeeping shared between the reader thread and the loop thread._interrupt_lock = threading.Lock()_inflight: set[str] = set()@@ -1293,6 +1300,46 @@ async def _handle_request(_send({"event": "done", "id": rid, "status": "error"})+async def _mcp_status_lane(req: dict[str, Any], ns: dict[str, Any]) -> None:+ """One dedicated-lane `mcp_status` request.++ The failure shape mirrors `_handle_request`'s backstop (one broken+ request fails alone, never the lane, never the serve loop); a+ shutdown cancellation is silent by design — the host is already+ tearing the kernel down and owns the deadline.+ """+ try:+ await _handle_mcp_status(req, ns)+ except asyncio.CancelledError:+ raise+ except BaseException as exc: # noqa: BLE001 - one broken lane request fails alone+ rid = req["id"]+ try:+ _send(_error_event(rid, exc))+ _send({"event": "done", "id": rid, "status": "error"})+ except BaseException:+ pass+++def _spawn_mcp_status_lane(req: dict[str, Any], ns: dict[str, Any]) -> None:+ """Hand one `mcp_status` request to the dedicated lane.++ `mcp_status` opens and lists the configured generic servers (the eager+ background settle and the connections view both ride it), and a slow or+ unreachable server can hold it for the whole per-server timeout. Awaiting+ it inline on the execution queue would park the user's first python cell+ behind a server handshake that no cell asked for (finding: the eager+ settle must never contend with the user's first-turn path; the join point+ stays at first use through the registry's per-server locks). The lane task+ runs on the same loop (the registry dispatch joins concurrent listings+ and an early user call onto the same in-flight open), so ordering between+ cells is untouched — only status work stops occupying the cell queue.+ """+ task = asyncio.get_running_loop().create_task(_mcp_status_lane(req, ns))+ _mcp_status_tasks.add(task)+ task.add_done_callback(_mcp_status_tasks.discard)++async def _serve(queue: asyncio.Queue[dict[str, Any]], ns: dict[str, Any]) -> None:while True:req = await queue.get()@@ -1307,6 +1354,15 @@ async def _serve(queue: asyncio.Queue[dict[str, Any]], ns: dict[str, Any]) -> No# Host stdin closed without a shutdown request: the host# process is gone, so this is the last chance to persist._flush_final_snapshot(ns)+ # The dedicated MCP status lane goes first: a still-listing+ # server is cancelled (bounded, silent) so the registry close+ # below cannot race an in-flight open under the host's 5s+ # shutdown deadline.+ if _mcp_status_tasks:+ for task in list(_mcp_status_tasks):+ task.cancel()+ await asyncio.wait(set(_mcp_status_tasks), timeout=1.0)+ _mcp_status_tasks.clear()# MCP children must close before the loop dies; close() is internally bounded under the host's 5s deadline.mcp_mod = sys.modules.get("rlm.mcp")if mcp_mod is not None:@@ -1326,7 +1382,9 @@ async def _serve(queue: asyncio.Queue[dict[str, Any]], ns: dict[str, Any]) -> Noelif rtype == "list_names":await _handle_request(_handle_list_names, req, ns)elif rtype == "mcp_status":- await _handle_request(_handle_mcp_status, req, ns)+ # The dedicated lane (see `_spawn_mcp_status_lane`): status/open+ # work never occupies the execution queue.+ _spawn_mcp_status_lane(req, ns)def _handle_bash_activity(req: dict[str, Any]) -> None: