Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat: improve ov chat UX with rustyline and markdown rendering (#466)

chenjw06e24fc24b3c
diff --git a/crates/ov_cli/Cargo.toml b/crates/ov_cli/Cargo.toml
index 72d542fc7..a7bb8a5a3 100644
--- a/crates/ov_cli/Cargo.toml
+++ b/crates/ov_cli/Cargo.toml
@@ -32,3 +32,4 @@ walkdir = "2.5"
rustyline = "14.0"
uuid = { version = "1.0", features = ["v4", "serde"] }
machine-uid = "0.5"
+termimad = "0.34"
diff --git a/crates/ov_cli/src/commands/chat.rs b/crates/ov_cli/src/commands/chat.rs
index cf985089c..d02076f54 100644
--- a/crates/ov_cli/src/commands/chat.rs
+++ b/crates/ov_cli/src/commands/chat.rs
@@ -1,16 +1,23 @@
//! Chat command for interacting with Vikingbot via OpenAPI
+//!
+//! Features:
+//! - Proper line editing with rustyline (no ^[[D characters)
+//! - Markdown rendering for bot responses
+//! - Command history support
-use std::io::{BufRead, Write};
use std::time::Duration;
use clap::Parser;
-use crate::utils::truncate_utf8;
use reqwest::Client;
+use rustyline::error::ReadlineError;
+use rustyline::DefaultEditor;
use serde::{Deserialize, Serialize};
+use termimad::MadSkin;
use crate::error::{Error, Result};
const DEFAULT_ENDPOINT: &str = "http://localhost:1933/bot/v1";
+const HISTORY_FILE: &str = ".ov_chat_history";
/// Chat with Vikingbot via OpenAPI
#[derive(Debug, Parser)]
@@ -39,9 +46,13 @@ pub struct ChatCommand {
#[arg(long)]
pub stream: bool,
- /// Disable rich formatting
+ /// Disable rich formatting / markdown rendering
#[arg(long)]
pub no_format: bool,
+
+ /// Disable command history
+ #[arg(long)]
+ pub no_history: bool,
}
/// Chat message for API
@@ -73,7 +84,8 @@ struct ChatResponse {
events: Option<Vec<serde_json::Value>>,
}
-/// Stream event
+/// Stream event - kept for compatibility
+#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct StreamEvent {
event: String,
@@ -89,7 +101,7 @@ impl ChatCommand {
.map_err(|e| Error::Network(format!("Failed to create HTTP client: {}", e)))?;
if let Some(message) = &self.message {
- // Single message mode - ignore stream flag for now
+ // Single message mode
self.send_message(&client, message).await
} else {
// Interactive mode
@@ -132,55 +144,15 @@ impl ChatCommand {
.map_err(|e| Error::Parse(format!("Failed to parse response: {}", e)))?;
// Print events if any
- if let Some(events) = &chat_response.events {
- for event in events {
- if let (Some(etype), Some(data)) = (
- event.get("type").and_then(|v| v.as_str()),
- event.get("data"),
- ) {
- match etype {
- "reasoning" => {
- let content = data.as_str().unwrap_or("");
- if !self.no_format {
- println!(" \x1b[2mThink: {}...\x1b[0m", truncate_utf8(content, 100));
- }
- }
- "tool_call" => {
- let content = data.as_str().unwrap_or("");
- if !self.no_format {
- println!(" \x1b[2m├─ Calling: {}\x1b[0m", content);
- }
- }
- "tool_result" => {
- let content = data.as_str().unwrap_or("");
- if !self.no_format {
- let truncated = if content.len() > 150 {
- format!("{}...", truncate_utf8(content, 150))
- } else {
- content.to_string()
- };
- println!(" \x1b[2m└─ Result: {}\x1b[0m", truncated);
- }
- }
- _ => {}
- }
- }
- }
- }
+ self.print_events(&chat_response.events);
// Print final response
- if !self.no_format {
- println!("\n\x1b[1;31mBot:\x1b[0m");
- println!("{}", chat_response.message);
- println!();
- } else {
- println!("{}", chat_response.message);
- }
+ self.print_response(&chat_response.message);
Ok(())
}
- /// Run interactive chat mode
+ /// Run interactive chat mode with rustyline
async fn run_interactive(&self, client: &Client) -> Result<()> {
println!("Vikingbot Chat - Interactive Mode");
println!("Endpoint: {}", self.endpoint);
@@ -190,114 +162,188 @@ impl ChatCommand {
println!("Type 'exit', 'quit', or press Ctrl+C to exit");
println!("----------------------------------------\n");
+ // Initialize rustyline editor
+ let mut rl = DefaultEditor::new()
+ .map_err(|e| Error::Client(format!("Failed to initialize editor: {}", e)))?;
+
+ // Load history if enabled
+ let history_path = if !self.no_history {
+ self.get_history_path()
+ } else {
+ None
+ };
+ if let Some(ref path) = history_path {
+ let _ = rl.load_history(path);
+ }
+
let mut session_id = self.session.clone();
loop {
- // Read input
- print!("\x1b[1;32mYou:\x1b[0m ");
- std::io::stdout().flush()?;
-
- // Read input as bytes first to handle invalid UTF-8 gracefully
- let mut buf = Vec::new();
- let stdin = std::io::stdin();
- let mut reader = stdin.lock();
- reader.read_until(b'\n', &mut buf)?;
- let input = String::from_utf8_lossy(&buf).trim().to_string();
-
- if input.is_empty() {
- continue;
- }
+ // Read input with rustyline
+ let prompt = "\x1b[1;32mYou:\x1b[0m ";
+ match rl.readline(prompt) {
+ Ok(line) => {
+ let input: &str = line.trim();
+
+ if input.is_empty() {
+ continue;
+ }
+
+ // Add to history
+ if !self.no_history {
+ let _ = rl.add_history_entry(input);
+ }
- // Check for exit
- if input.eq_ignore_ascii_case("exit") || input.eq_ignore_ascii_case("quit") {
- println!("\nGoodbye!");
- break;
+ // Check for exit
+ if input.eq_ignore_ascii_case("exit") || input.eq_ignore_ascii_case("quit") {
+ println!("\nGoodbye!");
+ break;
+ }
+
+ // Send message
+ match self.send_interactive_message(client, input, &mut session_id).await {
+ Ok(_) => {}
+ Err(e) => {
+ eprintln!("\x1b[1;31mError: {}\x1b[0m", e);
+ }
+ }
+ }
+ Err(ReadlineError::Interrupted) => {
+ // Ctrl+C
+ println!("\nGoodbye!");
+ break;
+ }
+ Err(ReadlineError::Eof) => {
+ // Ctrl+D
+ println!("\nGoodbye!");
+ break;
+ }
+ Err(e) => {
+ eprintln!("\x1b[1;31mError reading input: {}\x1b[0m", e);
+ break;
+ }
}
+ }
- // Send message
- let url = format!("{}/chat", self.endpoint);
+ // Save history
+ if let Some(ref path) = history_path {
+ let _ = rl.save_history(path);
+ }
- let request = ChatRequest {
- message: input.to_string(),
- session_id: session_id.clone(),
- user_id: Some(self.user.clone()),
- stream: false,
- context: None,
- };
+ Ok(())
+ }
- let mut req_builder = client.post(&url).json(&request);
+ /// Send a message in interactive mode
+ async fn send_interactive_message(
+ &self,
+ client: &Client,
+ input: &str,
+ session_id: &mut Option<String>,
+ ) -> Result<()> {
+ let url = format!("{}/chat", self.endpoint);
- if let Some(api_key) = &self.api_key {
- req_builder = req_builder.header("X-API-Key", api_key);
- }
+ let request = ChatRequest {
+ message: input.to_string(),
+ session_id: session_id.clone(),
+ user_id: Some(self.user.clone()),
+ stream: false,
+ context: None,
+ };
+
+ let mut req_builder = client.post(&url).json(&request);
+
+ if let Some(api_key) = &self.api_key {
+ req_builder = req_builder.header("X-API-Key", api_key);
+ }
+
+ let response = req_builder
+ .send()
+ .await
+ .map_err(|e| Error::Network(format!("Failed to send request: {}", e)))?;
- match req_builder.send().await {
- Ok(response) => {
- if response.status().is_success() {
- match response.json::<ChatResponse>().await {
- Ok(chat_response) => {
- // Save session ID
- if session_id.is_none() {
- session_id = Some(chat_response.session_id.clone());
- }
-
- // Print events
- if let Some(events) = chat_response.events {
- for event in events {
- if let (Some(etype), Some(data)) = (
- event.get("type").and_then(|v| v.as_str()),
- event.get("data"),
- ) {
- match etype {
- "reasoning" => {
- let content = data.as_str().unwrap_or("");
- if content.len() > 100 {
- println!("\t\x1b[2mThink: {}...\x1b[0m", truncate_utf8(content, 100));
- } else {
- println!("\t\x1b[2mThink: {}\x1b[0m", content);
- }
- }
- "tool_call" => {
- println!("\t\x1b[2m├─ Calling: {}\x1b[0m", data.as_str().unwrap_or(""));
- }
- "tool_result" => {
- let content = data.as_str().unwrap_or("");
- let truncated = if content.len() > 150 {
- format!("{}...", truncate_utf8(content, 150))
- } else {
- content.to_string()
- };
- println!("\t\x1b[2m└─ Result: {}\x1b[0m", truncated);
- }
- _ => {}
- }
- }
- }
- }
-
- // Print response
- println!("\n\x1b[1;31mBot:\x1b[0m");
- println!("{}", chat_response.message);
- println!();
- }
- Err(e) => {
- eprintln!("\x1b[1;31mError parsing response: {}\x1b[0m", e);
- }
+ if !response.status().is_success() {
+ let status = response.status();
+ let text = response.text().await.unwrap_or_default();
+ return Err(Error::Api(format!("Request failed ({}): {}", status, text)));
+ }
+
+ let chat_response: ChatResponse = response
+ .json()
+ .await
+ .map_err(|e| Error::Parse(format!("Failed to parse response: {}", e)))?;
+
+ // Save session ID
+ if session_id.is_none() {
+ *session_id = Some(chat_response.session_id.clone());
+ }
+
+ // Print events
+ self.print_events(&chat_response.events);
+
+ // Print response with markdown
+ println!();
+ self.print_response(&chat_response.message);
+ println!();
+
+ Ok(())
+ }
+
+ /// Print thinking/events
+ fn print_events(&self, events: &Option<Vec<serde_json::Value>>) {
+ if self.no_format {
+ return;
+ }
+
+ if let Some(events) = events {
+ for event in events {
+ if let (Some(etype), Some(data)) = (
+ event.get("type").and_then(|v| v.as_str()),
+ event.get("data"),
+ ) {
+ match etype {
+ "reasoning" => {
+ let content = data.as_str().unwrap_or("");
+ println!(
+ " \x1b[2mThink: {}...\x1b[0m",
+ truncate_utf8(content, 100)
+ );
+ }
+ "tool_call" => {
+ let content = data.as_str().unwrap_or("");
+ println!(" \x1b[2m├─ Calling: {}\x1b[0m", content);
}
- } else {
- let status = response.status();
- let text = response.text().await.unwrap_or_default();
- eprintln!("\x1b[1;31mRequest failed ({}): {}\x1b[0m", status, text);
+ "tool_result" => {
+ let content = data.as_str().unwrap_or("");
+ let truncated = if content.len() > 150 {
+ format!("{}...", truncate_utf8(content, 150))
+ } else {
+ content.to_string()
+ };
+ println!(" \x1b[2m└─ Result: {}\x1b[0m", truncated);
+ }
+ _ => {}
}
}
- Err(e) => {
- eprintln!("\x1b[1;31mFailed to send request: {}\x1b[0m", e);
- }
}
}
+ }
- println!("\nGoodbye!");
- Ok(())
+ /// Print response with optional markdown rendering
+ fn print_response(&self, message: &str) {
+ if self.no_format {
+ println!("{}", message);
+ return;
+ }
+
+ println!("\x1b[1;31mBot:\x1b[0m");
+
+ // Try to render markdown, fall back to plain text
+ render_markdown(message);
+ }
+
+ /// Get history file path
+ fn get_history_path(&self) -> Option<std::path::PathBuf> {
+ dirs::home_dir().map(|home| home.join(HISTORY_FILE))
}
}
@@ -308,6 +354,7 @@ impl ChatCommand {
}
}
+#[allow(dead_code)]
impl ChatCommand {
/// Create a new ChatCommand with the given parameters
#[allow(clippy::too_many_arguments)]
@@ -319,6 +366,7 @@ impl ChatCommand {
message: Option<String>,
stream: bool,
no_format: bool,
+ no_history: bool,
) -> Self {
Self {
endpoint,
@@ -328,6 +376,25 @@ impl ChatCommand {
message,
stream,
no_format,
+ no_history,
}
}
}
+
+/// Render markdown to terminal using termimad
+fn render_markdown(text: &str) {
+ let skin = MadSkin::default();
+ skin.print_text(text);
+}
+
+/// Truncate UTF-8 string safely
+fn truncate_utf8(s: &str, max_chars: usize) -> &str {
+ if s.chars().count() <= max_chars {
+ return s;
+ }
+ if let Some((idx, _)) = s.char_indices().nth(max_chars) {
+ &s[..idx]
+ } else {
+ s
+ }
+}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index f41d20812..82f175c7e 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -335,9 +335,12 @@ enum Commands {
/// Session ID (defaults to machine unique ID)
#[arg(short, long)]
session: Option<String>,
- /// Render assistant output as Markdown
- #[arg(long = "markdown", default_value = "true")]
- markdown: bool,
+ /// Disable rich formatting / markdown rendering
+ #[arg(long)]
+ no_format: bool,
+ /// Disable command history
+ #[arg(long)]
+ no_history: bool,
},
/// Configuration management
Config {
@@ -573,7 +576,7 @@ async fn main() {
Commands::Tui { uri } => {
handle_tui(uri, ctx).await
}
- Commands::Chat { message, session, markdown } => {
+ Commands::Chat { message, session, no_format, no_history } => {
let session_id = session.or_else(|| config::get_or_create_machine_id().ok());
let cmd = commands::chat::ChatCommand {
endpoint: std::env::var("VIKINGBOT_ENDPOINT").unwrap_or_else(|_| "http://localhost:1933/bot/v1".to_string()),
@@ -582,7 +585,8 @@ async fn main() {
user: "cli_user".to_string(),
message,
stream: false,
- no_format: !markdown,
+ no_format,
+ no_history,
};
cmd.run().await
}