Skip to content

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

Rust

start sessions under the parent from the agents view (#3047)

Sebastian Müller2231687fcdaf
diff --git a/crates/pa-cli/src/interactive_mode/telemetry.rs b/crates/pa-cli/src/interactive_mode/telemetry.rs
index e2d26d7f1f..cf92e74cc9 100644
--- a/crates/pa-cli/src/interactive_mode/telemetry.rs
+++ b/crates/pa-cli/src/interactive_mode/telemetry.rs
@@ -260,6 +260,18 @@ impl pa_tui::interactive::InteractionTelemetry for CliInteractionTelemetry {
})
}
+ fn scoped_agent_created(&self, depth: u32) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
+ Box::pin(async move {
+ let Some(client) = self.client() else {
+ return;
+ };
+ let mut properties = pa_telemetry::base_properties("interactive");
+ properties.set("depth", serde_json::Value::from(u64::from(depth)));
+ client.track("tui agents new scoped", properties);
+ let _ = client.shutdown().await;
+ })
+ }
+
fn command_used(&self, command: &'static str) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
// `agent command used` (TS `captureAgentCommandUsed`): builtin
// client commands report from the client; session commands report
diff --git a/crates/pa-telemetry/src/catalog.rs b/crates/pa-telemetry/src/catalog.rs
index 69ee6ccf4c..6ce4474eca 100644
--- a/crates/pa-telemetry/src/catalog.rs
+++ b/crates/pa-telemetry/src/catalog.rs
@@ -1463,6 +1463,14 @@ const TUI_EVENTS: &[EventRule] = &[
since: 1,
properties: &[("children_total", required(count()))],
},
+ // The scoped agents view's new action (the operator's 2026-09-28
+ // divergence): the created session's RLM depth, the scope root's
+ // depth + 1.
+ EventRule {
+ name: "tui agents new scoped",
+ since: 2,
+ properties: &[("depth", required(count()))],
+ },
EventRule {
name: "tui activity opened",
since: 1,
@@ -1885,6 +1893,25 @@ mod tests {
}
}
+ #[test]
+ fn the_scoped_new_event_catalogues_only_its_depth() {
+ // The scoped ctrl+n's adoption event: the depth count stays, and
+ // no other key rides it (the parent's session path is not a
+ // catalogued property, so sanitize drops it).
+ let rule = lookup("tui agents new scoped").expect("catalogued");
+ assert_eq!(rule.since, 2);
+ let mut properties = Properties::new();
+ properties.set("depth", json!(2u64));
+ properties.set("parent_session_path", json!("/sessions/p.jsonl"));
+ let adjusted = sanitize("tui agents new scoped", &mut properties);
+ assert_eq!(properties.get("depth"), Some(&json!(2u64)));
+ assert!(
+ properties.get("parent_session_path").is_none(),
+ "the parent's path never rides the event"
+ );
+ assert_eq!(adjusted, 1, "the path key dropped");
+ }
+
#[test]
fn sanitize_drops_unknown_keys_and_falls_back_enums() {
let mut properties = Properties::new();
diff --git a/crates/pa-tui/src/agents_view.rs b/crates/pa-tui/src/agents_view.rs
index b0e4c3f45e..7623929c6e 100644
--- a/crates/pa-tui/src/agents_view.rs
+++ b/crates/pa-tui/src/agents_view.rs
@@ -17,7 +17,7 @@ use tokio::sync::mpsc;
use crate::agents_view_forest::{
ancestor_session_ids, build_rows, compute_rollups, has_session_children, resolve_selection,
- scope_ancestors, scope_depth, scope_to_subtree, AgentsViewRow, RowKind, SelectionKey,
+ scope_ancestors, scope_root, scope_to_subtree, AgentsViewRow, RowKind, ScopeRoot, SelectionKey,
};
use crate::agents_view_state::truncate_text;
use crate::agents_view_state::{
@@ -122,8 +122,10 @@ pub struct AgentsViewOptions {
/// The open action the run ended with (TS `AgentsViewRunResult`'s
/// `open`/`scope_back` arms, unified): the session the flow opens plus
-/// the row metadata it carries across the view/session loop.
-#[derive(Debug, Clone)]
+/// the row metadata it carries across the view/session loop — the new
+/// sessions open the same way (TS `createNewSession`'s
+/// `finish({ type: "open" })`).
+#[derive(Debug, Clone, PartialEq)]
pub struct OpenedRow {
pub selection: SessionSelection,
pub expanded_ancestors: Vec<String>,
@@ -434,10 +436,11 @@ struct AgentsViewMode {
/// the catalog apply filters these paths out (a deleted row never
/// reappears behind a slow fetch).
deleted_saved_paths: std::collections::HashSet<String>,
- /// The scope root's `depth` metadata (`rlmDepth + 1`); `None` when the
- /// scope root is not on the roster (the view falls back to the global
- /// list with a status message, TS scope-resolution fallback).
- scope_depth: Option<u32>,
+ /// The scope root's facts the scoped view renders and creates with
+ /// ([`ScopeRoot`]); `None` when the scope root is not on the roster
+ /// (the view falls back to the global list with a status message, TS
+ /// scope-resolution fallback).
+ scope_root: Option<ScopeRoot>,
/// The scope root resolved on the last rebuild.
scope_active: bool,
/// Whether the scope root left the roster mid-run (TS
@@ -487,8 +490,6 @@ struct AgentsViewMode {
scope_back: bool,
/// The open action the run ended with (`None` while the view runs).
opened: Option<OpenedRow>,
- /// ctrl+n requested a fresh session (TS `app.agents.new`).
- new_session: bool,
/// The effective keybindings (TS `AgentsViewMode.keybindings`): every
/// action and hint dispatches through this manager.
keybindings: crate::keybindings::KeybindingsManager,
@@ -625,7 +626,7 @@ impl AgentsViewMode {
pending_headline: None,
pending_delete_action: None,
deleted_saved_paths: std::collections::HashSet::default(),
- scope_depth: None,
+ scope_root: None,
scope_active: false,
scope_dropped: false,
expanded_parents: std::collections::HashSet::default(),
@@ -641,7 +642,6 @@ impl AgentsViewMode {
scope_popped: false,
scope_back: false,
opened: None,
- new_session: false,
saved_fetch_failed: false,
saved_query_rearm: false,
saved_stream: Vec::new(),
@@ -1326,11 +1326,11 @@ async fn run_agents_view_surface(
// after the stop-or-delete drain settles: a confirmed request
// completes before any deadline can cut it down. `renderer.finish`
// consumes the renderer, so the terminal check is read first.
- let handing_off = mode.opened.is_some() || mode.new_session;
+ let handing_off = mode.opened.is_some();
let terminal_exit = matches!(renderer, Renderer::Terminal { .. }) && !handing_off;
// A selection hands the pane to the chat it opened (TS `result.type !== "exit"`);
// exiting releases the alternate screen.
- let frames = renderer.finish(mode.opened.is_some() || mode.new_session);
+ let frames = renderer.finish(mode.opened.is_some());
// TS `AgentsViewRosterStore.dispose` fires the roster unsubscribe
// fire-and-forget ("nobody needs the ack"; the supervisor also drops
// the subscription with the socket), so no handoff ever waits on it.
@@ -1414,7 +1414,7 @@ async fn run_agents_view_surface(
}
// A handoff returns the roster connection for the flow's next view run
// (TS `persistentState.rosterClient`); a selection-less exit closes it.
- let link = if opened.is_some() || mode.new_session {
+ let link = if opened.is_some() {
// The handoff link carries the catalog the run loaded (TS
// `persistentState.savedSessions`/`savedCatalogLoaded`): the flow's
// next view run paints the Inactive rows it already holds on its
@@ -1432,10 +1432,7 @@ async fn run_agents_view_surface(
Ok(AgentsViewRun {
link,
outcome: AgentsViewOutcome {
- selection: opened
- .as_ref()
- .map(|row| row.selection.clone())
- .or(mode.new_session.then_some(SessionSelection::New)),
+ selection: opened.as_ref().map(|row| row.selection.clone()),
frames,
query: (!mode.query.is_empty()).then(|| mode.query.clone()),
scope_popped: mode.scope_popped,
diff --git a/crates/pa-tui/src/agents_view/data_input.rs b/crates/pa-tui/src/agents_view/data_input.rs
index 280523a309..b762d9e20b 100644
--- a/crates/pa-tui/src/agents_view/data_input.rs
+++ b/crates/pa-tui/src/agents_view/data_input.rs
@@ -5,9 +5,10 @@
//! (moved with their concern).
use super::{
build_rows, compute_rollups, filter_empty_sessions, filter_unified_sessions,
- parse_search_query, reconcile_unified_sessions, resolve_selection, scope_ancestors,
- scope_depth, scope_to_subtree, AgentsViewMode, AgentsViewScope, Composer, PressedMouseClick,
- RowKind, SelectionEdge, Value, ANCHOR_LOADING_HINT,
+ parse_search_query, reconcile_unified_sessions, resolve_selection, scope_ancestors, scope_root,
+ scope_to_subtree, AgentsViewMode, AgentsViewScope, Composer, OpenedRow, PathBuf,
+ PressedMouseClick, RowKind, ScopeRoot, SelectionEdge, SelectionKey, SessionSelection, Value,
+ ANCHOR_LOADING_HINT,
};
impl AgentsViewMode {
@@ -34,10 +35,10 @@ impl AgentsViewMode {
Some(scope) if !self.scope_dropped => {
if let Some(scoped) = scope_to_subtree(&records, scope) {
scope_active = true;
- self.scope_depth = scope_depth(&records, scope);
+ self.scope_root = scope_root(&records, scope);
Some(scoped)
} else {
- self.scope_depth = None;
+ self.scope_root = None;
self.scope_dropped = true;
self.set_status("Scope is no longer available; returned to the global view");
None
@@ -520,11 +521,43 @@ impl AgentsViewMode {
return;
}
// TS `app.agents.new` (default ctrl+n): start a session; a plain
- // "n" is search text like any other character.
+ // "n" is search text like any other character. Scoped (the
+ // operator's 2026-09-28 directive, a deliberate TS divergence -
+ // TS always starts a root session): the session starts under the
+ // scope root, one level below it and in its directory, so it
+ // lists in this view and the agents-back return lands here. A
+ // root with no session file (a `--no-session` root) has nothing
+ // to bind and starts a root session.
if self.keybindings.matches(key, "app.agents.new") {
- self.opened = None;
+ let (selection, rlm_depth, cwd) = match self.scope_root.clone() {
+ Some(ScopeRoot {
+ child_depth,
+ session_file: Some(file),
+ cwd,
+ }) => (
+ SessionSelection::NewChild {
+ parent_session_file: PathBuf::from(file),
+ rlm_depth: child_depth,
+ },
+ Some(child_depth),
+ cwd,
+ ),
+ Some(ScopeRoot {
+ session_file: None, ..
+ })
+ | None => (SessionSelection::New, None, None),
+ };
+ self.opened = Some(OpenedRow {
+ selection,
+ expanded_ancestors: Vec::new(),
+ selected_row_identity: String::new(),
+ selected_key: SelectionKey::default(),
+ rlm_depth,
+ has_children: false,
+ status_message: None,
+ cwd,
+ });
self.running = false;
- self.new_session = true;
return;
}
// TS `app.agents.program` (default ctrl+o, empty editor only,
diff --git a/crates/pa-tui/src/agents_view/render.rs b/crates/pa-tui/src/agents_view/render.rs
index 2a9b604a6e..c54bdaedd7 100644
--- a/crates/pa-tui/src/agents_view/render.rs
+++ b/crates/pa-tui/src/agents_view/render.rs
@@ -37,8 +37,8 @@ impl AgentsViewMode {
"agents".to_string(),
format!("{running} running, {idle} idle, {inactive} inactive"),
)];
- if let Some(depth) = self.scope_depth {
- extra_metadata.push(("depth".to_string(), depth.to_string()));
+ if let Some(root) = &self.scope_root {
+ extra_metadata.push(("depth".to_string(), root.child_depth.to_string()));
}
let theme = &self.theme;
let chrome = crate::chrome::ChromeState {
diff --git a/crates/pa-tui/src/agents_view/tests.rs b/crates/pa-tui/src/agents_view/tests.rs
index 7b7a586f0f..992a0cde1c 100644
--- a/crates/pa-tui/src/agents_view/tests.rs
+++ b/crates/pa-tui/src/agents_view/tests.rs
@@ -189,6 +189,37 @@ fn mode_with_anchor(anchor: Option<&str>, roster: Vec<serde_json::Value>) -> Age
mode
}
+/// A scoped view over the given roster (the family's shared fixture: the
+/// scope shape the subagents summary line's open action carries; the
+/// anchor names the session the agents-back handoff waits on).
+fn scoped_mode(anchor: Option<&str>, roster: Vec<serde_json::Value>) -> AgentsViewMode {
+ 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: anchor.map(str::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(),
+ selected_row_identity: None,
+ 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 = roster;
+ mode.rebuild_rows();
+ mode
+}
+
/// A mode over the same live parent/child roster whose user bindings
/// replace keys (TS `keybindings.json` parity, the #184 binding-test
/// pattern: an override fires, the default goes inert).
diff --git a/crates/pa-tui/src/agents_view/tests/drill_down.rs b/crates/pa-tui/src/agents_view/tests/drill_down.rs
index 4a981a4084..280654caa1 100644
--- a/crates/pa-tui/src/agents_view/tests/drill_down.rs
+++ b/crates/pa-tui/src/agents_view/tests/drill_down.rs
@@ -74,33 +74,13 @@ fn pending_ancestors_expand_and_selection_restores_after_reentry() {
#[test]
fn scoped_left_returns_the_root_and_pops_the_scope() {
- 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: None,
- 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(),
- selected_row_identity: None,
- 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")),
- ];
- mode.rebuild_rows();
+ let mut mode = scoped_mode(
+ None,
+ vec![
+ roster_entry("p", "idle", &parent_summary("p")),
+ roster_entry("c", "running", &child_summary("c", "p", "worker one")),
+ ],
+ );
// The scoped view lists the direct child as a top-level row.
assert!(mode.scope_active);
assert_eq!(mode.rows.len(), 1);
diff --git a/crates/pa-tui/src/agents_view/tests/key_bindings.rs b/crates/pa-tui/src/agents_view/tests/key_bindings.rs
index 10c9595aa0..5b7896344f 100644
--- a/crates/pa-tui/src/agents_view/tests/key_bindings.rs
+++ b/crates/pa-tui/src/agents_view/tests/key_bindings.rs
@@ -61,12 +61,51 @@ fn expand_and_new_key_overrides_fire_and_defaults_are_inert() {
// default ctrl+n no longer does.
mode.handle_key("alt+n");
assert!(!mode.running);
- assert!(mode.new_session);
+ assert_eq!(
+ mode.opened.as_ref().map(|opened| &opened.selection),
+ Some(&SessionSelection::New)
+ );
let mut mode =
mode_with_user_bindings(&[("app.agents.expand", "alt+x"), ("app.agents.new", "alt+n")]);
mode.handle_key("ctrl+n");
assert!(mode.running, "the default new key is inert");
- assert!(!mode.new_session);
+ assert!(mode.opened.is_none());
+}
+
+/// The scoped view's ctrl+n creates the new session under the scope
+/// root (the operator's 2026-09-28 directive): one level below it and
+/// in its directory, so it lists in this view and the agents-back
+/// return lands here.
+#[test]
+fn new_key_in_a_scoped_view_creates_under_the_scope_root() {
+ let mut parent = parent_summary("p");
+ parent["cwd"] = serde_json::json!("/work/p");
+ let mut mode = scoped_mode(
+ None,
+ vec![
+ roster_entry("p", "idle", &parent),
+ roster_entry("c", "running", &child_summary("c", "p", "worker one")),
+ ],
+ );
+ assert!(mode.scope_active);
+ mode.handle_key("ctrl+n");
+ assert!(!mode.running);
+ assert_eq!(
+ mode.opened,
+ Some(OpenedRow {
+ selection: SessionSelection::NewChild {
+ parent_session_file: "/x/p.jsonl".into(),
+ rlm_depth: 1,
+ },
+ expanded_ancestors: vec![],
+ selected_row_identity: String::new(),
+ selected_key: SelectionKey::default(),
+ rlm_depth: Some(1),
+ has_children: false,
+ status_message: None,
+ cwd: Some("/work/p".into()),
+ })
+ );
}
/// TS `cycleProgramForSelected` (the `app.agents.program` key, default
diff --git a/crates/pa-tui/src/agents_view/tests/reply.rs b/crates/pa-tui/src/agents_view/tests/reply.rs
index d1080ca441..b4d8c54146 100644
--- a/crates/pa-tui/src/agents_view/tests/reply.rs
+++ b/crates/pa-tui/src/agents_view/tests/reply.rs
@@ -105,7 +105,7 @@ fn armed_keys_route_to_the_editor_and_the_cancels_disarm() {
// ctrl+n (the new-session action) is disabled while armed.
mode.handle_key("ctrl+n");
assert!(matches!(&mode.composer, Composer::Reply(_)));
- assert!(!mode.new_session);
+ assert!(mode.opened.is_none());
// Esc disarms; the query stays untouched (the composer never owned
// it).
mode.handle_key("escape");
diff --git a/crates/pa-tui/src/agents_view/tests/running_lines.rs b/crates/pa-tui/src/agents_view/tests/running_lines.rs
index 0043a3267c..03a9d52822 100644
--- a/crates/pa-tui/src/agents_view/tests/running_lines.rs
+++ b/crates/pa-tui/src/agents_view/tests/running_lines.rs
@@ -8,33 +8,13 @@ use super::*;
/// default stands there.
#[test]
fn scoped_view_keeps_the_first_row_default() {
- 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("p".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(),
- selected_row_identity: None,
- 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")),
- ];
- mode.rebuild_rows();
+ let mut mode = scoped_mode(
+ Some("p"),
+ vec![
+ roster_entry("p", "idle", &parent_summary("p")),
+ roster_entry("c", "running", &child_summary("c", "p", "worker one")),
+ ],
+ );
assert_eq!(mode.rows.len(), 1, "the scope root is excluded");
assert_eq!(mode.selected, 0);
assert_eq!(mode.rows[0].summary["sessionId"], "c");
@@ -54,31 +34,10 @@ fn scoped_view_keeps_the_first_row_default() {
/// A scoped view whose scope root has no children (the all-zero dock's
/// Subagents destination): the roster carries the root alone.
fn childless_scope() -> AgentsViewMode {
- 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("p".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(),
- selected_row_identity: None,
- 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"))];
- mode.rebuild_rows();
- mode
+ scoped_mode(
+ Some("p"),
+ vec![roster_entry("p", "idle", &parent_summary("p"))],
+ )
}
/// A childless scope is an empty view that keeps its keys: the
@@ -122,11 +81,13 @@ fn a_childless_scope_is_an_empty_view_that_keeps_its_keys() {
// ctrl+d quits the empty view without opening anything.
let mut mode = childless_scope();
mode.handle_key("ctrl+d");
- assert!(!mode.running && mode.opened.is_none() && !mode.new_session);
- // ctrl+n dispatches the new-session action.
+ assert!(!mode.running && mode.opened.is_none());
+ // ctrl+n dispatches the new-session action from the empty view too
+ // (the binding's whole-object shape is pinned in the key_bindings
+ // family's scoped test).
let mut mode = childless_scope();
mode.handle_key("ctrl+n");
- assert!(mode.new_session && !mode.running);
+ assert!(!mode.running && mode.opened.is_some());
}
/// TS `countRowsBySection` (the splash header counts) counts agent-kind
diff --git a/crates/pa-tui/src/agents_view_forest.rs b/crates/pa-tui/src/agents_view_forest.rs
index a71acab88d..db26d98f41 100644
--- a/crates/pa-tui/src/agents_view_forest.rs
+++ b/crates/pa-tui/src/agents_view_forest.rs
@@ -25,12 +25,11 @@ mod rows;
mod selection;
mod summary;
-pub use lineage::{
- compute_rollups, has_session_children, scope_ancestors, scope_depth, scope_to_subtree,
-};
+pub use lineage::{compute_rollups, has_session_children, scope_ancestors, scope_to_subtree};
+pub(crate) use lineage::{scope_root, ScopeRoot};
pub(crate) use rows::build_rows;
pub use selection::{ancestor_session_ids, resolve_selection};
-pub(crate) use summary::{is_subagent_summary, session_model};
+pub(crate) use summary::session_model;
pub use summary::{selection_key, session_title, summary_identity};
/// The scope of a scoped agents view (TS `AgentsViewScopeKey` plus the
diff --git a/crates/pa-tui/src/agents_view_forest/lineage.rs b/crates/pa-tui/src/agents_view_forest/lineage.rs
index 62197e80c7..157ba097cd 100644
--- a/crates/pa-tui/src/agents_view_forest/lineage.rs
+++ b/crates/pa-tui/src/agents_view_forest/lineage.rs
@@ -2,9 +2,9 @@ use std::collections::{HashMap, HashSet};
use serde_json::Value;
-use super::{is_subagent_summary, AgentsViewScope, Rollup, SelectionKey};
+use super::{AgentsViewScope, Rollup, SelectionKey};
use crate::agents_view_state::{summary_for_record, UnifiedRecord};
-use crate::subagents::summary_parent_keys;
+use crate::subagents::{depth_consistent_binding, is_subagent_summary, summary_parent_keys};
/// The record hierarchy (TS `UnifiedSessionIndex`): every record by its
/// aliases, and each record's children by parent linkage.
@@ -69,19 +69,23 @@ fn parent_reference_keys(record: &UnifiedRecord) -> Vec<String> {
}
/// The `parent` record's session file, live summary first, saved catalog
-/// row second (both serve absolute paths).
+/// row second (both serve absolute paths; an empty string is absent — a
+/// `--no-session` worker's in-memory store publishes one, and every other
+/// TUI accessor of the fact reads it the same way).
fn parent_record_file(parent: &UnifiedRecord) -> Option<&str> {
parent
.daemon
.as_ref()
.and_then(|daemon| daemon.get("sessionFile"))
.and_then(Value::as_str)
+ .filter(|file| !file.is_empty())
.or_else(|| {
parent
.saved
.as_ref()
.and_then(|saved| saved.get("path"))
.and_then(Value::as_str)
+ .filter(|file| !file.is_empty())
})
}
@@ -90,20 +94,6 @@ fn parent_record_file(parent: &UnifiedRecord) -> Option<&str> {
/// one level up); a fork's source binding sits at the SAME depth and is
/// a sibling, never a parent.
pub(super) fn depth_consistent_parent(daemon: &Value, parent: &UnifiedRecord) -> bool {
- let Some(depth) = daemon
- .get("rlmDepth")
- .and_then(Value::as_u64)
- .filter(|depth| *depth > 0)
- else {
- return false;
- };
- let Some(parent_path) = daemon
- .get("parentSessionPath")
- .and_then(Value::as_str)
- .filter(|path| !path.is_empty())
- else {
- return false;
- };
let parent_depth = parent
.daemon
.as_ref()
@@ -116,7 +106,7 @@ pub(super) fn depth_consistent_parent(daemon: &Value, parent: &UnifiedRecord) ->
.and_then(|saved| saved.get("rlmDepth"))
.and_then(Value::as_u64)
});
- parent_record_file(parent) == Some(parent_path) && parent_depth == Some(depth - 1)
+ depth_consistent_binding(daemon, parent_record_file(parent), parent_depth)
}
/// Whether `child` rolls up under `parent` (TS `isSubagentDescendantRecord`):
@@ -356,15 +346,37 @@ pub fn has_session_children(records: &[UnifiedRecord], key: &SelectionKey) -> bo
})
}
-/// The scope root's depth label (TS `getAgentsViewDepth`:
-/// `rlmDepth + 1`); `None` when the root is not in the record set.
-#[must_use]
-pub fn scope_depth(records: &[UnifiedRecord], scope: &AgentsViewScope) -> Option<u32> {
+/// The scope root's facts the scoped view renders and creates with:
+/// `child_depth` is the root's `rlmDepth + 1` (TS `getAgentsViewDepth`) —
+/// the view's depth label and the depth a session created in this scope
+/// runs at; `session_file` is the root's file exactly as the forest links
+/// children to it ([`parent_record_file`]); `cwd` is the root's directory.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ScopeRoot {
+ pub(crate) child_depth: u32,
+ pub(crate) session_file: Option<String>,
+ pub(crate) cwd: Option<String>,
+}
+
+/// The scope root's facts, `None` when the root is not in the record set.
+pub(crate) fn scope_root(records: &[UnifiedRecord], scope: &AgentsViewScope) -> Option<ScopeRoot> {
scope_root_index(records, scope).map(|root| {
- summary_for_record(&records[root])
+ let summary = summary_for_record(&records[root]);
+ // `rlmDepth` rides the wire as a u32 (the create check enforces
+ // it); an out-of-range value falls back to the root's 0.
+ let root_depth = summary
.get("rlmDepth")
.and_then(Value::as_u64)
- .unwrap_or(0) as u32
- + 1
+ .and_then(|depth| u32::try_from(depth).ok())
+ .unwrap_or(0);
+ ScopeRoot {
+ child_depth: root_depth + 1,
+ session_file: parent_record_file(&records[root]).map(str::to_string),
+ cwd: summary
+ .get("cwd")
+ .and_then(Value::as_str)
+ .filter(|cwd| !cwd.is_empty())
+ .map(str::to_string),
+ }
})
}
diff --git a/crates/pa-tui/src/agents_view_forest/rows.rs b/crates/pa-tui/src/agents_view_forest/rows.rs
index e590e365fa..cc0c75c296 100644
--- a/crates/pa-tui/src/agents_view_forest/rows.rs
+++ b/crates/pa-tui/src/agents_view_forest/rows.rs
@@ -4,13 +4,13 @@ use serde_json::Value;
use super::lineage::{depth_consistent_parent, is_subagent_descendant};
use super::{
- is_subagent_summary, session_model, session_title, AgentsViewRow, AgentsViewScope, Rollup,
- RowKind, SUMMARY_ROW_PREFIX,
+ session_model, session_title, AgentsViewRow, AgentsViewScope, Rollup, RowKind,
+ SUMMARY_ROW_PREFIX,
};
use crate::agents_view_state::{
now_ms, relative_age, section_rank, summary_for_record, Section, UnifiedRecord,
};
-use crate::subagents::{summary_identity_keys, summary_parent_keys};
+use crate::subagents::{is_subagent_summary, summary_identity_keys, summary_parent_keys};
struct BaseRow {
kind: RowKind,
diff --git a/crates/pa-tui/src/agents_view_forest/summary.rs b/crates/pa-tui/src/agents_view_forest/summary.rs
index 4ae13023cf..f4dc37b99a 100644
--- a/crates/pa-tui/src/agents_view_forest/summary.rs
+++ b/crates/pa-tui/src/agents_view_forest/summary.rs
@@ -57,29 +57,6 @@ pub fn session_title(summary: &Value) -> String {
"Untitled agent".to_string()
}
-/// Whether a summary is a spawned subagent (TS `isSubagentSummary`): the
-/// runtime kind decides when present; summaries from daemons that predate
-/// it still carry subagent linkage and never surface as top-level agents.
-pub(crate) fn is_subagent_summary(summary: &Value) -> bool {
- match summary.get("runtimeKind").and_then(Value::as_str) {
- Some(kind) => kind == "subagent",
- None => [
- "rlmChildId",
- "rlmParentNodeId",
- "parentActiveSessionId",
- "parentSessionId",
- "parentSessionPath",
- ]
- .iter()
- .any(|field| {
- summary
- .get(*field)
- .and_then(Value::as_str)
- .is_some_and(|value| !value.is_empty())
- }),
- }
-}
-
/// The stable row identity of one summary (TS `getAgentsViewSummaryIdentity`):
/// the roster-qualified child id for subagents, else file, active, session.
#[must_use]
diff --git a/crates/pa-tui/src/agents_view_forest/tests.rs b/crates/pa-tui/src/agents_view_forest/tests.rs
index 8a5d85d4e2..f470bea8dd 100644
--- a/crates/pa-tui/src/agents_view_forest/tests.rs
+++ b/crates/pa-tui/src/agents_view_forest/tests.rs
@@ -569,7 +569,14 @@ fn scoped_rows_lift_direct_children_and_exclude_the_root() {
// The scope's ancestors: the root has none; its depth label is
// rlmDepth + 1.
assert!(scope_ancestors(&records, &scope).is_empty());
- assert_eq!(scope_depth(&records, &scope), Some(1));
+ assert_eq!(
+ scope_root(&records, &scope),
+ Some(ScopeRoot {
+ child_depth: 1,
+ session_file: Some("/x/p.jsonl".to_string()),
+ cwd: None,
+ })
+ );
assert!(has_session_children(
&records,
&SelectionKey {
@@ -579,6 +586,33 @@ fn scoped_rows_lift_direct_children_and_exclude_the_root() {
));
}
+/// A `--no-session` root's live summary publishes an empty `sessionFile`
+/// (the daemon's in-memory store maps its empty path unconditionally):
+/// the scope root reads it as absent, so ctrl+n falls back to a plain new
+/// root session instead of binding to an empty path.
+#[test]
+fn a_root_with_an_empty_session_file_binds_nothing() {
+ let roster = vec![roster_entry("p", "idle", &{
+ let mut summary = parent_summary("p");
+ summary["sessionFile"] = json!("");
+ summary
+ })];
+ let scope = AgentsViewScope {
+ session_id: Some("p".to_string()),
+ active_session_id: Some("p-live".to_string()),
+ session_name: None,
+ };
+ let records = reconcile_unified_sessions(&roster, &[]);
+ assert_eq!(
+ scope_root(&records, &scope),
+ Some(ScopeRoot {
+ child_depth: 1,
+ session_file: None,
+ cwd: None,
+ })
+ );
+}
+
#[test]
fn saved_child_nests_under_its_saved_parent() {
let saved = vec![
diff --git a/crates/pa-tui/src/agents_view_state.rs b/crates/pa-tui/src/agents_view_state.rs
index 26f08f3ffe..46dcd6ac97 100644
--- a/crates/pa-tui/src/agents_view_state.rs
+++ b/crates/pa-tui/src/agents_view_state.rs
@@ -417,7 +417,7 @@ pub fn filter_empty_sessions(records: &[UnifiedRecord], preserved: &[&str]) -> V
.and_then(Value::as_f64)
.unwrap_or(0.0)
> 0.0
- || crate::agents_view_forest::is_subagent_summary(&summary)
+ || crate::subagents::is_subagent_summary(&summary)
|| get_str(&summary, "sessionId").is_some_and(|id| preserved.contains(&id));
if keep_row {
keep(index, &mut retained);
diff --git a/crates/pa-tui/src/interactive.rs b/crates/pa-tui/src/interactive.rs
index 65082b7511..9e688185b6 100644
--- a/crates/pa-tui/src/interactive.rs
+++ b/crates/pa-tui/src/interactive.rs
@@ -100,6 +100,15 @@ mod tests;
pub enum SessionSelection {
/// Create a fresh session (`create`, then `attach`).
New,
+ /// Create a fresh session bound under a parent session (the scoped
+ /// agents view's new action): the create records `parent_session_file`
+ /// as the session's `parentSessionPath` and runs it at `rlm_depth`
+ /// (one below the parent), so every roster surface nests it under the
+ /// parent.
+ NewChild {
+ parent_session_file: PathBuf,
+ rlm_depth: u32,
+ },
/// Attach an existing live session by active session id.
Attach(String),
/// Create with `sessionPath`: reopen a saved session file (`--resume`).
@@ -192,6 +201,10 @@ pub trait InteractionTelemetry: Send + Sync {
&self,
children_total: u64,
) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
+ /// The scoped agents view's new action created a session under the
+ /// scope root (`tui agents new scoped`): `depth` is the new session's
+ /// RLM depth.
+ fn scoped_agent_created(&self, depth: u32) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
/// An actionable activity group was opened; never includes command or goal text.
fn activity_opened(&self, kind: &'static str) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
/// A menu surface opened (event `tui menu opened`): `menu` names the
@@ -471,6 +484,14 @@ impl InteractiveOptions {
if self.telemetry_disabled == Some(true) {
config["telemetryDisabled"] = json!(true);
}
+ if let SessionSelection::NewChild {
+ parent_session_file,
+ rlm_depth,
+ } = &self.session
+ {
+ config["parentSessionPath"] = json!(parent_session_file.to_string_lossy());
+ config["rlmDepth"] = json!(rlm_depth);
+ }
config
}
}
diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rs
index 88a5db0dbf..345a590569 100644
--- a/crates/pa-tui/src/interactive/run.rs
+++ b/crates/pa-tui/src/interactive/run.rs
@@ -275,7 +275,12 @@ 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 && matches!(&options.session, SessionSelection::New) {
+ if !headless
+ && matches!(
+ &options.session,
+ SessionSelection::New | SessionSelection::NewChild { .. }
+ )
+ {
if let Some(renderer) = renderer.is_terminal_mut() {
crate::app::draw(renderer, &mut view)?;
}
diff --git a/crates/pa-tui/src/interactive/tests.rs b/crates/pa-tui/src/interactive/tests.rs
index 9b2e68ee28..666157f8bf 100644
--- a/crates/pa-tui/src/interactive/tests.rs
+++ b/crates/pa-tui/src/interactive/tests.rs
@@ -153,6 +153,23 @@ fn create_config_omits_thinking_when_no_flag_was_given() {
assert!(config.get("thinking").is_none());
}
+#[test]
+fn create_config_binds_a_new_child_to_its_parent() {
+ let mut opts = options(ModelSelection::default());
+ opts.session = SessionSelection::NewChild {
+ parent_session_file: "/x/p.jsonl".into(),
+ rlm_depth: 2,
+ };
+ assert_eq!(
+ opts.create_config(),
+ json!({
+ "cwd": "/tmp",
+ "parentSessionPath": "/x/p.jsonl",
+ "rlmDepth": 2
+ })
+ );
+}
+
#[test]
fn resume_hint_names_a_flushed_session() {
let dir = std::env::temp_dir().join("pa-tui-resume-hint-test");
diff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rs
index d36789d9e3..8b3cb0c483 100644
--- a/crates/pa-tui/src/session_ui/lifecycle.rs
+++ b/crates/pa-tui/src/session_ui/lifecycle.rs
@@ -31,6 +31,19 @@ impl SessionUi {
) -> Result<SessionUi> {
let active_session_id = match &options.session {
SessionSelection::New => create_session(&client, options, None).await?,
+ SessionSelection::NewChild { rlm_depth, .. } => {
+ let id = create_session(&client, options, None).await?;
+ // `tui agents new scoped`, fire-and-forget (the
+ // `subagents_view_opened` pattern): the open never waits on
+ // the telemetry flush.
+ if let Some(telemetry) = options.telemetry.clone() {
+ let depth = *rlm_depth;
+ tokio::spawn(async move {
+ telemetry.scoped_agent_created(depth).await;
+ });
+ }
+ id
+ }
SessionSelection::Attach(id) => id.clone(),
SessionSelection::Resume(_) => {
create_session(&client, options, Some(&options.session)).await?
diff --git a/crates/pa-tui/src/session_ui/sessions_fork.rs b/crates/pa-tui/src/session_ui/sessions_fork.rs
index e9d0678330..6f665cf238 100644
--- a/crates/pa-tui/src/session_ui/sessions_fork.rs
+++ b/crates/pa-tui/src/session_ui/sessions_fork.rs
@@ -521,7 +521,10 @@ pub(super) async fn create_session(
) -> Result<String> {
let session_path = match selection {
Some(SessionSelection::Resume(path)) => Some(path.to_string_lossy().to_string()),
- _ => None,
+ Some(
+ SessionSelection::New | SessionSelection::NewChild { .. } | SessionSelection::Attach(_),
+ )
+ | None => None,
};
// The create consumes the path; a refusal needs it again for the
// descriptive error.
diff --git a/crates/pa-tui/src/subagents.rs b/crates/pa-tui/src/subagents.rs
index 11c942c1e7..4e9712a0e4 100644
--- a/crates/pa-tui/src/subagents.rs
+++ b/crates/pa-tui/src/subagents.rs
@@ -103,12 +103,73 @@ pub(crate) fn summary_identity_keys(summary: &Value) -> Vec<String> {
keys
}
+/// Whether a summary is a spawned subagent (TS `isSubagentSummary`): the
+/// runtime kind decides when present; summaries from daemons that predate
+/// it still carry subagent linkage and never surface as top-level agents.
+pub(crate) fn is_subagent_summary(summary: &Value) -> bool {
+ match summary.get("runtimeKind").and_then(Value::as_str) {
+ Some(kind) => kind == "subagent",
+ None => [
+ "rlmChildId",
+ "rlmParentNodeId",
+ "parentActiveSessionId",
+ "parentSessionId",
+ "parentSessionPath",
+ ]
+ .iter()
+ .any(|field| {
+ summary
+ .get(*field)
+ .and_then(Value::as_str)
+ .is_some_and(|value| !value.is_empty())
+ }),
+ }
+}
+
+/// Whether `child` carries a spawn-consistent parent binding to the
+/// session whose file is `parent_file` at `parent_depth`: its
+/// `parentSessionPath` names that file and it runs exactly one level
+/// below it. A fork's source binding sits at the SAME depth and is a
+/// sibling, never a parent. Any runtime counts, so a session a user
+/// created under a parent (the scoped agents view's new action) is that
+/// parent's child exactly like a spawned one.
+pub(crate) fn depth_consistent_binding(
+ child: &Value,
+ parent_file: Option<&str>,
+ parent_depth: Option<u64>,
+) -> bool {
+ let Some(depth) = child
+ .get("rlmDepth")
+ .and_then(Value::as_u64)
+ .filter(|depth| *depth > 0)
+ else {
+ return false;
+ };
+ let Some(parent_path) = child
+ .get("parentSessionPath")
+ .and_then(Value::as_str)
+ .filter(|path| !path.is_empty())
+ else {
+ return false;
+ };
+ parent_file == Some(parent_path) && parent_depth == Some(depth - 1)
+}
+
/// Every row whose summary descends from `parent`, breadth-first over the
/// parent linkage, with each row's depth below `parent` (TS
/// `collectSubagentDescendantSummaries`): child rows link through their
/// parent keys, and each linked row extends the walk with its own
/// identity keys so deeper descendants stay reachable. The depth pairs
/// the direct/nested running counts (depth 1 = a direct child).
+///
+/// Operator ruling (2026-09-28, a deliberate TS divergence - "agents and
+/// users should be seen as equal collaborators working on the same
+/// project"): a LIVE top-level session with a depth-consistent parent
+/// binding (the scoped agents view's new action) links exactly like a
+/// spawned subagent, and linked rows extend the walk with themselves as
+/// the binding owner. A same-depth binding is a fork (a sibling, never a
+/// child); a message-less draft stays out of the walk, exactly as the
+/// agents view hides it.
#[must_use]
pub fn descendant_positions_with_depth(
summaries: &[&Value],
@@ -117,28 +178,48 @@ pub fn descendant_positions_with_depth(
let mut by_parent_key: std::collections::HashMap<String, Vec<usize>> =
std::collections::HashMap::new();
for (position, summary) in summaries.iter().enumerate() {
- if get_str(summary, "runtimeKind") != Some("subagent") {
- continue;
- }
for key in summary_parent_keys(summary) {
by_parent_key.entry(key).or_default().push(position);
}
}
- let mut queue: Vec<(String, usize)> = parent.keys().into_iter().map(|key| (key, 0)).collect();
+ let root_keys: std::collections::HashSet<String> = parent.keys().into_iter().collect();
+ // The binding owner at the root is the session's own roster row; a
+ // session missing from the roster it subscribed to keeps subagent-only
+ // links.
+ let root_owner = summaries.iter().copied().find(|summary| {
+ summary_identity_keys(summary)
+ .iter()
+ .any(|key| root_keys.contains(key))
+ });
+ let mut queue: Vec<(String, usize, Option<&Value>)> = parent
+ .keys()
+ .into_iter()
+ .map(|key| (key, 0, root_owner))
+ .collect();
let mut positions: Vec<(usize, usize)> = Vec::new();
let mut linked: std::collections::HashSet<usize> = std::collections::HashSet::new();
let mut index = 0;
while index < queue.len() {
// The owned copy ends the slice borrow before the extend below
// mutates the queue.
- let (key, owner_depth) = queue[index].clone();
+ let (key, owner_depth, owner) = queue[index].clone();
for position in by_parent_key.get(&key).into_iter().flatten() {
- if linked.insert(*position) {
+ let candidate = summaries[*position];
+ let links = is_subagent_summary(candidate)
+ || (get_str(candidate, "lifecycle") == Some("live")
+ && owner.is_some_and(|owner| {
+ depth_consistent_binding(
+ candidate,
+ get_str(owner, "sessionFile"),
+ owner.get("rlmDepth").and_then(Value::as_u64),
+ )
+ }));
+ if links && linked.insert(*position) {
positions.push((*position, owner_depth + 1));
queue.extend(
- summary_identity_keys(summaries[*position])
+ summary_identity_keys(candidate)
.into_iter()
- .zip(std::iter::repeat(owner_depth + 1)),
+ .map(|key| (key, owner_depth + 1, Some(candidate))),
);
}
}
@@ -432,21 +513,72 @@ mod tests {
);
}
+ /// One top-level session summary bound to `parent` (the user-created
+ /// child's shape: no spawn ids, a depth-consistent parent binding).
+ fn top_level(id: &str, rlm_depth: u64, parent: &str, lifecycle: &str) -> Value {
+ json!({
+ "sessionId": id,
+ "activeSessionId": format!("{id}-live"),
+ "sessionFile": format!("/sessions/{id}.jsonl"),
+ "runtimeKind": "top-level",
+ "lifecycle": lifecycle,
+ "rlmDepth": rlm_depth,
+ "parentSessionPath": parent,
+ })
+ }
+
+ /// The operator's 2026-09-28 ruling (agents and users are equal
+ /// collaborators): a live top-level session bound one level below
+ /// `parent` counts exactly like a spawned subagent; a same-depth fork
+ /// and a message-less draft never do.
#[test]
- fn non_subagent_rows_never_link() {
+ fn a_bound_session_counts_as_a_child_and_a_fork_or_draft_does_not() {
+ let mut root = parent_summary("p1");
+ root["rlmDepth"] = json!(0);
+ let mut spawned = child_summary("c1", "p1", "subagent");
+ spawned["rlmDepth"] = json!(1);
let roster = vec![
- entry("p1", &parent_summary("p1"), "idle"),
- entry("fork", &child_summary("f1", "p1", "top-level"), "running"),
+ entry("p1", &root, "idle"),
+ entry("c1", &spawned, "idle"),
+ entry(
+ "u1",
+ &top_level("u1", 1, "/sessions/p1.jsonl", "live"),
+ "running",
+ ),
+ entry(
+ "u2",
+ &top_level("u2", 2, "/sessions/c1.jsonl", "live"),
+ "running",
+ ),
+ entry(
+ "f1",
+ &top_level("f1", 0, "/sessions/p1.jsonl", "live"),
+ "running",
+ ),
+ entry(
+ "d1",
+ &top_level("d1", 1, "/sessions/p1.jsonl", "draft"),
+ "idle",
+ ),
];
- let counts = count_descendants(
- &roster,
- &SessionIdentity::new(
- Some("p1-live".to_string()),
- Some("p1".to_string()),
- Some("/sessions/p1.jsonl".to_string()),
+ assert_eq!(
+ count_descendants(
+ &roster,
+ &SessionIdentity::new(
+ Some("p1-live".to_string()),
+ Some("p1".to_string()),
+ Some("/sessions/p1.jsonl".to_string()),
+ ),
),
+ SubagentCounts {
+ total: 3,
+ running: 2,
+ running_direct: 1,
+ running_nested: 1,
+ idle: 1,
+ inactive: 0,
+ }
);
- assert_eq!(counts.total, 0);
}
#[test]