rho-coding-agent 3.2.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
624
625
626
627
628
629
630
631
632
633
634
635
636
//! In-app `/workflow` hub: start workflows and check runs from the chat TUI.

use std::{cmp::Reverse, str::FromStr};

use crate::tui::DefaultTerminal;

use super::{
    picker::OverlayChrome, App, ComposerMode, Entry, InlineChoice, InlineChoiceModal,
    InlineChoiceOption, InlineChoicePending, PickerBadge, PickerBadgeTone, PickerItem,
    PickerLayout, UiPicker,
};
use crate::{
    app::workflow_cli::{self, discover, WorkflowOps},
    workflow::{
        PlanId, PlanInventory, RunId, RunInventory, RunInventoryItem, RunLifecycle, StoredRun,
        UnsupportedRecord, WorkflowError, WorkflowOutcome,
    },
};

const SOURCE_PREFIX: &str = "source:";
const PLAN_PREFIX: &str = "plan:";
const RUN_PREFIX: &str = "run:";
const RETRY_RUN_PREFIX: &str = "retry-run:";
const UNSUPPORTED_PLAN_PREFIX: &str = "unsupported-plan:";
const UNSUPPORTED_RUN_PREFIX: &str = "unsupported-run:";

#[path = "workflow_plans.rs"]
mod plans;

const MAX_FINISHED_RUNS: usize = 8;

fn badge(text: impl Into<String>, tone: PickerBadgeTone) -> PickerBadge {
    PickerBadge {
        text: text.into(),
        tone,
    }
}

fn item(
    section: Option<&str>,
    label: impl Into<String>,
    detail: impl Into<String>,
    value: impl Into<String>,
    badge_text: Option<(String, PickerBadgeTone)>,
    selection_verb: Option<&'static str>,
) -> PickerItem {
    PickerItem {
        section: section.map(str::to_owned),
        detail: Some(super::picker::PickerDetail::Text(detail.into())),
        badge: badge_text.map(|(text, tone)| badge(text, tone)),
        selection_verb,
        ..PickerItem::new(label.into(), value.into())
    }
}

fn short_id(id: &str) -> String {
    id.chars().take(8).collect()
}

fn lifecycle_label(lifecycle: RunLifecycle) -> &'static str {
    match lifecycle {
        RunLifecycle::Planned => "ready",
        RunLifecycle::Running => "running",
        RunLifecycle::Cancelling => "stopping",
        RunLifecycle::Completed => "finished",
        RunLifecycle::NeedsRecovery => "needs recovery",
    }
}

fn lifecycle_tone(lifecycle: RunLifecycle) -> PickerBadgeTone {
    match lifecycle {
        RunLifecycle::Running | RunLifecycle::Planned => PickerBadgeTone::Selected,
        RunLifecycle::NeedsRecovery | RunLifecycle::Cancelling => PickerBadgeTone::Warning,
        RunLifecycle::Completed => PickerBadgeTone::Internal,
    }
}

fn outcome_label(outcome: Option<WorkflowOutcome>) -> String {
    match outcome {
        Some(WorkflowOutcome::Success) => "success".into(),
        Some(WorkflowOutcome::Failure) => "failed".into(),
        Some(WorkflowOutcome::Denial) => "denied".into(),
        Some(WorkflowOutcome::Cancellation) => "cancelled".into(),
        Some(WorkflowOutcome::Blocked) => "blocked".into(),
        None => "pending".into(),
    }
}

fn run_progress(done: usize, total: usize) -> String {
    let total = total.max(1);
    format!("{done}/{total} steps done")
}

/// A run saved before scoped workflow programs: listed so it can be deleted,
/// but this release cannot open it.
fn unsupported_run_item(record: &UnsupportedRecord<RunId>) -> PickerItem {
    let id = record.id.to_string();
    let short = short_id(&id);
    item(
        Some("RUNS"),
        format!("Unsupported  ·  {short}"),
        format!(
            "{}\nSaved by Rho before 2.15. Inspect it with Rho 2.x. Press d to delete.\nRun id {short}",
            record.name
        ),
        format!("{UNSUPPORTED_RUN_PREFIX}{id}"),
        Some(("unsupported".into(), PickerBadgeTone::Warning)),
        Some("close"),
    )
}

fn run_item(run: &RunInventoryItem) -> PickerItem {
    let id = run.run_id.to_string();
    let short = short_id(&id);
    let (label, tone) = match run.lifecycle {
        RunLifecycle::Completed => (outcome_label(run.outcome), outcome_tone(run.outcome)),
        RunLifecycle::Planned
        | RunLifecycle::Running
        | RunLifecycle::Cancelling
        | RunLifecycle::NeedsRecovery => (
            lifecycle_label(run.lifecycle).into(),
            lifecycle_tone(run.lifecycle),
        ),
    };
    item(
        Some("RUNS"),
        format!("Watch  {label}  ·  {short}"),
        format!("{}\n{label} · {}\nEnter opens the DAG watch screen. Press d to delete.\nRun id {short}", run.name, run_progress(run.done_steps, run.total_steps)),
        format!("{RUN_PREFIX}{id}"),
        Some((label, tone)),
        Some("watch"),
    )
}

/// Root list: start workflows, open runs, or reuse a saved plan.
pub(super) fn hub_picker(
    sources: &[discover::DiscoveredWorkflow],
    plans: &PlanInventory,
    runs: &RunInventory,
) -> UiPicker {
    let mut items = Vec::new();

    if sources.is_empty() {
        items.push(item(
            Some("START"),
            "No workflows yet",
            "Ask Rho to create your first workflow.",
            "noop:empty_sources",
            None,
            Some("close"),
        ));
    } else {
        for source in sources {
            items.push(item(
                Some("START"),
                format!("Start  {}", source.label),
                format!(
                    "Create a new run with default inputs.\nFile: {}",
                    source.relative_path
                ),
                format!("{SOURCE_PREFIX}{}", source.relative_path),
                Some(("new run".into(), PickerBadgeTone::Selected)),
                Some("start"),
            ));
        }
    }

    let mut active = runs
        .items
        .iter()
        .filter(|run| run.lifecycle != RunLifecycle::Completed)
        .collect::<Vec<_>>();
    active.sort_by_key(|run| Reverse((run.created_at_unix_nanos, run.run_id)));

    let mut finished = runs
        .items
        .iter()
        .filter(|run| run.lifecycle == RunLifecycle::Completed)
        .collect::<Vec<_>>();
    finished.sort_by_key(|run| Reverse((run.created_at_unix_nanos, run.run_id)));
    finished.truncate(MAX_FINISHED_RUNS);

    if active.is_empty() && finished.is_empty() && runs.unsupported.is_empty() {
        items.push(item(
            Some("RUNS"),
            "No runs yet",
            "Start a workflow above. Finished and active runs show up here.",
            "noop:empty_runs",
            None,
            Some("close"),
        ));
    } else {
        for run in active.into_iter().chain(finished) {
            items.push(run_item(run));
            if run.lifecycle == RunLifecycle::Planned {
                let id = run.run_id.to_string();
                let short = short_id(&id);
                items.push(item(
                    Some("RUNS"),
                    format!("Retry start  ·  {short}"),
                    format!("{}\nRetry launching this ready run in the background using its existing frozen graph and run id. Watch only inspects it.\nRun id {short}", run.name),
                    format!("{RETRY_RUN_PREFIX}{id}"),
                    None,
                    Some("retry"),
                ));
            }
        }
        items.extend(runs.unsupported.iter().map(unsupported_run_item));
    }

    let plan_count = plans.items.len() + plans.unsupported.len();
    if plan_count > 0 {
        items.push(item(
            Some("PLANS"),
            format!("Saved plans · {plan_count}"),
            "Browse frozen plans to reuse or delete. Starting from source uses the current workflow instead.",
            "browse:plans",
            None,
            Some("browse"),
        ));
    }

    UiPicker::workflow("Workflows", items)
        .with_key_hints(super::PickerKeyHints {
            tab: super::TabKey::None,
            row_delete: super::RowDeleteKeys::DOrDelete,
            ..Default::default()
        })
        .with_layout(PickerLayout::Overlay)
        .with_overlay_chrome(OverlayChrome {
            nav_label: " WORKFLOWS".into(),
            detail_label: Some(" DETAILS".into()),
            nav_keys_hint: "↑↓ items".into(),
        })
        .with_confirm_verb("open")
}

fn outcome_tone(outcome: Option<WorkflowOutcome>) -> PickerBadgeTone {
    match outcome {
        Some(WorkflowOutcome::Success) => PickerBadgeTone::Healthy,
        Some(
            WorkflowOutcome::Failure
            | WorkflowOutcome::Denial
            | WorkflowOutcome::Cancellation
            | WorkflowOutcome::Blocked,
        ) => PickerBadgeTone::Warning,
        None => PickerBadgeTone::Internal,
    }
}

impl App {
    pub(super) async fn execute_workflow_command(
        &mut self,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        self.open_workflow_hub_or_report();
        let _ = terminal;
        Ok(())
    }

    pub(super) fn open_workflow_hub_or_report(&mut self) {
        if let Err(error) = self.open_workflow_hub() {
            self.input_ui.set_composer(ComposerMode::Input);
            self.insert_entry(&Entry::Error(format!("could not open workflows: {error}")));
            self.set_status("workflow hub failed");
        }
    }

    pub(super) fn open_workflow_hub(&mut self) -> anyhow::Result<()> {
        let ops = self.workflow_ops()?;
        let sources = discover::discover_workflow_sources(&self.info.runtime.cwd);
        let plans = ops.list_workspace_plans()?;
        let runs = ops.list_workspace_runs()?;
        let picker = hub_picker(&sources, &plans, &runs);
        self.input_ui.set_composer(ComposerMode::Picker(picker));
        self.set_status("workflows");
        Ok(())
    }

    pub(super) fn prompt_delete_selected_workflow_item(&mut self) -> anyhow::Result<()> {
        let Some(value) = self.selected_workflow_value() else {
            return Ok(());
        };
        if let Some(plan_id) = value
            .strip_prefix(PLAN_PREFIX)
            .or_else(|| value.strip_prefix(UNSUPPORTED_PLAN_PREFIX))
        {
            let short = short_id(plan_id);
            let choice = InlineChoice::new(
                format!("Delete plan {short}?"),
                "Removes this saved plan. Existing runs keep their own graph copy and still open.",
                vec![
                    InlineChoiceOption::available(
                        "delete",
                        'd',
                        "Delete",
                        "Permanently remove this plan",
                    ),
                    InlineChoiceOption::available(
                        "cancel",
                        'c',
                        "Cancel",
                        "Keep the plan and return to workflows",
                    )
                    .with_alternate_shortcut('n'),
                ],
            )?;
            self.input_ui
                .set_composer(ComposerMode::InlineChoice(InlineChoiceModal {
                    choice,
                    pending: InlineChoicePending::DeleteWorkflowPlan {
                        plan_id: plan_id.to_owned(),
                    },
                    parent_picker: None,
                }));
            self.set_status("confirm delete plan");
            return Ok(());
        }
        if let Some(run_id) = value
            .strip_prefix(RUN_PREFIX)
            .or_else(|| value.strip_prefix(RETRY_RUN_PREFIX))
            .or_else(|| value.strip_prefix(UNSUPPORTED_RUN_PREFIX))
        {
            let short = short_id(run_id);
            let choice = InlineChoice::new(
                format!("Delete run {short}?"),
                "Removes this run's durable status and artifacts. Active runs must be stopped first.",
                vec![
                    InlineChoiceOption::available(
                        "delete",
                        'd',
                        "Delete",
                        "Permanently remove this run",
                    ),
                    InlineChoiceOption::available(
                        "cancel",
                        'c',
                        "Cancel",
                        "Keep the run and return to workflows",
                    )
                    .with_alternate_shortcut('n'),
                ],
            )?;
            self.input_ui
                .set_composer(ComposerMode::InlineChoice(InlineChoiceModal {
                    choice,
                    pending: InlineChoicePending::DeleteWorkflowRun {
                        run_id: run_id.to_owned(),
                    },
                    parent_picker: None,
                }));
            self.set_status("confirm delete run");
            return Ok(());
        }
        self.set_status(
            "Only saved plans and runs can be deleted here. Local workflow files stay on disk.",
        );
        Ok(())
    }

    pub(super) fn submit_delete_workflow_plan_choice(
        &mut self,
        value: &str,
        plan_id: &str,
    ) -> anyhow::Result<()> {
        if value != "delete" {
            return self.open_workflow_plans();
        }
        let short = short_id(plan_id);
        let parsed = PlanId::from_str(plan_id)?;
        let status = match self.workflow_ops()?.delete_workspace_plan(parsed) {
            Ok(()) => format!("deleted plan {short}"),
            Err(error) => {
                self.insert_entry(&Entry::Error(format!("could not delete plan: {error:#}")));
                "delete failed".into()
            }
        };
        self.open_workflow_plans()?;
        self.set_status(status);
        Ok(())
    }

    pub(super) fn submit_delete_workflow_run_choice(
        &mut self,
        value: &str,
        run_id: &str,
    ) -> anyhow::Result<()> {
        if value != "delete" {
            return self.open_workflow_hub();
        }
        let short = short_id(run_id);
        let parsed = RunId::from_str(run_id)?;
        let status = match self.workflow_ops()?.delete_workspace_run(parsed) {
            Ok(()) => format!("deleted run {short}"),
            Err(error) => {
                self.insert_entry(&Entry::Error(format!("could not delete run: {error:#}")));
                "delete failed".into()
            }
        };
        self.open_workflow_hub()?;
        self.set_status(status);
        Ok(())
    }

    fn selected_workflow_value(&self) -> Option<String> {
        match self.input_ui.composer() {
            ComposerMode::Picker(picker) if picker.is_workflow() => {
                picker.selected_item().map(|item| item.value.clone())
            }
            _ => None,
        }
    }

    pub(super) async fn submit_workflow_selection(
        &mut self,
        value: &str,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        if value.starts_with("noop:") {
            return Ok(());
        }
        match value {
            "browse:plans" => self.open_workflow_plans(),
            "browse:workflows" => self.open_workflow_hub(),
            value if value.starts_with(UNSUPPORTED_PLAN_PREFIX) => {
                let id = value
                    .strip_prefix(UNSUPPORTED_PLAN_PREFIX)
                    .expect("prefix checked above");
                self.report_unsupported_record("plan", id);
                Ok(())
            }
            value if value.starts_with(UNSUPPORTED_RUN_PREFIX) => {
                let id = value
                    .strip_prefix(UNSUPPORTED_RUN_PREFIX)
                    .expect("prefix checked above");
                self.report_unsupported_record("run", id);
                Ok(())
            }
            // Enter on a workflow starts it. No extra menu.
            value if value.starts_with(SOURCE_PREFIX) => {
                let path = value
                    .strip_prefix(SOURCE_PREFIX)
                    .expect("prefix checked above");
                self.start_daemon_workflow_source(path, terminal).await
            }
            // Enter on a saved plan runs it.
            value if value.starts_with(PLAN_PREFIX) => {
                let id = value
                    .strip_prefix(PLAN_PREFIX)
                    .expect("prefix checked above");
                self.run_workflow_plan(id, terminal).await
            }
            // Retry is explicit; watching a ready run must never start a driver.
            value if value.starts_with(RETRY_RUN_PREFIX) => {
                let id = value
                    .strip_prefix(RETRY_RUN_PREFIX)
                    .expect("prefix checked above");
                let Some(run) = self.load_run_for_watch(id.parse()?)? else {
                    return Ok(());
                };
                // Inventory can be stale if another process started the run.
                if run.state.state.lifecycle != RunLifecycle::Planned {
                    self.open_workflow_hub()?;
                    self.set_status("run is no longer ready; refreshed workflows");
                    return Ok(());
                }
                self.resume_workflow_run(id, /*recover_uncertain*/ false, terminal)
                    .await
            }
            // Enter on a run opens the live screen or finished status.
            value if value.starts_with(RUN_PREFIX) => {
                let id = value
                    .strip_prefix(RUN_PREFIX)
                    .expect("prefix checked above");
                self.open_workflow_run_primary(id, terminal).await
            }
            other => {
                self.insert_entry(&Entry::Error(format!(
                    "unknown workflow selection '{other}'"
                )));
                self.set_status("workflow selection failed");
                Ok(())
            }
        }
    }

    pub(super) fn workflow_ops(&self) -> anyhow::Result<WorkflowOps> {
        let path = self.info.services.config_repository.configured_path().ok();
        // The TUI's sessions run in this process's environment (#1659).
        WorkflowOps::open(
            self.info.runtime.cwd.clone(),
            path,
            &crate::session_environment::SessionEnvironment::default(),
        )
    }

    async fn open_workflow_run_primary(
        &mut self,
        run_id: &str,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        let parsed = RunId::from_str(run_id)?;
        let Some(run) = self.load_run_for_watch(parsed)? else {
            return Ok(());
        };
        match run.state.state.lifecycle {
            // The daemon recovers the run once its prompt is through; the
            // rail and the hub open it from there.
            RunLifecycle::NeedsRecovery => {
                self.resume_workflow_run(run_id, /*recover_uncertain*/ true, terminal)
                    .await
            }
            RunLifecycle::Planned
            | RunLifecycle::Running
            | RunLifecycle::Cancelling
            | RunLifecycle::Completed => self.open_workflow_watch(run, terminal).await,
        }
    }

    /// Explains in the transcript why a record saved before scoped workflow
    /// programs cannot open here.
    fn report_unsupported_record(&mut self, kind: &'static str, id: &str) {
        self.input_ui.set_composer(ComposerMode::Input);
        self.insert_entry(&Entry::Error(
            WorkflowError::UnsupportedRecord {
                kind,
                id: id.to_owned(),
            }
            .to_string(),
        ));
        self.set_status("unsupported workflow record");
    }

    /// Loads a watch target by exact ID, reporting unreadable or replaced
    /// records in the transcript instead of leaving the TUI.
    pub(super) fn load_run_for_watch(
        &mut self,
        run_id: RunId,
    ) -> anyhow::Result<Option<StoredRun>> {
        match self.workflow_ops()?.load_run_id(run_id) {
            Ok(run) => Ok(Some(run)),
            Err(error) => {
                self.insert_entry(&Entry::Error(format!("could not load run: {error:#}")));
                self.set_status("open failed");
                Ok(None)
            }
        }
    }

    pub(super) async fn open_workflow_watch(
        &mut self,
        run: StoredRun,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        let run_id = run.manifest.run_id;
        self.input_ui.set_composer(ComposerMode::Input);
        let mut terminal_session = match self.terminal_session.take() {
            Some(session) => session,
            None => {
                self.insert_entry(&Entry::Error(
                    "terminal session is unavailable for workflow watch".into(),
                ));
                self.set_status("watch failed");
                return Ok(());
            }
        };
        let suspended = terminal_session
            .run_suspended(terminal, "Opening workflow watch…", || async move {
                workflow_cli::watch_run(run).await
            })
            .await;
        self.terminal_session = Some(terminal_session);
        self.program_status.invalidate();

        if let Err(resume_error) = suspended.resume_result {
            self.insert_entry(&Entry::Error(format!(
                "could not return to chat after workflow watch: {resume_error:#}"
            )));
            if let Err(operation_error) = suspended.operation_result {
                self.insert_entry(&Entry::Error(format!(
                    "could not watch workflow: {operation_error:#}"
                )));
            }
            self.set_status("watch handoff failed");
            return Ok(());
        }
        self.ctrl_c_streak = 0;
        match suspended.operation_result {
            Ok(()) => {
                self.set_status(format!(
                    "left watch for run {}",
                    short_id(&run_id.to_string())
                ));
            }
            Err(error) => {
                self.insert_entry(&Entry::Error(format!(
                    "could not watch workflow: {error:#}"
                )));
                self.set_status("watch failed");
            }
        }
        Ok(())
    }

    async fn run_workflow_plan(
        &mut self,
        plan_id: &str,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        let command = discover::WorkflowLaunch::plan_command(PlanId::from_str(plan_id)?);
        self.launch_daemon_workflow(command, terminal).await
    }

    async fn resume_workflow_run(
        &mut self,
        run_id: &str,
        recover_uncertain: bool,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        let run_id = RunId::from_str(run_id)?;
        let command = discover::WorkflowLaunch::resume_command(run_id, recover_uncertain);
        self.launch_daemon_workflow(command, terminal).await
    }
}

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

#[cfg(test)]
fn test_source(label: &str, relative: &str) -> discover::DiscoveredWorkflow {
    discover::DiscoveredWorkflow {
        relative_path: relative.into(),
        label: label.into(),
    }
}