Skip to main content

ironflow_cli/
output.rs

1//! Output formatting for table and JSON modes.
2//!
3//! Provides helpers to render API responses as either a UTF-8 styled
4//! terminal table (with colored status) or raw JSON.
5
6use std::io::{Write, stdout};
7
8use anyhow::Result;
9use chrono::{DateTime, Utc};
10use comfy_table::presets::UTF8_FULL;
11use comfy_table::{Cell, CellAlignment, Color, ContentArrangement, Table};
12use ironflow_sdk::client::ApiResponse;
13use ironflow_sdk::types::{
14    AccountState, AccountWindowResponse, AccountWindowStatus, ApiKeyResponse, ApiKeyScope,
15    ArtifactResponse, AuditLogEntry, ConcurrencyLimit, CreateApiKeyResponse, ExecutionPlanResponse,
16    KeyVersionsResponse, PlannedStepResponse, ProviderAccountResponse, RunDetailResponse,
17    RunResponse, RunStatus, ScopeEntry, SecretResponse, StatsHistoryResponse, StatsResponse,
18    StepResponse, StepStatus, UserGroupsResponse, UserResponse, WorkerRouting,
19    WorkflowDetailResponse, WorkflowSummary,
20};
21use serde::Serialize;
22use serde_json::to_string_pretty;
23use uuid::Uuid;
24
25mod cancel;
26mod pause;
27
28pub use cancel::cancelled_table;
29pub use pause::{paused_table, resumed_table, workflow_pause_table};
30
31/// Map a [`RunStatus`] to a terminal color.
32fn status_color(status: &RunStatus) -> Color {
33    match status {
34        RunStatus::Completed => Color::Green,
35        RunStatus::Failed => Color::Red,
36        RunStatus::Running => Color::Blue,
37        RunStatus::Pending => Color::Yellow,
38        RunStatus::Cancelled => Color::Grey,
39        RunStatus::AwaitingApproval => Color::Magenta,
40        RunStatus::Retrying => Color::Cyan,
41        RunStatus::Warning => Color::DarkYellow,
42        RunStatus::Sleeping => Color::DarkCyan,
43        RunStatus::Paused => Color::DarkMagenta,
44    }
45}
46
47/// Map a [`StepStatus`] to a terminal color.
48fn step_status_color(status: &StepStatus) -> Color {
49    match status {
50        StepStatus::Completed => Color::Green,
51        StepStatus::Failed => Color::Red,
52        StepStatus::Running => Color::Blue,
53        StepStatus::Pending => Color::Yellow,
54        StepStatus::Skipped => Color::Grey,
55        StepStatus::AwaitingApproval => Color::Magenta,
56        StepStatus::Rejected => Color::Red,
57    }
58}
59
60/// Format a [`DateTime`] as `YYYY-MM-DD HH:MM:SS`.
61fn format_datetime(dt: &DateTime<Utc>) -> String {
62    dt.format("%Y-%m-%d %H:%M:%S").to_string()
63}
64
65/// Format an optional [`DateTime`].
66fn format_optional_datetime(dt: &Option<DateTime<Utc>>) -> String {
67    dt.as_ref().map_or("-".to_string(), format_datetime)
68}
69
70/// Fraction of the original SLA window below which the countdown turns yellow.
71const SLA_WARNING_RATIO: f64 = 0.1;
72
73/// Format a countdown in seconds as a coarse duration.
74///
75/// `None` renders as `"-"` (no deadline), a non-positive count as `"expired"`.
76fn format_remaining_secs(remaining: Option<i64>) -> String {
77    let Some(remaining) = remaining else {
78        return "-".to_string();
79    };
80    if remaining <= 0 {
81        return "expired".to_string();
82    }
83
84    if remaining < 60 {
85        return format!("{remaining}s");
86    }
87
88    let minutes = remaining / 60;
89    if minutes < 60 {
90        let rest = remaining % 60;
91        return if rest == 0 {
92            format!("{minutes}m")
93        } else {
94            format!("{minutes}m {rest}s")
95        };
96    }
97
98    let hours = minutes / 60;
99    let rest = minutes % 60;
100    if rest == 0 {
101        format!("{hours}h")
102    } else {
103        format!("{hours}h {rest}m")
104    }
105}
106
107/// Colour for a countdown: red once expired, yellow in the last
108/// [`SLA_WARNING_RATIO`] of the window, plain otherwise.
109fn remaining_color(remaining: Option<i64>, window_secs: Option<i64>) -> Option<Color> {
110    let remaining = remaining?;
111    if remaining <= 0 {
112        return Some(Color::Red);
113    }
114
115    let window = window_secs?;
116    if window > 0 && (remaining as f64) < (window as f64) * SLA_WARNING_RATIO {
117        return Some(Color::Yellow);
118    }
119
120    None
121}
122
123/// Format the remaining SLA of an approval gate.
124///
125/// Returns `"-"` for a step without a deadline, `"expired"` once the countdown
126/// reaches zero, and a coarse duration (`"45s"`, `"12m 30s"`, `"1h 12m"`)
127/// otherwise.
128fn format_sla(step: &StepResponse) -> String {
129    format_remaining_secs(step.approval_seconds_remaining)
130}
131
132/// Colour of the SLA cell.
133///
134/// The window is derived from the gate's own timestamps (`started_at` to
135/// `approval_deadline_at`), so no configuration parsing is needed.
136fn sla_color(step: &StepResponse) -> Option<Color> {
137    let window = match (step.approval_deadline_at, step.started_at) {
138        (Some(deadline), Some(started)) => Some((deadline - started).num_seconds()),
139        _ => None,
140    };
141    remaining_color(step.approval_seconds_remaining, window)
142}
143
144/// Format milliseconds as a human-readable duration.
145fn format_duration_ms(ms: i64) -> String {
146    if ms < 1000 {
147        return format!("{ms}ms");
148    }
149    let secs = ms / 1000;
150    if secs < 60 {
151        return format!("{secs}s");
152    }
153    let mins = secs / 60;
154    let remaining_secs = secs % 60;
155    if mins < 60 {
156        return format!("{mins}m {remaining_secs}s");
157    }
158    let hours = mins / 60;
159    let remaining_mins = mins % 60;
160    format!("{hours}h {remaining_mins}m")
161}
162
163/// Create a base table with UTF-8 styling.
164fn base_table() -> Table {
165    let mut table = Table::new();
166    table
167        .load_preset(UTF8_FULL)
168        .set_content_arrangement(ContentArrangement::Dynamic);
169    table
170}
171
172/// Render a value as JSON or table into the given writer.
173///
174/// # Errors
175///
176/// Returns an error if JSON serialization or writing fails.
177pub fn render_output<W: Write, T: Serialize>(
178    writer: &mut W,
179    json_mode: bool,
180    value: &T,
181    table_fn: impl FnOnce() -> Table,
182) -> Result<()> {
183    if json_mode {
184        let json = to_string_pretty(value)?;
185        writeln!(writer, "{json}")?;
186    } else {
187        writeln!(writer, "{}", table_fn())?;
188    }
189    Ok(())
190}
191
192/// Convenience wrapper: render to stdout.
193///
194/// # Errors
195///
196/// Returns an error if JSON serialization or writing fails.
197pub fn print_output<T: Serialize>(
198    json_mode: bool,
199    value: &T,
200    table_fn: impl FnOnce() -> Table,
201) -> Result<()> {
202    render_output(&mut stdout().lock(), json_mode, value, table_fn)
203}
204
205/// Render a value as pretty JSON to stdout.
206///
207/// For commands whose output is a summary the CLI builds itself, with no
208/// table equivalent.
209///
210/// # Errors
211///
212/// Returns an error if JSON serialization or writing fails.
213pub fn print_json<T: Serialize>(value: &T) -> Result<()> {
214    let json = to_string_pretty(value)?;
215    writeln!(stdout().lock(), "{json}")?;
216    Ok(())
217}
218
219/// Render a list of runs as a table.
220/// Fraction of the cost cap above which the spend is highlighted.
221const COST_WARNING_RATIO: f64 = 0.8;
222
223/// Render a run's spend, with its cap when one is configured.
224///
225/// Without a cap this is the plain amount; with one it reads `$0.1800 / $2.00`.
226fn format_cost(cost_usd: f64, max_cost_usd: Option<f64>) -> String {
227    match max_cost_usd {
228        Some(cap) => format!("${cost_usd:.4} / ${cap:.2}"),
229        None => format!("${cost_usd:.4}"),
230    }
231}
232
233/// Highlight colour for a run's spend relative to its cap.
234///
235/// `None` means no highlight: either the run has no cap, or it is comfortably
236/// below it. Yellow past [`COST_WARNING_RATIO`] of the cap, red once the cap is
237/// reached. A zero cap has no meaningful ratio, so any spend counts as reached.
238fn cost_color(cost_usd: f64, max_cost_usd: Option<f64>) -> Option<Color> {
239    let cap = max_cost_usd?;
240
241    if cap <= 0.0 {
242        return (cost_usd > 0.0).then_some(Color::Red);
243    }
244
245    let ratio = cost_usd / cap;
246    if ratio >= 1.0 {
247        Some(Color::Red)
248    } else if ratio >= COST_WARNING_RATIO {
249        Some(Color::Yellow)
250    } else {
251        None
252    }
253}
254
255/// Build the table cell for a run's spend, highlighted when close to its cap.
256fn cost_cell(cost_usd: f64, max_cost_usd: Option<f64>) -> Cell {
257    let cell = Cell::new(format_cost(cost_usd, max_cost_usd));
258    match cost_color(cost_usd, max_cost_usd) {
259        Some(color) => cell.fg(color),
260        None => cell,
261    }
262}
263
264pub fn runs_table(runs: &[RunResponse]) -> Table {
265    let mut table = base_table();
266    table.set_header(vec![
267        "ID",
268        "Workflow",
269        "Status",
270        "Priority",
271        "Triggered by",
272        "Duration",
273        "Cost",
274        "Created",
275        "Started",
276    ]);
277
278    for run in runs {
279        let status_cell = Cell::new(run.status)
280            .fg(status_color(&run.status))
281            .set_alignment(CellAlignment::Center);
282
283        table.add_row(vec![
284            Cell::new(run.id.to_string().split('-').next().unwrap_or("")),
285            Cell::new(&run.workflow_name),
286            status_cell,
287            Cell::new(format_priority(run.priority)).set_alignment(CellAlignment::Right),
288            Cell::new(&run.created_by.label),
289            Cell::new(format_duration_ms(run.duration_ms)),
290            cost_cell(run.cost_usd, run.max_cost_usd),
291            Cell::new(format_datetime(&run.created_at)),
292            Cell::new(format_optional_datetime(&run.started_at)),
293        ]);
294    }
295
296    table
297}
298
299/// Render a single run detail as a table.
300pub fn run_detail_table(detail: &RunDetailResponse) -> Table {
301    let run = &detail.run;
302    let mut table = base_table();
303    table.set_header(vec!["Field", "Value"]);
304
305    let status_cell = Cell::new(run.status).fg(status_color(&run.status));
306
307    table.add_row(vec![Cell::new("ID"), Cell::new(run.id)]);
308    table.add_row(vec![Cell::new("Workflow"), Cell::new(&run.workflow_name)]);
309    table.add_row(vec![Cell::new("Status"), status_cell]);
310    table.add_row(vec![
311        Cell::new("Priority"),
312        Cell::new(format_priority(run.priority)),
313    ]);
314    table.add_row(vec![
315        Cell::new("Trigger"),
316        Cell::new(format!("{:?}", run.trigger)),
317    ]);
318    table.add_row(vec![
319        Cell::new("Triggered by"),
320        Cell::new(&run.created_by.label),
321    ]);
322    table.add_row(vec![
323        Cell::new("Duration"),
324        Cell::new(format_duration_ms(run.duration_ms)),
325    ]);
326    table.add_row(vec![
327        Cell::new("Cost"),
328        cost_cell(run.cost_usd, run.max_cost_usd),
329    ]);
330    table.add_row(vec![
331        Cell::new("Created"),
332        Cell::new(format_datetime(&run.created_at)),
333    ]);
334    table.add_row(vec![
335        Cell::new("Started"),
336        Cell::new(format_optional_datetime(&run.started_at)),
337    ]);
338    table.add_row(vec![
339        Cell::new("Completed"),
340        Cell::new(format_optional_datetime(&run.completed_at)),
341    ]);
342    table.add_row(vec![
343        Cell::new("Retries"),
344        Cell::new(format!("{}/{}", run.retry_count, run.max_retries)),
345    ]);
346
347    if !run.concurrency_limits.is_empty() {
348        table.add_row(vec![
349            Cell::new("Concurrency groups"),
350            Cell::new(format_concurrency_limits(&run.concurrency_limits)),
351        ]);
352    }
353
354    if !run.worker_tags.is_empty() {
355        table.add_row(vec![
356            Cell::new("Worker tags"),
357            Cell::new(run.worker_tags.join(", ")),
358        ]);
359    }
360
361    if let Some(warning) = detail.worker_routing.as_ref().and_then(routing_warning) {
362        table.add_row(vec![
363            Cell::new("Workers"),
364            Cell::new(warning).fg(Color::Yellow),
365        ]);
366    }
367
368    if let Some(ref kind) = run.capacity_wait_kind {
369        let resumes = format_optional_datetime(&run.scheduled_at);
370        let reason = format!("{kind}, resumes at {resumes}");
371        table.add_row(vec![
372            Cell::new("Waiting for capacity"),
373            Cell::new(reason).fg(Color::DarkCyan),
374        ]);
375    }
376
377    if let Some(ref error) = run.error {
378        table.add_row(vec![Cell::new("Error"), Cell::new(error).fg(Color::Red)]);
379    }
380
381    if let Some(ref output) = run.output {
382        table.add_row(vec![Cell::new("Output"), Cell::new(output)]);
383    }
384
385    if !detail.steps.is_empty() {
386        table.add_row(vec![
387            Cell::new("Steps"),
388            Cell::new(format!("{} step(s)", detail.steps.len())),
389        ]);
390    }
391
392    table
393}
394
395/// Render a run priority, or `-` when the server did not send one.
396fn format_priority(priority: Option<i32>) -> String {
397    priority.map_or_else(|| "-".to_string(), |p| p.to_string())
398}
399
400/// Explain why a queued run may not be picked, or `None` when an eligible
401/// worker was seen recently.
402fn routing_warning(routing: &WorkerRouting) -> Option<&'static str> {
403    if routing.seen_workers == 0 {
404        Some("No worker seen recently")
405    } else if routing.eligible_workers == 0 {
406        Some("No eligible worker seen: none registers this workflow with every required tag")
407    } else {
408        None
409    }
410}
411
412/// List the concurrency groups of a run as `group (limit)`, comma separated.
413fn format_concurrency_limits(limits: &[ConcurrencyLimit]) -> String {
414    limits
415        .iter()
416        .map(|l| format!("{} ({})", l.group, l.limit))
417        .collect::<Vec<_>>()
418        .join(", ")
419}
420
421/// Summarize a step's artifacts as a count and a total size.
422///
423/// A dash when the step produced none, so the column stays scannable.
424fn format_artifacts(artifacts: &[ArtifactResponse]) -> String {
425    if artifacts.is_empty() {
426        return "-".to_string();
427    }
428
429    let total: i64 = artifacts.iter().map(|artifact| artifact.size_bytes).sum();
430    format!("{} ({})", artifacts.len(), format_bytes(total))
431}
432
433/// Human-readable file size, using 1024-based units.
434fn format_bytes(bytes: i64) -> String {
435    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
436
437    if bytes < 1024 {
438        return format!("{bytes} B");
439    }
440
441    let mut value = bytes as f64;
442    let mut unit = 0;
443    while value >= 1024.0 && unit < UNITS.len() - 1 {
444        value /= 1024.0;
445        unit += 1;
446    }
447
448    let decimals = if value < 10.0 { 1 } else { 0 };
449    format!("{value:.decimals$} {}", UNITS[unit])
450}
451
452/// Render a run's steps as a table.
453pub fn steps_table(steps: &[StepResponse]) -> Table {
454    let mut table = base_table();
455    table.set_header(vec![
456        "ID",
457        "Name",
458        "Status",
459        "SLA",
460        "Attempt",
461        "Duration",
462        "Cost",
463        "Artifacts",
464        "Started",
465        "Completed",
466    ]);
467
468    for step in steps {
469        let color = step_status_color(&step.status);
470
471        let mut sla = Cell::new(format_sla(step)).set_alignment(CellAlignment::Center);
472        if let Some(sla_fg) = sla_color(step) {
473            sla = sla.fg(sla_fg);
474        }
475
476        table.add_row(vec![
477            Cell::new(step.id.to_string().split('-').next().unwrap_or("")),
478            Cell::new(&step.name),
479            Cell::new(step.status)
480                .fg(color)
481                .set_alignment(CellAlignment::Center),
482            sla,
483            Cell::new(step.attempt).set_alignment(CellAlignment::Center),
484            Cell::new(format_duration_ms(step.duration_ms)),
485            Cell::new(format!("${:.4}", step.cost_usd)),
486            Cell::new(format_artifacts(&step.artifacts)).set_alignment(CellAlignment::Center),
487            Cell::new(format_optional_datetime(&step.started_at)),
488            Cell::new(format_optional_datetime(&step.completed_at)),
489        ]);
490    }
491
492    table
493}
494
495/// Render a list of workflows as a table.
496pub fn workflows_table(workflows: &[WorkflowSummary]) -> Table {
497    let mut table = base_table();
498    table.set_header(vec!["Name", "Category", "Version", "Paused since"]);
499
500    for wf in workflows {
501        table.add_row(vec![
502            Cell::new(&wf.name),
503            Cell::new(wf.category.as_deref().unwrap_or("-")),
504            Cell::new(wf.version.as_deref().unwrap_or("-")),
505            Cell::new(format_optional_datetime(&wf.paused_at)),
506        ]);
507    }
508
509    table
510}
511
512/// Render a workflow detail as a table.
513pub fn workflow_detail_table(detail: &WorkflowDetailResponse) -> Table {
514    let mut table = base_table();
515    table.set_header(vec!["Field", "Value"]);
516
517    table.add_row(vec![Cell::new("Name"), Cell::new(&detail.name)]);
518    table.add_row(vec![
519        Cell::new("Description"),
520        Cell::new(&detail.description),
521    ]);
522    table.add_row(vec![
523        Cell::new("Category"),
524        Cell::new(detail.category.as_deref().unwrap_or("-")),
525    ]);
526    table.add_row(vec![
527        Cell::new("Version"),
528        Cell::new(detail.version.as_deref().unwrap_or("-")),
529    ]);
530    if let Some(paused_at) = &detail.paused_at {
531        table.add_row(vec![
532            Cell::new("Paused since"),
533            Cell::new(format_datetime(paused_at)),
534        ]);
535    }
536
537    if !detail.sub_workflows.is_empty() {
538        let names: Vec<&str> = detail
539            .sub_workflows
540            .iter()
541            .map(|s| s.name.as_str())
542            .collect();
543        table.add_row(vec![
544            Cell::new("Sub-workflows"),
545            Cell::new(names.join(", ")),
546        ]);
547    }
548
549    table
550}
551
552/// Render an execution plan as an indented tree.
553///
554/// One line per step. Members of a parallel wave sit under a `parallel-N`
555/// header and are indented one extra level; sub-workflow steps are indented by
556/// their depth. A step carrying a condition shows why the planner took that
557/// branch.
558///
559/// # Examples
560///
561/// ```no_run
562/// use ironflow_cli::output::execution_plan_tree;
563/// use ironflow_sdk::types::ExecutionPlanResponse;
564///
565/// # fn example(plan: &ExecutionPlanResponse) {
566/// println!("{}", execution_plan_tree(plan));
567/// # }
568/// ```
569pub fn execution_plan_tree(plan: &ExecutionPlanResponse) -> String {
570    let mut lines = Vec::new();
571
572    let mut header = format!("workflow {}", plan.workflow);
573    if let Some(total) = plan.estimated_duration_ms {
574        header.push_str(&format!("  estimated ~{}", format_duration_ms(total)));
575    }
576    lines.push(header);
577
578    let mut current_group: Option<&str> = None;
579    for (index, step) in plan.steps.iter().enumerate() {
580        let group = step.parallel_group.as_deref();
581        if group != current_group {
582            if let Some(name) = group {
583                lines.push(format!("{}├─ {name}", indent(depth_of(step))));
584            }
585            current_group = group;
586        }
587
588        let extra = if group.is_some() { "  " } else { "" };
589        let branch = if is_last_at_depth(plan, index) {
590            "└─ "
591        } else {
592            "├─ "
593        };
594        lines.push(format!(
595            "{}{extra}{branch}{}",
596            indent(depth_of(step)),
597            step_label(step)
598        ));
599    }
600
601    if plan.truncated {
602        let reason = plan
603            .incomplete_reason
604            .as_deref()
605            .unwrap_or("the plan was cut short");
606        lines.push(format!("plan incomplete: {reason}"));
607    }
608
609    lines.join("\n")
610}
611
612/// Two spaces per sub-workflow level.
613fn indent(depth: usize) -> String {
614    "  ".repeat(depth)
615}
616
617/// Sub-workflow depth of a step as an indent level.
618fn depth_of(step: &PlannedStepResponse) -> usize {
619    usize::try_from(step.depth).unwrap_or(0)
620}
621
622/// Whether no later step sits at the same depth, making this the last branch.
623fn is_last_at_depth(plan: &ExecutionPlanResponse, index: usize) -> bool {
624    let depth = plan.steps[index].depth;
625    !plan.steps[index + 1..].iter().any(|s| s.depth == depth)
626}
627
628/// `name [kind] ~duration (condition)` for one planned step.
629fn step_label(step: &PlannedStepResponse) -> String {
630    let mut label = format!("{} [{}]", step.name, step.kind);
631
632    if let Some(ms) = step.estimated_duration_ms {
633        label.push_str(&format!(" ~{}", format_duration_ms(ms)));
634    }
635
636    if let Some(condition) = &step.condition {
637        let suffix = match condition.state.as_str() {
638            "evaluated" => format!(
639                " (when {} = {})",
640                condition.expression.as_deref().unwrap_or("?"),
641                condition.value.unwrap_or(false)
642            ),
643            "skipped" => format!(
644                " (skipped: {})",
645                condition.reason.as_deref().unwrap_or("no reason given")
646            ),
647            _ => format!(
648                " (condition unevaluable: {})",
649                condition.expression.as_deref().unwrap_or("?")
650            ),
651        };
652        label.push_str(&suffix);
653    }
654
655    label
656}
657
658/// Print an execution plan as JSON or as a tree.
659///
660/// # Errors
661///
662/// Returns an error if serialization or writing fails.
663pub fn render_execution_plan<W: Write>(
664    writer: &mut W,
665    json_mode: bool,
666    response: &ApiResponse<ExecutionPlanResponse>,
667) -> Result<()> {
668    if json_mode {
669        let json = to_string_pretty(response)?;
670        writeln!(writer, "{json}")?;
671    } else {
672        writeln!(writer, "{}", execution_plan_tree(&response.data))?;
673    }
674    Ok(())
675}
676
677/// Render stats as a table.
678pub fn stats_table(stats: &StatsResponse) -> Table {
679    let mut table = base_table();
680    table.set_header(vec!["Metric", "Value"]);
681
682    table.add_row(vec![Cell::new("Total runs"), Cell::new(stats.total_runs)]);
683    table.add_row(vec![
684        Cell::new("Completed"),
685        Cell::new(stats.completed_runs).fg(Color::Green),
686    ]);
687    table.add_row(vec![
688        Cell::new("Failed"),
689        Cell::new(stats.failed_runs).fg(Color::Red),
690    ]);
691    table.add_row(vec![
692        Cell::new("Cancelled"),
693        Cell::new(stats.cancelled_runs).fg(Color::Grey),
694    ]);
695    table.add_row(vec![
696        Cell::new("Active"),
697        Cell::new(stats.active_runs).fg(Color::Blue),
698    ]);
699    table.add_row(vec![
700        Cell::new("Awaiting approval"),
701        Cell::new(stats.awaiting_approval_runs).fg(Color::Magenta),
702    ]);
703    table.add_row(vec![
704        Cell::new("Success rate"),
705        Cell::new(format!("{:.1}%", stats.success_rate_percent)),
706    ]);
707    table.add_row(vec![
708        Cell::new("Total cost"),
709        Cell::new(format!("${:.4}", stats.total_cost_usd)),
710    ]);
711    table.add_row(vec![
712        Cell::new("Total duration"),
713        Cell::new(format_duration_ms(stats.total_duration_ms)),
714    ]);
715
716    table
717}
718
719/// Render historical stats as a table.
720pub fn stats_history_table(history: &StatsHistoryResponse) -> Table {
721    let mut table = base_table();
722    table.set_header(vec![
723        "Time",
724        "Completed",
725        "Warning",
726        "Failed",
727        "Cancelled",
728        "Active",
729        "Success %",
730        "Avg (ms)",
731        "P95 (ms)",
732        "Cost",
733    ]);
734
735    for bucket in &history.buckets {
736        let active = bucket.pending
737            + bucket.running
738            + bucket.retrying
739            + bucket.awaiting_approval
740            + bucket.sleeping
741            + bucket.paused;
742        table.add_row(vec![
743            Cell::new(bucket.time),
744            Cell::new(bucket.completed).fg(Color::Green),
745            Cell::new(bucket.warning).fg(Color::Yellow),
746            Cell::new(bucket.failed).fg(Color::Red),
747            Cell::new(bucket.cancelled).fg(Color::Grey),
748            Cell::new(active).fg(Color::Blue),
749            Cell::new(format_success_rate(bucket.success_rate_percent)),
750            Cell::new(bucket.avg_duration_ms),
751            Cell::new(bucket.p95_duration_ms),
752            Cell::new(format!("${:.4}", bucket.total_cost_usd)),
753        ]);
754    }
755
756    table
757}
758
759/// Render an optional success rate: `-` when the bucket has no finished run.
760fn format_success_rate(rate: Option<f64>) -> String {
761    rate.map_or_else(|| "-".to_string(), |r| format!("{r:.1}%"))
762}
763
764/// Render a list of key versions as a comma-separated string.
765fn format_versions(versions: &[i32]) -> String {
766    if versions.is_empty() {
767        return "-".to_string();
768    }
769    versions
770        .iter()
771        .map(|v| v.to_string())
772        .collect::<Vec<_>>()
773        .join(", ")
774}
775
776/// Outcome of a `delete` command.
777///
778/// The API answers `204 No Content`, which serializes to nothing useful, so the
779/// CLI reports the deletion itself and keeps `--json` machine-readable.
780///
781/// # Examples
782///
783/// ```
784/// use ironflow_cli::output::Deleted;
785///
786/// let deleted = Deleted::new("secret", "db/password");
787/// assert_eq!(deleted.kind, "secret");
788/// ```
789#[derive(Debug, Serialize)]
790pub struct Deleted {
791    /// What was deleted (`secret`, `api-key`, `user`).
792    pub kind: &'static str,
793    /// Identifier of the deleted resource.
794    pub id: String,
795    /// Always `true`; present so consumers can match on a stable shape.
796    pub deleted: bool,
797}
798
799impl Deleted {
800    /// Build a deletion report.
801    pub fn new(kind: &'static str, id: impl Into<String>) -> Self {
802        Self {
803            kind,
804            id: id.into(),
805            deleted: true,
806        }
807    }
808}
809
810/// Render a deletion report as a table.
811pub fn deleted_table(deleted: &Deleted) -> Table {
812    let mut table = base_table();
813    table.set_header(vec!["Deleted", "ID"]);
814    table.add_row(vec![Cell::new(deleted.kind), Cell::new(&deleted.id)]);
815    table
816}
817
818/// Report a deletion on stdout, as a table or as JSON.
819///
820/// # Errors
821///
822/// Returns an error if JSON serialization or writing fails.
823///
824/// # Examples
825///
826/// ```no_run
827/// use ironflow_cli::output::report_deletion;
828///
829/// # fn example() -> anyhow::Result<()> {
830/// report_deletion(false, "secret", "db/password")?;
831/// # Ok(())
832/// # }
833/// ```
834pub fn report_deletion(json_mode: bool, kind: &'static str, id: impl Into<String>) -> Result<()> {
835    let deleted = Deleted::new(kind, id);
836    print_output(json_mode, &deleted, || deleted_table(&deleted))
837}
838
839/// Render a list of secrets as a table.
840///
841/// [`SecretResponse`] carries no value field, so no secret material can reach
842/// this table by construction.
843pub fn secrets_table(secrets: &[SecretResponse]) -> Table {
844    let mut table = base_table();
845    table.set_header(vec!["Key", "Created", "Updated"]);
846
847    for secret in secrets {
848        table.add_row(vec![
849            Cell::new(&secret.key),
850            Cell::new(format_datetime(&secret.created_at)),
851            Cell::new(format_datetime(&secret.updated_at)),
852        ]);
853    }
854
855    table
856}
857
858/// Utilization of the unscoped window `name`, as a percentage, `-` when absent.
859fn window_percent(windows: &[AccountWindowResponse], name: &str) -> String {
860    windows
861        .iter()
862        .find(|w| w.window == name && w.model_scope.is_none())
863        .map_or_else(
864            || "-".to_string(),
865            |w| format!("{:.0}%", w.utilization * 100.0),
866        )
867}
868
869/// Colour of an account state.
870fn account_state_color(state: &AccountState) -> Color {
871    match state {
872        AccountState::Ok => Color::Green,
873        AccountState::NearLimit => Color::Yellow,
874        AccountState::Limited | AccountState::TokenInvalid => Color::Red,
875        AccountState::NeverUsed => Color::Grey,
876    }
877}
878
879/// Render Provider Accounts as a table. The credential is never part of the response.
880pub fn provider_accounts_table(accounts: &[ProviderAccountResponse]) -> Table {
881    let mut table = base_table();
882    table.set_header(vec![
883        "Name", "Kind", "State", "Enabled", "Priority", "Tags", "5h", "7d", "Expires",
884    ]);
885
886    for account in accounts {
887        table.add_row(vec![
888            Cell::new(&account.name),
889            Cell::new(&account.kind),
890            Cell::new(account.state.to_string()).fg(account_state_color(&account.state)),
891            Cell::new(if account.enabled { "yes" } else { "no" }),
892            Cell::new(account.priority).set_alignment(CellAlignment::Right),
893            Cell::new(account.tags.join(", ")),
894            Cell::new(window_percent(&account.windows, "five_hour"))
895                .set_alignment(CellAlignment::Right),
896            Cell::new(window_percent(&account.windows, "seven_day"))
897                .set_alignment(CellAlignment::Right),
898            Cell::new(format_datetime(&account.expires_at)),
899        ]);
900    }
901
902    table
903}
904
905/// Render the usage windows of one account as a table.
906pub fn provider_account_windows_table(windows: &[AccountWindowResponse]) -> Table {
907    let mut table = base_table();
908    table.set_header(vec![
909        "Window", "Scope", "Used", "Status", "Resets", "Observed",
910    ]);
911
912    for window in windows {
913        let color = match window.status {
914            AccountWindowStatus::Allowed => Color::Green,
915            AccountWindowStatus::AllowedWarning => Color::Yellow,
916            AccountWindowStatus::Rejected => Color::Red,
917        };
918        table.add_row(vec![
919            Cell::new(&window.window),
920            Cell::new(window.model_scope.as_deref().unwrap_or("-")),
921            Cell::new(format!("{:.0}%", window.utilization * 100.0))
922                .set_alignment(CellAlignment::Right),
923            Cell::new(window.status.to_string()).fg(color),
924            Cell::new(format_optional_datetime(&window.resets_at)),
925            Cell::new(format_datetime(&window.observed_at)),
926        ]);
927    }
928
929    table
930}
931
932/// Join the scopes of an API key into a single cell value.
933fn format_scopes(scopes: &[ApiKeyScope]) -> String {
934    scopes
935        .iter()
936        .map(ToString::to_string)
937        .collect::<Vec<_>>()
938        .join(", ")
939}
940
941/// Render the encryption key ring status as a table.
942pub fn key_versions_table(status: &KeyVersionsResponse) -> Table {
943    let mut table = base_table();
944    table.set_header(vec!["Property", "Versions"]);
945
946    table.add_row(vec![
947        Cell::new("Active"),
948        Cell::new(status.active).fg(Color::Green),
949    ]);
950    table.add_row(vec![
951        Cell::new("Configured"),
952        Cell::new(format_versions(&status.configured)),
953    ]);
954    table.add_row(vec![
955        Cell::new("In use"),
956        Cell::new(format_versions(&status.in_use)),
957    ]);
958    table.add_row(vec![
959        Cell::new("Missing"),
960        Cell::new(format_versions(&status.missing)).fg(if status.missing.is_empty() {
961            Color::Grey
962        } else {
963            Color::Red
964        }),
965    ]);
966    table.add_row(vec![
967        Cell::new("Retirable"),
968        Cell::new(format_versions(&status.retirable)).fg(if status.retirable.is_empty() {
969            Color::Grey
970        } else {
971            Color::Yellow
972        }),
973    ]);
974
975    table
976}
977
978/// Render a list of API keys as a table.
979///
980/// [`ApiKeyResponse`] never carries the raw key, only its prefix.
981pub fn api_keys_table(keys: &[ApiKeyResponse]) -> Table {
982    let mut table = base_table();
983    table.set_header(vec![
984        "ID",
985        "Name",
986        "Prefix",
987        "Scopes",
988        "Active",
989        "Rate limit",
990        "Last used",
991        "Expires",
992        "Created",
993    ]);
994
995    for key in keys {
996        let active = Cell::new(if key.is_active { "yes" } else { "no" })
997            .fg(if key.is_active {
998                Color::Green
999            } else {
1000                Color::Grey
1001            })
1002            .set_alignment(CellAlignment::Center);
1003
1004        let rate_limit = key
1005            .rate_limit_override
1006            .map(|v| v.to_string())
1007            .unwrap_or_else(|| "-".to_string());
1008
1009        table.add_row(vec![
1010            Cell::new(key.id),
1011            Cell::new(&key.name),
1012            Cell::new(&key.key_prefix),
1013            Cell::new(format_scopes(&key.scopes)),
1014            active,
1015            Cell::new(rate_limit),
1016            Cell::new(format_optional_datetime(&key.last_used_at)),
1017            Cell::new(format_optional_datetime(&key.expires_at)),
1018            Cell::new(format_datetime(&key.created_at)),
1019        ]);
1020    }
1021
1022    table
1023}
1024
1025/// Render a freshly created API key, including its one-time raw secret.
1026///
1027/// This is the only place the raw key is ever rendered: the API returns it once
1028/// at creation and never again, so withholding it would make the command
1029/// useless.
1030pub fn created_api_key_table(key: &CreateApiKeyResponse) -> Table {
1031    let mut table = base_table();
1032    table.set_header(vec!["Field", "Value"]);
1033
1034    table.add_row(vec![Cell::new("ID"), Cell::new(key.id)]);
1035    table.add_row(vec![Cell::new("Name"), Cell::new(&key.name)]);
1036    table.add_row(vec![
1037        Cell::new("Key"),
1038        Cell::new(&key.key).fg(Color::Yellow),
1039    ]);
1040    table.add_row(vec![Cell::new("Prefix"), Cell::new(&key.key_prefix)]);
1041    table.add_row(vec![
1042        Cell::new("Scopes"),
1043        Cell::new(format_scopes(&key.scopes)),
1044    ]);
1045    if let Some(override_val) = key.rate_limit_override {
1046        table.add_row(vec![
1047            Cell::new("Rate limit"),
1048            Cell::new(format!("{override_val} req/min")),
1049        ]);
1050    }
1051    table.add_row(vec![
1052        Cell::new("Expires"),
1053        Cell::new(format_optional_datetime(&key.expires_at)),
1054    ]);
1055    table.add_row(vec![
1056        Cell::new("Created"),
1057        Cell::new(format_datetime(&key.created_at)),
1058    ]);
1059
1060    table
1061}
1062
1063/// Render the available API key scopes as a table.
1064pub fn scopes_table(scopes: &[ScopeEntry]) -> Table {
1065    let mut table = base_table();
1066    table.set_header(vec!["Value", "Label", "Description"]);
1067
1068    for scope in scopes {
1069        table.add_row(vec![
1070            Cell::new(&scope.value),
1071            Cell::new(&scope.label),
1072            Cell::new(&scope.description),
1073        ]);
1074    }
1075
1076    table
1077}
1078
1079/// Render a list of users as a table.
1080pub fn users_table(users: &[UserResponse]) -> Table {
1081    let mut table = base_table();
1082    table.set_header(vec!["ID", "Username", "Email", "Admin", "Created"]);
1083
1084    for user in users {
1085        let admin = Cell::new(if user.is_admin { "yes" } else { "no" })
1086            .fg(if user.is_admin {
1087                Color::Magenta
1088            } else {
1089                Color::Grey
1090            })
1091            .set_alignment(CellAlignment::Center);
1092
1093        table.add_row(vec![
1094            Cell::new(user.id),
1095            Cell::new(&user.username),
1096            Cell::new(&user.email),
1097            admin,
1098            Cell::new(format_datetime(&user.created_at)),
1099        ]);
1100    }
1101
1102    table
1103}
1104
1105/// Render a user's group memberships.
1106pub fn user_groups_table(resp: &UserGroupsResponse) -> Table {
1107    let mut table = base_table();
1108    table.set_header(vec!["User ID", "Groups"]);
1109
1110    let groups = if resp.groups.is_empty() {
1111        "-".to_string()
1112    } else {
1113        resp.groups.join(", ")
1114    };
1115    table.add_row(vec![Cell::new(resp.user_id), Cell::new(groups)]);
1116
1117    table
1118}
1119
1120/// Render a side-by-side comparison of two runs of the same workflow.
1121pub fn run_diff_table(a: &RunDetailResponse, b: &RunDetailResponse) -> Table {
1122    let (ra, rb) = (&a.run, &b.run);
1123    let mut table = base_table();
1124    table.set_header(vec![
1125        "Field",
1126        &format!("Run {}", short_id(ra.id)),
1127        &format!("Run {}", short_id(rb.id)),
1128    ]);
1129
1130    let row = |f: &str, va: String, vb: String| -> Vec<Cell> {
1131        let hl = va != vb;
1132        vec![
1133            Cell::new(f),
1134            if hl {
1135                Cell::new(&va).fg(Color::Yellow)
1136            } else {
1137                Cell::new(&va)
1138            },
1139            if hl {
1140                Cell::new(&vb).fg(Color::Yellow)
1141            } else {
1142                Cell::new(&vb)
1143            },
1144        ]
1145    };
1146
1147    table.add_row(row("Status", ra.status.to_string(), rb.status.to_string()));
1148    table.add_row(row(
1149        "Duration",
1150        format_duration_ms(ra.duration_ms),
1151        format_duration_ms(rb.duration_ms),
1152    ));
1153    table.add_row(row(
1154        "Cost",
1155        format_cost(ra.cost_usd, ra.max_cost_usd),
1156        format_cost(rb.cost_usd, rb.max_cost_usd),
1157    ));
1158    table.add_row(row(
1159        "Started",
1160        format_optional_datetime(&ra.started_at),
1161        format_optional_datetime(&rb.started_at),
1162    ));
1163    table.add_row(row(
1164        "Completed",
1165        format_optional_datetime(&ra.completed_at),
1166        format_optional_datetime(&rb.completed_at),
1167    ));
1168    table.add_row(row(
1169        "Error",
1170        ra.error.clone().unwrap_or("-".into()),
1171        rb.error.clone().unwrap_or("-".into()),
1172    ));
1173    if a.payload != b.payload {
1174        table.add_row(row(
1175            "Payload",
1176            serde_json::to_string(&a.payload).unwrap_or_default(),
1177            serde_json::to_string(&b.payload).unwrap_or_default(),
1178        ));
1179    }
1180    for i in 0..a.steps.len().max(b.steps.len()) {
1181        let (sa, sb) = (a.steps.get(i), b.steps.get(i));
1182        let name = sa.or(sb).map(|s| s.name.as_str()).unwrap_or("-");
1183        table.add_row(row(
1184            &format!("{name} status"),
1185            sa.map(|s| s.status.to_string()).unwrap_or("-".into()),
1186            sb.map(|s| s.status.to_string()).unwrap_or("-".into()),
1187        ));
1188        table.add_row(row(
1189            &format!("{name} duration"),
1190            sa.map(|s| format_duration_ms(s.duration_ms))
1191                .unwrap_or("-".into()),
1192            sb.map(|s| format_duration_ms(s.duration_ms))
1193                .unwrap_or("-".into()),
1194        ));
1195        table.add_row(row(
1196            &format!("{name} cost"),
1197            sa.map(|s| format!("${:.4}", s.cost_usd))
1198                .unwrap_or("-".into()),
1199            sb.map(|s| format!("${:.4}", s.cost_usd))
1200                .unwrap_or("-".into()),
1201        ));
1202    }
1203    table
1204}
1205
1206/// Render a UUID as its first hyphen-separated group, enough to spot a row.
1207fn short_id(id: Uuid) -> String {
1208    id.to_string()
1209        .split('-')
1210        .next()
1211        .unwrap_or_default()
1212        .to_string()
1213}
1214
1215/// Render a UUID as a short prefix, or `-` when absent.
1216fn format_optional_id(id: &Option<Uuid>) -> String {
1217    id.map_or_else(|| "-".to_string(), short_id)
1218}
1219
1220/// Render a list of audit log entries as a table.
1221///
1222/// The event payload is omitted: it is arbitrary JSON that would wreck the
1223/// table layout. Use `--json` to get it.
1224pub fn audit_logs_table(entries: &[AuditLogEntry]) -> Table {
1225    let mut table = base_table();
1226    table.set_header(vec!["ID", "Type", "Run", "Step", "User", "Created"]);
1227
1228    for entry in entries {
1229        table.add_row(vec![
1230            Cell::new(short_id(entry.id)),
1231            Cell::new(entry.event_type.to_string()),
1232            Cell::new(format_optional_id(&entry.run_id)),
1233            Cell::new(format_optional_id(&entry.step_id)),
1234            Cell::new(format_optional_id(&entry.user_id)),
1235            Cell::new(format_datetime(&entry.created_at)),
1236        ]);
1237    }
1238
1239    table
1240}
1241
1242#[cfg(test)]
1243mod tests {
1244    use std::collections::HashMap;
1245    use std::slice;
1246
1247    use ironflow_sdk::types::{
1248        ApiKeyScope, ConditionResponse, CreatedBy, CreatedByKind, EventKind, TriggerKind,
1249    };
1250    use serde_json::{Map, Value, json};
1251
1252    use super::*;
1253
1254    /// Minimal run whose only meaningful field is its author.
1255    fn run_fixture(created_by: CreatedBy) -> RunResponse {
1256        let now = Utc::now();
1257        RunResponse {
1258            id: Uuid::now_v7(),
1259            workflow_name: "deploy".to_string(),
1260            status: RunStatus::Completed,
1261            trigger: TriggerKind::Api,
1262            error: None,
1263            retry_count: 0,
1264            max_retries: 0,
1265            cost_usd: 0.0,
1266            duration_ms: 0,
1267            created_at: now,
1268            updated_at: now,
1269            started_at: None,
1270            completed_at: None,
1271            handler_version: None,
1272            labels: HashMap::new(),
1273            scheduled_at: None,
1274            capacity_wait_kind: None,
1275            resume_status: None,
1276            created_by,
1277            idempotency_key: None,
1278            concurrency_key: None,
1279            priority: Some(0),
1280            concurrency_limits: Vec::new(),
1281            max_cost_usd: None,
1282            output: None,
1283            worker_tags: Vec::new(),
1284        }
1285    }
1286
1287    #[test]
1288    fn format_success_rate_renders_dash_when_absent() {
1289        assert_eq!(format_success_rate(None), "-");
1290    }
1291
1292    #[test]
1293    fn format_success_rate_renders_one_decimal() {
1294        assert_eq!(format_success_rate(Some(100.0)), "100.0%");
1295        assert_eq!(format_success_rate(Some(200.0 / 3.0)), "66.7%");
1296        assert_eq!(format_success_rate(Some(0.0)), "0.0%");
1297    }
1298
1299    #[test]
1300    fn format_cost_without_cap_shows_amount_only() {
1301        assert_eq!(format_cost(0.1234, None), "$0.1234");
1302    }
1303
1304    #[test]
1305    fn format_cost_with_cap_shows_both_amounts() {
1306        assert_eq!(format_cost(0.18, Some(2.0)), "$0.1800 / $2.00");
1307    }
1308
1309    #[test]
1310    fn cost_color_is_absent_without_a_cap() {
1311        assert_eq!(cost_color(999.0, None), None);
1312    }
1313
1314    #[test]
1315    fn cost_color_warns_past_the_threshold_and_alerts_at_the_cap() {
1316        assert_eq!(cost_color(1.0, Some(2.0)), None); // 50%
1317        assert_eq!(cost_color(1.6, Some(2.0)), Some(Color::Yellow)); // 80%
1318        assert_eq!(cost_color(1.99, Some(2.0)), Some(Color::Yellow));
1319        assert_eq!(cost_color(2.0, Some(2.0)), Some(Color::Red)); // at cap
1320        assert_eq!(cost_color(2.5, Some(2.0)), Some(Color::Red)); // over cap
1321    }
1322
1323    #[test]
1324    fn cost_color_handles_a_zero_cap() {
1325        assert_eq!(cost_color(0.0, Some(0.0)), None);
1326        assert_eq!(cost_color(0.01, Some(0.0)), Some(Color::Red));
1327    }
1328
1329    fn artifact(name: &str, size_bytes: i64) -> ArtifactResponse {
1330        ArtifactResponse {
1331            id: Uuid::now_v7(),
1332            step_id: Uuid::now_v7(),
1333            name: name.to_string(),
1334            content_type: "text/plain".to_string(),
1335            size_bytes,
1336            sha256: "0".repeat(64),
1337            created_at: Utc::now(),
1338        }
1339    }
1340
1341    #[test]
1342    fn format_bytes_keeps_raw_bytes_below_one_kilobyte() {
1343        assert_eq!(format_bytes(0), "0 B");
1344        assert_eq!(format_bytes(1023), "1023 B");
1345    }
1346
1347    #[test]
1348    fn format_bytes_switches_units_at_each_boundary() {
1349        assert_eq!(format_bytes(1024), "1.0 KB");
1350        assert_eq!(format_bytes(1024 * 1024), "1.0 MB");
1351        assert_eq!(format_bytes(1024 * 1024 * 1024), "1.0 GB");
1352    }
1353
1354    #[test]
1355    fn format_bytes_drops_the_decimal_past_ten() {
1356        assert_eq!(format_bytes(145_408), "142 KB");
1357    }
1358
1359    #[test]
1360    fn format_artifacts_shows_a_dash_when_there_are_none() {
1361        assert_eq!(format_artifacts(&[]), "-");
1362    }
1363
1364    #[test]
1365    fn format_artifacts_shows_the_count_and_total_size() {
1366        let artifacts = vec![artifact("a.txt", 1024), artifact("b.txt", 1024)];
1367        assert_eq!(format_artifacts(&artifacts), "2 (2.0 KB)");
1368    }
1369
1370    #[test]
1371    fn format_duration_ms_millis() {
1372        assert_eq!(format_duration_ms(500), "500ms");
1373        assert_eq!(format_duration_ms(0), "0ms");
1374    }
1375
1376    #[test]
1377    fn format_duration_ms_seconds() {
1378        assert_eq!(format_duration_ms(5000), "5s");
1379        assert_eq!(format_duration_ms(59000), "59s");
1380    }
1381
1382    #[test]
1383    fn format_duration_ms_minutes() {
1384        assert_eq!(format_duration_ms(60000), "1m 0s");
1385        assert_eq!(format_duration_ms(125000), "2m 5s");
1386    }
1387
1388    #[test]
1389    fn format_duration_ms_hours() {
1390        assert_eq!(format_duration_ms(3_600_000), "1h 0m");
1391        assert_eq!(format_duration_ms(5_400_000), "1h 30m");
1392    }
1393
1394    #[test]
1395    fn format_sla_without_a_deadline_is_a_dash() {
1396        assert_eq!(format_remaining_secs(None), "-");
1397    }
1398
1399    #[test]
1400    fn format_sla_reports_an_elapsed_deadline_as_expired() {
1401        assert_eq!(format_remaining_secs(Some(0)), "expired");
1402        assert_eq!(format_remaining_secs(Some(-30)), "expired");
1403    }
1404
1405    #[test]
1406    fn format_sla_uses_coarse_units() {
1407        assert_eq!(format_remaining_secs(Some(45)), "45s");
1408        assert_eq!(format_remaining_secs(Some(59)), "59s");
1409        assert_eq!(format_remaining_secs(Some(60)), "1m");
1410        assert_eq!(format_remaining_secs(Some(750)), "12m 30s");
1411        assert_eq!(format_remaining_secs(Some(3599)), "59m 59s");
1412        assert_eq!(format_remaining_secs(Some(3600)), "1h");
1413        assert_eq!(format_remaining_secs(Some(4320)), "1h 12m");
1414    }
1415
1416    #[test]
1417    fn sla_has_no_colour_without_a_deadline() {
1418        assert_eq!(remaining_color(None, None), None);
1419        assert_eq!(remaining_color(None, Some(3600)), None);
1420    }
1421
1422    #[test]
1423    fn sla_turns_red_once_expired() {
1424        assert_eq!(remaining_color(Some(0), Some(3600)), Some(Color::Red));
1425        assert_eq!(remaining_color(Some(-1), None), Some(Color::Red));
1426    }
1427
1428    #[test]
1429    fn sla_turns_yellow_in_the_last_tenth_of_the_window() {
1430        assert_eq!(remaining_color(Some(359), Some(3600)), Some(Color::Yellow));
1431        assert_eq!(remaining_color(Some(360), Some(3600)), None);
1432        assert_eq!(remaining_color(Some(3000), Some(3600)), None);
1433    }
1434
1435    #[test]
1436    fn sla_has_no_colour_without_a_measurable_window() {
1437        assert_eq!(remaining_color(Some(120), None), None);
1438        assert_eq!(remaining_color(Some(120), Some(0)), None);
1439    }
1440
1441    #[test]
1442    fn format_optional_datetime_none() {
1443        assert_eq!(format_optional_datetime(&None), "-");
1444    }
1445
1446    #[test]
1447    fn format_optional_datetime_some() {
1448        let dt = "2026-06-02T14:30:00Z".parse::<DateTime<Utc>>().unwrap();
1449        assert_eq!(format_optional_datetime(&Some(dt)), "2026-06-02 14:30:00");
1450    }
1451
1452    #[test]
1453    fn status_colors_are_distinct() {
1454        let statuses = [
1455            RunStatus::Completed,
1456            RunStatus::Failed,
1457            RunStatus::Running,
1458            RunStatus::Pending,
1459            RunStatus::Cancelled,
1460            RunStatus::AwaitingApproval,
1461            RunStatus::Retrying,
1462        ];
1463
1464        let colors: Vec<Color> = statuses.iter().map(status_color).collect();
1465        for (i, c1) in colors.iter().enumerate() {
1466            for (j, c2) in colors.iter().enumerate() {
1467                if i != j {
1468                    assert_ne!(c1, c2, "status colors must be distinct");
1469                }
1470            }
1471        }
1472    }
1473
1474    #[test]
1475    fn empty_runs_table_has_header() {
1476        let table = runs_table(&[]);
1477        let output = table.to_string();
1478        assert!(output.contains("ID"));
1479        assert!(output.contains("Workflow"));
1480        assert!(output.contains("Status"));
1481        assert!(output.contains("Triggered by"));
1482        assert!(output.contains("Priority"));
1483    }
1484
1485    #[test]
1486    fn runs_table_renders_the_author_label() {
1487        let run = run_fixture(CreatedBy {
1488            kind: CreatedByKind::ApiKey,
1489            id: Some(Uuid::now_v7()),
1490            label: "ci-deploy (alice)".to_string(),
1491        });
1492
1493        let output = runs_table(slice::from_ref(&run)).to_string();
1494        assert!(
1495            output.contains("ci-deploy (alice)"),
1496            "author missing from:\n{output}"
1497        );
1498    }
1499
1500    #[test]
1501    fn format_priority_renders_the_value_or_a_dash() {
1502        assert_eq!(format_priority(Some(-40)), "-40");
1503        assert_eq!(format_priority(Some(0)), "0");
1504        assert_eq!(format_priority(None), "-");
1505    }
1506
1507    #[test]
1508    fn runs_table_renders_the_priority() {
1509        let mut run = run_fixture(CreatedBy {
1510            kind: CreatedByKind::System,
1511            id: None,
1512            label: "api".to_string(),
1513        });
1514        run.priority = Some(-73);
1515
1516        let output = runs_table(slice::from_ref(&run)).to_string();
1517        assert!(output.contains("-73"), "priority missing from:\n{output}");
1518    }
1519
1520    #[test]
1521    fn run_detail_table_shows_the_priority() {
1522        let mut run = run_fixture(CreatedBy {
1523            kind: CreatedByKind::System,
1524            id: None,
1525            label: "api".to_string(),
1526        });
1527        run.priority = Some(64);
1528        let detail = RunDetailResponse {
1529            run,
1530            steps: Vec::new(),
1531            payload: Value::Object(Map::new()),
1532            active_descendant_count: 0,
1533            worker_routing: None,
1534        };
1535
1536        let output = run_detail_table(&detail).to_string();
1537        assert!(output.contains("Priority"), "row missing from:\n{output}");
1538        assert!(output.contains("64"), "priority missing from:\n{output}");
1539    }
1540
1541    #[test]
1542    fn run_detail_table_renders_the_run_output() {
1543        let mut run = run_fixture(CreatedBy {
1544            kind: CreatedByKind::System,
1545            id: None,
1546            label: "cron".to_string(),
1547        });
1548        run.output = Some(json!({"verdict": "approved"}));
1549        let detail = RunDetailResponse {
1550            run,
1551            steps: Vec::new(),
1552            payload: Value::Object(Map::new()),
1553            active_descendant_count: 0,
1554            worker_routing: None,
1555        };
1556
1557        let output = run_detail_table(&detail).to_string();
1558        assert!(
1559            output.contains("Output"),
1560            "output row missing from:\n{output}"
1561        );
1562        assert!(output.contains(r#"{"verdict":"approved"}"#), "{output}");
1563    }
1564
1565    #[test]
1566    fn run_detail_table_has_no_output_row_without_an_output() {
1567        let detail = RunDetailResponse {
1568            run: run_fixture(CreatedBy {
1569                kind: CreatedByKind::System,
1570                id: None,
1571                label: "cron".to_string(),
1572            }),
1573            steps: Vec::new(),
1574            payload: Value::Object(Map::new()),
1575            active_descendant_count: 0,
1576            worker_routing: None,
1577        };
1578
1579        let output = run_detail_table(&detail).to_string();
1580        assert!(!output.contains("Output"), "{output}");
1581    }
1582
1583    #[test]
1584    fn run_detail_table_renders_the_author_label() {
1585        let detail = RunDetailResponse {
1586            run: run_fixture(CreatedBy {
1587                kind: CreatedByKind::System,
1588                id: None,
1589                label: "/hooks/github".to_string(),
1590            }),
1591            steps: Vec::new(),
1592            payload: Value::Object(Map::new()),
1593            active_descendant_count: 0,
1594            worker_routing: None,
1595        };
1596
1597        let output = run_detail_table(&detail).to_string();
1598        assert!(output.contains("Triggered by"));
1599        assert!(
1600            output.contains("/hooks/github"),
1601            "author missing from:\n{output}"
1602        );
1603    }
1604
1605    #[test]
1606    fn format_concurrency_limits_lists_each_group_with_its_limit() {
1607        let limits = [
1608            ConcurrencyLimit {
1609                group: "repo:acme".to_string(),
1610                limit: 2,
1611            },
1612            ConcurrencyLimit {
1613                group: "tenant:42".to_string(),
1614                limit: 1,
1615            },
1616        ];
1617        assert_eq!(
1618            format_concurrency_limits(&limits),
1619            "repo:acme (2), tenant:42 (1)"
1620        );
1621    }
1622
1623    #[test]
1624    fn run_detail_table_shows_concurrency_groups_only_when_present() {
1625        let mut detail = RunDetailResponse {
1626            run: run_fixture(CreatedBy {
1627                kind: CreatedByKind::System,
1628                id: None,
1629                label: "api".to_string(),
1630            }),
1631            steps: Vec::new(),
1632            payload: Value::Object(Map::new()),
1633            active_descendant_count: 0,
1634            worker_routing: None,
1635        };
1636        let output = run_detail_table(&detail).to_string();
1637        assert!(
1638            !output.contains("Concurrency groups"),
1639            "unexpected row in:\n{output}"
1640        );
1641
1642        detail.run.concurrency_limits = vec![ConcurrencyLimit {
1643            group: "repo:acme".to_string(),
1644            limit: 2,
1645        }];
1646        let output = run_detail_table(&detail).to_string();
1647        assert!(
1648            output.contains("Concurrency groups"),
1649            "row missing from:\n{output}"
1650        );
1651        assert!(
1652            output.contains("repo:acme (2)"),
1653            "group missing from:\n{output}"
1654        );
1655    }
1656
1657    #[test]
1658    fn run_detail_table_shows_the_capacity_wait_only_when_waiting() {
1659        let mut detail = RunDetailResponse {
1660            run: run_fixture(CreatedBy {
1661                kind: CreatedByKind::System,
1662                id: None,
1663                label: "api".to_string(),
1664            }),
1665            steps: Vec::new(),
1666            payload: Value::Object(Map::new()),
1667            active_descendant_count: 0,
1668            worker_routing: None,
1669        };
1670        let output = run_detail_table(&detail).to_string();
1671        assert!(
1672            !output.contains("Waiting for capacity"),
1673            "unexpected row in:\n{output}"
1674        );
1675
1676        let wake_at = Utc::now();
1677        detail.run.status = RunStatus::Sleeping;
1678        detail.run.scheduled_at = Some(wake_at);
1679        detail.run.capacity_wait_kind = Some("claude_subscription".to_string());
1680        let output = run_detail_table(&detail).to_string();
1681        assert!(
1682            output.contains("Waiting for capacity"),
1683            "row missing from:\n{output}"
1684        );
1685        let expected = format!(
1686            "claude_subscription, resumes at {}",
1687            format_datetime(&wake_at)
1688        );
1689        assert!(
1690            output.contains(&expected),
1691            "{expected} missing from:\n{output}"
1692        );
1693    }
1694
1695    #[test]
1696    fn routing_warning_covers_each_case() {
1697        let none_seen = WorkerRouting {
1698            seen_workers: 0,
1699            eligible_workers: 0,
1700        };
1701        let warning = routing_warning(&none_seen);
1702        assert_eq!(warning, Some("No worker seen recently"));
1703
1704        let none_eligible = WorkerRouting {
1705            seen_workers: 3,
1706            eligible_workers: 0,
1707        };
1708        let warning = routing_warning(&none_eligible).expect("a warning");
1709        assert!(warning.starts_with("No eligible worker seen"), "{warning}");
1710
1711        let eligible = WorkerRouting {
1712            seen_workers: 3,
1713            eligible_workers: 1,
1714        };
1715        assert_eq!(routing_warning(&eligible), None);
1716    }
1717
1718    #[test]
1719    fn run_detail_table_shows_worker_tags_only_when_present() {
1720        let mut detail = RunDetailResponse {
1721            run: run_fixture(CreatedBy {
1722                kind: CreatedByKind::System,
1723                id: None,
1724                label: "api".to_string(),
1725            }),
1726            steps: Vec::new(),
1727            payload: Value::Object(Map::new()),
1728            active_descendant_count: 0,
1729            worker_routing: None,
1730        };
1731        let output = run_detail_table(&detail).to_string();
1732        assert!(
1733            !output.contains("Worker tags"),
1734            "unexpected row in:\n{output}"
1735        );
1736
1737        detail.run.worker_tags = vec!["gpu".to_string(), "region:eu".to_string()];
1738        let output = run_detail_table(&detail).to_string();
1739        assert!(
1740            output.contains("Worker tags"),
1741            "row missing from:\n{output}"
1742        );
1743        assert!(
1744            output.contains("gpu, region:eu"),
1745            "tags missing from:\n{output}"
1746        );
1747    }
1748
1749    #[test]
1750    fn run_detail_table_warns_when_no_worker_can_take_the_run() {
1751        let mut detail = RunDetailResponse {
1752            run: run_fixture(CreatedBy {
1753                kind: CreatedByKind::System,
1754                id: None,
1755                label: "api".to_string(),
1756            }),
1757            steps: Vec::new(),
1758            payload: Value::Object(Map::new()),
1759            active_descendant_count: 0,
1760            worker_routing: None,
1761        };
1762        let output = run_detail_table(&detail).to_string();
1763        assert!(!output.contains("Workers"), "unexpected row in:\n{output}");
1764
1765        detail.worker_routing = Some(WorkerRouting {
1766            seen_workers: 2,
1767            eligible_workers: 1,
1768        });
1769        let output = run_detail_table(&detail).to_string();
1770        assert!(!output.contains("Workers"), "unexpected row in:\n{output}");
1771
1772        detail.worker_routing = Some(WorkerRouting {
1773            seen_workers: 2,
1774            eligible_workers: 0,
1775        });
1776        let output = run_detail_table(&detail).to_string();
1777        assert!(output.contains("Workers"), "row missing from:\n{output}");
1778        assert!(
1779            output.contains("No eligible worker seen"),
1780            "warning missing from:\n{output}"
1781        );
1782    }
1783
1784    #[test]
1785    fn empty_workflows_table_has_header() {
1786        let table = workflows_table(&[]);
1787        let output = table.to_string();
1788        assert!(output.contains("Name"));
1789        assert!(output.contains("Category"));
1790        assert!(output.contains("Paused since"));
1791    }
1792
1793    // ── Secrets ────────────────────────────────────────────────
1794
1795    fn secret_fixture(key: &str) -> SecretResponse {
1796        let now = Utc::now();
1797        SecretResponse {
1798            id: Uuid::now_v7(),
1799            key: key.to_string(),
1800            created_at: now,
1801            updated_at: now,
1802        }
1803    }
1804
1805    #[test]
1806    fn empty_secrets_table_has_header() {
1807        let output = secrets_table(&[]).to_string();
1808        assert!(output.contains("Key"));
1809        assert!(output.contains("Created"));
1810        assert!(output.contains("Updated"));
1811    }
1812
1813    #[test]
1814    fn secrets_table_renders_the_key() {
1815        let secret = secret_fixture("workflows/inbox/gmail_token");
1816        let output = secrets_table(slice::from_ref(&secret)).to_string();
1817        assert!(output.contains("workflows/inbox/gmail_token"), "{output}");
1818    }
1819
1820    /// The value never even reaches this layer: `SecretResponse` has no such
1821    /// field. Rendering it as JSON proves the whole payload is value-free.
1822    #[test]
1823    fn a_secret_response_carries_no_value_at_all() {
1824        let secret = secret_fixture("db/password");
1825        let json = serde_json::to_string(&secret).unwrap();
1826        assert!(!json.contains("value"), "{json}");
1827    }
1828
1829    // ── API keys ───────────────────────────────────────────────
1830
1831    fn api_key_fixture() -> ApiKeyResponse {
1832        ApiKeyResponse {
1833            id: Uuid::now_v7(),
1834            name: "ci-deploy".to_string(),
1835            key_prefix: "ifk_abcd".to_string(),
1836            scopes: vec![ApiKeyScope::RunsRead, ApiKeyScope::RunsWrite],
1837            is_active: true,
1838            created_at: Utc::now(),
1839            expires_at: None,
1840            last_used_at: None,
1841            rate_limit_override: None,
1842        }
1843    }
1844
1845    #[test]
1846    fn empty_api_keys_table_has_header() {
1847        let output = api_keys_table(&[]).to_string();
1848        for header in ["ID", "Name", "Prefix", "Scopes", "Active"] {
1849            assert!(output.contains(header), "missing {header} in {output}");
1850        }
1851    }
1852
1853    #[test]
1854    fn api_keys_table_joins_the_scopes() {
1855        let key = api_key_fixture();
1856        let output = api_keys_table(slice::from_ref(&key)).to_string();
1857        assert!(output.contains("runs_read, runs_write"), "{output}");
1858        assert!(output.contains("ifk_abcd"), "{output}");
1859    }
1860
1861    #[test]
1862    fn created_api_key_table_shows_the_raw_key() {
1863        let created = CreateApiKeyResponse {
1864            id: Uuid::now_v7(),
1865            name: "ci-deploy".to_string(),
1866            key: "ifk_full_raw_key".to_string(),
1867            key_prefix: "ifk_full".to_string(),
1868            scopes: vec![ApiKeyScope::Admin],
1869            created_at: Utc::now(),
1870            expires_at: None,
1871            rate_limit_override: None,
1872        };
1873
1874        let output = created_api_key_table(&created).to_string();
1875        assert!(output.contains("ifk_full_raw_key"), "{output}");
1876    }
1877
1878    #[test]
1879    fn empty_scopes_table_has_header() {
1880        let output = scopes_table(&[]).to_string();
1881        assert!(output.contains("Value"));
1882        assert!(output.contains("Description"));
1883    }
1884
1885    // ── Users ──────────────────────────────────────────────────
1886
1887    fn user_fixture(is_admin: bool) -> UserResponse {
1888        let now = Utc::now();
1889        UserResponse {
1890            id: Uuid::now_v7(),
1891            username: "alice".to_string(),
1892            email: "alice@example.com".to_string(),
1893            is_admin,
1894            created_at: now,
1895            updated_at: now,
1896        }
1897    }
1898
1899    #[test]
1900    fn empty_users_table_has_header() {
1901        let output = users_table(&[]).to_string();
1902        for header in ["ID", "Username", "Email", "Admin", "Created"] {
1903            assert!(output.contains(header), "missing {header} in {output}");
1904        }
1905    }
1906
1907    #[test]
1908    fn users_table_spells_out_the_role() {
1909        let admin = user_fixture(true);
1910        assert!(
1911            users_table(slice::from_ref(&admin))
1912                .to_string()
1913                .contains("yes")
1914        );
1915
1916        let member = user_fixture(false);
1917        assert!(
1918            users_table(slice::from_ref(&member))
1919                .to_string()
1920                .contains("no")
1921        );
1922    }
1923
1924    #[test]
1925    fn user_groups_table_has_header_and_lists_the_groups() {
1926        let resp = UserGroupsResponse {
1927            user_id: Uuid::now_v7(),
1928            groups: vec!["finance".to_string(), "sre".to_string()],
1929        };
1930        let output = user_groups_table(&resp).to_string();
1931        for header in ["User ID", "Groups"] {
1932            assert!(output.contains(header), "missing {header} in {output}");
1933        }
1934        assert!(output.contains(&resp.user_id.to_string()), "{output}");
1935        assert!(output.contains("finance, sre"), "{output}");
1936    }
1937
1938    #[test]
1939    fn user_groups_table_shows_a_dash_without_groups() {
1940        let resp = UserGroupsResponse {
1941            user_id: Uuid::now_v7(),
1942            groups: Vec::new(),
1943        };
1944        let output = user_groups_table(&resp).to_string();
1945        assert!(output.contains("Groups"), "{output}");
1946        assert!(output.contains(" - "), "{output}");
1947        assert!(!output.contains("finance"), "{output}");
1948    }
1949
1950    // ── Audit logs ─────────────────────────────────────────────
1951
1952    #[test]
1953    fn empty_audit_logs_table_has_header() {
1954        let output = audit_logs_table(&[]).to_string();
1955        for header in ["ID", "Type", "Run", "Step", "User", "Created"] {
1956            assert!(output.contains(header), "missing {header} in {output}");
1957        }
1958    }
1959
1960    #[test]
1961    fn audit_logs_table_omits_the_payload() {
1962        let entry = AuditLogEntry {
1963            id: Uuid::now_v7(),
1964            event_type: EventKind::RunCreated,
1965            payload: Value::Object(Map::new()),
1966            run_id: Some(Uuid::now_v7()),
1967            step_id: None,
1968            user_id: None,
1969            created_at: Utc::now(),
1970        };
1971
1972        let output = audit_logs_table(slice::from_ref(&entry)).to_string();
1973        assert!(output.contains("run_created"), "{output}");
1974        // Absent IDs collapse to a dash rather than an empty cell.
1975        assert!(output.contains(" - "), "{output}");
1976    }
1977
1978    #[test]
1979    fn format_optional_id_shortens_and_falls_back() {
1980        assert_eq!(format_optional_id(&None), "-");
1981        let id = Uuid::now_v7();
1982        let short = format_optional_id(&Some(id));
1983        assert_eq!(short, id.to_string().split('-').next().unwrap());
1984    }
1985
1986    // ── Deletions ──────────────────────────────────────────────
1987
1988    #[test]
1989    fn deleted_table_reports_the_kind_and_id() {
1990        let deleted = Deleted::new("secret", "db/password");
1991        let output = deleted_table(&deleted).to_string();
1992        assert!(output.contains("secret"), "{output}");
1993        assert!(output.contains("db/password"), "{output}");
1994
1995        let json = serde_json::to_string(&deleted).unwrap();
1996        assert!(json.contains(r#""deleted":true"#), "{json}");
1997    }
1998
1999    // ── Execution plans ────────────────────────────────────────
2000
2001    fn planned_step(name: &str, kind: &str, parallel_group: Option<&str>) -> PlannedStepResponse {
2002        PlannedStepResponse {
2003            name: name.to_string(),
2004            kind: kind.to_string(),
2005            workflow: "deploy".to_string(),
2006            depth: 0,
2007            depends_on: Vec::new(),
2008            condition: None,
2009            parallel_group: parallel_group.map(str::to_string),
2010            estimated_duration_ms: None,
2011        }
2012    }
2013
2014    fn plan_fixture(steps: Vec<PlannedStepResponse>) -> ExecutionPlanResponse {
2015        ExecutionPlanResponse {
2016            workflow: "deploy".to_string(),
2017            steps,
2018            estimated_duration_ms: None,
2019            max_depth: 3,
2020            truncated: false,
2021            incomplete_reason: None,
2022        }
2023    }
2024
2025    #[test]
2026    fn execution_plan_tree_lists_step_names_and_kinds() {
2027        let plan = plan_fixture(vec![
2028            planned_step("build", "shell", None),
2029            planned_step("deploy", "shell", None),
2030        ]);
2031
2032        let output = execution_plan_tree(&plan);
2033        assert!(output.contains("workflow deploy"), "{output}");
2034        assert!(output.contains("build [shell]"), "{output}");
2035        assert!(output.contains("deploy [shell]"), "{output}");
2036    }
2037
2038    #[test]
2039    fn execution_plan_tree_prints_a_parallel_group_header_once() {
2040        let plan = plan_fixture(vec![
2041            planned_step("build", "shell", None),
2042            planned_step("test", "shell", Some("parallel-1")),
2043            planned_step("lint", "shell", Some("parallel-1")),
2044        ]);
2045
2046        let output = execution_plan_tree(&plan);
2047        assert_eq!(output.matches("parallel-1").count(), 1, "{output}");
2048    }
2049
2050    #[test]
2051    fn execution_plan_tree_shows_the_estimate_when_present() {
2052        let mut step = planned_step("build", "shell", None);
2053        step.estimated_duration_ms = Some(5000);
2054        let mut plan = plan_fixture(vec![step]);
2055        plan.estimated_duration_ms = Some(5000);
2056
2057        let output = execution_plan_tree(&plan);
2058        assert!(output.contains("estimated ~5s"), "{output}");
2059        assert!(output.contains("build [shell] ~5s"), "{output}");
2060    }
2061
2062    #[test]
2063    fn execution_plan_tree_marks_conditions() {
2064        let mut evaluated = planned_step("deploy-prod", "shell", None);
2065        evaluated.condition = Some(ConditionResponse {
2066            state: "evaluated".to_string(),
2067            expression: Some("env == prod".to_string()),
2068            value: Some(true),
2069            reason: None,
2070        });
2071        let mut skipped = planned_step("deploy-dev", "skip", None);
2072        skipped.condition = Some(ConditionResponse {
2073            state: "skipped".to_string(),
2074            expression: None,
2075            value: None,
2076            reason: Some("not prod".to_string()),
2077        });
2078        let mut unevaluable = planned_step("notify", "http", None);
2079        unevaluable.condition = Some(ConditionResponse {
2080            state: "unevaluable".to_string(),
2081            expression: Some("build succeeded".to_string()),
2082            value: None,
2083            reason: Some("depends on a step output".to_string()),
2084        });
2085
2086        let output = execution_plan_tree(&plan_fixture(vec![evaluated, skipped, unevaluable]));
2087        assert!(output.contains("(when env == prod = true)"), "{output}");
2088        assert!(output.contains("(skipped: not prod)"), "{output}");
2089        assert!(
2090            output.contains("(condition unevaluable: build succeeded)"),
2091            "{output}"
2092        );
2093    }
2094
2095    #[test]
2096    fn execution_plan_tree_reports_an_incomplete_plan() {
2097        let mut plan = plan_fixture(vec![planned_step("build", "shell", None)]);
2098        plan.truncated = true;
2099        plan.incomplete_reason = Some("step cap of 1000 reached".to_string());
2100
2101        let output = execution_plan_tree(&plan);
2102        assert!(
2103            output.contains("plan incomplete: step cap of 1000 reached"),
2104            "{output}"
2105        );
2106    }
2107
2108    #[test]
2109    fn execution_plan_tree_indents_sub_workflow_steps() {
2110        let mut nested = planned_step("child-step", "shell", None);
2111        nested.depth = 1;
2112        let plan = plan_fixture(vec![planned_step("child", "workflow", None), nested]);
2113
2114        let output = execution_plan_tree(&plan);
2115        let nested = output
2116            .lines()
2117            .find(|l| l.contains("child-step"))
2118            .expect("nested line");
2119        assert!(nested.starts_with("  "), "{nested}");
2120    }
2121}