rho-coding-agent 3.12.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
//! `/attach` overlay: pick a child to watch, a workspace subagent by role,
//! title, and activity, which opens read-only in place, or a session the
//! followed session started, which attaching follows as `/jobs` does.

use std::path::Path;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::subagent::{self, RunState, RunStatus, RunningRun};
use crate::title::activity_label;

use super::{
    agent_rail::{ChildTarget, RailState, StartedSession, SubagentAttachTarget},
    picker::{DetailBlock, DetailField, DetailSheet, DetailTone, ExcerptAnchor, OverlayChrome},
    session_attach::AttachPhase,
    session_picker::short_session_id,
    usage_cost::format_token_count,
    App, ComposerMode, PickerBadge, PickerBadgeTone, PickerItem, PickerLayout, UiPicker,
};

const RUNNING_ONLY_KEYS_HINT: &str = "↑↓ agents · Ctrl-R show finished";
const ALL_RUNS_KEYS_HINT: &str = "↑↓ agents · Ctrl-R running only";

/// Which attach-picker rows are visible. Listing always returns every
/// workspace run and every session the followed session started.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum WorkspaceRunFilter {
    RunningOnly,
    All,
}

impl WorkspaceRunFilter {
    pub(super) fn toggled(self) -> Self {
        match self {
            Self::RunningOnly => Self::All,
            Self::All => Self::RunningOnly,
        }
    }
}

/// Rows shown in the attach-picker TASK excerpt.
const TASK_EXCERPT_ROWS: usize = 4;
/// Rows shown in the LATEST excerpt, which keeps the newest output.
const LATEST_EXCERPT_ROWS: usize = 8;

/// One run the attach picker can list. `status` is the run's `result.json`
/// view (live from the panel or read from disk); `prompt` is its launch task.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct AttachCandidate {
    pub run_id: String,
    pub agent_id: String,
    pub elapsed_seconds: u64,
    pub status: RunStatus,
    pub prompt: Option<String>,
}

impl AttachCandidate {
    pub(super) fn state(&self) -> RunState {
        self.status.state
    }
}

impl From<RunningRun> for AttachCandidate {
    fn from(run: RunningRun) -> Self {
        Self {
            run_id: run.id,
            agent_id: run.agent_id,
            elapsed_seconds: run.elapsed_seconds,
            status: run.status,
            prompt: run.prompt,
        }
    }
}

fn is_running_filter_toggle(key: KeyEvent) -> bool {
    key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::ALT)
        && matches!(key.code, KeyCode::Char('r') | KeyCode::Char('R'))
}

pub(super) fn visible_candidates(
    candidates: &[AttachCandidate],
    filter: WorkspaceRunFilter,
) -> Vec<&AttachCandidate> {
    candidates
        .iter()
        .filter(|candidate| listed_under(candidate.state().into(), filter))
        .collect()
}

fn workspace_candidates(cwd: &Path) -> anyhow::Result<Vec<AttachCandidate>> {
    Ok(subagent::list_workspace_runs(cwd)?
        .into_iter()
        .map(AttachCandidate::from)
        .collect())
}

/// Overlay live panel rows onto the listed rows. Live rows carry no prompt,
/// so a matching row keeps the one it already has, and a run listed for the
/// first time reads it once through `read_prompt`.
pub(super) fn merge_live_candidates(
    mut candidates: Vec<AttachCandidate>,
    live: Vec<AttachCandidate>,
    mut read_prompt: impl FnMut(&str) -> Option<String>,
) -> Vec<AttachCandidate> {
    let mut missing = Vec::new();
    for mut live_run in live {
        if let Some(existing) = candidates
            .iter_mut()
            .find(|candidate| candidate.run_id == live_run.run_id)
        {
            live_run.prompt = live_run.prompt.or_else(|| existing.prompt.take());
            *existing = live_run;
        } else {
            live_run.prompt = live_run.prompt.or_else(|| read_prompt(&live_run.run_id));
            missing.push(live_run);
        }
    }
    missing.extend(candidates);
    missing
}

/// Swap in the finished status for runs that left the live set while the
/// picker is open, so the card shows the result, error, tokens, and finish
/// time. The prompt is kept. A run with no terminal status on disk becomes
/// `Stopped` with its last live snapshot.
pub(super) fn retire_departed_live_runs(
    candidates: &mut [AttachCandidate],
    live_ids: &std::collections::HashSet<String>,
    previously_live: &std::collections::HashSet<String>,
    mut terminal_status: impl FnMut(&str) -> Option<RunStatus>,
) {
    for candidate in candidates {
        if previously_live.contains(&candidate.run_id)
            && !live_ids.contains(&candidate.run_id)
            && !candidate.state().is_terminal()
        {
            match terminal_status(&candidate.run_id) {
                Some(status) => candidate.status = status,
                None => candidate.status.state = RunState::Stopped,
            }
        }
    }
}

fn journal_prompt(run_id: &str) -> Option<String> {
    let directory = subagent::resolve_run_directory(run_id).ok()?;
    crate::run_artifacts::read_prompt(&directory)
}

fn finished_run_status(run_id: &str) -> Option<RunStatus> {
    let directory = subagent::resolve_run_directory(run_id).ok()?;
    subagent::read_status(&directory.join(subagent::RESULT_FILE_NAME))
        .filter(|status| status.state.is_terminal())
}

/// The listed run `run_id` names, to open in place, by the role it ran
/// as.
pub(super) fn run_target(
    candidates: &[AttachCandidate],
    run_id: &str,
) -> Option<SubagentAttachTarget> {
    let candidate = candidates
        .iter()
        .find(|candidate| candidate.run_id == run_id)?;
    Some(SubagentAttachTarget {
        run_id: candidate.run_id.clone(),
        agent_id: Some(candidate.agent_id.clone())
            .filter(|agent_id| !agent_id.is_empty())
            .unwrap_or_else(|| "agent".into()),
    })
}

fn picker(
    candidates: &[AttachCandidate],
    sessions: &[StartedSession],
    filter: WorkspaceRunFilter,
) -> UiPicker {
    let items = visible_candidates(candidates, filter)
        .into_iter()
        .map(candidate_item)
        .chain(
            sessions
                .iter()
                .filter(|started| listed_under(started.state, filter))
                .map(session_item),
        )
        .collect();
    let running_only = matches!(filter, WorkspaceRunFilter::RunningOnly);
    UiPicker::attach_agent("attach agent", items)
        .with_layout(PickerLayout::Overlay)
        .with_badge_placement(super::PickerBadgePlacement::Navigation)
        .with_overlay_chrome(OverlayChrome {
            nav_label: " AGENTS".into(),
            detail_label: Some(" DETAILS".into()),
            nav_keys_hint: if running_only {
                RUNNING_ONLY_KEYS_HINT
            } else {
                ALL_RUNS_KEYS_HINT
            }
            .into(),
        })
        .with_empty_message(if running_only {
            "no running agents"
        } else {
            "no agents to attach"
        })
        .with_confirm_verb("attach")
}

fn candidate_item(candidate: &AttachCandidate) -> PickerItem {
    PickerItem {
        section: Some(candidate.agent_id.clone()),
        detail: Some(candidate_detail(candidate, subagent::unix_now_secs()).into()),
        badge: Some(nav_badge(candidate)),
        selection_verb: Some("attach"),
        ..PickerItem::new(
            candidate_title(candidate).to_owned(),
            candidate.run_id.clone(),
        )
    }
}

fn candidate_title(candidate: &AttachCandidate) -> &str {
    candidate
        .status
        .title
        .as_deref()
        .filter(|title| !title.is_empty())
        .unwrap_or("untitled")
}

/// Whether a child in `state` lists under `filter`: running only keeps
/// those at work or waiting on a person, as the rail counts them.
fn listed_under(state: RailState, filter: WorkspaceRunFilter) -> bool {
    match filter {
        WorkspaceRunFilter::All => true,
        WorkspaceRunFilter::RunningOnly => state.is_live(),
    }
}

/// A started session's row, under the agent it runs as, which attaching
/// follows.
fn session_item(started: &StartedSession) -> PickerItem {
    PickerItem {
        section: Some(started.agent.clone().unwrap_or_else(|| "session".into())),
        detail: Some(session_detail(started).into()),
        badge: Some(rail_badge(started.state, None)),
        selection_verb: Some("attach"),
        ..PickerItem::new(started.title.clone(), started.session.as_str().to_owned())
    }
}

/// Session card: what it is and how long its turn ran. Its transcript is
/// the session itself, which attaching follows.
fn session_detail(started: &StartedSession) -> DetailSheet {
    let turn = match started.elapsed {
        Some(elapsed) => DetailField::new(
            "Turn",
            subagent::format_elapsed_secs(elapsed.as_secs()),
            DetailTone::Normal,
        ),
        None => DetailField::new("Turn", "not reported", DetailTone::Muted),
    };
    DetailSheet {
        blocks: vec![
            DetailBlock::Title {
                text: started.title.clone(),
                tag: Some(rail_badge(started.state, None)),
            },
            DetailBlock::Rule,
            DetailBlock::Fields(vec![
                DetailField::new(
                    "Session",
                    short_session_id(started.session.as_str()),
                    DetailTone::Normal,
                ),
                turn,
            ]),
            DetailBlock::Rule,
            DetailBlock::Muted("a session this one started: attaching follows it".into()),
        ],
    }
}

/// Nav row badge: what a live run is doing, or how a finished one ended.
fn nav_badge(candidate: &AttachCandidate) -> PickerBadge {
    rail_badge(
        candidate.state().into(),
        candidate.status.last_activity.as_deref(),
    )
}

/// A child's badge: what it is doing, in the rail's words (see
/// [`RailState::label`]). Colour carries the outcome so a failed child
/// stands out while scanning.
fn rail_badge(state: RailState, activity: Option<&str>) -> PickerBadge {
    let tone = match state {
        RailState::Queued | RailState::Starting | RailState::Stopped => PickerBadgeTone::Muted,
        RailState::Working | RailState::AsksSession => PickerBadgeTone::Internal,
        RailState::NeedsInput => PickerBadgeTone::Warning,
        RailState::Idle | RailState::Done => PickerBadgeTone::Healthy,
        RailState::Failed => PickerBadgeTone::Error,
    };
    PickerBadge {
        text: state.label(activity).to_owned(),
        tone,
    }
}

/// Run card: identity and outcome, the facts that tell runs apart, what the
/// run was asked, then what it produced.
fn candidate_detail(candidate: &AttachCandidate, now: u64) -> DetailSheet {
    let status = &candidate.status;
    // The role is the nav section header beside this card, so it is not
    // repeated here.
    let mut fields = Vec::new();
    if candidate.state() == RunState::Running {
        fields.push(DetailField::new(
            "Activity",
            activity_label(status.last_activity.as_deref()),
            DetailTone::Normal,
        ));
    }
    fields.push(model_field(status));
    fields.push(elapsed_field(candidate, now));
    fields.push(tokens_field(status));

    let mut blocks = vec![
        DetailBlock::Title {
            text: candidate_title(candidate).to_owned(),
            tag: Some(rail_badge(candidate.state().into(), None)),
        },
        DetailBlock::Rule,
        DetailBlock::Fields(fields),
        DetailBlock::Rule,
        DetailBlock::Heading {
            label: "TASK".into(),
            status: String::new(),
        },
    ];
    blocks.push(match candidate.prompt.as_deref().map(str::trim) {
        Some(prompt) if !prompt.is_empty() => DetailBlock::Excerpt {
            text: prompt.to_owned(),
            rows: TASK_EXCERPT_ROWS,
            anchor: ExcerptAnchor::Start,
        },
        _ => DetailBlock::Muted("(task not recorded)".into()),
    });
    blocks.push(DetailBlock::Rule);
    blocks.extend(output_blocks(status));
    DetailSheet { blocks }
}

/// Resolved model when the runtime reported one, with reasoning inline and
/// the runtime as a note.
fn model_field(status: &RunStatus) -> DetailField {
    let model = status
        .runtime_model
        .as_deref()
        .or(status.model.as_deref())
        .filter(|model| !model.is_empty());
    let Some(model) = model else {
        return DetailField::new("Model", "not reported", DetailTone::Muted);
    };
    let value = match status.reasoning {
        Some(level) => format!("{model} · {level}"),
        None => model.to_owned(),
    };
    let field = DetailField::new("Model", value, DetailTone::Normal);
    match status.runtime {
        Some(runtime) => field.with_note(runtime.as_str()),
        None => field,
    }
}

/// Elapsed time, noting how long ago a finished run ended so old runs are
/// easy to tell from fresh ones.
fn elapsed_field(candidate: &AttachCandidate, now: u64) -> DetailField {
    let field = DetailField::new(
        "Elapsed",
        subagent::format_elapsed_secs(candidate.elapsed_seconds),
        DetailTone::Normal,
    );
    match candidate.status.finished_at {
        Some(finished_at) if candidate.state().is_terminal() => field.with_note(format!(
            "finished {}",
            super::session_picker::format_updated_ago(finished_at, now)
        )),
        _ => field,
    }
}

fn tokens_field(status: &RunStatus) -> DetailField {
    let (input, output) = (status.input_tokens, status.output_tokens);
    if input.is_none() && output.is_none() {
        return DetailField::new("Tokens", "not reported", DetailTone::Muted);
    }
    let count = |tokens: Option<u64>| tokens.map_or_else(|| "?".into(), format_token_count);
    let field = DetailField::new(
        "Tokens",
        format!("{} in · {} out", count(input), count(output)),
        DetailTone::Normal,
    );
    match status.total_cost_usd {
        Some(cost) if cost > 0.0 => field.with_note(format!("${cost:.2}")),
        _ => field,
    }
}

/// What the run produced: the newest output while live, the answer once it
/// finishes, or the failure in the error colour.
fn output_blocks(status: &RunStatus) -> Vec<DetailBlock> {
    let heading = |label: &str| DetailBlock::Heading {
        label: label.into(),
        status: String::new(),
    };
    let text_of = |text: &Option<String>| {
        text.as_deref()
            .map(str::trim)
            .filter(|text| !text.is_empty())
            .map(str::to_owned)
    };
    match status.state {
        RunState::Queued | RunState::Starting | RunState::Running => vec![
            heading("LATEST"),
            match text_of(&status.last_text) {
                Some(text) => DetailBlock::Excerpt {
                    text,
                    rows: LATEST_EXCERPT_ROWS,
                    anchor: ExcerptAnchor::End,
                },
                None => DetailBlock::Muted("(no output yet)".into()),
            },
        ],
        RunState::Ok => vec![
            heading("RESULT"),
            match text_of(&status.result) {
                Some(text) => DetailBlock::Paragraph(text),
                None => DetailBlock::Muted("(no result text)".into()),
            },
        ],
        RunState::Error => vec![
            heading("ERROR"),
            DetailBlock::Error(text_of(&status.error).unwrap_or_else(|| "run failed".into())),
        ],
        RunState::Stopped => vec![
            heading("STOPPED"),
            match text_of(&status.result).or_else(|| text_of(&status.last_text)) {
                Some(text) => DetailBlock::Muted(text),
                None => DetailBlock::Muted("(stopped before any output)".into()),
            },
        ],
    }
}

impl App {
    pub(super) fn execute_attach_command(&mut self) -> anyhow::Result<()> {
        self.open_attach_picker_on(WorkspaceRunFilter::RunningOnly);
        Ok(())
    }

    /// Opens `/attach` showing the rows `filter` keeps: the rail's finished
    /// row shows the finished children too.
    pub(super) fn open_attach_picker_on(&mut self, filter: WorkspaceRunFilter) {
        self.attach_run_filter = filter;
        self.open_attach_picker();
    }

    pub(super) fn toggle_attach_filter_if_requested(&mut self, key: KeyEvent) -> bool {
        let ComposerMode::Picker(picker) = self.input_ui.composer() else {
            return false;
        };
        if !picker.is_attach_agent() || !is_running_filter_toggle(key) {
            return false;
        }
        self.attach_run_filter = self.attach_run_filter.toggled();
        self.refresh_attach_picker();
        true
    }

    pub(super) fn refresh_attach_picker(&mut self) {
        let ComposerMode::Picker(open) = self.input_ui.composer() else {
            return;
        };
        if !open.is_attach_agent() {
            return;
        }
        let cursor = open.cursor();
        let selected = open.selected_item().map(|item| item.value.clone());
        let detail_scroll = open.detail_scroll;
        let mut next = picker(
            &self.sync_attach_candidates(),
            self.daemon_rail.sessions.listed(),
            self.attach_run_filter,
        );
        // Rows come and go as children start and end; Enter must keep
        // meaning the child the reader chose.
        next.restore_cursor_on(&cursor, selected.as_deref());
        // Live runs refresh every tick; keep the reader's place in the card
        // while the same run stays selected. Rendering clamps the offset.
        if next.selected_item().map(|item| &item.value) == selected.as_ref() {
            next.detail_scroll = detail_scroll;
        }
        self.input_ui.set_composer(ComposerMode::Picker(next));
    }

    /// Attaches the child the row `value` names, in `phase`.
    pub(super) async fn submit_attach_selection(&mut self, value: &str, phase: AttachPhase<'_>) {
        let session = self
            .daemon_rail
            .sessions
            .listed()
            .iter()
            .find(|started| started.session.as_str() == value)
            .map(|started| ChildTarget::Session(started.session.clone()));
        let child = session
            .or_else(|| run_target(&self.sync_attach_candidates(), value).map(ChildTarget::Run));
        match child {
            Some(child) => self.attach_child(child, phase).await,
            None => self.set_status("could not attach agent: it is no longer listed"),
        }
    }

    fn open_attach_picker(&mut self) {
        self.attach_seen_live.clear();
        let listing_error = match workspace_candidates(&self.info.runtime.cwd) {
            Ok(disk) => {
                self.attach_disk_candidates = disk;
                None
            }
            Err(error) => {
                self.attach_disk_candidates.clear();
                Some(error)
            }
        };
        let candidates = self.sync_attach_candidates();
        self.input_ui.set_composer(ComposerMode::Picker(picker(
            &candidates,
            self.daemon_rail.sessions.listed(),
            self.attach_run_filter,
        )));
        match listing_error {
            Some(error) => self.set_status(format!("could not list workspace runs: {error}")),
            None => self.set_status("attach agent"),
        }
    }

    fn sync_attach_candidates(&mut self) -> Vec<AttachCandidate> {
        let live = self.agent_rail.candidates();
        let live_ids = live
            .iter()
            .map(|candidate| candidate.run_id.clone())
            .collect::<std::collections::HashSet<_>>();
        self.attach_disk_candidates = merge_live_candidates(
            std::mem::take(&mut self.attach_disk_candidates),
            live,
            journal_prompt,
        );
        retire_departed_live_runs(
            &mut self.attach_disk_candidates,
            &live_ids,
            &self.attach_seen_live,
            finished_run_status,
        );
        self.attach_seen_live.extend(live_ids);
        self.attach_disk_candidates.clone()
    }
}

#[cfg(test)]
#[path = "attach_picker_tests.rs"]
mod tests;