Skip to main content

zeph_tui/
event.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::sync::Arc;
5use std::time::Duration;
6
7use crossterm::event::{self, Event as CrosstermEvent, KeyEvent, MouseEvent, MouseEventKind};
8use tokio::sync::{Notify, mpsc, oneshot, watch};
9
10use zeph_core::metrics::MetricsSnapshot;
11
12/// Source of raw terminal events consumed by [`EventReader`].
13///
14/// Implement this trait to provide a custom event source (e.g. a mock for
15/// testing or a replay driver).
16///
17/// # Examples
18///
19/// ```rust
20/// use zeph_tui::event::{AppEvent, EventSource};
21/// use crossterm::event::KeyEvent;
22///
23/// struct OneTickSource;
24///
25/// impl EventSource for OneTickSource {
26///     fn next_event(&mut self) -> Option<AppEvent> {
27///         None // signal EOF
28///     }
29/// }
30/// ```
31pub trait EventSource: Send + 'static {
32    /// Return the next event, or `None` to signal that the source is exhausted
33    /// and the event loop should terminate.
34    fn next_event(&mut self) -> Option<AppEvent>;
35}
36
37/// [`EventSource`] backed by crossterm's blocking event poll.
38///
39/// Polls for terminal events up to `tick_rate` before returning a
40/// [`AppEvent::Tick`] if no event arrived. This drives the TUI's animation
41/// and idle redraw cadence.
42///
43/// # Examples
44///
45/// ```rust
46/// use std::time::Duration;
47/// use zeph_tui::CrosstermEventSource;
48///
49/// let source = CrosstermEventSource::new(Duration::from_millis(250));
50/// ```
51pub struct CrosstermEventSource {
52    tick_rate: Duration,
53}
54
55impl CrosstermEventSource {
56    /// Create a new source with the given poll interval.
57    ///
58    /// # Examples
59    ///
60    /// ```rust
61    /// use std::time::Duration;
62    /// use zeph_tui::CrosstermEventSource;
63    ///
64    /// let src = CrosstermEventSource::new(Duration::from_millis(100));
65    /// ```
66    #[must_use]
67    pub fn new(tick_rate: Duration) -> Self {
68        Self { tick_rate }
69    }
70}
71
72impl EventSource for CrosstermEventSource {
73    fn next_event(&mut self) -> Option<AppEvent> {
74        if event::poll(self.tick_rate).unwrap_or(false) {
75            match event::read() {
76                Ok(CrosstermEvent::Key(key)) => Some(AppEvent::Key(key)),
77                Ok(CrosstermEvent::Resize(w, h)) => Some(AppEvent::Resize(w, h)),
78                Ok(CrosstermEvent::Paste(text)) => Some(AppEvent::Paste(text)),
79                Ok(CrosstermEvent::Mouse(m)) => {
80                    // C6: filter high-frequency motion events to Tick to avoid
81                    // setting dirty=Full on every cursor move, which would
82                    // stall the render loop with unnecessary full redraws.
83                    match m.kind {
84                        MouseEventKind::Moved | MouseEventKind::Drag(_) => Some(AppEvent::Tick),
85                        _ => Some(AppEvent::Mouse(m)),
86                    }
87                }
88                _ => Some(AppEvent::Tick),
89            }
90        } else {
91            Some(AppEvent::Tick)
92        }
93    }
94}
95
96/// Top-level event consumed by the [`crate::App`] event handler.
97///
98/// Events arrive from two sources:
99/// - Terminal input via [`EventReader`] / [`CrosstermEventSource`].
100/// - Agent output forwarded through [`AgentEvent`] by [`crate::TuiChannel`].
101///
102/// # Examples
103///
104/// ```rust
105/// use zeph_tui::event::AppEvent;
106///
107/// let ev = AppEvent::Tick;
108/// assert!(matches!(ev, AppEvent::Tick));
109/// ```
110#[non_exhaustive]
111#[derive(Debug)]
112pub enum AppEvent {
113    /// A keyboard event from crossterm.
114    Key(KeyEvent),
115    /// Periodic tick used to drive animations and idle redraws.
116    Tick,
117    /// The terminal was resized to the given `(columns, rows)`.
118    Resize(u16, u16),
119    /// An event forwarded from the agent event channel.
120    Agent(AgentEvent),
121    /// Text pasted via bracketed paste mode.
122    ///
123    /// The string may contain `\n` characters (multiline paste). The app
124    /// inserts it verbatim into the input buffer; Enter is still required
125    /// to submit (matching vim/neovim behaviour).
126    Paste(String),
127    /// A mouse event from crossterm (only produced when mouse capture is enabled via
128    /// `/mouse on`). High-frequency `Moved` and `Drag` events are folded into
129    /// [`AppEvent::Tick`] by [`CrosstermEventSource`] before reaching this variant (C6).
130    Mouse(MouseEvent),
131}
132
133/// Events produced by the agent and forwarded to the TUI via [`crate::TuiChannel`].
134///
135/// Each variant corresponds to a distinct phase or signal in the agent lifecycle
136/// (streaming output, tool execution, user confirmation, etc.).
137///
138/// # Examples
139///
140/// ```rust
141/// use zeph_tui::event::AgentEvent;
142///
143/// let ev = AgentEvent::Chunk("partial response".to_string());
144/// assert!(matches!(ev, AgentEvent::Chunk(_)));
145/// ```
146#[non_exhaustive]
147#[derive(Debug)]
148pub enum AgentEvent {
149    /// A streaming text chunk from the LLM — appended to the current message.
150    Chunk(String),
151    /// A complete (non-streaming) assistant message.
152    FullMessage(String),
153    /// Signals that streaming is complete; the chat widget stops the cursor.
154    Flush,
155    /// The agent is waiting for an LLM response (drives the throbber).
156    Typing,
157    /// A short status string to display in the activity bar (e.g. `"Searching memory…"`).
158    Status(String),
159    /// A tool call has started; the TUI should display a spinner with the tool name.
160    ToolStart {
161        /// Canonical tool name (e.g. `"bash"`, `"read_file"`).
162        tool_name: zeph_common::ToolName,
163        /// The primary command or argument string shown in the status bar.
164        command: String,
165        /// Opaque tool-call identifier for correlating subsequent events.
166        tool_call_id: String,
167        /// True when this tool call originates from an MCP server rather than a native tool.
168        is_mcp: bool,
169    },
170    /// An incremental output chunk from a long-running tool (e.g. streaming shell output).
171    ToolOutputChunk {
172        /// Tool that produced the chunk.
173        tool_name: zeph_common::ToolName,
174        /// Command argument associated with the tool call.
175        command: String,
176        /// The chunk text to append.
177        chunk: String,
178        /// Opaque tool-call identifier for id-based message lookup.
179        tool_call_id: String,
180    },
181    /// Final tool output, replacing any in-progress chunks for this call.
182    ToolOutput {
183        /// Tool that produced the output.
184        tool_name: zeph_common::ToolName,
185        /// Command argument associated with the tool call.
186        command: String,
187        /// Full rendered output body.
188        output: String,
189        /// `true` if the tool succeeded, `false` on error.
190        success: bool,
191        /// Optional diff to display inline in the chat.
192        diff: Option<zeph_core::DiffData>,
193        /// Human-readable filter summary, if output was filtered.
194        filter_stats: Option<String>,
195        /// Indices of lines retained by the filter.
196        kept_lines: Option<Vec<usize>>,
197        /// Opaque tool-call identifier for id-based message lookup.
198        tool_call_id: String,
199    },
200    /// The agent requests a boolean confirmation from the user.
201    ConfirmRequest {
202        /// Prompt text shown in the confirmation dialog.
203        prompt: String,
204        /// One-shot channel to send the user's `true`/`false` response.
205        response_tx: oneshot::Sender<bool>,
206    },
207    /// The agent requests structured input via an elicitation dialog.
208    ElicitationRequest {
209        /// The elicitation schema and prompt.
210        request: zeph_core::channel::ElicitationRequest,
211        /// One-shot channel to send the user's response.
212        response_tx: oneshot::Sender<zeph_core::channel::ElicitationResponse>,
213    },
214    /// Updated count of messages queued for the agent (shown in the input bar).
215    QueueCount(usize),
216    /// A diff is ready for immediate display in the diff panel.
217    DiffReady {
218        /// The diff payload to attach to the corresponding tool message.
219        diff: zeph_core::DiffData,
220        /// Identifies which tool call produced this diff.
221        tool_call_id: String,
222    },
223    /// Result from a slash-command dispatched to the agent.
224    CommandResult {
225        /// The slash-command identifier that produced this result.
226        command_id: String,
227        /// Formatted command output to display.
228        output: String,
229    },
230    /// Wire a cancel signal into the TUI App after early startup (Phase 2).
231    SetCancelSignal(Arc<Notify>),
232    /// Wire a metrics receiver into the TUI App after early startup (Phase 2).
233    SetMetricsRx(watch::Receiver<MetricsSnapshot>),
234    /// Wire a [`zeph_common::task_supervisor::TaskSupervisor`] into the TUI App after
235    /// early startup (Phase 2), so the task registry panel reflects live task state
236    /// instead of reporting "supervisor not available".
237    SetTaskSupervisor(zeph_common::task_supervisor::TaskSupervisor),
238    /// A foreground subagent has been spawned; the TUI should switch view to its transcript.
239    ForegroundSubagentStarted {
240        /// Stable sub-agent identifier (`task_id` from `SubAgentManager`).
241        id: String,
242        /// Human-readable agent definition name.
243        name: String,
244    },
245    /// A foreground subagent has reached a terminal state; the TUI should return to Main view.
246    ForegroundSubagentCompleted {
247        /// Stable sub-agent identifier.
248        id: String,
249        /// Human-readable agent definition name.
250        name: String,
251        /// `true` if Completed state, `false` if Failed/Canceled.
252        success: bool,
253    },
254    /// Current context token count estimate, updated after each context assembly.
255    ///
256    /// The value is an approximation based on character-level heuristics and may
257    /// diverge slightly from the actual token count sent to the LLM. Stale between
258    /// turns (the previous turn's estimate remains displayed until the next assembly).
259    ContextEstimate(usize),
260    /// Updated fleet snapshot from the background DB poll task (#3884).
261    FleetSnapshot(crate::widgets::fleet::FleetSnapshot),
262    /// Updated durable execution snapshot from the background poll task (spec-064, #4949).
263    DurableSnapshot(crate::widgets::durable::DurableSnapshot),
264    /// A non-empty prior conversation was resumed at startup (spec-068 §13.5).
265    ///
266    /// Renders as a **persistent** banner in the header/status area — unlike
267    /// [`AgentEvent::Status`], it must remain visible once the first prompt scrolls the
268    /// transient status line out of view. Never sent for a fresh (system-prompt-only)
269    /// conversation (§13.4, AC-16).
270    ResumeBanner(String),
271    /// Bounded `/history` transcript slice to backfill into the display buffer (spec-068
272    /// §13.6-§13.7).
273    ///
274    /// Pushed as distinct chat messages via `App::backfill_history_display_only`, split from
275    /// `input_history`/up-arrow recall (INV-SP-6, AC-20) — never routed through
276    /// `App::load_history`, which also feeds `input_history`.
277    HistoryBackfill(Vec<zeph_commands::TranscriptEntry>),
278}
279
280/// Blocking event pump that forwards terminal events to the async [`AppEvent`] channel.
281///
282/// `EventReader` must run on a **dedicated `std::thread`** — it calls
283/// `blocking_send` and crossterm's blocking poll, which would stall a tokio
284/// worker thread.
285///
286/// # Examples
287///
288/// ```rust,no_run
289/// use std::time::Duration;
290/// use tokio::sync::mpsc;
291/// use zeph_tui::EventReader;
292///
293/// let (tx, rx) = mpsc::channel(64);
294/// let reader = EventReader::new(tx, Duration::from_millis(250));
295/// std::thread::spawn(|| reader.run());
296/// ```
297pub struct EventReader {
298    tx: mpsc::Sender<AppEvent>,
299    tick_rate: Duration,
300}
301
302impl EventReader {
303    /// Create a new reader that sends events to `tx` at up to `tick_rate` cadence.
304    ///
305    /// # Examples
306    ///
307    /// ```rust
308    /// use std::time::Duration;
309    /// use tokio::sync::mpsc;
310    /// use zeph_tui::EventReader;
311    ///
312    /// let (tx, _rx) = mpsc::channel(64);
313    /// let reader = EventReader::new(tx, Duration::from_millis(250));
314    /// ```
315    #[must_use]
316    pub fn new(tx: mpsc::Sender<AppEvent>, tick_rate: Duration) -> Self {
317        Self { tx, tick_rate }
318    }
319
320    /// Start the blocking event loop using the default [`CrosstermEventSource`].
321    ///
322    /// **Must be called from a dedicated `std::thread`**, not a tokio worker.
323    /// Returns when the [`AppEvent`] channel receiver is dropped.
324    pub fn run(self) {
325        let tick_rate = self.tick_rate;
326        self.run_with_source(CrosstermEventSource::new(tick_rate));
327    }
328
329    /// Start the blocking event loop with a custom [`EventSource`].
330    ///
331    /// This variant exists primarily for testing with mock sources.
332    /// Returns when the source returns `None` or the channel is closed.
333    pub fn run_with_source(self, mut source: impl EventSource) {
334        while let Some(evt) = source.next_event() {
335            if self.tx.blocking_send(evt).is_err() {
336                break;
337            }
338        }
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345    use std::assert_matches;
346
347    #[test]
348    fn agent_event_debug() {
349        let e = AgentEvent::Chunk("hello".into());
350        let s = format!("{e:?}");
351        assert!(s.contains("Chunk"));
352    }
353
354    #[test]
355    fn app_event_variants() {
356        let tick = AppEvent::Tick;
357        assert_matches!(tick, AppEvent::Tick);
358
359        let resize = AppEvent::Resize(80, 24);
360        assert_matches!(resize, AppEvent::Resize(80, 24));
361    }
362
363    #[test]
364    fn event_reader_construction() {
365        let (tx, _rx) = mpsc::channel(16);
366        let reader = EventReader::new(tx, Duration::from_millis(100));
367        assert_eq!(reader.tick_rate, Duration::from_millis(100));
368    }
369
370    #[test]
371    fn confirm_request_debug() {
372        let (tx, _rx) = oneshot::channel();
373        let e = AgentEvent::ConfirmRequest {
374            prompt: "delete?".into(),
375            response_tx: tx,
376        };
377        let s = format!("{e:?}");
378        assert!(s.contains("ConfirmRequest"));
379        assert!(s.contains("delete?"));
380    }
381
382    #[test]
383    fn app_event_paste_variant() {
384        assert_matches!(AppEvent::Paste("x".into()), AppEvent::Paste(_));
385    }
386}