use std::time::Duration;
use ratatui::{
layout::Rect,
text::{Line, Span},
};
use rho_protocol::SessionId;
use super::{
activity,
attach_picker::WorkspaceRunFilter,
stacked_rail::{RailHit, RailItem, RailPointerPolicy, StackedRail},
theme::Theme,
};
use crate::{
subagent::{self, RunState},
title::activity_label,
};
const OPEN_ATTACH_PICKER_ID: &str = "/attach";
const FINISHED_ID: &str = "/attach finished";
#[derive(Clone, Debug, PartialEq)]
struct AgentRow {
id: String,
title: Option<String>,
state: RailState,
last_activity: Option<String>,
elapsed_seconds: Option<u64>,
child: RailChild,
}
impl AgentRow {
fn agent(&self) -> Option<&str> {
match &self.child {
RailChild::Run { agent_id, .. } => Some(agent_id),
RailChild::Session { agent, .. } => agent.as_deref(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
enum RailEntry {
Child(AgentRow),
Finished(FinishedChildren),
}
impl RailItem for RailEntry {
fn id(&self) -> &str {
match self {
Self::Child(row) => &row.id,
Self::Finished(_) => FINISHED_ID,
}
}
fn is_live(&self) -> bool {
match self {
Self::Child(row) => row.state.is_live(),
Self::Finished(_) => false,
}
}
fn is_failure(&self) -> bool {
match self {
Self::Child(row) => row.state == RailState::Failed,
Self::Finished(_) => false,
}
}
fn yields(&self) -> bool {
match self {
Self::Child(_) => false,
Self::Finished(_) => true,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FinishedChildren {
count: usize,
failed: usize,
stopped: usize,
}
impl FinishedChildren {
fn of(rows: &[AgentRow]) -> Option<Self> {
let with = |state| rows.iter().filter(|row| row.state == state).count();
(!rows.is_empty()).then(|| Self {
count: rows.len(),
failed: with(RailState::Failed),
stopped: with(RailState::Stopped),
})
}
}
fn hidden_live(entries: &[RailEntry], shown: &[&RailEntry]) -> usize {
let live = entries.iter().filter(|entry| entry.is_live()).count();
live - shown.iter().filter(|entry| entry.is_live()).count()
}
#[derive(Clone, Debug, PartialEq)]
enum RailChild {
Run {
agent_id: String,
status: Box<subagent::RunStatus>,
},
Session {
session: SessionId,
agent: Option<String>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum RailState {
Queued,
Starting,
Working,
NeedsInput,
Idle,
Done,
Failed,
Stopped,
}
impl RailState {
pub(super) fn is_live(self) -> bool {
match self {
Self::Queued | Self::Starting | Self::Working | Self::NeedsInput => true,
Self::Idle | Self::Done | Self::Failed | Self::Stopped => false,
}
}
pub(super) fn label(self, activity: Option<&str>) -> &str {
match self {
Self::Queued => "queued",
Self::Starting => "starting",
Self::Working => activity_label(activity),
Self::NeedsInput => "needs input",
Self::Idle => "โ idle",
Self::Done => "โ done",
Self::Failed => "โ error",
Self::Stopped => "โ stopped",
}
}
}
impl From<RunState> for RailState {
fn from(state: RunState) -> Self {
match state {
RunState::Queued => Self::Queued,
RunState::Starting => Self::Starting,
RunState::Running => Self::Working,
RunState::Ok => Self::Done,
RunState::Error => Self::Failed,
RunState::Stopped => Self::Stopped,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct StartedSession {
pub(super) session: SessionId,
pub(super) agent: Option<String>,
pub(super) title: String,
pub(super) state: RailState,
pub(super) elapsed: Option<Duration>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct SubagentAttachTarget {
pub(super) run_id: String,
pub(super) agent_id: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum ChildTarget {
Run(SubagentAttachTarget),
Session(SessionId),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum AgentRailTarget {
Child(ChildTarget),
OpenAttachPicker(WorkspaceRunFilter),
}
impl AgentRailTarget {
pub(super) fn pointer_id(&self) -> &str {
match self {
Self::Child(ChildTarget::Run(target)) => target.run_id.as_str(),
Self::Child(ChildTarget::Session(session)) => session.as_str(),
Self::OpenAttachPicker(WorkspaceRunFilter::RunningOnly) => OPEN_ATTACH_PICKER_ID,
Self::OpenAttachPicker(WorkspaceRunFilter::All) => FINISHED_ID,
}
}
}
#[derive(Clone, Debug)]
pub(super) struct AgentRail {
rail: StackedRail<RailEntry>,
runs: Vec<AgentRow>,
sessions: Vec<AgentRow>,
}
impl Default for AgentRail {
fn default() -> Self {
Self {
rail: StackedRail::new(RailPointerPolicy::OverflowOpens {
overflow_id: OPEN_ATTACH_PICKER_ID,
}),
runs: Vec::new(),
sessions: Vec::new(),
}
}
}
impl AgentRail {
pub(super) fn ingest_runs(
&mut self,
snapshots: Vec<crate::tools::agent::SubagentSnapshot>,
) -> bool {
self.runs = snapshots
.into_iter()
.map(|snapshot| AgentRow {
id: snapshot.id,
title: snapshot.title,
state: snapshot.status.state.into(),
last_activity: snapshot.status.last_activity.clone(),
elapsed_seconds: Some(snapshot.elapsed.as_secs()),
child: RailChild::Run {
agent_id: snapshot.agent_id,
status: Box::new(snapshot.status),
},
})
.collect();
self.show()
}
pub(super) fn ingest_sessions(&mut self, sessions: Vec<StartedSession>) -> bool {
self.sessions = sessions
.into_iter()
.map(|started| AgentRow {
id: started.session.as_str().to_owned(),
title: Some(started.title),
state: started.state,
last_activity: None,
elapsed_seconds: started.elapsed.map(|elapsed| elapsed.as_secs()),
child: RailChild::Session {
session: started.session,
agent: started.agent,
},
})
.collect();
self.show()
}
fn show(&mut self) -> bool {
let (live, finished): (Vec<_>, Vec<_>) = self
.runs
.iter()
.chain(&self.sessions)
.cloned()
.partition(|row| row.state.is_live());
let entries = live
.into_iter()
.map(RailEntry::Child)
.chain(FinishedChildren::of(&finished).map(RailEntry::Finished))
.collect();
self.rail.ingest(entries)
}
pub(super) fn count(&self) -> usize {
self.rail.live_count()
}
pub(super) fn is_active(&self) -> bool {
self.rail.is_active()
}
pub(super) fn desired_height(&self) -> usize {
self.rail.desired_height()
}
pub(super) fn clear_pointer_state(&mut self) {
self.rail.clear_pointer_state();
}
pub(super) fn clear_pressed(&mut self) {
self.rail.clear_pressed();
}
pub(super) fn set_hovered(&mut self, row_id: Option<&str>) -> bool {
self.rail.set_hovered(row_id)
}
pub(super) fn set_pressed(&mut self, row_id: Option<&str>) -> bool {
self.rail.set_pressed(row_id)
}
pub(super) fn pressed_row_id(&self) -> Option<&str> {
self.rail.pressed_id()
}
pub(super) fn highlighted_row(&self, height: usize) -> Option<(usize, activity::RailRowState)> {
self.rail.highlighted_row(height)
}
pub(super) fn candidates(&self) -> Vec<super::attach_picker::AttachCandidate> {
self.rail
.live_items()
.filter_map(|entry| match entry {
RailEntry::Child(agent) => Some(agent),
RailEntry::Finished(_) => None,
})
.filter_map(|agent| match &agent.child {
RailChild::Run { agent_id, status } => {
Some(super::attach_picker::AttachCandidate {
run_id: agent.id.clone(),
agent_id: agent_id.clone(),
elapsed_seconds: agent.elapsed_seconds.unwrap_or_default(),
status: (**status).clone(),
prompt: None,
})
}
RailChild::Session { .. } => None,
})
.collect()
}
pub(super) fn attach_target_at(
&self,
area: Rect,
column: u16,
row: u16,
) -> Option<AgentRailTarget> {
match self.rail.hit_at(area, column, row)? {
RailHit::Overflow => Some(AgentRailTarget::OpenAttachPicker(
WorkspaceRunFilter::RunningOnly,
)),
RailHit::Item(row_id) => self
.rail
.items()
.iter()
.find(|entry| entry.id() == row_id)
.map(|entry| match entry {
RailEntry::Child(agent) => AgentRailTarget::Child(match &agent.child {
RailChild::Run { agent_id, .. } => ChildTarget::Run(SubagentAttachTarget {
run_id: agent.id.clone(),
agent_id: agent_id.clone(),
}),
RailChild::Session { session, .. } => ChildTarget::Session(session.clone()),
}),
RailEntry::Finished(_) => {
AgentRailTarget::OpenAttachPicker(WorkspaceRunFilter::All)
}
}),
}
}
pub(super) fn lines(
&self,
width: usize,
height: usize,
action_hint: &str,
continues_below: bool,
) -> Vec<Line<'static>> {
if !self.rail.is_active() || width == 0 || height == 0 {
return Vec::new();
}
let (rows, hidden) = self.rail.visible(height);
let visible_count = rows.len() + usize::from(hidden.is_some());
let hidden = hidden.map(|_| hidden_live(self.rail.items(), &rows));
let mut lines = Vec::with_capacity(visible_count);
for (index, entry) in rows.into_iter().enumerate() {
let connector =
activity::tree_connector(index + 1 == visible_count && !continues_below);
let row_state = self.rail.row_state(entry.id());
lines.push(match entry {
RailEntry::Finished(finished) => {
finished_line(*finished, connector, width, row_state, action_hint)
}
RailEntry::Child(agent) => {
let (activity_text, activity_style) = agent_activity(agent);
agent_line(
agent,
activity_text,
activity_style,
connector,
width,
row_state,
action_hint,
)
}
});
}
if let Some(hidden) = hidden {
lines.push(overflow_line(
hidden,
activity::tree_connector(!continues_below),
width,
self.rail.overflow_row_state(),
action_hint,
));
}
lines
}
}
fn agent_line(
agent: &AgentRow,
activity_text: String,
activity_style: ratatui::style::Style,
connector: &'static str,
width: usize,
row_state: activity::RailRowState,
action_hint: &str,
) -> Line<'static> {
let elapsed = agent.elapsed_seconds.map(subagent::format_elapsed_secs);
let trailing = match (row_state, elapsed) {
(activity::RailRowState::Idle, elapsed) => elapsed.unwrap_or_default(),
(activity::RailRowState::Hovered | activity::RailRowState::Pressed, Some(elapsed)) => {
format!("โ {action_hint} ยท {elapsed}")
}
(activity::RailRowState::Hovered | activity::RailRowState::Pressed, None) => {
format!("โ {action_hint}")
}
};
let row_style = Theme::activity_rail_row(row_state);
activity::RailRow {
connector,
identity: rail_identity(agent, row_style),
activity: activity_text,
activity_style,
trailing,
trailing_style: Theme::activity_rail_dim(),
row_style,
}
.into_line(width)
}
fn overflow_line(
hidden: usize,
connector: &'static str,
width: usize,
row_state: activity::RailRowState,
action_hint: &str,
) -> Line<'static> {
summary_line(
activity::overflow_label(hidden, "agent", "agents"),
("/attach".into(), Theme::activity_rail_dim()),
connector,
width,
row_state,
action_hint,
)
}
fn finished_line(
finished: FinishedChildren,
connector: &'static str,
width: usize,
row_state: activity::RailRowState,
action_hint: &str,
) -> Line<'static> {
let FinishedChildren {
count,
failed,
stopped,
} = finished;
let mut outcome = Vec::new();
if failed > 0 {
outcome.push(format!("โ {failed} failed"));
}
if stopped > 0 {
outcome.push(format!("{stopped} stopped"));
}
let (label, style) = match failed {
0 if stopped == 0 => (format!("โ {count} finished"), Theme::activity_rail_dim()),
0 => (format!("{count} finished"), Theme::activity_rail_dim()),
_ => (format!("{count} finished"), Theme::activity_rail_error()),
};
outcome.push("/attach".into());
summary_line(
label,
(outcome.join(" ยท "), style),
connector,
width,
row_state,
action_hint,
)
}
fn summary_line(
label: String,
(activity, activity_style): (String, ratatui::style::Style),
connector: &'static str,
width: usize,
row_state: activity::RailRowState,
action_hint: &str,
) -> Line<'static> {
let trailing = match row_state {
activity::RailRowState::Idle => String::new(),
activity::RailRowState::Hovered | activity::RailRowState::Pressed => {
format!("โ {action_hint}")
}
};
let row_style = Theme::activity_rail_row(row_state);
activity::RailRow {
connector,
identity: vec![Span::styled(label, Theme::dim().patch(row_style))],
activity,
activity_style,
trailing,
trailing_style: Theme::activity_rail_dim(),
row_style,
}
.into_line(width)
}
fn rail_identity(agent: &AgentRow, row_style: ratatui::style::Style) -> Vec<Span<'static>> {
let mut identity = vec![Span::styled(
activity::AGENT_GLYPH,
Theme::text_strong().patch(row_style),
)];
if let Some(name) = agent.agent() {
identity.push(Span::styled(
name.to_owned(),
Theme::text_strong().patch(row_style),
));
}
if let Some(title) = agent.title.as_deref().filter(|title| !title.is_empty()) {
if agent.agent().is_some() {
identity.push(Span::styled(" ", row_style));
}
identity.push(Span::styled(
title.to_owned(),
Theme::dim().patch(row_style),
));
}
identity
}
fn agent_activity(agent: &AgentRow) -> (String, ratatui::style::Style) {
let style = match agent.state {
RailState::Queued | RailState::Starting | RailState::Working => Theme::text(),
RailState::NeedsInput => Theme::warning(),
RailState::Idle | RailState::Done => Theme::activity_rail_success(),
RailState::Failed => Theme::activity_rail_error(),
RailState::Stopped => Theme::activity_rail_dim(),
};
let label = agent.state.label(agent.last_activity.as_deref());
(label.to_owned(), style)
}
#[cfg(test)]
#[path = "agent_rail_tests.rs"]
mod tests;