1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! Main application loop for the TUI.
//!
//! This module provides a read-only observation dashboard that displays
//! formatted output from the Ralph orchestrator, with iteration navigation,
//! scroll, and search functionality.
use crate::input::{Action, map_key};
use crate::rpc_writer::RpcWriter;
use crate::state::TuiState;
use crate::widgets::{content::ContentPane, footer, header, help};
use anyhow::Result;
use crossterm::{
cursor::Show,
event::{
DisableMouseCapture, EnableMouseCapture, Event, EventStream, KeyCode, KeyEventKind,
KeyModifiers, MouseEventKind,
},
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use futures::StreamExt;
use ratatui::{
Terminal,
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout},
};
use scopeguard::defer;
use std::io;
use std::sync::{Arc, Mutex};
use tokio::io::AsyncWrite;
use tokio::sync::watch;
use tokio::time::{Duration, interval};
use tracing::info;
/// Dispatches an action to the TuiState.
///
/// Returns `true` if the action signals to quit the application.
pub fn dispatch_action(action: Action, state: &mut TuiState, viewport_height: usize) -> bool {
match action {
Action::Quit => return true,
Action::ScrollDown => {
if let Some(buffer) = state.current_iteration_mut() {
buffer.scroll_down(viewport_height);
}
}
Action::ScrollUp => {
if let Some(buffer) = state.current_iteration_mut() {
buffer.scroll_up();
}
}
Action::ScrollTop => {
if let Some(buffer) = state.current_iteration_mut() {
buffer.scroll_top();
}
}
Action::ScrollBottom => {
if let Some(buffer) = state.current_iteration_mut() {
buffer.scroll_bottom(viewport_height);
}
}
Action::NextIteration => {
state.navigate_next();
}
Action::PrevIteration => {
state.navigate_prev();
}
Action::ShowHelp => {
state.show_help = true;
}
Action::DismissHelp => {
state.show_help = false;
state.clear_search();
}
Action::StartSearch => {
state.search_state.search_mode = true;
}
Action::SearchNext => {
state.next_match();
}
Action::SearchPrev => {
state.prev_match();
}
Action::GuidanceNext => {
state.start_guidance(crate::state::GuidanceMode::Next);
}
Action::GuidanceNow => {
state.start_guidance(crate::state::GuidanceMode::Now);
}
Action::None => {}
}
false
}
/// Main TUI application for read-only observation.
pub struct App<W = tokio::process::ChildStdin> {
state: Arc<Mutex<TuiState>>,
/// Receives notification when the underlying process terminates.
/// This is the ONLY exit path for the TUI event loop (besides Action::Quit).
terminated_rx: watch::Receiver<bool>,
/// Channel to signal main loop on Ctrl+C.
/// In raw terminal mode, SIGINT is not generated, so TUI must signal
/// the main orchestration loop through this channel.
interrupt_tx: Option<watch::Sender<bool>>,
/// RPC writer for subprocess mode (replaces interrupt_tx for abort).
rpc_writer: Option<RpcWriter<W>>,
}
impl App<tokio::process::ChildStdin> {
/// Creates a new App with shared state, termination signal, and optional interrupt channel.
pub fn new(
state: Arc<Mutex<TuiState>>,
terminated_rx: watch::Receiver<bool>,
interrupt_tx: Option<watch::Sender<bool>>,
) -> Self {
Self {
state,
terminated_rx,
interrupt_tx,
rpc_writer: None,
}
}
}
impl<W: AsyncWrite + Unpin + Send + 'static> App<W> {
/// Creates a new App for subprocess mode with an RPC writer.
pub fn new_subprocess(
state: Arc<Mutex<TuiState>>,
terminated_rx: watch::Receiver<bool>,
rpc_writer: RpcWriter<W>,
) -> Self {
Self {
state,
terminated_rx,
interrupt_tx: None,
rpc_writer: Some(rpc_writer),
}
}
/// Runs the TUI event loop.
pub async fn run(mut self) -> Result<()> {
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
terminal.clear()?;
// CRITICAL: Ensure terminal cleanup on ANY exit path (normal, abort, or panic).
// When cleanup_tui() calls handle.abort(), the task is cancelled immediately
// at its current await point, skipping all code after the loop. This defer!
// guard runs on Drop, which is guaranteed even during task cancellation.
defer! {
let _ = disable_raw_mode();
let _ = execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture, Show);
}
// Event-driven architecture: input polling is the primary driver
// Render is throttled to ~60fps via interval tick
let mut events = EventStream::new();
let mut render_tick = interval(Duration::from_millis(16));
// Track viewport height for scroll calculations
let mut viewport_height: usize = 24; // Default, updated on render
loop {
// Use biased select to prioritize input over render ticks
tokio::select! {
biased;
// Priority 1: Handle input events immediately for responsiveness
maybe_event = events.next() => {
match maybe_event {
Some(Ok(event)) => {
match event {
// Handle Ctrl+C: signal main loop and exit.
// In raw mode, SIGINT is not generated, so we must signal the
// main orchestration loop through interrupt_tx channel or RPC writer.
Event::Key(key) if key.kind == KeyEventKind::Press
&& key.code == KeyCode::Char('c')
&& key.modifiers.contains(KeyModifiers::CONTROL) =>
{
info!("Ctrl+C detected, signaling abort");
if let Some(ref writer) = self.rpc_writer {
// Subprocess mode: send abort via RPC
let writer = writer.clone();
tokio::spawn(async move {
let _ = writer.send_abort().await;
});
} else if let Some(ref tx) = self.interrupt_tx {
// In-process mode: signal via channel
let _ = tx.send(true);
}
break;
}
Event::Mouse(mouse) => {
match mouse.kind {
MouseEventKind::ScrollUp => {
let mut state = self.state.lock().unwrap();
if let Some(buffer) = state.current_iteration_mut() {
for _ in 0..3 {
buffer.scroll_up();
}
}
}
MouseEventKind::ScrollDown => {
let mut state = self.state.lock().unwrap();
if let Some(buffer) = state.current_iteration_mut() {
for _ in 0..3 {
buffer.scroll_down(viewport_height);
}
}
}
_ => {}
}
}
Event::Paste(text) => {
let mut state = self.state.lock().unwrap();
if state.is_guidance_active() {
state.guidance_input.push_str(&text);
}
}
Event::Key(key) if key.kind == KeyEventKind::Press => {
// Guidance input mode: intercept all keys
{
let mut state = self.state.lock().unwrap();
if state.is_guidance_active() {
match key.code {
KeyCode::Esc => {
state.cancel_guidance();
}
KeyCode::Enter => {
// In subprocess mode, send via RPC
if let Some(ref writer) = self.rpc_writer {
let message = state.guidance_input.trim().to_string();
let mode = state.guidance_mode;
state.cancel_guidance(); // Clear input
if !message.is_empty() {
let writer = writer.clone();
tokio::spawn(async move {
let _ = match mode {
Some(crate::state::GuidanceMode::Now) => {
writer.send_steer(&message).await
}
_ => {
writer.send_guidance(&message).await
}
};
});
}
} else {
// In-process mode: use existing state method
state.send_guidance();
}
}
KeyCode::Backspace => {
state.guidance_input.pop();
}
KeyCode::Char(c) => {
state.guidance_input.push(c);
}
_ => {}
}
continue;
}
}
// Dismiss help on any key when help is showing
{
let mut state = self.state.lock().unwrap();
if state.show_help {
state.show_help = false;
continue;
}
}
// Map key to action and dispatch
let action = map_key(key);
let mut state = self.state.lock().unwrap();
if dispatch_action(action, &mut state, viewport_height) {
break;
}
}
// Ignore other events (FocusGained, FocusLost, Paste, Resize, key releases)
_ => {}
}
}
Some(Err(e)) => {
// Log error but continue - transient errors shouldn't crash TUI
tracing::warn!("Event stream error: {}", e);
}
None => {
// Stream ended unexpectedly
break;
}
}
}
// Priority 2: Render at throttled rate (~60fps)
_ = render_tick.tick() => {
let frame_size = terminal.size()?;
let frame_area = ratatui::layout::Rect::new(0, 0, frame_size.width, frame_size.height);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(2), // Header: content + bottom border
Constraint::Min(0), // Content: flexible
Constraint::Length(2), // Footer: top border + content
])
.split(frame_area);
let content_area = chunks[1];
viewport_height = content_area.height as usize;
let mut state = self.state.lock().unwrap();
// Clear expired flash messages (e.g., guidance send confirmation)
state.clear_expired_guidance_flash();
// Autoscroll: if user hasn't scrolled away, keep them at the bottom
// as new content arrives. This mimics standard terminal behavior.
if let Some(buffer) = state.current_iteration_mut()
&& buffer.following_bottom
{
let max_scroll = buffer.line_count().saturating_sub(viewport_height);
buffer.scroll_offset = max_scroll;
}
let state = state; // Rebind as immutable for rendering
terminal.draw(|f| {
// Render header
f.render_widget(header::render(&state, chunks[0].width), chunks[0]);
// Render content using ContentPane
if let Some(buffer) = state.current_iteration() {
let mut content_widget = ContentPane::new(buffer);
if let Some(query) = &state.search_state.query {
content_widget = content_widget.with_search(query);
}
f.render_widget(content_widget, content_area);
}
// Render footer
f.render_widget(footer::render(&state), chunks[2]);
// Render help overlay if active
if state.show_help {
help::render(f, f.area());
}
})?;
}
// Priority 3: Handle termination signal
_ = self.terminated_rx.changed() => {
if *self.terminated_rx.borrow() {
break;
}
}
}
}
// NOTE: Explicit cleanup removed - now handled by defer! guard above.
// The guard ensures cleanup happens even on task abort or panic.
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::input::{Action, map_key};
use crate::state::TuiState;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::text::Line;
// =========================================================================
// AC1: Events Reach State — TuiStreamHandler → IterationBuffer
// =========================================================================
#[test]
fn dispatch_action_scroll_down_calls_scroll_down_on_current_buffer() {
// Given TuiState with an iteration buffer containing content
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
for i in 0..20 {
buffer.append_line(Line::from(format!("line {}", i)));
}
let initial_offset = state.current_iteration().unwrap().scroll_offset;
assert_eq!(initial_offset, 0);
// When dispatch_action with ScrollDown and viewport_height 10
dispatch_action(Action::ScrollDown, &mut state, 10);
// Then scroll_offset is incremented
assert_eq!(
state.current_iteration().unwrap().scroll_offset,
1,
"scroll_down should increment scroll_offset"
);
}
// =========================================================================
// AC2: Keyboard Triggers Actions — 'j' → scroll_down()
// =========================================================================
#[test]
fn j_key_triggers_scroll_down_action() {
// Given key press 'j'
let key = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE);
// When map_key is called
let action = map_key(key);
// Then Action::ScrollDown is returned
assert_eq!(action, Action::ScrollDown);
}
#[test]
fn dispatch_action_scroll_up_calls_scroll_up_on_current_buffer() {
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
for i in 0..20 {
buffer.append_line(Line::from(format!("line {}", i)));
}
// Set initial scroll offset to 5
state.current_iteration_mut().unwrap().scroll_offset = 5;
dispatch_action(Action::ScrollUp, &mut state, 10);
assert_eq!(
state.current_iteration().unwrap().scroll_offset,
4,
"scroll_up should decrement scroll_offset"
);
}
#[test]
fn dispatch_action_scroll_top_jumps_to_top() {
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
for _ in 0..20 {
buffer.append_line(Line::from("line"));
}
state.current_iteration_mut().unwrap().scroll_offset = 10;
dispatch_action(Action::ScrollTop, &mut state, 10);
assert_eq!(state.current_iteration().unwrap().scroll_offset, 0);
}
#[test]
fn dispatch_action_scroll_bottom_jumps_to_bottom() {
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
for _ in 0..20 {
buffer.append_line(Line::from("line"));
}
dispatch_action(Action::ScrollBottom, &mut state, 10);
// max_scroll = 20 - 10 = 10
assert_eq!(state.current_iteration().unwrap().scroll_offset, 10);
}
#[test]
fn dispatch_action_next_iteration_navigates_forward() {
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 0;
state.following_latest = false;
dispatch_action(Action::NextIteration, &mut state, 10);
assert_eq!(state.current_view, 1);
}
#[test]
fn dispatch_action_prev_iteration_navigates_backward() {
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 2;
dispatch_action(Action::PrevIteration, &mut state, 10);
assert_eq!(state.current_view, 1);
}
#[test]
fn dispatch_action_show_help_sets_show_help() {
let mut state = TuiState::new();
assert!(!state.show_help);
dispatch_action(Action::ShowHelp, &mut state, 10);
assert!(state.show_help);
}
#[test]
fn dispatch_action_dismiss_help_clears_show_help() {
let mut state = TuiState::new();
state.show_help = true;
dispatch_action(Action::DismissHelp, &mut state, 10);
assert!(!state.show_help);
}
#[test]
fn dispatch_action_search_next_calls_next_match() {
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("find me"));
buffer.append_line(Line::from("find me again"));
state.search("find");
assert_eq!(state.search_state.current_match, 0);
dispatch_action(Action::SearchNext, &mut state, 10);
assert_eq!(state.search_state.current_match, 1);
}
#[test]
fn dispatch_action_search_prev_calls_prev_match() {
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("find me"));
buffer.append_line(Line::from("find me again"));
state.search("find");
state.search_state.current_match = 1;
dispatch_action(Action::SearchPrev, &mut state, 10);
assert_eq!(state.search_state.current_match, 0);
}
// =========================================================================
// AC5: Quit Returns True to Exit Loop
// =========================================================================
#[test]
fn dispatch_action_quit_returns_true() {
let mut state = TuiState::new();
let should_quit = dispatch_action(Action::Quit, &mut state, 10);
assert!(should_quit, "Quit action should return true to signal exit");
}
#[test]
fn dispatch_action_non_quit_returns_false() {
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("line"));
let should_quit = dispatch_action(Action::ScrollDown, &mut state, 10);
assert!(!should_quit, "Non-quit actions should return false");
}
// =========================================================================
// AC6: No PTY Code — Structural Test
// =========================================================================
#[test]
fn no_pty_handle_in_app() {
let source = include_str!("app.rs");
let test_module_start = source.find("#[cfg(test)]").unwrap_or(source.len());
let production_code = &source[..test_module_start];
// Check for PTY-related imports/code
assert!(
!production_code.contains("PtyHandle"),
"app.rs should not contain PtyHandle after refactor"
);
assert!(
!production_code.contains("tui_term"),
"app.rs should not contain tui_term references after refactor"
);
assert!(
!production_code.contains("TerminalWidget"),
"app.rs should not contain TerminalWidget after refactor"
);
}
/// Regression test: TUI must NOT have tokio::signal::ctrl_c() handler.
///
/// Raw mode prevents SIGINT, so tokio's signal handler never fires.
/// TUI must detect Ctrl+C directly via crossterm events.
#[test]
fn no_tokio_signal_handler_in_app() {
let source = include_str!("app.rs");
let pattern = ["tokio", "::", "signal", "::", "ctrl_c", "()"].concat();
let test_module_start = source.find("#[cfg(test)]").unwrap_or(source.len());
let production_code = &source[..test_module_start];
let occurrences: Vec<_> = production_code.match_indices(&pattern).collect();
assert!(
occurrences.is_empty(),
"Found {} occurrence(s) of tokio::signal::ctrl_c() in production code. \
This doesn't work in raw mode - use crossterm events instead.",
occurrences.len()
);
}
/// Verify Ctrl+C handling exists in production code.
///
/// Since raw mode prevents SIGINT, we must handle Ctrl+C via crossterm events.
/// TUI is observation-only, so Ctrl+C breaks out of the event loop.
#[test]
fn ctrl_c_handling_exists_in_app() {
let source = include_str!("app.rs");
let test_module_start = source.find("#[cfg(test)]").unwrap_or(source.len());
let production_code = &source[..test_module_start];
assert!(
production_code.contains("KeyCode::Char('c')")
&& production_code.contains("KeyModifiers::CONTROL"),
"Production code must detect Ctrl+C via crossterm events"
);
}
}