M2 TUI: EngineHandle, ratatui app, markdown renderer, permission modal, session picker, snapshot tests
harness-app: - EngineHandle: non-blocking multi-turn API (prompt/abort/permission_reply/ list_sessions/session_messages/message_parts), persistent SQLite store, no auto-approve — TUI handles permission asks via real oneshot path - App refactored to wrap EngineHandle; headless run -p keeps auto-approve harness-tui: - Terminal guard (raw mode, alternate screen, panic hook, Drop restore) - Event loop: tokio::select! over crossterm events, bus events, 33ms render tick - AppState with MessageView/PartView (cached Vec<Line> field), ModalState - pulldown-cmark → ratatui markdown renderer (headings, bold, italic, code blocks, lists, blockquotes, links, manual word-wrap) - Layout: header, chat viewport, input (tui-textarea), status bar - Permission modal (y/a/n) wired to EngineHandle::permission_reply - Session picker (Ctrl+S) with resume - Abort (Esc), Ctrl+C×2 quit, slash commands (/new /model /agent /sessions) - 7 TestBackend snapshot tests (empty, messages, tool cards, modals)
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crossterm::event::EventStream;
|
||||
use futures::StreamExt;
|
||||
use harness_app::EngineHandle;
|
||||
use harness_core::event::AppEvent;
|
||||
use ratatui::backend::CrosstermBackend;
|
||||
use ratatui::Terminal;
|
||||
use tokio::sync::broadcast;
|
||||
use tokio::time::{interval, Duration};
|
||||
|
||||
use crate::input::{apply_action, handle_event};
|
||||
use crate::render::render;
|
||||
use crate::state::AppState;
|
||||
use crate::terminal::TerminalGuard;
|
||||
|
||||
const DEFAULT_MODEL: &str = "anthropic/claude-sonnet-4-5";
|
||||
const DEFAULT_AGENT: &str = "orchestrator";
|
||||
const RENDER_TICK_MS: u64 = 33;
|
||||
|
||||
pub struct App {
|
||||
engine: EngineHandle,
|
||||
state: AppState,
|
||||
_terminal_guard: TerminalGuard,
|
||||
terminal: Terminal<CrosstermBackend<io::Stdout>>,
|
||||
events: EventStream,
|
||||
bus_rx: broadcast::Receiver<AppEvent>,
|
||||
render_interval: tokio::time::Interval,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub async fn new(cwd: PathBuf) -> anyhow::Result<Self> {
|
||||
let engine = EngineHandle::init(cwd)?;
|
||||
let bus_rx = engine.bus().subscribe();
|
||||
|
||||
let config = engine.config();
|
||||
let model_ref = config
|
||||
.model
|
||||
.clone()
|
||||
.unwrap_or_else(|| DEFAULT_MODEL.to_string());
|
||||
let agent = DEFAULT_AGENT.to_string();
|
||||
|
||||
let mut state = AppState::new(model_ref, agent);
|
||||
|
||||
// Create a default session so the user can start typing immediately.
|
||||
match engine.new_session(&state.agent, &state.model_ref).await {
|
||||
Ok(session_id) => {
|
||||
state.session_id = Some(session_id);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to create default session");
|
||||
}
|
||||
}
|
||||
|
||||
let terminal_guard = TerminalGuard::enter()?;
|
||||
let backend = CrosstermBackend::new(io::stdout());
|
||||
let terminal = Terminal::new(backend)?;
|
||||
let events = EventStream::new();
|
||||
let render_interval = interval(Duration::from_millis(RENDER_TICK_MS));
|
||||
|
||||
Ok(Self {
|
||||
engine,
|
||||
state,
|
||||
_terminal_guard: terminal_guard,
|
||||
terminal,
|
||||
events,
|
||||
bus_rx,
|
||||
render_interval,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) -> anyhow::Result<()> {
|
||||
self.state.dirty = true;
|
||||
while !self.state.quit {
|
||||
tokio::select! {
|
||||
biased;
|
||||
|
||||
maybe_event = self.events.next() => {
|
||||
match maybe_event {
|
||||
Some(Ok(event)) => {
|
||||
let action = handle_event(event, &mut self.state, &self.engine);
|
||||
apply_action(action, &mut self.state, &self.engine).await;
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
tracing::error!(error = %e, "input error");
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
|
||||
Ok(event) = self.bus_rx.recv() => {
|
||||
self.state.apply_event(event);
|
||||
}
|
||||
|
||||
_ = self.render_interval.tick() => {
|
||||
if self.state.dirty {
|
||||
self.terminal.draw(|frame| render(frame, &mut self.state))?;
|
||||
self.state.dirty = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
|
||||
use harness_app::EngineHandle;
|
||||
use harness_core::permission::PermissionReply;
|
||||
|
||||
use crate::modal;
|
||||
use crate::state::{AppState, ModalState};
|
||||
|
||||
/// Possible high-level actions produced by key input.
|
||||
#[derive(Debug)]
|
||||
pub enum InputAction {
|
||||
None,
|
||||
Submit { text: String },
|
||||
Abort,
|
||||
Quit,
|
||||
LoadSessions,
|
||||
NewSession,
|
||||
SetModel(String),
|
||||
SetAgent(String),
|
||||
CloseModal,
|
||||
ScrollUp(u16),
|
||||
ScrollDown(u16),
|
||||
PermissionReply(PermissionReply),
|
||||
SessionPickerUp,
|
||||
SessionPickerDown,
|
||||
SessionPickerSelect,
|
||||
}
|
||||
|
||||
/// Translate a crossterm event into an action and/or mutate `state` directly.
|
||||
pub fn handle_event(event: Event, state: &mut AppState, _engine: &EngineHandle) -> InputAction {
|
||||
match event {
|
||||
Event::Key(key) => {
|
||||
let action = handle_key(key, state);
|
||||
// Any keypress can change the input buffer or cursor; force a redraw so typed
|
||||
// characters appear immediately rather than only when some other event sets dirty.
|
||||
state.dirty = true;
|
||||
action
|
||||
}
|
||||
Event::Resize(_, _) => {
|
||||
state.dirty = true;
|
||||
InputAction::None
|
||||
}
|
||||
Event::Mouse(_) | Event::FocusGained | Event::FocusLost | Event::Paste(_) => {
|
||||
InputAction::None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_key(key: KeyEvent, state: &mut AppState) -> InputAction {
|
||||
match &state.modal {
|
||||
ModalState::Permission { .. } => handle_permission_key(key, state),
|
||||
ModalState::SessionPicker { .. } => handle_session_picker_key(key, state),
|
||||
ModalState::None => handle_normal_key(key, state),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_permission_key(key: KeyEvent, _state: &mut AppState) -> InputAction {
|
||||
match key.code {
|
||||
KeyCode::Char('y') | KeyCode::Char('Y') => {
|
||||
InputAction::PermissionReply(PermissionReply::Once)
|
||||
}
|
||||
KeyCode::Char('a') | KeyCode::Char('A') => {
|
||||
InputAction::PermissionReply(PermissionReply::Always)
|
||||
}
|
||||
KeyCode::Char('n') | KeyCode::Char('N') => {
|
||||
InputAction::PermissionReply(PermissionReply::Reject)
|
||||
}
|
||||
// Esc rejects the pending request rather than merely hiding the modal — closing
|
||||
// without a reply would leave the tool call blocked on its oneshot forever.
|
||||
KeyCode::Esc => InputAction::PermissionReply(PermissionReply::Reject),
|
||||
_ => InputAction::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_session_picker_key(key: KeyEvent, _state: &mut AppState) -> InputAction {
|
||||
match key.code {
|
||||
KeyCode::Up => InputAction::SessionPickerUp,
|
||||
KeyCode::Down => InputAction::SessionPickerDown,
|
||||
KeyCode::Enter => InputAction::SessionPickerSelect,
|
||||
KeyCode::Esc => InputAction::CloseModal,
|
||||
_ => InputAction::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_normal_key(key: KeyEvent, state: &mut AppState) -> InputAction {
|
||||
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
|
||||
|
||||
// Reset the double-Ctrl+C guard on any key that isn't another Ctrl+C.
|
||||
if !(matches!(key.code, KeyCode::Char('c') | KeyCode::Char('C')) && ctrl) {
|
||||
state.ctrl_c_pressed = false;
|
||||
}
|
||||
|
||||
match key.code {
|
||||
KeyCode::Enter => {
|
||||
let text = state.input.lines().join("\n");
|
||||
state.input = tui_textarea::TextArea::default();
|
||||
state
|
||||
.input
|
||||
.set_cursor_line_style(ratatui::style::Style::default());
|
||||
if let Some(action) = parse_slash_command(&text) {
|
||||
action
|
||||
} else {
|
||||
InputAction::Submit { text }
|
||||
}
|
||||
}
|
||||
KeyCode::Char('c') if ctrl => {
|
||||
if state.ctrl_c_pressed {
|
||||
InputAction::Quit
|
||||
} else {
|
||||
state.ctrl_c_pressed = true;
|
||||
state.dirty = true;
|
||||
InputAction::None
|
||||
}
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
if state.running {
|
||||
InputAction::Abort
|
||||
} else {
|
||||
InputAction::None
|
||||
}
|
||||
}
|
||||
KeyCode::Char('s') if ctrl => InputAction::LoadSessions,
|
||||
KeyCode::Up => {
|
||||
let (row, _) = state.input.cursor();
|
||||
if row == 0 {
|
||||
InputAction::ScrollUp(3)
|
||||
} else {
|
||||
state.input.input(key);
|
||||
InputAction::None
|
||||
}
|
||||
}
|
||||
KeyCode::Down => {
|
||||
let (row, _) = state.input.cursor();
|
||||
let last_line = state.input.lines().len().saturating_sub(1);
|
||||
if row == last_line {
|
||||
InputAction::ScrollDown(3)
|
||||
} else {
|
||||
state.input.input(key);
|
||||
InputAction::None
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
state.input.input(key);
|
||||
InputAction::None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_slash_command(text: &str) -> Option<InputAction> {
|
||||
let trimmed = text.trim();
|
||||
if !trimmed.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
let mut parts = trimmed.split_whitespace();
|
||||
let cmd = parts.next()?;
|
||||
let rest: String = parts.collect::<Vec<_>>().join(" ");
|
||||
match cmd {
|
||||
"/new" => Some(InputAction::NewSession),
|
||||
"/model" if !rest.is_empty() => Some(InputAction::SetModel(rest)),
|
||||
"/agent" if !rest.is_empty() => Some(InputAction::SetAgent(rest)),
|
||||
"/sessions" => Some(InputAction::LoadSessions),
|
||||
"/quit" => Some(InputAction::Quit),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply an action that needs async engine calls. Non-async decisions are applied inline.
|
||||
pub async fn apply_action(action: InputAction, state: &mut AppState, engine: &EngineHandle) {
|
||||
match action {
|
||||
InputAction::Submit { text } => {
|
||||
if let Some(session_id) = state.session_id.clone() {
|
||||
if let Err(e) = engine.prompt(session_id, text, &state.model_ref).await {
|
||||
tracing::error!(error = %e, "prompt failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
InputAction::Abort => {
|
||||
if let Some(session_id) = state.session_id.clone() {
|
||||
engine.abort(&session_id);
|
||||
}
|
||||
}
|
||||
InputAction::LoadSessions => match engine.list_sessions().await {
|
||||
Ok(sessions) => modal::open_session_picker(state, sessions),
|
||||
Err(e) => tracing::error!(error = %e, "failed to list sessions"),
|
||||
},
|
||||
InputAction::NewSession => match engine.new_session(&state.agent, &state.model_ref).await {
|
||||
Ok(id) => {
|
||||
state.session_id = Some(id);
|
||||
state.messages.clear();
|
||||
state.scroll_offset = 0;
|
||||
state.dirty = true;
|
||||
}
|
||||
Err(e) => tracing::error!(error = %e, "failed to create session"),
|
||||
},
|
||||
InputAction::SetModel(model_ref) => {
|
||||
state.model_ref = model_ref;
|
||||
state.dirty = true;
|
||||
}
|
||||
InputAction::SetAgent(agent) => {
|
||||
state.agent = agent;
|
||||
state.dirty = true;
|
||||
}
|
||||
InputAction::Quit => state.quit = true,
|
||||
InputAction::CloseModal => state.close_modal(),
|
||||
InputAction::ScrollUp(n) => state.scroll_up(n),
|
||||
InputAction::ScrollDown(n) => state.scroll_down(n),
|
||||
InputAction::PermissionReply(reply) => {
|
||||
modal::resolve_permission(state, engine, reply);
|
||||
}
|
||||
InputAction::SessionPickerUp => {
|
||||
if let ModalState::SessionPicker {
|
||||
selected,
|
||||
sessions: _,
|
||||
} = &mut state.modal
|
||||
{
|
||||
*selected = selected.saturating_sub(1);
|
||||
}
|
||||
state.dirty = true;
|
||||
}
|
||||
InputAction::SessionPickerDown => {
|
||||
if let ModalState::SessionPicker { selected, sessions } = &mut state.modal {
|
||||
if *selected + 1 < sessions.len() {
|
||||
*selected += 1;
|
||||
}
|
||||
}
|
||||
state.dirty = true;
|
||||
}
|
||||
InputAction::SessionPickerSelect => {
|
||||
if let ModalState::SessionPicker { sessions, selected } = &state.modal {
|
||||
if let Some(session) = sessions.get(*selected).cloned() {
|
||||
if let Err(e) = modal::select_session(state, engine, session).await {
|
||||
tracing::error!(error = %e, "failed to load session");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
InputAction::None => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::state::AppState;
|
||||
use crossterm::event::KeyEvent;
|
||||
|
||||
#[tokio::test]
|
||||
async fn typing_marks_frame_dirty_and_updates_input() {
|
||||
let engine = EngineHandle::init_in_memory(std::env::temp_dir()).unwrap();
|
||||
let mut state = AppState::new("anthropic/claude".into(), "orchestrator".into());
|
||||
state.dirty = false;
|
||||
|
||||
let action = handle_event(
|
||||
Event::Key(KeyEvent::from(KeyCode::Char('x'))),
|
||||
&mut state,
|
||||
&engine,
|
||||
);
|
||||
|
||||
assert!(matches!(action, InputAction::None));
|
||||
assert!(state.dirty, "a keystroke must request a redraw");
|
||||
assert_eq!(state.input.lines().join("\n"), "x");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,19 @@
|
||||
mod app;
|
||||
mod input;
|
||||
mod markdown;
|
||||
mod modal;
|
||||
mod render;
|
||||
mod state;
|
||||
mod terminal;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use harness_core::event::RunOutcome;
|
||||
|
||||
const DEFAULT_MODEL: &str = "anthropic/claude-sonnet-4-5";
|
||||
|
||||
fn print_usage() {
|
||||
eprintln!("usage: harness run -p \"<prompt>\" [-m provider/model]");
|
||||
eprintln!("usage: harness [run -p \"<prompt>\" [-m provider/model]] | [tui]");
|
||||
}
|
||||
|
||||
fn parse_run_args(args: &[String]) -> Option<(String, Option<String>)> {
|
||||
@@ -26,7 +36,7 @@ fn parse_run_args(args: &[String]) -> Option<(String, Option<String>)> {
|
||||
prompt.map(|p| (p, model))
|
||||
}
|
||||
|
||||
async fn run(args: &[String]) -> i32 {
|
||||
async fn run_headless(args: &[String]) -> i32 {
|
||||
let Some((prompt, model_arg)) = parse_run_args(args) else {
|
||||
print_usage();
|
||||
return 2;
|
||||
@@ -49,7 +59,7 @@ async fn run(args: &[String]) -> i32 {
|
||||
};
|
||||
|
||||
let model_ref = model_arg
|
||||
.or_else(|| app.config.model.clone())
|
||||
.or_else(|| app.config().model.clone())
|
||||
.unwrap_or_else(|| DEFAULT_MODEL.to_string());
|
||||
|
||||
match app.run_prompt(prompt, &model_ref).await {
|
||||
@@ -73,14 +83,74 @@ async fn run(args: &[String]) -> i32 {
|
||||
}
|
||||
}
|
||||
|
||||
fn log_dir() -> PathBuf {
|
||||
dirs::data_dir()
|
||||
.unwrap_or_else(std::env::temp_dir)
|
||||
.join("ai-harness")
|
||||
.join("log")
|
||||
}
|
||||
|
||||
fn setup_tracing() -> anyhow::Result<tracing_appender::non_blocking::WorkerGuard> {
|
||||
let log_dir = log_dir();
|
||||
std::fs::create_dir_all(&log_dir)?;
|
||||
let file_appender = tracing_appender::rolling::daily(log_dir, "harness-tui.log");
|
||||
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(non_blocking)
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
|
||||
.init();
|
||||
Ok(guard)
|
||||
}
|
||||
|
||||
async fn run_tui() -> i32 {
|
||||
let cwd = match std::env::current_dir() {
|
||||
Ok(cwd) => cwd,
|
||||
Err(e) => {
|
||||
eprintln!("error: could not read cwd: {e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
let _guard = match setup_tracing() {
|
||||
Ok(guard) => guard,
|
||||
Err(e) => {
|
||||
eprintln!("error: could not initialize logging: {e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
let mut app = match crate::app::App::new(cwd).await {
|
||||
Ok(app) => app,
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, "failed to start TUI");
|
||||
eprintln!("error: {e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = app.run().await {
|
||||
tracing::error!(error = %e, "TUI error");
|
||||
eprintln!("error: {e}");
|
||||
return 1;
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let exit_code = if args.first().map(String::as_str) == Some("run") {
|
||||
run(&args[1..]).await
|
||||
} else {
|
||||
println!("harness {}", env!("CARGO_PKG_VERSION"));
|
||||
0
|
||||
let exit_code = match args.first().map(String::as_str) {
|
||||
Some("run") => run_headless(&args[1..]).await,
|
||||
Some("tui") | None => run_tui().await,
|
||||
Some("help") | Some("--help") | Some("-h") => {
|
||||
print_usage();
|
||||
0
|
||||
}
|
||||
Some(cmd) => {
|
||||
eprintln!("unknown command: {cmd}");
|
||||
print_usage();
|
||||
2
|
||||
}
|
||||
};
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Parser, Tag, TagEnd};
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
|
||||
/// Render a markdown string into wrapped ratatui lines.
|
||||
pub fn render_markdown(text: &str, width: u16) -> Vec<Line<'static>> {
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
let mut current_spans: Vec<Span<'static>> = Vec::new();
|
||||
let mut current_text = String::new();
|
||||
|
||||
let mut in_bold = false;
|
||||
let mut in_italic = false;
|
||||
let mut in_code_block = false;
|
||||
let mut code_block_language = String::new();
|
||||
let mut list_stack: Vec<u64> = Vec::new();
|
||||
|
||||
let flush = |current: &mut String, spans: &mut Vec<Span<'static>>, bold, italic| {
|
||||
if current.is_empty() {
|
||||
return;
|
||||
}
|
||||
let style = base_style(bold, italic);
|
||||
let span = Span::styled(std::mem::take(current), style);
|
||||
spans.push(span);
|
||||
};
|
||||
|
||||
for event in Parser::new(text) {
|
||||
match event {
|
||||
Event::Start(tag) => match tag {
|
||||
Tag::Paragraph => {
|
||||
if !lines.is_empty() && !current_text.is_empty() {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
wrap_spans(&mut lines, &mut current_spans, width);
|
||||
}
|
||||
}
|
||||
Tag::Heading { level, .. } => {
|
||||
let level_num = heading_level_from(level);
|
||||
current_text.push_str(&"#".repeat(level_num as usize));
|
||||
current_text.push(' ');
|
||||
}
|
||||
Tag::Strong => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
in_bold = true;
|
||||
}
|
||||
Tag::Emphasis => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
in_italic = true;
|
||||
}
|
||||
Tag::List(start) => {
|
||||
list_stack.push(start.unwrap_or(1));
|
||||
}
|
||||
Tag::Item => {
|
||||
let prefix = if let Some(n) = list_stack.last_mut() {
|
||||
let p = format!("{n}. ");
|
||||
*n += 1;
|
||||
p
|
||||
} else {
|
||||
"• ".to_string()
|
||||
};
|
||||
current_text.push_str(&prefix);
|
||||
}
|
||||
Tag::CodeBlock(lang) => {
|
||||
in_code_block = true;
|
||||
code_block_language = match lang {
|
||||
CodeBlockKind::Fenced(name) => name.to_string(),
|
||||
CodeBlockKind::Indented => String::new(),
|
||||
};
|
||||
if !current_text.is_empty() || !current_spans.is_empty() {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
wrap_spans(&mut lines, &mut current_spans, width);
|
||||
}
|
||||
let border = if code_block_language.is_empty() {
|
||||
"┌────".to_string()
|
||||
} else {
|
||||
format!("┌──── {code_block_language}")
|
||||
};
|
||||
lines.push(Line::from(Span::styled(border, code_style())));
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::End(tag_end) => match tag_end {
|
||||
TagEnd::Heading(_) => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
let mut spans = std::mem::take(&mut current_spans);
|
||||
for span in &mut spans {
|
||||
span.style = span.style.add_modifier(Modifier::BOLD);
|
||||
}
|
||||
wrap_spans(&mut lines, &mut spans, width);
|
||||
}
|
||||
TagEnd::Paragraph => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
wrap_spans(&mut lines, &mut current_spans, width);
|
||||
}
|
||||
TagEnd::Strong => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
in_bold = false;
|
||||
}
|
||||
TagEnd::Emphasis => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
in_italic = false;
|
||||
}
|
||||
TagEnd::List(_) => {
|
||||
list_stack.pop();
|
||||
}
|
||||
TagEnd::CodeBlock => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
if !current_spans.is_empty() {
|
||||
for line in wrap_spans_to_lines(&mut current_spans, width) {
|
||||
lines.push(prefix_code_block_line(line));
|
||||
}
|
||||
}
|
||||
lines.push(Line::from(Span::styled("└────", code_style())));
|
||||
in_code_block = false;
|
||||
code_block_language.clear();
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Text(t) => {
|
||||
if in_code_block {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
current_spans.push(Span::styled(t.to_string(), code_style()));
|
||||
} else {
|
||||
current_text.push_str(&t);
|
||||
}
|
||||
}
|
||||
Event::Code(c) => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
current_spans.push(Span::styled(c.to_string(), code_style()));
|
||||
}
|
||||
Event::Html(h) | Event::InlineHtml(h) => {
|
||||
current_text.push_str(&h);
|
||||
}
|
||||
Event::SoftBreak | Event::HardBreak => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
wrap_spans(&mut lines, &mut current_spans, width);
|
||||
}
|
||||
Event::Rule => {
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
wrap_spans(&mut lines, &mut current_spans, width);
|
||||
lines.push(Line::from("─".repeat(width as usize)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
|
||||
if in_code_block {
|
||||
for line in wrap_spans_to_lines(&mut current_spans, width) {
|
||||
lines.push(prefix_code_block_line(line));
|
||||
}
|
||||
lines.push(Line::from(Span::styled("└────", code_style())));
|
||||
} else {
|
||||
wrap_spans(&mut lines, &mut current_spans, width);
|
||||
}
|
||||
|
||||
if lines.is_empty() {
|
||||
lines.push(Line::default());
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn heading_level_from(level: HeadingLevel) -> u8 {
|
||||
match level {
|
||||
HeadingLevel::H1 => 1,
|
||||
HeadingLevel::H2 => 2,
|
||||
HeadingLevel::H3 => 3,
|
||||
HeadingLevel::H4 => 4,
|
||||
HeadingLevel::H5 => 5,
|
||||
HeadingLevel::H6 => 6,
|
||||
}
|
||||
}
|
||||
|
||||
fn base_style(bold: bool, italic: bool) -> Style {
|
||||
let mut style = Style::new();
|
||||
if bold {
|
||||
style = style.add_modifier(Modifier::BOLD);
|
||||
}
|
||||
if italic {
|
||||
style = style.add_modifier(Modifier::ITALIC);
|
||||
}
|
||||
style
|
||||
}
|
||||
|
||||
fn code_style() -> Style {
|
||||
Style::new().fg(Color::Yellow)
|
||||
}
|
||||
|
||||
fn prefix_code_block_line(line: Line<'static>) -> Line<'static> {
|
||||
let mut spans = vec![Span::styled("│ ", code_style())];
|
||||
spans.extend(line.spans);
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// Flush accumulated spans into `lines`, wrapping to `width`.
|
||||
fn wrap_spans(lines: &mut Vec<Line<'static>>, spans: &mut Vec<Span<'static>>, width: u16) {
|
||||
if spans.is_empty() {
|
||||
return;
|
||||
}
|
||||
for line in wrap_spans_to_lines(spans, width) {
|
||||
lines.push(line);
|
||||
}
|
||||
spans.clear();
|
||||
}
|
||||
|
||||
fn wrap_spans_to_lines(spans: &mut Vec<Span<'static>>, width: u16) -> Vec<Line<'static>> {
|
||||
let width = width.max(1) as usize;
|
||||
let mut out: Vec<Line<'static>> = Vec::new();
|
||||
let mut current_line: Vec<Span<'static>> = Vec::new();
|
||||
let mut current_width = 0usize;
|
||||
|
||||
for span in spans.drain(..) {
|
||||
for word in span.content.split(' ') {
|
||||
let word_width = word.chars().count();
|
||||
let sep = if current_width == 0 { 0 } else { 1 };
|
||||
if current_width + sep + word_width > width && current_width > 0 {
|
||||
out.push(Line::from(std::mem::take(&mut current_line)));
|
||||
current_width = 0;
|
||||
}
|
||||
if current_width > 0 {
|
||||
current_line.push(Span::styled(" ", span.style));
|
||||
current_width += 1;
|
||||
}
|
||||
current_line.push(Span::styled(word.to_string(), span.style));
|
||||
current_width += word_width;
|
||||
}
|
||||
}
|
||||
|
||||
if !current_line.is_empty() {
|
||||
out.push(Line::from(current_line));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn renders_heading_and_bold() {
|
||||
let lines = render_markdown("# Hello\n\n**bold** text", 40);
|
||||
assert!(!lines.is_empty());
|
||||
let first: String = lines[0]
|
||||
.spans
|
||||
.iter()
|
||||
.map(|s| s.content.to_string())
|
||||
.collect();
|
||||
assert!(first.contains("# Hello"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wraps_long_paragraphs() {
|
||||
let text = "a ".repeat(50);
|
||||
let lines = render_markdown(&text, 20);
|
||||
assert!(lines.len() > 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Modal helpers for permission dialogs and the session picker.
|
||||
//!
|
||||
//! Rendering lives in `render.rs`; key handling lives in `input.rs`. This module
|
||||
//! provides shared utilities for modal state transitions.
|
||||
|
||||
use harness_app::EngineHandle;
|
||||
use harness_core::permission::PermissionReply;
|
||||
use harness_core::types::Session;
|
||||
|
||||
use crate::state::{AppState, ModalState};
|
||||
|
||||
/// Resolve the current permission request with `reply`.
|
||||
pub fn resolve_permission(state: &mut AppState, engine: &EngineHandle, reply: PermissionReply) {
|
||||
state.handle_permission_reply(reply, engine);
|
||||
}
|
||||
|
||||
/// Open the session picker with the supplied sessions.
|
||||
pub fn open_session_picker(state: &mut AppState, sessions: Vec<Session>) {
|
||||
state.open_session_picker(sessions);
|
||||
}
|
||||
|
||||
/// Load a session's messages and parts into state.
|
||||
pub async fn select_session(
|
||||
state: &mut AppState,
|
||||
engine: &EngineHandle,
|
||||
session: Session,
|
||||
) -> Result<(), harness_app::AppError> {
|
||||
let session_id = session.id.clone();
|
||||
let messages = engine.session_messages(session_id).await?;
|
||||
let mut all_parts = Vec::new();
|
||||
for message in &messages {
|
||||
let parts = engine.message_parts(message.id.clone()).await?;
|
||||
all_parts.extend(parts);
|
||||
}
|
||||
state.set_session(session, messages, all_parts);
|
||||
state.modal = ModalState::None;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
use ratatui::layout::{Constraint, Direction, Layout, Rect};
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
|
||||
use ratatui::Frame;
|
||||
|
||||
use crate::markdown::render_markdown;
|
||||
use crate::state::{AppState, ModalState, PartView, ToolStateView};
|
||||
use harness_core::types::Role;
|
||||
|
||||
/// Render the full UI into the terminal frame.
|
||||
pub fn render(frame: &mut Frame, state: &mut AppState) {
|
||||
let area = frame.area();
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(1),
|
||||
Constraint::Min(3),
|
||||
Constraint::Length(3),
|
||||
Constraint::Length(1),
|
||||
])
|
||||
.split(area);
|
||||
|
||||
render_header(frame, state, chunks[0]);
|
||||
render_chat(frame, state, chunks[1]);
|
||||
render_input(frame, state, chunks[2]);
|
||||
render_status(frame, state, chunks[3]);
|
||||
|
||||
match &state.modal {
|
||||
ModalState::Permission { requests } => {
|
||||
render_permission_modal(frame, &requests[0], area);
|
||||
}
|
||||
ModalState::SessionPicker { sessions, selected } => {
|
||||
render_session_picker(frame, sessions, *selected, area);
|
||||
}
|
||||
ModalState::None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_header(frame: &mut Frame, state: &AppState, area: Rect) {
|
||||
let title = if state.session_title.is_empty() {
|
||||
"new session"
|
||||
} else {
|
||||
state.session_title.as_str()
|
||||
};
|
||||
let text = format!("{} · {} · {}", title, state.agent, state.model_ref);
|
||||
let paragraph = Paragraph::new(text)
|
||||
.style(Style::new().add_modifier(Modifier::BOLD))
|
||||
.alignment(ratatui::layout::Alignment::Center);
|
||||
frame.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
fn render_chat(frame: &mut Frame, state: &mut AppState, area: Rect) {
|
||||
let effective_width = area.width.saturating_sub(4).max(1);
|
||||
// Cached lines are wrapped to a specific width, so a resize must drop them.
|
||||
if state.render_width != effective_width {
|
||||
state.invalidate_caches();
|
||||
state.render_width = effective_width;
|
||||
}
|
||||
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
for message in &mut state.messages {
|
||||
let role_style = match message.role {
|
||||
Role::User => Style::new().fg(Color::Cyan),
|
||||
Role::Assistant => Style::new(),
|
||||
};
|
||||
let prefix = match message.role {
|
||||
Role::User => "> ",
|
||||
Role::Assistant => "",
|
||||
};
|
||||
let mut first = true;
|
||||
for part in &mut message.parts {
|
||||
let part_lines = render_part(part, effective_width, role_style, prefix, first);
|
||||
lines.extend(part_lines);
|
||||
first = false;
|
||||
}
|
||||
lines.push(Line::default());
|
||||
}
|
||||
|
||||
let paragraph = Paragraph::new(lines)
|
||||
.block(Block::default().borders(Borders::ALL).title(" chat "))
|
||||
.scroll((state.scroll_offset, 0));
|
||||
frame.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
fn render_part(
|
||||
part: &mut PartView,
|
||||
effective_width: u16,
|
||||
role_style: Style,
|
||||
prefix: &'static str,
|
||||
first: bool,
|
||||
) -> Vec<Line<'static>> {
|
||||
match part {
|
||||
PartView::Text {
|
||||
text, cached_lines, ..
|
||||
} => {
|
||||
// Cache the prefix-free markdown render; the `> ` prefix is cheap to re-apply
|
||||
// to the clone each frame and would otherwise poison a shared cache.
|
||||
let base = cached_lines.get_or_insert_with(|| render_markdown(text, effective_width));
|
||||
let mut rendered = base.clone();
|
||||
if first && !prefix.is_empty() {
|
||||
if let Some(first_line) = rendered.first_mut() {
|
||||
let mut spans = vec![Span::styled(prefix, role_style)];
|
||||
spans.extend(first_line.spans.clone());
|
||||
*first_line = Line::from(spans);
|
||||
}
|
||||
}
|
||||
rendered
|
||||
}
|
||||
PartView::Reasoning { text, .. } => {
|
||||
let style = Style::new()
|
||||
.fg(Color::DarkGray)
|
||||
.add_modifier(Modifier::ITALIC);
|
||||
render_markdown(text, effective_width)
|
||||
.into_iter()
|
||||
.map(|line| {
|
||||
let mut spans = vec![Span::styled("🧠 ", style)];
|
||||
spans.extend(line.spans);
|
||||
Line::from(spans)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
PartView::Tool {
|
||||
name,
|
||||
state,
|
||||
cached_lines,
|
||||
..
|
||||
} => {
|
||||
if let Some(cached) = cached_lines {
|
||||
return cached.clone();
|
||||
}
|
||||
let status = state.status_label();
|
||||
let icon = match state {
|
||||
ToolStateView::Pending { .. } => "⏳",
|
||||
ToolStateView::Running { .. } => "⚙",
|
||||
ToolStateView::Completed { .. } => "✓",
|
||||
ToolStateView::Error { .. } => "✗",
|
||||
};
|
||||
let title = format!("{icon} {name} — {status}");
|
||||
let mut lines = vec![Line::from(title)];
|
||||
match state {
|
||||
ToolStateView::Pending { partial_input } => {
|
||||
lines.extend(render_markdown(partial_input, effective_width));
|
||||
}
|
||||
ToolStateView::Completed { output, .. } => {
|
||||
lines.extend(render_markdown(output, effective_width));
|
||||
}
|
||||
ToolStateView::Error { error } => {
|
||||
lines.extend(render_markdown(error, effective_width));
|
||||
}
|
||||
ToolStateView::Running { .. } => {}
|
||||
}
|
||||
*cached_lines = Some(lines.clone());
|
||||
lines
|
||||
}
|
||||
PartView::StepFinish { .. } => vec![Line::from("─── step ───")],
|
||||
}
|
||||
}
|
||||
|
||||
fn render_input(frame: &mut Frame, state: &mut AppState, area: Rect) {
|
||||
let block = Block::default().borders(Borders::ALL).title(" input ");
|
||||
state.input.set_block(block);
|
||||
frame.render_widget(&state.input, area);
|
||||
}
|
||||
|
||||
fn render_status(frame: &mut Frame, state: &AppState, area: Rect) {
|
||||
let spinner = if state.running { "⠋ " } else { "" };
|
||||
let status = if state.running { "running" } else { "idle" };
|
||||
let hints = if state.ctrl_c_pressed {
|
||||
"Press Ctrl+C again to quit"
|
||||
} else {
|
||||
"Ctrl+S: sessions | Esc: abort | Ctrl+C: quit"
|
||||
};
|
||||
let text = format!("{spinner}{status} · {hints}");
|
||||
let paragraph = Paragraph::new(text).style(Style::new().fg(Color::Gray));
|
||||
frame.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
fn render_permission_modal(
|
||||
frame: &mut Frame,
|
||||
request: &harness_core::event::PermissionRequest,
|
||||
area: Rect,
|
||||
) {
|
||||
let popup = centered_rect(60, 60, area);
|
||||
frame.render_widget(Clear, popup);
|
||||
|
||||
let text = vec![
|
||||
Line::from("Permission required").style(Style::new().add_modifier(Modifier::BOLD)),
|
||||
Line::default(),
|
||||
Line::from(format!("permission: {}", request.permission)),
|
||||
Line::from(format!("pattern: {}", request.pattern)),
|
||||
Line::default(),
|
||||
Line::from("y: allow once a: allow always n: reject"),
|
||||
];
|
||||
|
||||
let block = Block::default().borders(Borders::ALL).title(" permission ");
|
||||
let paragraph = Paragraph::new(text).block(block).wrap(Wrap { trim: true });
|
||||
frame.render_widget(paragraph, popup);
|
||||
}
|
||||
|
||||
fn render_session_picker(
|
||||
frame: &mut Frame,
|
||||
sessions: &[harness_core::types::Session],
|
||||
selected: usize,
|
||||
area: Rect,
|
||||
) {
|
||||
let popup = centered_rect(60, 60, area);
|
||||
frame.render_widget(Clear, popup);
|
||||
|
||||
let mut text: Vec<Line<'static>> =
|
||||
vec![Line::from("Select session").style(Style::new().add_modifier(Modifier::BOLD))];
|
||||
for (i, session) in sessions.iter().enumerate() {
|
||||
let marker = if i == selected { "> " } else { " " };
|
||||
let line = format!(
|
||||
"{}{} · {} · {}/{}",
|
||||
marker, session.id, session.agent, session.model.provider_id, session.model.model_id
|
||||
);
|
||||
let style = if i == selected {
|
||||
Style::new().bg(Color::Blue).fg(Color::White)
|
||||
} else {
|
||||
Style::new()
|
||||
};
|
||||
text.push(Line::from(Span::styled(line, style)));
|
||||
}
|
||||
|
||||
let block = Block::default().borders(Borders::ALL).title(" sessions ");
|
||||
let paragraph = Paragraph::new(text).block(block).wrap(Wrap { trim: false });
|
||||
frame.render_widget(paragraph, popup);
|
||||
}
|
||||
|
||||
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
||||
let popup_layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
Constraint::Percentage(percent_y),
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
])
|
||||
.split(r);
|
||||
|
||||
Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
Constraint::Percentage(percent_x),
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
])
|
||||
.split(popup_layout[1])[1]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use ratatui::backend::TestBackend;
|
||||
use ratatui::Terminal;
|
||||
|
||||
use super::*;
|
||||
use crate::state::{AppState, MessageView, PartView, ToolStateView};
|
||||
use harness_core::event::PermissionRequest;
|
||||
use harness_core::types::{MessageId, ModelRef, PartId, Role, Session, SessionId};
|
||||
|
||||
fn buffer_to_string(backend: &TestBackend) -> String {
|
||||
let buffer = backend.buffer();
|
||||
let area = buffer.area;
|
||||
let mut result = String::new();
|
||||
for y in 0..area.height {
|
||||
for x in 0..area.width {
|
||||
result.push_str(buffer[(x, y)].symbol());
|
||||
}
|
||||
while result.ends_with(' ') {
|
||||
result.pop();
|
||||
}
|
||||
result.push('\n');
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_empty_session() {
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut state = AppState::new(
|
||||
"anthropic/claude-sonnet-4-5".to_string(),
|
||||
"orchestrator".to_string(),
|
||||
);
|
||||
terminal.draw(|frame| render(frame, &mut state)).unwrap();
|
||||
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_user_and_assistant_messages() {
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut state = AppState::new(
|
||||
"anthropic/claude-sonnet-4-5".to_string(),
|
||||
"orchestrator".to_string(),
|
||||
);
|
||||
state.session_id = Some(SessionId("ses_test_001".to_string()));
|
||||
state.messages.push(MessageView {
|
||||
id: MessageId("msg_test_001".to_string()),
|
||||
role: Role::User,
|
||||
parts: vec![PartView::Text {
|
||||
id: PartId("prt_test_001".to_string()),
|
||||
text: "Hello, can you read foo.txt?".to_string(),
|
||||
cached_lines: None,
|
||||
}],
|
||||
});
|
||||
state.messages.push(MessageView {
|
||||
id: MessageId("msg_test_002".to_string()),
|
||||
role: Role::Assistant,
|
||||
parts: vec![PartView::Text {
|
||||
id: PartId("prt_test_002".to_string()),
|
||||
text: "I'll read that file for you.\n\n```rust\nlet x = 42;\n```".to_string(),
|
||||
cached_lines: None,
|
||||
}],
|
||||
});
|
||||
terminal.draw(|frame| render(frame, &mut state)).unwrap();
|
||||
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_tool_card_completed() {
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut state = AppState::new(
|
||||
"anthropic/claude-sonnet-4-5".to_string(),
|
||||
"orchestrator".to_string(),
|
||||
);
|
||||
state.session_id = Some(SessionId("ses_test_001".to_string()));
|
||||
state.messages.push(MessageView {
|
||||
id: MessageId("msg_test_003".to_string()),
|
||||
role: Role::Assistant,
|
||||
parts: vec![PartView::Tool {
|
||||
id: PartId("prt_test_003".to_string()),
|
||||
name: "read".to_string(),
|
||||
state: ToolStateView::Completed {
|
||||
title: "read foo.txt".to_string(),
|
||||
output: "file contents here".to_string(),
|
||||
},
|
||||
cached_lines: None,
|
||||
}],
|
||||
});
|
||||
terminal.draw(|frame| render(frame, &mut state)).unwrap();
|
||||
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_tool_card_running() {
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut state = AppState::new(
|
||||
"anthropic/claude-sonnet-4-5".to_string(),
|
||||
"orchestrator".to_string(),
|
||||
);
|
||||
state.session_id = Some(SessionId("ses_test_001".to_string()));
|
||||
state.messages.push(MessageView {
|
||||
id: MessageId("msg_test_004".to_string()),
|
||||
role: Role::Assistant,
|
||||
parts: vec![PartView::Tool {
|
||||
id: PartId("prt_test_004".to_string()),
|
||||
name: "read".to_string(),
|
||||
state: ToolStateView::Running {
|
||||
title: Some("read foo.txt".to_string()),
|
||||
},
|
||||
cached_lines: None,
|
||||
}],
|
||||
});
|
||||
terminal.draw(|frame| render(frame, &mut state)).unwrap();
|
||||
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_tool_card_error() {
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut state = AppState::new(
|
||||
"anthropic/claude-sonnet-4-5".to_string(),
|
||||
"orchestrator".to_string(),
|
||||
);
|
||||
state.session_id = Some(SessionId("ses_test_001".to_string()));
|
||||
state.messages.push(MessageView {
|
||||
id: MessageId("msg_test_005".to_string()),
|
||||
role: Role::Assistant,
|
||||
parts: vec![PartView::Tool {
|
||||
id: PartId("prt_test_005".to_string()),
|
||||
name: "read".to_string(),
|
||||
state: ToolStateView::Error {
|
||||
error: "file not found".to_string(),
|
||||
},
|
||||
cached_lines: None,
|
||||
}],
|
||||
});
|
||||
terminal.draw(|frame| render(frame, &mut state)).unwrap();
|
||||
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_permission_modal() {
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut state = AppState::new(
|
||||
"anthropic/claude-sonnet-4-5".to_string(),
|
||||
"orchestrator".to_string(),
|
||||
);
|
||||
let request = PermissionRequest {
|
||||
id: "test".to_string(),
|
||||
session_id: SessionId("ses_test_001".to_string()),
|
||||
permission: "bash".to_string(),
|
||||
pattern: "rm -rf /".to_string(),
|
||||
always_pattern: "rm *".to_string(),
|
||||
metadata: serde_json::Value::Null,
|
||||
};
|
||||
state.modal = ModalState::Permission {
|
||||
requests: vec![request],
|
||||
};
|
||||
terminal.draw(|frame| render(frame, &mut state)).unwrap();
|
||||
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_session_picker_modal() {
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut state = AppState::new(
|
||||
"anthropic/claude-sonnet-4-5".to_string(),
|
||||
"orchestrator".to_string(),
|
||||
);
|
||||
let sessions = vec![
|
||||
Session {
|
||||
id: SessionId("ses_test_001".to_string()),
|
||||
parent_id: None,
|
||||
depth: 0,
|
||||
title: "Session One".to_string(),
|
||||
agent: "orchestrator".to_string(),
|
||||
model: ModelRef::new("anthropic", "claude-sonnet-4-5"),
|
||||
usage: harness_core::types::TokenUsage::default(),
|
||||
cost: 0.0,
|
||||
extra_rules: Vec::new(),
|
||||
created_at: 1,
|
||||
updated_at: 1,
|
||||
},
|
||||
Session {
|
||||
id: SessionId("ses_test_002".to_string()),
|
||||
parent_id: None,
|
||||
depth: 0,
|
||||
title: "Session Two".to_string(),
|
||||
agent: "coder".to_string(),
|
||||
model: ModelRef::new("openai", "gpt-4o"),
|
||||
usage: harness_core::types::TokenUsage::default(),
|
||||
cost: 0.0,
|
||||
extra_rules: Vec::new(),
|
||||
created_at: 2,
|
||||
updated_at: 2,
|
||||
},
|
||||
Session {
|
||||
id: SessionId("ses_test_003".to_string()),
|
||||
parent_id: None,
|
||||
depth: 0,
|
||||
title: "Session Three".to_string(),
|
||||
agent: "reviewer".to_string(),
|
||||
model: ModelRef::new("google", "gemini-2.5"),
|
||||
usage: harness_core::types::TokenUsage::default(),
|
||||
cost: 0.0,
|
||||
extra_rules: Vec::new(),
|
||||
created_at: 3,
|
||||
updated_at: 3,
|
||||
},
|
||||
];
|
||||
state.modal = ModalState::SessionPicker {
|
||||
sessions,
|
||||
selected: 1,
|
||||
};
|
||||
terminal.draw(|frame| render(frame, &mut state)).unwrap();
|
||||
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_empty_state_produces_frame() {
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
let mut state = AppState::new("anthropic/claude".to_string(), "orchestrator".to_string());
|
||||
terminal.draw(|frame| render(frame, &mut state)).unwrap();
|
||||
let buffer = terminal.backend().buffer().clone();
|
||||
assert_eq!(buffer.area.width, 80);
|
||||
assert_eq!(buffer.area.height, 24);
|
||||
// Header should contain the agent/model line.
|
||||
let header_row: String = buffer
|
||||
.content
|
||||
.chunks(80)
|
||||
.next()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|c| c.symbol())
|
||||
.collect();
|
||||
assert!(header_row.contains("orchestrator"));
|
||||
assert!(header_row.contains("anthropic/claude"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
source: crates/harness-tui/src/render.rs
|
||||
assertion_line: 277
|
||||
expression: buffer_to_string(terminal.backend())
|
||||
---
|
||||
new session · orchestrator · anthropic/claude-sonnet-4-5
|
||||
┌ chat ────────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
┌ input ───────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
idle · Ctrl+S: sessions | Esc: abort | Ctrl+C: quit
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
---
|
||||
source: crates/harness-tui/src/render.rs
|
||||
assertion_line: 397
|
||||
expression: buffer_to_string(terminal.backend())
|
||||
---
|
||||
new session · orchestrator · anthropic/claude-sonnet-4-5
|
||||
┌ chat ────────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ ┌ permission ──────────────────────────────────┐ │
|
||||
│ │Permission required │ │
|
||||
│ │ │ │
|
||||
│ │permission: bash │ │
|
||||
│ │pattern: rm -rf / │ │
|
||||
│ │ │ │
|
||||
│ │y: allow once a: allow always n: reject │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
┌ input ───────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
idle · Ctrl+S: sessions | Esc: abort | Ctrl+C: quit
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
---
|
||||
source: crates/harness-tui/src/render.rs
|
||||
assertion_line: 449
|
||||
expression: buffer_to_string(terminal.backend())
|
||||
---
|
||||
new session · orchestrator · anthropic/claude-sonnet-4-5
|
||||
┌ chat ────────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ ┌ sessions ────────────────────────────────────┐ │
|
||||
│ │Select session │ │
|
||||
│ │ ses_test_001 · orchestrator · │ │
|
||||
│ │anthropic/claude-sonnet-4-5 │ │
|
||||
│ │> ses_test_002 · coder · openai/gpt-4o │ │
|
||||
│ │ ses_test_003 · reviewer · google/gemini-2.5 │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
┌ input ───────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
idle · Ctrl+S: sessions | Esc: abort | Ctrl+C: quit
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
---
|
||||
source: crates/harness-tui/src/render.rs
|
||||
assertion_line: 330
|
||||
expression: buffer_to_string(terminal.backend())
|
||||
---
|
||||
new session · orchestrator · anthropic/claude-sonnet-4-5
|
||||
┌ chat ────────────────────────────────────────────────────────────────────────┐
|
||||
│✓ read — read foo.txt │
|
||||
│file contents here │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
┌ input ───────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
idle · Ctrl+S: sessions | Esc: abort | Ctrl+C: quit
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
---
|
||||
source: crates/harness-tui/src/render.rs
|
||||
assertion_line: 376
|
||||
expression: buffer_to_string(terminal.backend())
|
||||
---
|
||||
new session · orchestrator · anthropic/claude-sonnet-4-5
|
||||
┌ chat ────────────────────────────────────────────────────────────────────────┐
|
||||
│✗ read — error: file not found │
|
||||
│file not found │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
┌ input ───────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
idle · Ctrl+S: sessions | Esc: abort | Ctrl+C: quit
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
---
|
||||
source: crates/harness-tui/src/render.rs
|
||||
assertion_line: 353
|
||||
expression: buffer_to_string(terminal.backend())
|
||||
---
|
||||
new session · orchestrator · anthropic/claude-sonnet-4-5
|
||||
┌ chat ────────────────────────────────────────────────────────────────────────┐
|
||||
│⚙ read — read foo.txt │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
┌ input ───────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
idle · Ctrl+S: sessions | Esc: abort | Ctrl+C: quit
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
---
|
||||
source: crates/harness-tui/src/render.rs
|
||||
assertion_line: 306
|
||||
expression: buffer_to_string(terminal.backend())
|
||||
---
|
||||
new session · orchestrator · anthropic/claude-sonnet-4-5
|
||||
┌ chat ────────────────────────────────────────────────────────────────────────┐
|
||||
│> Hello, can you read foo.txt? │
|
||||
│ │
|
||||
│I'll read that file for you. │
|
||||
│┌──── rust │
|
||||
││ let x = 42; │
|
||||
│└──── │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
┌ input ───────────────────────────────────────────────────────────────────────┐
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
idle · Ctrl+S: sessions | Esc: abort | Ctrl+C: quit
|
||||
@@ -0,0 +1,396 @@
|
||||
use harness_app::EngineHandle;
|
||||
use harness_core::event::{AppEvent, PermissionRequest, RunOutcome};
|
||||
use harness_core::permission::PermissionReply;
|
||||
use harness_core::types::{Message, Part, PartBody, PartId, Role, Session, SessionId, ToolState};
|
||||
use ratatui::text::Line;
|
||||
|
||||
/// Cached view of a message in the chat viewport.
|
||||
#[derive(Debug)]
|
||||
pub struct MessageView {
|
||||
pub id: harness_core::types::MessageId,
|
||||
pub role: Role,
|
||||
pub parts: Vec<PartView>,
|
||||
}
|
||||
|
||||
/// Cached view of a part. The optional `cached_lines` field stores a pre-rendered markdown
|
||||
/// representation; it is invalidated whenever the underlying text changes.
|
||||
#[derive(Debug)]
|
||||
pub enum PartView {
|
||||
Text {
|
||||
id: PartId,
|
||||
text: String,
|
||||
cached_lines: Option<Vec<Line<'static>>>,
|
||||
},
|
||||
Reasoning {
|
||||
id: PartId,
|
||||
text: String,
|
||||
},
|
||||
Tool {
|
||||
id: PartId,
|
||||
name: String,
|
||||
state: ToolStateView,
|
||||
cached_lines: Option<Vec<Line<'static>>>,
|
||||
},
|
||||
StepFinish {
|
||||
id: PartId,
|
||||
},
|
||||
}
|
||||
|
||||
/// Simplified tool state for rendering.
|
||||
#[derive(Debug)]
|
||||
pub enum ToolStateView {
|
||||
Pending { partial_input: String },
|
||||
Running { title: Option<String> },
|
||||
Completed { title: String, output: String },
|
||||
Error { error: String },
|
||||
}
|
||||
|
||||
impl ToolStateView {
|
||||
fn from_tool_state(state: &ToolState) -> Self {
|
||||
match state {
|
||||
ToolState::Pending { partial_input } => Self::Pending {
|
||||
partial_input: partial_input.clone(),
|
||||
},
|
||||
ToolState::Running { title, .. } => Self::Running {
|
||||
title: title.clone(),
|
||||
},
|
||||
ToolState::Completed { title, output, .. } => Self::Completed {
|
||||
title: title.clone(),
|
||||
output: output.clone(),
|
||||
},
|
||||
ToolState::Error { error, .. } => Self::Error {
|
||||
error: error.clone(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status_label(&self) -> String {
|
||||
match self {
|
||||
Self::Pending { .. } => "pending".to_string(),
|
||||
Self::Running { title } => title.clone().unwrap_or_else(|| "running".to_string()),
|
||||
Self::Completed { title, .. } => title.clone(),
|
||||
Self::Error { error } => format!("error: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Active modal overlay state.
|
||||
#[derive(Debug, Default)]
|
||||
pub enum ModalState {
|
||||
#[default]
|
||||
None,
|
||||
Permission {
|
||||
requests: Vec<PermissionRequest>,
|
||||
},
|
||||
SessionPicker {
|
||||
sessions: Vec<Session>,
|
||||
selected: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// All mutable UI state lives here.
|
||||
#[derive(Debug)]
|
||||
pub struct AppState {
|
||||
pub session_id: Option<SessionId>,
|
||||
pub session_title: String,
|
||||
pub messages: Vec<MessageView>,
|
||||
pub modal: ModalState,
|
||||
pub input: tui_textarea::TextArea<'static>,
|
||||
pub scroll_offset: u16,
|
||||
pub running: bool,
|
||||
pub model_ref: String,
|
||||
pub agent: String,
|
||||
pub quit: bool,
|
||||
pub dirty: bool,
|
||||
pub ctrl_c_pressed: bool,
|
||||
/// Width the currently cached part lines were wrapped to; a change invalidates them.
|
||||
pub render_width: u16,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(model_ref: String, agent: String) -> Self {
|
||||
let mut input = tui_textarea::TextArea::default();
|
||||
input.set_cursor_line_style(ratatui::style::Style::default());
|
||||
Self {
|
||||
session_id: None,
|
||||
session_title: String::new(),
|
||||
messages: Vec::new(),
|
||||
modal: ModalState::None,
|
||||
input,
|
||||
scroll_offset: 0,
|
||||
running: false,
|
||||
model_ref,
|
||||
agent,
|
||||
quit: false,
|
||||
dirty: true,
|
||||
ctrl_c_pressed: false,
|
||||
render_width: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop every part's cached render (e.g. after a resize changes the wrap width).
|
||||
pub fn invalidate_caches(&mut self) {
|
||||
for message in &mut self.messages {
|
||||
for part in &mut message.parts {
|
||||
match part {
|
||||
PartView::Text { cached_lines, .. } | PartView::Tool { cached_lines, .. } => {
|
||||
*cached_lines = None
|
||||
}
|
||||
PartView::Reasoning { .. } | PartView::StepFinish { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_session(&mut self, session: Session, messages: Vec<Message>, parts: Vec<Part>) {
|
||||
self.session_id = Some(session.id.clone());
|
||||
self.session_title = session.title;
|
||||
self.agent = session.agent;
|
||||
self.model_ref = format!("{}/{}", session.model.provider_id, session.model.model_id);
|
||||
self.messages.clear();
|
||||
|
||||
let mut messages = messages;
|
||||
messages.sort_by_key(|m| m.created_at);
|
||||
for message in messages {
|
||||
let message_parts: Vec<Part> = parts
|
||||
.iter()
|
||||
.filter(|p| p.message_id == message.id)
|
||||
.cloned()
|
||||
.collect();
|
||||
self.messages.push(message_view(message, message_parts));
|
||||
}
|
||||
self.scroll_offset = 0;
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
pub fn apply_event(&mut self, event: AppEvent) {
|
||||
match event {
|
||||
AppEvent::SessionCreated { session } | AppEvent::SessionUpdated { session } => {
|
||||
if self.session_id.as_ref() == Some(&session.id) {
|
||||
self.session_title = session.title;
|
||||
self.agent = session.agent;
|
||||
self.model_ref =
|
||||
format!("{}/{}", session.model.provider_id, session.model.model_id);
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
AppEvent::MessageCreated { message } => {
|
||||
if self.session_id.as_ref() == Some(&message.session_id) {
|
||||
self.messages.push(message_view(message, Vec::new()));
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
AppEvent::MessageUpdated { message } => {
|
||||
if let Some(view) = self.messages.iter_mut().find(|m| m.id == message.id) {
|
||||
view.role = message.role;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
AppEvent::PartUpdated { part } => {
|
||||
if self.session_id.as_ref() == Some(&part.session_id) {
|
||||
self.update_or_insert_part(part);
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
AppEvent::PartDelta {
|
||||
part_id,
|
||||
message_id,
|
||||
delta,
|
||||
} => {
|
||||
self.apply_delta(part_id, message_id, delta);
|
||||
self.dirty = true;
|
||||
}
|
||||
AppEvent::RunStarted { session_id } => {
|
||||
if self.session_id.as_ref() == Some(&session_id) {
|
||||
self.running = true;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
AppEvent::RunFinished {
|
||||
session_id,
|
||||
outcome,
|
||||
} => {
|
||||
if self.session_id.as_ref() == Some(&session_id) {
|
||||
self.running = false;
|
||||
if matches!(outcome, RunOutcome::Errored { .. }) {
|
||||
self.messages.push(MessageView {
|
||||
id: harness_core::types::MessageId::new(),
|
||||
role: Role::Assistant,
|
||||
parts: vec![PartView::Text {
|
||||
id: PartId::new(),
|
||||
text: match outcome {
|
||||
RunOutcome::Errored { message } => message,
|
||||
_ => String::new(),
|
||||
},
|
||||
cached_lines: None,
|
||||
}],
|
||||
});
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
AppEvent::PermissionAsked { request } => {
|
||||
if let ModalState::Permission { requests } = &mut self.modal {
|
||||
requests.push(request);
|
||||
} else {
|
||||
self.modal = ModalState::Permission {
|
||||
requests: vec![request],
|
||||
};
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
AppEvent::PermissionResolved { id } => {
|
||||
if let ModalState::Permission { requests } = &mut self.modal {
|
||||
requests.retain(|r| r.id != id);
|
||||
if requests.is_empty() {
|
||||
self.modal = ModalState::None;
|
||||
}
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
AppEvent::JobUpdated { .. }
|
||||
| AppEvent::AuthPrompt { .. }
|
||||
| AppEvent::ServerNotice { .. } => {
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scroll_up(&mut self, n: u16) {
|
||||
self.scroll_offset = self.scroll_offset.saturating_sub(n);
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
pub fn scroll_down(&mut self, n: u16) {
|
||||
self.scroll_offset = self.scroll_offset.saturating_add(n);
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
pub fn handle_permission_reply(&mut self, reply: PermissionReply, engine: &EngineHandle) {
|
||||
let request_id = if let ModalState::Permission { requests } = &self.modal {
|
||||
requests.first().map(|r| r.id.clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(id) = request_id {
|
||||
engine.permission_reply(&id, reply);
|
||||
if let ModalState::Permission { requests } = &mut self.modal {
|
||||
requests.retain(|r| r.id != id);
|
||||
if requests.is_empty() {
|
||||
self.modal = ModalState::None;
|
||||
}
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_session_picker(&mut self, sessions: Vec<Session>) {
|
||||
self.modal = ModalState::SessionPicker {
|
||||
sessions,
|
||||
selected: 0,
|
||||
};
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
pub fn close_modal(&mut self) {
|
||||
self.modal = ModalState::None;
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
fn update_or_insert_part(&mut self, part: Part) {
|
||||
let target_id = part.id.clone();
|
||||
let Some(message_view) = self.messages.iter_mut().find(|m| m.id == part.message_id) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let new_view = part_view(part);
|
||||
if let Some(existing) = message_view
|
||||
.parts
|
||||
.iter_mut()
|
||||
.find(|p| view_part_id(p) == target_id)
|
||||
{
|
||||
*existing = new_view;
|
||||
} else {
|
||||
message_view.parts.push(new_view);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_delta(
|
||||
&mut self,
|
||||
target_id: PartId,
|
||||
message_id: harness_core::types::MessageId,
|
||||
delta: String,
|
||||
) {
|
||||
let Some(message_view) = self.messages.iter_mut().find(|m| m.id == message_id) else {
|
||||
return;
|
||||
};
|
||||
|
||||
for part in &mut message_view.parts {
|
||||
if view_part_id(part) == target_id {
|
||||
match part {
|
||||
PartView::Text {
|
||||
text, cached_lines, ..
|
||||
} => {
|
||||
text.push_str(&delta);
|
||||
*cached_lines = None;
|
||||
}
|
||||
PartView::Reasoning { text, .. } => {
|
||||
text.push_str(&delta);
|
||||
}
|
||||
PartView::Tool { cached_lines, .. } => {
|
||||
*cached_lines = None;
|
||||
}
|
||||
PartView::StepFinish { .. } => {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn message_view(message: Message, mut parts: Vec<Part>) -> MessageView {
|
||||
parts.sort_by_key(|p| p.idx);
|
||||
MessageView {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
parts: parts.into_iter().map(part_view).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn part_view(part: Part) -> PartView {
|
||||
match part.body {
|
||||
PartBody::Text { text, .. } => PartView::Text {
|
||||
id: part.id,
|
||||
text,
|
||||
cached_lines: None,
|
||||
},
|
||||
PartBody::Reasoning { text, .. } => PartView::Reasoning { id: part.id, text },
|
||||
PartBody::Tool { name, state, .. } => PartView::Tool {
|
||||
id: part.id,
|
||||
name,
|
||||
state: ToolStateView::from_tool_state(&state),
|
||||
cached_lines: None,
|
||||
},
|
||||
PartBody::StepStart | PartBody::StepFinish { .. } => PartView::StepFinish { id: part.id },
|
||||
PartBody::Subtask { description, .. } => PartView::Text {
|
||||
id: part.id,
|
||||
text: description,
|
||||
cached_lines: None,
|
||||
},
|
||||
PartBody::Compaction { summary, .. } => PartView::Text {
|
||||
id: part.id,
|
||||
text: format!("_Compaction summary: {summary}_"),
|
||||
cached_lines: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn view_part_id(part: &PartView) -> PartId {
|
||||
match part {
|
||||
PartView::Text { id, .. }
|
||||
| PartView::Reasoning { id, .. }
|
||||
| PartView::Tool { id, .. }
|
||||
| PartView::StepFinish { id } => id.clone(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use std::io;
|
||||
use std::panic;
|
||||
|
||||
use crossterm::cursor::Show;
|
||||
use crossterm::execute;
|
||||
use crossterm::terminal::{
|
||||
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
|
||||
};
|
||||
|
||||
/// Restores the terminal when dropped or on panic.
|
||||
pub struct TerminalGuard;
|
||||
|
||||
impl TerminalGuard {
|
||||
/// Enables raw mode, enters the alternate screen, and installs a panic hook
|
||||
/// that restores the terminal before printing panic info.
|
||||
pub fn enter() -> io::Result<Self> {
|
||||
enable_raw_mode()?;
|
||||
let mut stdout = io::stdout();
|
||||
execute!(stdout, EnterAlternateScreen, Show)?;
|
||||
|
||||
let original_hook = panic::take_hook();
|
||||
panic::set_hook(Box::new(move |info| {
|
||||
let _ = restore();
|
||||
original_hook(info);
|
||||
}));
|
||||
|
||||
Ok(Self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TerminalGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = restore();
|
||||
}
|
||||
}
|
||||
|
||||
fn restore() -> io::Result<()> {
|
||||
disable_raw_mode()?;
|
||||
let mut stdout = io::stdout();
|
||||
execute!(stdout, LeaveAlternateScreen, Show)
|
||||
}
|
||||
Reference in New Issue
Block a user