Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(cli): improve config wizard and result UX (#2408)
Hao Zhed803557347d9
diff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rsindex 8c4d58ee1..4ac6b04e9 100644--- a/crates/ov_cli/src/commands/admin.rs+++ b/crates/ov_cli/src/commands/admin.rs@@ -1,7 +1,11 @@use crate::client::HttpClient;use crate::error::Result;use crate::output::{OutputFormat, output_success};-use serde_json::json;+use crate::theme;+use colored::Colorize;+use serde_json::{Value, json};++const SECRET_PLACEHOLDER: &str = "********";pub async fn create_account(client: &HttpClient,@@ -14,6 +18,7 @@ pub async fn create_account(.admin_create_account(account_id, admin_user_id).await?;output_success(&response, output_format, compact);+ print_admin_user_key_notice(&response, output_format, false);Ok(())}@@ -56,6 +61,7 @@ pub async fn register_user(.admin_register_user(account_id, user_id, role).await?;output_success(&response, output_format, compact);+ print_admin_user_key_notice(&response, output_format, false);Ok(())}@@ -68,7 +74,10 @@ pub async fn list_users(output_format: OutputFormat,compact: bool,) -> Result<()> {- let response = client.admin_list_users(account_id, limit, name, role).await?;+ let response = client+ .admin_list_users(account_id, limit, name, role)+ .await?;+ let response = list_users_response_for_output(response, output_format);output_success(&response, output_format, compact);Ok(())}@@ -124,5 +133,216 @@ pub async fn regenerate_key() -> Result<()> {let response = client.admin_regenerate_key(account_id, user_id).await?;output_success(&response, output_format, compact);+ print_admin_user_key_notice(&response, output_format, true);Ok(())}++fn print_admin_user_key_notice(+ response: &Value,+ output_format: OutputFormat,+ invalidates_old: bool,+) {+ let lines = admin_user_key_notice_lines(response, output_format, invalidates_old);+ if lines.is_empty() {+ return;+ }++ println!();+ for line in lines {+ println!("{line}");+ }+}++fn admin_user_key_notice_lines(+ response: &Value,+ output_format: OutputFormat,+ invalidates_old: bool,+) -> Vec<String> {+ if !matches!(output_format, OutputFormat::Table) || !contains_non_empty_user_key(response) {+ return Vec::new();+ }++ let mut lines = vec![+ format!(+ "{} {}",+ theme::warning("New user key generated.").bold(),+ theme::body("Copy and store it securely now.")+ ),+ format!(+ "{} {}{}",+ theme::body("This key may not be shown again. If lost, run"),+ theme::command("ov admin regenerate-key"),+ theme::body(".")+ ),+ format!(+ "{} {} {} {} {} {}{}",+ theme::body("To use this key for normal commands, run"),+ theme::command("ov config"),+ theme::body("->"),+ theme::heading("Edit config"),+ theme::body("->"),+ theme::heading("Set normal user API key"),+ theme::body(".")+ ),+ ];++ if invalidates_old {+ lines.push(+ theme::warning("The old user key is invalidated immediately.")+ .bold()+ .to_string(),+ );+ }++ lines+}++fn contains_non_empty_user_key(value: &Value) -> bool {+ match value {+ Value::Object(object) => {+ object+ .get("user_key")+ .and_then(Value::as_str)+ .is_some_and(|key| !key.trim().is_empty())+ || object.values().any(contains_non_empty_user_key)+ }+ Value::Array(items) => items.iter().any(contains_non_empty_user_key),+ _ => false,+ }+}++fn list_users_response_for_output(mut response: Value, output_format: OutputFormat) -> Value {+ if matches!(output_format, OutputFormat::Table) {+ redact_plaintext_api_keys(&mut response);+ }+ response+}++fn redact_plaintext_api_keys(value: &mut Value) {+ match value {+ Value::Object(object) => {+ for (key, child) in object {+ if key == "api_key"+ && child+ .as_str()+ .is_some_and(|api_key| !api_key.trim().is_empty())+ {+ *child = Value::String(SECRET_PLACEHOLDER.to_string());+ } else {+ redact_plaintext_api_keys(child);+ }+ }+ }+ Value::Array(items) => {+ for item in items {+ redact_plaintext_api_keys(item);+ }+ }+ _ => {}+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn user_key_notice_appears_for_table_key_generation_response() {+ let response = json!({+ "account_id": "acme",+ "admin_user_id": "alice",+ "user_key": "user-secret"+ });++ let lines = admin_user_key_notice_lines(&response, OutputFormat::Table, false);+ let rendered = lines.join("\n");++ assert!(rendered.contains("New user key generated. Copy and store it securely now."));+ assert!(+ rendered+ .contains("This key may not be shown again. If lost, run ov admin regenerate-key.")+ );+ assert!(rendered.contains("To use this key for normal commands, run ov config -> Edit config -> Set normal user API key."));+ assert!(!rendered.contains("old user key is invalidated"));+ }++ #[test]+ fn user_key_notice_detects_nested_result_response() {+ let response = json!({+ "status": "ok",+ "result": {+ "account_id": "acme",+ "user_key": "user-secret"+ }+ });++ assert!(!admin_user_key_notice_lines(&response, OutputFormat::Table, false).is_empty());+ }++ #[test]+ fn user_key_notice_is_hidden_without_non_empty_user_key() {+ let no_key = json!({"account_id": "acme", "admin_user_id": "alice"});+ let empty_key = json!({"account_id": "acme", "user_key": " "});++ assert!(admin_user_key_notice_lines(&no_key, OutputFormat::Table, false).is_empty());+ assert!(admin_user_key_notice_lines(&empty_key, OutputFormat::Table, false).is_empty());+ }++ #[test]+ fn user_key_notice_is_hidden_for_json_output() {+ let response = json!({"account_id": "acme", "user_key": "user-secret"});++ assert!(admin_user_key_notice_lines(&response, OutputFormat::Json, false).is_empty());+ }++ #[test]+ fn regenerate_key_notice_mentions_old_key_invalidation() {+ let response = json!({"user_key": "new-user-secret"});++ let rendered = admin_user_key_notice_lines(&response, OutputFormat::Table, true).join("\n");++ assert!(rendered.contains("The old user key is invalidated immediately."));+ }++ #[test]+ fn list_users_table_output_redacts_plaintext_api_keys() {+ let response = json!([+ {"user_id": "alice", "role": "admin", "api_key": "plain-secret"},+ {"user_id": "bob", "role": "user", "key_prefix": "prefix123"}+ ]);++ let sanitized = list_users_response_for_output(response, OutputFormat::Table);++ assert_eq!(+ sanitized,+ json!([+ {"user_id": "alice", "role": "admin", "api_key": "********"},+ {"user_id": "bob", "role": "user", "key_prefix": "prefix123"}+ ])+ );+ }++ #[test]+ fn list_users_table_output_preserves_empty_api_keys() {+ let response = json!([+ {"user_id": "alice", "role": "admin", "api_key": ""},+ {"user_id": "bob", "role": "user", "api_key": " "}+ ]);++ let sanitized = list_users_response_for_output(response.clone(), OutputFormat::Table);++ assert_eq!(sanitized, response);+ }++ #[test]+ fn list_users_json_output_preserves_plaintext_api_keys() {+ let response = json!([+ {"user_id": "alice", "role": "admin", "api_key": "plain-secret"}+ ]);++ let sanitized = list_users_response_for_output(response.clone(), OutputFormat::Json);++ assert_eq!(sanitized, response);+ }+}diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rsindex 06216bc9a..d910de9b8 100644--- a/crates/ov_cli/src/commands/filesystem.rs+++ b/crates/ov_cli/src/commands/filesystem.rs@@ -1,6 +1,20 @@+use super::render_utils::{append_profile_lines, with_ascii_ellipsis, wrap_display_text};use crate::client::HttpClient;use crate::error::Result;use crate::output::{OutputFormat, output_success};+use crate::theme;+use colored::Colorize;+use serde_json::Value;+use std::io::IsTerminal;+use unicode_width::UnicodeWidthStr;++const ENTRY_TEXT_WIDTH: usize = 96;+const ENTRY_MIN_TEXT_WIDTH: usize = 32;+const ENTRY_MAX_ABSTRACT_LINES: usize = 2;+const ENTRY_INDENT: &str = " ";+const TREE_INDENT: &str = " ";+const TREE_NAME_COLUMN_WIDTH: usize = 38;+const TREE_MIN_NAME_COLUMN_WIDTH: usize = 18;pub async fn ls(client: &HttpClient,@@ -25,7 +39,7 @@ pub async fn ls(node_limit,).await?;- output_success(&result, output_format, compact);+ output_filesystem_entries(&result, output_format, compact, false);Ok(())}@@ -50,10 +64,297 @@ pub async fn tree(level_limit,).await?;- output_success(&result, output_format, compact);+ output_filesystem_entries(&result, output_format, compact, true);Ok(())}+fn output_filesystem_entries(+ result: &Value,+ output_format: OutputFormat,+ compact: bool,+ is_tree: bool,+) {+ if let Some(rendered) = render_filesystem_entries_for_table(result, output_format, is_tree) {+ println!("{rendered}");+ } else {+ output_success(result, output_format, compact);+ }+}++fn render_filesystem_entries_for_table(+ value: &Value,+ output_format: OutputFormat,+ is_tree: bool,+) -> Option<String> {+ if matches!(output_format, OutputFormat::Json) {+ return None;+ }+ if is_tree {+ render_tree_entries_for_table(value)+ } else {+ render_ls_entries_for_table(value)+ }+}++fn render_ls_entries_for_table(value: &Value) -> Option<String> {+ let (entries, profile) = filesystem_entries(value)?;+ let mut lines = Vec::new();+ let text_width = entry_text_width();++ if entries.is_empty() {+ lines.push(theme::muted("(empty)").to_string());+ append_profile_lines(profile, &mut lines);+ return Some(lines.join("\n"));+ }++ for (index, entry) in entries.iter().enumerate() {+ if index > 0 {+ lines.push(String::new());+ }+ render_ls_entry(index + 1, entry, text_width, &mut lines);+ }++ append_profile_lines(profile, &mut lines);+ Some(lines.join("\n"))+}++fn render_tree_entries_for_table(value: &Value) -> Option<String> {+ let (entries, profile) = filesystem_entries(value)?;+ let mut lines = Vec::new();+ let text_width = entry_text_width();++ if entries.is_empty() {+ lines.push(theme::muted("(empty)").to_string());+ append_profile_lines(profile, &mut lines);+ return Some(lines.join("\n"));+ }++ for (index, entry) in entries.iter().enumerate() {+ render_tree_entry(index + 1, entry, text_width, &mut lines);+ }++ append_profile_lines(profile, &mut lines);+ Some(lines.join("\n"))+}++fn filesystem_entries(value: &Value) -> Option<(Vec<&Value>, Option<&Value>)> {+ if let Some(entries) = value.as_array() {+ if entries.iter().all(Value::is_object) {+ return Some((entries.iter().collect(), None));+ }+ return None;+ }++ let object = value.as_object()?;+ let profile = object.get("profile").filter(|profile| !profile.is_null());+ let entries = object.get("result")?.as_array()?;+ if !entries.iter().all(Value::is_object) {+ return None;+ }+ Some((entries.iter().collect(), profile))+}++fn render_ls_entry(rank: usize, entry: &Value, text_width: usize, lines: &mut Vec<String>) {+ let object = entry.as_object();+ let metadata = entry_metadata(object, false);+ lines.push(format!(+ "{}. {}",+ theme::command(rank.to_string()).bold(),+ metadata.join(" · ")+ ));++ if let Some(uri) = entry_string(object, "uri") {+ for line in wrap_display_text(uri, text_width, 2) {+ lines.push(format!("{ENTRY_INDENT}{}", theme::sky_value(line).bold()));+ }+ }++ append_entry_abstract(object, ENTRY_INDENT, text_width, lines);+}++fn render_tree_entry(rank: usize, entry: &Value, text_width: usize, lines: &mut Vec<String>) {+ let object = entry.as_object();+ let rel_path = entry_string(object, "rel_path");+ let path = rel_path+ .or_else(|| entry_string(object, "uri"))+ .unwrap_or("entry");+ let depth = rel_path+ .map(|rel_path| rel_path.matches('/').count())+ .unwrap_or(0);+ let indent = TREE_INDENT.repeat(depth);+ let display_name = path+ .trim_end_matches('/')+ .rsplit('/')+ .next()+ .filter(|value| !value.is_empty())+ .unwrap_or(path);+ let display_name = if entry_is_dir(object) {+ format!("{display_name}/")+ } else {+ display_name.to_string()+ };+ let metadata = tree_metadata(object);++ if rank > 1 && depth == 0 {+ lines.push(String::new());+ }++ lines.push(render_tree_line(+ &indent,+ &display_name,+ &metadata.join(" "),+ text_width,+ ));+}++fn entry_metadata(+ object: Option<&serde_json::Map<String, Value>>,+ compact_directory: bool,+) -> Vec<String> {+ let mut metadata = vec![+ theme::heading(if entry_is_dir(object) { "dir" } else { "file" })+ .bold()+ .to_string(),+ ];++ if !entry_is_dir(object)+ && let Some(size) = object+ .and_then(|object| object.get("size"))+ .and_then(Value::as_u64)+ {+ metadata.push(theme::value(format_size(size)).bold().to_string());+ }++ if !compact_directory || !entry_is_dir(object) {+ if let Some(mod_time) = entry_string(object, "modTime") {+ metadata.push(theme::muted(mod_time).to_string());+ }+ } else if let Some(mod_time) = entry_string(object, "modTime") {+ metadata.push(theme::muted(mod_time).to_string());+ }++ metadata+}++fn append_entry_abstract(+ object: Option<&serde_json::Map<String, Value>>,+ indent: &str,+ text_width: usize,+ lines: &mut Vec<String>,+) {+ let Some(abstract_text) = entry_string(object, "abstract") else {+ return;+ };+ if abstract_text.trim().is_empty() || is_directory_abstract_placeholder(abstract_text) {+ return;+ }++ for line in wrap_display_text(abstract_text, text_width, ENTRY_MAX_ABSTRACT_LINES) {+ lines.push(format!("{indent}{}", theme::body(line)));+ }+}++fn tree_metadata(object: Option<&serde_json::Map<String, Value>>) -> Vec<String> {+ let mut metadata = Vec::new();++ if !entry_is_dir(object)+ && let Some(size) = object+ .and_then(|object| object.get("size"))+ .and_then(Value::as_u64)+ {+ metadata.push(format_size(size));+ }++ if let Some(mod_time) = entry_string(object, "modTime") {+ metadata.push(mod_time.to_string());+ }++ metadata+}++fn render_tree_line(indent: &str, name: &str, metadata: &str, text_width: usize) -> String {+ if metadata.is_empty() {+ return format!("{indent}{}", theme::sky_value(name).bold());+ }++ let available_width = text_width.saturating_sub(indent.width());+ let metadata_width = metadata.width();+ let name_column_width = if available_width > metadata_width + 2 {+ TREE_NAME_COLUMN_WIDTH+ .min(available_width - metadata_width - 2)+ .max(TREE_MIN_NAME_COLUMN_WIDTH.min(available_width))+ } else {+ TREE_MIN_NAME_COLUMN_WIDTH.min(available_width)+ };+ let display_name = fit_display_text(name, name_column_width);+ let padding = name_column_width.saturating_sub(display_name.width()) + 2;++ format!(+ "{indent}{}{}{}",+ theme::sky_value(display_name).bold(),+ " ".repeat(padding),+ theme::muted(metadata)+ )+}++fn fit_display_text(value: &str, width: usize) -> String {+ if value.width() > width {+ with_ascii_ellipsis(value, width)+ } else {+ value.to_string()+ }+}++fn entry_is_dir(object: Option<&serde_json::Map<String, Value>>) -> bool {+ object+ .and_then(|object| object.get("isDir"))+ .and_then(Value::as_bool)+ .unwrap_or(false)+}++fn entry_string<'a>(+ object: Option<&'a serde_json::Map<String, Value>>,+ key: &str,+) -> Option<&'a str> {+ object?+ .get(key)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+}++fn is_directory_abstract_placeholder(value: &str) -> bool {+ value.contains("[Directory abstract is not ready]")+}++fn format_size(bytes: u64) -> String {+ const KB: f64 = 1024.0;+ const MB: f64 = KB * 1024.0;+ const GB: f64 = MB * 1024.0;++ if bytes < 1024 {+ format!("{bytes} B")+ } else if (bytes as f64) < MB {+ format!("{:.1} KB", bytes as f64 / KB)+ } else if (bytes as f64) < GB {+ format!("{:.1} MB", bytes as f64 / MB)+ } else {+ format!("{:.1} GB", bytes as f64 / GB)+ }+}++fn entry_text_width() -> usize {+ if std::io::stdout().is_terminal()+ && let Ok((columns, _)) = crossterm::terminal::size()+ {+ return usize::from(columns)+ .saturating_sub(ENTRY_INDENT.width())+ .clamp(ENTRY_MIN_TEXT_WIDTH, ENTRY_TEXT_WIDTH);+ }++ ENTRY_TEXT_WIDTH+}+pub async fn mkdir(client: &HttpClient,uri: &str,@@ -80,7 +381,10 @@ pub async fn rm() -> Result<()> {let result = client.rm(uri, recursive).await?;- let message = if let Some(count) = result.get("estimated_deleted_count").and_then(|v| v.as_u64()) {+ let message = if let Some(count) = result+ .get("estimated_deleted_count")+ .and_then(|v| v.as_u64())+ {format!("Removed: {} ({} items)", uri, count)} else {format!("Removed: {}", uri)@@ -128,13 +432,20 @@ fn output_message_result(match output_format {OutputFormat::Json => output_success(result, output_format, compact),OutputFormat::Table => {- println!("{}", crate::output::append_profile_to_rendered(message, &result));+ println!(+ "{}",+ crate::output::append_profile_to_rendered(message, &result)+ );}}}#[cfg(test)]mod tests {+ use super::{+ render_filesystem_entries_for_table, render_ls_entries_for_table,+ render_tree_entries_for_table,+ };use crate::output::render_profiled_scalar_result;use serde_json::json;@@ -163,4 +474,127 @@ mod tests {));}++ #[test]+ fn ls_table_output_renders_compact_entry_list() {+ let result = json!([+ {+ "uri": "viking://resources",+ "size": 0,+ "isDir": true,+ "modTime": "2026-05-26",+ "abstract": "The resources directory is a centralized collection of learning and reference materials focused on cloud architecture, AWS best practices, and technical quick-reference content."+ },+ {+ "uri": "viking://agent",+ "size": 0,+ "isDir": true,+ "modTime": "2026-05-25",+ "abstract": "# viking://agent [Directory abstract is not ready]"+ }+ ]);++ let rendered = strip_ansi(&render_ls_entries_for_table(&result).expect("ls"));++ assert!(rendered.contains("1. dir · 2026-05-26"));+ assert!(rendered.contains("viking://resources"));+ assert!(rendered.contains("The resources directory is a centralized collection"));+ assert!(rendered.contains("2. dir · 2026-05-25"));+ assert!(!rendered.contains("Directory abstract is not ready"));+ assert!(!rendered.contains("uri size isDir"));+ for line in rendered.lines() {+ assert!(+ line.chars().count() < 140,+ "line should not sprawl horizontally: {line}"+ );+ }+ }++ #[test]+ fn tree_table_output_renders_indented_tree() {+ let result = json!([+ {+ "uri": "viking://user/haozhe/memories/entities/sports_event",+ "size": 0,+ "isDir": true,+ "modTime": "2026-05-25",+ "rel_path": "sports_event",+ "abstract": "# viking://user/haozhe/memories/entities/sports_event [Directory abstract is not ready]"+ },+ {+ "uri": "viking://user/haozhe/memories/entities/sports_event/2026_fifa_world_cup.md",+ "size": 1304,+ "isDir": false,+ "modTime": "2026-05-25",+ "rel_path": "sports_event/2026_fifa_world_cup.md",+ "abstract": ""+ },+ {+ "uri": "viking://user/haozhe/memories/entities/program",+ "size": 0,+ "isDir": true,+ "modTime": "2026-05-25",+ "rel_path": "program",+ "abstract": ""+ }+ ]);++ let rendered = strip_ansi(&render_tree_entries_for_table(&result).expect("tree"));++ assert!(rendered.contains("sports_event/"));+ assert!(rendered.contains(" 2026_fifa_world_cup.md"));+ assert!(rendered.contains("1.3 KB 2026-05-25"));+ assert!(rendered.contains("program/"));+ assert!(!rendered.contains("1. dir"));+ assert!(!rendered.contains("2. file"));+ assert!(!rendered.contains("Directory abstract is not ready"));+ assert!(!rendered.contains("uri size isDir"));+ }++ #[test]+ fn tree_table_output_does_not_indent_uri_fallback_like_a_path() {+ let result = json!([+ {+ "uri": "viking://resources",+ "size": 0,+ "isDir": true,+ "modTime": "2026-05-26",+ "abstract": ""+ }+ ]);++ let rendered = strip_ansi(&render_tree_entries_for_table(&result).expect("tree"));++ assert!(rendered.starts_with("resources/"));+ }++ #[test]+ fn filesystem_renderers_skip_json_output() {+ let result = json!([+ {"uri": "viking://resources", "isDir": true}+ ]);++ assert!(+ render_filesystem_entries_for_table(&result, crate::output::OutputFormat::Json, false)+ .is_none()+ );+ }++ fn strip_ansi(input: &str) -> String {+ let mut output = String::with_capacity(input.len());+ let mut chars = input.chars().peekable();+ while let Some(ch) = chars.next() {+ if ch == '\u{1b}' && chars.peek() == Some(&'[') {+ chars.next();+ for next in chars.by_ref() {+ if next == 'm' {+ break;+ }+ }+ } else {+ output.push(ch);+ }+ }+ output+ }}diff --git a/crates/ov_cli/src/commands/mod.rs b/crates/ov_cli/src/commands/mod.rsindex 678546561..13e390ac4 100644--- a/crates/ov_cli/src/commands/mod.rs+++ b/crates/ov_cli/src/commands/mod.rs@@ -7,6 +7,7 @@ pub mod observer;pub mod pack;pub mod privacy;pub mod relations;+pub(crate) mod render_utils;pub mod resources;pub mod search;pub mod session;diff --git a/crates/ov_cli/src/commands/render_utils.rs b/crates/ov_cli/src/commands/render_utils.rsnew file mode 100644index 000000000..835dee0c6--- /dev/null+++ b/crates/ov_cli/src/commands/render_utils.rs@@ -0,0 +1,145 @@+use crate::theme;+use serde_json::Value;+use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};++pub(crate) fn append_profile_lines(profile: Option<&Value>, lines: &mut Vec<String>) {+ let Some(profile) = profile else {+ return;+ };++ lines.push(String::new());+ lines.push(theme::heading("profile").to_string());++ if let Some(items) = profile.as_array() {+ for item in items {+ if let Some(text) = item.as_str() {+ lines.push(theme::body(text).to_string());+ } else {+ lines.push(theme::body(item.to_string()).to_string());+ }+ }+ return;+ }++ if let Some(text) = profile.as_str() {+ lines.push(theme::body(text).to_string());+ } else {+ lines.push(theme::body(profile.to_string()).to_string());+ }+}++pub(crate) fn wrap_display_text(input: &str, width: usize, max_lines: usize) -> Vec<String> {+ if width == 0 || max_lines == 0 {+ return Vec::new();+ }++ let normalized = input.split_whitespace().collect::<Vec<_>>().join(" ");+ if normalized.is_empty() {+ return Vec::new();+ }++ let mut lines = Vec::new();+ let mut current = String::new();+ let mut truncated = false;++ for word in normalized.split(' ') {+ if word.is_empty() {+ continue;+ }++ if append_word_to_line(&mut current, word, width) {+ continue;+ }++ if !current.is_empty() {+ lines.push(std::mem::take(&mut current));++ if lines.len() == max_lines {+ truncated = true;+ break;+ }++ if append_word_to_line(&mut current, word, width) {+ continue;+ }+ }++ let mut segment = String::new();+ let mut segment_width = 0;+ for ch in word.chars() {+ let char_width = UnicodeWidthChar::width(ch).unwrap_or(0);+ if !segment.is_empty() && segment_width + char_width > width {+ lines.push(segment);+ segment = String::new();+ segment_width = 0;++ if lines.len() == max_lines {+ truncated = true;+ break;+ }+ }++ segment.push(ch);+ segment_width += char_width;+ }++ if truncated {+ break;+ }++ current = segment;+ }++ if !truncated && !current.is_empty() {+ lines.push(current);+ }++ if lines.len() > max_lines {+ lines.truncate(max_lines);+ truncated = true;+ }++ if truncated {+ if let Some(last) = lines.last_mut() {+ *last = with_ascii_ellipsis(last, width);+ }+ }++ lines+}++fn append_word_to_line(line: &mut String, word: &str, width: usize) -> bool {+ let separator_width = usize::from(!line.is_empty());+ if line.width() + separator_width + word.width() > width {+ return false;+ }++ if !line.is_empty() {+ line.push(' ');+ }+ line.push_str(word);+ true+}++pub(crate) fn with_ascii_ellipsis(line: &str, width: usize) -> String {+ const ELLIPSIS: &str = "...";+ let ellipsis_width = ELLIPSIS.width();+ if line.width() + ellipsis_width <= width {+ return format!("{line}{ELLIPSIS}");+ }++ let target_width = width.saturating_sub(ellipsis_width);+ let mut output = String::new();+ let mut output_width = 0;++ for ch in line.chars() {+ let char_width = UnicodeWidthChar::width(ch).unwrap_or(0);+ if output_width + char_width > target_width {+ break;+ }+ output.push(ch);+ output_width += char_width;+ }++ format!("{}{ELLIPSIS}", output.trim_end())+}diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rsindex b247a54f1..52f0cb51c 100644--- a/crates/ov_cli/src/commands/search.rs+++ b/crates/ov_cli/src/commands/search.rs@@ -1,6 +1,48 @@+use super::render_utils::{append_profile_lines, wrap_display_text};use crate::client::HttpClient;use crate::error::Result;use crate::output::{OutputFormat, output_success};+use crate::theme;+use colored::Colorize;+use serde_json::Value;+use std::io::IsTerminal;+use unicode_width::UnicodeWidthStr;++const SEARCH_TEXT_WIDTH: usize = 96;+const SEARCH_MIN_TEXT_WIDTH: usize = 32;+const SEARCH_MAX_ABSTRACT_LINES: usize = 2;+const SEARCH_MAX_URI_LINES: usize = 2;+const SEARCH_INDENT: &str = " ";+const SEARCH_RESULT_COLLECTION_KEYS: &[&str] =+ &["memories", "resources", "skills", "results", "items"];++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum SearchRenderMode {+ Find,+ Search,+}++#[derive(Debug, Clone, Copy)]+struct SearchRenderContext {+ mode: SearchRenderMode,+ node_limit: i32,+}++impl SearchRenderContext {+ fn find(node_limit: i32) -> Self {+ Self {+ mode: SearchRenderMode::Find,+ node_limit,+ }+ }++ fn search(node_limit: i32) -> Self {+ Self {+ mode: SearchRenderMode::Search,+ node_limit,+ }+ }+}pub async fn find(client: &HttpClient,@@ -27,7 +69,12 @@ pub async fn find(level,).await?;- output_success(&result, output_format, compact);+ output_search_results(+ &result,+ output_format,+ compact,+ SearchRenderContext::find(node_limit),+ );Ok(())}@@ -58,9 +105,328 @@ pub async fn search(level,).await?;- output_success(&result, output_format, compact);+ output_search_results(+ &result,+ output_format,+ compact,+ SearchRenderContext::search(node_limit),+ );Ok(())}++fn output_search_results(+ result: &Value,+ output_format: OutputFormat,+ compact: bool,+ context: SearchRenderContext,+) {+ if let Some(rendered) =+ render_search_output_for_table_with_context(result, output_format, Some(context))+ {+ println!("{rendered}");+ } else {+ output_success(result, output_format, compact);+ }+}++#[cfg(test)]+fn render_search_output_for_table(value: &Value, output_format: OutputFormat) -> Option<String> {+ render_search_output_for_table_with_context(value, output_format, None)+}++fn render_search_output_for_table_with_context(+ value: &Value,+ output_format: OutputFormat,+ context: Option<SearchRenderContext>,+) -> Option<String> {+ if matches!(output_format, OutputFormat::Json) {+ return None;+ }+ render_search_results_for_table_with_context(value, context)+}++#[cfg(test)]+fn render_search_results_for_table(value: &Value) -> Option<String> {+ render_search_results_for_table_with_context(value, None)+}++fn render_search_results_for_table_with_context(+ value: &Value,+ context: Option<SearchRenderContext>,+) -> Option<String> {+ let (items, profile) = search_result_items(value)?;+ let mut lines = Vec::new();+ let text_width = search_card_text_width();++ if items.is_empty() {+ lines.push(theme::muted("No results found.").to_string());+ lines.push(+ theme::body("Try a broader query, lower --threshold, or search a wider --uri.")+ .to_string(),+ );+ return Some(lines.join("\n"));+ }++ let pass_count = search_pass_count(value);+ lines.push(+ theme::heading(search_result_summary(items.len(), context, pass_count))+ .bold()+ .to_string(),+ );+ lines.push(theme::body(search_ranking_line(context, pass_count)).to_string());+ lines.push(String::new());++ for (index, item) in items.iter().enumerate() {+ if index > 0 {+ lines.push(String::new());+ }+ render_search_result_card(index + 1, item, text_width, &mut lines);+ }++ append_profile_lines(profile, &mut lines);+ Some(lines.join("\n"))+}++fn search_result_summary(+ item_count: usize,+ context: Option<SearchRenderContext>,+ pass_count: Option<usize>,+) -> String {+ let mut summary = format!(+ "{} {}",+ item_count,+ pluralize(item_count as u64, "result", "results")+ );++ if matches!(+ context.map(|context| context.mode),+ Some(SearchRenderMode::Search)+ ) && let Some(pass_count) = pass_count.filter(|count| *count > 1)+ {+ summary.push_str(&format!(+ " from {pass_count} {}",+ pluralize(pass_count as u64, "search pass", "search passes")+ ));+ }++ summary+}++fn search_ranking_line(context: Option<SearchRenderContext>, pass_count: Option<usize>) -> String {+ let Some(context) = context.filter(|context| context.node_limit > 0) else {+ return "Ranked by relevance".to_string();+ };++ let suffix = match context.mode {+ SearchRenderMode::Find => format!(+ "limit {} final {}",+ context.node_limit,+ pluralize(context.node_limit as u64, "result", "results")+ ),+ SearchRenderMode::Search if pass_count.is_some_and(|count| count > 1) => {+ format!("limit {} per pass", context.node_limit)+ }+ SearchRenderMode::Search => format!("limit {} per search pass", context.node_limit),+ };++ format!("Ranked by relevance · {suffix}")+}++fn search_pass_count(value: &Value) -> Option<usize> {+ fn count_from_object(object: &serde_json::Map<String, Value>) -> Option<usize> {+ object+ .get("query_plan")?+ .get("queries")?+ .as_array()+ .map(Vec::len)+ }++ let object = value.as_object()?;+ count_from_object(object).or_else(|| {+ object+ .get("result")+ .and_then(Value::as_object)+ .and_then(count_from_object)+ })+}++fn search_result_items(value: &Value) -> Option<(Vec<&Value>, Option<&Value>)> {+ if let Some(items) = value.as_array() {+ return Some((items.iter().collect(), None));+ }++ let object = value.as_object()?;+ let profile = object.get("profile").filter(|profile| !profile.is_null());++ if let Some(items) = object.get("result").and_then(Value::as_array) {+ return Some((items.iter().collect(), profile));+ }++ if let Some(result_object) = object.get("result").and_then(Value::as_object) {+ let nested_profile = result_object+ .get("profile")+ .filter(|profile| !profile.is_null())+ .or(profile);+ return collect_search_result_collections(result_object, nested_profile);+ }++ collect_search_result_collections(object, profile)+}++fn collect_search_result_collections<'a>(+ object: &'a serde_json::Map<String, Value>,+ profile: Option<&'a Value>,+) -> Option<(Vec<&'a Value>, Option<&'a Value>)> {+ let mut saw_collection = false;+ let mut items = Vec::new();++ for key in SEARCH_RESULT_COLLECTION_KEYS {+ if let Some(collection) = object.get(*key).and_then(Value::as_array) {+ saw_collection = true;+ items.extend(collection.iter());+ }+ }++ if saw_collection {+ Some((items, profile))+ } else {+ None+ }+}++fn render_search_result_card(+ rank: usize,+ item: &Value,+ text_width: usize,+ lines: &mut Vec<String>,+) {+ let object = item.as_object();+ let mut metadata = vec![+ theme::heading(search_result_kind(object))+ .bold()+ .to_string(),+ ];++ if let Some(level) = search_result_level(object) {+ metadata.push(theme::value(level).bold().to_string());+ }++ if let Some(score) = search_result_score(object) {+ metadata.push(theme::warning(score).bold().to_string());+ }++ lines.push(format!(+ "{}. {}",+ theme::command(rank.to_string()).bold(),+ metadata.join(" · ")+ ));++ if let Some(uri) = search_result_uri(object) {+ for line in wrap_display_text(uri, text_width, SEARCH_MAX_URI_LINES) {+ lines.push(format!("{SEARCH_INDENT}{}", theme::sky_value(line).bold()));+ }+ }++ let abstract_text = search_result_text(item, object);+ let wrapped = wrap_display_text(&abstract_text, text_width, SEARCH_MAX_ABSTRACT_LINES);+ if wrapped.is_empty() {+ lines.push(format!(+ "{SEARCH_INDENT}{}",+ theme::muted("No abstract available.")+ ));+ } else {+ for line in wrapped {+ lines.push(format!("{SEARCH_INDENT}{}", theme::body(line)));+ }+ }+}++fn search_card_text_width() -> usize {+ if std::io::stdout().is_terminal()+ && let Ok((columns, _)) = crossterm::terminal::size()+ {+ return usize::from(columns)+ .saturating_sub(SEARCH_INDENT.width())+ .clamp(SEARCH_MIN_TEXT_WIDTH, SEARCH_TEXT_WIDTH);+ }++ SEARCH_TEXT_WIDTH+}++fn search_result_kind(object: Option<&serde_json::Map<String, Value>>) -> &str {+ object+ .and_then(|object| object.get("context_type").or_else(|| object.get("type")))+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .unwrap_or("result")+}++fn search_result_level(object: Option<&serde_json::Map<String, Value>>) -> Option<String> {+ let value = object?.get("level")?;+ if let Some(level) = value.as_i64() {+ return Some(format!("Level {level}"));+ }+ value.as_str().and_then(|level| {+ let level = level.trim();+ if level.is_empty() {+ None+ } else {+ Some(format!("Level {}", normalize_level_value(level)))+ }+ })+}++fn normalize_level_value(level: &str) -> &str {+ level+ .strip_prefix("Level ")+ .or_else(|| level.strip_prefix("level "))+ .or_else(|| level.strip_prefix('L'))+ .or_else(|| level.strip_prefix('l'))+ .unwrap_or(level)+ .trim()+}++fn search_result_score(object: Option<&serde_json::Map<String, Value>>) -> Option<String> {+ let value = object?.get("score")?;+ let score = value.as_f64().or_else(|| {+ value+ .as_str()+ .and_then(|value| value.trim().parse::<f64>().ok())+ })?;+ Some(format!("score {score:.3}"))+}++fn search_result_uri(object: Option<&serde_json::Map<String, Value>>) -> Option<&str> {+ object?+ .get("uri")+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+}++fn search_result_text(item: &Value, object: Option<&serde_json::Map<String, Value>>) -> String {+ for key in ["abstract", "snippet", "content", "text"] {+ if let Some(text) = object+ .and_then(|object| object.get(key))+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ {+ return text.to_string();+ }+ }++ if object.is_some() {+ return "No abstract available.".to_string();+ }++ match item {+ Value::String(value) => value.clone(),+ other => other.to_string(),+ }+}+pub async fn grep(client: &HttpClient,uri: &str,@@ -82,10 +448,105 @@ pub async fn grep(level_limit,).await?;- output_success(&result, output_format, compact);+ output_grep_results(&result, output_format, compact);Ok(())}+fn output_grep_results(result: &Value, output_format: OutputFormat, compact: bool) {+ if let Some(rendered) = render_grep_output_for_table(result, output_format) {+ println!("{rendered}");+ } else {+ output_success(result, output_format, compact);+ }+}++fn render_grep_output_for_table(value: &Value, output_format: OutputFormat) -> Option<String> {+ if matches!(output_format, OutputFormat::Json) {+ return None;+ }++ let object = value.as_object()?;+ let matches = object.get("matches")?.as_array()?;+ let profile = object.get("profile").filter(|profile| !profile.is_null());+ let mut lines = Vec::new();+ let text_width = search_card_text_width();++ if matches.is_empty() {+ lines.push(theme::muted("No matches found.").to_string());+ lines.push(theme::body("Try a broader pattern or search a wider --uri.").to_string());+ append_profile_lines(profile, &mut lines);+ return Some(lines.join("\n"));+ }++ let match_count = object+ .get("match_count")+ .or_else(|| object.get("count"))+ .and_then(Value::as_u64)+ .unwrap_or(matches.len() as u64);+ let files_scanned = object.get("files_scanned").and_then(Value::as_u64);+ let mut summary = format!(+ "{match_count} {}",+ pluralize(match_count, "match", "matches")+ );+ if let Some(files_scanned) = files_scanned {+ summary.push_str(&format!(+ " · {files_scanned} {} scanned",+ pluralize(files_scanned, "file", "files")+ ));+ }+ lines.push(theme::heading(summary).bold().to_string());++ for (index, item) in matches.iter().enumerate() {+ lines.push(String::new());+ render_grep_match_card(index + 1, item, text_width, &mut lines);+ }++ append_profile_lines(profile, &mut lines);+ Some(lines.join("\n"))+}++fn render_grep_match_card(rank: usize, item: &Value, text_width: usize, lines: &mut Vec<String>) {+ let object = item.as_object();+ let line_number = object+ .and_then(|object| object.get("line"))+ .and_then(Value::as_i64)+ .map(|line| line.to_string())+ .unwrap_or_else(|| "?".to_string());++ lines.push(format!(+ "{}. {} {}",+ theme::command(rank.to_string()).bold(),+ theme::heading("line").bold(),+ theme::value(line_number).bold()+ ));++ if let Some(uri) = object+ .and_then(|object| object.get("uri"))+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ {+ for line in wrap_display_text(uri, text_width, SEARCH_MAX_URI_LINES) {+ lines.push(format!("{SEARCH_INDENT}{}", theme::sky_value(line).bold()));+ }+ }++ if let Some(content) = object+ .and_then(|object| object.get("content"))+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ {+ for line in wrap_display_text(content, text_width, SEARCH_MAX_ABSTRACT_LINES) {+ lines.push(format!("{SEARCH_INDENT}{}", theme::body(line)));+ }+ }+}++fn pluralize<'a>(count: u64, singular: &'a str, plural: &'a str) -> &'a str {+ if count == 1 { singular } else { plural }+}+pub async fn glob(client: &HttpClient,pattern: &str,@@ -98,3 +559,364 @@ pub async fn glob(output_success(&result, output_format, compact);Ok(())}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn search_result_cards_render_ranked_scannable_rows() {+ let results = json!([+ {+ "context_type": "memory",+ "uri": "viking://user/default/memories/entities/.overview.md",+ "level": 1,+ "score": 0.3805481195449829,+ "abstract": "Entity memories from user's world. Each entity has its own subdirectory including projects, people, concepts, etc."+ }+ ]);++ let rendered = strip_ansi(&render_search_results_for_table(&results).expect("cards"));++ assert!(rendered.starts_with("1 result\nRanked by relevance\n\n"));+ assert!(rendered.contains("1. memory · Level 1 · score 0.381"));+ assert!(rendered.contains("viking://user/default/memories/entities/.overview.md"));+ assert!(rendered.contains("Entity memories from user's world."));+ assert!(!rendered.contains("peop\n le"));+ assert!(!rendered.contains("context_type uri"));+ }++ #[test]+ fn search_result_cards_wrap_and_truncate_long_mixed_language_abstracts() {+ let results = json!([+ {+ "type": "resource",+ "uri": "viking://resources/openviking-conversation-2026-06-01.md",+ "score": 0.37084102630615234,+ "abstract": "本资源包含大量 OpenViking CLI 设置和调试记录,涵盖配置、认证、错误提示、命令输出和用户体验改进。This document is intentionally long enough to require wrapping and truncation in terminal output."+ }+ ]);++ let rendered = strip_ansi(&render_search_results_for_table(&results).expect("cards"));+ let abstract_lines: Vec<&str> = rendered+ .lines()+ .filter(|line| {+ line.trim_start().starts_with("本资源") || line.trim_start().starts_with("This")+ })+ .collect();++ assert!(!abstract_lines.is_empty());+ assert!(rendered.contains("..."));+ for line in rendered.lines() {+ assert!(+ line.chars().count() < 140,+ "line should not sprawl horizontally: {line}"+ );+ }+ }++ #[test]+ fn search_result_cards_handle_missing_optional_fields() {+ let results = json!([+ {"uri": "viking://resources/only-uri.md"}+ ]);++ let rendered = strip_ansi(&render_search_results_for_table(&results).expect("cards"));++ assert!(rendered.contains("1. result"));+ assert!(rendered.contains("viking://resources/only-uri.md"));+ assert!(rendered.contains("No abstract available."));+ assert!(!rendered.contains("score"));+ assert!(!rendered.contains("Level 0"));+ }++ #[test]+ fn search_result_cards_expand_compact_string_levels() {+ let results = json!([+ {+ "context_type": "memory",+ "uri": "viking://user/default/memories/events/.abstract.md",+ "level": "l0",+ "score": 0.42,+ "abstract": "User event records."+ },+ {+ "context_type": "memory",+ "uri": "viking://user/default/memories/.overview.md",+ "level": "Level 1",+ "score": 0.41,+ "abstract": "User memory overview."+ }+ ]);++ let rendered = strip_ansi(&render_search_results_for_table(&results).expect("cards"));++ assert!(rendered.starts_with("2 results\nRanked by relevance\n\n"));+ assert!(rendered.contains("1. memory · Level 0 · score 0.420"));+ assert!(rendered.contains("2. memory · Level 1 · score 0.410"));+ assert!(!rendered.contains(" L0 "));+ assert!(!rendered.contains(" L1 "));+ }++ #[test]+ fn search_result_cards_explain_multi_pass_search_limits() {+ let results = json!({+ "query_plan": {+ "queries": [+ {"query": "codename", "context_type": "memory"},+ {"query": "codename", "context_type": "resource"}+ ]+ },+ "memories": [+ {+ "context_type": "memory",+ "uri": "viking://user/default/memories/entities/.overview.md",+ "level": 1,+ "score": 0.452,+ "abstract": "Entity memories from user's world."+ }+ ],+ "resources": [+ {+ "context_type": "resource",+ "uri": "viking://resources/reference.md",+ "level": 0,+ "score": 0.401,+ "abstract": "Reference resource."+ }+ ]+ });++ let rendered = strip_ansi(+ &render_search_results_for_table_with_context(+ &results,+ Some(SearchRenderContext::search(10)),+ )+ .expect("cards"),+ );++ assert!(rendered.starts_with(+ "2 results from 2 search passes\nRanked by relevance · limit 10 per pass\n\n"+ ));+ }++ #[test]+ fn search_result_cards_explain_search_limit_without_query_plan() {+ let results = json!([+ {+ "context_type": "memory",+ "uri": "viking://user/default/memories/entities/.overview.md",+ "level": 1,+ "score": 0.452,+ "abstract": "Entity memories from user's world."+ }+ ]);++ let rendered = strip_ansi(+ &render_search_results_for_table_with_context(+ &results,+ Some(SearchRenderContext::search(10)),+ )+ .expect("cards"),+ );++ assert!(+ rendered.starts_with("1 result\nRanked by relevance · limit 10 per search pass\n\n")+ );+ }++ #[test]+ fn find_result_cards_explain_final_result_limit() {+ let results = json!([+ {+ "context_type": "memory",+ "uri": "viking://user/default/memories/entities/.overview.md",+ "level": 1,+ "score": 0.452,+ "abstract": "Entity memories from user's world."+ }+ ]);++ let rendered = strip_ansi(+ &render_search_results_for_table_with_context(+ &results,+ Some(SearchRenderContext::find(10)),+ )+ .expect("cards"),+ );++ assert!(rendered.starts_with("1 result\nRanked by relevance · limit 10 final results\n\n"));+ }++ #[test]+ fn search_result_cards_show_empty_state() {+ let rendered = strip_ansi(&render_search_results_for_table(&json!([])).expect("empty"));++ assert!(rendered.contains("No results found."));+ assert!(+ rendered.contains("Try a broader query, lower --threshold, or search a wider --uri.")+ );+ }++ #[test]+ fn search_result_cards_render_result_object_with_profile() {+ let results = json!({+ "result": [+ {+ "context_type": "memory",+ "uri": "viking://user/default/memories/events/.abstract.md",+ "abstract": "User event records.",+ }+ ],+ "profile": ["vector search: 12ms"]+ });++ let rendered = strip_ansi(&render_search_results_for_table(&results).expect("cards"));++ assert!(rendered.contains("1. memory"));+ assert!(rendered.contains("viking://user/default/memories/events/.abstract.md"));+ assert!(rendered.contains("profile"));+ assert!(rendered.contains("vector search: 12ms"));+ }++ #[test]+ fn search_result_cards_render_categorized_find_response() {+ let results = json!({+ "memories": [+ {+ "context_type": "memory",+ "uri": "viking://user/default/memories/entities/football_player/cristiano_ronaldo.md",+ "level": 2,+ "score": 0.5194366574287415,+ "abstract": "- 8 major individual awards\n- 35 career trophies"+ }+ ],+ "resources": [],+ "skills": [],+ "total": 1+ });++ let rendered = strip_ansi(&render_search_results_for_table(&results).expect("cards"));++ assert!(rendered.contains("1. memory · Level 2 · score 0.519"));+ assert!(rendered.contains(+ "viking://user/default/memories/entities/football_player/cristiano_ronaldo.md"+ ));+ assert!(rendered.contains("- 8 major individual awards - 35 career trophies"));+ assert!(!rendered.contains("context_type uri"));+ }++ #[test]+ fn search_result_cards_wrap_long_uris() {+ let long_uri = format!(+ "viking://resources/{}",+ "very-long-path-segment-".repeat(10)+ );+ let results = json!([+ {+ "type": "resource",+ "uri": long_uri,+ "abstract": "Short result."+ }+ ]);++ let rendered = strip_ansi(&render_search_results_for_table(&results).expect("cards"));++ assert!(rendered.contains("..."));+ for line in rendered.lines() {+ assert!(+ line.chars().count() < 140,+ "line should not sprawl horizontally: {line}"+ );+ }+ }++ #[test]+ fn search_result_renderer_skips_json_output() {+ let results = json!([+ {"uri": "viking://resources/raw.md", "abstract": "raw"}+ ]);++ assert!(render_search_output_for_table(&results, OutputFormat::Json).is_none());+ }++ #[test]+ fn grep_table_output_renders_match_cards() {+ let result = json!({+ "matches": [+ {+ "line": 1,+ "uri": "viking://user/haozhe/memories/events/2026/05/26/gent_canoeing.md",+ "content": "On 2026-05-26, user Haozhe provided a temporary codename and recorded a travel activity of canoeing in Ghent. The assistant noted these details and inquired whether this activity was part of Haozhe's 2025 European trip after Sweden."+ },+ {+ "line": 14,+ "uri": "viking://user/haozhe/memories/events/2026/05/26/gent_canoeing.md",+ "content": "\"event_name\": \"gent_canoeing\","+ }+ ],+ "count": 2,+ "match_count": 2,+ "files_scanned": 1+ });++ let rendered =+ strip_ansi(&render_grep_output_for_table(&result, OutputFormat::Table).expect("grep"));++ assert!(rendered.contains("2 matches · 1 file scanned"));+ assert!(rendered.contains("1. line 1"));+ assert!(+ rendered.contains("viking://user/haozhe/memories/events/2026/05/26/gent_canoeing.md")+ );+ assert!(rendered.contains("2. line 14"));+ assert!(!rendered.contains("line uri"));+ for line in rendered.lines() {+ assert!(+ line.chars().count() < 140,+ "line should not sprawl horizontally: {line}"+ );+ }+ }++ #[test]+ fn grep_table_output_handles_empty_matches() {+ let result = json!({+ "matches": [],+ "count": 0,+ "match_count": 0,+ "files_scanned": 3+ });++ let rendered =+ strip_ansi(&render_grep_output_for_table(&result, OutputFormat::Table).expect("grep"));++ assert!(rendered.contains("No matches found."));+ assert!(rendered.contains("Try a broader pattern or search a wider --uri."));+ }++ #[test]+ fn grep_renderer_skips_json_output() {+ let result = json!({"matches": []});++ assert!(render_grep_output_for_table(&result, OutputFormat::Json).is_none());+ }++ fn strip_ansi(input: &str) -> String {+ let mut output = String::with_capacity(input.len());+ let mut chars = input.chars().peekable();+ while let Some(ch) = chars.next() {+ if ch == '\u{1b}' && chars.peek() == Some(&'[') {+ chars.next();+ for next in chars.by_ref() {+ if next == 'm' {+ break;+ }+ }+ } else {+ output.push(ch);+ }+ }+ output+ }+}diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rsindex 3d025f656..3f1c60239 100644--- a/crates/ov_cli/src/commands/session.rs+++ b/crates/ov_cli/src/commands/session.rs@@ -1,6 +1,10 @@+use super::render_utils::append_profile_lines;use crate::client::HttpClient;-use crate::error::Result;+use crate::error::{Error, Result};use crate::output::{OutputFormat, output_success};+use crate::theme;+use colored::Colorize;+use serde_json::Value;use serde_json::json;pub async fn new_session(@@ -31,10 +35,182 @@ pub async fn get_session() -> Result<()> {let path = format!("/api/v1/sessions/{}", url_encode(session_id));let response: serde_json::Value = client.get(&path, &[]).await?;- output_success(&response, output_format, compact);+ output_session_get(&response, output_format, compact);Ok(())}+fn output_session_get(response: &Value, output_format: OutputFormat, compact: bool) {+ if matches!(output_format, OutputFormat::Table)+ && let Some(rendered) = render_session_get_for_table(response)+ {+ println!("{rendered}");+ } else {+ output_success(response, output_format, compact);+ }+}++fn render_session_get_for_table(value: &Value) -> Option<String> {+ let object = value.as_object()?;+ let session_id = object.get("session_id").and_then(Value::as_str)?;+ let mut lines = Vec::new();++ lines.push(theme::heading("Session").bold().to_string());+ push_row(&mut lines, "id", session_id);+ push_optional_row(&mut lines, "created", object.get("created_at"));+ push_optional_row(&mut lines, "updated", object.get("updated_at"));+ push_optional_row(&mut lines, "last commit", object.get("last_commit_at"));++ lines.push(String::new());+ lines.push(theme::heading("Identity").bold().to_string());+ push_optional_row(&mut lines, "created by", object.get("created_by_user_id"));+ if let Some(users) = object.get("participant_user_ids") {+ push_row(&mut lines, "participants", &format_list(users));+ }+ if let Some(agents) = object.get("participant_agent_ids") {+ push_row(&mut lines, "agents", &format_list(agents));+ }+ if let Some(user) = object.get("user").and_then(Value::as_object) {+ push_row(&mut lines, "active user", &format_identity(user));+ }++ lines.push(String::new());+ lines.push(theme::heading("Activity").bold().to_string());+ push_optional_row(&mut lines, "messages", object.get("message_count"));+ push_optional_row(+ &mut lines,+ "total messages",+ object.get("total_message_count"),+ );+ push_optional_row(&mut lines, "commits", object.get("commit_count"));+ push_optional_row(&mut lines, "pending tokens", object.get("pending_tokens"));+ push_optional_row(&mut lines, "keep recent", object.get("keep_recent_count"));++ if let Some(memories) = object.get("memories_extracted").and_then(Value::as_object) {+ lines.push(String::new());+ lines.push(theme::heading("Memory").bold().to_string());+ push_row(+ &mut lines,+ "memories extracted",+ &format_ordered_counts(+ memories,+ &[+ "profile",+ "preferences",+ "entities",+ "events",+ "cases",+ "patterns",+ "tools",+ "skills",+ "total",+ ],+ ),+ );+ }++ lines.push(String::new());+ lines.push(theme::heading("Tokens").bold().to_string());+ if let Some(llm) = object.get("llm_token_usage").and_then(Value::as_object) {+ push_row(+ &mut lines,+ "llm",+ &format_ordered_counts(llm, &["prompt_tokens", "completion_tokens", "total_tokens"]),+ );+ }+ if let Some(embedding) = object+ .get("embedding_token_usage")+ .and_then(Value::as_object)+ {+ push_row(+ &mut lines,+ "embedding",+ &format_ordered_counts(embedding, &["total_tokens"]),+ );+ }++ append_profile_lines(+ object.get("profile").filter(|profile| !profile.is_null()),+ &mut lines,+ );+ Some(lines.join("\n"))+}++fn push_optional_row(lines: &mut Vec<String>, label: &str, value: Option<&Value>) {+ let Some(value) = value else {+ return;+ };+ let formatted = format_json_value(value);+ if formatted.is_empty() || formatted == "null" {+ return;+ }+ push_row(lines, label, &formatted);+}++fn push_row(lines: &mut Vec<String>, label: &str, value: &str) {+ lines.push(format!(+ " {} {}",+ theme::muted(pad_label(label, 18)),+ theme::body(value)+ ));+}++fn pad_label(label: &str, width: usize) -> String {+ if label.len() >= width {+ label.to_string()+ } else {+ format!("{}{}", label, " ".repeat(width - label.len()))+ }+}++fn format_list(value: &Value) -> String {+ if let Some(items) = value.as_array() {+ return items+ .iter()+ .map(format_json_value)+ .filter(|value| !value.is_empty() && value != "null")+ .collect::<Vec<_>>()+ .join(", ");+ }+ format_json_value(value)+}++fn format_identity(object: &serde_json::Map<String, Value>) -> String {+ ["account_id", "user_id", "agent_id"]+ .into_iter()+ .filter_map(|key| object.get(key).map(|value| (key, format_json_value(value))))+ .filter(|(_, value)| !value.is_empty() && value != "null")+ .map(|(key, value)| format!("{key} {value}"))+ .collect::<Vec<_>>()+ .join(", ")+}++fn format_ordered_counts(object: &serde_json::Map<String, Value>, order: &[&str]) -> String {+ let mut parts = Vec::new();+ let mut seen = std::collections::HashSet::new();+ for key in order {+ if let Some(value) = object.get(*key) {+ seen.insert(*key);+ parts.push(format!("{key} {}", format_json_value(value)));+ }+ }+ for (key, value) in object {+ if !seen.contains(key.as_str()) {+ parts.push(format!("{key} {}", format_json_value(value)));+ }+ }+ parts.join(", ")+}++fn format_json_value(value: &Value) -> String {+ match value {+ Value::String(value) => value.clone(),+ Value::Number(value) => value.to_string(),+ Value::Bool(value) => value.to_string(),+ Value::Null => "null".to_string(),+ other => other.to_string(),+ }+}+pub async fn get_session_context(client: &HttpClient,session_id: &str,@@ -99,13 +275,13 @@ fn parse_messages(input: &str) -> Result<Vec<(String, String)>> {.enumerate().map(|(i, item)| {let role = item["role"].as_str().ok_or_else(|| {- crate::error::Error::Api(format!(+ Error::Client(format!("messages[{}]: 'role' must be a string, got {:?}",i, item["role"]))})?;let content = item["content"].as_str().ok_or_else(|| {- crate::error::Error::Api(format!(+ Error::Client(format!("messages[{}]: 'content' must be a string, got {:?}",i, item["content"]))@@ -116,13 +292,10 @@ fn parse_messages(input: &str) -> Result<Vec<(String, String)>> {return messages;} else if value.get("role").is_some() || value.get("content").is_some() {let role = value["role"].as_str().ok_or_else(|| {- crate::error::Error::Api(format!(- "'role' must be a string, got {:?}",- value["role"]- ))+ Error::Client(format!("'role' must be a string, got {:?}", value["role"]))})?;let content = value["content"].as_str().ok_or_else(|| {- crate::error::Error::Api(format!(+ Error::Client(format!("'content' must be a string, got {:?}",value["content"]))@@ -160,10 +333,7 @@ pub async fn add_messages(compact: bool,) -> Result<()> {let messages = parse_messages(input)?;- let path = format!(- "/api/v1/sessions/{}/messages/batch",- url_encode(session_id)- );+ let path = format!("/api/v1/sessions/{}/messages/batch", url_encode(session_id));let messages_json: Vec<serde_json::Value> = messages.iter().map(|(role, content)| json!({"role": role, "content": content}))@@ -208,10 +378,7 @@ pub async fn add_memory(})?;// 2. Add messages (batch)- let path = format!(- "/api/v1/sessions/{}/messages/batch",- url_encode(session_id)- );+ let path = format!("/api/v1/sessions/{}/messages/batch", url_encode(session_id));let messages_json: Vec<serde_json::Value> = messages.iter().map(|(role, content)| json!({"role": role, "content": content}))@@ -254,8 +421,36 @@ fn url_encode(s: &str) -> String {#[cfg(test)]mod tests {+ use super::{parse_messages, render_session_get_for_table};+ use crate::error::Error;use serde_json::json;+ #[test]+ fn parse_messages_reports_invalid_array_item_as_command_error() {+ let error = parse_messages(r#"[{"role":123,"content":"hello"}]"#)+ .expect_err("invalid role type should fail");++ match error {+ Error::Client(message) => {+ assert!(message.contains("messages[0]: 'role' must be a string"));+ }+ other => panic!("expected client error, got {other:?}"),+ }+ }++ #[test]+ fn parse_messages_reports_invalid_object_item_as_command_error() {+ let error = parse_messages(r#"{"role":"user","content":123}"#)+ .expect_err("invalid content type should fail");++ match error {+ Error::Client(message) => {+ assert!(message.contains("'content' must be a string"));+ }+ other => panic!("expected client error, got {other:?}"),+ }+ }+#[test]fn add_memory_ok_output_can_include_profile_section() {let result = json!({@@ -270,17 +465,80 @@ mod tests {assert_eq!(rendered,- Some(- [- "OK",- "",- "profile",- "create session 1ms",- "commit 2ms",- "",- ]- .join("\n")- )+ Some(["OK", "", "profile", "create session 1ms", "commit 2ms", "",].join("\n")));}++ #[test]+ fn session_get_table_output_groups_metadata_sections() {+ let result = json!({+ "session_id": "d34f8a7c-eb14-49c4-b689-2743ddb9b75e",+ "created_at": "2026-05-26T09:53:03.661Z",+ "updated_at": "2026-05-26T10:00:07.603Z",+ "created_by_user_id": "haozhe",+ "participant_user_ids": ["haozhe"],+ "participant_agent_ids": ["deerflow"],+ "message_count": 0,+ "commit_count": 1,+ "memories_extracted": {+ "profile": 0,+ "preferences": 0,+ "entities": 0,+ "events": 0,+ "total": 3+ },+ "llm_token_usage": {+ "prompt_tokens": 14807,+ "completion_tokens": 1087,+ "total_tokens": 15894+ },+ "embedding_token_usage": {+ "total_tokens": 831+ },+ "pending_tokens": 0,+ "total_message_count": 2,+ "user": {+ "account_id": "default",+ "user_id": "haozhe",+ "agent_id": "default"+ }+ });++ let rendered = strip_ansi(&render_session_get_for_table(&result).expect("session"));++ assert!(rendered.contains("Session"));+ assert!(rendered.contains("Identity"));+ assert!(rendered.contains("Activity"));+ assert!(rendered.contains("Memory"));+ assert!(rendered.contains("Tokens"));+ assert!(rendered.contains("d34f8a7c-eb14-49c4-b689-2743ddb9b75e"));+ assert!(rendered.contains("memories extracted"));+ assert!(rendered.contains("profile 0, preferences 0, entities 0, events 0, total 3"));+ assert!(!rendered.contains("{\"profile\":0"));+ }++ #[test]+ fn session_get_renderer_skips_non_session_objects() {+ let result = json!({"status": "ok"});++ assert!(render_session_get_for_table(&result).is_none());+ }++ fn strip_ansi(input: &str) -> String {+ let mut output = String::with_capacity(input.len());+ let mut chars = input.chars().peekable();+ while let Some(ch) = chars.next() {+ if ch == '\u{1b}' && chars.peek() == Some(&'[') {+ chars.next();+ for next in chars.by_ref() {+ if next == 'm' {+ break;+ }+ }+ } else {+ output.push(ch);+ }+ }+ output+ }}diff --git a/crates/ov_cli/src/commands/system.rs b/crates/ov_cli/src/commands/system.rsindex 6625d4f49..037cfae04 100644--- a/crates/ov_cli/src/commands/system.rs+++ b/crates/ov_cli/src/commands/system.rs@@ -50,13 +50,14 @@ pub async fn diagnostic_status(status_ui::render_status(&response, config, meta.active_name.as_deref(),)?);}- Err(_) => {+ Err(error) => {print!("{}",status_ui::render_unreachable_status(config,meta.active_name.as_deref(),meta.saved_count,+ Some(&error),));}diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rsindex d36de9ae2..af7fd1637 100644--- a/crates/ov_cli/src/config.rs+++ b/crates/ov_cli/src/config.rs@@ -195,10 +195,7 @@ impl Config {if path.exists() {Self::from_file(&path.to_string_lossy())} else {- Err(Error::Config(- "No CLI config file detected, please use `ov config` to initialize ovcli.conf"- .to_string(),- ))+ Err(Error::MissingConfig)}}@@ -266,6 +263,8 @@ pub fn get_or_create_machine_id() -> Result<String> {#[cfg(test)]mod tests {+ use crate::error::Error;+use super::{Config, merge_csv_options};#[test]@@ -274,13 +273,13 @@ mod tests {let path = dir.path().join("missing-ovcli.conf");let error = Config::load_required_from_path(&path)- .expect_err("missing required config should fail")- .to_string();+ .expect_err("missing required config should fail");- assert!(error.contains("No CLI config file detected"));- assert!(error.contains("ov config"));- assert!(!error.contains("setup-cli"));- assert!(error.contains("ovcli.conf"));+ assert!(matches!(error, Error::MissingConfig));+ let message = error.to_string();+ assert!(message.contains("No ovcli.conf detected"));+ assert!(message.contains("ov config"));+ assert!(!message.contains("setup-cli"));}#[test]@@ -427,9 +426,17 @@ mod tests {).expect("config should deserialize with extra_headers");- let headers = config.extra_headers.expect("extra_headers should be present");- assert_eq!(headers.get("X-Custom-Header"), Some(&"custom-value".to_string()));- assert_eq!(headers.get("Authorization"), Some(&"Bearer token".to_string()));+ let headers = config+ .extra_headers+ .expect("extra_headers should be present");+ assert_eq!(+ headers.get("X-Custom-Header"),+ Some(&"custom-value".to_string())+ );+ assert_eq!(+ headers.get("Authorization"),+ Some(&"Bearer token".to_string())+ );}#[test]@@ -470,8 +477,16 @@ mod tests {).expect("config should deserialize with alias");- let headers = config.extra_headers.expect("extra_headers should be present");- assert_eq!(headers.get("X-Custom-Header"), Some(&"custom-value".to_string()));- assert_eq!(headers.get("Authorization"), Some(&"Bearer token".to_string()));+ let headers = config+ .extra_headers+ .expect("extra_headers should be present");+ assert_eq!(+ headers.get("X-Custom-Header"),+ Some(&"custom-value".to_string())+ );+ assert_eq!(+ headers.get("Authorization"),+ Some(&"Bearer token".to_string())+ );}}diff --git a/crates/ov_cli/src/config_command_ui.rs b/crates/ov_cli/src/config_command_ui.rsindex c4ae8220a..b0177007b 100644--- a/crates/ov_cli/src/config_command_ui.rs+++ b/crates/ov_cli/src/config_command_ui.rs@@ -486,7 +486,7 @@ mod tests {let plain = strip_ansi(&labels.join("\n"));assert!(plain.contains("local Self-Managed [Active]"));- assert!(plain.contains("cloud-799f84 Volcengine Cloud"));+ assert!(plain.contains("cloud-799f84 VolcEngine Cloud"));assert_eq!(plain.matches("[Active]").count(), 1);assert!(!plain.contains("http://"));assert!(!plain.contains("https://"));diff --git a/crates/ov_cli/src/config_wizard/store.rs b/crates/ov_cli/src/config_wizard/store.rsindex e28773c9c..5854bdc61 100644--- a/crates/ov_cli/src/config_wizard/store.rs+++ b/crates/ov_cli/src/config_wizard/store.rs@@ -24,7 +24,7 @@ pub enum ConfigKind {impl ConfigKind {pub(crate) fn label(self) -> &'static str {match self {- Self::VolcengineCloud => "Volcengine Cloud",+ Self::VolcengineCloud => "VolcEngine Cloud",Self::SelfManaged => "Self-Managed",}}@@ -50,6 +50,7 @@ pub struct ConfigDraft {pub kind: ConfigKind,pub url: String,pub api_key: Option<String>,+ pub root_api_key: Option<String>,pub account: Option<String>,pub user: Option<String>,}@@ -346,10 +347,11 @@ pub fn build_config(draft: &ConfigDraft) -> Result<Config> {match draft.kind {ConfigKind::VolcengineCloud => {let api_key = non_empty_option(draft.api_key.as_deref()).ok_or_else(|| {- Error::Config("Volcengine Cloud configs require an API key".to_string())+ Error::Config("VolcEngine Cloud configs require an API key".to_string())})?;config.url = VOLCENGINE_CLOUD_URL.to_string();config.api_key = Some(api_key);+ config.root_api_key = None;config.account = account;config.user = user;}@@ -360,7 +362,9 @@ pub fn build_config(draft: &ConfigDraft) -> Result<Config> {"Self-managed configs require a server URL".to_string(),));}- let api_key = non_empty_option(draft.api_key.as_deref());+ let root_api_key = non_empty_option(draft.root_api_key.as_deref());+ let api_key =+ non_empty_option(draft.api_key.as_deref()).or_else(|| root_api_key.clone());if api_key.is_none() && self_managed_requires_api_key(&url) {return Err(Error::Config("Remote self-managed configs require an API key".to_string(),@@ -368,6 +372,7 @@ pub fn build_config(draft: &ConfigDraft) -> Result<Config> {}config.url = url.trim_end_matches('/').to_string();config.api_key = api_key;+ config.root_api_key = root_api_key;config.account = account;config.user = user;}@@ -507,12 +512,15 @@ fn should_run_authenticated_probe(require_api_key: bool,has_api_key: bool,) -> bool {- require_api_key- || has_api_key- || matches!(- health.get("auth_mode").and_then(Value::as_str),- Some("api_key" | "trusted")- )+ if require_api_key || has_api_key {+ return true;+ }++ match health.get("auth_mode").and_then(Value::as_str) {+ Some("dev") => false,+ Some("api_key" | "trusted") | None => true,+ Some(_) => false,+ }}pub(crate) fn validation_error_copy(kind: ConfigKind, _error: &Error) -> String {@@ -600,6 +608,11 @@ mod tests {config}+ #[test]+ fn cloud_provider_label_uses_product_casing() {+ assert_eq!(ConfigKind::VolcengineCloud.label(), "VolcEngine Cloud");+ }+fn write_config(path: &Path, config: &Config) {fs::write(path,@@ -734,6 +747,7 @@ mod tests {kind: ConfigKind::VolcengineCloud,url: String::new(),api_key: None,+ root_api_key: None,account: None,user: None,};@@ -756,6 +770,7 @@ mod tests {kind: ConfigKind::SelfManaged,url: "http://127.0.0.1:1933".to_string(),api_key: None,+ root_api_key: None,account: Some("default".to_string()),user: Some("default".to_string()),};@@ -767,6 +782,7 @@ mod tests {let with_key = build_config(&ConfigDraft {api_key: Some("local-key".to_string()),+ root_api_key: None,account: None,user: None,..draft@@ -784,6 +800,7 @@ mod tests {kind: ConfigKind::SelfManaged,url: "https://openviking.example.com".to_string(),api_key: None,+ root_api_key: None,account: Some("default".to_string()),user: Some("default".to_string()),};@@ -808,6 +825,7 @@ mod tests {kind: ConfigKind::SelfManaged,url: input.to_string(),api_key: None,+ root_api_key: None,account: Some("default".to_string()),user: Some("default".to_string()),};@@ -848,6 +866,18 @@ mod tests {assert!(matches!(error, crate::error::Error::Api(_)));}+ #[tokio::test]+ async fn local_empty_key_without_health_auth_mode_probes_status() {+ let url = spawn_status_auth_probe_server().await;+ let config = sample_config(&url, None);++ let error = validate_candidate_config(&config, false)+ .await+ .expect_err("auth-required local server should reject empty API key");++ assert!(matches!(error, crate::error::Error::Api(_)));+ }+#[test]fn authenticated_probe_runs_for_keys_or_auth_required_health_modes() {let dev_health = serde_json::json!({ "healthy": true, "auth_mode": "dev" });@@ -1022,6 +1052,37 @@ mod tests {format!("http://{addr}")}+ async fn spawn_status_auth_probe_server() -> String {+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("test server should bind");+ let addr = listener.local_addr().expect("test server should have addr");+ tokio::spawn(async move {+ for _ in 0..2 {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ let mut buffer = vec![0; 4096];+ let Ok(read) = stream.read(&mut buffer).await else {+ return;+ };+ let request = String::from_utf8_lossy(&buffer[..read]);+ let response = if request.starts_with("GET /health ") {+ http_response(200, r#"{"healthy":true}"#)+ } else if request.starts_with("GET /api/v1/system/status ") {+ http_response(+ 401,+ r#"{"error":{"code":"AuthenticationError","message":"missing key"}}"#,+ )+ } else {+ http_response(404, r#"{"error":{"message":"not found"}}"#)+ };+ let _ = stream.write_all(response.as_bytes()).await;+ }+ });+ format!("http://{addr}")+ }+async fn spawn_role_probe_server(root_api_key: &'static str,regular_api_key: &'static str,diff --git a/crates/ov_cli/src/config_wizard/wizard.rs b/crates/ov_cli/src/config_wizard/wizard.rsindex e2ad77e59..cf0ed7cc5 100644--- a/crates/ov_cli/src/config_wizard/wizard.rs+++ b/crates/ov_cli/src/config_wizard/wizard.rs@@ -41,6 +41,29 @@ enum IdentityMode {RootKey,}+#[derive(Clone, Copy, PartialEq, Eq)]+enum SelfManagedKeyMode {+ NoKey,+ UserKey,+ RootKey,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum SelfManagedEditKeyAction {+ Keep,+ SetUserKey,+ SetRootKey,+ UseRootForNormal,+ ClearRootKey,+ ClearAllKeys,+}++#[derive(Clone, Copy)]+enum IdentityField {+ Account,+ User,+}+const OV_LOGO_LINES: [&str; 14] = [""," ⢻⣶⣄",@@ -228,7 +251,7 @@ fn kind_label(kind: ConfigKind) -> &'static str {fn provider_labels(language: Language) -> [&'static str; 2] {match language {- Language::En => ["Volcengine Cloud", "Self-Managed"],+ Language::En => ["VolcEngine Cloud", "Self-Managed"],Language::ZhCn => ["火山引擎云", "自托管"],}}@@ -242,6 +265,185 @@ fn api_key_label(optional: bool) -> &'static str {}}+fn self_managed_api_key_input_label(mode: SelfManagedKeyMode) -> &'static str {+ match (Language::current(), mode) {+ (Language::En, SelfManagedKeyMode::RootKey) => "Root API key",+ (Language::En, SelfManagedKeyMode::UserKey) => "User API key",+ (Language::En, SelfManagedKeyMode::NoKey) => "API key",+ (Language::ZhCn, SelfManagedKeyMode::RootKey) => "Root API Key",+ (Language::ZhCn, SelfManagedKeyMode::UserKey) => "User API Key",+ (Language::ZhCn, SelfManagedKeyMode::NoKey) => "API Key",+ }+}++fn self_managed_api_key_input_helper_lines(mode: SelfManagedKeyMode) -> Vec<String> {+ let copy = match (Language::current(), mode) {+ (Language::En, SelfManagedKeyMode::RootKey) => {+ "For self-hosted admin setup and --sudo commands."+ }+ (Language::En, SelfManagedKeyMode::UserKey) => "For normal OpenViking commands.",+ (Language::En, SelfManagedKeyMode::NoKey) => {+ "Optional for local servers. Add one if auth is enabled."+ }+ (Language::ZhCn, SelfManagedKeyMode::RootKey) => "用于自托管管理初始化和 --sudo 命令。",+ (Language::ZhCn, SelfManagedKeyMode::UserKey) => "用于常规 OpenViking 命令。",+ (Language::ZhCn, SelfManagedKeyMode::NoKey) => "本地服务可不填;如果启用了认证,请填写。",+ };+ vec![theme::muted(copy).to_string()]+}++#[cfg(test)]+fn self_managed_key_mode_labels(allow_empty: bool) -> Vec<&'static str> {+ self_managed_key_mode_labels_for_language(allow_empty, Language::En)+}++fn self_managed_key_mode_labels_for_language(+ allow_empty: bool,+ language: Language,+) -> Vec<&'static str> {+ match (allow_empty, language) {+ (true, Language::En) => vec!["No key / local dev", "User API key", "Root API key"],+ (false, Language::En) => vec!["User API key", "Root API key"],+ (true, Language::ZhCn) => vec!["无密钥 / 本地开发", "User API Key", "Root API Key"],+ (false, Language::ZhCn) => vec!["User API Key", "Root API Key"],+ }+}++fn self_managed_key_mode_for_selection(allow_empty: bool, index: usize) -> SelfManagedKeyMode {+ match (allow_empty, index) {+ (true, 0) => SelfManagedKeyMode::NoKey,+ (true, 1) | (false, 0) => SelfManagedKeyMode::UserKey,+ _ => SelfManagedKeyMode::RootKey,+ }+}++fn edit_self_managed_key_actions(+ has_normal_user_key: bool,+ has_root_key: bool,+) -> Vec<SelfManagedEditKeyAction> {+ if !has_normal_user_key && !has_root_key {+ return vec![+ SelfManagedEditKeyAction::SetUserKey,+ SelfManagedEditKeyAction::SetRootKey,+ ];+ }++ let mut actions = vec![+ SelfManagedEditKeyAction::Keep,+ SelfManagedEditKeyAction::SetUserKey,+ SelfManagedEditKeyAction::SetRootKey,+ ];+ if has_normal_user_key && has_root_key {+ actions.push(SelfManagedEditKeyAction::UseRootForNormal);+ }+ if has_root_key {+ actions.push(SelfManagedEditKeyAction::ClearRootKey);+ }+ actions.push(SelfManagedEditKeyAction::ClearAllKeys);+ actions+}++#[cfg(test)]+fn edit_self_managed_key_action_labels(+ has_normal_user_key: bool,+ has_root_key: bool,+) -> Vec<&'static str> {+ edit_self_managed_key_actions(has_normal_user_key, has_root_key)+ .into_iter()+ .map(self_managed_edit_key_action_label)+ .collect()+}++fn self_managed_edit_key_action_label(action: SelfManagedEditKeyAction) -> &'static str {+ match (Language::current(), action) {+ (Language::En, SelfManagedEditKeyAction::Keep) => "Keep existing API keys",+ (Language::En, SelfManagedEditKeyAction::SetUserKey) => "Set normal user API key",+ (Language::En, SelfManagedEditKeyAction::SetRootKey) => "Set root API key",+ (Language::En, SelfManagedEditKeyAction::UseRootForNormal) => {+ "Use root key for normal commands"+ }+ (Language::En, SelfManagedEditKeyAction::ClearRootKey) => "Clear root API key",+ (Language::En, SelfManagedEditKeyAction::ClearAllKeys) => "Clear all API keys",+ (Language::ZhCn, SelfManagedEditKeyAction::Keep) => "保留现有 API Key",+ (Language::ZhCn, SelfManagedEditKeyAction::SetUserKey) => "设置普通用户 API Key",+ (Language::ZhCn, SelfManagedEditKeyAction::SetRootKey) => "设置 Root API Key",+ (Language::ZhCn, SelfManagedEditKeyAction::UseRootForNormal) => {+ "使用 Root Key 执行常规命令"+ }+ (Language::ZhCn, SelfManagedEditKeyAction::ClearRootKey) => "清除 Root API Key",+ (Language::ZhCn, SelfManagedEditKeyAction::ClearAllKeys) => "清除所有 API Key",+ }+}++fn root_key_redirect_labels() -> [&'static str; 3] {+ match Language::current() {+ Language::En => ["Continue as root key", "Re-enter user key", "Cancel"],+ Language::ZhCn => ["作为 Root Key 继续", "重新输入用户 Key", "取消"],+ }+}++fn root_key_redirect_helper_lines() -> Vec<String> {+ vec![+ theme::warning(copy(+ Language::current(),+ "This key has root access. Root keys are for admin and --sudo commands.",+ "此 Key 拥有 Root 权限。Root Key 用于管理和 --sudo 命令。",+ ))+ .to_string(),+ ]+}++fn user_key_redirect_labels() -> [&'static str; 3] {+ match Language::current() {+ Language::En => ["Continue as user key", "Re-enter root key", "Cancel"],+ Language::ZhCn => ["作为用户 Key 继续", "重新输入 Root Key", "取消"],+ }+}++fn user_key_redirect_helper_lines() -> Vec<String> {+ vec![+ theme::warning(copy(+ Language::current(),+ "This key does not have root access. User keys are for normal commands.",+ "此 Key 没有 Root 权限。用户 Key 用于常规命令。",+ ))+ .to_string(),+ ]+}++fn should_confirm_detected_root_key(+ kind: ConfigKind,+ key_mode: Option<SelfManagedKeyMode>,+ api_key_role: Option<ApiKeyRole>,+) -> bool {+ kind == ConfigKind::SelfManaged+ && key_mode == Some(SelfManagedKeyMode::UserKey)+ && api_key_role == Some(ApiKeyRole::Root)+}++fn should_confirm_detected_user_key(+ kind: ConfigKind,+ key_mode: Option<SelfManagedKeyMode>,+ api_key_role: Option<ApiKeyRole>,+) -> bool {+ kind == ConfigKind::SelfManaged+ && key_mode == Some(SelfManagedKeyMode::RootKey)+ && api_key_role == Some(ApiKeyRole::Regular)+}++fn has_non_empty(value: Option<&str>) -> bool {+ value.is_some_and(|value| !value.trim().is_empty())+}++fn has_normal_user_key(api_key: Option<&str>, root_api_key: Option<&str>) -> bool {+ let Some(api_key) = api_key.filter(|value| !value.trim().is_empty()) else {+ return false;+ };+ root_api_key+ .filter(|value| !value.trim().is_empty())+ .is_none_or(|root_api_key| root_api_key != api_key)+}+pub(crate) fn main_action_labels() -> [&'static str; 3] {["Add config", "Edit config", "Delete config"]}@@ -320,6 +522,55 @@ pub(crate) fn should_prompt_root_identity(&& (api_key_was_entered || is_blank(account) || is_blank(user))}+#[cfg(test)]+fn validate_account_id_value(value: &str) -> Result<()> {+ validate_identity_value(value, IdentityField::Account)+}++#[cfg(test)]+fn validate_user_id_value(value: &str) -> Result<()> {+ validate_identity_value(value, IdentityField::User)+}++fn validate_identity_value(value: &str, field: IdentityField) -> Result<()> {+ let field_name = match field {+ IdentityField::Account => "Account ID",+ IdentityField::User => "User ID",+ };+ let identifier_name = match field {+ IdentityField::Account => "account_id",+ IdentityField::User => "user_id",+ };+ let trimmed = value.trim();+ if trimmed.is_empty() {+ return Err(Error::Config(format!("{field_name} cannot be empty")));+ }+ if trimmed != value {+ return Err(Error::Config(format!(+ "{field_name} cannot start or end with whitespace"+ )));+ }+ if matches!(field, IdentityField::Account) && trimmed.starts_with('_') {+ return Err(Error::Config(+ "Account ID cannot start with '_'".to_string(),+ ));+ }+ if !trimmed+ .chars()+ .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | '@'))+ {+ return Err(Error::Config(format!(+ "{field_name} can only contain letters, numbers, '_', '-', '.', and '@'"+ )));+ }+ if trimmed.matches('@').count() > 1 {+ return Err(Error::Config(format!(+ "{identifier_name} must have at most one '@'"+ )));+ }+ Ok(())+}+fn print_header() {let lines = wizard_header_lines();println!();@@ -329,6 +580,10 @@ fn print_header() {}fn styled_wordmark_line(_index: usize, line: &str) -> String {+ styled_wordmark_line_for_color_level(line, theme::terminal_color_level())+}++fn styled_wordmark_line_for_color_level(line: &str, color_level: theme::ColorLevel) -> String {let width = wordmark_width().max(1);let mut rendered = String::new();@@ -336,13 +591,13 @@ fn styled_wordmark_line(_index: usize, line: &str) -> String {if ch.is_whitespace() {rendered.push(ch);} else {- let Rgb(red, green, blue) = wordmark_gradient_color(column, width);- rendered.push_str(- &ch.to_string()- .truecolor(red, green, blue)- .bold()- .to_string(),- );+ let rgb = header_display_rgb(wordmark_gradient_color(column, width), color_level);+ rendered.push_str(&theme::style_rgb_for_level(+ ch.to_string(),+ rgb,+ true,+ color_level,+ ));}}@@ -421,6 +676,10 @@ fn mix_rgb(base: Rgb, overlay: Rgb, amount: f32) -> Rgb {}fn styled_tagline(text: &str) -> String {+ styled_tagline_for_color_level(text, theme::terminal_color_level())+}++fn styled_tagline_for_color_level(text: &str, color_level: theme::ColorLevel) -> String {let width = display_width(text).max(1);let mut rendered = String::new();let mut column = 0usize;@@ -429,13 +688,13 @@ fn styled_tagline(text: &str) -> String {if ch.is_whitespace() {rendered.push(ch);} else {- let Rgb(red, green, blue) = tagline_texture_color(column, width);- rendered.push_str(- &ch.to_string()- .truecolor(red, green, blue)- .bold()- .to_string(),- );+ let rgb = header_display_rgb(tagline_texture_color(column, width), color_level);+ rendered.push_str(&theme::style_rgb_for_level(+ ch.to_string(),+ rgb,+ true,+ color_level,+ ));}column += UnicodeWidthChar::width(ch).unwrap_or(0);}@@ -1019,22 +1278,21 @@ fn styled_box_title_line(title: &str, width: usize) -> String {let title_width = display_width(&visible_title);let left = inner_width.saturating_sub(title_width) / 2;let right = inner_width.saturating_sub(title_width + left);- let Rgb(red, green, blue) = theme::active_theme().border.rgb_fallback();+ let border = theme::active_theme().border.rgb_fallback();format!("{}{}{}{}{}",- "╭".truecolor(red, green, blue),- "─".repeat(left).truecolor(red, green, blue),+ theme::style_rgb("╭", border, false),+ theme::style_rgb("─".repeat(left), border, false),styled_tagline(&visible_title),- "─".repeat(right).truecolor(red, green, blue),- "╮".truecolor(red, green, blue)+ theme::style_rgb("─".repeat(right), border, false),+ theme::style_rgb("╮", border, false))}fn styled_box_footer_line(title: &str, width: usize) -> String {- let Rgb(red, green, blue) = theme::active_theme().border.rgb_fallback();- let Rgb(version_red, version_green, version_blue) =- theme::active_theme().version.rgb_fallback();+ let border = theme::active_theme().border.rgb_fallback();+ let version = theme::active_theme().version.rgb_fallback();let inner_width = width.saturating_sub(2);let title = format!(" {title} ");let visible_title = truncate_to_width(&title, inner_width);@@ -1044,13 +1302,11 @@ fn styled_box_footer_line(title: &str, width: usize) -> String {format!("{}{}{}{}{}",- "╰".truecolor(red, green, blue),- "─".repeat(left).truecolor(red, green, blue),- visible_title- .truecolor(version_red, version_green, version_blue)- .bold(),- "─".repeat(right).truecolor(red, green, blue),- "╯".truecolor(red, green, blue)+ theme::style_rgb("╰", border, false),+ theme::style_rgb("─".repeat(left), border, false),+ theme::style_rgb(&visible_title, version, true),+ theme::style_rgb("─".repeat(right), border, false),+ theme::style_rgb("╯", border, false))}@@ -1063,18 +1319,27 @@ fn styled_box_content_line(let logo_width = ov_logo_width();let gutter = 3usize;let right_width = width.saturating_sub(4 + logo_width + gutter);- let Rgb(red, green, blue) = theme::active_theme().border.rgb_fallback();+ let border = theme::active_theme().border.rgb_fallback();format!("{} {}{}{} {}",- "│".truecolor(red, green, blue),+ theme::style_rgb("│", border, false),styled_logo_to_width(left, logo_width, logo_row)," ".repeat(gutter),styled_detail_to_width(detail, right_width),- "│".truecolor(red, green, blue)+ theme::style_rgb("│", border, false))}fn styled_logo_to_width(line: &str, width: usize, row: usize) -> String {+ styled_logo_to_width_for_color_level(line, width, row, theme::terminal_color_level())+}++fn styled_logo_to_width_for_color_level(+ line: &str,+ width: usize,+ row: usize,+ color_level: theme::ColorLevel,+) -> String {let mut rendered = String::new();let visible = truncate_to_width(line, width);@@ -1082,19 +1347,28 @@ fn styled_logo_to_width(line: &str, width: usize, row: usize) -> String {if ch.is_whitespace() {rendered.push(ch);} else {- let Rgb(red, green, blue) = logo_glass_color(ch, column, row, width.max(1));- rendered.push_str(- &ch.to_string()- .truecolor(red, green, blue)- .bold()- .to_string(),- );+ let rgb =+ header_display_rgb(logo_glass_color(ch, column, row, width.max(1)), color_level);+ rendered.push_str(&theme::style_rgb_for_level(+ ch.to_string(),+ rgb,+ true,+ color_level,+ ));}}rendered.push_str(&" ".repeat(width.saturating_sub(display_width(&visible))));rendered}+fn header_display_rgb(rgb: Rgb, color_level: theme::ColorLevel) -> Rgb {+ if matches!(color_level, theme::ColorLevel::TrueColor) {+ rgb+ } else {+ theme::active_theme().border.rgb_fallback()+ }+}+fn logo_glass_color(_ch: char, column: usize, row: usize, width: usize) -> Rgb {logo_glass_color_for_theme(theme::active_theme(), column, row, width)}@@ -1248,6 +1522,7 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolKind,Name,Url,+ KeyMode,ApiKey,Account,User,@@ -1259,9 +1534,11 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boollet mut name: Option<String> = None;let mut url = DEFAULT_SELF_MANAGED_URL.to_string();let mut api_key: Option<String> = None;+ let mut root_api_key: Option<String> = None;let mut account: Option<String> = None;let mut user: Option<String> = None;let mut identity_mode: Option<IdentityMode> = None;+ let mut key_mode: Option<SelfManagedKeyMode> = None;loop {match stage {@@ -1282,9 +1559,11 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolurl = VOLCENGINE_CLOUD_URL.to_string();name = None;api_key = None;+ root_api_key = None;account = None;user = None;identity_mode = None;+ key_mode = None;stage = Stage::Name;}PromptResult::Value(1) => {@@ -1292,9 +1571,11 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolurl = DEFAULT_SELF_MANAGED_URL.to_string();name = None;api_key = None;+ root_api_key = None;account = None;user = None;identity_mode = None;+ key_mode = None;stage = Stage::Name;}PromptResult::Back => return Ok(false),@@ -1317,9 +1598,11 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolPromptResult::Back => {name = None;api_key = None;+ root_api_key = None;account = None;user = None;identity_mode = None;+ key_mode = None;url = DEFAULT_SELF_MANAGED_URL.to_string();stage = Stage::Kind;}@@ -1341,7 +1624,7 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<bool)? {PromptResult::Value(value) => {url = value;- stage = Stage::ApiKey;+ stage = Stage::KeyMode;}PromptResult::Back => stage = Stage::Name,PromptResult::Quit => {@@ -1349,50 +1632,91 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolreturn Ok(true);}},+ Stage::KeyMode => {+ let allow_empty_api_key = self_managed_allows_empty_api_key(&url);+ let labels = self_managed_key_mode_labels_for_language(+ allow_empty_api_key,+ Language::current(),+ );+ match prompt_select(+ ui,+ section_add(),+ copy(Language::current(), "API key type", "API Key 类型"),+ &labels,+ 0,+ &self_managed_api_key_helper_lines(allow_empty_api_key),+ )? {+ PromptResult::Value(index) => {+ let selected =+ self_managed_key_mode_for_selection(allow_empty_api_key, index);+ key_mode = Some(selected);+ api_key = None;+ root_api_key = None;+ account = None;+ user = None;+ match selected {+ SelfManagedKeyMode::NoKey => {+ identity_mode = Some(IdentityMode::LocalNoKey);+ stage = Stage::Account;+ }+ SelfManagedKeyMode::UserKey | SelfManagedKeyMode::RootKey => {+ identity_mode = None;+ stage = Stage::ApiKey;+ }+ }+ }+ PromptResult::Back => stage = Stage::Url,+ PromptResult::Quit => {+ print_cancelled(ui)?;+ return Ok(true);+ }+ }+ }Stage::ApiKey => {let helper_lines = if kind == ConfigKind::VolcengineCloud {volcengine_api_key_helper_lines()} else {- self_managed_api_key_helper_lines(self_managed_allows_empty_api_key(&url))+ self_managed_api_key_input_helper_lines(+ key_mode.unwrap_or(SelfManagedKeyMode::UserKey),+ )};let label = if kind == ConfigKind::SelfManaged {- api_key_label(self_managed_allows_empty_api_key(&url))+ self_managed_api_key_input_label(+ key_mode.unwrap_or(SelfManagedKeyMode::UserKey),+ )} else {api_key_label(false)};- let allow_empty_api_key =- kind == ConfigKind::SelfManaged && self_managed_allows_empty_api_key(&url);match prompt_text(ui,section_add(),label,None,None,- allow_empty_api_key,+ false,true,&helper_lines,)? {PromptResult::Value(value) => {api_key = empty_to_none(value);- account = None;- user = None;- if kind == ConfigKind::SelfManaged- && api_key.is_none()- && self_managed_allows_empty_api_key(&url)+ root_api_key = if kind == ConfigKind::SelfManaged+ && key_mode == Some(SelfManagedKeyMode::RootKey){- identity_mode = Some(IdentityMode::LocalNoKey);- stage = Stage::Account;+ api_key.clone()} else {- identity_mode = None;- stage = Stage::Validate;- }+ None+ };+ account = None;+ user = None;+ identity_mode = None;+ stage = Stage::Validate;}PromptResult::Back => {stage = if kind == ConfigKind::VolcengineCloud {Stage::Name} else {- Stage::Url+ Stage::KeyMode};}PromptResult::Quit => {@@ -1407,6 +1731,7 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolui,section_add(),copy(Language::current(), "Account ID", "账户 ID"),+ IdentityField::Account,mode,)? {PromptResult::Value(value) => {@@ -1416,7 +1741,10 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolPromptResult::Back => {account = None;user = None;- stage = Stage::ApiKey;+ stage = match identity_mode {+ Some(IdentityMode::LocalNoKey) => Stage::KeyMode,+ Some(IdentityMode::RootKey) | None => Stage::ApiKey,+ };}PromptResult::Quit => {print_cancelled(ui)?;@@ -1430,6 +1758,7 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolui,section_add(),copy(Language::current(), "User ID", "用户 ID"),+ IdentityField::User,mode,)? {PromptResult::Value(value) => {@@ -1456,6 +1785,7 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolkind,url: url.clone(),api_key: api_key.clone(),+ root_api_key: root_api_key.clone(),account: account.clone(),user: user.clone(),};@@ -1463,7 +1793,83 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolOk(ValidatedConfig {config,api_key_role,+ root_api_key_role,}) => {+ if should_confirm_detected_root_key(kind, key_mode, api_key_role) {+ match prompt_select(+ ui,+ section_add(),+ copy(+ Language::current(),+ "This key has root access. Configure as root key?",+ "此 Key 拥有 Root 权限。配置为 Root Key?",+ ),+ &root_key_redirect_labels(),+ 0,+ &root_key_redirect_helper_lines(),+ )? {+ PromptResult::Value(0) => {+ key_mode = Some(SelfManagedKeyMode::RootKey);+ root_api_key = api_key.clone();+ identity_mode = Some(IdentityMode::RootKey);+ account = None;+ user = None;+ stage = Stage::Account;+ continue;+ }+ PromptResult::Value(1) | PromptResult::Back => {+ key_mode = Some(SelfManagedKeyMode::UserKey);+ root_api_key = None;+ identity_mode = None;+ stage = Stage::ApiKey;+ continue;+ }+ PromptResult::Value(_) | PromptResult::Quit => {+ print_cancelled(ui)?;+ return Ok(true);+ }+ }+ }+ let root_key_candidate_role = root_api_key_role.or(api_key_role);+ if should_confirm_detected_user_key(kind, key_mode, root_key_candidate_role)+ {+ match prompt_select(+ ui,+ section_add(),+ copy(+ Language::current(),+ "This key is a user API key. Configure as user key?",+ "此 Key 是用户 API Key。配置为用户 Key?",+ ),+ &user_key_redirect_labels(),+ 0,+ &user_key_redirect_helper_lines(),+ )? {+ PromptResult::Value(0) => {+ key_mode = Some(SelfManagedKeyMode::UserKey);+ root_api_key = None;+ identity_mode = None;+ account = None;+ user = None;+ stage = Stage::Validate;+ continue;+ }+ PromptResult::Value(1) | PromptResult::Back => {+ key_mode = Some(SelfManagedKeyMode::RootKey);+ api_key = None;+ root_api_key = None;+ identity_mode = None;+ account = None;+ user = None;+ stage = Stage::ApiKey;+ continue;+ }+ PromptResult::Value(_) | PromptResult::Quit => {+ print_cancelled(ui)?;+ return Ok(true);+ }+ }+ }if should_prompt_root_identity(api_key_role,false,@@ -1501,6 +1907,8 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolPromptResult::Back => {stage = if identity_mode.is_some() {Stage::User+ } else if kind == ConfigKind::SelfManaged {+ Stage::KeyMode} else {Stage::ApiKey};@@ -1545,14 +1953,20 @@ async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolprint_cancelled(ui)?;return Ok(true);} else {- Stage::ApiKey+ Stage::KeyMode};}PromptResult::Value(2) if kind == ConfigKind::SelfManaged => {print_cancelled(ui)?;return Ok(true);}- PromptResult::Back => stage = Stage::ApiKey,+ PromptResult::Back => {+ stage = if kind == ConfigKind::SelfManaged {+ Stage::KeyMode+ } else {+ Stage::ApiKey+ };+ }PromptResult::Value(_) => {print_cancelled(ui)?;return Ok(true);@@ -1575,6 +1989,7 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<booName,Url,ApiKeyChoice,+ KeyMode,ApiKeyInput,Account,User,@@ -1608,9 +2023,12 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolet mut kind = ConfigKind::SelfManaged;let mut url = String::new();let mut api_key: Option<String> = None;+ let mut root_api_key: Option<String> = None;let mut account: Option<String> = None;let mut user: Option<String> = None;let mut identity_mode: Option<IdentityMode> = None;+ let mut key_mode: Option<SelfManagedKeyMode> = None;+ let mut key_edit_action: Option<SelfManagedEditKeyAction> = None;let mut api_key_was_entered = false;loop {@@ -1628,9 +2046,21 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<bookind = config.kind;url = config.config.url.clone();api_key = config.config.api_key.clone();+ root_api_key = config.config.root_api_key.clone();+ if api_key.is_none() && root_api_key.is_some() {+ api_key = root_api_key.clone();+ }account = config.config.account.clone();user = config.config.user.clone();identity_mode = None;+ key_mode = if root_api_key.is_some() {+ Some(SelfManagedKeyMode::RootKey)+ } else if api_key.is_some() {+ Some(SelfManagedKeyMode::UserKey)+ } else {+ None+ };+ key_edit_action = None;api_key_was_entered = false;stage = Stage::Name;}@@ -1683,15 +2113,106 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boo}},Stage::ApiKeyChoice => {+ if kind == ConfigKind::SelfManaged {+ let has_root_key = has_non_empty(root_api_key.as_deref());+ let has_normal_user_key =+ has_normal_user_key(api_key.as_deref(), root_api_key.as_deref());+ let has_existing = has_root_key || has_normal_user_key;+ if !has_existing {+ stage = Stage::KeyMode;+ continue;+ }++ let actions = edit_self_managed_key_actions(has_normal_user_key, has_root_key);+ let labels: Vec<&str> = actions+ .iter()+ .copied()+ .map(self_managed_edit_key_action_label)+ .collect();+ match prompt_select(+ ui,+ section_edit(),+ copy(Language::current(), "API keys", "API Key"),+ &labels,+ 0,+ &self_managed_api_key_helper_lines(self_managed_allows_empty_api_key(&url)),+ )? {+ PromptResult::Value(index) => {+ let action = actions[index];+ key_edit_action = Some(action);+ api_key_was_entered = false;+ match action {+ SelfManagedEditKeyAction::Keep => {+ stage = Stage::Validate;+ }+ SelfManagedEditKeyAction::SetUserKey => {+ key_mode = Some(SelfManagedKeyMode::UserKey);+ identity_mode = None;+ stage = Stage::ApiKeyInput;+ }+ SelfManagedEditKeyAction::SetRootKey => {+ key_mode = Some(SelfManagedKeyMode::RootKey);+ identity_mode = None;+ stage = Stage::ApiKeyInput;+ }+ SelfManagedEditKeyAction::UseRootForNormal => {+ api_key = root_api_key.clone();+ key_mode = Some(SelfManagedKeyMode::RootKey);+ identity_mode = None;+ stage = Stage::Validate;+ }+ SelfManagedEditKeyAction::ClearRootKey => {+ if api_key.as_deref() == root_api_key.as_deref() {+ api_key = None;+ }+ root_api_key = None;+ key_mode = if api_key.is_some() {+ Some(SelfManagedKeyMode::UserKey)+ } else {+ None+ };+ identity_mode = None;+ stage = Stage::Validate;+ }+ SelfManagedEditKeyAction::ClearAllKeys => {+ api_key = None;+ root_api_key = None;+ key_mode = None;+ if self_managed_allows_empty_api_key(&url) {+ identity_mode = Some(IdentityMode::LocalNoKey);+ stage = Stage::Account;+ } else {+ identity_mode = None;+ stage = Stage::Validate;+ }+ }+ }+ }+ PromptResult::Back => stage = Stage::Url,+ PromptResult::Quit => {+ print_cancelled(ui)?;+ return Ok(true);+ }+ }+ continue;+ }+let helper_lines = if kind == ConfigKind::VolcengineCloud {volcengine_api_key_helper_lines()} else {self_managed_api_key_helper_lines(self_managed_allows_empty_api_key(&url))};- let has_existing = api_key.as_deref().is_some_and(|value| !value.is_empty());+ let has_existing = api_key.as_deref().is_some_and(|value| !value.is_empty())+ || root_api_key+ .as_deref()+ .is_some_and(|value| !value.is_empty());if !has_existing {- stage = Stage::ApiKeyInput;+ stage = if kind == ConfigKind::SelfManaged {+ Stage::KeyMode+ } else {+ Stage::ApiKeyInput+ };continue;}@@ -1711,9 +2232,18 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<booapi_key_was_entered = false;stage = Stage::Validate;}- PromptResult::Value(1) => stage = Stage::ApiKeyInput,+ PromptResult::Value(1) => {+ stage = if kind == ConfigKind::SelfManaged {+ Stage::KeyMode+ } else {+ Stage::ApiKeyInput+ };+ }PromptResult::Value(_) => {api_key = None;+ root_api_key = None;+ key_mode = None;+ key_edit_action = None;api_key_was_entered = false;if kind == ConfigKind::SelfManaged&& self_managed_allows_empty_api_key(&url)@@ -1738,19 +2268,64 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boo}}}+ Stage::KeyMode => {+ let allow_empty_api_key = self_managed_allows_empty_api_key(&url);+ let labels = self_managed_key_mode_labels_for_language(+ allow_empty_api_key,+ Language::current(),+ );+ match prompt_select(+ ui,+ section_edit(),+ copy(Language::current(), "API key type", "API Key 类型"),+ &labels,+ 0,+ &self_managed_api_key_helper_lines(allow_empty_api_key),+ )? {+ PromptResult::Value(index) => {+ let selected =+ self_managed_key_mode_for_selection(allow_empty_api_key, index);+ key_mode = Some(selected);+ api_key = None;+ root_api_key = None;+ key_edit_action = None;+ api_key_was_entered = false;+ match selected {+ SelfManagedKeyMode::NoKey => {+ identity_mode = Some(IdentityMode::LocalNoKey);+ stage = Stage::Account;+ }+ SelfManagedKeyMode::UserKey | SelfManagedKeyMode::RootKey => {+ identity_mode = None;+ stage = Stage::ApiKeyInput;+ }+ }+ }+ PromptResult::Back => stage = Stage::ApiKeyChoice,+ PromptResult::Quit => {+ print_cancelled(ui)?;+ return Ok(true);+ }+ }+ }Stage::ApiKeyInput => {- let has_existing = api_key.as_deref().is_some_and(|value| !value.is_empty());- let allow_empty =- kind == ConfigKind::SelfManaged && self_managed_allows_empty_api_key(&url);- let label = if allow_empty {- api_key_label(true)+ let has_existing = api_key.as_deref().is_some_and(|value| !value.is_empty())+ || root_api_key+ .as_deref()+ .is_some_and(|value| !value.is_empty());+ let label = if kind == ConfigKind::SelfManaged {+ self_managed_api_key_input_label(+ key_mode.unwrap_or(SelfManagedKeyMode::UserKey),+ )} else {api_key_label(false)};let helper_lines = if kind == ConfigKind::VolcengineCloud {volcengine_api_key_helper_lines()} else {- self_managed_api_key_helper_lines(allow_empty)+ self_managed_api_key_input_helper_lines(+ key_mode.unwrap_or(SelfManagedKeyMode::UserKey),+ )};match prompt_text(ui,@@ -1758,23 +2333,42 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolabel,api_key.as_deref(),api_key.as_deref().map(|_| InputValueLabel::Current),- allow_empty,+ false,true,&helper_lines,)? {PromptResult::Value(value) => {- api_key = empty_to_none(value);- api_key_was_entered = api_key.is_some();- if kind == ConfigKind::SelfManaged- && api_key.is_none()- && self_managed_allows_empty_api_key(&url)- {- identity_mode = Some(IdentityMode::LocalNoKey);- stage = Stage::Account;- } else {- identity_mode = None;- stage = Stage::Validate;+ let entered_key = empty_to_none(value);+ match key_edit_action {+ Some(SelfManagedEditKeyAction::SetUserKey) => {+ api_key = entered_key;+ api_key_was_entered = api_key.is_some();+ }+ Some(SelfManagedEditKeyAction::SetRootKey) => {+ let keep_normal_user_key = has_normal_user_key(+ api_key.as_deref(),+ root_api_key.as_deref(),+ );+ root_api_key = entered_key.clone();+ if !keep_normal_user_key {+ api_key = entered_key;+ }+ api_key_was_entered = root_api_key.is_some();+ }+ _ => {+ api_key = entered_key;+ root_api_key = if kind == ConfigKind::SelfManaged+ && key_mode == Some(SelfManagedKeyMode::RootKey)+ {+ api_key.clone()+ } else {+ None+ };+ api_key_was_entered = api_key.is_some();+ }}+ identity_mode = None;+ stage = Stage::Validate;}PromptResult::Back => {stage = if has_existing {@@ -1782,7 +2376,7 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boo} else if kind == ConfigKind::VolcengineCloud {Stage::Name} else {- Stage::Url+ Stage::KeyMode};}PromptResult::Quit => {@@ -1797,6 +2391,7 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<booui,section_edit(),copy(Language::current(), "Account ID", "账户 ID"),+ IdentityField::Account,mode,)? {PromptResult::Value(value) => {@@ -1804,13 +2399,12 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boostage = Stage::User;}PromptResult::Back => {- if identity_mode == Some(IdentityMode::RootKey) {- account = None;- user = None;- stage = Stage::ApiKeyInput;- } else {- stage = Stage::ApiKeyInput;- }+ account = None;+ user = None;+ stage = match identity_mode {+ Some(IdentityMode::LocalNoKey) => Stage::KeyMode,+ Some(IdentityMode::RootKey) | None => Stage::ApiKeyInput,+ };}PromptResult::Quit => {print_cancelled(ui)?;@@ -1824,6 +2418,7 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<booui,section_edit(),copy(Language::current(), "User ID", "用户 ID"),+ IdentityField::User,mode,)? {PromptResult::Value(value) => {@@ -1849,6 +2444,7 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<bookind,url: url.clone(),api_key: api_key.clone(),+ root_api_key: root_api_key.clone(),account: account.clone(),user: user.clone(),};@@ -1856,7 +2452,99 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<booOk(ValidatedConfig {config,api_key_role,+ root_api_key_role,}) => {+ if should_confirm_detected_root_key(kind, key_mode, api_key_role) {+ match prompt_select(+ ui,+ section_edit(),+ copy(+ Language::current(),+ "This key has root access. Configure as root key?",+ "此 Key 拥有 Root 权限。配置为 Root Key?",+ ),+ &root_key_redirect_labels(),+ 0,+ &root_key_redirect_helper_lines(),+ )? {+ PromptResult::Value(0) => {+ key_mode = Some(SelfManagedKeyMode::RootKey);+ key_edit_action = Some(SelfManagedEditKeyAction::SetRootKey);+ root_api_key = api_key.clone();+ identity_mode = Some(IdentityMode::RootKey);+ account = None;+ user = None;+ stage = Stage::Account;+ continue;+ }+ PromptResult::Value(1) | PromptResult::Back => {+ key_mode = Some(SelfManagedKeyMode::UserKey);+ api_key = None;+ identity_mode = None;+ stage = Stage::ApiKeyInput;+ continue;+ }+ PromptResult::Value(_) | PromptResult::Quit => {+ print_cancelled(ui)?;+ return Ok(true);+ }+ }+ }+ let root_key_candidate_role = root_api_key_role.or(api_key_role);+ if should_confirm_detected_user_key(kind, key_mode, root_key_candidate_role)+ {+ match prompt_select(+ ui,+ section_edit(),+ copy(+ Language::current(),+ "This key is a user API key. Configure as user key?",+ "此 Key 是用户 API Key。配置为用户 Key?",+ ),+ &user_key_redirect_labels(),+ 0,+ &user_key_redirect_helper_lines(),+ )? {+ PromptResult::Value(0) => {+ let entered_user_key = root_api_key.clone().or(api_key.clone());+ api_key = entered_user_key;+ root_api_key = configs[selected]+ .config+ .root_api_key+ .clone()+ .filter(|existing_root_key| {+ api_key.as_deref() != Some(existing_root_key.as_str())+ && !existing_root_key.trim().is_empty()+ });+ key_mode = Some(SelfManagedKeyMode::UserKey);+ key_edit_action = Some(SelfManagedEditKeyAction::SetUserKey);+ api_key_was_entered = api_key.is_some();+ identity_mode = None;+ account = None;+ user = None;+ stage = Stage::Validate;+ continue;+ }+ PromptResult::Value(1) | PromptResult::Back => {+ key_mode = Some(SelfManagedKeyMode::RootKey);+ key_edit_action = Some(SelfManagedEditKeyAction::SetRootKey);+ if api_key.as_deref() == root_api_key.as_deref() {+ api_key = None;+ }+ root_api_key = None;+ api_key_was_entered = false;+ identity_mode = None;+ account = None;+ user = None;+ stage = Stage::ApiKeyInput;+ continue;+ }+ PromptResult::Value(_) | PromptResult::Quit => {+ print_cancelled(ui)?;+ return Ok(true);+ }+ }+ }if should_prompt_root_identity(api_key_role,api_key_was_entered,@@ -1890,14 +2578,14 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<booui.clear()?;let original = configs[selected].name.clone();store.save_edited_config(&original, &name, &config)?;- print_saved(store, &name, SaveOutcome::UpdatedActive)?;+ print_saved(store, &name, SaveOutcome::UpdatedActive, &config)?;return Ok(true);}PromptResult::Value(SaveAction::SaveOnly) => {ui.clear()?;let original = configs[selected].name.clone();store.save_edited_config(&original, &name, &config)?;- print_saved(store, &name, SaveOutcome::SavedOnly)?;+ print_saved(store, &name, SaveOutcome::SavedOnly, &config)?;return Ok(true);}PromptResult::Value(SaveAction::SaveAndActivate) => {@@ -1905,7 +2593,7 @@ async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<boolet original = configs[selected].name.clone();store.save_edited_config(&original, &name, &config)?;store.activate_config(&name)?;- print_saved(store, &name, SaveOutcome::Activated)?;+ print_saved(store, &name, SaveOutcome::Activated, &config)?;return Ok(true);}PromptResult::Value(SaveAction::Cancel) => {@@ -2093,6 +2781,7 @@ fn run_delete_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<bool> {struct ValidatedConfig {config: Config,api_key_role: Option<ApiKeyRole>,+ root_api_key_role: Option<ApiKeyRole>,}async fn validate_draft(@@ -2112,16 +2801,29 @@ async fn validate_draft("正在验证连接...",),))?;+ let mut root_api_key_role = None;let api_key_role = if config.api_key.as_deref().is_some_and(|key| !key.trim().is_empty()){+ let configured_root_api_key = config+ .root_api_key+ .as_deref()+ .filter(|key| !key.trim().is_empty())+ .map(str::to_string);let mut detection_config = config.clone();detection_config.account = None;detection_config.user = None;let role = validate_candidate_config_with_role(&detection_config, require_api_key).await?;+ if config.root_api_key.as_deref() == config.api_key.as_deref() {+ root_api_key_role = role;+ }if role == Some(ApiKeyRole::Root) {+ if configured_root_api_key.is_none() {+ config.root_api_key = config.api_key.clone();+ root_api_key_role = role;+ }let has_identity = config.account.as_deref()@@ -2134,6 +2836,19 @@ async fn validate_draft(validate_candidate_config(&config, require_api_key).await?;}} else {+ if let Some(root_api_key) = configured_root_api_key.as_deref() {+ if config.api_key.as_deref() == Some(root_api_key) {+ config.root_api_key = None;+ root_api_key_role = role;+ } else {+ root_api_key_role = Some(+ validate_root_api_key_role(&config, root_api_key, require_api_key).await?,+ );+ if root_api_key_role != Some(ApiKeyRole::Root) {+ config.root_api_key = None;+ }+ }+ }config.account = None;config.user = None;}@@ -2145,20 +2860,45 @@ async fn validate_draft(Ok(ValidatedConfig {config,api_key_role,+ root_api_key_role,})}+async fn validate_root_api_key_role(+ config: &Config,+ root_api_key: &str,+ require_api_key: bool,+) -> Result<ApiKeyRole> {+ let mut root_config = config.clone();+ root_config.api_key = Some(root_api_key.to_string());+ root_config.root_api_key = Some(root_api_key.to_string());+ root_config.account = None;+ root_config.user = None;++ match validate_candidate_config_with_role(&root_config, require_api_key).await? {+ Some(role) => Ok(role),+ None => Err(Error::Config(+ "Expected a root API key, but the server rejected root access.".to_string(),+ )),+ }+}+fn save_config(store: &ConfigStore, name: &str, config: &Config, activate: bool) -> Result<()> {if activate {store.save_and_activate(name, config)?;- print_saved(store, name, SaveOutcome::Activated)+ print_saved(store, name, SaveOutcome::Activated, config)} else {store.save_named_config(name, config)?;- print_saved(store, name, SaveOutcome::SavedOnly)+ print_saved(store, name, SaveOutcome::SavedOnly, config)}}-fn print_saved(store: &ConfigStore, name: &str, outcome: SaveOutcome) -> Result<()> {+fn print_saved(+ store: &ConfigStore,+ name: &str,+ outcome: SaveOutcome,+ config: &Config,+) -> Result<()> {println!();let message = match outcome {SaveOutcome::Activated => saved_message_activated(name),@@ -2191,6 +2931,9 @@ fn print_saved(store: &ConfigStore, name: &str, outcome: SaveOutcome) -> Result<);}}+ for line in root_key_normal_command_notice_lines(config) {+ println!("{line}");+ }println!("{} {}",theme::muted(copy(Language::current(), "Next:", "下一步:")),@@ -2199,10 +2942,109 @@ fn print_saved(store: &ConfigStore, name: &str, outcome: SaveOutcome) -> Result<Ok(())}+fn root_key_normal_command_notice_lines(config: &Config) -> Vec<String> {+ if !root_key_used_for_normal_commands(config) {+ return Vec::new();+ }++ vec![+ root_key_configured_notice(),+ normal_commands_root_key_notice(),+ least_privilege_user_key_notice(),+ ]+}++fn root_key_configured_notice() -> String {+ match Language::current() {+ Language::En => format!(+ "{}{}",+ theme::warning("Root key").bold(),+ theme::body(" configured.")+ ),+ Language::ZhCn => format!(+ "{}{}",+ theme::warning("Root Key").bold(),+ theme::body(" 已配置。")+ ),+ }+}++fn normal_commands_root_key_notice() -> String {+ match Language::current() {+ Language::En => format!(+ "{}{}{}{}",+ theme::strong("Normal commands"),+ theme::body(" will use this key until you set a "),+ theme::warning("separate user API key").bold(),+ theme::body("."),+ ),+ Language::ZhCn => format!(+ "{}{}{}{}{}",+ theme::body("在设置"),+ theme::warning("单独的用户 API Key").bold(),+ theme::body("前,"),+ theme::strong("常规命令"),+ theme::body("会使用此 Key。"),+ ),+ }+}++fn least_privilege_user_key_notice() -> String {+ match Language::current() {+ Language::En => format!(+ "{}{}{}{}{}{}{}{}{}",+ theme::body("For "),+ theme::warning("least privilege").bold(),+ theme::body(", run "),+ theme::command("ov config").bold(),+ theme::body(" -> "),+ theme::strong("Edit config"),+ theme::body(" -> "),+ theme::strong("Set normal user API key"),+ theme::body("."),+ ),+ Language::ZhCn => format!(+ "{}{}{}{}{}{}{}",+ theme::body("为遵循最小权限原则,请运行 "),+ theme::command("ov config").bold(),+ theme::body(" -> "),+ theme::strong("Edit config"),+ theme::body(" -> "),+ theme::strong("Set normal user API key"),+ theme::body("。"),+ ),+ }+}++fn root_key_used_for_normal_commands(config: &Config) -> bool {+ if ConfigKind::from_config(config) != ConfigKind::SelfManaged {+ return false;+ }++ let Some(api_key) = config.api_key.as_deref().map(str::trim) else {+ return false;+ };+ let Some(root_api_key) = config.root_api_key.as_deref().map(str::trim) else {+ return false;+ };++ !api_key.is_empty() && api_key == root_api_key+}+fn next_step_copy() -> String {match Language::current() {- Language::En => format!("Run {} to get started.", theme::command("ov --help").bold()),- Language::ZhCn => format!("运行 {} 查看可用命令。", theme::command("ov --help").bold()),+ Language::En => format!(+ "{}{}{}",+ theme::body("Run "),+ theme::command("ov --help").bold(),+ theme::body(" to get started.")+ ),+ Language::ZhCn => format!(+ "{}{}{}",+ theme::body("运行 "),+ theme::command("ov --help").bold(),+ theme::body(" 查看可用命令。")+ ),}}@@ -2364,19 +3206,34 @@ fn prompt_identity_value(ui: &mut LiveRegion,section: &str,prompt: &str,+ field: IdentityField,mode: IdentityMode,) -> Result<PromptResult<String>> {let (default, value_label, helper_lines) = identity_prompt_parts(mode);- prompt_text(- ui,- section,- prompt,- default,- value_label,- false,- false,- &helper_lines,- )+ let mut error: Option<String> = None;+ loop {+ let mut lines = helper_lines.clone();+ if let Some(value) = error.as_ref() {+ lines.push(theme::error(value).to_string());+ }+ match prompt_text(+ ui,+ section,+ prompt,+ default,+ value_label,+ false,+ false,+ &lines,+ )? {+ PromptResult::Value(value) => match validate_identity_value(&value, field) {+ Ok(()) => return Ok(PromptResult::Value(value)),+ Err(next_error) => error = Some(next_error.to_string()),+ },+ PromptResult::Back => return Ok(PromptResult::Back),+ PromptResult::Quit => return Ok(PromptResult::Quit),+ }+ }}fn identity_prompt_parts(@@ -2961,27 +3818,37 @@ impl Drop for RawPrompt {#[cfg(test)]mod tests {use super::{- IdentityMode, InputValueLabel, OV_LOGO_LINES, Rgb, StatusBoxRuntime,+ IdentityMode, InputValueLabel, OV_LOGO_LINES, Rgb, SelfManagedKeyMode, StatusBoxRuntime,active_delete_block_helper_lines, active_summary_lines, active_summary_render_parts,add_config_name_label, add_save_action_labels, allocate_config_name, box_content_line,box_footer_line, box_title_line, cloud_validation_failure_choices, config_select_label,display_config_home, display_width, edit_api_key_choice_labels, edit_save_action_labels,- erase_sequence_for_char, extract_models_from_status_payload, identity_prompt_parts,- input_live_lines, logo_glass_color_for_theme, main_action_labels, next_step_copy,- ov_logo_width, saved_summary_render_parts, select_live_lines,- self_managed_api_key_helper_lines, self_managed_validation_failure_choices,+ edit_self_managed_key_action_labels, erase_sequence_for_char,+ extract_models_from_status_payload, identity_prompt_parts, input_live_lines,+ logo_glass_color_for_theme, main_action_labels, next_step_copy, ov_logo_width,+ root_key_normal_command_notice_lines, root_key_redirect_labels, saved_summary_render_parts,+ select_live_lines, self_managed_api_key_helper_lines,+ self_managed_api_key_input_helper_lines, self_managed_key_mode_labels,+ self_managed_validation_failure_choices, should_confirm_detected_user_key,should_prompt_root_identity, status_box_lines, status_box_lines_with_runtime,- status_box_width, status_payload_is_healthy, tagline_ice_color_for_theme,- validate_config_name, volcengine_api_key_helper_lines, wizard_header_lines,+ status_box_width, status_payload_is_healthy, styled_logo_to_width_for_color_level,+ styled_wordmark_line_for_color_level, tagline_ice_color_for_theme,+ user_key_redirect_labels, validate_account_id_value, validate_config_name, validate_draft,+ validate_user_id_value, volcengine_api_key_helper_lines, wizard_header_lines,wordmark_gradient_color_for_theme, wordmark_lines, wordmark_width,};use crate::config::Config;- use crate::config_wizard::store::{ApiKeyRole, ConfigEntry, ConfigKind, ConfigStore};+ use crate::config_wizard::store::{+ ApiKeyRole, ConfigDraft, ConfigEntry, ConfigKind, ConfigStore,+ };use crate::theme::{self, ThemeColor};+ use colored::Colorize;use serde_json::json;use std::fs;use std::path::PathBuf;use std::time::{SystemTime, UNIX_EPOCH};+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ use tokio::net::TcpListener;fn unique_dir(name: &str) -> PathBuf {let suffix = SystemTime::now()@@ -2991,6 +3858,26 @@ mod tests {std::env::temp_dir().join(format!("openviking-wizard-{name}-{suffix}"))}+ fn strip_ansi(input: &str) -> String {+ let mut output = String::new();+ let mut chars = input.chars().peekable();++ while let Some(ch) = chars.next() {+ if ch == '\u{1b}' && chars.peek() == Some(&'[') {+ chars.next();+ for next in chars.by_ref() {+ if next.is_ascii_alphabetic() {+ break;+ }+ }+ } else {+ output.push(ch);+ }+ }++ output+ }+#[test]fn wizard_header_is_scrollback_branded() {let header = wizard_header_lines().join("\n");@@ -3376,6 +4263,30 @@ mod tests {);}+ #[test]+ fn wordmark_uses_stable_teal_ansi256_fallback_when_truecolor_is_unavailable() {+ let rendered =+ styled_wordmark_line_for_color_level(wordmark_lines()[0], theme::ColorLevel::Ansi256);++ assert!(rendered.contains("\u{1b}[1;38;5;"));+ assert!(!rendered.contains("38;2;"));+ assert_eq!(ansi256_indexes(&rendered), vec![30]);+ }++ #[test]+ fn logo_uses_stable_teal_ansi256_fallback_when_truecolor_is_unavailable() {+ let rendered = styled_logo_to_width_for_color_level(+ OV_LOGO_LINES[8],+ ov_logo_width(),+ 8,+ theme::ColorLevel::Ansi256,+ );++ assert!(rendered.contains("\u{1b}[1;38;5;"));+ assert!(!rendered.contains("38;2;"));+ assert_eq!(ansi256_indexes(&rendered), vec![30]);+ }+#[test]fn tagline_ice_color_runs_pearl_jade() {let width = display_width("Context Database for AI Agents");@@ -3395,6 +4306,25 @@ mod tests {);}+ fn ansi256_indexes(rendered: &str) -> Vec<u8> {+ let mut indexes = Vec::new();+ let mut rest = rendered;+ while let Some(start) = rest.find("38;5;") {+ let value_start = start + "38;5;".len();+ let digits: String = rest[value_start..]+ .chars()+ .take_while(|ch| ch.is_ascii_digit())+ .collect();+ if let Ok(index) = digits.parse::<u8>()+ && !indexes.contains(&index)+ {+ indexes.push(index);+ }+ rest = &rest[value_start..];+ }+ indexes+ }+#[test]fn status_box_border_uses_pearl_jade() {assert_eq!(@@ -3563,6 +4493,31 @@ mod tests {);}+ #[test]+ fn self_managed_key_mode_choices_distinguish_no_key_user_key_and_root_key() {+ assert_eq!(+ self_managed_key_mode_labels(true),+ ["No key / local dev", "User API key", "Root API key"]+ );+ assert_eq!(+ self_managed_key_mode_labels(false),+ ["User API key", "Root API key"]+ );+ }++ #[test]+ fn self_managed_key_input_copy_explains_storage_target() {+ let user_key = self_managed_api_key_input_helper_lines(SelfManagedKeyMode::UserKey);+ let root_key = self_managed_api_key_input_helper_lines(SelfManagedKeyMode::RootKey);++ assert!(user_key.iter().any(|line| line.contains("normal")));+ assert!(!user_key.iter().any(|line| line.contains("api_key")));+ assert!(!root_key.iter().any(|line| line.contains("root_api_key")));+ assert!(!root_key.iter().any(|line| line.contains("api_key")));+ assert!(root_key.iter().any(|line| line.contains("--sudo")));+ assert!(!root_key.iter().any(|line| line.contains("remote")));+ }+#[test]fn add_self_managed_api_key_rendering_has_no_existing_value_placeholder() {let lines = input_live_lines(@@ -3690,6 +4645,87 @@ mod tests {assert!(next_step_copy().contains("get started"));}+ #[test]+ fn root_key_notice_points_to_edit_flow_when_root_key_is_reused() {+ let config = Config {+ api_key: Some("root-key".to_string()),+ root_api_key: Some("root-key".to_string()),+ ..Config::default()+ };++ let text = strip_ansi(&root_key_normal_command_notice_lines(&config).join("\n"));++ assert!(text.contains("Root key configured."));+ assert!(text.contains("Normal commands will use this key"));+ assert!(text.contains("ov config -> Edit config -> Set normal user API key"));+ }++ #[test]+ fn root_key_notice_styles_sentence_text_with_body_color() {+ colored::control::set_override(true);+ let config = Config {+ api_key: Some("root-key".to_string()),+ root_api_key: Some("root-key".to_string()),+ ..Config::default()+ };+ let expected = vec![+ format!(+ "{}{}",+ theme::warning("Root key").bold(),+ theme::body(" configured.")+ ),+ format!(+ "{}{}{}{}",+ theme::strong("Normal commands"),+ theme::body(" will use this key until you set a "),+ theme::warning("separate user API key").bold(),+ theme::body(".")+ ),+ format!(+ "{}{}{}{}{}{}{}{}{}",+ theme::body("For "),+ theme::warning("least privilege").bold(),+ theme::body(", run "),+ theme::command("ov config").bold(),+ theme::body(" -> "),+ theme::strong("Edit config"),+ theme::body(" -> "),+ theme::strong("Set normal user API key"),+ theme::body(".")+ ),+ ];+ let lines = root_key_normal_command_notice_lines(&config);+ colored::control::unset_override();++ assert_eq!(lines, expected);+ }++ #[test]+ fn next_step_copy_styles_sentence_text_with_body_color() {+ colored::control::set_override(true);+ let expected = format!(+ "{}{}{}",+ theme::body("Run "),+ theme::command("ov --help").bold(),+ theme::body(" to get started.")+ );+ let rendered = next_step_copy();+ colored::control::unset_override();++ assert_eq!(rendered, expected);+ }++ #[test]+ fn root_key_notice_is_hidden_for_separate_user_key() {+ let config = Config {+ api_key: Some("user-key".to_string()),+ root_api_key: Some("root-key".to_string()),+ ..Config::default()+ };++ assert!(root_key_normal_command_notice_lines(&config).is_empty());+ }+#[test]fn edit_api_key_choices_match_kind_and_existing_key_state() {assert!(edit_api_key_choice_labels(ConfigKind::SelfManaged, false).is_empty());@@ -3704,6 +4740,86 @@ mod tests {);}+ #[test]+ fn edit_self_managed_key_actions_preserve_separate_credential_roles() {+ assert_eq!(+ edit_self_managed_key_action_labels(false, false),+ ["Set normal user API key", "Set root API key"]+ );+ assert_eq!(+ edit_self_managed_key_action_labels(true, true),+ [+ "Keep existing API keys",+ "Set normal user API key",+ "Set root API key",+ "Use root key for normal commands",+ "Clear root API key",+ "Clear all API keys"+ ]+ );+ assert_eq!(+ edit_self_managed_key_action_labels(true, false),+ [+ "Keep existing API keys",+ "Set normal user API key",+ "Set root API key",+ "Clear all API keys"+ ]+ );+ }++ #[test]+ fn root_key_redirect_copy_is_outcome_based() {+ assert_eq!(+ root_key_redirect_labels(),+ ["Continue as root key", "Re-enter user key", "Cancel"]+ );+ }++ #[test]+ fn user_key_redirect_copy_is_outcome_based() {+ assert_eq!(+ user_key_redirect_labels(),+ ["Continue as user key", "Re-enter root key", "Cancel"]+ );+ }++ #[test]+ fn root_key_route_detects_regular_user_key() {+ assert!(should_confirm_detected_user_key(+ ConfigKind::SelfManaged,+ Some(SelfManagedKeyMode::RootKey),+ Some(ApiKeyRole::Regular),+ ));+ assert!(!should_confirm_detected_user_key(+ ConfigKind::SelfManaged,+ Some(SelfManagedKeyMode::UserKey),+ Some(ApiKeyRole::Regular),+ ));+ assert!(!should_confirm_detected_user_key(+ ConfigKind::SelfManaged,+ Some(SelfManagedKeyMode::RootKey),+ Some(ApiKeyRole::Root),+ ));+ assert!(!should_confirm_detected_user_key(+ ConfigKind::VolcengineCloud,+ Some(SelfManagedKeyMode::RootKey),+ Some(ApiKeyRole::Regular),+ ));+ }++ #[test]+ fn identity_validation_rejects_spaces_before_server_validation() {+ assert!(validate_user_id_value("alice").is_ok());+ assert!(validate_user_id_value("[email protected]").is_ok());+ let error = validate_user_id_value("alice smith").expect_err("spaces should be rejected");+ assert_eq!(+ error.to_string(),+ "Configuration error: User ID can only contain letters, numbers, '_', '-', '.', and '@'"+ );+ assert!(validate_account_id_value("_system").is_err());+ }+#[test]fn replaced_root_key_requires_identity_confirmation() {assert!(should_prompt_root_identity(@@ -3732,6 +4848,275 @@ mod tests {));}+ #[tokio::test]+ async fn validated_root_key_config_populates_root_api_key_for_sudo() {+ let url = spawn_root_probe_server("root-key").await;+ let draft = ConfigDraft {+ name: "local".to_string(),+ kind: ConfigKind::SelfManaged,+ url,+ api_key: Some("root-key".to_string()),+ root_api_key: None,+ account: Some("admin".to_string()),+ user: Some("default".to_string()),+ };+ let mut ui = super::LiveRegion::default();++ let validated = validate_draft(&mut ui, "test", &draft)+ .await+ .expect("root key should validate");++ assert_eq!(validated.api_key_role, Some(ApiKeyRole::Root));+ assert_eq!(validated.config.api_key.as_deref(), Some("root-key"));+ assert_eq!(validated.config.root_api_key.as_deref(), Some("root-key"));+ }++ #[tokio::test]+ async fn validated_user_key_config_preserves_separate_root_api_key_for_sudo() {+ let url = spawn_dual_key_probe_server("user-key", "root-key").await;+ let draft = ConfigDraft {+ name: "local".to_string(),+ kind: ConfigKind::SelfManaged,+ url,+ api_key: Some("user-key".to_string()),+ root_api_key: Some("root-key".to_string()),+ account: Some("admin".to_string()),+ user: Some("default".to_string()),+ };+ let mut ui = super::LiveRegion::default();++ let validated = validate_draft(&mut ui, "test", &draft)+ .await+ .expect("separate user and root keys should validate");++ assert_eq!(validated.api_key_role, Some(ApiKeyRole::Regular));+ assert_eq!(validated.config.api_key.as_deref(), Some("user-key"));+ assert_eq!(validated.config.root_api_key.as_deref(), Some("root-key"));+ assert_eq!(validated.config.account, None);+ assert_eq!(validated.config.user, None);+ }++ #[tokio::test]+ async fn selected_root_key_regular_user_key_returns_regular_role_without_root_key() {+ let url = spawn_dual_key_probe_server("user-key", "root-key").await;+ let draft = ConfigDraft {+ name: "local".to_string(),+ kind: ConfigKind::SelfManaged,+ url,+ api_key: Some("user-key".to_string()),+ root_api_key: Some("user-key".to_string()),+ account: None,+ user: None,+ };+ let mut ui = super::LiveRegion::default();++ let validated = validate_draft(&mut ui, "test", &draft)+ .await+ .expect("regular key should validate so the wizard can redirect");++ assert_eq!(validated.api_key_role, Some(ApiKeyRole::Regular));+ assert_eq!(validated.config.api_key.as_deref(), Some("user-key"));+ assert_eq!(validated.config.root_api_key, None);+ assert_eq!(validated.config.account, None);+ assert_eq!(validated.config.user, None);+ }++ #[tokio::test]+ async fn separate_root_key_candidate_regular_user_key_returns_regular_root_candidate_role() {+ let url =+ spawn_two_user_key_probe_server("existing-user-key", "entered-user-key", "root-key")+ .await;+ let draft = ConfigDraft {+ name: "local".to_string(),+ kind: ConfigKind::SelfManaged,+ url,+ api_key: Some("existing-user-key".to_string()),+ root_api_key: Some("entered-user-key".to_string()),+ account: None,+ user: None,+ };+ let mut ui = super::LiveRegion::default();++ let validated = validate_draft(&mut ui, "test", &draft)+ .await+ .expect("regular root-key candidate should validate so the wizard can redirect");++ assert_eq!(validated.api_key_role, Some(ApiKeyRole::Regular));+ assert_eq!(validated.root_api_key_role, Some(ApiKeyRole::Regular));+ assert_eq!(+ validated.config.api_key.as_deref(),+ Some("existing-user-key")+ );+ assert_eq!(validated.config.root_api_key, None);+ }++ async fn spawn_root_probe_server(root_api_key: &'static str) -> String {+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("test server should bind");+ let addr = listener.local_addr().expect("test server should have addr");+ tokio::spawn(async move {+ for _ in 0..6 {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ let mut buffer = vec![0; 4096];+ let Ok(read) = stream.read(&mut buffer).await else {+ return;+ };+ let request = String::from_utf8_lossy(&buffer[..read]);+ let lower_request = request.to_ascii_lowercase();+ let root_header = format!("x-api-key: {root_api_key}");+ let response = if request.starts_with("GET /health ") {+ http_response(200, r#"{"healthy":true,"auth_mode":"api_key"}"#)+ } else if request.starts_with("GET /api/v1/system/status ") {+ if lower_request.contains(&root_header) {+ http_response(200, r#"{"status":"ok","result":{"initialized":true}}"#)+ } else {+ http_response(+ 401,+ r#"{"error":{"code":"AuthenticationError","message":"invalid key"}}"#,+ )+ }+ } else if request.starts_with("GET /api/v1/admin/accounts ") {+ if lower_request.contains(&root_header) {+ http_response(200, r#"{"accounts":[]}"#)+ } else {+ http_response(+ 403,+ r#"{"error":{"code":"PermissionDenied","message":"root required"}}"#,+ )+ }+ } else {+ http_response(404, r#"{"error":{"message":"not found"}}"#)+ };+ let _ = stream.write_all(response.as_bytes()).await;+ }+ });+ format!("http://{addr}")+ }++ async fn spawn_dual_key_probe_server(+ user_api_key: &'static str,+ root_api_key: &'static str,+ ) -> String {+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("test server should bind");+ let addr = listener.local_addr().expect("test server should have addr");+ tokio::spawn(async move {+ for _ in 0..12 {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ let mut buffer = vec![0; 4096];+ let Ok(read) = stream.read(&mut buffer).await else {+ return;+ };+ let request = String::from_utf8_lossy(&buffer[..read]);+ let lower_request = request.to_ascii_lowercase();+ let user_header = format!("x-api-key: {user_api_key}");+ let root_header = format!("x-api-key: {root_api_key}");+ let has_user_key = lower_request.contains(&user_header);+ let has_root_key = lower_request.contains(&root_header);+ let response = if request.starts_with("GET /health ") {+ http_response(200, r#"{"healthy":true,"auth_mode":"api_key"}"#)+ } else if request.starts_with("GET /api/v1/system/status ") {+ if has_user_key || has_root_key {+ http_response(200, r#"{"status":"ok","result":{"initialized":true}}"#)+ } else {+ http_response(+ 401,+ r#"{"error":{"code":"AuthenticationError","message":"invalid key"}}"#,+ )+ }+ } else if request.starts_with("GET /api/v1/admin/accounts ") {+ if has_root_key {+ http_response(200, r#"{"accounts":[]}"#)+ } else {+ http_response(+ 403,+ r#"{"error":{"code":"PermissionDenied","message":"root required"}}"#,+ )+ }+ } else {+ http_response(404, r#"{"error":{"message":"not found"}}"#)+ };+ let _ = stream.write_all(response.as_bytes()).await;+ }+ });+ format!("http://{addr}")+ }++ async fn spawn_two_user_key_probe_server(+ first_user_api_key: &'static str,+ second_user_api_key: &'static str,+ root_api_key: &'static str,+ ) -> String {+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("test server should bind");+ let addr = listener.local_addr().expect("test server should have addr");+ tokio::spawn(async move {+ for _ in 0..12 {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ let mut buffer = vec![0; 4096];+ let Ok(read) = stream.read(&mut buffer).await else {+ return;+ };+ let request = String::from_utf8_lossy(&buffer[..read]);+ let lower_request = request.to_ascii_lowercase();+ let first_user_header = format!("x-api-key: {first_user_api_key}");+ let second_user_header = format!("x-api-key: {second_user_api_key}");+ let root_header = format!("x-api-key: {root_api_key}");+ let has_regular_key = lower_request.contains(&first_user_header)+ || lower_request.contains(&second_user_header);+ let has_root_key = lower_request.contains(&root_header);+ let response = if request.starts_with("GET /health ") {+ http_response(200, r#"{"healthy":true,"auth_mode":"api_key"}"#)+ } else if request.starts_with("GET /api/v1/system/status ") {+ if has_regular_key || has_root_key {+ http_response(200, r#"{"status":"ok","result":{"initialized":true}}"#)+ } else {+ http_response(+ 401,+ r#"{"error":{"code":"AuthenticationError","message":"invalid key"}}"#,+ )+ }+ } else if request.starts_with("GET /api/v1/admin/accounts ") {+ if has_root_key {+ http_response(200, r#"{"accounts":[]}"#)+ } else {+ http_response(+ 403,+ r#"{"error":{"code":"PermissionDenied","message":"root required"}}"#,+ )+ }+ } else {+ http_response(404, r#"{"error":{"message":"not found"}}"#)+ };+ let _ = stream.write_all(response.as_bytes()).await;+ }+ });+ format!("http://{addr}")+ }++ fn http_response(status: u16, body: &str) -> String {+ let reason = match status {+ 200 => "OK",+ 401 => "Unauthorized",+ 403 => "Forbidden",+ 404 => "Not Found",+ _ => "Error",+ };+ format!(+ "HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",+ body.len()+ )+ }+#[test]fn live_select_lines_are_current_step_only() {let lines = select_live_lines(diff --git a/crates/ov_cli/src/error.rs b/crates/ov_cli/src/error.rsindex 02b29a256..05303364c 100644--- a/crates/ov_cli/src/error.rs+++ b/crates/ov_cli/src/error.rs@@ -2,9 +2,15 @@ use thiserror::Error;#[derive(Error, Debug)]pub enum Error {+ #[error("No ovcli.conf detected. Run ov config to create one before using server commands.")]+ MissingConfig,+#[error("Configuration error: {0}")]Config(String),+ #[error("Language error: {0}")]+ Language(String),+#[error("Network error: {0}")]Network(String),diff --git a/crates/ov_cli/src/error_ui.rs b/crates/ov_cli/src/error_ui.rsindex 1ec8b9b93..6aad4af54 100644--- a/crates/ov_cli/src/error_ui.rs+++ b/crates/ov_cli/src/error_ui.rs@@ -128,15 +128,21 @@ pub(crate) fn report_for_clap_error(args: &[OsString], clap_output: &str) -> Errcopy(language, "Run the suggested command", "运行建议的命令"),));}- actions.push(ErrorAction::new(- "ov --help",- copy(language, "Show all commands", "查看所有命令"),- ));+ let help_command = usage+ .as_deref()+ .and_then(help_command_from_usage)+ .unwrap_or_else(|| "ov --help".to_string());+ let help_description = if help_command == "ov --help" {+ copy(language, "Show all commands", "查看所有命令")+ } else {+ copy(language, "Show this command's help", "查看此命令帮助")+ };+ actions.push(ErrorAction::new(help_command, help_description));let message = unknown.map(|value| match language {- Language::En => format!("Unknown command: {value}"),- Language::ZhCn => format!("未知命令:{value}"),+ Language::En => format!("Unknown command: {value}."),+ Language::ZhCn => format!("未知命令:{value}。"),}).unwrap_or_else(|| first_error_line(clap_output));@@ -161,15 +167,53 @@ pub(crate) fn report_for_message_error(.with_actions(actions)}+pub(crate) fn report_for_plain_help_error(+ command: impl Into<String>,+ help_command: impl Into<String>,+) -> ErrorReport {+ let language = Language::current();+ let help_command = help_command.into();+ ErrorReport::new(+ copy(language, "Command Error", "命令错误"),+ copy(+ language,+ "Plain help is not supported for this command. Use prefixed help instead.",+ "此命令不支持 plain help。请改用带前缀的 help。",+ ),+ )+ .with_command(command)+ .with_suggestion(help_command.clone())+ .with_actions(vec![ErrorAction::new(+ help_command,+ copy(language, "Show this command's help", "查看此命令帮助"),+ )])+}+pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &Error) -> ErrorReport {let language = Language::current();let command = command.into();match error {+ Error::MissingConfig => ErrorReport::new(+ copy(language, "Configuration Error", "配置错误"),+ copy(+ language,+ "No ovcli.conf detected. Run ov config to create one before using server commands.",+ "未检测到 ovcli.conf。请先运行 ov config 创建配置,再使用服务器命令。",+ ),+ )+ .with_command(command)+ .with_actions(vec![ErrorAction::new(+ "ov config",+ copy(language, "Create a config", "创建配置"),+ )]),Error::Config(message) => ErrorReport::new(copy(language, "Configuration Error", "配置错误"), message)+ .with_command(command)+ .with_actions(config_error_actions(message, language)),+ Error::Language(message) => ErrorReport::new(copy(language, "Language Error", "语言错误"), message).with_command(command).with_actions(vec![- ErrorAction::new("ov config", copy(language, "Add or edit a config", "添加或编辑配置")),- ErrorAction::new("ov config show", copy(language, "Show the active config", "显示当前配置")),+ ErrorAction::new("ov language en", copy(language, "Use English", "使用英文")),+ ErrorAction::new("ov language zh-CN", copy(language, "Use Simplified Chinese", "使用简体中文")),]),Error::Network(message) => ErrorReport::new(copy(language, "Connection Error", "连接错误"),@@ -198,7 +242,7 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &Error]),Error::Api(message) => ErrorReport::new(copy(language, "OpenViking API Error", "OpenViking API 错误"),- copy(language, "OpenViking returned an error for this request.", "OpenViking 返回了请求错误。"),+ api_error_message(language, message),).with_command(command).with_detail(message)@@ -206,16 +250,25 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &ErrorErrorAction::new("ov config validate", copy(language, "Check the active config", "检查当前配置")),ErrorAction::new("ov status", copy(language, "Check OpenViking status", "查看 OpenViking 状态")),]),- Error::Client(message) => ErrorReport::new(copy(language, "Command Error", "命令错误"), message)- .with_command(command)- .with_actions(vec![ErrorAction::new("ov --help", copy(language, "Show all commands", "查看所有命令"))]),- Error::Parse(message) => ErrorReport::new(copy(language, "Parse Error", "解析错误"), message)- .with_command(command)- .with_actions(vec![ErrorAction::new("ov --help", copy(language, "Show all commands", "查看所有命令"))]),+ Error::Client(message) => ErrorReport::new(+ copy(language, "Command Error", "命令错误"),+ sentence_case_error(message),+ )+ .with_command(command.clone())+ .with_actions(contextual_help_actions(&command, language)),+ Error::Parse(message) => ErrorReport::new(+ copy(language, "Parse Error", "解析错误"),+ sentence_case_error(message),+ )+ .with_command(command.clone())+ .with_actions(contextual_help_actions(&command, language)),Error::Output(message) => ErrorReport::new(copy(language, "Output Error", "输出错误"), message).with_command(command),- Error::InvalidPath(message) => ErrorReport::new(copy(language, "Invalid Path", "路径无效"), message)- .with_command(command)- .with_actions(vec![ErrorAction::new("ov --help", copy(language, "Show all commands", "查看所有命令"))]),+ Error::InvalidPath(message) => ErrorReport::new(+ copy(language, "Invalid Path", "路径无效"),+ sentence_case_error(message),+ )+ .with_command(command.clone())+ .with_actions(contextual_help_actions(&command, language)),Error::Io(error) => ErrorReport::new(copy(language, "IO Error", "IO 错误"), copy(language, "OpenViking could not read or write a file.", "OpenViking 无法读取或写入文件。")).with_command(command).with_detail(error.to_string()),@@ -232,9 +285,300 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &Error}}+fn config_error_actions(message: &str, language: Language) -> Vec<ErrorAction> {+ if is_config_file_load_error(message) {+ return vec![ErrorAction::new(+ "ov config",+ copy(+ language,+ "Repair or recreate the active config",+ "修复或重新创建当前配置",+ ),+ )];+ }++ vec![+ ErrorAction::new(+ "ov config",+ copy(language, "Add or edit a config", "添加或编辑配置"),+ ),+ ErrorAction::new(+ "ov config show",+ copy(language, "Show the active config", "显示当前配置"),+ ),+ ]+}++fn is_config_file_load_error(message: &str) -> bool {+ message.starts_with("Failed to read config file:")+ || message.starts_with("Failed to parse config file:")+}++fn contextual_help_actions(command: &str, language: Language) -> Vec<ErrorAction> {+ let help_command = contextual_help_command(command).unwrap_or_else(|| "ov --help".to_string());+ let description = if help_command.ends_with(" --help") && help_command != "ov --help" {+ copy(language, "Show this command's help", "查看此命令帮助")+ } else {+ copy(language, "Show all commands", "查看所有命令")+ };+ vec![ErrorAction::new(help_command, description)]+}++fn contextual_help_command(command: &str) -> Option<String> {+ let tokens = command.split_whitespace().collect::<Vec<_>>();+ let program = *tokens.first()?;+ let root = *tokens.get(1)?;++ match root {+ "config" => Some(group_help_command(+ program,+ root,+ tokens.get(2).copied(),+ &["show", "validate", "switch"],+ )),+ "task" => Some(task_help_command(program, &tokens)),+ "admin" => Some(group_help_command(+ program,+ root,+ tokens.get(2).copied(),+ &[+ "create-account",+ "list-accounts",+ "delete-account",+ "register-user",+ "list-users",+ "list-agents",+ "remove-user",+ "set-role",+ "regenerate-key",+ ],+ )),+ "system" => Some(system_help_command(program, &tokens)),+ "session" => Some(group_help_command(+ program,+ root,+ tokens.get(2).copied(),+ &[+ "new",+ "list",+ "get",+ "get-session-context",+ "get-session-archive",+ "delete",+ "add-message",+ "add-messages",+ "commit",+ ],+ )),+ "privacy" => Some(group_help_command(+ program,+ root,+ tokens.get(2).copied(),+ &[+ "categories",+ "list",+ "get",+ "upsert",+ "versions",+ "version",+ "activate",+ ],+ )),+ "observer" => Some(group_help_command(+ program,+ root,+ tokens.get(2).copied(),+ &[+ "queue",+ "vikingdb",+ "models",+ "transaction",+ "retrieval",+ "filesystem",+ "system",+ ],+ )),+ command if is_contextual_top_level_command(command) => {+ Some(format!("{program} {command} --help"))+ }+ _ => None,+ }+}++fn group_help_command(+ program: &str,+ root: &str,+ leaf: Option<&str>,+ known_leaves: &[&str],+) -> String {+ match leaf {+ Some(leaf) if known_leaves.contains(&leaf) => format!("{program} {root} {leaf} --help"),+ _ => format!("{program} {root} --help"),+ }+}++fn task_help_command(program: &str, tokens: &[&str]) -> String {+ match tokens.get(2).copied() {+ Some("watch") => match tokens.get(3).copied() {+ Some(leaf)+ if ["ls", "show", "rm", "pause", "resume", "update", "trigger"].contains(&leaf) =>+ {+ format!("{program} task watch {leaf} --help")+ }+ _ => format!("{program} task watch --help"),+ },+ Some("status" | "list") => format!("{program} task {} --help", tokens[2]),+ _ => format!("{program} task --help"),+ }+}++fn system_help_command(program: &str, tokens: &[&str]) -> String {+ match tokens.get(2).copied() {+ Some("crypto") => match tokens.get(3).copied() {+ Some("init-key") => format!("{program} system crypto init-key --help"),+ _ => format!("{program} system crypto --help"),+ },+ Some("wait" | "status" | "health" | "consistency") => {+ format!("{program} system {} --help", tokens[2])+ }+ _ => format!("{program} system --help"),+ }+}++fn is_contextual_top_level_command(command: &str) -> bool {+ matches!(+ command,+ "add-resource"+ | "add-skill"+ | "ls"+ | "tree"+ | "mkdir"+ | "rm"+ | "mv"+ | "stat"+ | "read"+ | "abstract"+ | "overview"+ | "write"+ | "get"+ | "find"+ | "search"+ | "grep"+ | "glob"+ | "add-memory"+ | "relations"+ | "link"+ | "unlink"+ | "export"+ | "backup"+ | "import"+ | "restore"+ | "tui"+ | "chat"+ | "wait"+ | "status"+ | "health"+ | "reindex"+ | "language"+ )+}++fn api_error_message(language: Language, raw: &str) -> String {+ let Some(summary) = summarize_api_error(raw) else {+ return copy(+ language,+ "OpenViking returned an error for this request.",+ "OpenViking 返回了请求错误。",+ )+ .to_string();+ };++ match language {+ Language::En => format!("OpenViking returned an error: {summary}"),+ Language::ZhCn => format!("OpenViking 返回了请求错误:{summary}"),+ }+}++fn summarize_api_error(raw: &str) -> Option<String> {+ let raw = raw.trim();+ if raw.is_empty() {+ return None;+ }++ if let Some(summary) = summarize_json_api_error(raw) {+ return Some(summary);+ }++ let cleaned = strip_request_id(raw);+ let cleaned = cleaned.trim();+ if cleaned.is_empty() {+ return None;+ }++ if let Some((code, message)) = bracketed_error(cleaned) {+ return Some(format_summary(Some(code), message));+ }++ Some(ensure_sentence(+ cleaned.lines().next().unwrap_or(cleaned).trim(),+ ))+}++fn summarize_json_api_error(raw: &str) -> Option<String> {+ let value: serde_json::Value = serde_json::from_str(raw).ok()?;+ let error = value.get("error").unwrap_or(&value);+ let code = error+ .get("code")+ .and_then(serde_json::Value::as_str)+ .filter(|value| !value.trim().is_empty());+ let message = error+ .get("message")+ .and_then(serde_json::Value::as_str)+ .or_else(|| error.get("detail").and_then(serde_json::Value::as_str))+ .filter(|value| !value.trim().is_empty())?;+ Some(format_summary(code, message))+}++fn bracketed_error(value: &str) -> Option<(&str, &str)> {+ let rest = value.strip_prefix('[')?;+ let end = rest.find(']')?;+ let code = rest[..end].trim();+ let message = rest[end + 1..].trim();+ if code.is_empty() || message.is_empty() {+ return None;+ }+ Some((code, message))+}++fn format_summary(code: Option<&str>, message: &str) -> String {+ let message = ensure_sentence(strip_request_id(message).trim());+ match code {+ Some(code) => format!("{code}: {message}"),+ None => message,+ }+}++fn strip_request_id(value: &str) -> &str {+ for marker in ["Request ID:", "Request Id:", "request ID:", "request id:"] {+ if let Some(index) = value.find(marker) {+ return value[..index].trim_end();+ }+ }+ value+}++fn ensure_sentence(value: &str) -> String {+ let value = value.trim().trim_end_matches('.').trim();+ if value.is_empty() {+ return "OpenViking returned an error.".to_string();+ }+ format!("{value}.")+}+pub(crate) fn render_report(report: &ErrorReport, verbose: bool) -> String {let mut output = String::new();let language = Language::current();+ let try_command = try_command_for_report(report);if let Some(command) = report.command.as_deref() {output.push_str(&format!("{}\n\n", theme::strong(command)));@@ -248,7 +592,7 @@ pub(crate) fn render_report(report: &ErrorReport, verbose: bool) -> String {output.push_str(&format!("{} {}\n\n",theme::muted(copy(language, "Try:", "可尝试:")),- theme::command("ov --help")+ theme::command(&try_command)));}@@ -462,11 +806,103 @@ fn qualified_suggestion(args: &[OsString], suggested_leaf: &str) -> String {}fn first_error_line(clap_output: &str) -> String {- clap_output+ if let Some(message) = required_arguments_message(clap_output) {+ return message;+ }+ if let Some(message) = unexpected_argument_message(clap_output) {+ return message;+ }++ let Some(raw) = clap_output.lines().find_map(|line| line.trim().strip_prefix("error: "))- .map(ToString::to_string)- .unwrap_or_else(|| "Command could not be parsed.".to_string())+ else {+ return "Command could not be parsed.".to_string();+ };++ sentence_case_error(raw)+}++fn required_arguments_message(clap_output: &str) -> Option<String> {+ let mut lines = clap_output.lines().map(str::trim);+ while let Some(line) = lines.next() {+ if line != "error: the following required arguments were not provided:" {+ continue;+ }++ let arguments = lines+ .by_ref()+ .take_while(|line| !line.is_empty())+ .filter(|line| line.starts_with('<') || line.starts_with('['))+ .map(ToString::to_string)+ .collect::<Vec<_>>();+ return Some(match arguments.as_slice() {+ [] => "Required argument missing.".to_string(),+ [argument] => format!("Required argument missing: {argument}."),+ _ => format!("Required arguments missing: {}.", arguments.join(", ")),+ });+ }++ None+}++fn unexpected_argument_message(clap_output: &str) -> Option<String> {+ clap_output.lines().find_map(|line| {+ let error = line.trim().strip_prefix("error: ")?;+ if !error.starts_with("unexpected argument ") {+ return None;+ }+ first_single_quoted(error)+ .map(|argument| format!("Unexpected argument: {argument}."))+ .or_else(|| Some(sentence_case_error(error)))+ })+}++fn sentence_case_error(raw: &str) -> String {+ let raw = raw.trim().trim_end_matches(':').trim();+ if raw.is_empty() {+ return "Command could not be parsed.".to_string();+ }++ let mut chars = raw.chars();+ let Some(first) = chars.next() else {+ return "Command could not be parsed.".to_string();+ };+ let mut message = first.to_uppercase().collect::<String>();+ message.push_str(chars.as_str());+ if !matches!(message.chars().last(), Some('.' | '?' | '!')) {+ message.push('.');+ }+ message+}++fn try_command_for_report(report: &ErrorReport) -> String {+ report+ .usage+ .as_deref()+ .and_then(help_command_from_usage)+ .unwrap_or_else(|| "ov --help".to_string())+}++fn help_command_from_usage(usage: &str) -> Option<String> {+ let mut parts = Vec::new();+ for token in usage.split_whitespace() {+ if token.starts_with('<') || token.starts_with('[') || token == "..." {+ break;+ }+ parts.push(token);+ }+ let Some(program) = parts.first() else {+ return None;+ };+ if !program.starts_with("ov") {+ return None;+ }+ if parts.len() == 1 {+ Some(format!("{program} --help"))+ } else {+ Some(format!("{} --help", parts.join(" ")))+ }}#[cfg(test)]@@ -521,6 +957,59 @@ Usage: ov [OPTIONS] <COMMAND>assert!(rendered.contains("ov --help"));}+ #[test]+ fn required_argument_error_is_sentence_case_and_specific() {+ let clap_output = "\+error: the following required arguments were not provided:+ <TASK_ID>++Usage: ov task status <TASK_ID>+";+ let report = report_for_clap_error(&os_args(&["ov", "task", "status"]), clap_output);+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Required argument missing: <TASK_ID>."));+ assert!(!rendered.contains("the following required arguments were not provided:"));+ assert!(rendered.contains("Try: ov task status --help"));+ assert!(rendered.contains("ov task status --help"));+ }++ #[test]+ fn preview_binary_usage_points_to_preview_help() {+ let clap_output = "\+error: the following required arguments were not provided:+ <TASK_ID>++Usage: ov-preview task status <TASK_ID>+";+ let report =+ report_for_clap_error(&os_args(&["ov-preview", "task", "status"]), clap_output);+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Required argument missing: <TASK_ID>."));+ assert!(rendered.contains("Try: ov-preview task status --help"));+ assert!(rendered.contains("ov-preview task status --help"));+ }++ #[test]+ fn unexpected_argument_error_is_sentence_case_and_specific() {+ let clap_output = "\+error: unexpected argument '--bad' found++Usage: ov task status <TASK_ID>+";+ let report = report_for_clap_error(+ &os_args(&["ov", "task", "status", "abc", "--bad"]),+ clap_output,+ );+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Unexpected argument: --bad."));+ assert!(!rendered.contains("unexpected argument '--bad' found"));+ assert!(rendered.contains("Try: ov task status --help"));+ assert!(rendered.contains("ov task status --help"));+ }+#[test]fn removed_setup_cli_only_suggests_ov_config() {let clap_output = "\@@ -560,6 +1049,65 @@ Usage: ov config [OPTIONS] [COMMAND]assert!(verbose.contains("Request ID"));}+ #[test]+ fn runtime_api_error_shows_sanitized_detail_by_default() {+ let error = Error::Api(+ "[InvalidRequest] resource not found. Request ID: 02177930089909800000000000000000"+ .to_string(),+ );+ let report = report_for_runtime_error("ov read viking://missing", &error);+ let normal = strip_ansi(&render_report(&report, false));+ let verbose = strip_ansi(&render_report(&report, true));++ assert!(normal.contains("OpenViking API Error"));+ assert!(normal.contains("InvalidRequest: resource not found."));+ assert!(!normal.contains("Request ID"));+ assert!(!normal.contains("02177930089909800000000000000000"));++ assert!(verbose.contains("Detail:"));+ assert!(verbose.contains("Request ID"));+ }++ #[test]+ fn runtime_api_error_summarizes_json_error_envelope() {+ let error = Error::Api(+ r#"{"error":{"code":"PermissionDenied","message":"root key required","request_id":"abc"}}"#+ .to_string(),+ );+ let report = report_for_runtime_error("ov admin list-users --sudo", &error);+ let normal = strip_ansi(&render_report(&report, false));++ assert!(normal.contains("PermissionDenied: root key required."));+ assert!(!normal.contains("request_id"));+ assert!(!normal.contains("abc"));+ }++ #[test]+ fn plain_help_error_points_to_prefixed_help() {+ let report = super::report_for_plain_help_error("ov config help", "ov config --help");+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Command Error"));+ assert!(rendered.contains("Plain help is not supported"));+ assert!(rendered.contains("Did you mean: ov config --help"));+ assert!(rendered.contains("ov config --help"));+ }++ #[test]+ fn missing_config_error_points_to_config_creation() {+ let report = report_for_runtime_error("ov ls", &Error::MissingConfig);+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Configuration Error"));+ assert!(rendered.contains("No ovcli.conf detected"));+ assert!(rendered.contains("Run ov config to create one"));+ assert!(rendered.contains("ov config"));+ assert!(rendered.contains("Create a config"));+ assert!(!rendered.contains("OpenViking API Error"));+ assert!(!rendered.contains("ov config validate"));+ assert!(!rendered.contains("ov status"));+ }+#[test]fn network_error_suggests_validation_and_health_commands() {let error = Error::Network("HTTP request failed: connection refused".to_string());@@ -573,6 +1121,68 @@ Usage: ov config [OPTIONS] [COMMAND]assert!(rendered.contains("ov config switch"));}+ #[test]+ fn language_error_points_to_language_commands() {+ let error = Error::Language("Unsupported language 'fr'. Use 'en' or 'zh-CN'.".to_string());+ let report = report_for_runtime_error("ov language fr", &error);+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Language Error"));+ assert!(rendered.contains("Unsupported language 'fr'"));+ assert!(rendered.contains("ov language en"));+ assert!(rendered.contains("ov language zh-CN"));+ assert!(!rendered.contains("ov config"));+ }++ #[test]+ fn client_error_uses_command_specific_help_action() {+ let error = Error::Client("Specify exactly one of --content or --from-file.".to_string());+ let report = report_for_runtime_error("ov write viking://resources/a.md", &error);+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Command Error"));+ assert!(rendered.contains("ov write --help"));+ assert!(!rendered.contains("ov --help Show all commands"));+ }++ #[test]+ fn client_error_adds_terminal_punctuation() {+ let error = Error::Client("Specify exactly one of --content or --from-file".to_string());+ let report = report_for_runtime_error("ov write viking://resources/a.md", &error);+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Specify exactly one of --content or --from-file."));+ }++ #[test]+ fn parse_error_uses_nested_command_specific_help_action() {+ let error = Error::Parse(+ "minutes must be > 0 (got 0). To pause a watch task, use `ov task watch pause`."+ .to_string(),+ );+ let report = report_for_runtime_error("ov task watch update demo --interval 0", &error);+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Parse Error"));+ assert!(rendered.contains("Minutes must be > 0"));+ assert!(!rendered.contains("minutes must be > 0"));+ assert!(rendered.contains("ov task watch update --help"));+ assert!(!rendered.contains("ov --help Show all commands"));+ }++ #[test]+ fn malformed_config_error_only_suggests_config_repair() {+ let error = Error::Config("Failed to parse config file: key must be a string".to_string());+ let report = report_for_runtime_error("ov ls", &error);+ let rendered = strip_ansi(&render_report(&report, false));++ assert!(rendered.contains("Configuration Error"));+ assert!(rendered.contains("Failed to parse config file"));+ assert!(rendered.contains("ov config"));+ assert!(rendered.contains("Repair or recreate the active config"));+ assert!(!rendered.contains("ov config show"));+ }+#[test]fn chinese_error_card_uses_display_width_for_borders() {let report = ErrorReport::new("命令错误", "未知命令:con").with_suggestion("ov config");diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex cc9c8d1c4..da12eab5a 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -35,26 +35,9 @@ pub async fn handle_add_resource(let unescaped_path = path.replace("\\ ", " ");let path_obj = Path::new(&unescaped_path);if !path_obj.exists() {- eprintln!("Error: Path '{}' does not exist.", path);-- // Check if there might be unquoted spaces- use std::env;- let args: Vec<String> = env::args().collect();-- if let Some(add_resource_pos) =- args.iter().position(|s| s == "add-resource" || s == "add")- {- if args.len() > add_resource_pos + 2 {- let extra_args = &args[add_resource_pos + 2..];- let suggested_path = format!("{} {}", path, extra_args.join(" "));- eprintln!(- "\nIt looks like you may have forgotten to quote a path with spaces."- );- eprintln!("Suggested command: ov add-resource \"{}\"", suggested_path);- }- }-- std::process::exit(1);+ return Err(Error::Client(format!(+ "Local path does not exist: {path}. If the path contains spaces, wrap it in quotes."+ )));}path = unescaped_path;}@@ -72,10 +55,9 @@ pub async fn handle_add_resource(}if exclusive_count > 1 {- eprintln!(- "Error: Cannot specify more than one of --to, --parent, or --parent-auto-create at the same time."- );- std::process::exit(1);+ return Err(Error::Client(+ "Specify only one of --to, --parent, or --parent-auto-create.".to_string(),+ ));}let strict = strict_mode;@@ -632,7 +614,7 @@ pub async fn handle_config(cmd: Option<ConfigCommands>, _ctx: CliContext) -> Respub async fn handle_language(value: Option<String>) -> Result<()> {let language = match value {Some(value) => Language::from_code(&value).ok_or_else(|| {- Error::Config(format!(+ Error::Language(format!("Unsupported language '{value}'. Use 'en' or 'zh-CN'."))})?,@@ -1300,16 +1282,9 @@ pub async fn handle_grep() -> Result<()> {// Prevent grep from root directory to avoid excessive server load and timeoutsif uri == "viking://" || uri == "viking:///" {- eprintln!(- "Error: Cannot grep from root directory 'viking://'.\n\- Grep from root would search across all scopes (resources, user, agent, session, queue, temp),\n\- which may cause server timeout or excessive load.\n\- Please specify a more specific scope, e.g.:\n\- ov grep --uri=viking://resources '{}'\n\- ov grep --uri=viking://user '{}'",- pattern, pattern- );- std::process::exit(1);+ return Err(Error::Client(format!(+ "Cannot grep from root directory 'viking://'. Use a more specific scope, for example `ov grep --uri=viking://resources {pattern}`."+ )));}let mut params = vec![@@ -1389,16 +1364,7 @@ pub async fn handle_tui(uri: String, ctx: CliContext) -> Result<()> {println!("Warning: Server reports unhealthy status");}}- Err(e) => {- println!("Error: Failed to connect to server at {}", ctx.config.url);- println!("{}", e);- println!("\nPlease check:");- println!(" 1. The server is running");- println!(" 2. The URL is correct");- println!(" 3. Your API key is valid (if required)");- println!("\nRun `ov config` to reconfigure if needed.");- std::process::exit(1);- }+ Err(e) => return Err(e),}tui::run_tui(client, &uri).awaitdiff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rsindex 52b6ac9cf..2cbccb2b5 100644--- a/crates/ov_cli/src/help_ui.rs+++ b/crates/ov_cli/src/help_ui.rs@@ -51,6 +51,11 @@ const CORE_WORKFLOW: &[HelpCommand] = &[description: "Add files, folders, URLs, or repos into OpenViking",badge: None,},+ HelpCommand {+ name: "add-skill",+ description: "Add a skill into OpenViking",+ badge: None,+ },HelpCommand {name: "find",description: "Retrieve relevant context semantically",@@ -134,17 +139,17 @@ const SEARCH_CONTEXT: &[HelpCommand] = &[},HelpCommand {name: "abstract",- description: "Read L0 abstract",+ description: "Read Level 0 abstract",badge: None,},HelpCommand {name: "overview",- description: "Read L1 overview",+ description: "Read Level 1 overview",badge: None,},HelpCommand {name: "read",- description: "Read L2 content",+ description: "Read Level 2 content",badge: None,},];@@ -172,7 +177,7 @@ const CONFIG_STATUS: &[HelpCommand] = &[},HelpCommand {name: "language",- description: "Choose CLI display language",+ description: "Choose CLI display language (alias: lang)",badge: None,},HelpCommand {@@ -185,6 +190,11 @@ const CONFIG_STATUS: &[HelpCommand] = &[description: "Full server status",badge: None,},+ HelpCommand {+ name: "observer",+ description: "Inspect server subsystems",+ badge: None,+ },HelpCommand {name: "wait",description: "Wait for async work",@@ -195,6 +205,11 @@ const CONFIG_STATUS: &[HelpCommand] = &[description: "Track async tasks",badge: None,},+ HelpCommand {+ name: "version",+ description: "Show CLI version",+ badge: None,+ },];const IMPORT_EXPORT_SESSIONS: &[HelpCommand] = &[@@ -664,7 +679,7 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[},CommandHelpSpec {path: &["read"],- purpose: "Read exact L2 file content from a Viking URI.",+ purpose: "Read exact Level 2 file content from a Viking URI.",usage: "ov read <uri>",examples: &[HelpItem {label: "ov read viking://projects/acme/spec.md",@@ -690,7 +705,7 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[},CommandHelpSpec {path: &["abstract"],- purpose: "Read L0 abstract content for a directory.",+ purpose: "Read Level 0 abstract content for a directory.",usage: "ov abstract <directory-uri>",examples: &[HelpItem {label: "ov abstract viking://projects/acme",@@ -705,12 +720,12 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[subcommands: &[],next_steps: &[HelpItem {label: "ov overview <directory-uri>",- description: "Read a richer L1 overview.",+ description: "Read a richer Level 1 overview.",}],},CommandHelpSpec {path: &["overview"],- purpose: "Read L1 overview content for a directory.",+ purpose: "Read Level 1 overview content for a directory.",usage: "ov overview <directory-uri>",examples: &[HelpItem {label: "ov overview viking://projects/acme",@@ -725,7 +740,7 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[subcommands: &[],next_steps: &[HelpItem {label: "ov read <file-uri>",- description: "Open exact L2 content.",+ description: "Open exact Level 2 content.",}],},CommandHelpSpec {@@ -831,7 +846,7 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[},HelpItem {label: "-n, --node-limit <n>",- description: "Maximum number of results.",+ description: "Maximum final results returned.",},HelpItem {label: "-t, --threshold <score>",@@ -887,7 +902,7 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[},HelpItem {label: "-n, --node-limit <n>",- description: "Maximum number of results.",+ description: "Maximum results per search pass. Search may merge multiple passes.",},],advanced_options: &[@@ -1658,6 +1673,10 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[label: "ov language zh-CN",description: "Switch display text to Simplified Chinese.",},+ HelpItem {+ label: "ov lang en",+ description: "Use the short alias to switch display text to English.",+ },],arguments: &[HelpItem {label: "language",@@ -1821,7 +1840,7 @@ pub(crate) fn is_top_level_help_request(args: &[OsString]) -> bool {matches!(args[1].to_string_lossy().as_ref(),- "--help" | "-h" | "-help" | "help"+ "--help" | "-h" | "-help")}@@ -2075,6 +2094,7 @@ fn localized_help_item_description<'a>("ov config switch" => "选择一个已保存配置并设为当前配置。","ov language" => "打开语言选择器。","ov language zh-CN" => "将显示语言切换为简体中文。",+ "ov lang en" => "使用短别名切换为英文显示。","language" => "可选语言代码:en 或 zh-CN。","-o, --output <table|json>" => "选择表格输出或机器可读 JSON。","-c, --compact <bool>" => "使用紧凑的表格或 JSON 输出。",@@ -2205,6 +2225,7 @@ fn localized_command_description<'a>(}match name {"add-resource" => "添加文件、文件夹、URL 或仓库",+ "add-skill" => "添加技能到 OpenViking","find" => "语义检索相关上下文","read" => "读取精确资源内容","write" => "更新已有资源",@@ -2245,7 +2266,7 @@ fn localized_command_description<'a>("privacy" => "管理隐私策略","reindex" => "重建语义和向量索引","version" => "显示版本信息",- "language" => "选择 CLI 显示语言",+ "language" => "选择 CLI 显示语言(别名:lang)",_ => description,}}@@ -2259,15 +2280,6 @@ fn command_help_path(args: &[OsString]) -> Option<Vec<String>> {return None;}- if tokens.get(1).is_some_and(|token| token == "help") {- let path: Vec<String> = tokens[2..]- .iter()- .filter(|token| !token.starts_with('-'))- .map(|token| canonical_command_token(token))- .collect();- return if path.is_empty() { None } else { Some(path) };- }-let has_help_flag = tokens.iter().skip(1).any(|token| is_help_flag(token));let mut path = Vec::new();@@ -2297,9 +2309,8 @@ fn command_help_path(args: &[OsString]) -> Option<Vec<String>> {} else if !next.starts_with('-') {if has_help_flag && path.len() == 1 && allows_curated_nested(&path[0]) {path.push(canonical_command_token(next));- } else {- return None;}+ return if has_help_flag { Some(path) } else { None };} else {return None;}@@ -2377,8 +2388,8 @@ fn consumes_value(token: &str) -> bool {#[cfg(test)]mod tests {use super::{- HELP_SECTIONS, command_help_path, display_width, render_command_help_request,- render_top_level_help,+ COMMAND_HELP_SPECS, HELP_SECTIONS, command_help_path, display_width,+ render_command_help_request, render_top_level_help,};use super::{command_spec, is_top_level_help_request};use std::ffi::OsString;@@ -2412,7 +2423,7 @@ mod tests {assert!(is_top_level_help_request(&os_args(&["ov", "--help"])));assert!(is_top_level_help_request(&os_args(&["ov", "-h"])));assert!(is_top_level_help_request(&os_args(&["ov", "-help"])));- assert!(is_top_level_help_request(&os_args(&["ov", "help"])));+ assert!(!is_top_level_help_request(&os_args(&["ov", "help"])));assert!(!is_top_level_help_request(&os_args(&["ov", "config", "--help"@@ -2484,6 +2495,30 @@ mod tests {}}+ #[test]+ fn top_level_help_exposes_all_curated_top_level_commands() {+ let top_level_names: Vec<&str> = HELP_SECTIONS+ .iter()+ .flat_map(|section| section.commands.iter().map(|command| command.name))+ .collect();++ for spec in COMMAND_HELP_SPECS+ .iter()+ .filter(|spec| spec.path.len() == 1)+ {+ let command = spec.path[0];+ assert!(+ top_level_names.contains(&command),+ "top-level help is missing curated command {command}"+ );+ }++ let rendered = strip_ansi(&render_top_level_help());+ for expected in ["add-skill", "observer", "version", "alias: lang"] {+ assert!(rendered.contains(expected), "missing {expected}");+ }+ }+#[test]fn renders_curated_find_help() {let rendered = strip_ansi(@@ -2499,6 +2534,22 @@ mod tests {assert!(rendered.contains("ov read <uri>"));}+ #[test]+ fn find_and_search_help_explain_node_limit_semantics() {+ let find_help = strip_ansi(+ &render_command_help_request(&os_args(&["ov", "find", "--help"]))+ .expect("find help should render"),+ );+ let search_help = strip_ansi(+ &render_command_help_request(&os_args(&["ov", "search", "--help"]))+ .expect("search help should render"),+ );++ assert!(find_help.contains("Maximum final results returned."));+ assert!(search_help.contains("Maximum results per search pass."));+ assert!(search_help.contains("Search may merge multiple passes."));+ }+#[test]fn renders_curated_command_help_for_single_dash_help_alias() {let rendered = strip_ansi(@@ -2527,7 +2578,8 @@ mod tests {fn renders_curated_config_switch_help_from_both_help_forms() {for args in [os_args(&["ov", "config", "switch", "--help"]),- os_args(&["ov", "help", "config", "switch"]),+ os_args(&["ov", "config", "switch", "-h"]),+ os_args(&["ov", "config", "switch", "-help"]),] {let rendered = strip_ansi(&render_command_help_request(&args).expect("config switch help should render"),@@ -2628,7 +2680,25 @@ mod tests {}#[test]- fn unsupported_nested_help_falls_back_to_clap() {- assert!(render_command_help_request(&os_args(&["ov", "task", "list", "--help"])).is_none());+ fn unsupported_nested_prefixed_help_renders_parent_group_help() {+ let rendered = strip_ansi(+ &render_command_help_request(&os_args(&["ov", "task", "list", "--help"]))+ .expect("task list help should render parent task help"),+ );++ assert!(rendered.contains("ov task <subcommand>"));+ assert!(rendered.contains("Inspect and manage async processing tasks."));+ assert!(rendered.contains("Subcommands"));+ }++ #[test]+ fn prefixed_help_with_positional_value_renders_curated_command_help() {+ let rendered = strip_ansi(+ &render_command_help_request(&os_args(&["ov", "ls", "viking://projects", "--help"]))+ .expect("ls help with positional value should render curated ls help"),+ );++ assert!(rendered.contains("ov ls [uri]"));+ assert!(rendered.contains("List resources under a Viking URI."));}}diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 1db23556c..3d094fe8f 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -361,17 +361,17 @@ enum Commands {/// Viking URI to get metadata foruri: String,},- /// [Data] Read file content (L2)+ /// [Data] Read file content (Level 2)Read {/// Viking URIuri: String,},- /// [Data] Read abstract content (L0)+ /// [Data] Read abstract content (Level 0)Abstract {/// Directory URIuri: String,},- /// [Data] Read overview content (L1)+ /// [Data] Read overview content (Level 1)Overview {/// Directory URIuri: String,@@ -699,7 +699,7 @@ fn legacy_upload_option_error() -> Option<&'static str> {if options.is_set() && !command.supports_upload_options() {Some(- "--progress, --no-progress, and --verbose are only supported for add-resource and add-skill",+ "--progress, --no-progress, and --verbose are only supported for add-resource and add-skill.",)} else {None@@ -1057,6 +1057,401 @@ fn find_command_index(args: &[OsString]) -> Option<usize> {None}+#[derive(Debug, Clone, PartialEq, Eq)]+struct PlainHelpMisuse {+ help_command: String,+}++fn plain_help_misuse(args: &[OsString]) -> Option<PlainHelpMisuse> {+ let tokens = command_tokens_for_plain_help(args);+ let help_index = tokens.iter().position(|token| token == "help")?;+ if help_index == 0 {+ return Some(PlainHelpMisuse {+ help_command: "ov --help".to_string(),+ });+ }++ let command = tokens+ .first()+ .map(|token| canonical_plain_help_token(token))?;+ if allows_plain_help_as_user_input(command) {+ return None;+ }++ let mut path = vec![command.to_string()];+ if is_plain_help_group(command) {+ if help_index == 1 {+ return Some(PlainHelpMisuse {+ help_command: prefixed_help_command(&path),+ });+ }+ if let Some(subcommand) = tokens.get(1).map(|token| canonical_plain_help_token(token)) {+ path.push(subcommand.to_string());+ }+ if command == "task" && path.get(1).is_some_and(|token| token == "watch") {+ if let Some(watch_subcommand) =+ tokens.get(2).map(|token| canonical_plain_help_token(token))+ {+ if watch_subcommand != "help" {+ path.push(watch_subcommand.to_string());+ }+ }+ }+ return Some(PlainHelpMisuse {+ help_command: prefixed_help_command(&path),+ });+ }++ Some(PlainHelpMisuse {+ help_command: prefixed_help_command(&path),+ })+}++fn command_tokens_for_plain_help(args: &[OsString]) -> Vec<String> {+ let mut tokens = Vec::new();+ let mut i = 1;+ while i < args.len() {+ let token = args[i].to_string_lossy();+ let token_ref = token.as_ref();+ if consumes_plain_help_value(token_ref) {+ i += if token_ref.contains('=') { 1 } else { 2 };+ continue;+ }+ if token_ref.starts_with('-') {+ i += 1;+ continue;+ }+ tokens.push(token.into_owned());+ i += 1;+ }+ tokens+}++fn consumes_plain_help_value(token: &str) -> bool {+ matches!(+ token,+ "-o" | "--output"+ | "-c"+ | "--compact"+ | "--account"+ | "--user"+ | "--agent-id"+ | "-u"+ | "--uri"+ | "-x"+ | "--exclude-uri"+ | "--to"+ | "--parent"+ | "-p"+ | "--parent-auto-create"+ | "--reason"+ | "--instruction"+ | "--timeout"+ | "--ignore-dirs"+ | "--include"+ | "--exclude"+ | "-n"+ | "--node-limit"+ | "--limit"+ | "-l"+ | "--abs-limit"+ | "-L"+ | "--level"+ | "--level-limit"+ | "-s"+ | "--session"+ | "--sender"+ | "--message"+ | "--role"+ | "--content"+ | "--mode"+ | "--on-conflict"+ | "--vector-mode"+ | "--token-budget"+ | "--interval"+ | "--active"+ ) || token.starts_with("--output=")+ || token.starts_with("--compact=")+ || token.starts_with("--account=")+ || token.starts_with("--user=")+ || token.starts_with("--agent-id=")+ || token.starts_with("--uri=")+ || token.starts_with("--exclude-uri=")+ || token.starts_with("--to=")+ || token.starts_with("--parent=")+ || token.starts_with("--parent-auto-create=")+ || token.starts_with("--reason=")+ || token.starts_with("--instruction=")+ || token.starts_with("--timeout=")+ || token.starts_with("--ignore-dirs=")+ || token.starts_with("--include=")+ || token.starts_with("--exclude=")+ || token.starts_with("--node-limit=")+ || token.starts_with("--limit=")+ || token.starts_with("--abs-limit=")+ || token.starts_with("--level=")+ || token.starts_with("--level-limit=")+ || token.starts_with("--session=")+ || token.starts_with("--sender=")+ || token.starts_with("--message=")+ || token.starts_with("--role=")+ || token.starts_with("--content=")+ || token.starts_with("--mode=")+ || token.starts_with("--on-conflict=")+ || token.starts_with("--vector-mode=")+ || token.starts_with("--token-budget=")+ || token.starts_with("--interval=")+ || token.starts_with("--active=")+}++fn canonical_plain_help_token(token: &str) -> &str {+ match token {+ "list" => "ls",+ "del" | "delete" => "rm",+ "rename" => "mv",+ "lang" => "language",+ other => other,+ }+}++fn allows_plain_help_as_user_input(command: &str) -> bool {+ matches!(+ command,+ "add-resource" | "add-skill" | "find" | "search" | "grep" | "glob" | "add-memory"+ )+}++fn is_plain_help_group(command: &str) -> bool {+ matches!(+ command,+ "config" | "task" | "admin" | "system" | "session" | "privacy" | "observer"+ )+}++fn prefixed_help_command(path: &[String]) -> String {+ if path.is_empty() {+ "ov --help".to_string()+ } else {+ format!("ov {} --help", path.join(" "))+ }+}++fn pre_parse_requires_cli_config_file(args: &[OsString]) -> bool {+ let tokens = command_tokens_for_config_gate(args);+ let Some(command) = tokens+ .first()+ .map(|token| canonical_plain_help_token(token))+ else {+ return false;+ };++ match command {+ "config" => matches!(tokens.get(1).map(String::as_str), Some("show" | "validate")),+ "language" | "version" => false,+ "task" => known_task_command_requires_config(&tokens),+ "admin" => tokens+ .get(1)+ .map(|token| is_admin_subcommand(token))+ .unwrap_or(false),+ "system" => known_system_command_requires_config(&tokens),+ "session" => tokens+ .get(1)+ .map(|token| is_session_subcommand(token))+ .unwrap_or(false),+ "privacy" => tokens+ .get(1)+ .map(|token| is_privacy_subcommand(token))+ .unwrap_or(false),+ "observer" => tokens+ .get(1)+ .map(|token| is_observer_subcommand(token))+ .unwrap_or(false),+ _ => is_top_level_server_command(command),+ }+}++fn command_tokens_for_config_gate(args: &[OsString]) -> Vec<String> {+ let mut tokens = Vec::new();+ let mut seen_command = false;+ let mut i = 1;++ while i < args.len() {+ let token = args[i].to_string_lossy();+ let token_ref = token.as_ref();++ if token_ref == "--" {+ tokens.extend(+ args.iter()+ .skip(i + 1)+ .map(|arg| arg.to_string_lossy().to_string()),+ );+ break;+ }++ if !seen_command {+ if token_ref == "--compact" || token_ref == "-c" {+ i += if args+ .get(i + 1)+ .is_some_and(|value| is_bool_arg(&value.to_string_lossy()))+ {+ 2+ } else {+ 1+ };+ continue;+ }+ if token_ref.starts_with("--") {+ i += if global_option_takes_value(token_ref) && !token_ref.contains('=') {+ 2+ } else {+ 1+ };+ continue;+ }+ if token_ref.starts_with('-') {+ i += if global_short_option_takes_value(token_ref) {+ 2+ } else {+ 1+ };+ continue;+ }+ seen_command = true;+ tokens.push(token.into_owned());+ i += 1;+ continue;+ }++ if token_ref == "--compact" || token_ref == "-c" {+ i += if args+ .get(i + 1)+ .is_some_and(|value| is_bool_arg(&value.to_string_lossy()))+ {+ 2+ } else {+ 1+ };+ continue;+ }+ if consumes_plain_help_value(token_ref) {+ i += if token_ref.contains('=') { 1 } else { 2 };+ continue;+ }+ if token_ref.starts_with('-') {+ i += 1;+ continue;+ }+ tokens.push(token.into_owned());+ i += 1;+ }++ tokens+}++fn known_task_command_requires_config(tokens: &[String]) -> bool {+ match tokens.get(1).map(String::as_str) {+ Some("status" | "list") => true,+ Some("watch") => match tokens.get(2).map(String::as_str) {+ None => true,+ Some(token) => is_watch_subcommand(token),+ },+ _ => false,+ }+}++fn known_system_command_requires_config(tokens: &[String]) -> bool {+ match tokens.get(1).map(String::as_str) {+ Some("wait" | "status" | "health" | "consistency") => true,+ Some("crypto") => match tokens.get(2).map(String::as_str) {+ None => true,+ Some("init-key") => true,+ _ => false,+ },+ _ => false,+ }+}++fn is_top_level_server_command(command: &str) -> bool {+ matches!(+ command,+ "add-resource"+ | "add-skill"+ | "ls"+ | "tree"+ | "mkdir"+ | "rm"+ | "mv"+ | "stat"+ | "read"+ | "abstract"+ | "overview"+ | "write"+ | "get"+ | "find"+ | "search"+ | "grep"+ | "glob"+ | "add-memory"+ | "relations"+ | "link"+ | "unlink"+ | "export"+ | "backup"+ | "import"+ | "restore"+ | "tui"+ | "chat"+ | "wait"+ | "status"+ | "health"+ | "reindex"+ )+}++fn is_watch_subcommand(token: &str) -> bool {+ matches!(+ token,+ "ls" | "show" | "rm" | "pause" | "resume" | "update" | "trigger"+ )+}++fn is_admin_subcommand(token: &str) -> bool {+ matches!(+ token,+ "create-account"+ | "list-accounts"+ | "delete-account"+ | "register-user"+ | "list-users"+ | "list-agents"+ | "remove-user"+ | "set-role"+ | "regenerate-key"+ )+}++fn is_observer_subcommand(token: &str) -> bool {+ matches!(+ token,+ "queue" | "vikingdb" | "models" | "transaction" | "retrieval" | "filesystem" | "system"+ )+}++fn is_session_subcommand(token: &str) -> bool {+ matches!(+ token,+ "new"+ | "list"+ | "get"+ | "get-session-context"+ | "get-session-archive"+ | "delete"+ | "add-message"+ | "add-messages"+ | "commit"+ )+}+fn is_privacy_subcommand(token: &str) -> bool {matches!(token,@@ -1293,6 +1688,24 @@ async fn main() {print!("{help}");return;}+ if let Some(misuse) = plain_help_misuse(&args) {+ let report = error_ui::report_for_plain_help_error(&command_display, misuse.help_command);+ error_ui::print_report(&report, false);+ std::process::exit(2);+ }++ let mut preloaded_required_config = if pre_parse_requires_cli_config_file(&args) {+ match Config::load_required() {+ Ok(config) => Some(config),+ Err(e) => {+ let report = error_ui::report_for_runtime_error(&command_display, &e);+ error_ui::print_report(&report, false);+ std::process::exit(2);+ }+ }+ } else {+ None+ };let cli = match Cli::try_parse_from(args.clone()) {Ok(cli) => cli,@@ -1372,11 +1785,15 @@ async fn main() {return;}- let config = match if cli.command.requires_cli_config_file() {- Config::load_required()+ let config_result = if cli.command.requires_cli_config_file() {+ match preloaded_required_config.take() {+ Some(config) => Ok(config),+ None => Config::load_required(),+ }} else {Config::load_default()- } {+ };+ let config = match config_result {Ok(config) => config,Err(e) => {let report = error_ui::report_for_runtime_error(&command_display, &e);@@ -1760,7 +2177,7 @@ mod tests {Cli, CliContext, Commands, LanguageGateAction, PrivacyCommands, UploadCliOptions,first_command_token, is_language_command_request, language_command_can_run_picker,language_gate_action, language_required_message, legacy_upload_option_error,- preprocess_privacy_args,+ plain_help_misuse, pre_parse_requires_cli_config_file, preprocess_privacy_args,};use crate::config::{Config, DEFAULT_SELF_MANAGED_URL};use crate::handlers;@@ -1812,6 +2229,172 @@ mod tests {assert!(!version.command.requires_cli_config_file());}+ #[test]+ fn pre_parse_config_gate_catches_incomplete_known_server_commands() {+ for args in [+ &["ov", "find"][..],+ &["ov", "task", "status"],+ &["ov", "task", "watch", "show"],+ &["ov", "config", "validate"],+ &["ov", "config", "show"],+ &["ov", "system", "consistency"],+ &["ov", "admin", "list-accounts"],+ ] {+ assert!(+ pre_parse_requires_cli_config_file(&os_args(args)),+ "{args:?} should require ovcli.conf before Clap positional validation"+ );+ }+ }++ #[test]+ fn pre_parse_config_gate_covers_known_top_level_server_commands() {+ for command in [+ "add-resource",+ "add-skill",+ "ls",+ "tree",+ "mkdir",+ "rm",+ "mv",+ "stat",+ "read",+ "abstract",+ "overview",+ "write",+ "get",+ "find",+ "search",+ "grep",+ "glob",+ "add-memory",+ "relations",+ "link",+ "unlink",+ "export",+ "backup",+ "import",+ "restore",+ "tui",+ "chat",+ "wait",+ "status",+ "health",+ "reindex",+ ] {+ assert!(+ pre_parse_requires_cli_config_file(&os_args(&["ov", command])),+ "{command} should require ovcli.conf before Clap validation"+ );+ }+ }++ #[test]+ fn pre_parse_config_gate_covers_known_group_server_commands() {+ let cases: &[&[&str]] = &[+ &["ov", "config", "show"],+ &["ov", "config", "validate"],+ &["ov", "task", "status"],+ &["ov", "task", "list"],+ &["ov", "task", "watch"],+ &["ov", "task", "watch", "ls"],+ &["ov", "task", "watch", "show"],+ &["ov", "task", "watch", "rm"],+ &["ov", "task", "watch", "pause"],+ &["ov", "task", "watch", "resume"],+ &["ov", "task", "watch", "update"],+ &["ov", "task", "watch", "trigger"],+ &["ov", "admin", "create-account"],+ &["ov", "admin", "list-accounts"],+ &["ov", "admin", "delete-account"],+ &["ov", "admin", "register-user"],+ &["ov", "admin", "list-users"],+ &["ov", "admin", "list-agents"],+ &["ov", "admin", "remove-user"],+ &["ov", "admin", "set-role"],+ &["ov", "admin", "regenerate-key"],+ &["ov", "system", "wait"],+ &["ov", "system", "status"],+ &["ov", "system", "health"],+ &["ov", "system", "consistency"],+ &["ov", "system", "crypto"],+ &["ov", "system", "crypto", "init-key"],+ &["ov", "session", "new"],+ &["ov", "session", "list"],+ &["ov", "session", "get"],+ &["ov", "session", "get-session-context"],+ &["ov", "session", "get-session-archive"],+ &["ov", "session", "delete"],+ &["ov", "session", "add-message"],+ &["ov", "session", "add-messages"],+ &["ov", "session", "commit"],+ &["ov", "privacy", "categories"],+ &["ov", "privacy", "list"],+ &["ov", "privacy", "get"],+ &["ov", "privacy", "upsert"],+ &["ov", "privacy", "versions"],+ &["ov", "privacy", "version"],+ &["ov", "privacy", "activate"],+ &["ov", "observer", "queue"],+ &["ov", "observer", "vikingdb"],+ &["ov", "observer", "models"],+ &["ov", "observer", "transaction"],+ &["ov", "observer", "retrieval"],+ &["ov", "observer", "filesystem"],+ &["ov", "observer", "system"],+ ];++ for args in cases {+ assert!(+ pre_parse_requires_cli_config_file(&os_args(args)),+ "{args:?} should require ovcli.conf before Clap validation"+ );+ }++ assert!(+ pre_parse_requires_cli_config_file(&preprocess_privacy_args(os_args(&[+ "ov", "privacy", "skill", "demo",+ ]))),+ "privacy shortcut should require ovcli.conf after preprocessing"+ );+ }++ #[test]+ fn pre_parse_config_gate_respects_aliases_and_valid_help_values() {+ for args in [+ &["ov", "list"][..],+ &["ov", "delete"],+ &["ov", "rename"],+ &["ov", "lang", "en"],+ ] {+ let expected = args[1] != "lang";+ assert_eq!(+ pre_parse_requires_cli_config_file(&os_args(args)),+ expected,+ "{args:?} pre-parse gate mismatch"+ );+ }+ }++ #[test]+ fn pre_parse_config_gate_allows_non_server_and_unknown_commands() {+ for args in [+ &["ov", "con"][..],+ &["ov", "task", "nope"],+ &["ov", "config"],+ &["ov", "config", "switch"],+ &["ov", "config", "setup-cli"],+ &["ov", "version"],+ &["ov", "language", "en"],+ &["ov", "lang", "en"],+ ] {+ assert!(+ !pre_parse_requires_cli_config_file(&os_args(args)),+ "{args:?} should not be gated before Clap parsing"+ );+ }+ }+#[test]fn cli_tree_help_hides_upload_and_admin_only_flags() {let err = Cli::command()@@ -1917,7 +2500,12 @@ mod tests {let tree = Cli::try_parse_from(["ov", "--progress", "tree", "viking://"]).expect("hidden legacy flag still parses before runtime validation");- assert!(legacy_upload_option_error(upload_options, &tree.command).is_some());+ assert_eq!(+ legacy_upload_option_error(upload_options, &tree.command),+ Some(+ "--progress, --no-progress, and --verbose are only supported for add-resource and add-skill."+ )+ );let add_resource = Cli::try_parse_from(["ov", "--progress", "add-resource", "./README.md"]).expect("legacy pre-command upload flags should parse for add-resource");@@ -2065,6 +2653,64 @@ mod tests {}}+ #[test]+ fn plain_help_is_rejected_for_top_level_group_and_structured_leaf_commands() {+ for (args, expected_help) in [+ (vec!["ov", "help"], "ov --help"),+ (vec!["ov", "config", "help"], "ov config --help"),+ (vec!["ov", "task", "help"], "ov task --help"),+ (vec!["ov", "admin", "help"], "ov admin --help"),+ (vec!["ov", "ls", "help"], "ov ls --help"),+ (vec!["ov", "tree", "help"], "ov tree --help"),+ (vec!["ov", "read", "help"], "ov read --help"),+ (+ vec!["ov", "task", "status", "help"],+ "ov task status --help",+ ),+ (+ vec!["ov", "system", "consistency", "help"],+ "ov system consistency --help",+ ),+ ] {+ let misuse = plain_help_misuse(&os_args(&args))+ .unwrap_or_else(|| panic!("{args:?} should be plain-help misuse"));+ assert_eq!(misuse.help_command, expected_help);+ }+ }++ #[test]+ fn plain_help_is_allowed_as_free_form_user_input() {+ for args in [+ vec!["ov", "find", "help"],+ vec!["ov", "search", "help"],+ vec!["ov", "grep", "help"],+ vec!["ov", "glob", "help"],+ vec!["ov", "add-memory", "help"],+ vec!["ov", "add-resource", "help"],+ vec!["ov", "add-skill", "help"],+ ] {+ assert!(+ plain_help_misuse(&os_args(&args)).is_none(),+ "{args:?} should remain normal user input"+ );+ }+ }++ #[test]+ fn plain_help_ignores_option_values() {+ assert!(+ plain_help_misuse(&os_args(&[+ "ov",+ "read",+ "--account",+ "help",+ "viking://resource",+ ]))+ .is_none()+ );+ assert!(plain_help_misuse(&os_args(&["ov", "grep", "--uri", "help", "TODO",])).is_none());+ }+#[test]fn cli_context_overrides_identity_from_cli_flags() {let config = Config {diff --git a/crates/ov_cli/src/output.rs b/crates/ov_cli/src/output.rsindex 5de93e958..b609acaa9 100644--- a/crates/ov_cli/src/output.rs+++ b/crates/ov_cli/src/output.rs@@ -1,5 +1,5 @@use serde::Serialize;-use serde_json::{json, Value};+use serde_json::{Value, json};use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};use crate::theme;@@ -384,10 +384,7 @@ pub fn render_profiled_scalar_result(value: &serde_json::Value) -> Option<StringSome(append_profile_section(result.to_string(), obj))}-pub fn append_profile_to_rendered(- rendered: String,- value: &serde_json::Value,-) -> String {+pub fn append_profile_to_rendered(rendered: String, value: &serde_json::Value) -> String {let Some(obj) = value.as_object() else {return rendered;};@@ -913,11 +910,35 @@ fn style_table_value(value: &str, is_uri: bool) -> String {return theme::sky_value(value).bold().to_string();}+ match table_value_tone(trimmed) {+ TableValueTone::Success => theme::success(value).bold().to_string(),+ TableValueTone::Warning => theme::warning(value).bold().to_string(),+ TableValueTone::Error => theme::error(value).bold().to_string(),+ TableValueTone::Muted => theme::muted(value).to_string(),+ TableValueTone::Body => theme::body(value).to_string(),+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum TableValueTone {+ Success,+ Warning,+ Error,+ Muted,+ Body,+}++fn table_value_tone(trimmed: &str) -> TableValueTone {match trimmed.to_ascii_lowercase().as_str() {- "healthy" | "ok" | "true" | "success" => theme::success(value).bold().to_string(),- "unhealthy" | "failed" | "error" | "false" => theme::error(value).bold().to_string(),- "unknown" | "null" | "(empty)" => theme::muted(value).to_string(),- _ => theme::body(value).to_string(),+ "healthy" | "ok" | "true" | "success" | "completed" | "done" | "connected" => {+ TableValueTone::Success+ }+ "running" | "in_progress" | "in-progress" | "pending" | "queued" | "processing"+ | "checking" | "warning" => TableValueTone::Warning,+ "unhealthy" | "failed" | "error" | "false" | "cancelled" | "canceled" | "timeout"+ | "timed_out" | "unreachable" => TableValueTone::Error,+ "unknown" | "null" | "(empty)" => TableValueTone::Muted,+ _ => TableValueTone::Body,}}@@ -988,6 +1009,7 @@ fn truncate_string(s: &str, is_unbounded: bool, max_width: usize) -> (String, bo#[cfg(test)]mod tests {use super::*;+ use colored::Colorize;use serde_json::json;#[test]@@ -1030,6 +1052,43 @@ mod tests {assert!(skip_padding);}+ #[test]+ fn task_status_values_map_to_severity_tones() {+ assert_eq!(table_value_tone("completed"), TableValueTone::Success);+ assert_eq!(table_value_tone("done"), TableValueTone::Success);+ assert_eq!(table_value_tone("connected"), TableValueTone::Success);++ assert_eq!(table_value_tone("running"), TableValueTone::Warning);+ assert_eq!(table_value_tone("pending"), TableValueTone::Warning);+ assert_eq!(table_value_tone("queued"), TableValueTone::Warning);+ assert_eq!(table_value_tone("processing"), TableValueTone::Warning);++ assert_eq!(table_value_tone("failed"), TableValueTone::Error);+ assert_eq!(table_value_tone("cancelled"), TableValueTone::Error);+ assert_eq!(table_value_tone("unreachable"), TableValueTone::Error);++ assert_eq!(table_value_tone("unknown"), TableValueTone::Muted);+ assert_eq!(table_value_tone("task-1"), TableValueTone::Body);+ }++ #[test]+ fn rendered_status_column_uses_severity_colors() {+ let rows = vec![json!({+ "task_id": "task-1",+ "status": "running"+ })];++ colored::control::set_override(true);+ let rendered = format_array_to_table(&rows, true).expect("table should render");+ let expected = theme::warning("running").bold().to_string();+ colored::control::unset_override();++ assert!(+ rendered.contains(&expected),+ "rendered table should color the running status: {rendered:?}"+ );+ }+#[test]fn test_profile_section_is_preserved_for_table_objects_with_list_payloads() {let value = json!({@@ -1203,17 +1262,7 @@ mod tests {assert_eq!(rendered,- Some(- [- "content",- "",- "profile",- "line one",- "line two",- "",- ]- .join("\n")- )+ Some(["content", "", "profile", "line one", "line two", "",].join("\n")));}}diff --git a/crates/ov_cli/src/status_ui.rs b/crates/ov_cli/src/status_ui.rsindex 78f26ecef..46bc9e61a 100644--- a/crates/ov_cli/src/status_ui.rs+++ b/crates/ov_cli/src/status_ui.rs@@ -5,7 +5,8 @@ use unicode_width::UnicodeWidthStr;use crate::{config::{Config, display_config_home},config_wizard::{ConfigKind, ConfigStore},- error::Result,+ error::{Error, Result},+ error_classifier::looks_like_auth_error,i18n::{Language, copy},theme,};@@ -154,8 +155,10 @@ pub(crate) fn render_unreachable_status(config: &Config,active_name: Option<&str>,saved_count: usize,+ error: Option<&Error>,) -> String {let language = Language::current();+ let failure = StatusFailureKind::from_error(error);let kind = kind_label(ConfigKind::from_config(config), language);let active = active_name.unwrap_or_else(|| unknown(language));let mut lines = Vec::new();@@ -179,7 +182,11 @@ pub(crate) fn render_unreachable_status(lines.push(section_title(copy(language, "System", "系统")));lines.push(detail_line_styled(copy(language, "Status", "状态"),- error_value(copy(language, "Unreachable", "无法连接")),+ error_value(failure.status_label(language)),+ ));+ lines.push(detail_line_styled(+ copy(language, "Issue", "问题"),+ plain_value(failure.issue_label(language)),));lines.push(detail_line_styled(copy(language, "Saved configs", "已保存配置"),@@ -187,26 +194,101 @@ pub(crate) fn render_unreachable_status());lines.push(String::new());lines.push(section_title(copy(language, "What to try", "可以尝试")));- lines.push(action_line(- "ov config validate",- copy(- language,- "Check config, auth, and server reachability",- "检查配置、认证和服务器连接",- ),- ));- lines.push(action_line(- "ov config",- copy(language, "Edit or switch config", "编辑或切换配置"),- ));- lines.push(action_line(- "ov health",- copy(language, "Run a quick health check", "快速健康检查"),- ));+ for (command, description) in failure.actions(language) {+ lines.push(action_line(command, description));+ }format!("{}\n", lines.join("\n"))}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum StatusFailureKind {+ Authentication,+ Api,+ Connection,+}++impl StatusFailureKind {+ fn from_error(error: Option<&Error>) -> Self {+ match error {+ Some(Error::Api(message)) if looks_like_auth_error(message) => Self::Authentication,+ Some(Error::Api(_)) => Self::Api,+ _ => Self::Connection,+ }+ }++ fn status_label(self, language: Language) -> &'static str {+ match self {+ Self::Authentication => copy(language, "Authentication failed", "认证失败"),+ Self::Api => copy(language, "Server error", "服务器错误"),+ Self::Connection => copy(language, "Unreachable", "无法连接"),+ }+ }++ fn issue_label(self, language: Language) -> &'static str {+ match self {+ Self::Authentication => copy(language, "API key rejected", "API Key 被拒绝"),+ Self::Api => copy(+ language,+ "OpenViking returned an API error",+ "OpenViking 返回 API 错误",+ ),+ Self::Connection => copy(language, "Cannot reach server", "无法连接服务器"),+ }+ }++ fn actions(self, language: Language) -> Vec<(&'static str, &'static str)> {+ match self {+ Self::Authentication => vec![+ (+ "ov config",+ copy(language, "Edit the active API key", "编辑当前 API Key"),+ ),+ (+ "ov config switch",+ copy(language, "Use another config", "切换到其他配置"),+ ),+ (+ "ov config validate",+ copy(language, "Validate after updating", "更新后验证"),+ ),+ ],+ Self::Api => vec![+ (+ "ov config validate",+ copy(language, "Check config and auth", "检查配置和认证"),+ ),+ (+ "ov status --verbose",+ copy(language, "Show backend error details", "显示后端错误详情"),+ ),+ (+ "ov health",+ copy(language, "Run a quick health check", "快速健康检查"),+ ),+ ],+ Self::Connection => vec![+ (+ "ov config validate",+ copy(+ language,+ "Check config, auth, and server reachability",+ "检查配置、认证和服务器连接",+ ),+ ),+ (+ "ov config",+ copy(language, "Edit or switch config", "编辑或切换配置"),+ ),+ (+ "ov health",+ copy(language, "Run a quick health check", "快速健康检查"),+ ),+ ],+ }+ }+}+fn status_title(language: Language) -> String {theme::brand_title(copy(language, "OPENVIKING STATUS", "OPENVIKING 状态")).bold()@@ -800,6 +882,36 @@ mod tests {assert!(plain.contains("ov status --verbose Show full component tables"));}+ #[test]+ fn unreachable_status_distinguishes_auth_failures() {+ let error = crate::error::Error::Api(+ "[AuthenticationError] API key invalid. Request ID: abc".to_string(),+ );+ let rendered =+ super::render_unreachable_status(&sample_config(), Some("local"), 2, Some(&error));+ let rendered = strip_ansi(&rendered);++ assert!(rendered.contains("Status Authentication failed"));+ assert!(rendered.contains("Issue API key rejected"));+ assert!(rendered.contains("ov config Edit the active API key"));+ assert!(!rendered.contains("Request ID"));+ }++ #[test]+ fn unreachable_status_keeps_connection_guidance_for_network_errors() {+ let error = crate::error::Error::Network("connection refused".to_string());+ let rendered =+ super::render_unreachable_status(&sample_config(), Some("local"), 2, Some(&error));+ let rendered = strip_ansi(&rendered);++ assert!(rendered.contains("Status Unreachable"));+ assert!(rendered.contains("Issue Cannot reach server"));+ assert!(+ rendered+ .contains("ov config validate Check config, auth, and server reachability")+ );+ }+fn strip_ansi(input: &str) -> String {let mut output = String::with_capacity(input.len());let mut chars = input.chars().peekable();diff --git a/crates/ov_cli/src/theme.rs b/crates/ov_cli/src/theme.rsindex 4e8e4f874..3b35f0b8b 100644--- a/crates/ov_cli/src/theme.rs+++ b/crates/ov_cli/src/theme.rs@@ -1,3 +1,5 @@+use std::env;+use colored::{ColoredString, Colorize};#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -8,6 +10,14 @@ pub(crate) enum ThemeColor {TrueColor(Rgb),}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ColorLevel {+ NoColor,+ Ansi16,+ Ansi256,+ TrueColor,+}+impl ThemeColor {pub(crate) fn rgb_fallback(&self) -> Rgb {match self {@@ -82,6 +92,155 @@ pub(crate) fn colorize(text: impl Into<String>, color: ThemeColor) -> ColoredStr}}+pub(crate) fn terminal_color_level() -> ColorLevel {+ if !colored::control::SHOULD_COLORIZE.should_colorize() {+ return ColorLevel::NoColor;+ }++ terminal_color_level_from_env(+ env::var("COLORTERM").ok().as_deref(),+ env::var("TERM").ok().as_deref(),+ env::var("TERM_PROGRAM").ok().as_deref(),+ )+}++pub(crate) fn terminal_color_level_from_env(+ colorterm: Option<&str>,+ term: Option<&str>,+ term_program: Option<&str>,+) -> ColorLevel {+ if colorterm+ .map(|value| value.eq_ignore_ascii_case("truecolor") || value.eq_ignore_ascii_case("24bit"))+ .unwrap_or(false)+ || term+ .map(|value| {+ let value = value.to_ascii_lowercase();+ value.contains("truecolor") || value.contains("24bit") || value.contains("direct")+ })+ .unwrap_or(false)+ || term_program+ .map(|value| {+ matches!(+ value.to_ascii_lowercase().as_str(),+ "iterm.app" | "wezterm" | "vscode" | "windows_terminal"+ )+ })+ .unwrap_or(false)+ {+ return ColorLevel::TrueColor;+ }++ if term+ .map(|value| value.to_ascii_lowercase().contains("256color"))+ .unwrap_or(false)+ || term_program+ .map(|value| value.eq_ignore_ascii_case("Apple_Terminal"))+ .unwrap_or(false)+ {+ return ColorLevel::Ansi256;+ }++ ColorLevel::Ansi16+}++pub(crate) fn style_rgb(text: impl AsRef<str>, rgb: Rgb, bold: bool) -> String {+ style_rgb_for_level(text, rgb, bold, terminal_color_level())+}++pub(crate) fn style_rgb_for_level(+ text: impl AsRef<str>,+ rgb: Rgb,+ bold: bool,+ level: ColorLevel,+) -> String {+ let text = text.as_ref();+ match level {+ ColorLevel::NoColor => text.to_string(),+ ColorLevel::TrueColor => {+ let Rgb(red, green, blue) = rgb;+ ansi_style(text, &format!("38;2;{red};{green};{blue}"), bold)+ }+ ColorLevel::Ansi256 => {+ ansi_style(text, &format!("38;5;{}", ansi256_index_for_rgb(rgb)), bold)+ }+ ColorLevel::Ansi16 => ansi_style(text, &ansi16_fg_code_for_rgb(rgb).to_string(), bold),+ }+}++fn ansi_style(text: &str, fg_code: &str, bold: bool) -> String {+ if bold {+ format!("\u{1b}[1;{fg_code}m{text}\u{1b}[0m")+ } else {+ format!("\u{1b}[{fg_code}m{text}\u{1b}[0m")+ }+}++pub(crate) fn ansi256_index_for_rgb(rgb: Rgb) -> u8 {+ let Rgb(red, green, blue) = rgb;++ if red.abs_diff(green) <= 10 && green.abs_diff(blue) <= 10 {+ let average = (u16::from(red) + u16::from(green) + u16::from(blue)) / 3;+ if average < 8 {+ return 16;+ }+ if average > 238 {+ return 231;+ }+ return 232 + ((average - 8) / 10) as u8;+ }++ let red = ansi256_cube_component(red);+ let green = ansi256_cube_component(green);+ let blue = ansi256_cube_component(blue);++ 16 + 36 * red + 6 * green + blue+}++fn ansi256_cube_component(value: u8) -> u8 {+ if value < 48 {+ 0+ } else if value < 115 {+ 1+ } else {+ ((value - 35) / 40).min(5)+ }+}++fn ansi16_fg_code_for_rgb(rgb: Rgb) -> u8 {+ const ANSI16: [(u8, Rgb); 16] = [+ (30, Rgb(0, 0, 0)),+ (31, Rgb(128, 0, 0)),+ (32, Rgb(0, 128, 0)),+ (33, Rgb(128, 128, 0)),+ (34, Rgb(0, 0, 128)),+ (35, Rgb(128, 0, 128)),+ (36, Rgb(0, 128, 128)),+ (37, Rgb(192, 192, 192)),+ (90, Rgb(128, 128, 128)),+ (91, Rgb(255, 0, 0)),+ (92, Rgb(0, 255, 0)),+ (93, Rgb(255, 255, 0)),+ (94, Rgb(0, 0, 255)),+ (95, Rgb(255, 0, 255)),+ (96, Rgb(0, 255, 255)),+ (97, Rgb(255, 255, 255)),+ ];++ ANSI16+ .iter()+ .min_by_key(|(_, candidate)| rgb_distance_squared(rgb, *candidate))+ .map(|(code, _)| *code)+ .unwrap_or(37)+}++fn rgb_distance_squared(left: Rgb, right: Rgb) -> u32 {+ let red = i32::from(left.0) - i32::from(right.0);+ let green = i32::from(left.1) - i32::from(right.1);+ let blue = i32::from(left.2) - i32::from(right.2);++ (red * red + green * green + blue * blue) as u32+}+pub(crate) fn brand_title(text: impl Into<String>) -> ColoredString {let theme = active_theme();colorize(text, theme.brand_title)@@ -179,7 +338,10 @@ fn relative_luminance(color: Rgb) -> f32 {#[cfg(test)]mod tests {- use super::{CliTheme, Rgb, ThemeColor, active_theme, palette, relative_luminance};+ use super::{+ CliTheme, ColorLevel, Rgb, ThemeColor, active_theme, ansi256_index_for_rgb, palette,+ relative_luminance, style_rgb_for_level, terminal_color_level_from_env,+ };const PALE_PEARL: Rgb = Rgb(234, 253, 247);const WHITE: Rgb = Rgb(255, 255, 255);@@ -190,6 +352,38 @@ mod tests {assert_eq!(active_theme(), palette());}+ #[test]+ fn apple_terminal_uses_ansi256_instead_of_truecolor() {+ assert_eq!(+ terminal_color_level_from_env(None, Some("xterm-256color"), Some("Apple_Terminal")),+ ColorLevel::Ansi256+ );+ assert_eq!(+ terminal_color_level_from_env(+ Some("truecolor"),+ Some("xterm-256color"),+ Some("Apple_Terminal")+ ),+ ColorLevel::TrueColor+ );+ }++ #[test]+ fn ansi256_mapping_keeps_dark_teal_out_of_black_and_gray() {+ let index = ansi256_index_for_rgb(Rgb(5, 86, 80));++ assert_eq!(index, 23);+ assert!(!matches!(index, 0 | 8 | 232..=255));+ }++ #[test]+ fn rgb_styling_uses_fixed_ansi256_when_truecolor_is_unavailable() {+ let styled = style_rgb_for_level("X", Rgb(5, 86, 80), true, ColorLevel::Ansi256);++ assert_eq!(styled, "\u{1b}[1;38;5;23mX\u{1b}[0m");+ assert!(!styled.contains("38;2"));+ }+fn functional_colors(palette: CliTheme) -> [(&'static str, ThemeColor); 13] {[("brand_title", palette.brand_title),