A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[factory] pa-tui: factory view arrows walk the states that ran; Enter/→ opens the session (#3798)
Sebastian Müller407aa2b2d22c
diff --git a/.changes/view-nav.md b/.changes/view-nav.mdnew file mode 100644index 0000000000..d2907c7a9a--- /dev/null+++ b/.changes/view-nav.md@@ -0,0 +1 @@+- Factory page: the arrows now walk each run's header and the states that spawned a session, and Enter or → opens that state's latest session. The opened session shows its `depth N` label, and leaving it returns to the factory page on the same run and state. Navigation never stops a run any more: stopping takes two presses of Ctrl+X (the agents view's stop key) — on a run header it stops the run, on a running state it stops that state's agent — and `r` resumes a paused run. `/resume <session>` now opens that session instead of exiting the app.diff --git a/crates/pa-cli/src/interactive_mode.rs b/crates/pa-cli/src/interactive_mode.rsindex 987e8f59d8..7f9a5e4da5 100644--- a/crates/pa-cli/src/interactive_mode.rs+++ b/crates/pa-cli/src/interactive_mode.rs@@ -13,7 +13,10 @@ use anyhow::{anyhow, Context, Result};use crate::config;use crate::mode::RunOptions;use pa_core::session::discovery::{resolve_session_path, ResolvedSession};-use pa_tui::interactive::{InteractiveOptions, ModelSelection, SessionSelection, UiMode};+use pa_tui::interactive::{+ InteractiveOptions, InteractiveOutcome, ModelSelection, SelectionOrigin, SessionSelection,+ UiMode,+};mod daemon;@@ -151,7 +154,7 @@ pub fn run_interactive_mode(options: &RunOptions) -> Result<i32> {let (anchor, notice) = continue_view.map_or((None, None), |view| {(Some(view.session_id), Some(view.notice))});- run_agents_view_flow(tui_options, anchor, notice).await+ run_agents_view_flow(tui_options, anchor, notice, None).await} else {let outcome =pa_tui::interactive::run_interactive(tui_options.clone(), UiMode::Terminal)@@ -159,18 +162,15 @@ pub fn run_interactive_mode(options: &RunOptions) -> Result<i32> {// TS `main.ts`: a direct session run closes into the agents view// when the exit came through agents-back or `/resume`// (`launchAgentsView` anchored on the session just left); every- // other exit (ctrl+c/ctrl+d, `/quit`) ends the process.- if outcome.return_to_agents_view {- // A startup attach that fell back to the view has no session- // identity to anchor on; its notice seeds the view's status- // line instead.- let anchor =- (!outcome.session_id.is_empty()).then(|| outcome.session_id.clone());- run_agents_view_flow(tui_options, anchor, outcome.agents_view_notice).await- } else {- print_resume_hint(outcome.resume_hint.as_deref());- Ok(())- }+ // other exit (ctrl+c/ctrl+d, `/quit`) ends the process. The flow+ // makes that call, exactly as for the sessions the view opens. The+ // run consumed the CLI message: no later run of the flow replays it.+ let base = InteractiveOptions {+ initial_message: None,+ ..tui_options+ };+ let entry = (base.clone(), outcome);+ run_agents_view_flow(base, None, None, Some(entry)).await}};let result = run.await;@@ -234,10 +234,15 @@ fn print_resume_hint(hint: Option<&str>) {/// The agents-view loop: open the view, run the session it opens, and return/// to the view on agents-back or bare `/resume`; every other exit ends the app.+/// `entry` is a session run that already ended (the direct launch): the flow+/// continues its handoff before the first view run. A session a run requests+/// (`/resume <selector>`, the factory page's state open) runs next, and leaving+/// it reopens the requesting session's origin page when the request carried one.async fn run_agents_view_flow(- base: InteractiveOptions,+ mut base: InteractiveOptions,anchor: Option<String>,notice: Option<String>,+ entry: Option<(InteractiveOptions, InteractiveOutcome)>,) -> Result<()> {let mut anchor = anchor;// Every view run reuses the roster connection (a chat run hands it@@ -254,7 +259,58 @@ async fn run_agents_view_flow(let mut selected_row_identity: Option<String> = None;let mut selected_key: Option<pa_tui::agents_view::AgentsViewSelectionKey> = None;let mut status_message: Option<String> = notice;+ let mut handoff = entry;loop {+ // The session runs chained by handoffs, each with the options it ran+ // with; the origin is the requesting session (its options re-targeted+ // at its live runtime) and the page leaving the requested session+ // reopens.+ let mut origin: Option<(InteractiveOptions, SelectionOrigin)> = None;+ while let Some((ran_with, outcome)) = handoff.take() {+ if !outcome.session_id.is_empty() {+ anchor = Some(outcome.session_id.clone());+ }+ if let Some(notice) = &outcome.agents_view_notice {+ status_message = Some(notice.clone());+ }+ if !outcome.return_to_agents_view && outcome.selection_request.is_none() {+ print_resume_hint(outcome.resume_hint.as_deref());+ if let Some(link) = roster_link.take() {+ link.close();+ }+ return Ok(());+ }+ if let Some(scope) = outcome.agents_view_scope {+ // Push a frame with the session as the return chat and clear the+ // query — a filter typed to find the session would hide the subtree.+ frames.retain(|(frame, _)| frame.session_id != scope.session_id);+ frames.push((+ scope,+ Some(SessionSelection::Attach(outcome.active_session_id.clone())),+ ));+ query = None;+ } else if let Some(selection) = outcome.selection_request {+ origin = outcome.selection_origin.map(|page| {+ let mut requester = ran_with;+ requester.session = SessionSelection::Attach(outcome.active_session_id);+ (requester, page)+ });+ let mut next = base.clone();+ next.session = selection;+ next.session_rlm_depth = outcome.selection_rlm_depth;+ let outcome =+ pa_tui::interactive::run_interactive(next.clone(), UiMode::Terminal).await?;+ handoff = Some((next, outcome));+ } else if let Some((requester, page)) = origin.take() {+ let outcome = pa_tui::interactive::run_interactive_origin_open(+ requester.clone(),+ UiMode::Terminal,+ page,+ )+ .await?;+ handoff = Some((requester, outcome));+ }+ }let view_options = pa_tui::agents_view::AgentsViewOptions {socket_path: base.socket_path.clone(),cwd: base.cwd.clone(),@@ -330,62 +386,16 @@ async fn run_agents_view_flow(session_options.cwd = cwd;}let outcome = pa_tui::interactive::run_interactive_agents_view_open(- session_options,+ session_options.clone(),UiMode::Terminal,view.panel,).await?;- if !outcome.session_id.is_empty() {- anchor = Some(outcome.session_id.clone());- }- if let Some(notice) = &outcome.agents_view_notice {- status_message = Some(notice.clone());- }- if !outcome.return_to_agents_view {- print_resume_hint(outcome.resume_hint.as_deref());- if let Some(link) = roster_link.take() {- link.close();- }- return Ok(());- }- if let Some(scope) = outcome.agents_view_scope {- // Push a frame with the session as the return chat and clear the- // query — a filter typed to find the session would hide the subtree.- frames.retain(|(frame, _)| frame.session_id != scope.session_id);- frames.push((- scope,- Some(SessionSelection::Attach(outcome.active_session_id.clone())),- ));- query = None;- }- let mut pending = outcome.selection_request;- while let Some(selection) = pending.take() {- let mut next = base.clone();- next.session = selection;- let outcome = pa_tui::interactive::run_interactive(next, UiMode::Terminal).await?;- if !outcome.session_id.is_empty() {- anchor = Some(outcome.session_id.clone());- }- if let Some(notice) = &outcome.agents_view_notice {- status_message = Some(notice.clone());- }- if !outcome.return_to_agents_view {- print_resume_hint(outcome.resume_hint.as_deref());- if let Some(link) = roster_link.take() {- link.close();- }- return Ok(());- }- if let Some(scope) = outcome.agents_view_scope {- frames.retain(|(frame, _)| frame.session_id != scope.session_id);- frames.push((- scope,- Some(SessionSelection::Attach(outcome.active_session_id.clone())),- ));- query = None;- }- pending = outcome.selection_request;- }+ // The run consumed the CLI message: neither a later open nor a return+ // to this session replays it.+ base.initial_message = None;+ session_options.initial_message = None;+ handoff = Some((session_options, outcome));}}diff --git a/crates/pa-tui/src/agents_view.rs b/crates/pa-tui/src/agents_view.rsindex dcf8998d2b..73a3148686 100644--- a/crates/pa-tui/src/agents_view.rs+++ b/crates/pa-tui/src/agents_view.rs@@ -48,7 +48,8 @@ mod session_activity;#[cfg(test)]use delete::no_effect_summary;-use delete::{spawn_delete_dispatch, DeleteAction, PendingDelete};+pub(crate) use delete::{execute_delete_action, DeleteAction};+use delete::{spawn_delete_dispatch, PendingDelete};mod rename;use rename::{spawn_rename_dispatch, Rename};@@ -59,7 +60,8 @@ use reply::{};mod status;-use status::{Status, StatusTone};+use status::Status;+pub(crate) use status::StatusTone;#[derive(Debug, Clone)]pub struct AgentsViewOptions {diff --git a/crates/pa-tui/src/agents_view/delete.rs b/crates/pa-tui/src/agents_view/delete.rsindex e3e106d96c..ad91fe740f 100644--- a/crates/pa-tui/src/agents_view/delete.rs+++ b/crates/pa-tui/src/agents_view/delete.rs@@ -19,7 +19,7 @@ pub(super) struct PendingDelete {/// One stop-or-delete dispatch the run loop executes (the wire variant follows the row kind).#[derive(Debug, Clone, PartialEq, Eq)]-pub(super) enum DeleteAction {+pub(crate) enum DeleteAction {/// A running subagent: stop it via its parent's session/// (`cancel_rlm_child`).StopSubagent {@@ -119,6 +119,85 @@ pub(super) fn no_effect_summary(data: Option<&serde_json::Value>) -> String {)}+/// Run one stop-or-delete on the wire and summarize its outcome: the status text and its tone+/// (success muted, a no-effect warning, a failure error). The factory page's child stop shares it.+pub(crate) async fn execute_delete_action(+ client: &DaemonClient,+ action: &DeleteAction,+) -> (String, StatusTone) {+ let request = match action {+ DeleteAction::StopSubagent {+ active_session_id,+ child_id,+ ..+ } => DaemonCommand::CancelRlmChild {+ id: None,+ active_session_id: active_session_id.clone(),+ child_id: child_id.clone(),+ rest: serde_json::Map::default(),+ },+ DeleteAction::DeleteSubagent {+ active_session_id,+ child_id,+ ..+ } => DaemonCommand::DeleteRlmSubagent {+ id: None,+ active_session_id: active_session_id.clone(),+ child_id: child_id.clone(),+ rest: serde_json::Map::default(),+ },+ DeleteAction::StopAgent {+ active_session_id, ..+ } => DaemonCommand::Kill {+ id: None,+ active_session_id: active_session_id.clone(),+ rest: serde_json::Map::default(),+ },+ DeleteAction::DeleteSavedSession { session_path, .. } => {+ DaemonCommand::DeleteSavedSession {+ id: None,+ active_session_id: None,+ session_path: session_path.clone(),+ rest: serde_json::Map::default(),+ }+ }+ DeleteAction::StopShell { shell_id, .. } => DaemonCommand::KillPersistentShell {+ id: None,+ shell_id: shell_id.clone(),+ rest: serde_json::Map::default(),+ },+ };+ // The outcome's tone is explicit: success muted, a no-effect stop warning, a+ // failure error — the status line never re-derives it from the text.+ match client.request(request).await {+ Ok(response) if response.success && action.effect_happened(&response) => {+ (action.success_message(), StatusTone::Muted)+ }+ Ok(response) if response.success => {+ // The wire ran but changed nothing: the status carries+ // what the wire said, never the button's hope.+ let summary = no_effect_summary(response.data.as_ref());+ (+ format!("{} did not change anything: {summary}", action.fail_word()),+ StatusTone::Warning,+ )+ }+ Ok(response) => {+ let error = response+ .error+ .unwrap_or_else(|| "the command failed".into());+ (+ format!("{} failed: {error}", action.fail_word()),+ StatusTone::Error,+ )+ }+ Err(error) => (+ format!("{} failed: {error}", action.fail_word()),+ StatusTone::Error,+ ),+ }+}+/// One stop-or-delete wire dispatch: the call runs off the key loop, its outcome re-enters as a/// `DeleteResult` status line — the roster push, not the status, refreshes the rows.pub(super) fn spawn_delete_dispatch(@@ -128,77 +207,7 @@ pub(super) fn spawn_delete_dispatch() -> tokio::task::JoinHandle<()> {let client = client.clone();tokio::spawn(async move {- let request = match &action {- DeleteAction::StopSubagent {- active_session_id,- child_id,- ..- } => DaemonCommand::CancelRlmChild {- id: None,- active_session_id: active_session_id.clone(),- child_id: child_id.clone(),- rest: serde_json::Map::default(),- },- DeleteAction::DeleteSubagent {- active_session_id,- child_id,- ..- } => DaemonCommand::DeleteRlmSubagent {- id: None,- active_session_id: active_session_id.clone(),- child_id: child_id.clone(),- rest: serde_json::Map::default(),- },- DeleteAction::StopAgent {- active_session_id, ..- } => DaemonCommand::Kill {- id: None,- active_session_id: active_session_id.clone(),- rest: serde_json::Map::default(),- },- DeleteAction::DeleteSavedSession { session_path, .. } => {- DaemonCommand::DeleteSavedSession {- id: None,- active_session_id: None,- session_path: session_path.clone(),- rest: serde_json::Map::default(),- }- }- DeleteAction::StopShell { shell_id, .. } => DaemonCommand::KillPersistentShell {- id: None,- shell_id: shell_id.clone(),- rest: serde_json::Map::default(),- },- };- // The outcome's tone is explicit: success muted, a no-effect stop warning, a- // failure error — the status line never re-derives it from the text.- let (outcome, tone) = match client.request(request).await {- Ok(response) if response.success && action.effect_happened(&response) => {- (action.success_message(), StatusTone::Muted)- }- Ok(response) if response.success => {- // The wire ran but changed nothing: the status carries- // what the wire said, never the button's hope.- let summary = no_effect_summary(response.data.as_ref());- (- format!("{} did not change anything: {summary}", action.fail_word()),- StatusTone::Warning,- )- }- Ok(response) => {- let error = response- .error- .unwrap_or_else(|| "the command failed".into());- (- format!("{} failed: {error}", action.fail_word()),- StatusTone::Error,- )- }- Err(error) => (- format!("{} failed: {error}", action.fail_word()),- StatusTone::Error,- ),- };+ let (outcome, tone) = execute_delete_action(&client, &action).await;let deleted_saved_path = match &action {DeleteAction::DeleteSavedSession { session_path, .. }if outcome.starts_with("Deleted session") =>diff --git a/crates/pa-tui/src/agents_view/open_incident.rs b/crates/pa-tui/src/agents_view/open_incident.rsindex 971987f15f..9beaa4168e 100644--- a/crates/pa-tui/src/agents_view/open_incident.rs+++ b/crates/pa-tui/src/agents_view/open_incident.rs@@ -3,7 +3,7 @@//! structured-log poll, the dismissal, and the panel render).use super::{ancestor_session_ids, has_session_children, scope_ancestors, AgentsViewMode, AgentsViewRow,- Line, OpenedRow, PathBuf, RowKind, SessionPanel, SessionSelection, Value, ANCHOR_LOADING_HINT,+ Line, OpenedRow, RowKind, SessionPanel, SessionSelection, Value, ANCHOR_LOADING_HINT,};impl AgentsViewMode {@@ -25,7 +25,9 @@ impl AgentsViewMode {RowKind::Shells => {self.open_activity_line(&row, SessionPanel::Shells { shell_id: None });}- RowKind::FactoryRuns => self.open_activity_line(&row, SessionPanel::FactoryRuns),+ RowKind::FactoryRuns => {+ self.open_activity_line(&row, SessionPanel::FactoryRuns { row: None });+ }}}@@ -96,8 +98,7 @@ impl AgentsViewMode {/// the tree re-expands to the row when the chat returns to the view.pub(super) fn open_subagent_row(&mut self, row: &AgentsViewRow) {let ancestors = ancestor_session_ids(&self.rows, row.parent_identity.as_deref());- if row.summary.get("activeSessionId").is_some() || row.summary.get("sessionFile").is_some()- {+ if SessionSelection::open_summary(&row.summary).is_some() {self.open_row(row, ancestors);return;}@@ -168,36 +169,11 @@ impl AgentsViewMode {status_message: Option<String>,selected_identity: Option<String>,) {- let summary = &row.summary;- if let Some(active) = summary- .get("activeSessionId")- .and_then(Value::as_str)- .filter(|id| !id.is_empty())- {- self.finish_open(- SessionSelection::Attach(active.to_string()),- row,- ancestors,- status_message,- selected_identity,- );- return;- }- if let Some(file) = summary- .get("sessionFile")- .and_then(Value::as_str)- .filter(|file| !file.is_empty())- {- self.finish_open(- SessionSelection::Resume(PathBuf::from(file)),- row,- ancestors,- status_message,- selected_identity,- );+ let Some(selection) = SessionSelection::open_summary(&row.summary) else {+ self.set_status("Cannot open agent without an active runtime or saved session file");return;- }- self.set_status("Cannot open agent without an active runtime or saved session file");+ };+ self.finish_open(selection, row, ancestors, status_message, selected_identity);}/// Record the open outcome: the selection plus the row metadata the flow and the sessiondiff --git a/crates/pa-tui/src/agents_view/status.rs b/crates/pa-tui/src/agents_view/status.rsindex a2db11ecf6..80365dd305 100644--- a/crates/pa-tui/src/agents_view/status.rs+++ b/crates/pa-tui/src/agents_view/status.rs@@ -4,7 +4,7 @@use std::time::Duration;#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(super) enum StatusTone {+pub(crate) enum StatusTone {Muted,Warning,Error,diff --git a/crates/pa-tui/src/agents_view/tests/activity_lines.rs b/crates/pa-tui/src/agents_view/tests/activity_lines.rsindex fd4325e86f..e666699c9b 100644--- a/crates/pa-tui/src/agents_view/tests/activity_lines.rs+++ b/crates/pa-tui/src/agents_view/tests/activity_lines.rs@@ -69,7 +69,7 @@ fn enter_on_a_nested_factory_line_opens_the_child_with_the_factory_panel() {opened.selection,SessionSelection::Attach("c-live".to_string()));- assert_eq!(opened.panel, Some(SessionPanel::FactoryRuns));+ assert_eq!(opened.panel, Some(SessionPanel::FactoryRuns { row: None }));assert_eq!(opened.expanded_ancestors, vec!["p".to_string()]);}diff --git a/crates/pa-tui/src/factory_view.rs b/crates/pa-tui/src/factory_view.rsindex 30d350651a..8ec300f19c 100644--- a/crates/pa-tui/src/factory_view.rs+++ b/crates/pa-tui/src/factory_view.rs@@ -1,19 +1,22 @@//! The `/factory` view: one panel per live factory run — the machine//! diagram with live highlighting, the run's state, the instances-//! running and queued, the budget consumed, and the milestone tail — on-//! the activity pages' picker keyset (arrows + Enter + Esc): the arrows-//! move the run selection over the NEWEST-FIRST feed (a run created-//! after an existing one renders above it, and the page opens with the-//! newest run selected), Enter opens the selected run's in-page action-//! rows (stop/resume — the heartbeats picker's drill-in shape), and Esc-//! backs out of the open action rows or closes the page.+//! running and queued, the budget consumed, and the milestone tail. The+//! panels read NEWEST-FIRST (a run created after an existing one renders+//! above it). The arrows walk the run headers and the states that ran a+//! session, across panels; Enter/→ open the selected state's latest+//! child session, ←/Esc close the page. Navigation never acts on a run:+//! the stop rides the agents view's two-press `app.agents.delete`+//! grammar (a header stops its run, a state stops its running child),+//! and `r` resumes a paused run.//!//! The view is pure presentation and selection: the session UI owns the//! refresh cadence (the run's collect cycle: a bounded watch on the-//! selected run, then the graph list), executes the actions through the-//! daemon's `factory_activity` lane, and repaints on the snapshot-//! signatures' hysteresis (a per-transition repaint never spams: only a-//! notice-worthy run-shape change flips the changed marker).+//! selected run, then the graph list), executes the actions (run+//! stop/resume on the daemon's `factory_activity` lane, a child stop on+//! `cancel_rlm_child`, the open through the session's roster), and+//! repaints on the snapshot signatures' hysteresis (a per-transition+//! repaint never spams: only a notice-worthy run-shape change flips the+//! changed marker).//!//! The diagram is the honest in-terminal machine graph: every state as a//! status-glyphed row in the machine's declared order — the row's label@@ -180,26 +183,15 @@ pub fn dock_factory_items(runs: &[FactoryRunSnapshot]) -> Vec<String> {.collect()}-/// One run-level action the page offers on a live run (the heartbeats-/// picker's action-row grammar): the stop that tears the run and its-/// children down, and the pause complement's resume.+/// One run-level action the page offers on a live run: the stop that+/// tears the run and its children down, and the pause complement's+/// resume.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum FactoryAction {Stop,Resume,}-impl FactoryAction {- /// The action row's label.- #[must_use]- pub fn label(self) -> &'static str {- match self {- Self::Stop => "Stop the run",- Self::Resume => "Resume the run",- }- }-}-/// Parse the daemon `factory_activity` graph reply: `{"runs": [...]}` in/// the kernel's compact snapshot shape. Malformed rows drop (a truncated/// panel never renders), and an unknown shape answers an empty view.@@ -357,10 +349,20 @@ fn parse_run(run: &Value) -> Option<FactoryRunSnapshot> {#[derive(Debug, Clone, PartialEq, Eq)]pub enum FactoryViewAction {None,- /// Stop the selected run.+ /// Open the selected state's latest child session.+ Open {+ child_id: String,+ },+ /// Stop the selected run (a confirmed stop on its header).Stop {run_id: String,},+ /// Stop the selected state's running child (a confirmed stop on its+ /// state row); `label` names the row (`<run>/<state>`).+ StopChild {+ child_id: String,+ label: String,+ },/// Resume the selected (paused) run.Resume {run_id: String,@@ -368,28 +370,25 @@ pub enum FactoryViewAction {Close,}-/// The page's mode: the run feed, or the selected run's open action rows-/// (the heartbeats picker's list/detail drill-in shape, one level — the-/// feed stays mounted behind the action rows; there is no separate detail-/// page to paint).+/// One selectable row, by identity: a run's header (`state_id` `None`)+/// or one of its states with a session.#[derive(Debug, Clone, PartialEq, Eq)]-enum Mode {- /// The run feed: the arrows walk the run selection.- Feed,- /// The open run's action rows: the arrows walk the offered actions.- /// The tracked action rides by IDENTITY, not index — a fold may- /// change the run's state (and with it the offered set) while the- /// rows are open, and a tracked index would silently rename the- /// selection to a different action (the feed's same-run lesson, one- /// level up).- Actions {- run_id: String,- action: FactoryAction,- },+pub struct FactoryRow {+ pub run_id: String,+ pub state_id: Option<String>,+}++impl FactoryRow {+ fn header(run_id: &str) -> Self {+ Self {+ run_id: run_id.to_string(),+ state_id: None,+ }+ }}-/// The `/factory` view's state: the parsed run panels, the selection, the-/// open action rows, and the hysteresis bookkeeping.+/// The `/factory` view's state: the parsed run panels, the selected row,+/// the armed stop, and the hysteresis bookkeeping.#[derive(Debug)]pub struct FactoryView {runs: Vec<FactoryRunSnapshot>,@@ -397,8 +396,12 @@ pub struct FactoryView {/// signature changed, decayed on the next cycle (no per-transition/// repaint spam — one marker per notice-worthy change).recent_change: Vec<bool>,- selected: usize,- mode: Mode,+ selected: Option<FactoryRow>,+ /// The row a first stop press armed, with the stop it armed: the next+ /// stop press on the same row confirms exactly that stop (a child a+ /// retry replaced in between is a different stop), any other key+ /// disarms.+ armed: Option<(FactoryRow, FactoryViewAction)>,error: Option<String>,viewport_rows: usize,}@@ -406,29 +409,27 @@ pub struct FactoryView {impl FactoryView {/// Build the view from the first snapshot batch. The batch arrives/// newest-first ([`parse_factory_runs`]'s reading order), so the- /// default selection — index 0 — is the newest run: the page opens on- /// the feed's live head.+ /// default selection — the first row — is the newest run's header.#[must_use]pub fn new(runs: Vec<FactoryRunSnapshot>, viewport_rows: usize) -> Self {let recent_change = vec![false; runs.len()];- Self {+ let mut view = Self {runs,recent_change,- selected: 0,- mode: Mode::Feed,+ selected: None,+ armed: None,error: None,viewport_rows,- }+ };+ view.selected = view.rows().into_iter().next();+ view}- /// The actions the page offers on one run (the heartbeats picker's- /// `availableActions` grammar): the pause complement first — resume- /// on a paused run — then stop, exactly while the run is live (a- /// `done` run with residents still in flight keeps its stop; a- /// fully terminal run offers nothing). The offered set is derived- /// from the run's CURRENT snapshot everywhere — the render, the- /// arrow walk, the Enter confirmation — so a fold's state change- /// can never leave a stale action offered.+ /// The run-level actions the page offers on one run: resume on a+ /// paused run, then stop exactly while the run is live (a `done` run+ /// with residents still in flight keeps its stop; a fully terminal+ /// run offers nothing). Always read from the run's CURRENT snapshot,+ /// so a fold's state change never leaves a stale action offered.#[must_use]pub fn available_actions(run: &FactoryRunSnapshot) -> Vec<FactoryAction> {let mut actions = Vec::with_capacity(2);@@ -460,8 +461,33 @@ impl FactoryView {view}+ /// The selectable rows in display order, flattened across panels:+ /// each run's header, then its states whose node has a session+ /// ([`FactoryNodeState::latest_child`]).+ fn rows(&self) -> Vec<FactoryRow> {+ let mut rows = Vec::new();+ for run in &self.runs {+ rows.push(FactoryRow::header(&run.run_id));+ rows.extend(+ run.states+ .iter()+ .filter(|state| {+ run.nodes+ .get(&state.id)+ .and_then(FactoryNodeState::latest_child)+ .is_some()+ })+ .map(|state| FactoryRow {+ run_id: run.run_id.clone(),+ state_id: Some(state.id.clone()),+ }),+ );+ }+ rows+ }+/// Apply one refreshed snapshot batch: keep the selection on the same- /// run, and light the changed marker exactly on the runs whose+ /// row, and light the changed marker exactly on the runs whose/// signature changed this cycle (the marker decays when the run goes/// quiet — the repaint hysteresis, no per-transition spam). Returns/// whether any run changed.@@ -479,56 +505,51 @@ impl FactoryView {changed = true;}}- // Keep the selection on the same run id, never the same index:- // the list reads newest-first, so a newer run folding in moves- // the selected run down without stealing the selection. A run- // that left the batch (the wire cap's oldest-end trim, a- // cleared registry) returns the selection to the feed's head —- // the newest run — because the same slot names a different run- // in the reversed order.- let selected_id = self.runs.get(self.selected).map(|run| run.run_id.clone());self.runs = runs;self.recent_change = recent_change;- self.selected = match selected_id {- Some(selected_id) => self- .runs- .iter()- .position(|run| run.run_id == selected_id)- .unwrap_or(0),- None => 0,- };- // The open action rows ride the same fold discipline as the- // feed's selection: a run that left the batch closes the rows,- // and a state change under them re-reads the offered set — a- // paused run that stopped mid-menu no longer offers resume,- // and the tracked action clamps to what the run still offers- // (never a stale target: the rows confirm against the folded- // snapshot, not the one they opened on).- if let Mode::Actions { run_id, action } = self.mode.clone() {- let offered = self- .runs- .iter()- .find(|run| run.run_id == run_id)- .map(Self::available_actions)- .unwrap_or_default();- match offered.first().copied() {- None => self.mode = Mode::Feed,- Some(first) if !offered.contains(&action) => {- self.mode = Mode::Actions {- run_id,- action: first,- };- }- Some(_) => {}+ // The selection rides the row's identity, never its index (the+ // feed reads newest-first, so a newer run folding in shifts every+ // index): a vanished state falls back to its run's header, a+ // vanished run to the first row.+ let rows = self.rows();+ self.selected = match self.selected.take() {+ Some(row) if rows.contains(&row) => Some(row),+ Some(row) if rows.contains(&FactoryRow::header(&row.run_id)) => {+ Some(FactoryRow::header(&row.run_id))}+ _ => rows.into_iter().next(),+ };+ // An armed stop the row no longer offers (the run left the batch+ // or stopped offering stop, the child settled or a retry replaced+ // it) disarms.+ if self+ .armed+ .as_ref()+ .is_some_and(|(row, stop)| self.stop_action(row).as_ref() != Some(stop))+ {+ self.armed = None;}changed}- /// The selected run's snapshot, when any run is live.+ /// The run that owns the selected row (the watch target and the run+ /// actions' target).#[must_use]pub fn selected_run(&self) -> Option<&FactoryRunSnapshot> {- self.runs.get(self.selected)+ let selected = self.selected.as_ref()?;+ self.runs.iter().find(|run| run.run_id == selected.run_id)+ }++ #[must_use]+ pub fn selected_row(&self) -> Option<&FactoryRow> {+ self.selected.as_ref()+ }++ /// Select `row` by identity. A row the batch does not list yet stays+ /// selected until the refresh that lists it lands ([`Self::apply_runs`]+ /// keeps a listed selection).+ pub fn select(&mut self, row: FactoryRow) {+ self.selected = Some(row);}/// Record one fetch/error line from the session UI's refresh. The@@ -539,135 +560,142 @@ impl FactoryView {self.error = error.map(|text| crate::menu_panel::scrub_controls(&text));}- /// One key press on the activity pages' picker keyset (arrows +- /// Enter + Esc — the heartbeats/bash pages' family): the arrows- /// move the selection (the feed's run, or the open action rows'- /// action), Enter opens the selected run's action rows or runs the- /// selected action, and Esc/ctrl+c back out of the open action rows- /// or close the page. Every binding reads the keybinding manager- /// (`tui.select.up`/`down`/`confirm`/`cancel`), so a user's remap- /// reaches this page exactly like its siblings.+ /// One key press. Navigation never acts on a run: the arrows (the+ /// `tui.select.up`/`down` bindings) walk the rows, Enter/→ open the+ /// selected state's session (inert on a header), ←/Esc/ctrl+c close+ /// the page. The stop rides the agents view's two-press grammar on+ /// `app.agents.delete`: the first press arms the selected row, a+ /// second press on it stops (the run on a header, the child on a+ /// state), and any other key only disarms. `r` resumes a paused run.#[must_use]pub fn handle_key(&mut self, key: &str, kb: &KeybindingsManager) -> FactoryViewAction {- if key == "ctrl+c" || kb.matches(key, "tui.select.cancel") {- // Esc backs out of the open action rows before it closes- // the page — the drill-in's back.- if self.mode != Mode::Feed {- self.mode = Mode::Feed;+ let armed = self.armed.take();+ if kb.matches(key, "app.agents.delete") {+ let Some(row) = self.selected.clone() else {+ return FactoryViewAction::None;+ };+ let Some(stop) = self.stop_action(&row) else {return FactoryViewAction::None;+ };+ if armed+ .as_ref()+ .is_some_and(|(armed_row, armed_stop)| *armed_row == row && *armed_stop == stop)+ {+ return stop;}+ self.armed = Some((row, stop));+ return FactoryViewAction::None;+ }+ if armed.is_some() {+ return FactoryViewAction::None;+ }+ if key == "ctrl+c" || kb.matches(key, "tui.select.cancel") {return FactoryViewAction::Close;}- if kb.matches(key, "tui.select.up") || kb.matches(key, "tui.select.down") {- let delta: isize = if kb.matches(key, "tui.select.up") {- -1- } else {- 1- };- self.move_selection(delta);+ if kb.matches(key, "tui.select.up") {+ self.move_selection(-1);+ return FactoryViewAction::None;+ }+ if kb.matches(key, "tui.select.down") {+ self.move_selection(1);return FactoryViewAction::None;}if kb.matches(key, "tui.select.confirm") {- return self.confirm_selection();- }- // The horizontal arrows mirror back/confirm — as fallbacks only,- // after the configured bindings, so a rebound Left/Right keeps- // its configured action.- if key == "left" {- if self.mode != Mode::Feed {- self.mode = Mode::Feed;- return FactoryViewAction::None;- }- return FactoryViewAction::Close;+ return self.open_selected();}- if key == "right" {- return self.confirm_selection();+ // The horizontal arrows are fallbacks after the configured+ // bindings, so a rebound Left/Right keeps its configured action.+ match key {+ "left" => FactoryViewAction::Close,+ "right" => self.open_selected(),+ "r" => match self.selected_run() {+ Some(run) if Self::available_actions(run).contains(&FactoryAction::Resume) => {+ FactoryViewAction::Resume {+ run_id: run.run_id.clone(),+ }+ }+ _ => FactoryViewAction::None,+ },+ _ => FactoryViewAction::None,}- FactoryViewAction::None}- /// One arrow step: the feed walks the run selection (newest-first —- /// down the feed reads OLDER), the open action rows walk their- /// offered set. A run that left the batch under open rows closes- /// them (the fold's own hand-back, reached from the key path too).+ /// One arrow step over the flattened rows; both ends clamp.fn move_selection(&mut self, delta: isize) {- match self.mode.clone() {- Mode::Feed => {- if self.runs.is_empty() {- return;- }- let next = (self.selected as isize + delta).clamp(0, self.runs.len() as isize - 1)- as usize;- self.selected = next;- }- Mode::Actions { run_id, action } => {- let Some(run) = self.runs.iter().find(|run| run.run_id == run_id) else {- self.mode = Mode::Feed;- return;- };- let actions = Self::available_actions(run);- let Some(current) = actions.iter().position(|candidate| *candidate == action)- else {- return;- };- let next = (current as isize + delta).clamp(0, actions.len() as isize - 1) as usize;- self.mode = Mode::Actions {- run_id,- action: actions[next],- };- }+ let rows = self.rows();+ if rows.is_empty() {+ return;}+ let current = self+ .selected+ .as_ref()+ .and_then(|selected| rows.iter().position(|row| row == selected))+ .unwrap_or(0);+ let next = (current as isize + delta).clamp(0, rows.len() as isize - 1) as usize;+ self.selected = Some(rows[next].clone());}- /// Enter: the feed opens the selected run's action rows (when the- /// run offers any — a terminal run answers nothing), the open rows- /// run the selected action and return to the feed. The- /// confirmation re-resolves the run and its offered set against- /// the CURRENT batch — a fold may have changed the run's state, or- /// dropped the run, while the rows were open — so the action lands- /// on the folded truth, never a stale target.- fn confirm_selection(&mut self) -> FactoryViewAction {- match self.mode.clone() {- Mode::Feed => {- if let Some(run) = self.selected_run() {- if let Some(action) = Self::available_actions(run).first().copied() {- self.mode = Mode::Actions {- run_id: run.run_id.clone(),- action,- };- }- }- FactoryViewAction::None- }- Mode::Actions { run_id, action } => {- let offered = self- .runs- .iter()- .find(|run| run.run_id == run_id)- .map(Self::available_actions)- .unwrap_or_default();- self.mode = Mode::Feed;- if offered.contains(&action) {- match action {- FactoryAction::Stop => FactoryViewAction::Stop { run_id },- FactoryAction::Resume => FactoryViewAction::Resume { run_id },- }- } else {- FactoryViewAction::None+ /// The selected state's latest child, as the open action; a header+ /// opens nothing.+ fn open_selected(&self) -> FactoryViewAction {+ self.selected+ .as_ref()+ .and_then(|row| self.row_child(row))+ .map_or(FactoryViewAction::None, |(child_id, _)| {+ FactoryViewAction::Open {+ child_id: child_id.to_string(),}- }+ })+ }++ /// A state row's latest child and its instance row.+ fn row_child(&self, row: &FactoryRow) -> Option<(&str, &diagram::FactoryInstance)> {+ let run = self.runs.iter().find(|run| run.run_id == row.run_id)?;+ run.nodes.get(row.state_id.as_ref()?)?.latest_child()+ }++ /// The row's display label: the run's name, `<run>/<state>` for a+ /// state.+ fn row_label(&self, row: &FactoryRow) -> String {+ let run = self+ .runs+ .iter()+ .find(|run| run.run_id == row.run_id)+ .map_or_else(|| row.run_id.clone(), FactoryRunSnapshot::display_name);+ match &row.state_id {+ Some(state_id) => format!("{run}/{state_id}"),+ None => run,}}+ /// What a confirmed stop on the row does, when the row can be stopped+ /// now: a header stops its run while the run offers stop; a state+ /// stops its latest child while that child runs.+ fn stop_action(&self, row: &FactoryRow) -> Option<FactoryViewAction> {+ if row.state_id.is_some() {+ let (child_id, instance) = self.row_child(row)?;+ return (instance.status == "running").then(|| FactoryViewAction::StopChild {+ child_id: child_id.to_string(),+ label: self.row_label(row),+ });+ }+ let run = self.runs.iter().find(|run| run.run_id == row.run_id)?;+ Self::available_actions(run)+ .contains(&FactoryAction::Stop)+ .then(|| FactoryViewAction::Stop {+ run_id: run.run_id.clone(),+ })+ }+/// Render the view: one panel per live run (the machine diagram with/// live highlighting), the empty state when nothing runs, and the/// trailing key hint.#[must_use]pub fn render(&self, theme: &Theme, width: usize, kb: &KeybindingsManager) -> Vec<Line> {- // The panel area: one panel per run, each panel's row range- // recorded for the budget window below.+ // The panel area: one panel per run; the selected row's line (and+ // its panel's start) is recorded for the budget window below.let mut panels: Vec<Line> = Vec::new();- let mut panel_ranges: Vec<(usize, usize)> = Vec::new();+ let mut focus: Option<(usize, usize)> = None;if self.runs.is_empty() {panels.push(vec![Span::raw("")]);panels.push(vec![@@ -687,15 +715,13 @@ impl FactoryView {panels.push(vec![Span::raw("")]);}let panel_start = panels.len();- self.render_panel(theme, width, run, index, &mut panels);- panel_ranges.push((panel_start, panels.len()));- }- // The chrome area: the open action rows, the error line from the- // last failed refresh, and the trailing key hint. The chrome- // always renders — the hint is the view's only key legend, and- // the action rows are the page's only action surface.- let action_rows = self.action_block(theme);- let mut chrome_rows = 2 + action_rows.len();+ if let Some(line) = self.render_panel(theme, width, run, index, &mut panels) {+ focus = Some((panel_start, line));+ }+ }+ // The chrome area: the error line from the last failed refresh+ // and the trailing key hint (the view's only key legend).+ let mut chrome_rows = 2;if self.error.is_some() {chrome_rows += 2;}@@ -703,35 +729,28 @@ impl FactoryView {// renders more rows than the viewport asked for. A tall view// windows over the panel area: the leading window keeps the top// of the feed (the newest panels — the oldest panels drop- // first), and when the focused run's panel falls below it the- // window slides to it (the focused run is the actionable one —- // the feed's selection, or the run whose action rows are- // open — so a stop/resume target never hides behind the- // budget); the chrome stays pinned at the end either way.- let focus = match &self.mode {- Mode::Actions { run_id, .. } => self- .runs- .iter()- .position(|run| &run.run_id == run_id)- .unwrap_or(self.selected),- Mode::Feed => self.selected,- };+ // first), and when the selected row falls below it the window+ // slides: to the row's panel header when the row fits under it,+ // else just far enough to show the row (an open or stop target+ // never hides behind the budget); the chrome stays pinned at the+ // end.let budget = self.viewport_rows.max(1);let panel_budget = budget.saturating_sub(chrome_rows);if panels.len() > panel_budget {- let mut start = 0;- if let Some((focus_start, _)) = panel_ranges.get(focus) {- if *focus_start >= panel_budget {- start = *focus_start;+ let start = match focus {+ Some((panel_start, line)) if line >= panel_budget => {+ if line - panel_start < panel_budget {+ panel_start+ } else {+ line + 1 - panel_budget+ }}- }- if start > 0 {- panels.drain(..start);- }+ _ => 0,+ };+ panels.drain(..start);panels.truncate(panel_budget);}let mut rows = panels;- rows.extend(action_rows);if let Some(error) = &self.error {rows.push(vec![Span::raw("")]);rows.push(vec![@@ -740,11 +759,8 @@ impl FactoryView {]);}rows.push(vec![Span::raw("")]);- let hint = match self.mode {- Mode::Feed => Self::feed_hint(kb),- Mode::Actions { .. } => Self::actions_hint(kb),- };- rows.push(vec![Span::raw(" "), theme.fg_span(ThemeColor::Dim, hint)]);+ let (hint, hint_color) = self.hint(kb);+ rows.push(vec![Span::raw(" "), theme.fg_span(hint_color, hint)]);// A degenerate budget (a sub-chrome viewport on a short terminal)// tail-clips: the hint is the chrome's last row and always survives.if rows.len() > budget {@@ -755,76 +771,53 @@ impl FactoryView {.collect()}- /// The feed's bottom hint line (the heartbeats/bash pages' grammar):- /// the arrows move, Enter opens the selected run's action rows, Esc- /// closes.- fn feed_hint(kb: &KeybindingsManager) -> String {+ /// The bottom hint line: the confirm prompt while a stop is armed,+ /// else the keys, with stop/resume only when the selected row offers+ /// them.+ fn hint(&self, kb: &KeybindingsManager) -> (String, ThemeColor) {let key = |binding: &str, fallback: &str| {kb.first_key(binding).map_or_else(|| fallback.to_string(), |key| format_key_text(&key))};- format!(- "{}/{} move \u{b7} {} actions \u{b7} {} close",- key("tui.select.up", "\u{2191}"),- key("tui.select.down", "\u{2193}"),- key("tui.select.confirm", "Enter"),- key("tui.select.cancel", "Esc"),- )- }-- /// The open action rows' hint line: the arrows walk the actions,- /// Enter runs the tracked one, Esc backs out to the feed.- fn actions_hint(kb: &KeybindingsManager) -> String {- let key = |binding: &str, fallback: &str| {- kb.first_key(binding)- .map_or_else(|| fallback.to_string(), |key| format_key_text(&key))- };- format!(- "{}/{} action \u{b7} {} run \u{b7} {} back",- key("tui.select.up", "\u{2191}"),- key("tui.select.down", "\u{2193}"),- key("tui.select.confirm", "Enter"),- key("tui.select.cancel", "Esc"),- )- }-- /// The open action rows (the heartbeats picker's drill-in, one- /// level): a blank, a header naming the run, one row per offered- /// action with the tracked one marked. The block rides the- /// trailing chrome — the panel window's budget keeps it and the- /// hint painted together.- fn action_block(&self, theme: &Theme) -> Vec<Line> {- let Mode::Actions { run_id, action } = &self.mode else {- return Vec::new();- };- let Some(run) = self.runs.iter().find(|run| &run.run_id == run_id) else {- return Vec::new();- };- let mut rows = vec![vec![Span::raw("")]];- let mut header: Line = vec![Span::raw(" ")];- header.push(theme.fg_span(ThemeColor::ToolTitle, "actions: "));- header.push(theme.fg_span(ThemeColor::Text, run.display_name()));- rows.push(header);- for offered in Self::available_actions(run) {- let tracked = offered == *action;- let mut row: Line = vec![Span::raw(" ")];- row.push(Span::raw(if tracked { "▸ " } else { " " }));- row.push(theme.fg_span(- if tracked {- ThemeColor::Text- } else {- ThemeColor::Muted- },- offered.label().to_string(),- ));- rows.push(row);+ let stop_key = key("app.agents.delete", "ctrl+x");+ if let Some((armed, _)) = &self.armed {+ return (+ format!(+ "stop {}? {stop_key} again to confirm, any other key cancels",+ self.row_label(armed)+ ),+ ThemeColor::Warning,+ );}- rows+ let mut parts = vec![+ format!(+ "{}/{} move",+ key("tui.select.up", "\u{2191}"),+ key("tui.select.down", "\u{2193}"),+ ),+ format!("{}/\u{2192} open", key("tui.select.confirm", "Enter")),+ "\u{2190} back".to_string(),+ ];+ if self+ .selected+ .as_ref()+ .is_some_and(|selected| self.stop_action(selected).is_some())+ {+ parts.push(format!("{stop_key} stop"));+ }+ if self+ .selected_run()+ .is_some_and(|run| Self::available_actions(run).contains(&FactoryAction::Resume))+ {+ parts.push("r resume".to_string());+ }+ (parts.join(" \u{b7} "), ThemeColor::Dim)}/// One run panel: the header (name, state, changed marker), the stats/// line (budget consumed, parallel, instances), the machine diagram,- /// and the milestone tail.+ /// and the milestone tail. Returns the selected row's line in `rows`+ /// when the selection is in this panel.fn render_panel(&self,theme: &Theme,@@ -832,11 +825,16 @@ impl FactoryView {run: &FactoryRunSnapshot,index: usize,rows: &mut Vec<Line>,- ) {- let selected = index == self.selected;+ ) -> Option<usize> {+ let selected = self+ .selected+ .as_ref()+ .filter(|row| row.run_id == run.run_id);+ let header_selected = selected.is_some_and(|row| row.state_id.is_none());+ let selected_state = selected.and_then(|row| row.state_id.as_deref());let changed = self.recent_change.get(index).copied().unwrap_or(false);// The header: the selection marker, the run's name, its state.- let mut header: Line = vec![Span::raw(if selected { "▸ " } else { " " })];+ let mut header: Line = vec![Span::raw(if header_selected { "▸ " } else { " " })];header.push(theme.fg_span(ThemeColor::ToolTitle, "factory: "));header.push(theme.fg_span(ThemeColor::Text, run.display_name()));let state_text = match run.state.as_deref() {@@ -857,10 +855,11 @@ impl FactoryView {Span::raw(" "),theme.fg_span(ThemeColor::Muted, Self::stats_line(run, running)),];+ let header_line = rows.len();rows.push(header);rows.push(truncate_line(&stats, width, ""));rows.push(vec![Span::raw("")]);- Self::render_diagram(theme, run, rows);+ let state_line = Self::render_diagram(theme, run, selected_state, rows);if !run.milestones.is_empty() {let tail = run.milestones@@ -877,6 +876,11 @@ impl FactoryView {theme.fg_span(ThemeColor::Muted, tail),]);}+ if header_selected {+ Some(header_line)+ } else {+ state_line+ }}fn stats_line(run: &FactoryRunSnapshot, running: u64) -> String {@@ -905,10 +909,17 @@ impl FactoryView {}/// The machine diagram: every state in the machine's declared order as- /// a status-glyphed row, its outgoing transitions as connector rows- /// (joins once, back edges marked, the last-fired edges marked and- /// colored).- fn render_diagram(theme: &Theme, run: &FactoryRunSnapshot, rows: &mut Vec<Line>) {+ /// a status-glyphed row (the selected state marked), its outgoing+ /// transitions as connector rows (joins once, back edges marked, the+ /// last-fired edges marked and colored). Returns the selected state's+ /// line in `rows`.+ fn render_diagram(+ theme: &Theme,+ run: &FactoryRunSnapshot,+ selected_state: Option<&str>,+ rows: &mut Vec<Line>,+ ) -> Option<usize> {+ let mut selected_line = None;let order: Vec<&str> = run.states.iter().map(|state| state.id.as_str()).collect();let position = |id: &str| order.iter().position(|candidate| *candidate == id);for state in &run.states {@@ -917,13 +928,25 @@ impl FactoryView {// status: a multi-entry state whose latest entry settled while// an earlier one still runs stays bright (is_active covers// every entry's status, not just the newest).+ // A state without a session (never entered, or no child+ // spawned yet) paints dim whatever its status: it is not+ // selectable.let (glyph, color) = match node {+ Some(node) if node.latest_child().is_none() => {+ (node_glyph(&node.status).0, ThemeColor::Dim)+ }Some(node) if node.is_active() => ("●", ThemeColor::Accent),Some(node) => node_glyph(&node.status),None => ("○", ThemeColor::Dim),};+ let marker = if selected_state == Some(state.id.as_str()) {+ selected_line = Some(rows.len());+ " ▸ "+ } else {+ " "+ };let mut row: Line = vec![- Span::raw(" "),+ Span::raw(marker),theme.fg_span(color, glyph.to_string()),Span::raw(" "),// The whole row paints in the node's status color: active@@ -997,6 +1020,7 @@ impl FactoryView {rows.push(row);}}+ selected_line}}diff --git a/crates/pa-tui/src/factory_view/diagram.rs b/crates/pa-tui/src/factory_view/diagram.rsindex ec594971ef..096ba37245 100644--- a/crates/pa-tui/src/factory_view/diagram.rs+++ b/crates/pa-tui/src/factory_view/diagram.rs@@ -158,6 +158,16 @@ impl FactoryEdge {}}+/// One instance row of a node: its status and the child it spawned+/// (`child`, the `rlm_child_id`; a retry overwrites it in place, so the+/// row always names its latest attempt). The child id is an identity,+/// never painted, so it stays raw like the run id.+#[derive(Debug, Clone, PartialEq)]+pub struct FactoryInstance {+ pub status: String,+ pub child: Option<String>,+}+/// One live node's runtime state (the `status()` node shape, compact/// lane). `running`/`queued` are the kernel's per-stage agent counts —/// how many agents run at the stage and how many queue behind them —@@ -170,7 +180,7 @@ pub struct FactoryNodeState {pub entries_used: u64,pub max_entries: u64,pub entries: Vec<String>,- pub instances: Vec<String>,+ pub instances: Vec<FactoryInstance>,pub error: Option<String>,pub running: Option<u64>,pub queued: Option<u64>,@@ -203,8 +213,16 @@ impl FactoryNodeState {.map(|instances| {instances.iter()- .filter_map(|instance| instance.get("status").and_then(Value::as_str))- .map(scrubbed)+ .filter_map(|instance| {+ Some(FactoryInstance {+ status: scrubbed(instance.get("status")?.as_str()?),+ child: instance+ .get("child")+ .and_then(Value::as_str)+ .filter(|child| !child.is_empty())+ .map(str::to_string),+ })+ }).collect()}).unwrap_or_default(),@@ -222,10 +240,26 @@ impl FactoryNodeState {self.status,self.entries_used,self.max_entries,- self.instances.join(",")+ self.instances+ .iter()+ .map(|instance| instance.status.as_str())+ .collect::<Vec<_>>()+ .join(","))}+ /// The state's latest spawned child: the last instance row (report+ /// order — entry order, then instance order) that carries a child.+ /// The one predicate behind a state row's selectability, its muted+ /// paint, and its open/stop target.+ #[must_use]+ pub fn latest_child(&self) -> Option<(&str, &FactoryInstance)> {+ self.instances+ .iter()+ .rev()+ .find_map(|instance| Some((instance.child.as_deref()?, instance)))+ }+/// Whether the node is in flight: an entry pending (awaiting its/// inputs) or running, an instance still running or queued, or — for/// snapshots without entry rows — the derived `running` status. The@@ -266,7 +300,10 @@ impl FactoryNodeState {}fn instance_count(&self, status: &str) -> u64 {- self.instances.iter().filter(|row| *row == status).count() as u64+ self.instances+ .iter()+ .filter(|row| row.status == status)+ .count() as u64}/// The stage's occupancy label — `3 run · 2 queued` — when agentsdiff --git a/crates/pa-tui/src/factory_view/tests.rs b/crates/pa-tui/src/factory_view/tests.rsindex 12a4bfa4bf..8d3611f63e 100644--- a/crates/pa-tui/src/factory_view/tests.rs+++ b/crates/pa-tui/src/factory_view/tests.rs@@ -1,7 +1,7 @@//! The `/factory` view's battery: the snapshot parsing, the diagram's//! highlighted rendering (asserted per span, so removing the active-node-//! marking fails the test — the mutation check), the picker keyset (the-//! arrows + Enter + Esc loop and the in-page action rows), the repaint+//! marking fails the test — the mutation check), the key loop (the row+//! walk, the session open, and the two-press stop), the repaint//! hysteresis, and the scale battery (the complex machine and the//! fifteen-run world: selection stability, the dock's liveness count,//! the render window, the refresh markers, and the churn discipline).@@ -653,143 +653,237 @@ fn the_empty_state_names_the_surface() {joined.contains("move"),"the hint names the arrows: {joined}");- assert!(joined.contains("actions"), "{joined}");- assert!(joined.contains("close"), "{joined}");+ assert!(joined.contains("open"), "{joined}");+ assert!(joined.contains("back"), "{joined}");}-/// The picker keyset (arrows + Enter + Esc — the heartbeats/bash pages'-/// family): the arrows move the run selection, Enter opens the selected-/// run's in-page action rows (stop/resume, the offered set derived from-/// the run's state) and runs the tracked action, Esc backs out of the-/// action rows before it closes the page.+/// The selected row as `(run id, state id)`.+fn selected_row(view: &FactoryView) -> (String, Option<String>) {+ let row = view.selected.clone().expect("a row is selected");+ (row.run_id, row.state_id)+}++/// Select a run's header directly (the many-run battery targets a run+/// without walking every row above it).+fn select_run(view: &mut FactoryView, run_id: &str) {+ view.selected = Some(FactoryRow::header(run_id));+}++fn row(run_id: &str, state_id: Option<&str>) -> (String, Option<String>) {+ (run_id.to_string(), state_id.map(str::to_string))+}++/// The arrows walk the run headers and the states that ran a session,+/// flattened across panels (newest run first); a state without a child —+/// never entered, or entered with no child spawned yet — is skipped and+/// paints dim, never accent. Both ends clamp.#[test]-fn the_key_loop_resolves_the_orchestration_actions() {- let runs = parse_factory_runs(&two_run_response());- let mut view = FactoryView::new(runs, 40);- // The feed: the newest run is selected, the arrows walk the feed —- // down reads older, up reads newer, and both ends clamp.- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-def67890".to_string())- );- let _ = view.handle_key("down", &kb());- assert_eq!(view.selected, 1);+fn the_arrows_walk_headers_and_session_states_across_panels() {+ let mut response = two_run_response();+ // The newest run's `fixing` entered but spawned no child yet.+ response["runs"][1]["nodes"][2]["status"] = json!("running");+ response["runs"][1]["nodes"][2]["entries"] =+ json!([ { "index": 0, "status": "running", "error": null } ]);+ let mut view = FactoryView::new(parse_factory_runs(&response), 80);+ let expected = [+ row("run-def67890", None),+ row("run-def67890", Some("collect")),+ row("run-def67890", Some("reviewing")),+ row("run-abc12345", None),+ row("run-abc12345", Some("collect")),+ row("run-abc12345", Some("reviewing")),+ ];+ assert_eq!(selected_row(&view), expected[0]);+ for want in &expected[1..] {+ let _ = view.handle_key("down", &kb());+ assert_eq!(&selected_row(&view), want);+ }let _ = view.handle_key("down", &kb());- assert_eq!(view.selected, 1, "down clamps at the oldest run");- let _ = view.handle_key("up", &kb());- assert_eq!(view.selected, 0);- let _ = view.handle_key("up", &kb());- assert_eq!(view.selected, 0, "up clamps at the newest run");- // The letters are not page keys (the keyset is arrows + Enter + Esc):- // j/k/s/r move nothing and act on nothing (the mutation check: a- // restored j/k arm moves the selection and fails this pin).- for letter in ["j", "k", "s", "r", "m"] {- assert_eq!(view.handle_key(letter, &kb()), FactoryViewAction::None);- assert_eq!(view.selected, 0, "{letter} moved nothing");+ assert_eq!(selected_row(&view), expected[5], "down clamps");+ for want in expected[..5].iter().rev() {+ let _ = view.handle_key("up", &kb());+ assert_eq!(&selected_row(&view), want);}- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-def67890".to_string()),- "no letter changed the focused run"+ let _ = view.handle_key("up", &kb());+ assert_eq!(selected_row(&view), expected[0], "up clamps");+ // The selected row carries the marker; the session-less state paints+ // dim even though it is active.+ let _ = view.handle_key("down", &kb());+ let text = frame_text(&mut view);+ assert!(+ text.iter().any(|row| row.starts_with(" ▸ ✓ collect")),+ "{text:?}");- // Enter opens the selected run's action rows: a running run offers- // exactly stop, the block names the run, and the hint flips to the- // action grammar.- assert_eq!(view.handle_key("enter", &kb()), FactoryViewAction::None);- let rows = frame_text(&mut view);- let joined = rows.join("\n");- assert!(joined.contains("actions: second-run"), "{joined}");- assert!(joined.contains("▸ Stop the run"), "{joined}");- assert!(joined.contains("action · Enter run · Esc back"), "{joined}");- // Enter runs the tracked action: the stop rides the SELECTED run.- assert_eq!(- view.handle_key("enter", &kb()),- FactoryViewAction::Stop {- run_id: "run-def67890".to_string()+ let spans = frame_spans(&mut view);+ let paints = |color: ThemeColor| {+ spans+ .iter()+ .flatten()+ .any(|span| span.content == "fixing" && span.style == theme().fg_style(color))+ };+ assert!(paints(ThemeColor::Dim) && !paints(ThemeColor::Accent));+}++/// Enter and → open the selected state's LATEST child (a retry overwrites+/// the instance's child; a later entry's child wins); on a header they+/// open nothing.+#[test]+fn enter_and_right_open_the_latest_child_and_headers_open_nothing() {+ let mut snapshot = scripted_snapshot();+ snapshot["nodes"][1]["instances"] = json!([+ { "index": 0, "entry": 0, "status": "done", "attempt": 2, "child": "child-2-retry", "durationMs": 5, "error": null },+ { "index": 0, "entry": 1, "status": "running", "attempt": 1, "child": "child-5", "durationMs": 0, "error": null },+ { "index": 1, "entry": 1, "status": "pending", "attempt": 0, "child": null, "durationMs": null, "error": null }+ ]);+ let mut view = FactoryView::new(parse_factory_runs(&runs_response(&snapshot)), 40);+ for key in ["enter", "right"] {+ assert_eq!(view.handle_key(key, &kb()), FactoryViewAction::None);+ }+ let _ = view.handle_key("down", &kb());+ let open = |child: &str| FactoryViewAction::Open {+ child_id: child.to_string(),+ };+ assert_eq!(view.handle_key("enter", &kb()), open("child-1"));+ let _ = view.handle_key("down", &kb());+ assert_eq!(view.handle_key("enter", &kb()), open("child-5"));+ assert_eq!(view.handle_key("right", &kb()), open("child-5"));+}++/// The accident this page had: on a live run, repeated navigation —+/// →→, Enter Enter, on the header or a running state — never stops or+/// resumes anything (paused, so both run actions are on offer).+#[test]+fn navigation_never_stops_or_resumes_a_run() {+ let mut runs = parse_factory_runs(&runs_response(&scripted_snapshot()));+ runs[0].state = Some("paused".to_string());+ let mut view = FactoryView::new(runs, 40);+ for _ in 0..3 {+ for key in ["right", "right", "enter", "enter"] {+ let action = view.handle_key(key, &kb());+ assert!(+ matches!(+ action,+ FactoryViewAction::None | FactoryViewAction::Open { .. }+ ),+ "{key} on {:?} acted: {action:?}",+ selected_row(&view)+ );}- );- // Right mirrors Enter and Left mirrors Esc: Right opens the action- // rows, Left backs out to the feed, then Left closes the page.- assert_eq!(view.handle_key("right", &kb()), FactoryViewAction::None);+ let _ = view.handle_key("down", &kb());+ }+}++/// The stop's two-press grammar (the agents view's `app.agents.delete`):+/// the first press arms the selected row and the footer asks to confirm,+/// a second press on the same row stops it — the run on a header, the+/// running child on a state — and any other key between the presses+/// disarms and does nothing else. A state whose child settled offers no+/// stop.+#[test]+fn the_stop_key_arms_then_stops_the_selected_row() {+ let mut view = FactoryView::new(parse_factory_runs(&runs_response(&scripted_snapshot())), 40);+ let hint = |view: &mut FactoryView| frame_text(view).last().cloned().unwrap_or_default();assert!(- frame_text(&mut view)- .join("\n")- .contains("actions: second-run"),- "right did not open the action rows"+ hint(&mut view).contains("stop"),+ "a live header offers stop");- assert_eq!(view.handle_key("left", &kb()), FactoryViewAction::None);+ assert_eq!(view.handle_key("ctrl+x", &kb()), FactoryViewAction::None);assert!(- !frame_text(&mut view)- .join("\n")- .contains("actions: second-run"),- "left did not back out of the action rows"+ hint(&mut view).contains("stop review-loop? Ctrl+X again to confirm"),+ "{}",+ hint(&mut view));- assert_eq!(view.handle_key("left", &kb()), FactoryViewAction::Close);- // A rebound horizontal arrow keeps its configured action: with Left- // bound to tui.select.up, Left walks the feed instead of closing- // (the fallback runs only when no configured binding matches).- let rebound: KeybindingsManager = KeybindingsManager::with_user_bindings(- serde_json::from_value(json!({"tui.select.up": ["left"]})).unwrap(),+ assert_eq!(+ view.handle_key("ctrl+x", &kb()),+ FactoryViewAction::Stop {+ run_id: "run-abc12345".to_string()+ });- let _ = view.handle_key("down", &rebound);- assert_eq!(view.selected, 1);- assert_eq!(view.handle_key("left", &rebound), FactoryViewAction::None);- assert_eq!(view.selected, 0, "rebound Left walks the feed, not Close");+ // Any other key between the presses disarms and does nothing else:+ // the arrow does not move, Esc does not close.+ for key in ["down", "escape", "enter"] {+ let _ = view.handle_key("ctrl+x", &kb());+ assert_eq!(view.handle_key(key, &kb()), FactoryViewAction::None);+ assert_eq!(selected_row(&view), row("run-abc12345", None));+ assert_eq!(+ view.handle_key("ctrl+x", &kb()),+ FactoryViewAction::None,+ "{key} disarmed: the next press re-arms"+ );+ let _ = view.handle_key("left", &kb());+ }+ // A settled child offers no stop; the running child stops.let _ = view.handle_key("down", &kb());- // Esc backs out of the action rows to the feed, then closes.- let _ = view.handle_key("enter", &kb());- assert_eq!(view.handle_key("escape", &kb()), FactoryViewAction::None);- assert!(- frame_text(&mut view).join("\n").contains("Enter actions"),- "Esc returns the feed's hint"+ assert!(!hint(&mut view).contains("stop"), "{}", hint(&mut view));+ assert_eq!(view.handle_key("ctrl+x", &kb()), FactoryViewAction::None);+ assert_eq!(view.handle_key("ctrl+x", &kb()), FactoryViewAction::None);+ let _ = view.handle_key("down", &kb());+ let _ = view.handle_key("ctrl+x", &kb());+ assert!(hint(&mut view).contains("stop review-loop/reviewing?"));+ assert_eq!(+ view.handle_key("ctrl+x", &kb()),+ FactoryViewAction::StopChild {+ child_id: "child-2".to_string(),+ label: "review-loop/reviewing".to_string()+ });- // The real key id for the Escape key is "escape" (`key_event_to_id`)- // — the page must close on it (the mutation check: matching only- // "esc" strands the Escape key).+ // A retry that replaces the armed child disarms: the next press arms+ // the new child, never stops it unconfirmed.+ let _ = view.handle_key("ctrl+x", &kb());+ let mut retried = scripted_snapshot();+ retried["nodes"][1]["instances"][0]["child"] = json!("child-9");+ view.apply_runs(parse_factory_runs(&runs_response(&retried)));+ assert_eq!(view.handle_key("ctrl+x", &kb()), FactoryViewAction::None);assert_eq!(- view.handle_key("escape", &kb()),- FactoryViewAction::Close,- "the Escape key closes the page"- );- assert_eq!(view.handle_key("esc", &kb()), FactoryViewAction::Close);- assert_eq!(view.handle_key("ctrl+c", &kb()), FactoryViewAction::Close);- // A paused run offers the pause complement first — resume — then- // stop; the arrows walk the offered set, Enter runs the tracked- // one.+ view.handle_key("ctrl+x", &kb()),+ FactoryViewAction::StopChild {+ child_id: "child-9".to_string(),+ label: "review-loop/reviewing".to_string()+ }+ );+ // A fold that settles the armed child disarms it.+ let _ = view.handle_key("ctrl+x", &kb());+ let mut settled = scripted_snapshot();+ settled["nodes"][1]["instances"][0]["status"] = json!("done");+ view.apply_runs(parse_factory_runs(&runs_response(&settled)));+ assert!(!hint(&mut view).contains("again to confirm"));+ assert_eq!(view.handle_key("ctrl+x", &kb()), FactoryViewAction::None);+}++/// `r` resumes the selected row's run only while it is paused (no+/// confirmation); the footer offers it exactly then.+#[test]+fn r_resumes_only_a_paused_run() {+ let mut view = FactoryView::new(parse_factory_runs(&runs_response(&scripted_snapshot())), 40);+ assert_eq!(view.handle_key("r", &kb()), FactoryViewAction::None);+ assert!(!frame_text(&mut view).join("\n").contains("r resume"));let mut paused = parse_factory_runs(&runs_response(&scripted_snapshot()));paused[0].state = Some("paused".to_string());let mut view = FactoryView::new(paused, 40);- let _ = view.handle_key("enter", &kb());- let rows = frame_text(&mut view);- let joined = rows.join("\n");- assert!(joined.contains("▸ Resume the run"), "{joined}");- assert!(joined.contains("Stop the run"), "{joined}");- // The tracked action is resume (the complement first); walking down- // lands on stop, and Enter runs stop.- assert_eq!(- view.handle_key("enter", &kb()),- FactoryViewAction::Resume {- run_id: "run-abc12345".to_string()- }- );- let _ = view.handle_key("enter", &kb());let _ = view.handle_key("down", &kb());+ assert!(frame_text(&mut view).join("\n").contains("r resume"));assert_eq!(- view.handle_key("enter", &kb()),- FactoryViewAction::Stop {+ view.handle_key("r", &kb()),+ FactoryViewAction::Resume {run_id: "run-abc12345".to_string()});- // A fully terminal run offers nothing: Enter answers no rows.- let mut terminal = parse_factory_runs(&runs_response(&scripted_snapshot()));- terminal[0].state = Some("done".to_string());- terminal[0].usage.as_mut().unwrap().running = 0;- let mut view = FactoryView::new(terminal, 40);- assert_eq!(view.handle_key("enter", &kb()), FactoryViewAction::None);- assert!(- !frame_text(&mut view).join("\n").contains("actions: "),- "a terminal run opens no action rows"+}++/// ← and Esc (the real `escape` key id), `esc`, and ctrl+c close the+/// page; a rebound Left keeps its configured action.+#[test]+fn left_and_escape_close_the_page() {+ let mut view = FactoryView::new(parse_factory_runs(&two_run_response()), 40);+ for key in ["left", "escape", "esc", "ctrl+c"] {+ assert_eq!(view.handle_key(key, &kb()), FactoryViewAction::Close);+ }+ let rebound: KeybindingsManager = KeybindingsManager::with_user_bindings(+ serde_json::from_value(json!({"tui.select.up": ["left"]})).unwrap(),);+ let _ = view.handle_key("down", &rebound);+ assert_eq!(view.handle_key("left", &rebound), FactoryViewAction::None);+ assert_eq!(selected_row(&view), row("run-def67890", None));}/// The repaint hysteresis: an unchanged snapshot applies without a@@ -895,53 +989,40 @@ fn the_runs_list_reads_newest_first_and_opens_on_the_newest_run() {);}-/// Two runs: the selection moves down the feed, and a refresh keeps-/// the selection on the SAME RUN, never the same index — a newer run-/// folding in on top moves the selected run down the list without-/// stealing the selection, and a run that left the batch returns the-/// selection to the feed's head (the mutation check: index-tracking-/// jumps to the new newest run and fails the fold assertions).+/// A refresh keeps the selection on the SAME ROW, never the same index:+/// a newer run folding in on top shifts every index without stealing the+/// selection, a state that lost its session falls back to its run's+/// header, and a run that left the batch hands the selection to the+/// first row (the newest run's header).#[test]-fn multiple_runs_keep_the_selection_on_the_same_run() {- let runs = parse_factory_runs(&two_run_response());- let mut view = FactoryView::new(runs, 40);- // The page opens on the newest run.- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-def67890".to_string())- );- // The down arrow moves the selection down the feed, to the older run.- let _ = view.handle_key("down", &kb());- assert_eq!(view.selected, 1);+fn a_fold_keeps_the_selection_on_the_same_row() {+ let mut view = FactoryView::new(parse_factory_runs(&two_run_response()), 40);+ for _ in 0..5 {+ let _ = view.handle_key("down", &kb());+ }+ assert_eq!(selected_row(&view), row("run-abc12345", Some("reviewing")));+ view.apply_runs(parse_factory_runs(&three_run_response()));assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-abc12345".to_string())+ selected_row(&view),+ row("run-abc12345", Some("reviewing")),+ "a newer run on top never steals the selection");- // An unchanged refresh keeps the selection on the same run id.- view.apply_runs(parse_factory_runs(&two_run_response()));+ let mut without_session = three_run_response();+ without_session["runs"][0]["nodes"][1]["instances"] = json!([]);+ view.apply_runs(parse_factory_runs(&without_session));assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-abc12345".to_string())+ selected_row(&view),+ row("run-abc12345", None),+ "a vanished state falls back to its run's header");- // A run created after both folds in on top: the selected run moves- // down the list (index 1 becomes index 2) and the selection stays- // on the same run — the same index would be the new newest run.- view.apply_runs(parse_factory_runs(&three_run_response()));- assert_eq!(view.selected, 2);- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-abc12345".to_string()),- "the selection stays on the same run, not the same index"- );- // The selected run leaves the batch (the wire cap's oldest-end trim- // dropped it): the selection returns to the feed's head, the newest- // run.view.apply_runs(parse_factory_runs(&later_pair_response()));assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-ghi13579".to_string()),- "a run that left the batch returns the selection to the head"+ selected_row(&view),+ row("run-ghi13579", None),+ "a run that left the batch hands the selection to the first row");+ view.apply_runs(Vec::new());+ assert!(view.selected.is_none(), "no runs, nothing selected");}/// The degenerate budget (a sub-chrome viewport on a short terminal):@@ -955,7 +1036,7 @@ fn the_degenerate_budget_still_honors_the_viewport() {let rows = frame_text(&mut one_row);assert_eq!(rows.len(), 1, "a 1-row viewport renders exactly one row");assert!(- rows[0].contains("close"),+ rows[0].contains("back"),"the tail-clip keeps the hint: {:?}",rows[0]);@@ -963,7 +1044,7 @@ fn the_degenerate_budget_still_honors_the_viewport() {let rows = frame_text(&mut two_rows);assert_eq!(rows.len(), 2, "a 2-row viewport renders exactly two rows");assert!(- rows[1].contains("close"),+ rows[1].contains("back"),"the hint is the last row: {:?}",rows[1]);@@ -990,7 +1071,7 @@ fn the_budget_window_keeps_the_hint_and_the_selected_panel() {);// The key hint stays painted (the trailing chrome never truncates).assert!(- joined.contains("Enter actions"),+ joined.contains("Enter/→ open"),"the key hint stays painted: {joined}");// The default selection is the newest run: its header stays visible@@ -1008,7 +1089,7 @@ fn the_budget_window_keeps_the_hint_and_the_selected_panel() {// follows the selection, keeps the hint, and drops the newest// panel instead.let mut selected_older = FactoryView::new(parse_factory_runs(&two_run_response()), 8);- let _ = selected_older.handle_key("down", &kb());+ select_run(&mut selected_older, "run-abc12345");let rows = frame_text(&mut selected_older);let joined = rows.join("\n");assert!(@@ -1016,7 +1097,7 @@ fn the_budget_window_keeps_the_hint_and_the_selected_panel() {"the view stays inside the budget: {joined}");assert!(- joined.contains("Enter actions"),+ joined.contains("Enter/→ open"),"the key hint stays painted: {joined}");assert!(@@ -1370,13 +1451,6 @@ fn world_w07_stopping() -> serde_json::Value {reply}-/// The world with run w09 resumed (it was paused).-fn world_w09_resumed() -> serde_json::Value {- let mut reply = world_response();- reply["runs"].as_array_mut().expect("runs")[9]["state"] = json!("running");- reply-}-/// A burst of five brand-new runs folded in on top of the world (the/// newest runs render first, the feed grows by five in one tick).fn world_with_burst() -> serde_json::Value {@@ -1569,26 +1643,18 @@ fn the_dock_count_reads_one_liveness_rule_across_many_runs() {#[test]fn selection_stays_on_the_same_run_across_a_many_run_churn() {let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);- // The head is the newest run; seven downs walk to run #7 among- // fifteen.+ // The head is the newest run.assert_eq!(view.selected_run().map(|run| run.run_id.clone()),Some("run-w14".to_string()),"the page opens on the feed's head");- for _ in 0..7 {- let _ = view.handle_key("down", &kb());- }- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-w07".to_string())- );+ select_run(&mut view, "run-w07");// Fold two: three new runs folded in on top, the two oldest left// the batch, the done-with-residents pair settled. The selection// stays on run w07 — at a NEW index (the same index would name a// different run).view.apply_runs(parse_factory_runs(&world_fold_two()));- assert_eq!(view.selected, 10, "the fold moved the run down the feed");assert_eq!(view.selected_run().map(|run| run.run_id.clone()),Some("run-w07".to_string()),@@ -1620,7 +1686,7 @@ fn fifteen_panels_window_to_the_focus_on_a_small_viewport() {rows.len());assert!(- rows.last().is_some_and(|row| row.contains("close")),+ rows.last().is_some_and(|row| row.contains("back")),"the hint paints as the chrome's last row: {:?}",rows.last());@@ -1631,11 +1697,9 @@ fn fifteen_panels_window_to_the_focus_on_a_small_viewport() {"the newest panel renders first: {}",rows.join("\n"));- // Seven downs: the window slides to the focused run — its header- // paints, the head panel drops instead, and the hint survives.- for _ in 0..7 {- let _ = view.handle_key("down", &kb());- }+ // Focus run #7: the window slides to it — its header paints, the+ // head panel drops instead, and the hint survives.+ select_run(&mut view, "run-w07");let rows = frame_text(&mut view);let joined = rows.join("\n");assert!(rows.len() <= 26, "the windowed frame stays in budget");@@ -1648,18 +1712,33 @@ fn fifteen_panels_window_to_the_focus_on_a_small_viewport() {"the head panel dropped instead of the chrome: {joined}");assert!(- rows.last().is_some_and(|row| row.contains("close")),+ rows.last().is_some_and(|row| row.contains("back")),"the hint still paints after the slide");+ // A selected state deep inside a tall panel: the window slides to+ // the row itself, so the open/stop target stays visible.+ let mut short = FactoryView::new(parse_factory_runs(&world_response()), 10);+ short.selected = Some(FactoryRow {+ run_id: "run-w07".to_string(),+ state_id: Some("watchdog".to_string()),+ });+ let rows = frame_text(&mut short);+ assert!(rows.len() <= 10);+ assert!(+ rows.iter()+ .any(|row| row.contains("▸") && row.contains("watchdog")),+ "the selected state paints: {}",+ rows.join("\n")+ );// Degenerate budgets honor the viewport exactly.let mut one_row = FactoryView::new(parse_factory_runs(&world_response()), 1);let rows = frame_text(&mut one_row);assert_eq!(rows.len(), 1);- assert!(rows[0].contains("close"), "{:?}", rows[0]);+ assert!(rows[0].contains("back"), "{:?}", rows[0]);let mut three_rows = FactoryView::new(parse_factory_runs(&world_response()), 3);let rows = frame_text(&mut three_rows);assert_eq!(rows.len(), 3);- assert!(rows[2].contains("close"), "{:?}", rows[2]);+ assert!(rows[2].contains("back"), "{:?}", rows[2]);}/// The refresh tick across the fifteen-run world: the changed marker@@ -1768,48 +1847,25 @@ fn the_refresh_tick_lights_only_notice_worthy_changes_across_many_runs() {);}-/// Orchestration at scale: the Enter path targets THE FOCUSED run among+/// Orchestration at scale: the stop targets THE FOCUSED run among/// fifteen — no cross-run leakage — and the stop's immediate refresh/// updates its panel to stopping without losing the selection. The-/// offered set reads the run's state: a paused run offers the resume-/// complement first, a done-with-residents run keeps its stop (the-/// residents teardown), a terminal run offers nothing. The open action-/// rows stay honest across a fold: a state change under them clamps-/// the tracked action to what the run still offers, and a run that-/// leaves the batch closes them (the mutation check: confirming a-/// blindly tracked action would fire a stale resume here).+/// offered actions read the run's state: a paused run resumes, a+/// done-with-residents run keeps its stop (the residents teardown), a+/// terminal run offers nothing, and a fold that ends the armed run's+/// stop disarms it (the mutation check: a blindly kept arm would fire a+/// stale stop here).#[test]fn orchestration_targets_the_focused_run_among_many() {let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);- // Walk to run #7 and stop it through the action rows.- for _ in 0..7 {- let _ = view.handle_key("down", &kb());- }- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-w07".to_string())- );- let _ = view.handle_key("enter", &kb());- let rows = frame_text(&mut view);- assert!(- rows.join("\n").contains("actions: world-run-7"),- "the action rows name the focused run"- );- assert_eq!(- view.handle_key("enter", &kb()),- FactoryViewAction::Stop {- run_id: "run-w07".to_string()- },- "the stop rides the focused run, none other"- );- // The stop landed: the immediate refresh folds the stopping state- // — the panel updates, the selection never moves.+ let stop = |run_id: &str| FactoryViewAction::Stop {+ run_id: run_id.to_string(),+ };+ select_run(&mut view, "run-w07");+ let _ = view.handle_key("ctrl+x", &kb());+ assert_eq!(view.handle_key("ctrl+x", &kb()), stop("run-w07"));view.apply_runs(parse_factory_runs(&world_w07_stopping()));- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-w07".to_string()),- "stopping a run never loses the selection"- );+ assert_eq!(selected_row(&view), row("run-w07", None));let rows = frame_text(&mut view);assert!(panel_rows(&rows, "factory: world-run-7")@@ -1817,96 +1873,25 @@ fn orchestration_targets_the_focused_run_among_many() {.any(|row| row.contains("— stopping")),"the stopped run's panel reads stopping");- // A paused run offers the resume complement first: walk to w09- // (two up from w07) and resume it.- for _ in 0..2 {- let _ = view.handle_key("up", &kb());- }+ // A paused run resumes.+ select_run(&mut view, "run-w09");assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-w09".to_string())- );- let _ = view.handle_key("enter", &kb());- let rows = frame_text(&mut view);- let joined = rows.join("\n");- assert!(joined.contains("actions: world-run-9"), "{joined}");- assert!(joined.contains("▸ Resume the run"), "{joined}");- assert!(joined.contains("Stop the run"), "{joined}");- assert_eq!(- view.handle_key("enter", &kb()),+ view.handle_key("r", &kb()),FactoryViewAction::Resume {run_id: "run-w09".to_string()});- // The action rows stay honest across a fold: reopen w09's rows- // (paused, resume tracked), fold the world where w09 already- // resumed — resume is no longer offered, the tracked action clamps- // to stop, and Enter runs stop, never a stale resume.- let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);- for _ in 0..5 {- let _ = view.handle_key("down", &kb());- }- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-w09".to_string())- );- let _ = view.handle_key("enter", &kb());- view.apply_runs(parse_factory_runs(&world_w09_resumed()));- let rows = frame_text(&mut view);- let joined = rows.join("\n");- assert!(- joined.contains("actions: world-run-9"),- "the rows stay open on the run: {joined}"- );- assert!(- !joined.contains("Resume the run"),- "the clamped rows offer only what the run still offers: {joined}"- );- assert!(joined.contains("▸ Stop the run"), "{joined}");- assert_eq!(- view.handle_key("enter", &kb()),- FactoryViewAction::Stop {- run_id: "run-w09".to_string()- },- "the confirmation runs the offered action, never a stale resume"- );- // A done-with-residents run keeps its stop (the residents- // teardown): w11 sits two up from w09.- let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);- for _ in 0..3 {- let _ = view.handle_key("down", &kb());- }- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-w11".to_string())- );- let _ = view.handle_key("enter", &kb());- let rows = frame_text(&mut view);- let joined = rows.join("\n");- assert!(joined.contains("actions: world-run-11"), "{joined}");- assert!(- !joined.contains("Resume the run"),- "a done run never offers resume: {joined}"- );- assert!(joined.contains("▸ Stop the run"), "{joined}");- assert_eq!(- view.handle_key("enter", &kb()),- FactoryViewAction::Stop {- run_id: "run-w11".to_string()- }- );+ // A done-with-residents run keeps its stop; the fold that stops its+ // residents ends the offer and disarms the armed stop.+ select_run(&mut view, "run-w11");+ let _ = view.handle_key("ctrl+x", &kb());+ view.apply_runs(parse_factory_runs(&world_fold_two()));+ assert_eq!(view.handle_key("ctrl+x", &kb()), FactoryViewAction::None);+ assert!(view.armed.is_none(), "a run without a stop never arms");// A terminal run offers nothing.- let _ = view.handle_key("up", &kb());- let _ = view.handle_key("up", &kb());- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-w13".to_string())- );- assert_eq!(view.handle_key("enter", &kb()), FactoryViewAction::None);- assert!(- !frame_text(&mut view).join("\n").contains("actions: "),- "a terminal run opens no action rows"- );+ select_run(&mut view, "run-w13");+ let _ = view.handle_key("ctrl+x", &kb());+ assert_eq!(view.handle_key("ctrl+x", &kb()), FactoryViewAction::None);}/// Rapid-change churn (the serialized fold discipline at scale): one@@ -1920,13 +1905,7 @@ fn orchestration_targets_the_focused_run_among_many() {#[test]fn rapid_churn_keeps_the_folded_page_coherent() {let mut view = FactoryView::new(parse_factory_runs(&world_response()), 400);- for _ in 0..7 {- let _ = view.handle_key("down", &kb());- }- assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-w07".to_string())- );+ select_run(&mut view, "run-w07");// The busy tick: a five-run burst folds in on top while four runs// change shape underneath.assert!(view.apply_runs(parse_factory_runs(&world_churn_tick())));@@ -1935,7 +1914,6 @@ fn rapid_churn_keeps_the_folded_page_coherent() {Some("run-w07".to_string()),"the selection tracks the same run through the burst");- assert_eq!(view.selected, 12, "five new runs folded in on top");// Exactly the four changed runs light the marker — the burst's new// runs paint none, the untouched runs none.let rows = frame_text(&mut view);@@ -1969,7 +1947,7 @@ fn rapid_churn_keeps_the_folded_page_coherent() {joined.contains("▸ factory: world-run-7 — running"),"{joined}");- assert!(joined.contains("Enter actions"), "{joined}");+ assert!(joined.contains("Enter/→ open"), "{joined}");// The focused run vanishes mid-orchestration: the selection hands// back to the head, and the very next keypress resolves against// the folded batch — never a stale index.@@ -1984,15 +1962,9 @@ fn rapid_churn_keeps_the_folded_page_coherent() {Some("run-w19".to_string()),"the vanished run hands the selection back to the head");- let _ = view.handle_key("enter", &kb());- assert!(- frame_text(&mut view)- .join("\n")- .contains("actions: world-run-19"),- "the keypress after the fold opens the head's rows"- );+ let _ = view.handle_key("ctrl+x", &kb());assert_eq!(- view.handle_key("enter", &kb()),+ view.handle_key("ctrl+x", &kb()),FactoryViewAction::Stop {run_id: "run-w19".to_string()}@@ -2005,8 +1977,8 @@ fn rapid_churn_keeps_the_folded_page_coherent() {let _ = view.apply_runs(parse_factory_runs(&world_churn_tick()));}assert_eq!(- view.selected_run().map(|run| run.run_id.clone()),- Some("run-w16".to_string()),+ selected_row(&view),+ row("run-w19", Some("watchdog")),"every keypress resolved against the folded batch");}diff --git a/crates/pa-tui/src/interactive.rs b/crates/pa-tui/src/interactive.rsindex b6b97e0a41..367ab00ae4 100644--- a/crates/pa-tui/src/interactive.rs+++ b/crates/pa-tui/src/interactive.rs@@ -50,7 +50,7 @@ use reconnect::{DAEMON_SHUTDOWN_RECONNECT_WINDOW, SHUTDOWN_RECONNECT_RETRY};mod run;-pub use run::{run_interactive, run_interactive_agents_view_open};+pub use run::{run_interactive, run_interactive_agents_view_open, run_interactive_origin_open};use crossterm::event::KeyEvent;use crossterm::terminal;@@ -78,15 +78,43 @@ pub enum SessionSelection {Resume(PathBuf),}+impl SessionSelection {+ /// How a roster summary opens: attach its live runtime+ /// (`activeSessionId`), else resume its saved file (`sessionFile`);+ /// `None` when it has neither.+ pub(crate) fn open_summary(summary: &Value) -> Option<Self> {+ let field = |name: &str| {+ summary+ .get(name)+ .and_then(Value::as_str)+ .filter(|text| !text.is_empty())+ };+ field("activeSessionId")+ .map(|active| Self::Attach(active.to_string()))+ .or_else(|| field("sessionFile").map(|file| Self::Resume(PathBuf::from(file))))+ }+}+/// The session panel an agents-view activity line mounts when its session opens; the panel's close/// returns to the agents view.#[derive(Debug, Clone, PartialEq, Eq)]pub enum SessionPanel {/// The Bash panel, on `shell_id`'s row when a persistent shell row opened it.- Shells {- shell_id: Option<String>,+ Shells { shell_id: Option<String> },+ /// The factory page, on `row` when a return from a state's session reopened it.+ FactoryRuns {+ row: Option<crate::factory_view::FactoryRow>,},- FactoryRuns,+}++/// The page that requested a session (the factory page's state open): leaving the requested+/// session reopens the requesting session with this panel mounted.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SelectionOrigin {+ pub panel: SessionPanel,+ /// The panel's close returns to the agents view (an agents-view activity line mounted it),+ /// not to the chat.+ pub closes_to_agents_view: bool,}/// Cap on the exit-path telemetry flush (the `tui exit` event's bound):@@ -461,6 +489,11 @@ pub struct InteractiveOutcome {pub agents_view_scope: Option<crate::agents_view::AgentsViewScope>,/// `/resume <selector>` requested this session next.pub selection_request: Option<SessionSelection>,+ /// The requested session's RLM depth, when the requester read it from the roster.+ pub selection_rlm_depth: Option<u32>,+ /// Where leaving the requested session returns (see [`SelectionOrigin`]); `None` returns to+ /// the agents view.+ pub selection_origin: Option<SelectionOrigin>,/// Texts copied out by finished mouse selections (headless runs have no terminal for/// OSC 52; the verifiers read these).pub copies: Vec<String>,diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rsindex 6769ced763..361d07ba7b 100644--- a/crates/pa-tui/src/interactive/run.rs+++ b/crates/pa-tui/src/interactive/run.rs@@ -5,7 +5,7 @@ use super::{apply_startup_chrome, arm_shutdown_recovery, check_tmux_keyboard_setup, mpsc,run_onboarding_phase, spawn_session_reader, AgentView, DaemonClient, Duration, ExitGuard,HeadlessSettle, Instant, InteractiveOptions, InteractiveOutcome, PaneDrive, ReconnectConnect,- ReconnectLoop, RecoveryKind, Renderer, Result, SessionPanel, SessionReconnect,+ ReconnectLoop, RecoveryKind, Renderer, Result, SelectionOrigin, SessionPanel, SessionReconnect,SessionSelection, SessionUi, TerminalHandoff, UiInput, UiMode, VecDeque,ACTIVITY_POLL_INTERVAL, SESSION_RECONNECT_ATTEMPT_TIMEOUT_S, TELEMETRY_EXIT_TIMEOUT_MS,};@@ -58,6 +58,9 @@ pub(crate) enum SessionOpenRoute {/// The agents view's open: waits through the update-restart window and retries; `panel`/// mounts on open and its close returns to the agents view.AgentsView { panel: Option<SessionPanel> },+ /// The return from a session the run requested: the requesting session reopens with its+ /// origin panel mounted; waits through the update restart like the agents view's open.+ Origin(SelectionOrigin),}/// Run one interactive session (the CLI open route).@@ -88,6 +91,20 @@ pub async fn run_interactive_agents_view_open(run_interactive_route(options, ui, SessionOpenRoute::AgentsView { panel }).await}+/// Reopen the session that requested the session just left (see [`SessionOpenRoute::Origin`]).+///+/// # Errors+///+/// Returns `Err` when the interactive surface fails or the open waits out the update-restart+/// window; the restore runs first whenever this run owned or adopted the terminal.+pub async fn run_interactive_origin_open(+ options: InteractiveOptions,+ ui: UiMode,+ origin: SelectionOrigin,+) -> Result<InteractiveOutcome> {+ run_interactive_route(options, ui, SessionOpenRoute::Origin(origin)).await+}+async fn run_interactive_route(options: InteractiveOptions,ui: UiMode,@@ -313,7 +330,7 @@ async fn run_interactive_surface(let factory_tx = factory_tx.clone();let commands_tx = commands_tx.clone();let page_tx = page_tx.clone();- let waits_through_update_restart = matches!(route, SessionOpenRoute::AgentsView { .. });+ let waits_through_update_restart = !matches!(route, SessionOpenRoute::Cli);tokio::spawn(async move {crate::update_restart_wait::wait_through_update_restart(waits_through_update_restart,@@ -714,8 +731,14 @@ async fn run_interactive_surface(// previous chat view of this session left via the agents view or a// switch) returns to the editor when its chat reopens.session.restore_prompt_stash_on_open(&mut view);- if let SessionOpenRoute::AgentsView { panel: Some(panel) } = route {- session.open_agents_view_panel(panel, &mut view);+ match route {+ SessionOpenRoute::AgentsView { panel: Some(panel) } => {+ session.open_agents_view_panel(panel, true, &mut view);+ }+ SessionOpenRoute::Origin(origin) => {+ session.open_agents_view_panel(origin.panel, origin.closes_to_agents_view, &mut view);+ }+ SessionOpenRoute::AgentsView { panel: None } | SessionOpenRoute::Cli => {}}// Declared above the onboarding phase: the pane's drive marks it.let mut headless_done = false;@@ -753,6 +776,8 @@ async fn run_interactive_surface(agents_view_scope: None,return_to_agents_view: false,selection_request: None,+ selection_rlm_depth: None,+ selection_origin: None,copies: Vec::new(),opened_urls: Vec::new(),agents_view_notice: None,@@ -2118,6 +2143,8 @@ async fn run_interactive_surface(return_to_agents_view: preserve_alt_screen,agents_view_scope: session.scoped_agents_view.take(),selection_request: session.pending_selection,+ selection_rlm_depth: session.pending_selection_rlm_depth,+ selection_origin: session.pending_selection_origin,copies: std::mem::take(&mut session.copies),opened_urls: std::mem::take(&mut session.opened_urls),// The view's status line keeps the wait notice when the chat hands back.diff --git a/crates/pa-tui/src/session_ui.rs b/crates/pa-tui/src/session_ui.rsindex cf35c08f2b..45e77cb7f3 100644--- a/crates/pa-tui/src/session_ui.rs+++ b/crates/pa-tui/src/session_ui.rs@@ -326,6 +326,8 @@ pub(crate) struct SessionUi {/// subagent linkage; `None` for unpersisted sessions).session_file: Option<String>,pub(crate) pending_selection: Option<SessionSelection>,+ pub(crate) pending_selection_rlm_depth: Option<u32>,+ pub(crate) pending_selection_origin: Option<crate::interactive::SelectionOrigin>,/// Whether this run may hand the terminal back to the agents view:/// false only for `--no-session` runs.pub(crate) return_to_agents_view: bool,diff --git a/crates/pa-tui/src/session_ui/factory.rs b/crates/pa-tui/src/session_ui/factory.rsindex 92f391eae0..bef9c0a29c 100644--- a/crates/pa-tui/src/session_ui/factory.rs+++ b/crates/pa-tui/src/session_ui/factory.rs@@ -16,7 +16,9 @@ use crate::factory_view::{factory_reply_lists_runs, live_run_count, parse_factory_runs, FactoryView, FactoryViewAction,FACTORY_WATCH_TICK_MS,};+use crate::interactive::{SelectionOrigin, SessionPanel, SessionSelection};use crate::session_ui::{picker_viewport_rows, UI_REQUEST_TIMEOUT_MS};+use crate::subagents::{descendant_entries_with_depth, SessionIdentity};/// One background factory refresh's delivery: the session the request/// asked about (a late reply from a previous session never repaints the@@ -34,6 +36,11 @@ pub(crate) enum FactoryUpdate {epoch: u64,message: String,},+ ChildStop {+ session: String,+ message: String,+ tone: crate::agents_view::StatusTone,+ },}impl super::SessionUi {@@ -82,8 +89,9 @@ impl super::SessionUi {}/// One key press while the view is open: the view resolves the key;- /// stop/resume ride the daemon lane (bounded, with the outcome- /// reported), and Esc closes.+ /// Open hands off to the child's session, the run stop/resume ride the+ /// daemon lane and the child stop rides `cancel_rlm_child` (bounded,+ /// with the outcome reported), and Close closes.pub(crate) async fn handle_factory_view_key(&mut self,key: crossterm::event::KeyEvent,@@ -109,9 +117,13 @@ impl super::SessionUi {self.close_panel_to_agents_view();self.dirty = true;}+ Some(FactoryViewAction::Open { child_id }) => self.open_factory_child(view, &child_id),Some(FactoryViewAction::Stop { run_id }) => {self.factory_control(view, "stop", run_id).await?;}+ Some(FactoryViewAction::StopChild { child_id, label }) => {+ self.stop_factory_child(child_id, label);+ }Some(FactoryViewAction::Resume { run_id }) => {self.factory_control(view, "resume", run_id).await?;}@@ -119,6 +131,71 @@ impl super::SessionUi {Ok(())}+ /// Open a state's child session: hand off like `/resume <session>`+ /// (the selection plus the leave-now signal), with the child's depth+ /// and this page on its selected row as the origin leaving the child+ /// returns to. A child the roster cannot open yet reports on the+ /// page's error line.+ fn open_factory_child(&mut self, view: &mut AgentView, child_id: &str) {+ if let Some((selection, rlm_depth)) =+ factory_child_selection(&self.roster, &self.session_identity(), child_id)+ {+ self.pending_selection = Some(selection);+ self.pending_selection_rlm_depth = rlm_depth;+ self.pending_selection_origin = Some(SelectionOrigin {+ panel: SessionPanel::FactoryRuns {+ row: view+ .factory_view+ .as_ref()+ .and_then(FactoryView::selected_row)+ .cloned(),+ },+ closes_to_agents_view: self.panel_returns_to_agents_view,+ });+ self.exit_requested = true;+ } else if let Some(factory_view) = view.factory_view.as_mut() {+ factory_view.set_error(Some(format!(+ "cannot open {child_id}: no live runtime or saved session yet"+ )));+ }+ self.dirty = true;+ }++ /// Stop a state's running child through the agents view's stop+ /// (`cancel_rlm_child` on this session, its parent). The kernel+ /// treats the cancel as a failed attempt under the state's retries+ /// and failure policy. Success toasts; a no-effect or failed stop+ /// lands on the page's error line.+ fn stop_factory_child(&mut self, child_id: String, label: String) {+ let action = crate::agents_view::DeleteAction::StopSubagent {+ active_session_id: self.active_session_id.clone(),+ child_id,+ name: label,+ };+ let client = self.client.clone();+ let tx = self.factory_updates.clone();+ let session = self.active_session_id.clone();+ tokio::spawn(async move {+ let (message, tone) = match tokio::time::timeout(+ Duration::from_millis(UI_REQUEST_TIMEOUT_MS),+ crate::agents_view::execute_delete_action(&client, &action),+ )+ .await+ {+ Ok(result) => result,+ Err(_) => (+ "timed out waiting for the Prime Agent daemon response".to_string(),+ crate::agents_view::StatusTone::Error,+ ),+ };+ let _ = tx.send(FactoryUpdate::ChildStop {+ session,+ message,+ tone,+ });+ });+ }+/// One orchestration action (stop/resume): bounded request, the/// outcome reported on the view's error line, then an immediate/// refresh (the state change repaints without waiting a full cycle).@@ -336,9 +413,6 @@ impl super::SessionUi {/// reports it on its error line instead of painting a fake empty/// state (the emptiness the view shows is real).pub(crate) fn apply_factory_update(&mut self, update: FactoryUpdate, view: &mut AgentView) {- // The slot frees on every delivery path; a queued tick fires next.- self.factory_refresh_in_flight = false;- let queued = std::mem::take(&mut self.factory_refresh_queued);let (session, epoch, payload) = match update {FactoryUpdate::Snapshot {session,@@ -350,7 +424,33 @@ impl super::SessionUi {epoch,message,} => (session, epoch, Err(message)),+ FactoryUpdate::ChildStop {+ session,+ message,+ tone,+ } => {+ if session == self.active_session_id {+ match tone {+ crate::agents_view::StatusTone::Muted => self.toast(&message, view),+ crate::agents_view::StatusTone::Warning+ | crate::agents_view::StatusTone::Error => {+ if let Some(factory_view) = view.factory_view.as_mut() {+ factory_view.set_error(Some(message));+ } else {+ self.toast(&message, view);+ }+ }+ }+ self.dirty = true;+ self.spawn_factory_refresh();+ }+ return;+ }};+ // Only refresh deliveries release the refresh slot; child-stop+ // results are independent of any snapshot currently in flight.+ self.factory_refresh_in_flight = false;+ let queued = std::mem::take(&mut self.factory_refresh_queued);if session != self.active_session_id || epoch != self.factory_list_epoch {if queued {self.spawn_factory_refresh();@@ -400,11 +500,79 @@ impl super::SessionUi {}}+/// How a factory child opens: its roster row among this session's DIRECT+/// children (child ids are only unique among siblings), opened like an+/// agents-view row ([`SessionSelection::open_summary`], with the row's+/// `rlmDepth`).+fn factory_child_selection(+ roster: &[Value],+ session: &SessionIdentity,+ child_id: &str,+) -> Option<(SessionSelection, Option<u32>)> {+ let summary = descendant_entries_with_depth(roster, session)+ .into_iter()+ .filter(|(_, depth)| *depth == 1)+ .filter_map(|(entry, _)| entry.get("summary"))+ .find(|summary| summary.get("rlmChildId").and_then(Value::as_str) == Some(child_id))?;+ let rlm_depth = summary+ .get("rlmDepth")+ .and_then(Value::as_u64)+ .map(|depth| depth as u32);+ Some((SessionSelection::open_summary(summary)?, rlm_depth))+}+#[cfg(test)]mod fold_tests {use super::super::SessionUi;+ use super::{factory_child_selection, SessionIdentity, SessionSelection};use serde_json::json;+ /// A factory child opens through the roster: among this session's+ /// direct children, a live runtime attaches and a saved-only child+ /// resumes its file, each with its row's depth; a deeper descendant reusing the id (child ids+ /// are only unique among siblings) and an unknown id resolve nothing.+ #[test]+ fn a_factory_child_resolves_to_attach_or_resume_via_the_roster() {+ let child = |agent: &str, child_id: &str, parent: &str, extra: serde_json::Value| {+ let mut summary = json!({+ "runtimeKind": "subagent",+ "rlmChildId": child_id,+ "parentActiveSessionId": parent,+ });+ summary+ .as_object_mut()+ .unwrap()+ .extend(extra.as_object().unwrap().clone());+ json!({ "agentId": agent, "summary": summary })+ };+ let roster = vec![+ child(+ "a",+ "review-1",+ "root",+ json!({ "activeSessionId": "live-a", "rlmDepth": 1 }),+ ),+ child("b", "fix-1", "root", json!({ "sessionFile": "/s/b.jsonl" })),+ child(+ "c",+ "deep-1",+ "live-a",+ json!({ "activeSessionId": "live-c" }),+ ),+ ];+ let root = SessionIdentity::new(Some("root".to_string()), None, None);+ assert_eq!(+ factory_child_selection(&roster, &root, "review-1"),+ Some((SessionSelection::Attach("live-a".to_string()), Some(1)))+ );+ assert_eq!(+ factory_child_selection(&roster, &root, "fix-1"),+ Some((SessionSelection::Resume("/s/b.jsonl".into()), None))+ );+ assert_eq!(factory_child_selection(&roster, &root, "deep-1"), None);+ assert_eq!(factory_child_selection(&roster, &root, "missing"), None);+ }+/// The malformed fold keeps the dock's cached reply (the Cursor/// review finding): a bad batch never replaces the last good reply,/// so the dock's live-run count and a later remount keep reading itdiff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rsindex aabaf0e1fe..888144c8ac 100644--- a/crates/pa-tui/src/session_ui/lifecycle.rs+++ b/crates/pa-tui/src/session_ui/lifecycle.rs@@ -156,6 +156,8 @@ impl SessionUi {subagent_counts: crate::subagents::SubagentCounts::default(),session_file: None,pending_selection: None,+ pending_selection_rlm_depth: None,+ pending_selection_origin: None,return_to_agents_view: !options.no_session,panel_returns_to_agents_view: false,client_auth: options.client_auth.clone(),@@ -874,6 +876,7 @@ mod backfill_tests {));session.open_agents_view_panel(crate::interactive::SessionPanel::Shells { shell_id: None },+ true,&mut view,);session.rebuild_view(&mut view, &RebuildKind::Rebind);@@ -921,6 +924,7 @@ mod backfill_tests {crate::interactive::SessionPanel::Shells {shell_id: Some("s2".to_string()),},+ true,&mut view,);if !preloaded {diff --git a/crates/pa-tui/src/session_ui/panels.rs b/crates/pa-tui/src/session_ui/panels.rsindex 45696e2b43..a197d91542 100644--- a/crates/pa-tui/src/session_ui/panels.rs+++ b/crates/pa-tui/src/session_ui/panels.rs@@ -71,14 +71,20 @@ impl SessionUi {}}- /// Refresh the activity dock and the title's cost (the only writer- /// of `chrome.cost_usd`).- pub(super) fn update_subagent_summary(&mut self, view: &mut AgentView) {- let identity = crate::subagents::SessionIdentity::new(+ /// This session's family-addressing identity: the keys its roster+ /// children reference it by.+ pub(super) fn session_identity(&self) -> crate::subagents::SessionIdentity {+ crate::subagents::SessionIdentity::new((!self.active_session_id.is_empty()).then(|| self.active_session_id.clone()),(!self.session_id.is_empty()).then(|| self.session_id.clone()),self.session_file.clone(),- );+ )+ }++ /// Refresh the activity dock and the title's cost (the only writer+ /// of `chrome.cost_usd`).+ pub(super) fn update_subagent_summary(&mut self, view: &mut AgentView) {+ let identity = self.session_identity();self.subagent_counts = crate::subagents::count_descendants(&self.roster, &identity);// The title's spend is the family rollup the agents view bills the// session's row.@@ -236,11 +242,13 @@ impl SessionUi {self.dirty = true;}- /// Mount the panel an agents-view activity line requested; its close returns to the agents+ /// Mount the panel an agents-view activity line (or a return to the page that requested the+ /// session just left) asked for; with `closes_to_agents_view`, its close returns to the agents/// view.pub(crate) fn open_agents_view_panel(&mut self,panel: crate::interactive::SessionPanel,+ closes_to_agents_view: bool,view: &mut AgentView,) {match panel {@@ -250,9 +258,16 @@ impl SessionUi {bash_view.select(&id);}}- crate::interactive::SessionPanel::FactoryRuns => self.open_factory_page(view),+ crate::interactive::SessionPanel::FactoryRuns { row } => {+ self.open_factory_page(view);+ if let (Some(row), Some(factory_view)) = (row, view.factory_view.as_mut()) {+ factory_view.select(row);+ self.sync_factory_selection(view);+ }+ }}- self.panel_returns_to_agents_view = view.bash_view.is_some() || view.factory_view.is_some();+ self.panel_returns_to_agents_view =+ closes_to_agents_view && (view.bash_view.is_some() || view.factory_view.is_some());}/// The close of a panel the agents view requested hands the pane back to it; returns whetherdiff --git a/crates/pa-tui/tests/dock_panel_exit_focus_headless.rs b/crates/pa-tui/tests/dock_panel_exit_focus_headless.rsindex 29f4754be3..34260739ea 100644--- a/crates/pa-tui/tests/dock_panel_exit_focus_headless.rs+++ b/crates/pa-tui/tests/dock_panel_exit_focus_headless.rs@@ -575,14 +575,14 @@ fn agents_view_factory_panel_opens_on_the_run_list_and_returns() {});let outcome = run_plan_with(vec![wait_render("solo-spec"), key(KeyCode::Esc)],- Some(SessionPanel::FactoryRuns),+ Some(SessionPanel::FactoryRuns { row: None }),Some(graph),);assert!(outcome.frames.iter()- .any(|frame| frame.contains("solo-spec") && frame.contains("actions \u{b7}")),+ .any(|frame| frame.contains("solo-spec") && frame.contains("open \u{b7}")),"the factory page mounted on its run list");assert!(diff --git a/crates/pa-tui/tests/factory_command_headless.rs b/crates/pa-tui/tests/factory_command_headless.rsindex 97c9ee0915..872f935f37 100644--- a/crates/pa-tui/tests/factory_command_headless.rs+++ b/crates/pa-tui/tests/factory_command_headless.rs@@ -845,7 +845,7 @@ fn alt_a() -> KeyEvent {KeyEvent::new(KeyCode::Char('a'), KeyModifiers::ALT)}-/// One down-arrow key event (`tui.select.down`: the dock's next row, the page's next run).+/// One down-arrow key event (`tui.select.down`: the dock's next row, the page's next row).fn down() -> KeyEvent {KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)}@@ -855,6 +855,11 @@ fn enter() -> KeyEvent {KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)}+/// One ctrl+x key event (`app.agents.delete`: the page's two-press stop).+fn ctrl_x() -> KeyEvent {+ KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)+}+/// One Esc key event (`tui.select.cancel`: the open page closes).fn escape() -> KeyEvent {KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)@@ -929,10 +934,10 @@ fn a_closed_session_clears_the_open_factory_page() {needle: "factory: only-run".to_string(),timeout_ms: 5_000,},- // Enter opens the run's action rows, the second Enter stops it; the mock's daemon then- // closes the session.- HeadlessStep::Key(enter()),- HeadlessStep::Key(enter()),+ // The first stop press arms the selected run, the second stops it; the mock's daemon+ // then closes the session.+ HeadlessStep::Key(ctrl_x()),+ HeadlessStep::Key(ctrl_x()),HeadlessStep::WaitRender {needle: "No live factory runs.".to_string(),timeout_ms: 5_000,diff --git a/prime-agent-runtime/src/rlm/factory.py b/prime-agent-runtime/src/rlm/factory.pyindex d096447dc2..388662f330 100644--- a/prime-agent-runtime/src/rlm/factory.py+++ b/prime-agent-runtime/src/rlm/factory.py@@ -5641,10 +5641,12 @@ watched = await rlm.factory.watch(result["run_id"], 30)derive from their shapes.- The TUI factory page: the activity dock's `⚙ N factory` group (Enter orclick) opens one live diagram per run, newest run first. The up/down- arrows move the run selection, Enter opens the selected run's action- rows (stop, or resume first while the run is paused — the arrows walk- the rows, Enter runs the tracked action), and Esc backs out of the rows- before it closes the page.+ arrows walk the run headers and the states that spawned a child;+ Enter or Right opens the selected state's latest child session, and+ Left or Esc closes the page. Ctrl+X (the agents view's stop key) twice+ stops the selected row: the whole run on its header, or the state's+ running child (that attempt fails under the state's `retries` and+ `failure_policy`). `r` resumes a paused run.## Safetydiff --git a/scripts/check_factory_navigation.py b/scripts/check_factory_navigation.pyindex 3658cc08ee..be73e5d23f 100644--- a/scripts/check_factory_navigation.py+++ b/scripts/check_factory_navigation.py@@ -1,5 +1,8 @@#!/usr/bin/env python3-"""Hosted actual factory Left/Right navigation with raw PTY evidence.+"""Hosted actual factory page navigation with raw PTY evidence: Right and+Enter on a run header are inert, the stop key only arms, Left closes. Enter+on a state opens its child session without ending the app, and Left in the+child returns to the page with the same run and state selected.A protocol fixture supplies one real-shaped run; actual input parsing, viewrendering and fallback keys execute unchanged.@@ -21,22 +24,50 @@ from lifecycle_lib import Supervisor, Terminal, digest, env_forfrom lifecycle_lib import OwnedProcesses, TAG, finishRUN = 'factory-navigation-run'+CHILD = 'factory-navigation-child'GRAPH = {'runs': [{'run_id': RUN, 'spec_id': 'navigation-fixture', 'name': RUN,'state': 'running', 'machine': {'states': [{'id': 'work'}], 'transitions': []},- 'usage': {'running': 1}, 'nodes': [{'id': 'work', 'status': 'running', 'running': 1}]}]}+ 'usage': {'running': 1}, 'nodes': [{'id': 'work', 'status': 'running', 'running': 1,+ 'instances': [{'status': 'running', 'child': 'work-1'}]}]}]}+# The roster row the page resolves the state's child through: a live depth-1+# subagent of the fixture session s1.+ROSTER = [{'agentId': 'work-agent', 'summary': {'runtimeKind': 'subagent',+ 'rlmChildId': 'work-1', 'parentActiveSessionId': 's1', 'activeSessionId': CHILD,+ 'rlmDepth': 1}}]+STATE_SELECTED = '\u25b8 \u25cf work'class FactorySupervisor(Supervisor):+ def extra_command(self, command, response):+ return command.get('type') == 'cancel_rlm_child'+def send(self, sock, data):data = copy.deepcopy(data)+ if data.get('type') == 'response' and data.get('command') == 'cancel_rlm_child':+ return # A real socket sink that never replies to the confirmed stop.if data.get('type') == 'daemon_hello':data['serverCapabilities'] = ['session_input_admission', 'factory_activity']if data.get('type') == 'response' and data.get('command') == 'factory_activity':# The base fixture already recognizes this lane with an empty# legacy response. Supply its graph shape without mutating errors.data['data'] = copy.deepcopy(GRAPH)+ if data.get('type') == 'response' and data.get('command') == 'roster_subscribe':+ data['data'] = {'roster': copy.deepcopy(ROSTER)}+ if data.get('type') == 'response' and data.get('command') == 'attach' \+ and self.attach_target() == CHILD:+ # The base fixture attaches every session as s1; the child keeps+ # its own identity so the roster and the handoff can tell them apart.+ snapshot = data['data']['snapshot']+ data['data']['activeSessionId'] = snapshot['activeSessionId'] = CHILD+ snapshot['summary']['id'] = snapshot['state']['activeSessionId'] = CHILD+ snapshot['state'].update(sessionId='fixture-child', sessionName='Child fixture')super().send(sock, data)+ def attach_target(self):+ with self.lock:+ attaches = [c for c in self.commands if c.get('type') == 'attach']+ return attaches[-1].get('activeSessionId') if attaches else None+def hello(binary, root, env, observed):path = root / 'hello.sock'@@ -85,14 +116,50 @@ def observe(binary, root, observed):snap('dock', lambda text: server.attaches > 0 and 'factory' in textand any(c.get('type') == 'factory_activity' for c in server.commands))terminal.send(factory_click(terminal.screen))- snap('page', lambda text: RUN in text and 'actions:' not in text)+ snap('page', lambda text: RUN in text and '\u2190 back' in text and 'Ctrl+X stop' in text)+ # Right and Enter on the selected run header are inert; the stop+ # key's armed prompt is the barrier proving they were handled.+ terminal.send('\x1b[C\x1b[C\r\r')+ terminal.send('\x18')+ snap('right_enter_inert_then_stop_armed', lambda text: RUN in text+ and 'again to confirm' in text)terminal.send('\x1b[C')- snap('right_opens_actions', lambda text: 'actions: ' + RUN in text)- terminal.send('\x1b[D')- snap('left_backs_out', lambda text: RUN in text and 'actions:' not in text)+ snap('other_key_disarms', lambda text: RUN in text and 'again to confirm' not in text)terminal.send('\x1b[D')terminal.send('FACTORY_CLOSED_INPUT_BARRIER')snap('left_closes_page', lambda text: 'FACTORY_CLOSED_INPUT_BARRIER' in text and RUN not in text)+ # Reopen the page, select the state, and open its child: the app must+ # stay up and attach the child, which shows its depth label.+ terminal.send(factory_click(terminal.screen))+ snap('page_reopened', lambda text: RUN in text and '\u2190 back' in text)+ terminal.send('\x1b[B')+ snap('state_selected', lambda text: STATE_SELECTED in text)+ terminal.send('\r')+ snap('child_opened', lambda text: 'depth 1' in text and server.attach_target() == CHILD)+ # Left on the child's empty editor leaves it: the page is back on the+ # same run and state, and its Left closes to the chat as before.+ terminal.send('\x1b[D')+ snap('page_returned_on_the_state', lambda text: server.attach_target() == 's1'+ and RUN in text and STATE_SELECTED in text and '\u25b8 factory: ' not in text)+ # A confirmed child stop must leave navigation and paint responsive+ # even while the daemon never replies. The returned page above is+ # already on the child row; no dock-readiness assumption is needed.+ terminal.send('\x18')+ snap('child_stop_armed', lambda text: STATE_SELECTED in text and 'again to confirm' in text)+ terminal.send('\x18')+ terminal.wait('child stop reached hanging sink', lambda: any(+ c.get('type') == 'cancel_rlm_child' for c in server.commands), server)+ started = time.monotonic()+ terminal.send('\x1b[DSTOP_PENDING_INPUT_BARRIER')+ snap('child_stop_does_not_block_navigation', lambda text:+ 'STOP_PENDING_INPUT_BARRIER' in text and RUN not in text)+ observed['stop_navigation_seconds'] = time.monotonic() - started+ assert observed['stop_navigation_seconds'] < 3, 'child stop blocked the UI until its timeout'+ snap('returned_page_closes', lambda text: 'FACTORY_CLOSED_INPUT_BARRIER' in text+ and RUN not in text)+ snap('child_stop_timeout_survives_page_close', lambda text:+ 'timed out waiting for the Prime Agent daemon response' in text+ and RUN not in text)assert not server.prompts, 'navigation submitted a prompt'assert all(c.get('action') in ('graph', 'watch') for c in server.commandsif c.get('type') == 'factory_activity'), server.commands@@ -130,7 +197,7 @@ def main():args = parser.parse_args()receipt = {'verified': False, 'scope': __doc__, 'not_verified': ['real factory execution',- 'rebound keybindings (unit regression)', 'action execution after Right confirmation']}+ 'rebound keybindings (unit regression)', 'stop execution after the second press']}try:assert sys.platform == 'linux', 'hosted Linux only'with tempfile.TemporaryDirectory(prefix='pa-fnav-', dir='/tmp') as folder:diff --git a/skills/factory/SKILL.md b/skills/factory/SKILL.mdindex 74bac188e4..3c4e789fb0 100644--- a/skills/factory/SKILL.md+++ b/skills/factory/SKILL.md@@ -52,6 +52,9 @@ user to run `/factory on` and restart the client.manages them. The seeds are `builder`, `pr-manager`, and `review-sweep`.- The TUI factory page: the activity dock's `⚙ N factory` group (Enter orclick) opens one live diagram per run, newest run first. The up/down- arrows move the selection, Enter opens the selected run's action rows- (stop, or resume while it is paused — arrows to walk, Enter to run),- Esc closes.+ arrows walk the run headers and the states that spawned a child;+ Enter or Right opens the selected state's latest child session, and+ Left or Esc closes the page. Ctrl+X (the agents view's stop key) twice+ stops the selected row: the whole run on its header, or the state's+ running child (that attempt fails under the state's `retries` and+ `failure_policy`). `r` resumes a paused run.