rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! The agent rail: one row per child of the followed session, a subagent
//! run or a session it started, under the activity spinner.

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";
/// The id of the row the finished children fold into.
const FINISHED_ID: &str = "/attach finished";

/// One row of the agent rail: a subagent run, or a session the followed
/// session started.
#[derive(Clone, Debug, PartialEq)]
struct AgentRow {
    /// The run's id, or the session's.
    id: String,
    title: Option<String>,
    state: RailState,
    last_activity: Option<String>,
    /// How long the run, or the session's turn, ran, when known.
    elapsed_seconds: Option<u64>,
    child: RailChild,
}

impl AgentRow {
    /// The agent the row names, if any.
    fn agent(&self) -> Option<&str> {
        match &self.child {
            RailChild::Run { agent_id, .. } => Some(agent_id),
            RailChild::Session { agent, .. } => agent.as_deref(),
        }
    }
}

/// One row the rail lists: a live child, or the children that finished,
/// folded into one.
#[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,
            // It never competes for a slot: every other row is live.
            Self::Finished(_) => false,
        }
    }

    fn yields(&self) -> bool {
        match self {
            Self::Child(_) => false,
            // Working children fill the rail first.
            Self::Finished(_) => true,
        }
    }
}

/// The children that finished, which the rail folds into one row: how
/// many, and how many of them failed or were stopped.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FinishedChildren {
    count: usize,
    failed: usize,
    stopped: usize,
}

impl FinishedChildren {
    /// The fold of `rows`, the children no longer live, if any.
    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),
        })
    }
}

/// How many agents the overflow row stands for: the live children of
/// `entries` that `shown` leaves out, which its click lists. A finished
/// row it hides gave way to them, and `/attach` lists those with Ctrl-R.
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()
}

/// What a rail row is, which says what activating it opens.
#[derive(Clone, Debug, PartialEq)]
enum RailChild {
    /// A subagent run, with its full status for the `/attach` run card.
    Run {
        agent_id: String,
        status: Box<subagent::RunStatus>,
    },
    /// A session the followed session started, which a click follows.
    Session {
        session: SessionId,
        agent: Option<String>,
    },
}

/// What a rail row's child is doing, as its row says it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum RailState {
    Queued,
    Starting,
    Working,
    /// Waits on a person: a session's turn's request, or a question one of
    /// its subagents asked.
    NeedsInput,
    /// A session that waits only on sessions it asked, which were given
    /// its questions; a person may still answer them.
    AsksSession,
    /// A session between turns: the turn its parent started ended, and it
    /// can be prompted again.
    Idle,
    Done,
    Failed,
    Stopped,
}

impl RailState {
    /// Whether the child is still at work, or waits on a person to go on:
    /// such a row counts among the agents and can be clicked, and `/attach`
    /// lists it while it shows running children only.
    pub(super) fn is_live(self) -> bool {
        match self {
            Self::Queued
            | Self::Starting
            | Self::Working
            | Self::NeedsInput
            | Self::AsksSession => true,
            Self::Idle | Self::Done | Self::Failed | Self::Stopped => false,
        }
    }

    /// What the child is doing, in the words the rail and `/attach` say it:
    /// a working child's `activity` when it reported one.
    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::AsksSession => "asks a session",
            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,
        }
    }
}

/// A session the followed session started, as the rail shows it.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct StartedSession {
    pub(super) session: SessionId,
    /// The agent the row names, if any (see `daemon_job.rs`).
    pub(super) agent: Option<String>,
    pub(super) title: String,
    pub(super) state: RailState,
    /// How long its last turn ran, or the one under way, when known.
    pub(super) elapsed: Option<Duration>,
}

/// A clickable subagent row resolved from a pointer position.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct SubagentAttachTarget {
    pub(super) run_id: String,
    pub(super) agent_id: String,
}

/// A child to attach, from the rail, `/attach`, or `/jobs`: a subagent run,
/// which opens read-only in place, or a session the followed session
/// started, which attaching follows (`session_attach.rs`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum ChildTarget {
    Run(SubagentAttachTarget),
    Session(SessionId),
}

/// Pointer hit on the agent rail: attach a child, or open `/attach`, on
/// the running children from the overflow row, on every one, the finished
/// too, from the finished row.
#[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>,
    /// The rows of the runs, then of the sessions, last shown.
    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 {
    /// Shows `snapshots`, the runs, before the sessions it shows; returns
    /// whether the rows changed.
    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()
    }

    /// Shows `sessions`, the sessions the followed session started, after
    /// the runs it shows; returns whether the rows changed.
    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()
    }

    /// Shows the live rows, then the finished ones folded into one, so a
    /// child that ended never takes the place of one at work.
    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();
    }

    /// Returns whether the hovered row changed.
    pub(super) fn set_hovered(&mut self, row_id: Option<&str>) -> bool {
        self.rail.set_hovered(row_id)
    }

    /// Returns whether the pressed row changed.
    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),
                // Not live.
                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,
    )
}

/// The row the finished children fold into: how many, how many of them
/// failed or were stopped, and that `/attach` lists them.
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,
    )
}

/// A row that stands for other children, which a click opens in `/attach`.
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 | RailState::AsksSession => {
            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;