A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
agents view: show the selected agent's progress note (port of TS #2526) (#3349)
Sebastian Müllera8834c5b4431
diff --git a/.changes/agents-view-progress-note.md b/.changes/agents-view-progress-note.mdnew file mode 100644index 0000000000..f7448e562c--- /dev/null+++ b/.changes/agents-view-progress-note.md@@ -0,0 +1,2 @@+- Agents view: the selected agent's row now expands to show its latest `rlm.progress_note` (live child progress) while it runs.+- Progress notes fit narrow panes and clear before an aborted run is published as idle.diff --git a/crates/pa-cli/src/print_boundary/tests.rs b/crates/pa-cli/src/print_boundary/tests.rsindex 70ca6e12e7..5f38e602bc 100644--- a/crates/pa-cli/src/print_boundary/tests.rs+++ b/crates/pa-cli/src/print_boundary/tests.rs@@ -129,6 +129,7 @@ async fn faux_engine_with_telemetry(additional_prompt_paths: Vec::new(),extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,+ progress_note_emit: None,rlm_depth: None,daemonless: true,model_info: Some(model.clone()),diff --git a/crates/pa-cli/src/print_goal.rs b/crates/pa-cli/src/print_goal.rsindex decf0bc367..51f04589dd 100644--- a/crates/pa-cli/src/print_goal.rs+++ b/crates/pa-cli/src/print_goal.rs@@ -853,6 +853,7 @@ mod tests {additional_prompt_paths: Vec::new(),extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,+ progress_note_emit: None,daemonless: true,rlm_depth: None,model_info: Some(model.clone()),@@ -1467,6 +1468,7 @@ mod tests {additional_prompt_paths: Vec::new(),extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,+ progress_note_emit: None,daemonless: true,rlm_depth: None,model_info: Some(model.clone()),diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rsindex a538ec39b8..7393f33074 100644--- a/crates/pa-cli/src/print_runtime.rs+++ b/crates/pa-cli/src/print_runtime.rs@@ -755,6 +755,7 @@ pub(crate) async fn build_headless_engine_with(.collect(),extra_builtin_skill_overrides: vec![],rlm_subagent_host,+ progress_note_emit: None,rlm_depth,daemonless: true,model_info: Some(model.clone()),diff --git a/crates/pa-cli/src/print_runtime/faux.rs b/crates/pa-cli/src/print_runtime/faux.rsindex 801dea967c..07e3cb3d20 100644--- a/crates/pa-cli/src/print_runtime/faux.rs+++ b/crates/pa-cli/src/print_runtime/faux.rs@@ -162,6 +162,7 @@ pub(crate) async fn build_faux_engine_with(additional_prompt_paths: vec![],extra_builtin_skill_overrides: vec![],rlm_subagent_host,+ progress_note_emit: None,rlm_depth,daemonless: true,model_info: Some(model.clone()),diff --git a/crates/pa-cli/src/print_session_command.rs b/crates/pa-cli/src/print_session_command.rsindex a79955bdd0..29b076fa04 100644--- a/crates/pa-cli/src/print_session_command.rs+++ b/crates/pa-cli/src/print_session_command.rs@@ -345,6 +345,7 @@ mod tests {additional_prompt_paths: Vec::new(),extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,+ progress_note_emit: None,daemonless: true,rlm_depth: None,model_info: Some(model.clone()),diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex c1b4c9f3d7..790bb819f7 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -46,6 +46,9 @@ pub struct SessionEngineConfig {pub additional_prompt_paths: Vec<String>,pub extra_builtin_skill_overrides: Vec<String>,pub rlm_subagent_host: Option<Arc<dyn super::rlm_host::RlmSubagentHost>>,+ /// Announces every accepted `rlm.progress.note`; `None` keeps the store+ /// the only surface.+ pub progress_note_emit: Option<super::rlm_host::RlmProgressNoteEmit>,/// The session's depth in the RLM recursion tree (0 for top-level/// sessions); gates the `refine.*` host requests.pub rlm_depth: Option<u32>,@@ -123,6 +126,9 @@ pub struct SessionEngine {/// session facts captured in `create_session` (the #3184 capture/// pattern) and reached through [`SessionEngine::factory_activity`].pub factory_host: super::factory_host::FactoryHost,+ /// The progress-note store the `rlm.progress.note` handler throttles+ /// into; the embedding mirrors the Arc for sync reads.+ pub rlm_progress_notes: std::sync::Arc<super::rlm_host::RlmProgressNotes>,/// The session's kernel provisioner. The engine is the STRONG owner on/// purpose: the `ipython` tool on the agent and the compaction/// kernel-state probe on the session hold weak references, because the@@ -218,6 +224,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Ssuper::runtime_wiring::RlmWiring {model_registry: None,subagent_host: config.rlm_subagent_host.clone(),+ progress_note_emit: config.progress_note_emit.clone(),},config.queued_goal_context_purge.clone(),config.cron_store.clone(),@@ -798,6 +805,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Stelemetry,rlm_usage: wiring.rlm_usage,factory_host,+ rlm_progress_notes: Arc::clone(&wiring.rlm.notes),provisioner,})}diff --git a/crates/pa-core/src/session_engine/engine/tests.rs b/crates/pa-core/src/session_engine/engine/tests.rsindex 5282d8a54d..bb1d6578db 100644--- a/crates/pa-core/src/session_engine/engine/tests.rs+++ b/crates/pa-core/src/session_engine/engine/tests.rs@@ -80,6 +80,7 @@ async fn engine_runs_tool_loop_and_persists() {additional_prompt_paths: vec![],extra_builtin_skill_overrides: vec![],rlm_subagent_host: None,+ progress_note_emit: None,rlm_depth: None,daemonless: true,telemetry: None,@@ -180,6 +181,7 @@ async fn spawned_child_prompt_stamps_its_depth() {additional_prompt_paths: vec![],extra_builtin_skill_overrides: vec![],rlm_subagent_host: None,+ progress_note_emit: None,rlm_depth: Some(2),daemonless: true,telemetry: None,@@ -248,6 +250,7 @@ async fn oauth_creds_unlock_generic_mcp_gating_in_new_sessions() {additional_prompt_paths: vec![],extra_builtin_skill_overrides: vec![],rlm_subagent_host: None,+ progress_note_emit: None,rlm_depth: None,daemonless: true,telemetry: None,@@ -433,6 +436,7 @@ async fn create_session_appends_missing_resume_settings_rows() {additional_prompt_paths: vec![],extra_builtin_skill_overrides: vec![],rlm_subagent_host: None,+ progress_note_emit: None,rlm_depth: None,daemonless: true,telemetry: None,diff --git a/crates/pa-core/src/session_engine/rlm_host.rs b/crates/pa-core/src/session_engine/rlm_host.rsindex 60dc38fea9..16a2f32de8 100644--- a/crates/pa-core/src/session_engine/rlm_host.rs+++ b/crates/pa-core/src/session_engine/rlm_host.rs@@ -15,7 +15,6 @@ use std::sync::Arc;use std::time::Instant;use serde_json::{json, Map, Value};-use tokio::sync::Mutex;use crate::kernel::rlm_runtime::{find_rlm_model_matches, kwargs_from_payload, normalize_requested_rlm_subagent_model,@@ -394,11 +393,11 @@ pub struct RlmProgressNoteResult {pub retry_after_ms: Option<u64>,}-/// Latest-note store with the 10-second throttle. The daemon roster reads-/// `latest_note` so a child snapshot surfaces the note to its parent.+/// Latest-note store with the 10-second throttle; the sync roster-summary+/// composer reads it, so the lock is a std mutex.#[derive(Debug, Default)]pub struct RlmProgressNotes {- state: Mutex<RlmProgressNoteState>,+ state: std::sync::Mutex<RlmProgressNoteState>,}#[derive(Debug, Default)]@@ -409,8 +408,11 @@ struct RlmProgressNoteState {impl RlmProgressNotes {/// Accept or throttle one note. The message is already validated.- pub async fn note(&self, message: &str, now_ms: u64) -> RlmProgressNoteResult {- let mut state = self.state.lock().await;+ pub fn note(&self, message: &str, now_ms: u64) -> RlmProgressNoteResult {+ let mut state = self+ .state+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);if let Some(last_at) = state.last_at {let elapsed_ms = last_at.elapsed().as_millis() as u64;if elapsed_ms < RLM_PROGRESS_NOTE_MIN_INTERVAL_MS {@@ -429,11 +431,27 @@ impl RlmProgressNotes {}/// The newest accepted note with its wall-clock timestamp.- pub async fn latest_note(&self) -> Option<(String, u64)> {- self.state.lock().await.latest.clone()+ pub fn latest_note(&self) -> Option<(String, u64)> {+ self.state+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .latest+ .clone()+ }++ /// Drops the stored note at a run boundary; the throttle clock stays.+ pub fn clear(&self) {+ self.state+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .latest = None;}}+/// Announces one accepted note (message, wall-clock ms) as the+/// `rlm_progress_note` session event.+pub type RlmProgressNoteEmit = Arc<dyn Fn(&str, u64) + Send + Sync>;+/// Message length in UTF-16 code units, matching the host-side bound.pub fn utf16_length(message: &str) -> usize {message.chars().map(char::len_utf16).sum()@@ -454,6 +472,8 @@ pub(crate) struct SemanticSpawnAnchor {pub struct RlmHostBridge {registry: Arc<ModelRegistry>,pub notes: Arc<RlmProgressNotes>,+ /// Fires on every accepted note; `None` keeps the store the only surface.+ note_emit: Option<RlmProgressNoteEmit>,host: Arc<dyn RlmSubagentHost>,/// The child-usage attribution producer `rlm.spawn` registers into/// and the daemon's child observation drives.@@ -471,10 +491,12 @@ impl RlmHostBridge {registry: Arc<ModelRegistry>,host: Arc<dyn RlmSubagentHost>,usage: Arc<super::rlm_usage::RlmChildUsageAttributions>,+ note_emit: Option<RlmProgressNoteEmit>,) -> Self {Self {registry,notes: Arc::new(RlmProgressNotes::default()),+ note_emit,host,usage,semantic_spawn: std::sync::OnceLock::new(),@@ -538,10 +560,12 @@ fn register_find_models(handlers: &mut HostRequestHandlers, bridge: &Arc<RlmHostfn register_progress_note(handlers: &mut HostRequestHandlers, bridge: &Arc<RlmHostBridge>) {let notes = Arc::clone(&bridge.notes);+ let note_emit = bridge.note_emit.clone();handlers.register("rlm.progress.note",host_handler(move |payload| {let notes = Arc::clone(¬es);+ let note_emit = note_emit.clone();Box::pin(async move {let Some(raw) = payload.data.get("message").and_then(Value::as_str) else {anyhow::bail!("rlm.progress.note message must be a non-empty string");@@ -559,7 +583,10 @@ fn register_progress_note(handlers: &mut HostRequestHandlers, bridge: &Arc<RlmHo.duration_since(std::time::UNIX_EPOCH).map(|duration| duration.as_millis() as u64).unwrap_or_default();- let outcome = notes.note(message, now_ms).await;+ let outcome = notes.note(message, now_ms);+ if let (true, Some(emit)) = (outcome.accepted, note_emit.as_deref()) {+ emit(message, now_ms);+ }Ok(match outcome.retry_after_ms {None => json!({ "accepted": true }),Some(retry_after_ms) => json!({@@ -855,6 +882,7 @@ mod tests {use crate::kernel::shared::HostRequestPayload;use crate::session::manager::SessionManager;use std::sync::Arc;+ use tokio::sync::Mutex;/// A host recording every call, answering with fixed handles./// One recorded collect call: its targets and timeout.@@ -1058,6 +1086,7 @@ mod tests {crate::session_engine::runtime_wiring::RlmWiring {model_registry: Some(Arc::clone(®istry)),subagent_host: host,+ progress_note_emit: None,},None,None,@@ -1177,8 +1206,18 @@ mod tests {.await.unwrap();assert_eq!(accepted, json!({ "accepted": true }));- let (latest, _) = wiring.rlm.notes.latest_note().await.unwrap();+ let (latest, _) = wiring.rlm.notes.latest_note().unwrap();assert_eq!(latest, "making progress");+ wiring.rlm.notes.clear();+ assert!(wiring.rlm.notes.latest_note().is_none());+ let still_throttled = call(+ &wiring,+ "rlm.progress.note",+ json!({ "type": "rlm.progress.note", "message": "too soon" }),+ )+ .await+ .unwrap();+ assert_eq!(still_throttled["accepted"], false);let throttled = call(&wiring,"rlm.progress.note",@@ -1207,6 +1246,56 @@ mod tests {);}+ /// The accepted note announces with its message and wall-clock+ /// timestamp; a throttled note announces nothing.+ #[tokio::test]+ async fn accepted_note_announces_throttled_note_stays_silent() {+ let dir = tempfile::TempDir::new().unwrap();+ let session = persisted_session(dir.path());+ let announced: Arc<std::sync::Mutex<Vec<(String, u64)>>> =+ Arc::new(std::sync::Mutex::new(Vec::new()));+ let sink = Arc::clone(&announced);+ let wiring = crate::session_engine::runtime_wiring::wire_session_runtime(+ session,+ dir.path(),+ crate::session_engine::runtime_wiring::RlmWiring {+ model_registry: None,+ subagent_host: None,+ progress_note_emit: Some(Arc::new(move |message, timestamp| {+ sink.lock().unwrap().push((message.to_string(), timestamp));+ })),+ },+ None,+ None,+ );+ call(+ &wiring,+ "rlm.progress.note",+ json!({ "type": "rlm.progress.note", "message": "halfway" }),+ )+ .await+ .unwrap();+ let seen = announced.lock().unwrap().clone();+ assert_eq!(seen.len(), 1, "the accepted note announced: {seen:?}");+ assert_eq!(seen[0].0, "halfway");+ let now_ms = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_millis() as u64;+ assert!(+ seen[0].1.abs_diff(now_ms) < 5_000,+ "the announcement carries the note's wall-clock timestamp"+ );+ call(+ &wiring,+ "rlm.progress.note",+ json!({ "type": "rlm.progress.note", "message": "again" }),+ )+ .await+ .unwrap();+ assert_eq!(announced.lock().unwrap().len(), 1);+ }+#[tokio::test]async fn spawn_round_trip_through_the_registry() {let dir = tempfile::TempDir::new().unwrap();diff --git a/crates/pa-core/src/session_engine/runtime_wiring.rs b/crates/pa-core/src/session_engine/runtime_wiring.rsindex 221cde9b1d..1effbb0aef 100644--- a/crates/pa-core/src/session_engine/runtime_wiring.rs+++ b/crates/pa-core/src/session_engine/runtime_wiring.rs@@ -35,6 +35,9 @@ pub struct RlmWiring {/// Child-session machinery backing `rlm.spawn`/`rlm.create_session` and/// the roster/collect/delete surface.pub subagent_host: Option<Arc<dyn RlmSubagentHost>>,+ /// Announces every accepted `rlm.progress.note`; `None` keeps the store+ /// the only surface.+ pub progress_note_emit: Option<super::rlm_host::RlmProgressNoteEmit>,}/// The embedding's cron wiring for the kernel's `rlm_heartbeat.*` host@@ -175,6 +178,7 @@ pub fn wire_session_runtime(model_registry,subagent_host,rlm_usage.clone(),+ rlm.progress_note_emit,));register_rlm_host_handlers(&mut handlers, &rlm_bridge);SessionKernelWiring {diff --git a/crates/pa-core/tests/abort_kernel_cell.rs b/crates/pa-core/tests/abort_kernel_cell.rsindex b55c84ea35..0cf8ae91cf 100644--- a/crates/pa-core/tests/abort_kernel_cell.rs+++ b/crates/pa-core/tests/abort_kernel_cell.rs@@ -164,6 +164,7 @@ async fn abort_during_a_kernel_cell_settles_the_turn_immediately() {additional_prompt_paths: Vec::new(),extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,+ progress_note_emit: None,rlm_depth: None,daemonless: true,telemetry: None,diff --git a/crates/pa-core/tests/turn_boundary_kernel.rs b/crates/pa-core/tests/turn_boundary_kernel.rsindex ff2b198d04..6e80977c6f 100644--- a/crates/pa-core/tests/turn_boundary_kernel.rs+++ b/crates/pa-core/tests/turn_boundary_kernel.rs@@ -199,6 +199,7 @@ async fn turn_boundary_host_requests_round_trip_through_a_real_kernel() {additional_prompt_paths: Vec::new(),extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,+ progress_note_emit: None,rlm_depth: None,daemonless: true,telemetry: None,diff --git a/crates/pa-daemon/src/agent_engine.rs b/crates/pa-daemon/src/agent_engine.rsindex 07abbd31dd..df5671af8a 100644--- a/crates/pa-daemon/src/agent_engine.rs+++ b/crates/pa-daemon/src/agent_engine.rs@@ -215,6 +215,15 @@ pub struct AgentSessionEngine {/// session. `None` without a worker pump.compaction_summary_sink:std::sync::Mutex<Option<pa_core::session_engine::compaction_exec::SummaryDeltaSink>>,+ /// The built session's progress-note store, mirrored at every build+ /// adoption; `None` until the first build.+ pub(crate) progress_notes: std::sync::Mutex<+ Option<std::sync::Arc<pa_core::session_engine::rlm_host::RlmProgressNotes>>,+ >,+ /// The worker's accepted-note announcer, threaded into every session+ /// build; `None` without a worker pump.+ progress_note_emit:+ std::sync::Mutex<Option<pa_core::session_engine::rlm_host::RlmProgressNoteEmit>>,/// The attribution producer the children registry's sink last got:/// children outlive a rebuild, so their spawn registrations are adopted/// forward.diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex b9a0a98269..1abed1189d 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -185,6 +185,8 @@ impl AgentSessionEngine {overflow_recovery: std::sync::Mutex::new(OverflowRecovery::default()),auto_compaction_abort: std::sync::Mutex::new(None),compaction_summary_sink: std::sync::Mutex::new(None),+ progress_notes: std::sync::Mutex::new(None),+ progress_note_emit: std::sync::Mutex::new(None),model_refusal_telemetry,semantic_identity: std::sync::Mutex::new(None),})@@ -271,6 +273,22 @@ impl AgentSessionEngine {.expect("compaction summary sink lock") = Some(sink);}+ /// Installs the worker's accepted-note announcer, threaded into every+ /// session build.+ ///+ /// # Panics+ ///+ /// Panics when the announcer slot's mutex is poisoned.+ pub fn set_progress_note_emit(+ &self,+ emit: pa_core::session_engine::rlm_host::RlmProgressNoteEmit,+ ) {+ *self+ .progress_note_emit+ .lock()+ .expect("progress note emit lock") = Some(emit);+ }+/// The stale-row guard's deferred durable write: the terminal row/// lands AFTER the context adoption, so the active row stops being/// rediscovered.@@ -306,6 +324,11 @@ impl AgentSessionEngine {async fn adopt_built_session(&self, built: &CoreSessionEngine) -> anyhow::Result<()> {self.mirror_goal_runtime(built).await;+ *self+ .progress_notes+ .lock()+ .expect("progress notes mirror lock") =+ Some(std::sync::Arc::clone(&built.rlm_progress_notes));if let Some(sink) = self.compaction_summary_sink.lock()@@ -594,6 +617,7 @@ impl AgentSessionEngine {.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None;*self.goal_runtime.lock().expect("goal runtime lock") = None;+ *self.progress_notes.lock().expect("progress notes lock") = None;*self.turn_agent.lock().expect("turn agent lock") = None;*self.autonomous_boundary@@ -903,6 +927,11 @@ impl AgentSessionEngine {.lock().expect("goal queue purge lock").clone();+ let progress_note_emit = self+ .progress_note_emit+ .lock()+ .expect("progress note emit lock")+ .clone();// The kernel's last live background `bash()` handle settling// (or a mid-run teardown) retries the owed continuations. No// registered arc wires nothing.@@ -960,6 +989,7 @@ impl AgentSessionEngine {rlm_subagent_host: self.children.clone().map(|children| {children as Arc<dyn pa_core::session_engine::rlm_host::RlmSubagentHost>}),+ progress_note_emit,rlm_depth: Some(self.rlm_depth.load(std::sync::atomic::Ordering::Relaxed)),// The worker session runs under the daemon scheduler and its wake-ups.daemonless: false,diff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rsindex 4aa6d107a0..53d238765d 100644--- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs+++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs@@ -314,6 +314,29 @@ impl SessionEngine for AgentSessionEngine {}}+ /// The session's newest accepted progress note; `None` before the+ /// first build and after a run boundary cleared it.+ fn progress_note(&self) -> Option<String> {+ self.progress_notes+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ .and_then(|notes| notes.latest_note())+ .map(|(note, _)| note)+ }++ /// Clears the stored note at the run boundary; the throttle clock stays.+ fn clear_progress_note(&self) {+ if let Some(notes) = self+ .progress_notes+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ {+ notes.clear();+ }+ }+fn configure_service_tier(&self, tier: Option<pa_types::ai::ServiceTier>) {*self.service_tier.write().expect("service tier lock") = tier;if let Some(target) = selfdiff --git a/crates/pa-daemon/src/agent_message_ingest.rs b/crates/pa-daemon/src/agent_message_ingest.rsindex 61217409a3..d389100645 100644--- a/crates/pa-daemon/src/agent_message_ingest.rs+++ b/crates/pa-daemon/src/agent_message_ingest.rs@@ -143,6 +143,7 @@ impl Worker {}}core.follow_up = retained_follow_up;+ crate::worker::clear_withdrawn_progress_note(&core, self.engine.as_ref());let snapshot = Self::snapshot_locked(&core);drop(core);// The sweep may have settled the session: the verdict follows the remaining lanes.diff --git a/crates/pa-daemon/src/engine.rs b/crates/pa-daemon/src/engine.rsindex a8b7a9f7c9..890684d73f 100644--- a/crates/pa-daemon/src/engine.rs+++ b/crates/pa-daemon/src/engine.rs@@ -342,6 +342,16 @@ pub trait SessionEngine: Send + Sync {None}+ /// The session's newest accepted progress note; engines without a note+ /// store report `None`.+ fn progress_note(&self) -> Option<String> {+ None+ }++ /// Clears the stored note at the run boundary; engines without a note+ /// store do nothing.+ fn clear_progress_note(&self) {}+/// The session's autonomous-run status snapshot (the accounting lock/// is async-held, hence the boxed future). The scripted harness reports `None`.fn autonomous_status(diff --git a/crates/pa-daemon/src/prompt_admission.rs b/crates/pa-daemon/src/prompt_admission.rsindex 91aee4828c..2cfd7909a3 100644--- a/crates/pa-daemon/src/prompt_admission.rs+++ b/crates/pa-daemon/src/prompt_admission.rs@@ -581,6 +581,7 @@ impl Worker {core.follow_up.retain(|item| item.admission_id.as_deref() != Some(admission_id));self.prompt_admissions.clear(admission_id);+ crate::worker::clear_withdrawn_progress_note(&core, self.engine.as_ref());}let abort_running = cancel_owned&& status == Some(AdmissionStatus::Owned)@@ -594,6 +595,8 @@ impl Worker {self.checkpoint_queue(crate::worker::QueueCheckpoint::Settle {operation: "queue_dropped",});+ // A cancelled idle admission has no turn-end event to refresh the roster.+ self.push_roster_delta();}if abort_running {self.engine.abort_in_flight_turn();diff --git a/crates/pa-daemon/src/queue_commands.rs b/crates/pa-daemon/src/queue_commands.rsindex 136a42f239..6762bf6bda 100644--- a/crates/pa-daemon/src/queue_commands.rs+++ b/crates/pa-daemon/src/queue_commands.rs@@ -111,6 +111,7 @@ impl Worker {}}}+ crate::worker::clear_withdrawn_progress_note(&core, self.engine.as_ref());(status, true)} else {(status, false)diff --git a/crates/pa-daemon/src/roster_activity.rs b/crates/pa-daemon/src/roster_activity.rsindex 42570cef57..d0864be236 100644--- a/crates/pa-daemon/src/roster_activity.rs+++ b/crates/pa-daemon/src/roster_activity.rs@@ -17,6 +17,9 @@ pub(crate) const ROSTER_PUSH_DISABLE_ENV: &str = "PA_WORKER_DISABLE_ROSTER_PUSH"pub(crate) const ROSTER_SESSION_EVENT_TRIGGERS: &[&str] = &["turn_start","turn_end",+ // The run's end and the accepted note itself change summary fields.+ "agent_end",+ "rlm_progress_note","bash_start","bash_end","compaction_start",@@ -91,6 +94,19 @@ impl RosterPushQueue {Self { inner: None }}+ /// Observe command-triggered publication without an asynchronous consumer.+ #[cfg(test)]+ pub(crate) fn observed_for_test() -> (Self, impl Fn() -> bool) {+ let state = Arc::new(PushState {+ notify: tokio::sync::Notify::new(),+ pending: std::sync::atomic::AtomicBool::new(false),+ });+ let observed = Arc::clone(&state);+ (Self { inner: Some(state) }, move || {+ observed.pending.load(std::sync::atomic::Ordering::SeqCst)+ })+ }+/// Enqueue one flush request: the first request of a burst wakes/// the consumer, every later one only keeps the flag set.pub(crate) fn push(&self) {@@ -227,7 +243,6 @@ mod tests {"message_update","tool_execution_update","agent_start",- "agent_end","goal_update","ipython_sent_agent_message",] {diff --git a/crates/pa-daemon/src/types.rs b/crates/pa-daemon/src/types.rsindex eabe3217a2..88108d600c 100644--- a/crates/pa-daemon/src/types.rs+++ b/crates/pa-daemon/src/types.rs@@ -96,6 +96,10 @@ pub struct SessionSummary {pub modified: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub first_message: Option<String>,+ /// The run's latest accepted `rlm.progress.note`, cleared at the run+ /// boundaries so an idle row never carries one.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub progress_note: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub parent_session_path: Option<String>,/// The parent's live active-session id (subagent summaries).diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rsindex 04db62b0de..6dc4255bf1 100644--- a/crates/pa-daemon/src/worker.rs+++ b/crates/pa-daemon/src/worker.rs@@ -25,11 +25,12 @@ pub use queue::Lane;pub use queue::QueuePriority;pub(crate) use queue::{admit_autonomous_follow_up, admit_bash_completion_notice, admit_goal_follow_up,- checkpoint_queue_recovery, enqueue_priority, gather_delivery_batch, parse_custom_message,- parse_prompt_images, queue_lanes, restore_queue_snapshot, restored_turn_policy,- withdraw_bash_completion_notice, QueueCheckpoint, QueueLanes, QueuedItem, TurnPolicy,- TurnSettle, ABORTED_TURN_SETTLE_ERROR, PROMPT_ABORTED_BEFORE_DELIVERY, QUEUED_INPUT_SUSPENDED,- QUEUED_PROMPT_DELETED, SIDE_QUESTION_SETTLE_TIMEOUT,+ checkpoint_queue_recovery, clear_withdrawn_progress_note, enqueue_priority,+ gather_delivery_batch, parse_custom_message, parse_prompt_images, queue_lanes,+ restore_queue_snapshot, restored_turn_policy, withdraw_bash_completion_notice, QueueCheckpoint,+ QueueLanes, QueuedItem, TurnPolicy, TurnSettle, ABORTED_TURN_SETTLE_ERROR,+ PROMPT_ABORTED_BEFORE_DELIVERY, QUEUED_INPUT_SUSPENDED, QUEUED_PROMPT_DELETED,+ SIDE_QUESTION_SETTLE_TIMEOUT,};mod create;@@ -460,6 +461,7 @@ impl Worker {concrete.set_autonomous_admission(autonomous_sink);let purge_core = Arc::clone(&core);let purge_recovery = Arc::clone(&recovery);+ let purge_engine = Arc::downgrade(concrete);let autonomous_purge: std::sync::Arc<dyn Fn() + Send + Sync> =std::sync::Arc::new(move || {{@@ -470,6 +472,9 @@ impl Worker {core.steering.retain(|item| {item.queue_key.as_deref() != Some(AUTONOMOUS_QUEUE_KEY)});+ if let Some(engine) = purge_engine.upgrade() {+ clear_withdrawn_progress_note(&core, engine.as_ref());+ }}// The withdraw settles the rows: dropping the last// queued row must not leave busy=true promising a@@ -525,11 +530,15 @@ impl Worker {// goal-context turns.let purge_core = Arc::clone(&core);let purge_recovery = Arc::clone(&recovery);+ let purge_engine = Arc::downgrade(concrete);let queue_purge: std::sync::Arc<dyn Fn() + Send + Sync> = Arc::new(move || {{let mut core = purge_core.lock().unwrap();core.steering.retain(|item| !is_goal_context_item(item));core.follow_up.retain(|item| !is_goal_context_item(item));+ if let Some(engine) = purge_engine.upgrade() {+ clear_withdrawn_progress_note(&core, engine.as_ref());+ }}// Same settle as the autonomous withdraw: a pause/clear// cannot leave busy=true.@@ -621,10 +630,33 @@ impl Worker {});let withdraw_core = Arc::clone(&core);let withdraw_recovery = Arc::clone(&recovery);+ let withdraw_engine = Arc::downgrade(concrete);let consumed: crate::engine::BashConsumedSink = Arc::new(move |notice| {- withdraw_bash_completion_notice(&withdraw_recovery, &withdraw_core, ¬ice);+ let engine = withdraw_engine.upgrade();+ withdraw_bash_completion_notice(+ &withdraw_recovery,+ &withdraw_core,+ ¬ice,+ engine.as_deref().map(|engine| engine as &dyn SessionEngine),+ );});concrete.set_bash_notice_sinks(completion, consumed);+ // The accepted note frames as a session event on the pump.+ let note_core = Arc::clone(&core);+ let note_events = events.clone();+ let note_emit: pa_core::session_engine::rlm_host::RlmProgressNoteEmit =+ Arc::new(move |message, timestamp| {+ emit_worker_event_with(+ ¬e_core,+ ¬e_events,+ json!({+ "type": "rlm_progress_note",+ "message": message,+ "timestamp": timestamp,+ }),+ );+ });+ concrete.set_progress_note_emit(note_emit);}// The live roster activity feed (TS `observeRosterEvent`): busy// flips and trigger events coalesce into `worker_roster_delta`diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rsindex 2a791cbc2b..8a59e62972 100644--- a/crates/pa-daemon/src/worker/commands.rs+++ b/crates/pa-daemon/src/worker/commands.rs@@ -1,9 +1,9 @@//! The dispatch surface: command routing, the command handlers,//! and the abort family.use super::{- json, persist_custom_row, response_failure, response_success, KillCloseReason, Lane,- QueueCheckpoint, QueuedItem, Result, SessionFile, TurnSettle, VecDeque, Worker,- PROMPT_ABORTED_BEFORE_DELIVERY, SIDE_QUESTION_SETTLE_TIMEOUT,+ clear_withdrawn_progress_note, json, persist_custom_row, response_failure, response_success,+ KillCloseReason, Lane, QueueCheckpoint, QueuedItem, Result, SessionFile, TurnSettle, VecDeque,+ Worker, PROMPT_ABORTED_BEFORE_DELIVERY, SIDE_QUESTION_SETTLE_TIMEOUT,};use serde_json::Value;@@ -379,6 +379,7 @@ impl Worker {};cancel(&mut core.steering);cancel(&mut core.follow_up);+ clear_withdrawn_progress_note(&core, self.engine.as_ref());}// A withdrawn continuation's pending guard already released at ITS admission,// so the withdraw clears nothing (a mirror clear could drop an unrelated guard).@@ -386,6 +387,8 @@ impl Worker {// The in-flight turn's fetch cancels now, not at its next// streamed event.self.engine.abort_in_flight_turn();+ // An idle withdrawal has no turn-end event to refresh the roster.+ self.push_roster_delta();}fn handle_abort(&self) -> DaemonResponse {@@ -501,6 +504,7 @@ impl Worker {};let steering: Vec<String> = drain_lane(&mut core.steering);let follow_up: Vec<String> = drain_lane(&mut core.follow_up);+ clear_withdrawn_progress_note(&core, self.engine.as_ref());let snapshot = Self::snapshot_locked(&core);drop(core);// The verdict refresh rides the same checkpoint as the snapshot: a stalediff --git a/crates/pa-daemon/src/worker/queue.rs b/crates/pa-daemon/src/worker/queue.rsindex bed5bf4249..1a251c473f 100644--- a/crates/pa-daemon/src/worker/queue.rs+++ b/crates/pa-daemon/src/worker/queue.rs@@ -231,6 +231,17 @@ pub(crate) enum QueueCheckpoint {Settle { operation: &'static str },}+/// Clear a withdrawn run's note before publishing an idle, empty queue.+/// Call while holding the core lock; summary readers take core then note too.+pub(crate) fn clear_withdrawn_progress_note(+ core: &SessionCore,+ engine: &dyn crate::engine::SessionEngine,+) {+ if !core.busy && core.steering.is_empty() && core.follow_up.is_empty() {+ engine.clear_progress_note();+ }+}+/// Write one queue-lane recovery checkpoint: under the recovery lock (then/// the core lock) the lanes and the busy verdict record from the same read.pub(crate) fn checkpoint_queue_recovery(@@ -571,6 +582,7 @@ pub(crate) fn withdraw_bash_completion_notice(recovery: &std::sync::Mutex<Option<WorkerRecoveryJournal>>,core: &Arc<Mutex<SessionCore>>,notice: &crate::engine::BashConsumedNotice,+ engine: Option<&dyn crate::engine::SessionEngine>,) {let removed = {let mut core_guard = core.lock().unwrap();@@ -588,6 +600,9 @@ pub(crate) fn withdraw_bash_completion_notice(};core_guard.steering.retain(&mut withdraw_one);core_guard.follow_up.retain(withdraw_one);+ if let Some(engine) = engine {+ clear_withdrawn_progress_note(&core_guard, engine);+ }before != core_guard.steering.len() + core_guard.follow_up.len()};if removed {diff --git a/crates/pa-daemon/src/worker/recovery_verdict_tests.rs b/crates/pa-daemon/src/worker/recovery_verdict_tests.rsindex 63dadbbd1b..970c84df94 100644--- a/crates/pa-daemon/src/worker/recovery_verdict_tests.rs+++ b/crates/pa-daemon/src/worker/recovery_verdict_tests.rs@@ -198,6 +198,7 @@ async fn bash_consumed_withdraws_the_undelivered_notice_and_settles() {pid: 4321,command: "another command".to_string(),},+ Some(worker.engine.as_ref()),);assert!(worker.core.lock().unwrap().steering.len() == 1,@@ -214,6 +215,8 @@ async fn bash_consumed_withdraws_the_undelivered_notice_and_settles() {pid: 4321,command: "sleep 12; echo RW_WAKE_DONE".to_string(),},+ /*engine*/+ None, // A retired engine must not prevent withdrawal or its checkpoint.);{let core = worker.core.lock().unwrap();diff --git a/crates/pa-daemon/src/worker/summary.rs b/crates/pa-daemon/src/worker/summary.rsindex 84548a160b..d690f22df6 100644--- a/crates/pa-daemon/src/worker/summary.rs+++ b/crates/pa-daemon/src/worker/summary.rs@@ -412,6 +412,7 @@ pub(crate) struct SummaryInputs {pub(crate) bash_running: bool,pub(crate) quota_parked: bool,pub(crate) subagents_running: bool,+ pub(crate) progress_note: Option<String>,}impl SummaryInputs {@@ -447,6 +448,7 @@ impl SummaryInputs {bash_running: user_bash.is_running(),quota_parked: engine.is_quota_parked(),subagents_running: engine.has_running_subagents(),+ progress_note: engine.progress_note(),}}}@@ -577,6 +579,7 @@ pub(crate) fn session_summary(core: &SessionCore, inputs: SummaryInputs) -> Sesscreated: store.map(|s| s.header.timestamp.clone()),modified,first_message: store.and_then(crate::session_store::SessionFile::first_message),+ progress_note: inputs.progress_note,parent_session_path: store.and_then(|store| store.header.parent_session.clone()),parent_active_session_id: core.parent_active_session_id.clone(),parent_session_id: core.parent_session_id.clone(),diff --git a/crates/pa-daemon/src/worker/tests/summary_tests.rs b/crates/pa-daemon/src/worker/tests/summary_tests.rsindex 36cc8d40bb..ace3ae1bf6 100644--- a/crates/pa-daemon/src/worker/tests/summary_tests.rs+++ b/crates/pa-daemon/src/worker/tests/summary_tests.rs@@ -9,6 +9,7 @@ fn inputs() -> SummaryInputs {bash_running: false,quota_parked: false,subagents_running: false,+ progress_note: None,}}@@ -263,3 +264,77 @@ fn display_ids_are_twelve_hex() {assert_eq!(id.len(), 12);assert!(id.chars().all(|c| c.is_ascii_hexdigit()));}++/// The summary carries the live note, and the next run's boundaries clear it.+#[allow(clippy::await_holding_lock)] // the faux registry is process-global: the guard must span the async flow+#[tokio::test]+async fn summary_carries_the_live_note_until_the_run_boundaries_clear_it() {+ let _faux = crate::agent_engine::tests::FAUX_TEST_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let dir = std::env::temp_dir().join(format!("pa-worker-note-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let config = WorkerConfig {+ socket_path: dir.join("worker.sock"),+ supervisor_socket_path: std::path::PathBuf::new(),+ token: "token".to_string(),+ worker_instance_id: String::new(),+ active_session_id: "note-session".to_string(),+ agent_dir: dir.join("agent"),+ recovery_journal_path: dir.join("recovery.jsonl"),+ telemetry_disabled: None,+ script: Some(json!({+ "engine": "faux",+ "responses": ["first reply", "second reply"],+ })),+ };+ let worker = std::sync::Arc::new(Worker::new(config, None));+ let created = worker+ .dispatch(+ "create",+ &json!({ "noSession": true, "cwd": "/tmp", "name": "note" }),+ )+ .await;+ assert!(created.success, "create failed: {created:?}");+ let first = worker+ .dispatch(+ "prompt_and_wait",+ &json!({ "activeSessionId": "note-session", "message": "hello" }),+ )+ .await;+ assert!(first.success, "the first turn failed: {first:?}");+ let engine = worker+ .agent_engine+ .as_ref()+ .expect("the faux worker runs the real engine");+ let notes = engine+ .progress_notes+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone()+ .expect("the built session mirrored its note store");+ assert!(+ notes.note("running tests", 0).accepted,+ "the fresh store accepts the injected note"+ );+ let state = worker.dispatch("get_state", &json!({})).await;+ assert!(state.success, "get_state failed: {state:?}");+ assert_eq!(+ state.data.as_ref().unwrap_or(&Value::Null)["progressNote"],+ json!("running tests"),+ "the summary carries the live note: {state:?}"+ );+ let second = worker+ .dispatch(+ "prompt_and_wait",+ &json!({ "activeSessionId": "note-session", "message": "again" }),+ )+ .await;+ assert!(second.success, "the second turn failed: {second:?}");+ let state = worker.dispatch("get_state", &json!({})).await;+ let summary = state.data.unwrap_or(Value::Null);+ assert!(+ summary.get("progressNote").is_none(),+ "the run boundary cleared the note: {summary:?}"+ );+}diff --git a/crates/pa-daemon/src/worker/turn.rs b/crates/pa-daemon/src/worker/turn.rsindex 622e8a0960..f325489962 100644--- a/crates/pa-daemon/src/worker/turn.rs+++ b/crates/pa-daemon/src/worker/turn.rs@@ -374,6 +374,7 @@ impl TurnRunner {// Own engine clone, fenced on the session identity it serviced:// a branch move or replacement swaps the store mid-review.let review_engine = std::sync::Arc::clone(&engine);+ let settle_engine = std::sync::Arc::clone(&engine);let review_session_id = {let core = self.core.lock().unwrap();core.store@@ -476,6 +477,19 @@ impl TurnRunner {| EngineEvent::DoneAborted);let mut core = core.lock().unwrap();+ // The run's TRUE end — an `agent_end` with no queued work+ // taking the next turn — keys both the note clear here and+ // the pane's idle debounce below. An internal boundary that+ // hands the next turn to queued work (the async bash+ // completion that cut this run) keeps the note for the work+ // continuing in the next delivery. Clear before the frame:+ // its roster flush must not publish the stale note.+ let agent_end = matches!(event, EngineEvent::AgentEnd { .. });+ let more_queued =+ agent_end && (!core.steering.is_empty() || !core.follow_up.is_empty());+ if agent_end && !more_queued {+ engine.clear_progress_note();+ }if core.abort_requested {// The sighting arms the fallback's silence only when// load-bearing: a sighting on a run that completed on its own@@ -509,7 +523,6 @@ impl TurnRunner {herdr_run_end_seen.store(false, std::sync::atomic::Ordering::SeqCst);}EngineEvent::AgentEnd { messages } => {- let more_queued = !core.steering.is_empty() || !core.follow_up.is_empty();herdr.lock().unwrap()@@ -1001,12 +1014,24 @@ impl TurnRunner {coalescer.close();flusher.abort();- {+ let engine_reported_run_end = engine_agent_end.load(std::sync::atomic::Ordering::SeqCst);+ let more_queued = {let mut core = self.core.lock().unwrap();+ let more_queued = !core.steering.is_empty() || !core.follow_up.is_empty();+ // Publish the note clear and idle transition atomically to+ // roster readers, which capture core then the engine note.+ // An abort-gated run may emit no later event to repair a+ // roster push that observes idle with its old note.+ // AgentEnd may have retained the note for work withdrawn before+ // this settle. Recheck the lanes even when that frame was observed.+ if !more_queued {+ settle_engine.clear_progress_note();+ }core.busy = false;core.active_action = None;core.running_admission_ids.clear();- }+ more_queued+ };self.push_roster_delta();// The fallback `agent_end` for runs that ended without a model// turn (session commands, pre-model failures): the engine's own@@ -1026,7 +1051,6 @@ impl TurnRunner {// (the flag stays armed until the next pickup — a settle-time// re-read would race `handle_abort` and silence a completed// session-command or pre-model-failure run).- let engine_reported_run_end = engine_agent_end.load(std::sync::atomic::Ordering::SeqCst);if !engine_reported_run_end && !abort_gate_armed.load(std::sync::atomic::Ordering::SeqCst) {self.emit_turn_event(json!({ "type": "agent_end" }));}@@ -1046,13 +1070,7 @@ impl TurnRunner {// `core.busy` flipped to false above; queued lanes still// holding items keep the settle debounced so the next pickup// cancels the idle flip.- let (error_hold, more_queued) = {- let core = self.core.lock().unwrap();- (- herdr_settle_error.lock().unwrap().take(),- !core.steering.is_empty() || !core.follow_up.is_empty(),- )- };+ let error_hold = herdr_settle_error.lock().unwrap().take();if !herdr_run_end.load(std::sync::atomic::Ordering::SeqCst) {self.herdr.lock()diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rsindex b55ef96f12..73a7f896ab 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs@@ -763,3 +763,422 @@ async fn abort_and_send_queued_acks_before_the_follow_up_delivery() {);let _ = std::fs::remove_dir_all(&dir);}++#[derive(Default)]+struct NoteWitnessEngine {+ note: Mutex<Option<String>>,+ note_at_notice_turn: Mutex<Option<String>>,+ withdraw_follow_up_after_end: Mutex<Option<Arc<Mutex<SessionCore>>>>,+ turns: std::sync::atomic::AtomicUsize,+}++impl SessionEngine for NoteWitnessEngine {+ fn progress_note(&self) -> Option<String> {+ self.note.lock().unwrap().clone()+ }++ fn clear_progress_note(&self) {+ *self.note.lock().unwrap() = None;+ }++ fn run_prompt(+ &self,+ _prompt_index: usize,+ _request: PromptRequest,+ _aborted: &dyn Fn() -> bool,+ emit: &mut dyn FnMut(EngineEvent) -> bool,+ ) {+ emit(EngineEvent::AgentStart);+ if self.turns.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {+ // Turn one: the mid-run note acceptance (the model's+ // `rlm.progress_note`).+ *self.note.lock().unwrap() = Some("halfway through the review".to_string());+ } else {+ *self.note_at_notice_turn.lock().unwrap() = self.note.lock().unwrap().clone();+ }+ emit(EngineEvent::AgentEnd {+ messages: Vec::new(),+ });+ if let Some(core) = self.withdraw_follow_up_after_end.lock().unwrap().take() {+ // A queue withdrawal can land after AgentEnd but before the runner settles.+ core.lock().unwrap().follow_up.clear();+ }+ }++ fn run_side_question(+ &self,+ _request: SideQuestionRequest,+ _signal: &pa_agent::abort::AbortSignal,+ _sink: &pa_core::session_engine::side_question::SideQuestionSink,+ ) -> SideQuestionOutcome {+ SideQuestionOutcome::Failed {+ answer: String::new(),+ error: "unsupported".to_string(),+ }+ }++ fn run_compaction(+ &self,+ _request: CompactionRequest,+ _signal: &pa_agent::abort::AbortSignal,+ ) -> CompactionOutcome {+ CompactionOutcome::Skipped {+ message: "nothing to compact".to_string(),+ }+ }++ fn run_branch_summary(+ &self,+ _request: crate::engine::BranchSummaryRequest,+ _signal: &pa_agent::abort::AbortSignal,+ ) -> crate::engine::BranchSummaryOutcome {+ crate::engine::BranchSummaryOutcome::Failed {+ error: "unsupported".to_string(),+ }+ }++ fn rebuild_session_context(+ &self,+ _branch_entries: Vec<pa_types::session::FileEntry>,+ _goal_reload: pa_core::session_engine::goal_driver::GoalBranchReload,+ ) -> anyhow::Result<()> {+ Ok(())+ }+}++/// The queued async bash completion's delivery keeps the note its cut run+/// accepted mid-flight; the note clears only at the run's true end.+#[tokio::test]+async fn the_async_completion_notice_delivery_keeps_the_live_note() {+ let engine = Arc::new(NoteWitnessEngine::default());+ let runner = burst_runner(engine.clone());+ // The busy-session row `admit_bash_completion_notice` queues.+ runner+ .core+ .lock()+ .unwrap()+ .steering+ .push_back(queued_prompt(+ "[bash-done pid:4321 exit:137]",+ TurnPolicy::Queued,+ ));+ // Turn one's end is the steering cut; the runner then hands the queued+ // notice its own turn.+ runner+ .run_turn(+ engine.clone(),+ vec![queued_prompt("review the installer", TurnPolicy::Queued)],+ )+ .await;+ assert_eq!(+ engine.note.lock().unwrap().as_deref(),+ Some("halfway through the review"),+ "the steering-cut run end must keep the live note"+ );+ let notice = runner.core.lock().unwrap().steering.pop_front();+ runner+ .run_turn(engine.clone(), vec![notice.expect("the queued notice row")])+ .await;+ assert_eq!(+ engine.note_at_notice_turn.lock().unwrap().as_deref(),+ Some("halfway through the review"),+ "the notice's turn must still see the live note"+ );+ assert!(+ engine.note.lock().unwrap().is_none(),+ "the lanes-empty run end cleared the note"+ );+}++/// An ordinary queued follow-up retains the note until its own final end, like steering.+#[tokio::test]+async fn queued_follow_up_keeps_the_note_until_its_final_end() {+ let engine = Arc::new(NoteWitnessEngine::default());+ let runner = burst_runner(engine.clone());+ runner+ .core+ .lock()+ .unwrap()+ .follow_up+ .push_back(queued_prompt(+ "also check the deployment",+ TurnPolicy::Queued,+ ));+ runner+ .run_turn(+ engine.clone(),+ vec![queued_prompt("review", TurnPolicy::Queued)],+ )+ .await;+ assert_eq!(+ engine.progress_note().as_deref(),+ Some("halfway through the review")+ );+ let follow_up = runner.core.lock().unwrap().follow_up.pop_front().unwrap();+ runner.run_turn(engine.clone(), vec![follow_up]).await;+ assert_eq!(+ engine.note_at_notice_turn.lock().unwrap().as_deref(),+ Some("halfway through the review")+ );+ assert_eq!(engine.progress_note(), None);+}++/// `AgentEnd`'s queued-work decision must be reconsidered if the queue is withdrawn+/// before the final idle snapshot.+#[tokio::test]+async fn withdrawing_follow_up_after_agent_end_clears_the_note_at_settle() {+ let engine = Arc::new(NoteWitnessEngine::default());+ let runner = burst_runner(engine.clone());+ runner+ .core+ .lock()+ .unwrap()+ .follow_up+ .push_back(queued_prompt("withdraw this follow-up", TurnPolicy::Queued));+ *engine.withdraw_follow_up_after_end.lock().unwrap() = Some(Arc::clone(&runner.core));+ runner+ .run_turn(+ engine.clone(),+ vec![queued_prompt("review", TurnPolicy::Queued)],+ )+ .await;+ assert!(!runner.core.lock().unwrap().busy);+ assert_eq!(+ engine.progress_note(),+ None,+ "idle must not retain the canceled work's note"+ );+}++/// Clearing queued work while a run is active preserves its note, but clearing the+/// last queued work after the run settled ends the retained note's lifetime.+#[tokio::test]+async fn clearing_an_idle_queue_drops_the_retained_note() {+ let dir = tempfile::tempdir().unwrap();+ let engine = Arc::new(NoteWitnessEngine::default());+ let mut worker = Worker::new(+ WorkerConfig {+ socket_path: dir.path().join("worker.sock"),+ supervisor_socket_path: dir.path().join("supervisor.sock"),+ token: "token".to_string(),+ worker_instance_id: String::new(),+ active_session_id: "note-session".to_string(),+ agent_dir: dir.path().join("agent"),+ recovery_journal_path: dir.path().join("recovery.jsonl"),+ telemetry_disabled: Some(true),+ script: Some(json!({ "responses": ["unused"] })),+ },+ None,+ );+ worker.engine = engine.clone();+ *engine.note.lock().unwrap() = Some("checking deployment".to_string());+ {+ let mut core = worker.core.lock().unwrap();+ core.created = true;+ core.busy = true;+ core.follow_up+ .push_back(queued_prompt("queued", TurnPolicy::Queued));+ }+ assert!(worker.dispatch("clear_queue", &json!({})).await.success);+ assert_eq!(+ engine.progress_note().as_deref(),+ Some("checking deployment")+ );+ {+ let mut core = worker.core.lock().unwrap();+ core.busy = false;+ core.queued_input_suspended = true;+ core.follow_up+ .push_back(queued_prompt("queued", TurnPolicy::Queued));+ }+ assert!(worker.dispatch("clear_queue", &json!({})).await.success);+ assert_eq!(+ engine.progress_note(),+ None,+ "no remaining work can replace the stale note"+ );+}++/// An engine whose run parks mid-flight until the worker aborts, then+/// ends with the abort gate armed and no `agent_end` of its own: the+/// user stop that cuts the run at the source.+#[derive(Default)]+struct AbortSwallowedEngine {+ note: Mutex<Option<String>>,+ clear_gate: Option<Arc<NoteClearGate>>,+}++struct NoteClearGate {+ entered: Notify,+ release: Mutex<std::sync::mpsc::Receiver<()>>,+}++impl SessionEngine for AbortSwallowedEngine {+ fn progress_note(&self) -> Option<String> {+ self.note.lock().unwrap().clone()+ }++ fn clear_progress_note(&self) {+ if let Some(gate) = &self.clear_gate {+ gate.entered.notify_one();+ gate.release+ .lock()+ .unwrap()+ .recv_timeout(std::time::Duration::from_secs(10))+ .expect("the test releases the note clear");+ }+ *self.note.lock().unwrap() = None;+ }++ fn run_prompt(+ &self,+ _prompt_index: usize,+ _request: PromptRequest,+ aborted: &dyn Fn() -> bool,+ emit: &mut dyn FnMut(EngineEvent) -> bool,+ ) {+ emit(EngineEvent::AgentStart);+ // The mid-run note acceptance (the model's `rlm.progress_note`).+ *self.note.lock().unwrap() = Some("halfway through the review".to_string());+ // Park until the user's stop lands mid-flight.+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);+ while !aborted() {+ assert!(+ std::time::Instant::now() < deadline,+ "the test never aborted the run"+ );+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ // The stop cuts the next event before it settles: the abort gate+ // arms on the sighting and the run ends with NO `agent_end`.+ emit(EngineEvent::AgentStart);+ }++ fn run_side_question(+ &self,+ _request: SideQuestionRequest,+ _signal: &pa_agent::abort::AbortSignal,+ _sink: &pa_core::session_engine::side_question::SideQuestionSink,+ ) -> SideQuestionOutcome {+ SideQuestionOutcome::Failed {+ answer: String::new(),+ error: "unsupported".to_string(),+ }+ }++ fn run_compaction(+ &self,+ _request: CompactionRequest,+ _signal: &pa_agent::abort::AbortSignal,+ ) -> CompactionOutcome {+ CompactionOutcome::Skipped {+ message: "nothing to compact".to_string(),+ }+ }++ fn run_branch_summary(+ &self,+ _request: crate::engine::BranchSummaryRequest,+ _signal: &pa_agent::abort::AbortSignal,+ ) -> crate::engine::BranchSummaryOutcome {+ crate::engine::BranchSummaryOutcome::Failed {+ error: "unsupported".to_string(),+ }+ }++ fn rebuild_session_context(+ &self,+ _branch_entries: Vec<pa_types::session::FileEntry>,+ _goal_reload: pa_core::session_engine::goal_driver::GoalBranchReload,+ ) -> anyhow::Result<()> {+ Ok(())+ }+}++/// The abort gate swallows the stopped run's `agent_end`, but the pane+/// still settles idle at the same settle: the note — the roster+/// summary's `progressNote` source — must not survive that idle settle.+#[tokio::test]+async fn an_aborted_run_clears_the_note_at_its_idle_settle() {+ let engine = Arc::new(AbortSwallowedEngine::default());+ let runner = burst_runner(engine.clone());+ let core = std::sync::Arc::clone(&runner.core);+ let engine_for_turn = std::sync::Arc::clone(&engine);+ let turn = tokio::spawn(async move {+ runner+ .run_turn(+ engine_for_turn,+ vec![queued_prompt("review the gate", TurnPolicy::Queued)],+ )+ .await;+ });+ // The run parks mid-flight: wait for the note, then stop the run.+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);+ while engine.progress_note().is_none() {+ assert!(+ std::time::Instant::now() < deadline,+ "the run never set its note"+ );+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;+ }+ core.lock().unwrap().abort_requested = true;+ let _ = turn.await;+ assert!(+ engine.note.lock().unwrap().is_none(),+ "the aborted run's idle settle must clear the note"+ );+}++/// Pause the note clear so a roster reader can attempt the same+/// core-then-note snapshot as `SummaryInputs`. Idle must never become+/// observable with the stopped run's note still present.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn an_aborted_run_never_exposes_an_idle_summary_with_its_old_note() {+ let (release, receiver) = std::sync::mpsc::channel();+ let gate = Arc::new(NoteClearGate {+ entered: Notify::new(),+ release: Mutex::new(receiver),+ });+ let engine = Arc::new(AbortSwallowedEngine {+ note: Mutex::new(None),+ clear_gate: Some(Arc::clone(&gate)),+ });+ let runner = burst_runner(engine.clone());+ let core = Arc::clone(&runner.core);+ core.lock().unwrap().busy = true;+ let engine_for_turn = Arc::clone(&engine);+ let turn = tokio::spawn(async move {+ runner+ .run_turn(+ engine_for_turn,+ vec![queued_prompt("review the gate", TurnPolicy::Queued)],+ )+ .await;+ });+ tokio::time::timeout(std::time::Duration::from_secs(10), async {+ while engine.progress_note().is_none() {+ tokio::task::yield_now().await;+ }+ })+ .await+ .expect("the run publishes a progress note");+ core.lock().unwrap().abort_requested = true;+ tokio::time::timeout(std::time::Duration::from_secs(10), gate.entered.notified())+ .await+ .expect("the aborted run reaches its note clear");+ let exposed_stale_idle = match core.try_lock() {+ Ok(core) => !core.busy && engine.progress_note().is_some(),+ Err(std::sync::TryLockError::WouldBlock) => false,+ Err(error) => panic!("the summary lock is poisoned: {error}"),+ };+ release.send(()).unwrap();+ turn.await.unwrap();+ assert!(+ !exposed_stale_idle,+ "an idle roster snapshot could retain the aborted run's progress note"+ );+ assert!(!core.lock().unwrap().busy);+ assert!(engine.progress_note().is_none());+}++mod withdrawal;diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/queue/withdrawal.rs b/crates/pa-daemon/src/worker/turn_stream_tests/queue/withdrawal.rsnew file mode 100644index 0000000000..4986bc9435--- /dev/null+++ b/crates/pa-daemon/src/worker/turn_stream_tests/queue/withdrawal.rs@@ -0,0 +1,120 @@+//! Real withdrawal commands preserve active/remaining work and clear the last idle note.+use super::*;++#[tokio::test]+async fn queue_withdrawals_clear_only_the_last_idle_notes() {+ for command in [+ "mutate_queued_message",+ "cancel_prompt_admission",+ "agent_messages_pause",+ "agent_messages_clear",+ "bash_consumed",+ "abort",+ ] {+ for state in ["last", "busy", "remaining"] {+ let dir = tempfile::tempdir().unwrap();+ let engine = Arc::new(NoteWitnessEngine::default());+ let mut worker = Worker::new(+ WorkerConfig {+ socket_path: dir.path().join("worker.sock"),+ supervisor_socket_path: dir.path().join("supervisor.sock"),+ token: "token".to_string(),+ worker_instance_id: String::new(),+ active_session_id: "withdraw-note".to_string(),+ agent_dir: dir.path().join("agent"),+ recovery_journal_path: dir.path().join("recovery.jsonl"),+ telemetry_disabled: Some(true),+ script: Some(json!({ "responses": ["unused"] })),+ },+ None,+ );+ worker.engine = engine.clone();+ let (roster_pushes, publication_pending) =+ crate::roster_activity::RosterPushQueue::observed_for_test();+ worker.roster_pushes = roster_pushes;+ // Represent a run whose AgentEnd retained its note for queued work.+ *engine.note.lock().unwrap() = Some("checking deployment".to_string());+ worker.register_prompt_admission("owned-note");+ assert!(worker.prompt_admissions.commit("owned-note"));+ {+ let mut core = worker.core.lock().unwrap();+ core.created = true;+ core.busy = state == "busy";+ core.queued_input_suspended = true;+ if command != "bash_consumed" {+ let mut row = queued_prompt("withdraw me", TurnPolicy::Queued);+ row.admission_id = Some("owned-note".to_string());+ if command.starts_with("agent_messages_") {+ row.agent_message = Some("message-note".to_string());+ }+ if command == "abort" {+ row.queue_visible = false;+ }+ core.follow_up.push_back(row);+ }+ if state == "remaining" {+ let mut row = queued_prompt("keep me", TurnPolicy::Queued);+ row.queue_visible = true;+ core.steering.push_back(row);+ }+ }+ if command == "bash_consumed" {+ admit_bash_completion_notice(+ &worker.recovery,+ &worker.core,+ &Arc::new(Notify::new()),+ &crate::engine::BashCompletionNotice {+ pid: 4321,+ command: "fixture command".to_string(),+ exit_code: 0,+ },+ || false,+ );+ withdraw_bash_completion_notice(+ &worker.recovery,+ &worker.core,+ &crate::engine::BashConsumedNotice {+ pid: 4321,+ command: "fixture command".to_string(),+ },+ Some(engine.as_ref()),+ );+ } else {+ let payload = match command {+ "mutate_queued_message" => json!({+ "lane": "followUp", "index": 0, "expectedText": "withdraw me",+ "mutation": { "type": "delete" },+ }),+ "cancel_prompt_admission" => json!({+ "admissionId": "owned-note", "cancelOwned": true,+ }),+ _ => json!({}),+ };+ let response = worker.dispatch(command, &payload).await;+ assert!(response.success, "{command}/{state}: {response:?}");+ if command == "mutate_queued_message" {+ assert_eq!(response.data, Some(json!({ "status": "applied" })));+ }+ }+ let core = worker.core.lock().unwrap();+ assert!(core.follow_up.is_empty(), "{command}/{state}");+ assert_eq!(+ core.steering.len(),+ usize::from(state == "remaining"),+ "{command}/{state}"+ );+ let expected = (state != "last").then(|| "checking deployment".to_string());+ assert_eq!(engine.progress_note(), expected, "{command}/{state}");+ drop(core);+ if matches!(command, "cancel_prompt_admission" | "abort") {+ assert!(publication_pending(), "{command}/{state}: no roster push");+ let (core, inputs) = worker.summary_inputs();+ let summary = crate::worker::summary::session_summary(&core, inputs);+ assert_eq!(+ summary.progress_note, expected,+ "{command}/{state}: summary"+ );+ }+ }+ }+}diff --git a/crates/pa-daemon/tests/agent_family_e2e.rs b/crates/pa-daemon/tests/agent_family_e2e.rsindex 1bb8880bde..0d736cb382 100644--- a/crates/pa-daemon/tests/agent_family_e2e.rs+++ b/crates/pa-daemon/tests/agent_family_e2e.rs@@ -1242,6 +1242,7 @@ async fn parent_renames_a_child_end_to_end() {pa_core::session_engine::runtime_wiring::RlmWiring {model_registry: None,subagent_host: Some(Arc::clone(&children) as Arc<dyn RlmSubagentHost>),+ progress_note_emit: None,},None,None,diff --git a/crates/pa-tui/src/agents_view/render.rs b/crates/pa-tui/src/agents_view/render.rsindex 5d7e3e80ae..c9e8263373 100644--- a/crates/pa-tui/src/agents_view/render.rs+++ b/crates/pa-tui/src/agents_view/render.rs@@ -258,6 +258,9 @@ impl AgentsViewMode {Spacer,Heading(Section),Row(usize, &'a AgentsViewRow),+ /// One note line of the selected row's expansion; one item per+ /// line so the viewport clips at line granularity.+ Detail(Line),}// The click surface records this render's visible rows; the early exits below leave it// empty.@@ -274,6 +277,11 @@ impl AgentsViewMode {return vec![vec![self.theme.fg(ThemeColor::Dim, text.to_string())]];}let layout = build_layout(&self.rows, width);+ let mut note_details = self+ .rows+ .get(self.selected)+ .map(|row| self.render_note_details(row, width))+ .filter(|details| !details.is_empty());// Each non-empty section contributes a spacer (when not first), its heading, then its rows.let counts: Vec<(Section, usize)> = [Section::Running, Section::Idle, Section::Inactive].into_iter()@@ -306,16 +314,23 @@ impl AgentsViewMode {}if include {display.push(DisplayItem::Row(index, row));+ if index == self.selected {+ if let Some(details) = note_details.take() {+ display.extend(details.into_iter().map(DisplayItem::Detail));+ }+ }}}}} else {- display.extend(- self.rows- .iter()- .enumerate()- .map(|(index, row)| DisplayItem::Row(index, row)),- );+ for (index, row) in self.rows.iter().enumerate() {+ display.push(DisplayItem::Row(index, row));+ if index == self.selected {+ if let Some(details) = note_details.take() {+ display.extend(details.into_iter().map(DisplayItem::Detail));+ }+ }+ }}// The viewport: reserve the column header and its spacer, center the slice on the// selected row, clip the overflow — a re-sorting rebuild keeps the selection on-screen.@@ -331,18 +346,46 @@ impl AgentsViewMode {|item| matches!(item, DisplayItem::Row(_, row) if Some(row.identity.as_str()) == selected_identity),).map_or(-1, |index| index as isize);+ let detail_count = display+ .iter()+ .filter(|item| matches!(item, DisplayItem::Detail(_)))+ .count() as isize;+ let block_end = selected_display_index + detail_count;let anchor = selected_display_index - (visible_rows / 2) as isize;let upper = display.len() as isize - visible_rows as isize;let start = anchor.min(upper).max(0) as usize;- let show_leading = start > 0 && visible_rows > 1;- let show_trailing = start + visible_rows < display.len() && visible_rows > 2;- let content_rows = visible_rows - usize::from(show_leading) - usize::from(show_trailing);- let slice_start = if selected_display_index >= start as isize + content_rows as isize {- (selected_display_index + 1 - content_rows as isize) as usize- } else {- start- };- let slice_end = (slice_start + content_rows).min(display.len());+ // The clip markers read the FINAL slice: the shift below can move+ // the slice past the section heading of a top selection, and a+ // hidden side must always paint its `...`. The markers' rows fold+ // out of the row budget before the slice is placed, so the reserved+ // rows and the painted `...` agree with what the slice actually+ // hides — the markers only turn on as the budget shrinks, so the+ // fold settles in a pass or two.+ let mut show_leading = start > 0 && visible_rows > 1;+ let mut show_trailing = start + visible_rows < display.len() && visible_rows > 2;+ let mut content_rows =+ visible_rows - usize::from(show_leading) - usize::from(show_trailing);+ let mut slice_start;+ let mut slice_end;+ loop {+ // Shift the window forward when the selected row's note block+ // is taller than the anchored window: pin the block's tail to+ // the window's bottom edge, never past the selected row.+ slice_start = if block_end >= start as isize + content_rows as isize {+ (block_end + 1 - content_rows as isize).min(selected_display_index) as usize+ } else {+ start+ };+ slice_end = (slice_start + content_rows).min(display.len());+ let leading = slice_start > 0 && visible_rows > 1;+ let trailing = slice_end < display.len() && visible_rows > 2;+ if (leading, trailing) == (show_leading, show_trailing) {+ break;+ }+ show_leading = leading;+ show_trailing = trailing;+ content_rows = visible_rows - usize::from(leading) - usize::from(trailing);+ }// The viewport's front rows shift the session rows down — the click rows and the hover// band carry the shift.let shift = header_rows + usize::from(show_leading);@@ -374,6 +417,9 @@ impl AgentsViewMode {click_rows.push((local, *index));}}+ DisplayItem::Detail(detail) => {+ lines.push(detail.clone());+ }}}if show_leading {@@ -565,6 +611,43 @@ impl AgentsViewMode {finish_session_row(theme, line, selected, hovered, width)}+ /// The selected agent/subagent row's progress note: wrapped,+ /// indented to the title column, dim; other row kinds render nothing.+ pub(super) fn render_note_details(&self, row: &AgentsViewRow, width: usize) -> Vec<Line> {+ if width == 0 || !matches!(row.kind, RowKind::Agent | RowKind::Subagent) {+ return Vec::new();+ }+ let Some(note) = row+ .summary+ .get("progressNote")+ .and_then(Value::as_str)+ .map(|text| text.split_whitespace().collect::<Vec<_>>().join(" "))+ .filter(|text| !text.is_empty())+ else {+ return Vec::new();+ };+ // Keep room for a wide character when nesting exceeds the pane.+ let indent_width = row+ .depth+ .saturating_add(1)+ .saturating_mul(2)+ .min(width.saturating_sub(2));+ let indent = " ".repeat(indent_width);+ let dim = self.theme.fg_style(ThemeColor::Dim);+ let wrap_width = width.saturating_sub(str_width(&indent)).max(1);+ crate::width::wrap_text(¬e, wrap_width)+ .into_iter()+ .map(|mut wrapped| {+ let mut out: Line = vec![crate::Span::styled(indent.clone(), dim)];+ for span in wrapped.drain(..) {+ out.push(crate::Span::styled(span.content, dim));+ }+ // A one-column pane cannot contain a wide character.+ crate::width::slice_line_by_column_strict(&out, 0, width, true)+ })+ .collect()+ }+/// The bottom hint/status line. `status_override` carries the/// notice's first line when the degenerate pane skipped the panel.pub(super) fn render_hints(&self, width: usize, status_override: Option<&str>) -> Line {diff --git a/crates/pa-tui/src/agents_view/tests.rs b/crates/pa-tui/src/agents_view/tests.rsindex 2b08dd7ca8..a0ca7ab59c 100644--- a/crates/pa-tui/src/agents_view/tests.rs+++ b/crates/pa-tui/src/agents_view/tests.rs@@ -16,6 +16,7 @@ mod hints_render;mod hover_band;mod key_bindings;mod notices;+mod progress_note;mod render_pulse;mod reply;mod running_lines;diff --git a/crates/pa-tui/src/agents_view/tests/progress_note.rs b/crates/pa-tui/src/agents_view/tests/progress_note.rsnew file mode 100644index 0000000000..8480c56b9b--- /dev/null+++ b/crates/pa-tui/src/agents_view/tests/progress_note.rs@@ -0,0 +1,271 @@+//! The selected agent row's progress-note expansion and its viewport+//! behavior.++use super::*;++fn note_into(mode: &mut AgentsViewMode, index: usize, note: &str) {+ mode.rows[index]+ .summary+ .as_object_mut()+ .expect("row summary is an object")+ .insert("progressNote".to_string(), serde_json::json!(note));+}++fn flat_lines(mode: &mut AgentsViewMode, width: usize, max_rows: usize) -> Vec<String> {+ mode.render_list(width, max_rows, 0)+ .iter()+ .map(flat)+ .collect()+}++fn note_line_count(lines: &[String]) -> usize {+ lines+ .iter()+ .filter(|line| line.starts_with(" word"))+ .count()+}++/// The selected row expands its note under it; unselected rows never expand.+#[test]+fn the_selected_row_expands_its_wrapped_note() {+ let (mut mode, index) = mode_with_row("worker", "mock-1");+ note_into(&mut mode, index, "running the\n final gate suite");+ mode.selected = index;+ let lines = flat_lines(&mut mode, 60, 30);+ let worker_row = lines+ .iter()+ .position(|line| line.contains("worker"))+ .expect("the worker row renders");+ assert_eq!(+ lines[worker_row + 1].trim(),+ "running the final gate suite",+ "the note line renders collapsed under the row: {lines:?}"+ );+ assert_eq!(+ &lines[worker_row + 1][..2],+ " ",+ "the note indents to the title column: {lines:?}"+ );+ assert_eq!(lines.len(), worker_row + 2, "no further lines: {lines:?}");+ let rendered = mode.render_list(60, 30, 0);+ let dim = mode.theme.fg_style(ThemeColor::Dim);+ assert!(+ rendered[worker_row + 1]+ .iter()+ .all(|span| span.style == dim),+ "the note renders dim"+ );+ mode.selected = 0;+ let lines = flat_lines(&mut mode, 60, 30);+ assert!(+ !lines.iter().any(|line| line.contains("gate")),+ "an unselected row never expands: {lines:?}"+ );+}++/// A long note wraps within the width, keeps the indent, and carries the+/// whole text.+#[test]+fn a_long_note_wraps_within_the_width() {+ let (mut mode, index) = mode_with_row("worker", "mock-1");+ let note = (0..30)+ .map(|n| format!("word{n}"))+ .collect::<Vec<_>>()+ .join(" ");+ note_into(&mut mode, index, ¬e);+ mode.selected = index;+ let width = 40;+ let lines = flat_lines(&mut mode, width, 40);+ let worker_row = lines+ .iter()+ .position(|line| line.contains("worker"))+ .expect("the worker row renders");+ let note_lines: Vec<&String> = lines[worker_row + 1..]+ .iter()+ .take_while(|line| line.starts_with(" word"))+ .collect();+ assert!(note_lines.len() > 1, "the note wrapped: {note_lines:?}");+ for line in ¬e_lines {+ assert!(str_width(line) <= width, "a line overran: {line:?}");+ assert!(line.starts_with(" "), "a line lost the indent: {line:?}");+ }+ let joined = note_lines+ .iter()+ .map(|line| line.trim())+ .collect::<Vec<_>>()+ .join(" ");+ assert_eq!(joined, note, "the wrapped lines carry the whole note");+}++#[test]+fn a_nested_note_fits_when_the_pane_is_narrower_than_its_indent() {+ let (mut mode, index) = mode_with_row("worker", "mock-1");+ mode.rows[index].kind = RowKind::Subagent;+ mode.rows[index].depth = 3;+ note_into(&mut mode, index, "checking");+ for width in [1, 4, 8, 9] {+ let lines = mode.render_note_details(&mode.rows[index], width);+ assert!(!lines.is_empty());+ let text: String = lines+ .iter()+ .map(|line| flat(line).trim().to_string())+ .collect();+ assert_eq!(text, "checking", "the note survives at width {width}");+ for line in lines {+ let text = flat(&line);+ assert!(+ str_width(&text) <= width,+ "note exceeds width {width}: {text:?}"+ );+ }+ }+}++#[test]+fn a_zero_width_pane_has_no_note_lines() {+ let (mut mode, index) = mode_with_row("worker", "mock-1");+ note_into(&mut mode, index, "checking");+ assert!(mode.render_note_details(&mode.rows[index], 0).is_empty());+}++#[test]+fn a_nested_wide_note_stays_within_the_pane() {+ let (mut mode, index) = mode_with_row("worker", "mock-1");+ mode.rows[index].kind = RowKind::Subagent;+ mode.rows[index].depth = 3;+ note_into(&mut mode, index, "検証中");+ for width in [1, 2, 4, 8, 9, 10] {+ let lines = mode.render_note_details(&mode.rows[index], width);+ let text: String = lines+ .iter()+ .map(|line| flat(line).trim().to_string())+ .collect();+ if width >= 2 {+ assert_eq!(text, "検証中", "wide characters survive at width {width}");+ }+ for line in lines {+ let text = flat(&line);+ assert!(+ str_width(&text) <= width,+ "wide note exceeds width {width}: {text:?}"+ );+ }+ }+}++/// A short pane keeps the selected row plus the note lines that fit.+#[test]+fn a_short_pane_keeps_the_row_and_the_fitting_note_lines() {+ let (mut mode, index) = mode_with_row("worker", "mock-1");+ let note = (0..30)+ .map(|n| format!("word{n}"))+ .collect::<Vec<_>>()+ .join(" ");+ note_into(&mut mode, index, ¬e);+ mode.selected = index;+ let mut third = mode.rows[index].clone();+ third.identity = "third".to_string();+ third.title = "third".to_string();+ mode.rows.push(third);+ let full_count = note_line_count(&flat_lines(&mut mode, 60, 40));+ assert!(full_count > 1, "the note wraps: {full_count}");+ let lines = flat_lines(&mut mode, 60, 7);+ assert!(+ lines.iter().any(|line| line.contains("worker")),+ "the selected row stays visible: {lines:?}"+ );+ let shown = note_line_count(&lines);+ assert!(shown > 0, "the note lines ride the window: {lines:?}");+ assert!(+ shown < full_count,+ "the overflow clips behind the ellipsis: shown {shown} of {full_count}: {lines:?}"+ );+ assert_eq!(+ lines.last().expect("a trailing line").trim(),+ "...",+ "the trailing ellipsis covers the clip: {lines:?}"+ );+ assert!(+ !lines.iter().any(|line| line.contains("third")),+ "a below-the-fold row gives way to the note lines: {lines:?}"+ );+}++/// A top-section selection with a note taller than the viewport shifts+/// the slice past the section heading; the clipped heading still gets+/// its leading `...`.+#[test]+fn a_top_row_with_a_tall_note_keeps_the_leading_ellipsis() {+ let (mut mode, index) = mode_with_row("worker", "mock-1");+ let note = (0..40)+ .map(|n| format!("word{n}"))+ .collect::<Vec<_>>()+ .join(" ");+ note_into(&mut mode, index, ¬e);+ mode.selected = index;+ let lines = flat_lines(&mut mode, 60, 7);+ let worker_row = lines+ .iter()+ .position(|line| line.contains("worker"))+ .expect("the selected row stays visible: {lines:?}");+ assert!(+ worker_row > 2,+ "the worker row must sit under the header rows: {lines:?}"+ );+ assert_eq!(+ lines[worker_row - 1].trim(),+ "...",+ "the leading ellipsis marks the clipped heading: {lines:?}"+ );+}++/// The note lines are no click targets; rows below still click their own+/// rows.+#[test]+fn rows_below_the_expansion_still_click_their_own_rows() {+ let (mut mode, index) = mode_with_row("worker", "mock-1");+ note_into(&mut mode, index, "one note line");+ mode.selected = index;+ let mut third = mode.rows[index].clone();+ third.identity = "third".to_string();+ third.title = "third".to_string();+ mode.rows.push(third);+ mode.render_list(60, 30, 0);+ let mut clicks = mode.click_rows.clone();+ clicks.sort_unstable();+ assert_eq!(+ clicks.len(),+ 3,+ "the note line is no click target: {clicks:?}"+ );+ let row_targets: Vec<usize> = clicks.iter().map(|(_, row)| *row).collect();+ assert_eq!(row_targets, [0, 1, 2]);+ let lines = flat_lines(&mut mode, 60, 30);+ for (position, row) in clicks {+ assert!(+ lines[position].contains(&mode.rows[row].title),+ "click position {position} must sit on row {row}: {lines:?}"+ );+ }+}++/// Summary rows never expand, even when their summary carries the note.+#[test]+fn summary_rows_never_expand_a_note() {+ let (mut mode, index) = mode_with_row("worker", "mock-1");+ mode.rows[index].kind = RowKind::SubagentSummary;+ mode.rows[index].identity = "subagents:worker".to_string();+ mode.rows[index].parent_identity = Some("holder".to_string());+ mode.rows[index].depth = 1;+ note_into(&mut mode, index, "a note that must not render");+ mode.selected = index;+ let lines = flat_lines(&mut mode, 60, 30);+ assert!(+ lines.iter().any(|line| line.contains("\u{25b8} worker")),+ "the summary row renders nested: {lines:?}"+ );+ assert!(+ !lines.iter().any(|line| line.contains("must not render")),+ "a summary row never expands: {lines:?}"+ );+}