Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions crates/ox-tui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use crate::theme::Theme;

/// Number of lines scrolled by `PageUp` and `PageDown`.
const PAGE_SCROLL_STEP: u16 = 5;
/// Default number of recent turns kept visible when clearing the screen.
pub const DEFAULT_CLEAR_KEEP_TURNS: usize = 2;

/// Execution status of a tool call displayed in the transcript.
#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -69,6 +71,8 @@ pub enum AppStatus {
pub enum AppAction {
/// Submit a user prompt to the agent.
Submit(String),
/// Clear and force a full terminal redraw.
ClearScreen,
/// Exit the TUI cleanly.
Quit,
}
Expand All @@ -78,6 +82,9 @@ pub enum AppAction {
pub struct App {
model: String,
entries: Vec<TranscriptEntry>,
visible_start: usize,
hidden_turns: usize,
clear_keep_turns: usize,
messages: Vec<Message>,
input: String,
cursor: usize,
Expand All @@ -103,6 +110,9 @@ impl App {
Self {
model: model.into(),
entries: Vec::new(),
visible_start: 0,
hidden_turns: 0,
clear_keep_turns: DEFAULT_CLEAR_KEEP_TURNS,
messages: Vec::new(),
input: String::new(),
cursor: 0,
Expand Down Expand Up @@ -151,6 +161,13 @@ impl App {
self
}

/// Sets the default number of recent turns kept visible when clearing the screen.
#[must_use]
pub const fn with_clear_keep_turns(mut self, turns: usize) -> Self {
self.clear_keep_turns = turns;
self
}

/// Returns the active model identifier.
pub fn model(&self) -> &str {
&self.model
Expand All @@ -161,6 +178,21 @@ impl App {
&self.entries
}

/// Returns the currently visible slice of transcript entries.
pub fn visible_entries(&self) -> &[TranscriptEntry] {
&self.entries[self.visible_start.min(self.entries.len())..]
}

/// Returns the number of earlier turns hidden above the visible transcript window.
pub const fn hidden_turns(&self) -> usize {
self.hidden_turns
}

/// Returns the configured default number of recent turns kept visible on clear-screen.
pub const fn clear_keep_turns(&self) -> usize {
self.clear_keep_turns
}

/// Returns the full conversation history passed to the agent.
pub fn messages(&self) -> &[Message] {
&self.messages
Expand Down Expand Up @@ -411,6 +443,35 @@ impl App {
}
}

/// Hides earlier turns above a visual divider without mutating session history.
///
/// Keeps the most recent `keep_turns` user turns visible (or [`Self::clear_keep_turns`] when
/// `None`) and resets the transcript scroll offset to the bottom.
pub fn clear_screen(&mut self, keep_turns: Option<usize>) {
let keep = keep_turns.unwrap_or(self.clear_keep_turns);
let turn_starts: Vec<usize> = self
.entries
.iter()
.enumerate()
.filter_map(|(idx, entry)| matches!(entry, TranscriptEntry::User(_)).then_some(idx))
.collect();
let total_turns = turn_starts.len();

if keep == 0 {
self.visible_start = self.entries.len();
self.hidden_turns = total_turns;
} else if total_turns > keep {
let hidden = total_turns - keep;
self.visible_start = turn_starts[hidden];
self.hidden_turns = hidden;
} else {
self.visible_start = 0;
self.hidden_turns = 0;
}

self.scroll = 0;
}

/// Handles a terminal key event and returns any [`AppAction`] for the runner to execute.
pub fn handle_key(&mut self, key: KeyEvent) -> Option<AppAction> {
if key.kind != KeyEventKind::Press {
Expand Down Expand Up @@ -471,6 +532,11 @@ impl App {
None
}

CommandId::ClearScreen => {
self.clear_screen(None);
Some(AppAction::ClearScreen)
}

CommandId::Submit => self.handle_submit(),

CommandId::InsertNewline => {
Expand Down Expand Up @@ -562,11 +628,18 @@ impl App {

CommandEffect::ClearTranscript => {
self.entries.clear();
self.visible_start = 0;
self.hidden_turns = 0;
self.messages.clear();
self.scroll = 0;
None
}

CommandEffect::ClearScreen(keep_turns) => {
self.clear_screen(keep_turns);
Some(AppAction::ClearScreen)
}

CommandEffect::SystemMessage(msg) => {
self.entries.push(TranscriptEntry::System(msg));
self.scroll = 0;
Expand Down Expand Up @@ -798,6 +871,79 @@ mod tests {
);
}

#[test]
fn clear_screen_hides_earlier_turns_without_mutating_history() {
let mut app = App::new("gemini-4-hydrogen").with_clear_keep_turns(2);
assert_eq!(app.clear_keep_turns(), 2);

let mut history = Vec::new();
for i in 1..=4 {
let prompt = format!("turn-{i}");
let reply = format!("reply-{i}");
app.submit_user_message(prompt.clone());
app.apply_agent_event(AgentEvent::TextDelta(reply.clone()));
history.push(Message::user(prompt));
history.push(Message::assistant(reply));
app.apply_agent_event(AgentEvent::Done {
reason: AgentStopReason::Completed(StopReason::EndTurn),
turns: 1,
messages: history.clone(),
});
}

// Scroll up, then trigger Ctrl+L.
app.handle_key(key(KeyCode::PageUp));
assert!(app.scroll() > 0);

assert_eq!(
app.handle_key(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)),
Some(AppAction::ClearScreen)
);
assert_eq!(app.scroll(), 0);
assert_eq!(app.hidden_turns(), 2);
assert_eq!(app.entries().len(), 8);
assert_eq!(app.messages().len(), 8);
assert_eq!(
app.visible_entries(),
&[
TranscriptEntry::User("turn-3".into()),
TranscriptEntry::Assistant("reply-3".into()),
TranscriptEntry::User("turn-4".into()),
TranscriptEntry::Assistant("reply-4".into()),
]
);

// /clear-screen 1 keeps only the latest turn.
type_text(&mut app, "/clear-screen 1");
assert_eq!(
app.handle_key(key(KeyCode::Enter)),
Some(AppAction::ClearScreen)
);
assert_eq!(app.hidden_turns(), 3);
assert_eq!(
app.visible_entries(),
&[
TranscriptEntry::User("turn-4".into()),
TranscriptEntry::Assistant("reply-4".into()),
]
);

// /clear-screen 0 hides all turns while keeping history intact.
type_text(&mut app, "/clear-screen 0");
assert_eq!(
app.handle_key(key(KeyCode::Enter)),
Some(AppAction::ClearScreen)
);
assert_eq!(app.hidden_turns(), 4);
assert_eq!(app.visible_entries(), []);
assert_eq!(app.messages().len(), 8);

// Keeping more turns than exist shows everything.
app.clear_screen(Some(10));
assert_eq!(app.hidden_turns(), 0);
assert_eq!(app.visible_entries().len(), 8);
}

#[test]
fn handle_key_edits_input_and_submits() {
let mut app = App::new("gemini-4-hydrogen");
Expand Down
34 changes: 34 additions & 0 deletions crates/ox-tui/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub enum CommandEffect {
Quit,
/// Clear the transcript and conversation history.
ClearTranscript,
/// Redraw the screen and hide earlier turns, keeping an optional number of recent turns.
ClearScreen(Option<usize>),
/// Append a system message to the transcript.
SystemMessage(String),
/// Open an inline [`Overlay`] primitive.
Expand Down Expand Up @@ -58,6 +60,21 @@ impl CommandRegistry {
registry.register("clear", "Clear transcript and conversation history", |_| {
CommandEffect::ClearTranscript
});
registry.register(
"clear-screen",
"Redraw screen and hide earlier turns (keeps history)",
|args| {
if args.is_empty() {
CommandEffect::ClearScreen(None)
} else if let Ok(keep) = args.parse::<usize>() {
CommandEffect::ClearScreen(Some(keep))
} else {
CommandEffect::SystemMessage(format!(
"invalid turn count for /clear-screen: {args}"
))
}
},
);
registry.register(
"help",
"Show available slash commands and keybindings",
Expand Down Expand Up @@ -137,6 +154,7 @@ impl CommandRegistry {
fn format_help(&self) -> String {
const KEYBINDINGS: &[(&str, &str)] = &[
("Ctrl+C", "Quit"),
("Ctrl+L", "Clear screen (keep recent turns)"),
("Ctrl+O", "Toggle tool output"),
("Esc", "Dismiss overlay"),
];
Expand Down Expand Up @@ -198,6 +216,20 @@ mod tests {
registry.dispatch("/clear"),
Some(CommandEffect::ClearTranscript)
);
assert_eq!(
registry.dispatch("/clear-screen"),
Some(CommandEffect::ClearScreen(None))
);
assert_eq!(
registry.dispatch("/clear-screen 3"),
Some(CommandEffect::ClearScreen(Some(3)))
);
assert_eq!(
registry.dispatch("/clear-screen nope"),
Some(CommandEffect::SystemMessage(
"invalid turn count for /clear-screen: nope".into()
))
);

let Some(CommandEffect::SystemMessage(help)) = registry.dispatch("/help") else {
panic!("expected help system message");
Expand All @@ -207,11 +239,13 @@ mod tests {
indoc::indoc! {"
Commands:
/clear Clear transcript and conversation history
/clear-screen Redraw screen and hide earlier turns (keeps history)
/help Show available slash commands and keybindings
/quit (/exit, /q) Exit the TUI

Keybindings:
Ctrl+C Quit
Ctrl+L Clear screen (keep recent turns)
Ctrl+O Toggle tool output
Esc Dismiss overlay"
}
Expand Down
7 changes: 7 additions & 0 deletions crates/ox-tui/src/keymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ pub enum CommandId {
DismissOverlay,
/// Toggle expanded/collapsed tool call details.
ToggleExpand,
/// Redraw the terminal and hide earlier turns while preserving history.
ClearScreen,
/// Submit the current input buffer or slash command.
Submit,
/// Insert a literal newline in the input buffer.
Expand Down Expand Up @@ -87,6 +89,7 @@ impl Default for Keymap {
let mut bindings = HashMap::new();
bindings.insert(KeyChord::ctrl('c'), CommandId::Quit);
bindings.insert(KeyChord::ctrl('d'), CommandId::QuitIfEmpty);
bindings.insert(KeyChord::ctrl('l'), CommandId::ClearScreen);
bindings.insert(KeyChord::ctrl('o'), CommandId::ToggleExpand);
bindings.insert(KeyChord::plain(KeyCode::Esc), CommandId::DismissOverlay);
bindings.insert(KeyChord::plain(KeyCode::Enter), CommandId::Submit);
Expand Down Expand Up @@ -147,6 +150,10 @@ mod tests {
keymap.resolve(&KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)),
Some(CommandId::QuitIfEmpty)
);
assert_eq!(
keymap.resolve(&KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)),
Some(CommandId::ClearScreen)
);
assert_eq!(
keymap.resolve(&KeyEvent::new(KeyCode::Char('o'), KeyModifiers::CONTROL)),
Some(CommandId::ToggleExpand)
Expand Down
4 changes: 3 additions & 1 deletion crates/ox-tui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ mod statusline;
mod theme;
mod ui;

pub use app::{App, AppAction, AppStatus, ToolCallStatus, TranscriptEntry};
pub use app::{
App, AppAction, AppStatus, DEFAULT_CLEAR_KEEP_TURNS, ToolCallStatus, TranscriptEntry,
};
pub use command::{CommandEffect, CommandRegistry, CommandSpec};
pub use keymap::{CommandId, KeyChord, Keymap};
pub use markdown::{MarkdownCache, render_markdown, render_markdown_incremental};
Expand Down
40 changes: 40 additions & 0 deletions crates/ox-tui/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ where
active_stream = Some(start_turn(messages));
}

Some(AppAction::ClearScreen) => {
terminal.clear()?;
}

Some(AppAction::Quit) => break,

None => {}
Expand Down Expand Up @@ -308,4 +312,40 @@ mod tests {
.expect_err("event stream error should propagate");
assert!(err.to_string().contains("tty closed"));
}

#[tokio::test]
async fn run_loop_clears_terminal_on_ctrl_l() {
let backend = TestBackend::new(80, 12);
let mut terminal = Terminal::new(backend).expect("create test terminal");
let mut app = App::new("gemini-4-hydrogen");

for i in 1..=3 {
app.submit_user_message(format!("turn-{i}"));
app.apply_agent_event(ox_core::agent::AgentEvent::Done {
reason: ox_core::agent::AgentStopReason::Completed(StopReason::EndTurn),
turns: 1,
messages: Vec::new(),
});
}

let mut events = Box::pin(stream::iter(vec![
Ok(Event::Key(KeyEvent::new(
KeyCode::Char('l'),
KeyModifiers::CONTROL,
))),
Ok(Event::Key(KeyEvent::new(
KeyCode::Char('c'),
KeyModifiers::CONTROL,
))),
]));

run_loop(&mut terminal, &mut app, &mut events, |_| {
Box::pin(stream::empty())
})
.await
.expect("run_loop should handle Ctrl+L cleanly");

assert_eq!(app.hidden_turns(), 1);
assert!(app.should_quit());
}
}
Loading
Loading