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 runs via the daemon (the rows stay, marked cancelled).
130    /// Carries one id for the selected run, several when runs are marked.
131    Kill { run_ids: Vec<String> },
132    /// Cancel and permanently delete the runs' on-disk state.
133    /// Carries one id for the selected run, several when runs are marked.
134    Delete { run_ids: Vec<String> },
135    /// Remove an MCP server from the config.
136    McpRemove { name: String },
137    /// Turn on unattended runs for the new-run screen.
138    EnableYolo,
139}
140
141/// Display status for agents in the dashboard.
142#[derive(Debug, Clone, PartialEq)]
143pub enum AgentDisplayStatus {
144    /// Working.
145    Active,
146    /// Blocked on a person answering.
147    Waiting,
148    /// Finished, with nothing further to accept.
149    Complete,
150    /// All required work done; still accepting optional follow-up input.
151    CompleteInteractive,
152    /// Stopped by a failure, carrying its message.
153    Error(String),
154    /// Loaded but not currently doing anything.
155    Idle,
156    /// Paused by the user; resumable with `r` (or `lev resume`). Distinct from
157    /// `Idle` because a paused run is deliberate unfinished business, not a run
158    /// that merely has not ticked yet.
159    Paused,
160    /// Stopped from outside, by `lev kill` or a shutting-down daemon.
161    Cancelled,
162    /// On disk the run claims to be live, but the daemon has no such run and its
163    /// metadata has not been touched in a long time - so nothing is driving it.
164    ///
165    /// Shown distinctly rather than as ACTIVE because the two are not the same
166    /// thing to the user: an ACTIVE row implies work is happening. Killable, like
167    /// every other non-finished state.
168    Stale,
169}
170
171impl std::fmt::Display for AgentDisplayStatus {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        match self {
174            Self::Active => write!(f, "{}ACTIVE", GLYPH_ACTIVE),
175            Self::Waiting => write!(f, "{}WAITING", GLYPH_WAITING),
176            Self::Complete => write!(f, "{}COMPLETE", GLYPH_COMPLETE),
177            Self::CompleteInteractive => write!(f, "{}COMPLETE", GLYPH_COMPLETE),
178            Self::Error(msg) => write!(f, "{}ERROR: {}", GLYPH_ERROR, msg),
179            Self::Idle => write!(f, "{}IDLE", GLYPH_PENDING),
180            Self::Paused => write!(f, "{}PAUSED", GLYPH_PENDING),
181            Self::Cancelled => write!(f, "⊘CANCEL"),
182            Self::Stale => write!(f, "{}STALE", GLYPH_ERROR),
183        }
184    }
185}
186
187impl AgentDisplayStatus {
188    /// Whether this run has finished, one way or another.
189    pub(super) fn is_terminal(&self) -> bool {
190        matches!(
191            self,
192            Self::Complete | Self::CompleteInteractive | Self::Error(_) | Self::Cancelled
193        )
194    }
195
196    /// Whether the run can be killed. Anything that has not finished can be -
197    /// `Idle` and `Stale` included: skipping those would leave a run the
198    /// dashboard shows as live with no way to get rid of it.
199    pub(super) fn is_killable(&self) -> bool {
200        !self.is_terminal()
201    }
202
203    pub(super) fn color(&self) -> Color {
204        match self {
205            Self::Active => C_ACTIVE,
206            Self::Waiting => C_WARN,
207            Self::Complete | Self::CompleteInteractive => C_SUCCESS,
208            Self::Error(_) => C_ERROR,
209            Self::Idle => C_DIM,
210            Self::Paused => C_WARN,
211            Self::Cancelled => C_DIM,
212            Self::Stale => C_WARN,
213        }
214    }
215}
216
217/// An agent displayed in the dashboard.
218#[derive(Debug, Clone)]
219pub struct DashboardAgent {
220    /// The run id, which is also what every action against this row quotes.
221    pub id: String,
222    /// The blueprint's name, as the manifest declares it.
223    pub blueprint_name: String,
224    /// The stage the run is in, by name.
225    pub stage: String,
226    /// That stage's position in the blueprint's list.
227    pub stage_index: usize,
228    /// How many stages the blueprint has, so the pair renders as "3 of 7".
229    pub num_stages: usize,
230    /// What the row shows, including states no other status enum has.
231    pub status: AgentDisplayStatus,
232    /// Cumulative prompt (input) tokens for background runs.
233    pub tokens_in: usize,
234    /// Cumulative completion (output) tokens for background runs.
235    pub tokens_out: usize,
236    /// Cumulative tokens read from provider cache.
237    pub cached_tokens: usize,
238    /// Inference turns taken in the current stage.
239    pub iteration: usize,
240    /// The question a waiting run is asking, in one line, for the list row.
241    pub waiting_prompt: Option<String>,
242    /// Full structured interaction request (populated for WaitingInput agents)
243    pub pending_request: Option<interaction::InteractionRequest>,
244    /// The request_id we most recently submitted a response for, used to suppress
245    /// re-showing the same prompt before the worker has consumed the response.
246    pub last_answered_request_id: Option<String>,
247    /// Live context window snapshot from context.json (background workers only)
248    /// Shared, not owned: the live snapshot comes out of the sync tick's
249    /// stat-gated cache, and cloning a full context window per tick was the
250    /// churn that cache exists to remove.
251    pub context_snapshot: Option<std::sync::Arc<runstate::ContextSnapshot>>,
252    /// Per-stage records from stages.json
253    pub stages: Vec<StageRecord>,
254    /// Working directory the agent ran in
255    pub workdir: String,
256    /// Original task prompt
257    pub task: String,
258    /// Auto-generated short title (None until the worker generates it).
259    pub title: Option<String>,
260    /// Original model override
261    pub model: Option<String>,
262    /// Parent agent ID (if this is a sub-agent)
263    pub parent_id: Option<String>,
264    /// Depth in the sub-agent tree (0 = root)
265    pub depth: usize,
266    /// Unix timestamp when the run started (for elapsed display)
267    pub started_at: i64,
268    /// Unix timestamp of the run's last recorded progress (`None` before the
269    /// first progress mark). Drives the recent-activity sort.
270    pub last_progress_at: Option<i64>,
271    /// Frozen wall-clock time (Unix seconds) when the agent entered a waiting state.
272    /// Used to prevent the elapsed timer from incrementing while waiting for input.
273    pub active_until: Option<i64>,
274    /// Total seconds spent waiting for user input across all completed waits.
275    /// Subtracted from elapsed to show only actual running time.
276    pub waiting_secs: u64,
277    /// Cached graph transition info (None = linear mode or not yet loaded)
278    pub(super) graph_info: Option<GraphTransitionInfo>,
279    /// Whether the current stage accepts mid-run user messages
280    pub accepts_messages: bool,
281    /// Per-region taint levels (region_name, taint_level_string).
282    /// Empty when taint tracking is disabled or not yet populated.
283    pub taint_summary: Vec<(String, String)>,
284}
285
286/// Log entry for the dashboard log panel.
287#[derive(Debug, Clone)]
288pub(super) struct LogEntry {
289    pub(super) timestamp: String,
290    pub(super) message: String,
291}
292
293/// Command sent from the dashboard's (sync) input handlers to the async
294/// daemon-control background task, which forwards it over the control socket.
295#[derive(Debug, PartialEq)]
296pub(super) enum DaemonCommand {
297    /// Cancel a run.
298    Cancel { run_id: String },
299    /// Pause a run.
300    Pause { run_id: String },
301    /// Resume a paused run.
302    Resume { run_id: String },
303    /// Answer a pending `ask_user` interaction.
304    Answer {
305        response: interaction::InteractionResponse,
306    },
307    /// Deliver a mid-run message to a running agent.
308    Message { agent_id: String, content: String },
309}
310
311/// The result of a [`DaemonCommand`], drained each tick.
312///
313/// Discarding these would make a cancel the daemon refused look identical to
314/// one that worked: the row flashes CANCEL, the log says "Killed", and the
315/// next disk sync puts it back to ACTIVE with no explanation.
316#[derive(Debug, PartialEq)]
317pub(super) struct DaemonOutcome {
318    /// The run the command targeted.
319    pub(super) run_id: String,
320    /// Human-readable result, shown as a toast when it failed.
321    pub(super) message: String,
322    /// Whether the daemon applied it.
323    pub(super) ok: bool,
324}
325
326/// A long-running MCP action dispatched from the (sync) MCP screen to the async
327/// background task, so browser login and connect-and-list never block the UI.
328#[derive(Debug, PartialEq)]
329pub(super) enum McpCommand {
330    /// Run the OAuth browser login for a server.
331    Login { name: String },
332    /// Connect to a server and count its tools.
333    Test { name: String },
334}
335
336/// The result of an [`McpCommand`], drained each tick and shown as a toast.
337#[derive(Debug, PartialEq)]
338pub(super) struct McpOutcome {
339    /// Human-readable result to toast.
340    pub(super) message: String,
341    /// Whether it succeeded (drives the toast colour).
342    pub(super) ok: bool,
343}
344
345/// One row of the MCP management screen.
346#[derive(Debug, Clone, PartialEq)]
347pub(super) struct McpRow {
348    pub(super) name: String,
349    pub(super) transport: String,
350    pub(super) endpoint: String,
351    pub(super) auth: String,
352}
353
354/// Paths + injected seams the MCP screen's file/OAuth operations use, so the
355/// whole screen is testable without the real home directory or a browser.
356#[derive(Clone)]
357pub(super) struct McpContext {
358    pub(super) config_path: std::path::PathBuf,
359    pub(super) store_path: std::path::PathBuf,
360    pub(super) opener: leviath_mcp::BrowserOpener,
361    pub(super) clock: fn() -> u64,
362}
363
364/// Which pane of the new-run screen holds keyboard focus (Tab toggles).
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub(super) enum NewRunPane {
367    Agents,
368    Task,
369}
370
371/// One runnable agent offered by the new-run screen.
372#[derive(Debug, Clone, PartialEq, Eq)]
373pub(super) struct NewRunAgent {
374    pub(super) name: String,
375    /// Where it came from: `installed`, `configured`, `local`, or `bundled`.
376    pub(super) source: String,
377    pub(super) description: String,
378    /// What gets handed to `lev run`'s resolver: the manifest's directory for a
379    /// discovered agent, the bare name for a bundled one (which resolves only
380    /// once `lev setup` has installed it - and says so if it has not).
381    pub(super) path: String,
382}
383
384/// Where the new-run screen reads its agent catalog and its `@` file
385/// candidates from, so the whole screen is testable against a temp tree
386/// instead of the user's real home directory and working directory.
387#[derive(Clone)]
388pub(super) struct NewRunContext {
389    /// `~/.leviath/agents`, scanned for installed agents.
390    pub(super) agents_dir: std::path::PathBuf,
391    /// The config whose `agent_paths` add more places to look.
392    pub(super) config_path: std::path::PathBuf,
393    /// The directory the run's tools are confined to, and the root the `@`
394    /// completion offers files from.
395    pub(super) workdir: std::path::PathBuf,
396}
397
398/// A run the new-run screen asked for, dispatched to the async spawn lane.
399///
400/// Resolving a blueprint reads and parses files and the spawn itself is a
401/// socket round trip, so neither happens on the draw loop.
402#[derive(Debug, PartialEq, Eq)]
403pub(super) struct SpawnCommand {
404    /// The agent path or name to resolve.
405    pub(super) agent_path: String,
406    /// The task text as typed.
407    pub(super) task: String,
408    /// The working directory the run gets.
409    pub(super) workdir: String,
410    /// Whether the run approves its own tool calls.
411    pub(super) yolo: bool,
412}
413
414/// The result of a [`SpawnCommand`], drained each tick and shown as a toast.
415#[derive(Debug, PartialEq, Eq)]
416pub(super) struct SpawnOutcome {
417    /// Human-readable result to toast.
418    pub(super) message: String,
419    /// Whether the run actually started (drives the toast colour).
420    pub(super) ok: bool,
421    /// The id the daemon gave it, so the dashboard can open its page.
422    pub(super) run_id: Option<String>,
423}
424
425/// Toast notification shown as an overlay.
426#[derive(Debug, Clone)]
427pub(super) struct Toast {
428    pub(super) message: String,
429    pub(super) remaining_ticks: u32,
430    pub(super) level: ToastLevel,
431}
432
433#[derive(Debug, Clone, PartialEq)]
434pub(super) enum ToastLevel {
435    Info,
436    Warning,
437    Error,
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    #[test]
445    fn agent_display_status_display() {
446        assert!(AgentDisplayStatus::Active.to_string().contains("ACTIVE"));
447        assert!(AgentDisplayStatus::Waiting.to_string().contains("WAITING"));
448        assert!(
449            AgentDisplayStatus::Complete
450                .to_string()
451                .contains("COMPLETE")
452        );
453        assert!(
454            AgentDisplayStatus::CompleteInteractive
455                .to_string()
456                .contains("COMPLETE")
457        );
458        assert!(
459            AgentDisplayStatus::Error("boom".to_string())
460                .to_string()
461                .contains("boom")
462        );
463        assert!(AgentDisplayStatus::Idle.to_string().contains("IDLE"));
464        assert!(AgentDisplayStatus::Paused.to_string().contains("PAUSED"));
465        assert!(AgentDisplayStatus::Cancelled.to_string().contains("CANCEL"));
466        assert!(AgentDisplayStatus::Stale.to_string().contains("STALE"));
467    }
468
469    #[test]
470    fn agent_display_status_colors_are_distinct() {
471        let active = AgentDisplayStatus::Active.color();
472        let error = AgentDisplayStatus::Error("x".to_string()).color();
473        let success = AgentDisplayStatus::Complete.color();
474        assert_ne!(active, error);
475        assert_ne!(error, success);
476    }
477
478    #[test]
479    fn agent_display_status_color_idle_and_cancelled() {
480        assert_eq!(AgentDisplayStatus::Idle.color(), C_DIM);
481        assert_eq!(AgentDisplayStatus::Cancelled.color(), C_DIM);
482        // Stale is a warning, not a finished state: it wants attention.
483        assert_eq!(AgentDisplayStatus::Stale.color(), C_WARN);
484        // Paused is deliberate unfinished business, not a dim afterthought.
485        assert_eq!(AgentDisplayStatus::Paused.color(), C_WARN);
486        assert!(!AgentDisplayStatus::Paused.is_terminal());
487        assert!(AgentDisplayStatus::Paused.is_killable());
488        assert_eq!(AgentDisplayStatus::Waiting.color(), C_WARN);
489        assert_eq!(AgentDisplayStatus::CompleteInteractive.color(), C_SUCCESS);
490    }
491
492    #[test]
493    fn stage_content_mode_equality() {
494        assert_eq!(StageContentMode::Output, StageContentMode::Output);
495        assert_ne!(StageContentMode::Output, StageContentMode::Logs);
496        assert_ne!(StageContentMode::Logs, StageContentMode::Context);
497    }
498
499    #[test]
500    fn toast_level_debug() {
501        let toast = Toast {
502            message: "hello".to_string(),
503            remaining_ticks: 25,
504            level: ToastLevel::Info,
505        };
506        let dbg = format!("{:?}", toast);
507        assert!(dbg.contains("hello"));
508        assert!(dbg.contains("25"));
509    }
510
511    #[test]
512    fn daemon_command_debug_and_eq() {
513        let cmd = DaemonCommand::Cancel {
514            run_id: "run-123".to_string(),
515        };
516        let dbg = format!("{:?}", cmd);
517        assert!(dbg.contains("run-123"));
518        assert_eq!(
519            cmd,
520            DaemonCommand::Cancel {
521                run_id: "run-123".to_string()
522            }
523        );
524        assert_ne!(
525            cmd,
526            DaemonCommand::Message {
527                agent_id: "a".to_string(),
528                content: "b".to_string()
529            }
530        );
531    }
532
533    #[test]
534    fn log_entry_clone() {
535        let entry = LogEntry {
536            timestamp: "12:00:00".to_string(),
537            message: "started".to_string(),
538        };
539        let cloned = entry.clone();
540        assert_eq!(cloned.timestamp, "12:00:00");
541        assert_eq!(cloned.message, "started");
542    }
543
544    #[test]
545    fn dashboard_agent_clone() {
546        let agent = DashboardAgent {
547            id: "run-1".to_string(),
548            blueprint_name: "coder".to_string(),
549            stage: "plan".to_string(),
550            stage_index: 0,
551            num_stages: 2,
552            status: AgentDisplayStatus::Active,
553            tokens_in: 100,
554            tokens_out: 50,
555            cached_tokens: 0,
556            iteration: 1,
557            waiting_prompt: None,
558            pending_request: None,
559            last_answered_request_id: None,
560            context_snapshot: None,
561            stages: vec![],
562            workdir: "/tmp".to_string(),
563            task: "do stuff".to_string(),
564            title: Some("My Task".to_string()),
565            model: None,
566            parent_id: None,
567            depth: 0,
568            started_at: 1000,
569            last_progress_at: None,
570            active_until: None,
571            waiting_secs: 0,
572            graph_info: None,
573            accepts_messages: true,
574            taint_summary: vec![],
575        };
576        let cloned = agent.clone();
577        assert_eq!(cloned.id, "run-1");
578        assert_eq!(cloned.blueprint_name, "coder");
579        assert_eq!(cloned.stage, "plan");
580        assert_eq!(cloned.tokens_in, 100);
581    }
582
583    #[test]
584    fn agent_display_status_complete_interactive_shows_complete() {
585        let status = AgentDisplayStatus::CompleteInteractive;
586        let display = status.to_string();
587        assert!(display.contains("COMPLETE"));
588        assert_eq!(status.color(), C_SUCCESS);
589    }
590}