Skip to main content

leviath_cli/commands/dashboard/
types.rs

1//! Type definitions for the dashboard: display status, agent representation, events.
2
3use clap::Args;
4
5use super::graph::GraphTransitionInfo;
6use super::theme::{C_ACTIVE, C_DIM, C_ERROR, C_SUCCESS, C_WARN};
7use super::theme::{GLYPH_ACTIVE, GLYPH_COMPLETE, GLYPH_ERROR, GLYPH_PENDING, GLYPH_WAITING};
8
9use crate::runstate::{self, StageRecord};
10use leviath_core::interaction;
11
12use ratatui::style::Color;
13
14/// Arguments for `lev dash`. It takes none; the dashboard is interactive.
15#[derive(Args)]
16pub struct DashboardArgs {}
17
18/// Whether the detail content pane shows Output or Logs.
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub(super) enum StageContentMode {
21    Output,
22    Logs,
23    Context,
24}
25
26/// How the main run list is ordered. Whatever the mode, the order is a total
27/// one (unique tie-break by id), so a status change alone never reshuffles
28/// rows within a mode.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub(super) enum SortMode {
31    /// Newest run first, and a run keeps its row for its whole life. The
32    /// default: predictable, nothing ever jumps.
33    StartedAt,
34    /// Most recently progressed run first: whatever just did something is on
35    /// top. Rows move only on real progress, never on a status flip alone.
36    RecentActivity,
37    /// The old grouping: active first, finished below, stable within a group.
38    StatusGrouped,
39}
40
41impl SortMode {
42    pub(super) fn next(self) -> Self {
43        match self {
44            Self::StartedAt => Self::RecentActivity,
45            Self::RecentActivity => Self::StatusGrouped,
46            Self::StatusGrouped => Self::StartedAt,
47        }
48    }
49
50    /// Short label for the table title.
51    pub(super) fn label(self) -> &'static str {
52        match self {
53            Self::StartedAt => "started",
54            Self::RecentActivity => "activity",
55            Self::StatusGrouped => "status",
56        }
57    }
58}
59
60/// Which pane of the main screen holds keyboard focus.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub(super) enum MainPane {
63    RunList,
64    LogPane,
65}
66
67/// A pane with its own wheel-scroll behavior, hit-tested against the rects
68/// each renderer registers per frame. Panes not listed here (detail content,
69/// review) share the keyboard's scroll target via `scroll_by`.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub(super) enum PaneId {
72    RunTable,
73    LogPanel,
74}
75
76/// Which tab of the full-screen stage explorer is showing.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub(super) enum ExplorerTab {
79    Graph,
80    Timeline,
81}
82
83/// The full-screen stage explorer (`g` in the detail view of a graph agent):
84/// a real layered rendering of the stage DAG, and the visit timeline the old
85/// one-row strip could not show.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub(super) struct ExplorerState {
88    pub(super) tab: ExplorerTab,
89    /// Show stages never visited (dimmed); `u` toggles them off.
90    pub(super) show_unvisited: bool,
91    /// Vertical scroll of the graph canvas, in rows.
92    pub(super) scroll: usize,
93    /// Selected row on the timeline tab.
94    pub(super) timeline_selected: usize,
95}
96
97impl ExplorerState {
98    pub(super) fn new() -> Self {
99        Self {
100            tab: ExplorerTab::Graph,
101            show_unvisited: true,
102            scroll: 0,
103            timeline_selected: 0,
104        }
105    }
106}
107
108/// Cursor + expansion state of the structured Context view.
109///
110/// Regions default to expanded (header + one-line entry stubs); entries
111/// default to collapsed. The state survives ticks and history steps, and
112/// resets only when the selected run changes.
113#[derive(Debug, Clone, Default)]
114pub(super) struct ContextTreeState {
115    /// Regions whose entry list is folded away.
116    pub(super) collapsed_regions: std::collections::HashSet<String>,
117    /// `(region, entry_index)` pairs expanded to their full content.
118    pub(super) expanded_entries: std::collections::HashSet<(String, usize)>,
119    /// Cursor over the tree's interactive rows (headers + stubs).
120    pub(super) cursor: usize,
121    /// Set when a key moved the cursor, so the renderer scrolls to it once
122    /// rather than pinning the view to the cursor forever.
123    pub(super) follow_cursor: bool,
124}
125
126/// A destructive action waiting on its confirmation dialog.
127#[derive(Debug, Clone, PartialEq)]
128pub(super) enum ConfirmAction {
129    /// Cancel the run via the daemon (the row stays, marked cancelled).
130    Kill { run_id: String },
131    /// Cancel and permanently delete the run's on-disk state.
132    Delete { run_id: String },
133    /// Remove an MCP server from the config.
134    McpRemove { name: String },
135}
136
137/// Display status for agents in the dashboard.
138#[derive(Debug, Clone, PartialEq)]
139pub enum AgentDisplayStatus {
140    /// Working.
141    Active,
142    /// Blocked on a person answering.
143    Waiting,
144    /// Finished, with nothing further to accept.
145    Complete,
146    /// All required work done; still accepting optional follow-up input.
147    CompleteInteractive,
148    /// Stopped by a failure, carrying its message.
149    Error(String),
150    /// Loaded but not currently doing anything.
151    Idle,
152    /// Paused by the user; resumable with `r` (or `lev resume`). Distinct from
153    /// `Idle` because a paused run is deliberate unfinished business, not a run
154    /// that merely has not ticked yet.
155    Paused,
156    /// Stopped from outside, by `lev kill` or a shutting-down daemon.
157    Cancelled,
158    /// On disk the run claims to be live, but the daemon has no such run and its
159    /// metadata has not been touched in a long time - so nothing is driving it.
160    ///
161    /// Shown distinctly rather than as ACTIVE because the two are not the same
162    /// thing to the user: an ACTIVE row implies work is happening. Killable, like
163    /// every other non-finished state.
164    Stale,
165}
166
167impl std::fmt::Display for AgentDisplayStatus {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        match self {
170            Self::Active => write!(f, "{}ACTIVE", GLYPH_ACTIVE),
171            Self::Waiting => write!(f, "{}WAITING", GLYPH_WAITING),
172            Self::Complete => write!(f, "{}COMPLETE", GLYPH_COMPLETE),
173            Self::CompleteInteractive => write!(f, "{}COMPLETE", GLYPH_COMPLETE),
174            Self::Error(msg) => write!(f, "{}ERROR: {}", GLYPH_ERROR, msg),
175            Self::Idle => write!(f, "{}IDLE", GLYPH_PENDING),
176            Self::Paused => write!(f, "{}PAUSED", GLYPH_PENDING),
177            Self::Cancelled => write!(f, "⊘CANCEL"),
178            Self::Stale => write!(f, "{}STALE", GLYPH_ERROR),
179        }
180    }
181}
182
183impl AgentDisplayStatus {
184    /// Whether this run has finished, one way or another.
185    pub(super) fn is_terminal(&self) -> bool {
186        matches!(
187            self,
188            Self::Complete | Self::CompleteInteractive | Self::Error(_) | Self::Cancelled
189        )
190    }
191
192    /// Whether the run can be killed. Anything that has not finished can be -
193    /// `Idle` and `Stale` included: skipping those would leave a run the
194    /// dashboard shows as live with no way to get rid of it.
195    pub(super) fn is_killable(&self) -> bool {
196        !self.is_terminal()
197    }
198
199    pub(super) fn color(&self) -> Color {
200        match self {
201            Self::Active => C_ACTIVE,
202            Self::Waiting => C_WARN,
203            Self::Complete | Self::CompleteInteractive => C_SUCCESS,
204            Self::Error(_) => C_ERROR,
205            Self::Idle => C_DIM,
206            Self::Paused => C_WARN,
207            Self::Cancelled => C_DIM,
208            Self::Stale => C_WARN,
209        }
210    }
211}
212
213/// An agent displayed in the dashboard.
214#[derive(Debug, Clone)]
215pub struct DashboardAgent {
216    /// The run id, which is also what every action against this row quotes.
217    pub id: String,
218    /// The blueprint's name, as the manifest declares it.
219    pub blueprint_name: String,
220    /// The stage the run is in, by name.
221    pub stage: String,
222    /// That stage's position in the blueprint's list.
223    pub stage_index: usize,
224    /// How many stages the blueprint has, so the pair renders as "3 of 7".
225    pub num_stages: usize,
226    /// What the row shows, including states no other status enum has.
227    pub status: AgentDisplayStatus,
228    /// Cumulative prompt (input) tokens for background runs.
229    pub tokens_in: usize,
230    /// Cumulative completion (output) tokens for background runs.
231    pub tokens_out: usize,
232    /// Cumulative tokens read from provider cache.
233    pub cached_tokens: usize,
234    /// Inference turns taken in the current stage.
235    pub iteration: usize,
236    /// The question a waiting run is asking, in one line, for the list row.
237    pub waiting_prompt: Option<String>,
238    /// Full structured interaction request (populated for WaitingInput agents)
239    pub pending_request: Option<interaction::InteractionRequest>,
240    /// The request_id we most recently submitted a response for, used to suppress
241    /// re-showing the same prompt before the worker has consumed the response.
242    pub last_answered_request_id: Option<String>,
243    /// Live context window snapshot from context.json (background workers only)
244    /// Shared, not owned: the live snapshot comes out of the sync tick's
245    /// stat-gated cache, and cloning a full context window per tick was the
246    /// churn that cache exists to remove.
247    pub context_snapshot: Option<std::sync::Arc<runstate::ContextSnapshot>>,
248    /// Per-stage records from stages.json
249    pub stages: Vec<StageRecord>,
250    /// Working directory the agent ran in
251    pub workdir: String,
252    /// Original task prompt
253    pub task: String,
254    /// Auto-generated short title (None until the worker generates it).
255    pub title: Option<String>,
256    /// Original model override
257    pub model: Option<String>,
258    /// Parent agent ID (if this is a sub-agent)
259    pub parent_id: Option<String>,
260    /// Depth in the sub-agent tree (0 = root)
261    pub depth: usize,
262    /// Unix timestamp when the run started (for elapsed display)
263    pub started_at: i64,
264    /// Unix timestamp of the run's last recorded progress (`None` before the
265    /// first progress mark). Drives the recent-activity sort.
266    pub last_progress_at: Option<i64>,
267    /// Frozen wall-clock time (Unix seconds) when the agent entered a waiting state.
268    /// Used to prevent the elapsed timer from incrementing while waiting for input.
269    pub active_until: Option<i64>,
270    /// Total seconds spent waiting for user input across all completed waits.
271    /// Subtracted from elapsed to show only actual running time.
272    pub waiting_secs: u64,
273    /// Cached graph transition info (None = linear mode or not yet loaded)
274    pub(super) graph_info: Option<GraphTransitionInfo>,
275    /// Whether the current stage accepts mid-run user messages
276    pub accepts_messages: bool,
277    /// Per-region taint levels (region_name, taint_level_string).
278    /// Empty when taint tracking is disabled or not yet populated.
279    pub taint_summary: Vec<(String, String)>,
280}
281
282/// Log entry for the dashboard log panel.
283#[derive(Debug, Clone)]
284pub(super) struct LogEntry {
285    pub(super) timestamp: String,
286    pub(super) message: String,
287}
288
289/// Command sent from the dashboard's (sync) input handlers to the async
290/// daemon-control background task, which forwards it over the control socket.
291#[derive(Debug, PartialEq)]
292pub(super) enum DaemonCommand {
293    /// Cancel a run.
294    Cancel { run_id: String },
295    /// Pause a run.
296    Pause { run_id: String },
297    /// Resume a paused run.
298    Resume { run_id: String },
299    /// Answer a pending `ask_user` interaction.
300    Answer {
301        response: interaction::InteractionResponse,
302    },
303    /// Deliver a mid-run message to a running agent.
304    Message { agent_id: String, content: String },
305}
306
307/// The result of a [`DaemonCommand`], drained each tick.
308///
309/// Discarding these would make a cancel the daemon refused look identical to
310/// one that worked: the row flashes CANCEL, the log says "Killed", and the
311/// next disk sync puts it back to ACTIVE with no explanation.
312#[derive(Debug, PartialEq)]
313pub(super) struct DaemonOutcome {
314    /// The run the command targeted.
315    pub(super) run_id: String,
316    /// Human-readable result, shown as a toast when it failed.
317    pub(super) message: String,
318    /// Whether the daemon applied it.
319    pub(super) ok: bool,
320}
321
322/// A long-running MCP action dispatched from the (sync) MCP screen to the async
323/// background task, so browser login and connect-and-list never block the UI.
324#[derive(Debug, PartialEq)]
325pub(super) enum McpCommand {
326    /// Run the OAuth browser login for a server.
327    Login { name: String },
328    /// Connect to a server and count its tools.
329    Test { name: String },
330}
331
332/// The result of an [`McpCommand`], drained each tick and shown as a toast.
333#[derive(Debug, PartialEq)]
334pub(super) struct McpOutcome {
335    /// Human-readable result to toast.
336    pub(super) message: String,
337    /// Whether it succeeded (drives the toast colour).
338    pub(super) ok: bool,
339}
340
341/// One row of the MCP management screen.
342#[derive(Debug, Clone, PartialEq)]
343pub(super) struct McpRow {
344    pub(super) name: String,
345    pub(super) transport: String,
346    pub(super) endpoint: String,
347    pub(super) auth: String,
348}
349
350/// Paths + injected seams the MCP screen's file/OAuth operations use, so the
351/// whole screen is testable without the real home directory or a browser.
352#[derive(Clone)]
353pub(super) struct McpContext {
354    pub(super) config_path: std::path::PathBuf,
355    pub(super) store_path: std::path::PathBuf,
356    pub(super) opener: leviath_mcp::BrowserOpener,
357    pub(super) clock: fn() -> u64,
358}
359
360/// Toast notification shown as an overlay.
361#[derive(Debug, Clone)]
362pub(super) struct Toast {
363    pub(super) message: String,
364    pub(super) remaining_ticks: u32,
365    pub(super) level: ToastLevel,
366}
367
368#[derive(Debug, Clone, PartialEq)]
369pub(super) enum ToastLevel {
370    Info,
371    Warning,
372    Error,
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn agent_display_status_display() {
381        assert!(AgentDisplayStatus::Active.to_string().contains("ACTIVE"));
382        assert!(AgentDisplayStatus::Waiting.to_string().contains("WAITING"));
383        assert!(
384            AgentDisplayStatus::Complete
385                .to_string()
386                .contains("COMPLETE")
387        );
388        assert!(
389            AgentDisplayStatus::CompleteInteractive
390                .to_string()
391                .contains("COMPLETE")
392        );
393        assert!(
394            AgentDisplayStatus::Error("boom".to_string())
395                .to_string()
396                .contains("boom")
397        );
398        assert!(AgentDisplayStatus::Idle.to_string().contains("IDLE"));
399        assert!(AgentDisplayStatus::Paused.to_string().contains("PAUSED"));
400        assert!(AgentDisplayStatus::Cancelled.to_string().contains("CANCEL"));
401        assert!(AgentDisplayStatus::Stale.to_string().contains("STALE"));
402    }
403
404    #[test]
405    fn agent_display_status_colors_are_distinct() {
406        let active = AgentDisplayStatus::Active.color();
407        let error = AgentDisplayStatus::Error("x".to_string()).color();
408        let success = AgentDisplayStatus::Complete.color();
409        assert_ne!(active, error);
410        assert_ne!(error, success);
411    }
412
413    #[test]
414    fn agent_display_status_color_idle_and_cancelled() {
415        assert_eq!(AgentDisplayStatus::Idle.color(), C_DIM);
416        assert_eq!(AgentDisplayStatus::Cancelled.color(), C_DIM);
417        // Stale is a warning, not a finished state: it wants attention.
418        assert_eq!(AgentDisplayStatus::Stale.color(), C_WARN);
419        // Paused is deliberate unfinished business, not a dim afterthought.
420        assert_eq!(AgentDisplayStatus::Paused.color(), C_WARN);
421        assert!(!AgentDisplayStatus::Paused.is_terminal());
422        assert!(AgentDisplayStatus::Paused.is_killable());
423        assert_eq!(AgentDisplayStatus::Waiting.color(), C_WARN);
424        assert_eq!(AgentDisplayStatus::CompleteInteractive.color(), C_SUCCESS);
425    }
426
427    #[test]
428    fn stage_content_mode_equality() {
429        assert_eq!(StageContentMode::Output, StageContentMode::Output);
430        assert_ne!(StageContentMode::Output, StageContentMode::Logs);
431        assert_ne!(StageContentMode::Logs, StageContentMode::Context);
432    }
433
434    #[test]
435    fn toast_level_debug() {
436        let toast = Toast {
437            message: "hello".to_string(),
438            remaining_ticks: 25,
439            level: ToastLevel::Info,
440        };
441        let dbg = format!("{:?}", toast);
442        assert!(dbg.contains("hello"));
443        assert!(dbg.contains("25"));
444    }
445
446    #[test]
447    fn daemon_command_debug_and_eq() {
448        let cmd = DaemonCommand::Cancel {
449            run_id: "run-123".to_string(),
450        };
451        let dbg = format!("{:?}", cmd);
452        assert!(dbg.contains("run-123"));
453        assert_eq!(
454            cmd,
455            DaemonCommand::Cancel {
456                run_id: "run-123".to_string()
457            }
458        );
459        assert_ne!(
460            cmd,
461            DaemonCommand::Message {
462                agent_id: "a".to_string(),
463                content: "b".to_string()
464            }
465        );
466    }
467
468    #[test]
469    fn log_entry_clone() {
470        let entry = LogEntry {
471            timestamp: "12:00:00".to_string(),
472            message: "started".to_string(),
473        };
474        let cloned = entry.clone();
475        assert_eq!(cloned.timestamp, "12:00:00");
476        assert_eq!(cloned.message, "started");
477    }
478
479    #[test]
480    fn dashboard_agent_clone() {
481        let agent = DashboardAgent {
482            id: "run-1".to_string(),
483            blueprint_name: "coder".to_string(),
484            stage: "plan".to_string(),
485            stage_index: 0,
486            num_stages: 2,
487            status: AgentDisplayStatus::Active,
488            tokens_in: 100,
489            tokens_out: 50,
490            cached_tokens: 0,
491            iteration: 1,
492            waiting_prompt: None,
493            pending_request: None,
494            last_answered_request_id: None,
495            context_snapshot: None,
496            stages: vec![],
497            workdir: "/tmp".to_string(),
498            task: "do stuff".to_string(),
499            title: Some("My Task".to_string()),
500            model: None,
501            parent_id: None,
502            depth: 0,
503            started_at: 1000,
504            last_progress_at: None,
505            active_until: None,
506            waiting_secs: 0,
507            graph_info: None,
508            accepts_messages: true,
509            taint_summary: vec![],
510        };
511        let cloned = agent.clone();
512        assert_eq!(cloned.id, "run-1");
513        assert_eq!(cloned.blueprint_name, "coder");
514        assert_eq!(cloned.stage, "plan");
515        assert_eq!(cloned.tokens_in, 100);
516    }
517
518    #[test]
519    fn agent_display_status_complete_interactive_shows_complete() {
520        let status = AgentDisplayStatus::CompleteInteractive;
521        let display = status.to_string();
522        assert!(display.contains("COMPLETE"));
523        assert_eq!(status.color(), C_SUCCESS);
524    }
525}