A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
agents view: the session you left keeps the focus on return (#3722)
Sebastian Müller80a0d9c239f4
diff --git a/.changes/fix-agents-view-return-focus.md b/.changes/fix-agents-view-return-focus.mdnew file mode 100644index 0000000000..3703ad396f--- /dev/null+++ b/.changes/fix-agents-view-return-focus.md@@ -0,0 +1 @@+- Agents view: leaving a session now returns the focus to that session's row, even after `/switch`, `/new`, `/fork`, or `/resume` in the chat, and when the row loads late.diff --git a/crates/pa-tui/src/agents_view.rs b/crates/pa-tui/src/agents_view.rsindex 86fa8286b5..6fa106c291 100644--- a/crates/pa-tui/src/agents_view.rs+++ b/crates/pa-tui/src/agents_view.rs@@ -14,8 +14,8 @@ use tokio::sync::mpsc;use crate::agents_view_forest::{ancestor_session_ids, build_rows, compute_rollups, has_session_children, resolve_selection,- scope_ancestors, scope_root, scope_to_subtree, AgentsViewRow, RowKind, ScopeRoot, SelectionKey,- SessionActivity,+ scope_ancestors, scope_root, scope_to_subtree, subtree_contains, AgentsViewRow, RowKind,+ ScopeRoot, SelectionKey, SessionActivity,};use crate::agents_view_state::truncate_text;use crate::agents_view_state::{@@ -68,7 +68,7 @@ pub struct AgentsViewOptions {pub session_dir: Option<PathBuf>,pub theme: String,pub version: String,- /// The session the view was opened from: anchors a fresh open's entry selection on its row.+ /// The session the view was opened from: anchors the entry selection on its row.pub anchor_session_id: Option<String>,/// Open scoped to one session's subtree: the root lists its descendants.pub scope: Option<AgentsViewScope>,@@ -519,21 +519,16 @@ impl AgentsViewMode {let selected_identity = options.selected_row_identity.clone();let selected_key = options.selected_key.clone();let keybindings = options.keybindings.clone();- // A fresh open (the scope-back handoff leaks an empty identity and a key with no session- // ids) waits on the anchor: the session the view was opened from.- let carried_selection = options- .selected_row_identity+ // Every open waits on the anchor: the chat may have switched sessions since the carried+ // row was opened. A scoped view never lists its own root, so that anchor arms no wait.+ let scope_root = options+ .scope+ .as_ref()+ .and_then(|scope| scope.session_id.as_deref());+ let anchor_selection_pending = options+ .anchor_session_id.as_deref()- .is_some_and(|identity| !identity.is_empty())- || options- .selected_key- .as_ref()- .is_some_and(|key| key.session_id.is_some() || key.active_session_id.is_some());- let anchor_selection_pending = !carried_selection- && options- .anchor_session_id- .as_deref()- .is_some_and(|anchor| !anchor.is_empty());+ .is_some_and(|anchor| !anchor.is_empty() && Some(anchor) != scope_root);// The first run starts fresh; later runs continue the carried state.let incident_notice_state = options.incident_notice_state.take().unwrap_or_default();AgentsViewMode {diff --git a/crates/pa-tui/src/agents_view/data_input.rs b/crates/pa-tui/src/agents_view/data_input.rsindex 97af46e6a7..c3f4610e53 100644--- a/crates/pa-tui/src/agents_view/data_input.rs+++ b/crates/pa-tui/src/agents_view/data_input.rs@@ -4,9 +4,9 @@use super::{build_rows, compute_rollups, filter_empty_sessions, filter_unified_sessions,parse_search_query, reconcile_unified_sessions, resolve_selection, scope_ancestors, scope_root,- scope_to_subtree, AgentsViewMode, AgentsViewRow, AgentsViewScope, Composer, OpenedRow, PathBuf,- PressedMouseClick, RowKind, SavedMore, ScopeRoot, SelectionEdge, SelectionKey,- SessionSelection, Value, ANCHOR_LOADING_HINT, SAVED_CATALOG_PAGE_FILES,+ scope_to_subtree, subtree_contains, AgentsViewMode, AgentsViewRow, AgentsViewScope, Composer,+ OpenedRow, PathBuf, PressedMouseClick, RowKind, SavedMore, ScopeRoot, SelectionEdge,+ SelectionKey, SessionSelection, Value, ANCHOR_LOADING_HINT, SAVED_CATALOG_PAGE_FILES,};impl AgentsViewMode {@@ -76,22 +76,33 @@ impl AgentsViewMode {&self.session_activity,self.options.anchor_session_id.as_deref(),);- // The entry anchor's row may be nested: arm the same ancestor expansion below so this- // pass reveals it (a scoped view never lists the anchor).+ // The entry anchor's row may be nested: add its ancestors to the expansion below so this+ // pass reveals it.if let (true, Some(anchor)) = (- self.anchor_selection_pending- && self.options.scope.is_none()- && self.pending_ancestors.is_none(),+ self.anchor_selection_pending,self.options.anchor_session_id.as_deref(),) {- self.pending_ancestors = Some(scope_ancestors(- &records,- &AgentsViewScope {- session_id: Some(anchor.to_string()),- active_session_id: None,- session_name: None,- },- ));+ let anchor_scope = AgentsViewScope {+ session_id: Some(anchor.to_string()),+ active_session_id: None,+ session_name: None,+ };+ let outside_scope = scope_active+ && self+ .options+ .scope+ .as_ref()+ .and_then(|scope| scope.session_id.as_deref())+ .and_then(|root| subtree_contains(&records, root, &anchor_scope))+ == Some(false);+ if outside_scope {+ // An anchor whose full lineage misses the scope root never lists here.+ self.end_anchor_wait();+ } else {+ self.pending_ancestors+ .get_or_insert_with(Vec::new)+ .extend(scope_ancestors(&records, &anchor_scope));+ }}// Re-expand the drilled-in row's ancestors: a nested row appears only once its parent is// expanded (expand-and-rebuild until a pass reveals nothing new).@@ -136,16 +147,32 @@ impl AgentsViewMode {identity.as_deref().or(self.selected_identity.as_deref()),self.selected_key.as_ref(),);- // The entry anchor lands the selection on its row once it appears; the sync below pins it,- // so later rebuilds restore onto it through the carried identity/key alone.+ // The entry anchor lands the selection on its session's row once it appears. A carried row+ // keyed to the anchor session also counts (a persistent shell row, an unattachable child+ // opened through its root). The sync below pins the landing for later rebuilds.if let (true, Some(anchor)) = (self.anchor_selection_pending,self.options.anchor_session_id.as_deref(),) {- if let Some(index) = rows.iter().position(|row| {+ let on_anchor = |row: &AgentsViewRow| {row.selectable()&& row.summary.get("sessionId").and_then(Value::as_str) == Some(anchor)- }) {+ };+ let carried_on_anchor = self+ .selected_key+ .as_ref()+ .and_then(|key| key.session_id.as_deref())+ == Some(anchor);+ let is_carried = |row: &AgentsViewRow| {+ self.selected_identity.as_deref() == Some(row.identity.as_str())+ };+ let landed = match rows.get(self.selected) {+ Some(row) if on_anchor(row) || (carried_on_anchor && is_carried(row)) => {+ Some(self.selected)+ }+ _ => rows.iter().position(on_anchor),+ };+ if let Some(index) = landed {self.selected = index;self.end_anchor_wait();}diff --git a/crates/pa-tui/src/agents_view/tests/entry_anchor.rs b/crates/pa-tui/src/agents_view/tests/entry_anchor.rsindex 8013a3f429..be2afb60d9 100644--- a/crates/pa-tui/src/agents_view/tests/entry_anchor.rs+++ b/crates/pa-tui/src/agents_view/tests/entry_anchor.rs@@ -268,33 +268,116 @@ fn nested_anchor_expands_its_ancestors() {}#[test]-fn carried_selection_wins_over_the_entry_anchor() {+fn a_scoped_reopen_expands_a_nested_anchor_outside_the_carried_branch() {let mut mode = AgentsViewMode::new(AgentsViewOptions {socket_path: PathBuf::from("/tmp/agents-view-test.sock"),cwd: PathBuf::from("/tmp"),session_dir: None,theme: "prime".to_string(),version: "0.0.0".to_string(),- anchor_session_id: Some("s2".to_string()),- scope: None,+ anchor_session_id: Some("g".to_string()),+ scope: Some(AgentsViewScope {+ session_id: Some("p".to_string()),+ active_session_id: Some("p-live".to_string()),+ session_name: Some("p name".to_string()),+ }),query: None,- expanded_ancestors: Vec::new(),+ expanded_ancestors: vec!["p".to_string(), "d".to_string()],selected_row_identity: None,- selected_key: Some(crate::agents_view_forest::SelectionKey {- session_id: Some("s1".to_string()),- active_session_id: Some("s1-live".to_string()),- }),+ selected_key: None,status_message: None,keybindings: crate::keybindings::KeybindingsManager::new(),show_hardware_cursor: false,incident_notice_state: None,create_config: serde_json::json!({}),});+ mode.roster = vec![+ roster_entry("p", "idle", &parent_summary("p")),+ roster_entry("c", "running", &child_summary("c", "p", "worker one")),+ roster_entry("g", "running", &child_summary("g", "c", "grandchild")),+ roster_entry("d", "running", &child_summary("d", "p", "worker two")),+ roster_entry("e", "running", &child_summary("e", "d", "other grandchild")),+ ];+ mode.rebuild_rows();+ assert_eq!(mode.rows[mode.selected].summary["sessionId"], "g");+ assert!(!mode.anchor_selection_pending);+}++/// A reopened view: anchored on the session just left, carrying the row the previous run opened.+fn returning_mode(+ anchor: &str,+ selected_row_identity: String,+ selected_key: crate::agents_view_forest::SelectionKey,+) -> AgentsViewMode {+ AgentsViewMode::new(AgentsViewOptions {+ socket_path: PathBuf::from("/tmp/agents-view-test.sock"),+ cwd: PathBuf::from("/tmp"),+ session_dir: None,+ theme: "prime".to_string(),+ version: "0.0.0".to_string(),+ anchor_session_id: Some(anchor.to_string()),+ scope: None,+ query: None,+ expanded_ancestors: Vec::new(),+ selected_row_identity: Some(selected_row_identity),+ selected_key: Some(selected_key),+ status_message: None,+ keybindings: crate::keybindings::KeybindingsManager::new(),+ show_hardware_cursor: false,+ incident_notice_state: None,+ create_config: serde_json::json!({}),+ })+}++#[test]+fn the_left_session_wins_over_a_stale_carried_selection() {+ let mut mode = returning_mode(+ "s2",+ "file:/x/s1.jsonl".to_string(),+ crate::agents_view_forest::SelectionKey {+ session_id: Some("s1".to_string()),+ active_session_id: Some("s1-live".to_string()),+ },+ );mode.roster = vec![roster_entry("s1", "idle", &parent_summary("s1")),roster_entry("s2", "idle", &parent_summary("s2")),];mode.rebuild_rows();- assert_eq!(mode.rows[mode.selected].summary["sessionId"], "s1");+ assert_eq!(mode.rows[mode.selected].summary["sessionId"], "s2");assert!(!mode.anchor_selection_pending);}++#[test]+fn a_round_trip_returns_to_the_origin_when_its_row_lands_late() {+ let mut first = mode_with_anchor(+ Some("s2"),+ vec![+ roster_entry("s1", "idle", &parent_summary("s1")),+ roster_entry("s2", "idle", &parent_summary("s2")),+ ],+ );+ first.handle_key("enter");+ let opened = first.opened.expect("the origin opens");+ assert_eq!(+ opened.selection,+ SessionSelection::Attach("s2-live".to_string())+ );+ let mut back = returning_mode("s2", opened.selected_row_identity, opened.selected_key);+ back.roster = vec![roster_entry("s1", "idle", &parent_summary("s1"))];+ back.rebuild_rows();+ back.apply_roster_update(+ vec![+ roster_entry("s3", "running", &parent_summary("s3")),+ roster_entry("s2", "idle", &parent_summary("s2")),+ ],+ Vec::new(),+ false,+ );+ assert_eq!(back.rows[back.selected].summary["sessionId"], "s2");+ back.handle_key("enter");+ assert_eq!(+ back.opened.expect("the origin reopens").selection,+ SessionSelection::Attach("s2-live".to_string())+ );+}diff --git a/crates/pa-tui/src/agents_view/tests/running_lines.rs b/crates/pa-tui/src/agents_view/tests/running_lines.rsindex 87ababfce2..eb31d22edc 100644--- a/crates/pa-tui/src/agents_view/tests/running_lines.rs+++ b/crates/pa-tui/src/agents_view/tests/running_lines.rs@@ -15,11 +15,8 @@ fn scoped_view_keeps_the_first_row_default() {assert_eq!(mode.rows.len(), 1, "the scope root is excluded");assert_eq!(mode.selected, 0);assert_eq!(mode.rows[0].summary["sessionId"], "c");- assert!(mode.anchor_selection_pending, "the wait never resolves");mode.handle_key("enter");- let opened = mode- .opened- .expect("the scoped view opens despite the never-resolving wait");+ let opened = mode.opened.expect("the scoped view opens the first row");assert_eq!(opened.selection,SessionSelection::Attach("c-live".to_string())diff --git a/crates/pa-tui/src/agents_view/tests/saved_pages.rs b/crates/pa-tui/src/agents_view/tests/saved_pages.rsindex fc2b2792dd..80a8efae4d 100644--- a/crates/pa-tui/src/agents_view/tests/saved_pages.rs+++ b/crates/pa-tui/src/agents_view/tests/saved_pages.rs@@ -56,6 +56,45 @@ fn a_saved_anchor_beyond_the_first_page_remains_pending_until_it_arrives() {);}+#[test]+fn a_panel_anchored_outside_its_listed_subtree_does_not_page_the_catalog() {+ for anchor in ["p", "x"] {+ let mut mode = scoped_mode(+ Some(anchor),+ vec![+ roster_entry("p", "idle", &parent_summary("p")),+ roster_entry("c", "running", &child_summary("c", "p", "worker one")),+ roster_entry("x", "idle", &parent_summary("x")),+ ],+ );+ mode.finish_saved_page(more());+ assert!(!mode.anchor_selection_pending, "anchor {anchor}");+ assert_eq!(mode.next_saved_fetch(), None, "anchor {anchor}");+ }+}++#[test]+fn a_panel_keeps_waiting_for_a_nested_anchor_whose_parent_has_not_loaded() {+ let mut mode = scoped_mode(+ Some("g"),+ vec![+ roster_entry("p", "idle", &parent_summary("p")),+ roster_entry("g", "running", &child_summary("g", "c", "grandchild")),+ ],+ );+ mode.finish_saved_page(more());+ assert!(mode.anchor_selection_pending);+ assert!(mode.next_saved_fetch().is_some());+ mode.roster.push(roster_entry(+ "c",+ "running",+ &child_summary("c", "p", "worker one"),+ ));+ mode.rebuild_rows();+ assert_eq!(mode.rows[mode.selected].summary["sessionId"], "g");+ assert!(!mode.anchor_selection_pending);+}+#[test]fn a_carried_partial_catalog_keeps_waiting_for_a_missing_anchor() {let mut mode = mode_with_anchor(Some("older"), Vec::new());diff --git a/crates/pa-tui/src/agents_view_forest.rs b/crates/pa-tui/src/agents_view_forest.rsindex 2ec0524c12..ebdf9d4ce7 100644--- a/crates/pa-tui/src/agents_view_forest.rs+++ b/crates/pa-tui/src/agents_view_forest.rs@@ -13,7 +13,7 @@ mod selection;mod summary;pub use lineage::{compute_rollups, has_session_children, scope_ancestors, scope_to_subtree};-pub(crate) use lineage::{scope_root, ScopeRoot};+pub(crate) use lineage::{scope_root, subtree_contains, ScopeRoot};pub(crate) use rows::build_rows;pub use selection::{ancestor_session_ids, resolve_selection};pub(crate) use summary::session_model;diff --git a/crates/pa-tui/src/agents_view_forest/lineage.rs b/crates/pa-tui/src/agents_view_forest/lineage.rsindex 245f437017..731eb5668f 100644--- a/crates/pa-tui/src/agents_view_forest/lineage.rs+++ b/crates/pa-tui/src/agents_view_forest/lineage.rs@@ -44,17 +44,24 @@ fn find_parent_index(by_key: &HashMap<String, usize>,index: usize,) -> Option<usize> {- let mut keys = parent_reference_keys(&records[index]);- if let Some(saved) = &records[index].saved {+ parent_keys(&records[index])+ .iter()+ .find_map(|key| by_key.get(key).copied())+ .filter(|parent| *parent != index)+}++/// Every parent-reference key of one record: daemon summary keys first, then the saved catalog's+/// parent path.+fn parent_keys(record: &UnifiedRecord) -> Vec<String> {+ let mut keys = parent_reference_keys(record);+ if let Some(saved) = &record.saved {if let Some(parent_path) = saved.get("parentSessionPath").and_then(Value::as_str) {if !parent_path.is_empty() {keys.push(crate::agents_view_state::file_identity(parent_path));}}}- keys.iter()- .find_map(|key| by_key.get(key).copied())- .filter(|parent| *parent != index)+ keys}/// The parent-reference keys of one record's daemon summary.@@ -307,6 +314,32 @@ pub fn scope_ancestors(records: &[UnifiedRecord], scope: &AgentsViewScope) -> Veancestors}+/// Whether `anchor` sits in the subtree of the session `root`. `None` while the record set cannot+/// tell: the anchor is unknown, or its parent chain ends on a parent that has not loaded yet.+pub(crate) fn subtree_contains(+ records: &[UnifiedRecord],+ root: &str,+ anchor: &AgentsViewScope,+) -> Option<bool> {+ let index = build_record_index(records);+ let mut current = scope_root_index(records, anchor)?;+ let mut visited: HashSet<usize> = HashSet::new();+ while visited.insert(current) {+ if summary_for_record(&records[current])+ .get("sessionId")+ .and_then(Value::as_str)+ == Some(root)+ {+ return Some(true);+ }+ if parent_keys(&records[current]).is_empty() {+ return Some(false);+ }+ current = find_parent_index(records, &index.by_key, current)?;+ }+ None+}+/// Whether the session has direct children on the record set.#[must_use]pub fn has_session_children(records: &[UnifiedRecord], key: &SelectionKey) -> bool {