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")
}
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"),
)
}
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(())
}
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
}
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
}
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(());
};
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, false, terminal)
.await
}
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();
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 {
RunLifecycle::NeedsRecovery => {
self.resume_workflow_run(run_id, true, terminal)
.await
}
RunLifecycle::Planned
| RunLifecycle::Running
| RunLifecycle::Cancelling
| RunLifecycle::Completed => self.open_workflow_watch(run, terminal).await,
}
}
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");
}
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(),
}
}