Skip to content

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

feat(cli): Revamp OpenViking CLI (#2198)

Hao Zhe7ae22460deb1
diff --git a/README.md b/README.md
index f2f53d46a..137cd8480 100644
--- a/README.md
+++ b/README.md
@@ -504,7 +504,7 @@ set "OPENVIKING_CONFIG_FILE=%USERPROFILE%\.openviking\ov.conf"
#### CLI/Client Configuration Examples
-You can initialize the configuration of the CLI/client interactively through the `ov config setup-cli` command. If you have multiple openviking servers, you can also switch to other configurations using the `ov config switch` command.
+You can initialize the configuration of the CLI/client interactively through the `ov config` command. If you have multiple openviking servers, you can also switch to other configurations using the `ov config switch` command.
👇 Expand to see the configuration example for your CLI/Client:
<details>
diff --git a/README_CN.md b/README_CN.md
index cc8117f19..b16d3334a 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -434,7 +434,7 @@ set "OPENVIKING_CONFIG_FILE=%USERPROFILE%\.openviking\ov.conf"
#### CLI/客户端配置示例
-你可以通过 `ov config setup-cli` 命令来以交互式方式初始化 CLI/客户端的配置。如果你有多个 openviking 服务器,你还可以通过 `ov config switch` 命令来切换到其他配置。
+你可以通过 `ov config` 命令来以交互式方式初始化 CLI/客户端的配置。如果你有多个 openviking 服务器,你还可以通过 `ov config switch` 命令来切换到其他配置。
👇 展开查看您的 CLI/客户端的配置示例:
diff --git a/crates/ov_cli/src/commands/system.rs b/crates/ov_cli/src/commands/system.rs
index 99d6f2519..6625d4f49 100644
--- a/crates/ov_cli/src/commands/system.rs
+++ b/crates/ov_cli/src/commands/system.rs
@@ -1,6 +1,9 @@
use crate::client::HttpClient;
+use crate::config::Config;
use crate::error::Result;
+use crate::health_ui;
use crate::output::{OutputFormat, output_success};
+use crate::status_ui;
use serde_json::json;
pub async fn wait(
@@ -22,6 +25,46 @@ pub async fn status(client: &HttpClient, output_format: OutputFormat, compact: b
Ok(())
}
+pub async fn diagnostic_status(
+ client: &HttpClient,
+ config: &Config,
+ output_format: OutputFormat,
+ compact: bool,
+ verbose: bool,
+) -> Result<()> {
+ let meta = status_ui::current_config_meta();
+
+ if matches!(output_format, OutputFormat::Json) || verbose {
+ let response: serde_json::Value = client.get("/api/v1/observer/system", &[]).await?;
+ output_success(&response, output_format, compact);
+ return Ok(());
+ }
+
+ match client
+ .get::<serde_json::Value>("/api/v1/observer/system", &[])
+ .await
+ {
+ Ok(response) => {
+ print!(
+ "{}",
+ status_ui::render_status(&response, config, meta.active_name.as_deref(),)?
+ );
+ }
+ Err(_) => {
+ print!(
+ "{}",
+ status_ui::render_unreachable_status(
+ config,
+ meta.active_name.as_deref(),
+ meta.saved_count,
+ )
+ );
+ }
+ }
+
+ Ok(())
+}
+
pub async fn consistency(
client: &HttpClient,
uri: &str,
@@ -90,6 +133,7 @@ fn output_consistency_table(response: &serde_json::Value, compact: bool) {
pub async fn health(
client: &HttpClient,
+ config: Option<&Config>,
output_format: OutputFormat,
compact: bool,
) -> Result<bool> {
@@ -101,19 +145,10 @@ pub async fn health(
.and_then(|v| v.as_bool())
.unwrap_or(false);
- // For table output, print in a readable format
- if matches!(output_format, OutputFormat::Table) || matches!(output_format, OutputFormat::Json) {
+ if matches!(output_format, OutputFormat::Json) {
output_success(&response, output_format, compact);
} else {
- // Simple text output - print healthy first, then other fields line by line
- println!("healthy {}", if healthy { "true" } else { "false" });
- if let Some(obj) = response.as_object() {
- for (key, value) in obj {
- if key != "healthy" {
- println!("{} {}", key, value);
- }
- }
- }
+ print!("{}", health_ui::render_health(&response, config));
}
Ok(healthy)
diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rs
index dd6178311..b99168ea2 100644
--- a/crates/ov_cli/src/config.rs
+++ b/crates/ov_cli/src/config.rs
@@ -4,6 +4,8 @@ use std::path::{Path, PathBuf};
use crate::error::{Error, Result};
const OPENVIKING_CLI_CONFIG_ENV: &str = "OPENVIKING_CLI_CONFIG_FILE";
+pub const DEFAULT_SELF_MANAGED_PORT: &str = "1933";
+pub const DEFAULT_SELF_MANAGED_URL: &str = "http://127.0.0.1:1933";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UploadConfig {
@@ -52,7 +54,7 @@ pub struct Config {
}
fn default_url() -> String {
- "http://localhost:1933".to_string()
+ DEFAULT_SELF_MANAGED_URL.to_string()
}
fn default_timeout() -> f64 {
@@ -78,7 +80,7 @@ fn default_verbose() -> bool {
impl Default for Config {
fn default() -> Self {
Self {
- url: "http://localhost:1933".to_string(),
+ url: DEFAULT_SELF_MANAGED_URL.to_string(),
api_key: None,
root_api_key: None,
account: None,
@@ -154,7 +156,7 @@ impl Config {
Self::from_file(&path.to_string_lossy())
} else {
Err(Error::Config(
- "No CLI config file detected, please use `ov config setup-cli` to initialize ovcli.conf"
+ "No CLI config file detected, please use `ov config` to initialize ovcli.conf"
.to_string(),
))
}
@@ -196,6 +198,22 @@ pub fn default_config_path() -> Result<PathBuf> {
Ok(home.join(".openviking").join("ovcli.conf"))
}
+pub fn display_config_home() -> String {
+ let path = default_config_path()
+ .ok()
+ .and_then(|path| path.parent().map(|parent| parent.to_path_buf()));
+ let Some(path) = path else {
+ return "~/.openviking".to_string();
+ };
+ let Some(home) = dirs::home_dir() else {
+ return path.display().to_string();
+ };
+ if let Ok(stripped) = path.strip_prefix(&home) {
+ return format!("~/{}", stripped.display());
+ }
+ path.display().to_string()
+}
+
/// Get a unique machine ID using machine-uid crate.
///
/// Uses the system's machine ID, falls back to "default" if unavailable.
@@ -220,7 +238,8 @@ mod tests {
.to_string();
assert!(error.contains("No CLI config file detected"));
- assert!(error.contains("ov config setup-cli"));
+ assert!(error.contains("ov config"));
+ assert!(!error.contains("setup-cli"));
assert!(error.contains("ovcli.conf"));
}
@@ -232,14 +251,14 @@ mod tests {
let config = Config::load_default_from_path(&path)
.expect("default-loading path should still fall back");
- assert_eq!(config.url, "http://localhost:1933");
+ assert_eq!(config.url, "http://127.0.0.1:1933");
}
#[test]
fn config_deserializes_account_and_user_fields() {
let config: Config = serde_json::from_str(
r#"{
- "url": "http://localhost:1933",
+ "url": "http://127.0.0.1:1933",
"api_key": "test-key",
"account": "acme",
"user": "alice",
@@ -260,7 +279,7 @@ mod tests {
fn config_deserializes_root_api_key() {
let config: Config = serde_json::from_str(
r#"{
- "url": "http://localhost:1933",
+ "url": "http://127.0.0.1:1933",
"api_key": "user-key",
"root_api_key": "root-key"
}"#,
@@ -275,7 +294,7 @@ mod tests {
fn config_deserializes_account_id_and_user_id_aliases() {
let config: Config = serde_json::from_str(
r#"{
- "url": "http://localhost:1933",
+ "url": "http://127.0.0.1:1933",
"account_id": "acme",
"user_id": "alice"
}"#,
@@ -290,7 +309,7 @@ mod tests {
fn config_deserializes_upload_fields() {
let config: Config = serde_json::from_str(
r#"{
- "url": "http://localhost:1933",
+ "url": "http://127.0.0.1:1933",
"upload": {
"ignore_dirs": "node_modules,dist",
"include": "*.md,*.pdf",
@@ -359,7 +378,7 @@ mod tests {
fn config_deserializes_extra_headers() {
let config: Config = serde_json::from_str(
r#"{
- "url": "http://localhost:1933",
+ "url": "http://127.0.0.1:1933",
"extra_headers": {
"X-Custom-Header": "custom-value",
"Authorization": "Bearer token"
@@ -377,7 +396,7 @@ mod tests {
fn config_deserializes_extra_headers_none_when_missing() {
let config: Config = serde_json::from_str(
r#"{
- "url": "http://localhost:1933"
+ "url": "http://127.0.0.1:1933"
}"#,
)
.expect("config should deserialize");
@@ -389,7 +408,7 @@ mod tests {
fn config_deserializes_profile_flag() {
let config: Config = serde_json::from_str(
r#"{
- "url": "http://localhost:1933",
+ "url": "http://127.0.0.1:1933",
"profile": true
}"#,
)
@@ -402,7 +421,7 @@ mod tests {
fn config_deserializes_extra_header_alias() {
let config: Config = serde_json::from_str(
r#"{
- "url": "http://localhost:1933",
+ "url": "http://127.0.0.1:1933",
"extra_header": {
"X-Custom-Header": "custom-value",
"Authorization": "Bearer token"
diff --git a/crates/ov_cli/src/config_command_ui.rs b/crates/ov_cli/src/config_command_ui.rs
new file mode 100644
index 000000000..c4ae8220a
--- /dev/null
+++ b/crates/ov_cli/src/config_command_ui.rs
@@ -0,0 +1,521 @@
+use colored::Colorize;
+use unicode_width::UnicodeWidthStr;
+
+use crate::{
+ config::{Config, display_config_home},
+ config_wizard::ConfigKind,
+ error::Error,
+ error_classifier::looks_like_auth_error,
+ i18n::{Language, copy},
+ theme,
+};
+
+const LABEL_WIDTH: usize = 14;
+const ACTION_WIDTH: usize = 26;
+const NAME_WIDTH: usize = 17;
+const KIND_WIDTH: usize = 18;
+
+#[derive(Debug, Clone)]
+pub(crate) struct SwitchConfigRow {
+ pub name: String,
+ pub kind: ConfigKind,
+ pub is_active: bool,
+}
+
+pub(crate) fn render_validate_success(config: &Config, active_name: Option<&str>) -> String {
+ render_validate_success_with_language(config, active_name, Language::current())
+}
+
+pub(crate) fn render_validate_success_with_language(
+ config: &Config,
+ active_name: Option<&str>,
+ language: Language,
+) -> String {
+ let mut lines = Vec::new();
+ let kind = kind_label(ConfigKind::from_config(config), language);
+ let active = active_name.unwrap_or_else(|| unknown(language));
+
+ lines.push(title(copy(
+ language,
+ "OPENVIKING CONFIG CHECK",
+ "OPENVIKING 配置检查",
+ )));
+ lines.push(String::new());
+ lines.push(section(copy(language, "Config", "配置")));
+ lines.push(detail_line(
+ copy(language, "Active", "当前配置"),
+ active_value(active, kind),
+ ));
+ lines.push(detail_line(
+ copy(language, "Server", "服务器"),
+ path_value(&config.url),
+ ));
+ lines.push(detail_line(
+ copy(language, "Config home", "配置目录"),
+ path_value(&display_config_home()),
+ ));
+ lines.push(String::new());
+ lines.push(section(copy(language, "Checks", "检查项")));
+ lines.push(detail_line(
+ copy(language, "Config file", "配置文件"),
+ ok_value(copy(language, "valid", "有效")),
+ ));
+ lines.push(detail_line(
+ copy(language, "Server", "服务器"),
+ ok_value(copy(language, "reachable", "可连接")),
+ ));
+ lines.push(detail_line(
+ copy(language, "Auth", "认证"),
+ ok_value(copy(language, "accepted", "已通过")),
+ ));
+ lines.push(detail_line(
+ copy(language, "Health", "健康状态"),
+ ok_value(copy(language, "healthy", "健康")),
+ ));
+ lines.push(String::new());
+ lines.push(section(copy(language, "Next", "下一步")));
+ lines.push(action_line(
+ "ov status",
+ copy(language, "Full system diagnostics", "查看完整系统诊断"),
+ ));
+ lines.push(action_line(
+ "ov config switch",
+ copy(language, "Use another config", "切换到其他配置"),
+ ));
+ lines.push(action_line(
+ "ov config",
+ copy(
+ language,
+ "Add, edit, or delete configs",
+ "添加、编辑或删除配置",
+ ),
+ ));
+
+ format!("{}\n", lines.join("\n"))
+}
+
+pub(crate) fn render_validate_failure(
+ config: &Config,
+ active_name: Option<&str>,
+ error: &Error,
+) -> String {
+ render_validate_failure_with_language(config, active_name, error, Language::current())
+}
+
+pub(crate) fn render_validate_failure_with_language(
+ config: &Config,
+ active_name: Option<&str>,
+ error: &Error,
+ language: Language,
+) -> String {
+ let mut lines = Vec::new();
+ let kind = kind_label(ConfigKind::from_config(config), language);
+ let active = active_name.unwrap_or_else(|| unknown(language));
+ let classification = ValidationFailureKind::from_error(error);
+
+ lines.push(title(copy(
+ language,
+ "OPENVIKING CONFIG CHECK",
+ "OPENVIKING 配置检查",
+ )));
+ lines.push(String::new());
+ lines.push(section(copy(language, "Config", "配置")));
+ lines.push(detail_line(
+ copy(language, "Active", "当前配置"),
+ active_value(active, kind),
+ ));
+ lines.push(detail_line(
+ copy(language, "Server", "服务器"),
+ path_value(&config.url),
+ ));
+ lines.push(detail_line(
+ copy(language, "Config home", "配置目录"),
+ path_value(&display_config_home()),
+ ));
+ lines.push(String::new());
+ lines.push(section(copy(language, "Checks", "检查项")));
+ lines.push(detail_line(
+ copy(language, "Config file", "配置文件"),
+ ok_value(copy(language, "valid", "有效")),
+ ));
+ lines.push(detail_line(
+ copy(language, "Server", "服务器"),
+ classification.server_check(language),
+ ));
+ lines.push(detail_line(
+ copy(language, "Auth", "认证"),
+ classification.auth_check(language),
+ ));
+ lines.push(detail_line(
+ copy(language, "Health", "健康状态"),
+ classification.health_check(language),
+ ));
+ lines.push(String::new());
+ lines.push(section(copy(language, "Issue", "问题")));
+ lines.push(format!(
+ " {}",
+ theme::error(classification.message(language))
+ ));
+ lines.push(String::new());
+ lines.push(section(copy(language, "Try", "可以尝试")));
+ lines.push(action_line(
+ "ov health",
+ copy(language, "Quick server probe", "快速检查服务器"),
+ ));
+ lines.push(action_line(
+ "ov config",
+ copy(language, "Edit this config", "编辑当前配置"),
+ ));
+ lines.push(action_line(
+ "ov config switch",
+ copy(language, "Use another config", "切换到其他配置"),
+ ));
+
+ format!("{}\n", lines.join("\n"))
+}
+
+pub(crate) fn render_switch_header(
+ active_name: Option<&str>,
+ active_kind: Option<ConfigKind>,
+) -> String {
+ let language = Language::current();
+ let mut lines = Vec::new();
+ lines.push(title(copy(
+ language,
+ "OPENVIKING CONFIG SWITCH",
+ "OPENVIKING 配置切换",
+ )));
+ lines.push(String::new());
+ match (active_name, active_kind) {
+ (Some(name), Some(kind)) => lines.push(format!(
+ "{} {}",
+ theme::muted(copy(language, "Active:", "当前配置:")),
+ active_value(name, kind_label(kind, language))
+ )),
+ _ => lines.push(format!(
+ "{} {}",
+ theme::muted(copy(language, "Active:", "当前配置:")),
+ unknown_value(copy(language, "none", "无"))
+ )),
+ }
+ format!("{}\n", lines.join("\n"))
+}
+
+pub(crate) fn switch_labels(rows: &[SwitchConfigRow]) -> Vec<String> {
+ let language = Language::current();
+ rows.iter()
+ .map(|row| {
+ let name = theme::command(pad_to_display_width(&row.name, NAME_WIDTH)).bold();
+ let kind = theme::strong(pad_to_display_width(
+ kind_label(row.kind, language),
+ KIND_WIDTH,
+ ));
+ if row.is_active {
+ format!(
+ "{name}{kind}{}",
+ theme::error(copy(language, "[Active]", "[当前]")).bold()
+ )
+ } else {
+ format!("{name}{kind}")
+ }
+ })
+ .collect()
+}
+
+pub(crate) fn render_no_saved_configs() -> String {
+ let language = Language::current();
+ let mut lines = Vec::new();
+ lines.push(title(copy(
+ language,
+ "OPENVIKING CONFIG SWITCH",
+ "OPENVIKING 配置切换",
+ )));
+ lines.push(String::new());
+ lines.push(section(copy(
+ language,
+ "No saved configs",
+ "没有已保存配置",
+ )));
+ lines.push(format!(
+ " {}",
+ theme::muted(copy(
+ language,
+ "Run ov config to add and save a config first.",
+ "请先运行 ov config 添加并保存配置。",
+ ))
+ ));
+ format!("{}\n", lines.join("\n"))
+}
+
+pub(crate) fn render_switch_success(name: &str) -> String {
+ let language = Language::current();
+ format!(
+ "{} {}\n{}\n",
+ theme::success("✓").bold(),
+ theme::success(copy_switch_success(language, name)).bold(),
+ format!(
+ " {}",
+ theme::muted(copy(
+ language,
+ "Run ov status to inspect it.",
+ "运行 ov status 查看状态。"
+ ))
+ )
+ )
+}
+
+pub(crate) fn render_switch_validation_failure(name: &str, error: &Error) -> String {
+ let language = Language::current();
+ let classification = ValidationFailureKind::from_error(error);
+ format!(
+ "{}\n\n{}\n {}\n {}\n\n{}",
+ title(copy(
+ language,
+ "OPENVIKING CONFIG SWITCH",
+ "OPENVIKING 配置切换"
+ )),
+ section(copy(language, "Issue", "问题")),
+ theme::error(copy_target_validation_failed(language, name)),
+ theme::muted(classification.message(language)),
+ action_line(
+ "ov config",
+ copy(language, "Edit this config", "编辑这个配置")
+ )
+ )
+}
+
+fn unknown(language: Language) -> &'static str {
+ copy(language, "unknown", "未知")
+}
+
+fn kind_label(kind: ConfigKind, language: Language) -> &'static str {
+ match language {
+ Language::En => kind.label(),
+ Language::ZhCn => match kind {
+ ConfigKind::VolcengineCloud => "火山引擎云",
+ ConfigKind::SelfManaged => "自托管",
+ },
+ }
+}
+
+fn copy_switch_success(language: Language, name: &str) -> String {
+ match language {
+ Language::En => format!("Switched active config to '{name}'."),
+ Language::ZhCn => format!("已切换当前配置为 '{name}'。"),
+ }
+}
+
+fn copy_target_validation_failed(language: Language, name: &str) -> String {
+ match language {
+ Language::En => format!("Target config '{name}' failed validation."),
+ Language::ZhCn => format!("目标配置 '{name}' 验证失败。"),
+ }
+}
+
+fn title(value: &str) -> String {
+ theme::brand_title(value).bold().to_string()
+}
+
+fn section(value: &str) -> String {
+ theme::heading(value).bold().to_string()
+}
+
+fn detail_line(label: &str, value: String) -> String {
+ let label = theme::muted(pad_to_display_width(label, LABEL_WIDTH));
+ format!(" {label}{value}")
+}
+
+fn action_line(command: &str, description: &str) -> String {
+ let command = theme::command(pad_to_display_width(command, ACTION_WIDTH)).bold();
+ format!(" {command}{}", theme::muted(description))
+}
+
+fn pad_to_display_width(value: &str, width: usize) -> String {
+ format!(
+ "{}{}",
+ value,
+ " ".repeat(width.saturating_sub(UnicodeWidthStr::width(value)))
+ )
+}
+
+fn active_value(name: &str, kind: &str) -> String {
+ format!(
+ "{} {}",
+ theme::config_name(name).bold(),
+ theme::strong(format!("({kind})"))
+ )
+}
+
+fn path_value(value: &str) -> String {
+ theme::value(value).to_string()
+}
+
+fn ok_value(value: &str) -> String {
+ theme::success(value).bold().to_string()
+}
+
+fn warn_value(value: &str) -> String {
+ theme::warning(value).bold().to_string()
+}
+
+fn fail_value(value: &str) -> String {
+ theme::error(value).bold().to_string()
+}
+
+fn unknown_value(value: &str) -> String {
+ theme::muted(value).to_string()
+}
+
+#[derive(Debug, Clone, Copy)]
+enum ValidationFailureKind {
+ Network,
+ Auth,
+ Unhealthy,
+ Other,
+}
+
+impl ValidationFailureKind {
+ fn from_error(error: &Error) -> Self {
+ match error {
+ Error::Network(message) if message.contains("unhealthy") => Self::Unhealthy,
+ Error::Network(_) => Self::Network,
+ Error::Api(message) if looks_like_auth_error(message) => Self::Auth,
+ _ => Self::Other,
+ }
+ }
+
+ fn server_check(self, language: Language) -> String {
+ match self {
+ Self::Network => fail_value(copy(language, "unreachable", "无法连接")),
+ Self::Auth | Self::Unhealthy => ok_value(copy(language, "reachable", "可连接")),
+ Self::Other => warn_value(unknown(language)),
+ }
+ }
+
+ fn auth_check(self, language: Language) -> String {
+ match self {
+ Self::Auth => fail_value(copy(language, "rejected", "被拒绝")),
+ Self::Network => warn_value(copy(language, "not checked", "未检查")),
+ Self::Unhealthy => ok_value(copy(language, "accepted", "已通过")),
+ Self::Other => warn_value(unknown(language)),
+ }
+ }
+
+ fn health_check(self, language: Language) -> String {
+ match self {
+ Self::Unhealthy => fail_value(copy(language, "unhealthy", "不健康")),
+ Self::Network | Self::Auth => warn_value(copy(language, "not checked", "未检查")),
+ Self::Other => warn_value(unknown(language)),
+ }
+ }
+
+ fn message(self, language: Language) -> &'static str {
+ match language {
+ Language::En => match self {
+ Self::Network => "Could not reach the configured OpenViking server.",
+ Self::Auth => "OpenViking rejected the API key for this config.",
+ Self::Unhealthy => "OpenViking is reachable but reported an unhealthy state.",
+ Self::Other => "The active config could not be validated.",
+ },
+ Language::ZhCn => match self {
+ Self::Network => "无法连接已配置的 OpenViking 服务器。",
+ Self::Auth => "OpenViking 拒绝了这个配置的 API Key。",
+ Self::Unhealthy => "服务器可连接,但健康状态异常。",
+ Self::Other => "当前配置验证失败。",
+ },
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::{config::Config, config_wizard::ConfigKind, error::Error};
+
+ #[test]
+ fn validate_success_rendering_is_styled_and_actionable() {
+ let config = sample_config();
+
+ colored::control::set_override(true);
+ let rendered = super::render_validate_success(&config, Some("VPS"));
+ colored::control::unset_override();
+
+ assert!(rendered.contains("\u{1b}["));
+
+ let plain = strip_ansi(&rendered);
+ assert!(plain.contains("OPENVIKING CONFIG CHECK"));
+ assert!(plain.contains("Active VPS (Self-Managed)"));
+ assert!(plain.contains("Server http://127.0.0.1:1933"));
+ assert!(plain.contains("Config file valid"));
+ assert!(plain.contains("Server reachable"));
+ assert!(plain.contains("Auth accepted"));
+ assert!(plain.contains("Health healthy"));
+ assert!(plain.contains("ov status Full system diagnostics"));
+ assert!(plain.contains("ov config switch Use another config"));
+ }
+
+ #[test]
+ fn validate_failure_rendering_hides_raw_error_and_suggests_recovery() {
+ let config = sample_config();
+ let error = Error::Network("connection refused at 127.0.0.1:1933".to_string());
+
+ let rendered = super::render_validate_failure(&config, Some("VPS"), &error);
+ let plain = strip_ansi(&rendered);
+
+ assert!(plain.contains("OPENVIKING CONFIG CHECK"));
+ assert!(plain.contains("Server unreachable"));
+ assert!(plain.contains("Auth not checked"));
+ assert!(plain.contains("Could not reach the configured OpenViking server."));
+ assert!(plain.contains("ov health Quick server probe"));
+ assert!(!plain.contains("connection refused"));
+ }
+
+ #[test]
+ fn switch_labels_mark_active_once_without_url() {
+ let labels = super::switch_labels(&[
+ super::SwitchConfigRow {
+ name: "local".to_string(),
+ kind: ConfigKind::SelfManaged,
+ is_active: true,
+ },
+ super::SwitchConfigRow {
+ name: "cloud-799f84".to_string(),
+ kind: ConfigKind::VolcengineCloud,
+ is_active: false,
+ },
+ ]);
+
+ let plain = strip_ansi(&labels.join("\n"));
+ assert!(plain.contains("local Self-Managed [Active]"));
+ assert!(plain.contains("cloud-799f84 Volcengine Cloud"));
+ assert_eq!(plain.matches("[Active]").count(), 1);
+ assert!(!plain.contains("http://"));
+ assert!(!plain.contains("https://"));
+ }
+
+ fn sample_config() -> Config {
+ Config {
+ url: "http://127.0.0.1:1933".to_string(),
+ ..Config::default()
+ }
+ }
+
+ 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.is_ascii_alphabetic() {
+ break;
+ }
+ }
+ continue;
+ }
+ output.push(ch);
+ }
+
+ output
+ }
+}
diff --git a/crates/ov_cli/src/config_wizard/mod.rs b/crates/ov_cli/src/config_wizard/mod.rs
new file mode 100644
index 000000000..5951f31fa
--- /dev/null
+++ b/crates/ov_cli/src/config_wizard/mod.rs
@@ -0,0 +1,6 @@
+mod store;
+mod wizard;
+
+pub(crate) use store::{ConfigKind, ConfigStore};
+pub use store::{redacted_config_value, validate_config};
+pub use wizard::run_config_wizard;
diff --git a/crates/ov_cli/src/config_wizard/store.rs b/crates/ov_cli/src/config_wizard/store.rs
new file mode 100644
index 000000000..e28773c9c
--- /dev/null
+++ b/crates/ov_cli/src/config_wizard/store.rs
@@ -0,0 +1,1089 @@
+use std::{
+ fs,
+ io::Write,
+ path::{Path, PathBuf},
+};
+
+use serde_json::Value;
+use url::Url;
+
+use crate::{
+ base_client::BaseClient,
+ config::{Config, DEFAULT_SELF_MANAGED_PORT, default_config_path},
+ error::{Error, Result},
+};
+
+pub const VOLCENGINE_CLOUD_URL: &str = "https://api.vikingdb.cn-beijing.volces.com/openviking";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ConfigKind {
+ VolcengineCloud,
+ SelfManaged,
+}
+
+impl ConfigKind {
+ pub(crate) fn label(self) -> &'static str {
+ match self {
+ Self::VolcengineCloud => "Volcengine Cloud",
+ Self::SelfManaged => "Self-Managed",
+ }
+ }
+
+ pub(crate) fn from_config(config: &Config) -> Self {
+ if config.url.trim_end_matches('/') == VOLCENGINE_CLOUD_URL {
+ Self::VolcengineCloud
+ } else {
+ Self::SelfManaged
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum ApiKeyRole {
+ Root,
+ Regular,
+}
+
+#[derive(Debug, Clone)]
+pub struct ConfigDraft {
+ pub name: String,
+ pub kind: ConfigKind,
+ pub url: String,
+ pub api_key: Option<String>,
+ pub account: Option<String>,
+ pub user: Option<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct ConfigEntry {
+ pub name: String,
+ pub config: Config,
+ pub is_active: bool,
+ pub kind: ConfigKind,
+}
+
+#[derive(Debug, Clone)]
+pub struct ConfigStore {
+ config_dir: PathBuf,
+ active_path: PathBuf,
+}
+
+impl ConfigStore {
+ pub fn new() -> Result<Self> {
+ let active_path = default_config_path()?;
+ let config_dir = active_path
+ .parent()
+ .ok_or_else(|| Error::Config("Could not determine config directory".to_string()))?
+ .to_path_buf();
+ Ok(Self {
+ config_dir,
+ active_path,
+ })
+ }
+
+ #[cfg(test)]
+ pub fn for_config_dir(config_dir: PathBuf) -> Self {
+ Self {
+ active_path: config_dir.join("ovcli.conf"),
+ config_dir,
+ }
+ }
+
+ pub fn active_path(&self) -> &Path {
+ &self.active_path
+ }
+
+ pub fn config_dir(&self) -> &Path {
+ &self.config_dir
+ }
+
+ pub fn saved_config_path(&self, name: &str) -> Result<PathBuf> {
+ validate_config_name(name)?;
+ Ok(self.config_dir.join(format!("ovcli.conf.{name}")))
+ }
+
+ pub fn load_active(&self) -> Result<Option<Config>> {
+ if !self.active_path.exists() {
+ return Ok(None);
+ }
+ Ok(Some(Config::from_file(
+ &self.active_path.to_string_lossy(),
+ )?))
+ }
+
+ pub fn list_configs(&self) -> Result<Vec<ConfigEntry>> {
+ let mut configs = Vec::new();
+
+ if !self.config_dir.exists() {
+ return Ok(configs);
+ }
+
+ for entry in fs::read_dir(&self.config_dir)? {
+ let entry = entry?;
+ let path = entry.path();
+ if !path.is_file() {
+ continue;
+ }
+
+ let Some(filename) = path.file_name().and_then(|value| value.to_str()) else {
+ continue;
+ };
+ let Some(name) = filename.strip_prefix("ovcli.conf.") else {
+ continue;
+ };
+ if name == "bak" || validate_config_name(name).is_err() {
+ continue;
+ }
+
+ let Ok(config) = Config::from_file(&path.to_string_lossy()) else {
+ eprintln!(
+ "Warning: skipped invalid OpenViking config '{}'",
+ path.display()
+ );
+ continue;
+ };
+
+ configs.push(ConfigEntry {
+ name: name.to_string(),
+ is_active: false,
+ kind: ConfigKind::from_config(&config),
+ config,
+ });
+ }
+
+ if !configs.is_empty() {
+ let active_config = self.load_active()?;
+ for entry in &mut configs {
+ entry.is_active = match active_config.as_ref() {
+ Some(active) => configs_equivalent(active, &entry.config)?,
+ None => false,
+ };
+ }
+ }
+
+ configs.sort_by(|left, right| left.name.cmp(&right.name));
+ normalize_active_config(&mut configs);
+ Ok(configs)
+ }
+
+ pub fn save_named_config(&self, name: &str, config: &Config) -> Result<()> {
+ let path = self.saved_config_path(name)?;
+ write_config_file(&path, config)
+ }
+
+ pub fn activate_config(&self, name: &str) -> Result<()> {
+ let path = self.saved_config_path(name)?;
+ if !path.exists() {
+ return Err(Error::Config(format!("Config '{name}' does not exist")));
+ }
+ let content = fs::read(&path)
+ .map_err(|e| Error::Config(format!("Failed to read config '{name}': {e}")))?;
+ write_file_atomically(&self.active_path, &content)
+ }
+
+ pub fn save_and_activate(&self, name: &str, config: &Config) -> Result<()> {
+ self.save_named_config(name, config)?;
+ write_config_file(&self.active_path, config)
+ }
+
+ pub fn save_edited_config(
+ &self,
+ old_name: &str,
+ new_name: &str,
+ config: &Config,
+ ) -> Result<()> {
+ let old_path = self.saved_config_path(old_name)?;
+ let new_path = self.saved_config_path(new_name)?;
+ let was_active = self.is_config_name_active(old_name)?;
+
+ if old_name != new_name && new_path.exists() {
+ return Err(Error::Config(format!("Config '{new_name}' already exists")));
+ }
+
+ self.save_named_config(new_name, config)?;
+ if was_active {
+ // Keep the active config consistent before removing the old saved file. If cleanup
+ // fails, the user may see both names, but the active config still points at the edit.
+ write_config_file(&self.active_path, config)?;
+ }
+
+ if old_name != new_name && old_path.exists() {
+ fs::remove_file(old_path).map_err(|e| {
+ Error::Config(format!("Failed to remove old config '{old_name}': {e}"))
+ })?;
+ }
+
+ Ok(())
+ }
+
+ pub fn delete_config(&self, name: &str) -> Result<()> {
+ if self.is_config_name_active(name)? {
+ return Err(Error::Config(
+ "Cannot delete the active config. Switch to another config first.".to_string(),
+ ));
+ }
+
+ let path = self.saved_config_path(name)?;
+ fs::remove_file(&path)
+ .map_err(|e| Error::Config(format!("Failed to delete config '{name}': {e}")))
+ }
+
+ pub fn is_config_name_active(&self, name: &str) -> Result<bool> {
+ let Some(active_config) = self.load_active()? else {
+ return Ok(false);
+ };
+ let path = self.saved_config_path(name)?;
+ if !path.exists() {
+ return Ok(false);
+ }
+ let Ok(saved_config) = Config::from_file(&path.to_string_lossy()) else {
+ return Ok(false);
+ };
+ if !configs_equivalent(&active_config, &saved_config)? {
+ return Ok(false);
+ }
+
+ // Saved configs are file copies, so duplicate files can be equivalent to the active
+ // config. Keep the UI's single-active invariant by treating the first equivalent saved
+ // config as active, matching list_configs().
+ Ok(self
+ .primary_equivalent_config_name(&active_config)?
+ .is_some_and(|active_name| active_name == name))
+ }
+
+ fn primary_equivalent_config_name(&self, active_config: &Config) -> Result<Option<String>> {
+ if !self.config_dir.exists() {
+ return Ok(None);
+ }
+
+ let mut names = Vec::new();
+ for entry in fs::read_dir(&self.config_dir)? {
+ let entry = entry?;
+ let path = entry.path();
+ if !path.is_file() {
+ continue;
+ }
+
+ let Some(filename) = path.file_name().and_then(|value| value.to_str()) else {
+ continue;
+ };
+ let Some(name) = filename.strip_prefix("ovcli.conf.") else {
+ continue;
+ };
+ if name == "bak" || validate_config_name(name).is_err() {
+ continue;
+ }
+
+ let Ok(config) = Config::from_file(&path.to_string_lossy()) else {
+ eprintln!(
+ "Warning: skipped invalid OpenViking config '{}'",
+ path.display()
+ );
+ continue;
+ };
+
+ if configs_equivalent(active_config, &config)? {
+ names.push(name.to_string());
+ }
+ }
+
+ names.sort();
+ Ok(names.into_iter().next())
+ }
+}
+
+fn normalize_active_config(configs: &mut [ConfigEntry]) {
+ let mut found_active = false;
+ for entry in configs {
+ if !entry.is_active {
+ continue;
+ }
+ if found_active {
+ entry.is_active = false;
+ } else {
+ found_active = true;
+ }
+ }
+}
+
+pub fn validate_config_name(name: &str) -> Result<()> {
+ let trimmed = name.trim();
+ if trimmed.is_empty() {
+ return Err(Error::Config("Config name cannot be empty".to_string()));
+ }
+ if trimmed != name {
+ return Err(Error::Config(
+ "Config name cannot start or end with whitespace".to_string(),
+ ));
+ }
+ if trimmed.starts_with('.') {
+ return Err(Error::Config(
+ "Config name cannot start with '.'".to_string(),
+ ));
+ }
+ if trimmed.contains('/') || trimmed.contains('\\') {
+ return Err(Error::Config(
+ "Config name cannot contain path separators".to_string(),
+ ));
+ }
+ if !trimmed
+ .chars()
+ .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')
+ {
+ return Err(Error::Config(
+ "Config name can only contain letters, numbers, '-' and '_'".to_string(),
+ ));
+ }
+ Ok(())
+}
+
+pub fn build_config(draft: &ConfigDraft) -> Result<Config> {
+ validate_config_name(&draft.name)?;
+
+ let mut config = Config::default();
+ let account = non_empty_option(draft.account.as_deref());
+ let user = non_empty_option(draft.user.as_deref());
+ 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())
+ })?;
+ config.url = VOLCENGINE_CLOUD_URL.to_string();
+ config.api_key = Some(api_key);
+ config.account = account;
+ config.user = user;
+ }
+ ConfigKind::SelfManaged => {
+ let url = normalize_self_managed_url(&draft.url);
+ if url.is_empty() {
+ return Err(Error::Config(
+ "Self-managed configs require a server URL".to_string(),
+ ));
+ }
+ let api_key = non_empty_option(draft.api_key.as_deref());
+ 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(),
+ ));
+ }
+ config.url = url.trim_end_matches('/').to_string();
+ config.api_key = api_key;
+ config.account = account;
+ config.user = user;
+ }
+ }
+
+ Ok(config)
+}
+
+pub(crate) fn self_managed_requires_api_key(url: &str) -> bool {
+ !self_managed_allows_empty_api_key(url)
+}
+
+pub(crate) fn self_managed_allows_empty_api_key(url: &str) -> bool {
+ let normalized = normalize_self_managed_url(url);
+ let Ok(parsed) = Url::parse(&normalized) else {
+ return false;
+ };
+ matches!(
+ parsed.host_str().map(|host| host.to_ascii_lowercase()),
+ Some(host) if matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1" | "[::1]")
+ )
+}
+
+pub(crate) fn normalize_self_managed_url(url: &str) -> String {
+ let trimmed = url.trim().trim_end_matches('/');
+ if trimmed.eq_ignore_ascii_case("::1") || trimmed.eq_ignore_ascii_case("[::1]") {
+ return format!("http://[::1]:{DEFAULT_SELF_MANAGED_PORT}");
+ }
+ if let Some(port) = trimmed.strip_prefix("[::1]:") {
+ if !port.trim().is_empty() {
+ return format!("http://[::1]:{port}");
+ }
+ }
+ if let Some(port) = trimmed.strip_prefix("::1:") {
+ if !port.trim().is_empty() {
+ return format!("http://[::1]:{port}");
+ }
+ }
+
+ if Url::parse(trimmed).is_ok() {
+ return trimmed.to_string();
+ }
+
+ let (host, port) = trimmed.split_once(':').unwrap_or((trimmed, ""));
+ if matches!(
+ host.to_ascii_lowercase().as_str(),
+ "localhost" | "127.0.0.1"
+ ) {
+ if port.trim().is_empty() {
+ format!("http://{host}:{DEFAULT_SELF_MANAGED_PORT}")
+ } else {
+ format!("http://{host}:{port}")
+ }
+ } else {
+ trimmed.to_string()
+ }
+}
+
+pub fn redacted_config_value(config: &Config) -> Result<Value> {
+ let mut value = serde_json::to_value(config)?;
+ if let Some(object) = value.as_object_mut() {
+ for key in ["api_key", "root_api_key"] {
+ if object.get(key).is_some_and(|value| !value.is_null()) {
+ object.insert(key.to_string(), Value::String("********".to_string()));
+ }
+ }
+ }
+ Ok(value)
+}
+
+pub async fn validate_config(config: &Config) -> Result<()> {
+ validate_candidate_config(config, false).await
+}
+
+pub(crate) async fn validate_candidate_config(
+ config: &Config,
+ require_api_key: bool,
+) -> Result<()> {
+ validate_candidate_config_with_role(config, require_api_key)
+ .await
+ .map(|_| ())
+}
+
+pub(crate) async fn validate_candidate_config_with_role(
+ config: &Config,
+ require_api_key: bool,
+) -> Result<Option<ApiKeyRole>> {
+ let api_key = non_empty_option(config.api_key.as_deref());
+ if require_api_key && api_key.is_none() {
+ return Err(Error::Config("API key is required".to_string()));
+ }
+
+ let timeout = config.timeout.clamp(1.0, 10.0);
+ let client = BaseClient::new(
+ &config.url,
+ api_key.clone(),
+ config.agent_id.clone(),
+ config.account.clone(),
+ config.user.clone(),
+ timeout,
+ config.profile,
+ config.extra_headers.clone(),
+ );
+
+ let value: Value = client.get("/health", &[]).await?;
+ if value
+ .get("healthy")
+ .and_then(Value::as_bool)
+ .is_some_and(|healthy| !healthy)
+ {
+ return Err(Error::Network(
+ "Server responded but reported unhealthy status".to_string(),
+ ));
+ }
+
+ if should_run_authenticated_probe(&value, require_api_key, api_key.is_some()) {
+ let _: Value = client.get("/api/v1/system/status", &[]).await?;
+ }
+
+ if api_key.is_some() {
+ return detect_api_key_role(&client).await.map(Some);
+ }
+
+ Ok(None)
+}
+
+async fn detect_api_key_role(client: &BaseClient) -> Result<ApiKeyRole> {
+ match client.get::<Value>("/api/v1/admin/accounts", &[]).await {
+ Ok(_) => Ok(ApiKeyRole::Root),
+ Err(Error::Api(_)) => Ok(ApiKeyRole::Regular),
+ Err(error) => Err(error),
+ }
+}
+
+fn should_run_authenticated_probe(
+ health: &Value,
+ 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")
+ )
+}
+
+pub(crate) fn validation_error_copy(kind: ConfigKind, _error: &Error) -> String {
+ match kind {
+ ConfigKind::VolcengineCloud => {
+ "Validation failed. Check your API key and try again.".to_string()
+ }
+ ConfigKind::SelfManaged => {
+ "Validation failed. Check the server URL and API key if required.".to_string()
+ }
+ }
+}
+
+fn write_config_file(path: &Path, config: &Config) -> Result<()> {
+ let content = serde_json::to_string_pretty(config)?;
+ write_file_atomically(path, content.as_bytes())
+}
+
+fn write_file_atomically(path: &Path, content: &[u8]) -> Result<()> {
+ let parent = path
+ .parent()
+ .ok_or_else(|| Error::Config("Could not determine config file directory".to_string()))?;
+ fs::create_dir_all(parent)?;
+
+ let mut temp_file = tempfile::Builder::new()
+ .prefix(".ovcli.conf.")
+ .suffix(".tmp")
+ .tempfile_in(parent)?;
+ temp_file.write_all(content)?;
+ temp_file.flush()?;
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut permissions = temp_file.as_file().metadata()?.permissions();
+ permissions.set_mode(0o600);
+ temp_file.as_file().set_permissions(permissions)?;
+ }
+
+ temp_file.as_file().sync_all()?;
+ temp_file.persist(path).map_err(|error| {
+ Error::Config(format!("Failed to replace config file: {}", error.error))
+ })?;
+
+ Ok(())
+}
+
+fn configs_equivalent(left: &Config, right: &Config) -> Result<bool> {
+ Ok(serde_json::to_value(left)? == serde_json::to_value(right)?)
+}
+
+fn non_empty_option(value: Option<&str>) -> Option<String> {
+ value
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(ToString::to_string)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ ApiKeyRole, ConfigDraft, ConfigKind, ConfigStore, VOLCENGINE_CLOUD_URL, build_config,
+ should_run_authenticated_probe, validate_candidate_config,
+ validate_candidate_config_with_role, validate_config_name, validation_error_copy,
+ };
+ use crate::config::Config;
+ use std::fs;
+ use std::path::{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()
+ .duration_since(UNIX_EPOCH)
+ .expect("clock should be valid")
+ .as_nanos();
+ std::env::temp_dir().join(format!("openviking-config-{name}-{suffix}"))
+ }
+
+ fn sample_config(url: &str, api_key: Option<&str>) -> Config {
+ let mut config = Config::default();
+ config.url = url.to_string();
+ config.api_key = api_key.map(ToString::to_string);
+ config
+ }
+
+ fn write_config(path: &Path, config: &Config) {
+ fs::write(
+ path,
+ serde_json::to_string_pretty(config).expect("config should serialize"),
+ )
+ .expect("config should be written");
+ }
+
+ #[test]
+ fn config_listing_ignores_active_config_and_bak_file() {
+ let dir = unique_dir("list");
+ fs::create_dir_all(&dir).expect("dir should exist");
+ write_config(
+ &dir.join("ovcli.conf"),
+ &sample_config("http://active", None),
+ );
+ write_config(
+ &dir.join("ovcli.conf.bak"),
+ &sample_config("http://backup", None),
+ );
+ write_config(
+ &dir.join("ovcli.conf.local"),
+ &sample_config("http://local", None),
+ );
+ fs::write(dir.join("ovcli.conf.notes.txt"), "{}").expect("notes file should be written");
+
+ let store = ConfigStore::for_config_dir(dir.clone());
+ let configs = store.list_configs().expect("configs should load");
+
+ assert_eq!(configs.len(), 1);
+ assert_eq!(configs[0].name, "local");
+ assert_eq!(configs[0].config.url, "http://local");
+ assert!(!configs[0].is_active);
+ }
+
+ #[test]
+ fn config_listing_skips_corrupted_saved_config() {
+ let dir = unique_dir("list-corrupted");
+ fs::create_dir_all(&dir).expect("dir should exist");
+ write_config(
+ &dir.join("ovcli.conf.local"),
+ &sample_config("http://local", None),
+ );
+ fs::write(dir.join("ovcli.conf.broken"), "{not json")
+ .expect("corrupted config should be written");
+
+ let store = ConfigStore::for_config_dir(dir);
+ let configs = store
+ .list_configs()
+ .expect("valid configs should still load");
+
+ assert_eq!(configs.len(), 1);
+ assert_eq!(configs[0].name, "local");
+ }
+
+ #[test]
+ fn config_listing_marks_only_one_duplicate_as_active() {
+ let dir = unique_dir("duplicate-active");
+ let store = ConfigStore::for_config_dir(dir.clone());
+ let config = sample_config("http://local", None);
+ store
+ .save_named_config("local", &config)
+ .expect("local config should save");
+ store
+ .save_named_config("local-copy", &config)
+ .expect("copy config should save");
+ store
+ .activate_config("local")
+ .expect("local config should become active");
+
+ let configs = store.list_configs().expect("configs should load");
+ let active = configs
+ .iter()
+ .filter(|entry| entry.is_active)
+ .map(|entry| entry.name.as_str())
+ .collect::<Vec<_>>();
+
+ assert_eq!(active, vec!["local"]);
+ assert!(store.is_config_name_active("local").expect("active check"));
+ assert!(
+ !store
+ .is_config_name_active("local-copy")
+ .expect("copy active check")
+ );
+ }
+
+ #[test]
+ fn cloud_config_listing_marks_only_one_duplicate_as_active() {
+ let dir = unique_dir("duplicate-cloud-active");
+ let store = ConfigStore::for_config_dir(dir.clone());
+ let config = sample_config(VOLCENGINE_CLOUD_URL, Some("cloud-key"));
+ store
+ .save_named_config("cloud", &config)
+ .expect("cloud config should save");
+ store
+ .save_named_config("cloud-copy", &config)
+ .expect("cloud copy config should save");
+ store
+ .activate_config("cloud")
+ .expect("cloud config should become active");
+
+ let configs = store.list_configs().expect("configs should load");
+ let active = configs
+ .iter()
+ .filter(|entry| entry.is_active)
+ .map(|entry| entry.name.as_str())
+ .collect::<Vec<_>>();
+
+ assert_eq!(active, vec!["cloud"]);
+ assert!(store.is_config_name_active("cloud").expect("active check"));
+ assert!(
+ !store
+ .is_config_name_active("cloud-copy")
+ .expect("copy active check")
+ );
+ }
+
+ #[test]
+ fn config_name_validation_rejects_unsafe_names() {
+ for name in ["", " ", ".hidden", "../prod", "prod/dev", "prod\\dev"] {
+ assert!(validate_config_name(name).is_err(), "{name:?} should fail");
+ }
+
+ assert!(validate_config_name("prod").is_ok());
+ assert!(validate_config_name("prod-cn-beijing_1").is_ok());
+ }
+
+ #[test]
+ fn volcengine_config_uses_fixed_url_and_requires_api_key() {
+ let missing_key = ConfigDraft {
+ name: "cloud".to_string(),
+ kind: ConfigKind::VolcengineCloud,
+ url: String::new(),
+ api_key: None,
+ account: None,
+ user: None,
+ };
+ assert!(build_config(&missing_key).is_err());
+
+ let draft = ConfigDraft {
+ api_key: Some("viking-key".to_string()),
+ ..missing_key
+ };
+ let config = build_config(&draft).expect("cloud config should build");
+
+ assert_eq!(config.url, VOLCENGINE_CLOUD_URL);
+ assert_eq!(config.api_key.as_deref(), Some("viking-key"));
+ }
+
+ #[test]
+ fn self_managed_config_accepts_custom_url_and_optional_key() {
+ let draft = ConfigDraft {
+ name: "local".to_string(),
+ kind: ConfigKind::SelfManaged,
+ url: "http://127.0.0.1:1933".to_string(),
+ api_key: None,
+ account: Some("default".to_string()),
+ user: Some("default".to_string()),
+ };
+ let without_key = build_config(&draft).expect("self-managed config should build");
+ assert_eq!(without_key.url, "http://127.0.0.1:1933");
+ assert!(without_key.api_key.is_none());
+ assert_eq!(without_key.account.as_deref(), Some("default"));
+ assert_eq!(without_key.user.as_deref(), Some("default"));
+
+ let with_key = build_config(&ConfigDraft {
+ api_key: Some("local-key".to_string()),
+ account: None,
+ user: None,
+ ..draft
+ })
+ .expect("self-managed config with key should build");
+ assert_eq!(with_key.api_key.as_deref(), Some("local-key"));
+ assert!(with_key.account.is_none());
+ assert!(with_key.user.is_none());
+ }
+
+ #[test]
+ fn remote_self_managed_config_requires_api_key() {
+ let draft = ConfigDraft {
+ name: "remote".to_string(),
+ kind: ConfigKind::SelfManaged,
+ url: "https://openviking.example.com".to_string(),
+ api_key: None,
+ account: Some("default".to_string()),
+ user: Some("default".to_string()),
+ };
+
+ let error = build_config(&draft).expect_err("remote self-managed requires key");
+
+ assert!(error.to_string().contains("API key"));
+ }
+
+ #[test]
+ fn bare_loopback_self_managed_urls_are_local_and_get_default_port() {
+ for (input, expected) in [
+ ("127.0.0.1", "http://127.0.0.1:1933"),
+ ("localhost", "http://localhost:1933"),
+ ("::1", "http://[::1]:1933"),
+ ("[::1]", "http://[::1]:1933"),
+ ("::1:1944", "http://[::1]:1944"),
+ ("[::1]:1944", "http://[::1]:1944"),
+ ] {
+ let draft = ConfigDraft {
+ name: "local".to_string(),
+ kind: ConfigKind::SelfManaged,
+ url: input.to_string(),
+ api_key: None,
+ account: Some("default".to_string()),
+ user: Some("default".to_string()),
+ };
+
+ let config = build_config(&draft)
+ .unwrap_or_else(|error| panic!("{input} should be treated as local: {error}"));
+
+ assert_eq!(config.url, expected);
+ }
+ }
+
+ #[tokio::test]
+ async fn api_key_role_detection_distinguishes_root_from_regular_keys() {
+ let url = spawn_role_probe_server("root-key", "regular-key").await;
+ let root_config = sample_config(&url, Some("root-key"));
+ let regular_config = sample_config(&url, Some("regular-key"));
+
+ let root_role = validate_candidate_config_with_role(&root_config, true)
+ .await
+ .expect("root key should validate");
+ let regular_role = validate_candidate_config_with_role(&regular_config, true)
+ .await
+ .expect("regular key should validate");
+
+ assert_eq!(root_role, Some(ApiKeyRole::Root));
+ assert_eq!(regular_role, Some(ApiKeyRole::Regular));
+ }
+
+ #[tokio::test]
+ async fn self_managed_config_with_api_key_validates_authenticated_probe() {
+ let url = spawn_auth_probe_server("good-key").await;
+ let config = sample_config(&url, Some("bad-key"));
+
+ let error = validate_candidate_config(&config, false)
+ .await
+ .expect_err("bad self-managed API key should fail validation");
+
+ 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" });
+ let api_key_health = serde_json::json!({ "healthy": true, "auth_mode": "api_key" });
+ let trusted_health = serde_json::json!({ "healthy": true, "auth_mode": "trusted" });
+
+ assert!(!should_run_authenticated_probe(&dev_health, false, false));
+ assert!(should_run_authenticated_probe(&dev_health, false, true));
+ assert!(should_run_authenticated_probe(&dev_health, true, false));
+ assert!(should_run_authenticated_probe(
+ &api_key_health,
+ false,
+ false
+ ));
+ assert!(should_run_authenticated_probe(
+ &trusted_health,
+ false,
+ false
+ ));
+ }
+
+ #[test]
+ fn validation_error_copy_hides_raw_backend_details() {
+ let error = crate::error::Error::Api(
+ "[AuthenticationError] invalid key. Request ID: 02177930089909800000000000000000ffff"
+ .to_string(),
+ );
+
+ let cloud = validation_error_copy(ConfigKind::VolcengineCloud, &error);
+ let self_managed = validation_error_copy(ConfigKind::SelfManaged, &error);
+
+ assert_eq!(
+ cloud,
+ "Validation failed. Check your API key and try again."
+ );
+ assert_eq!(
+ self_managed,
+ "Validation failed. Check the server URL and API key if required."
+ );
+ assert!(!cloud.contains("Request ID"));
+ assert!(!self_managed.contains("AuthenticationError"));
+ }
+
+ #[test]
+ fn edit_active_config_updates_active_config_and_saved_config() {
+ let dir = unique_dir("edit-active");
+ let store = ConfigStore::for_config_dir(dir.clone());
+ let original = sample_config("http://old", Some("old-key"));
+ store
+ .save_named_config("local", &original)
+ .expect("config should save");
+ store
+ .activate_config("local")
+ .expect("config should become active");
+
+ let edited = sample_config("http://new", Some("new-key"));
+ store
+ .save_edited_config("local", "renamed", &edited)
+ .expect("active edit should save");
+
+ let saved = Config::from_file(&dir.join("ovcli.conf.renamed").to_string_lossy())
+ .expect("renamed config should load");
+ let active = Config::from_file(&dir.join("ovcli.conf").to_string_lossy())
+ .expect("active config should load");
+
+ assert_eq!(saved.url, "http://new");
+ assert_eq!(active.url, "http://new");
+ assert!(!dir.join("ovcli.conf.local").exists());
+ }
+
+ #[test]
+ fn edit_duplicate_non_active_config_does_not_update_active_config() {
+ let dir = unique_dir("edit-duplicate");
+ let store = ConfigStore::for_config_dir(dir.clone());
+ let original = sample_config("http://local", None);
+ store
+ .save_named_config("local", &original)
+ .expect("local config should save");
+ store
+ .save_named_config("local-copy", &original)
+ .expect("copy config should save");
+ store
+ .activate_config("local")
+ .expect("local config should become active");
+
+ let edited = sample_config("http://copy", None);
+ store
+ .save_edited_config("local-copy", "local-copy", &edited)
+ .expect("copy edit should save");
+
+ let active = Config::from_file(&dir.join("ovcli.conf").to_string_lossy())
+ .expect("active config should load");
+ let copy = Config::from_file(&dir.join("ovcli.conf.local-copy").to_string_lossy())
+ .expect("copy config should load");
+
+ assert_eq!(active.url, "http://local");
+ assert_eq!(copy.url, "http://copy");
+ }
+
+ #[test]
+ fn delete_refuses_active_config() {
+ let dir = unique_dir("delete-active");
+ let store = ConfigStore::for_config_dir(dir.clone());
+ store
+ .save_named_config("local", &sample_config("http://local", None))
+ .expect("config should save");
+ store
+ .activate_config("local")
+ .expect("config should become active");
+
+ assert!(store.delete_config("local").is_err());
+ assert!(dir.join("ovcli.conf.local").exists());
+ }
+
+ #[test]
+ fn delete_duplicate_non_active_config_is_allowed() {
+ let dir = unique_dir("delete-duplicate");
+ let store = ConfigStore::for_config_dir(dir.clone());
+ let config = sample_config("http://local", None);
+ store
+ .save_named_config("local", &config)
+ .expect("local config should save");
+ store
+ .save_named_config("local-copy", &config)
+ .expect("copy config should save");
+ store
+ .activate_config("local")
+ .expect("local config should become active");
+
+ store
+ .delete_config("local-copy")
+ .expect("non-active duplicate should delete");
+
+ assert!(dir.join("ovcli.conf.local").exists());
+ assert!(!dir.join("ovcli.conf.local-copy").exists());
+ assert!(dir.join("ovcli.conf").exists());
+ }
+
+ async fn spawn_auth_probe_server(valid_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..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,"auth_mode":"api_key"}"#)
+ } else if request.starts_with("GET /api/v1/system/status ") {
+ let header = format!("x-api-key: {valid_api_key}");
+ if request.to_ascii_lowercase().contains(&header) {
+ http_response(200, r#"{"status":"ok","result":{"initialized":true}}"#)
+ } else {
+ http_response(
+ 401,
+ r#"{"error":{"code":"AuthenticationError","message":"invalid 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,
+ ) -> 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 regular_header = format!("x-api-key: {regular_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)
+ || lower_request.contains(&regular_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}")
+ }
+
+ fn http_response(status: u16, body: &str) -> String {
+ let reason = match status {
+ 200 => "OK",
+ 401 => "Unauthorized",
+ 404 => "Not Found",
+ _ => "OK",
+ };
+ format!(
+ "HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ )
+ }
+}
diff --git a/crates/ov_cli/src/config_wizard/wizard.rs b/crates/ov_cli/src/config_wizard/wizard.rs
new file mode 100644
index 000000000..e2ad77e59
--- /dev/null
+++ b/crates/ov_cli/src/config_wizard/wizard.rs
@@ -0,0 +1,3759 @@
+use std::{
+ env,
+ io::{self, Write},
+ path::Path,
+};
+
+use colored::Colorize;
+use crossterm::{
+ ExecutableCommand,
+ cursor::{Hide, MoveToColumn, MoveUp, Show},
+ event::{self, Event, KeyCode, KeyModifiers},
+ terminal::{Clear, ClearType, disable_raw_mode, enable_raw_mode},
+};
+use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
+use uuid::Uuid;
+
+use crate::{
+ base_client::BaseClient,
+ config::{Config, DEFAULT_SELF_MANAGED_URL},
+ error::{Error, Result},
+ i18n::{self, Language, copy},
+ theme::{self, Rgb},
+};
+use serde_json::Value;
+
+use super::store::{
+ ApiKeyRole, ConfigDraft, ConfigEntry, ConfigKind, ConfigStore, VOLCENGINE_CLOUD_URL,
+ build_config, self_managed_allows_empty_api_key, validate_candidate_config,
+ validate_candidate_config_with_role, validate_config_name, validation_error_copy,
+};
+
+const VOLCENGINE_API_KEY_URL: &str =
+ "https://console.volcengine.com/vikingdb/openviking/region:openviking+cn-beijing";
+const HEADER_TAGLINE: &str = "Context Database for AI Agents";
+const HEADER_TAGLINE_ZH: &str = "AI Agent 上下文数据库";
+const STATUS_BOX_PROBE_TIMEOUT_SECS: f64 = 3.0;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum IdentityMode {
+ LocalNoKey,
+ RootKey,
+}
+
+const OV_LOGO_LINES: [&str; 14] = [
+ "",
+ " ⢻⣶⣄",
+ " ⠈⣿⣿⣟⢦⡀",
+ " ⣿⣿⣿⡌⢻⣦⡀",
+ " ⣿⣿⣿⣧ ⠹⣿⣦⡀",
+ " ⢀⣿⣿⣿⣿ ⢹⣿⣷⡀",
+ " ⣼⣿⣿⣿⡟ ⠈⣿⣿⣷",
+ " ⢀⣼⣿⣿⣿⣿⣁⣀⣤⣤⣿⣿⣿⡄ ⡀",
+ " ⢀⣾⡿⠿⠛⢛⣿⣿⣿⣿⣿⣿⣿⣿⡇⢀⣼⠃",
+ " ⢀⣰⣿⣿⣿⣿⣿⠿⠟⠛⠋⣡⣿⠇",
+ " ⠠⣶⣾⣿⣿⣿⣶⣤⣀ ⠾⠟⠛⠉⠉ ⣀⣤⣾⡿⠃",
+ " ⠙⢿⣿⣿⣿⣿⣿⣿⣷⣶⣶⣶⣶⣶⣿⣿⣿⡿⠟⠁",
+ " ⠈⠛⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⠉",
+ " ⠈⠉⠉⠉⠁",
+];
+
+pub async fn run_config_wizard() -> Result<()> {
+ let store = ConfigStore::new()?;
+ run_config_wizard_with_store(store).await
+}
+
+async fn run_config_wizard_with_store(store: ConfigStore) -> Result<()> {
+ let mut ui = LiveRegion::default();
+ if !ensure_language_selected(&mut ui)? {
+ return Ok(());
+ }
+ print_header();
+ print_status_box(&store).await?;
+
+ loop {
+ let language = Language::current();
+ match prompt_select(
+ &mut ui,
+ copy(
+ language,
+ "What would you like to configure?",
+ "你想配置什么?",
+ ),
+ copy(language, "Choose action", "选择操作"),
+ &main_action_labels_for_language(language),
+ 0,
+ &[],
+ )? {
+ PromptResult::Value(0) => {
+ if run_add_config(&store, &mut ui).await? {
+ return Ok(());
+ }
+ }
+ PromptResult::Value(1) => {
+ if run_edit_config(&store, &mut ui).await? {
+ return Ok(());
+ }
+ }
+ PromptResult::Value(2) => {
+ if run_delete_config(&store, &mut ui)? {
+ return Ok(());
+ }
+ }
+ PromptResult::Back | PromptResult::Quit => {
+ print_cancelled(&mut ui)?;
+ return Ok(());
+ }
+ PromptResult::Value(_) => unreachable!("selection is constrained by action list"),
+ }
+ }
+}
+
+fn ensure_language_selected(ui: &mut LiveRegion) -> Result<bool> {
+ if i18n::has_saved_language() {
+ return Ok(true);
+ }
+
+ let choices = ["English", "简体中文"];
+ match prompt_select(
+ ui,
+ "Language / 语言",
+ "Choose display language / 选择显示语言",
+ &choices,
+ 0,
+ &[format!(
+ "{} {}",
+ theme::muted("Change later:"),
+ theme::command("ov language").bold()
+ )],
+ )? {
+ PromptResult::Value(0) => i18n::save_language(Language::En)?,
+ PromptResult::Value(1) => i18n::save_language(Language::ZhCn)?,
+ PromptResult::Back | PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(false);
+ }
+ PromptResult::Value(_) => unreachable!("selection is constrained by language list"),
+ }
+
+ ui.clear()?;
+ Ok(true)
+}
+
+pub(crate) fn wizard_header_lines() -> Vec<String> {
+ let mut lines: Vec<String> = wordmark_lines()
+ .iter()
+ .map(|line| (*line).to_string())
+ .collect();
+ lines.push(String::new());
+ lines
+}
+
+pub(crate) fn wordmark_width() -> usize {
+ wordmark_lines()
+ .iter()
+ .map(|line| display_width(line))
+ .max()
+ .unwrap_or_default()
+}
+
+fn wordmark_lines() -> [&'static str; 6] {
+ [
+ " ██████╗ ██████╗ ███████╗███╗ ██╗██╗ ██╗ ██╗ ██╗ ██╗ ██╗ ███╗ ██╗ ██████╗ ",
+ "██╔═══██╗██╔══██╗██╔════╝████╗ ██║██║ ██║ ██║ ██║ ██╔╝ ██║ ████╗ ██║██╔════╝ ",
+ "██║ ██║██████╔╝█████╗ ██╔██╗ ██║██║ ██║ ██║ █████╔╝ ██║ ██╔██╗ ██║██║ ███╗",
+ "██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║╚██╗ ██╔╝ ██║ ██╔═██╗ ██║ ██║╚██╗██║██║ ██║",
+ "╚██████╔╝██║ ███████╗██║ ╚████║ ╚████╔╝ ██║ ██║ ██╗ ██║ ██║ ╚████║╚██████╔╝",
+ " ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ",
+ ]
+}
+
+fn header_version_text() -> String {
+ format!("v{}", env!("OPENVIKING_CLI_VERSION"))
+}
+
+fn status_box_width() -> usize {
+ wordmark_width()
+}
+
+fn nav_hint() -> &'static str {
+ copy(
+ Language::current(),
+ "↑/↓ choose · Enter select · Esc back · Ctrl+C exit",
+ "↑/↓ 选择 · Enter 确认 · Esc 返回 · Ctrl+C 退出",
+ )
+}
+
+fn input_hint() -> &'static str {
+ copy(
+ Language::current(),
+ "Enter continue · Esc back · Ctrl+C exit",
+ "Enter 继续 · Esc 返回 · Ctrl+C 退出",
+ )
+}
+
+fn section_add() -> &'static str {
+ copy(
+ Language::current(),
+ "Create a new OpenViking config.",
+ "创建新的 OpenViking 配置。",
+ )
+}
+
+fn section_edit() -> &'static str {
+ copy(
+ Language::current(),
+ "Update a saved config.",
+ "更新已保存的配置。",
+ )
+}
+
+fn section_delete() -> &'static str {
+ copy(
+ Language::current(),
+ "Delete a saved config.",
+ "删除已保存的配置。",
+ )
+}
+
+fn kind_label(kind: ConfigKind) -> &'static str {
+ match Language::current() {
+ Language::En => kind.label(),
+ Language::ZhCn => match kind {
+ ConfigKind::VolcengineCloud => "火山引擎云",
+ ConfigKind::SelfManaged => "自托管",
+ },
+ }
+}
+
+fn provider_labels(language: Language) -> [&'static str; 2] {
+ match language {
+ Language::En => ["Volcengine Cloud", "Self-Managed"],
+ Language::ZhCn => ["火山引擎云", "自托管"],
+ }
+}
+
+fn api_key_label(optional: bool) -> &'static str {
+ match (Language::current(), optional) {
+ (Language::En, true) => "API key (optional)",
+ (Language::En, false) => "API key",
+ (Language::ZhCn, true) => "API Key(可选)",
+ (Language::ZhCn, false) => "API Key",
+ }
+}
+
+pub(crate) fn main_action_labels() -> [&'static str; 3] {
+ ["Add config", "Edit config", "Delete config"]
+}
+
+fn main_action_labels_for_language(language: Language) -> [&'static str; 3] {
+ match language {
+ Language::En => main_action_labels(),
+ Language::ZhCn => ["添加配置", "编辑配置", "删除配置"],
+ }
+}
+
+pub(crate) fn cloud_validation_failure_choices() -> [&'static str; 2] {
+ ["Retry API key", "Cancel"]
+}
+
+fn cloud_validation_failure_choices_for_language(language: Language) -> [&'static str; 2] {
+ match language {
+ Language::En => cloud_validation_failure_choices(),
+ Language::ZhCn => ["重新输入 API Key", "取消"],
+ }
+}
+
+pub(crate) fn self_managed_validation_failure_choices() -> [&'static str; 3] {
+ ["Edit server URL", "Edit API key", "Cancel"]
+}
+
+fn self_managed_validation_failure_choices_for_language(language: Language) -> [&'static str; 3] {
+ match language {
+ Language::En => self_managed_validation_failure_choices(),
+ Language::ZhCn => ["修改服务器 URL", "修改 API Key", "取消"],
+ }
+}
+
+pub(crate) fn edit_api_key_choice_labels(
+ kind: ConfigKind,
+ has_existing: bool,
+) -> Vec<&'static str> {
+ if !has_existing {
+ return Vec::new();
+ }
+
+ match kind {
+ ConfigKind::VolcengineCloud => vec!["Keep existing API key", "Replace API key"],
+ ConfigKind::SelfManaged => {
+ vec!["Keep existing API key", "Replace API key", "Clear API key"]
+ }
+ }
+}
+
+fn edit_api_key_choice_labels_for_language(
+ kind: ConfigKind,
+ has_existing: bool,
+ language: Language,
+) -> Vec<&'static str> {
+ if language == Language::En {
+ return edit_api_key_choice_labels(kind, has_existing);
+ }
+
+ if !has_existing {
+ return Vec::new();
+ }
+
+ match kind {
+ ConfigKind::VolcengineCloud => vec!["保留现有 API Key", "替换 API Key"],
+ ConfigKind::SelfManaged => vec!["保留现有 API Key", "替换 API Key", "清除 API Key"],
+ }
+}
+
+pub(crate) fn should_prompt_root_identity(
+ api_key_role: Option<ApiKeyRole>,
+ api_key_was_entered: bool,
+ account: Option<&str>,
+ user: Option<&str>,
+) -> bool {
+ api_key_role == Some(ApiKeyRole::Root)
+ && (api_key_was_entered || is_blank(account) || is_blank(user))
+}
+
+fn print_header() {
+ let lines = wizard_header_lines();
+ println!();
+ for (index, line) in lines.iter().take(wordmark_lines().len()).enumerate() {
+ println!("{}", styled_wordmark_line(index, line));
+ }
+}
+
+fn styled_wordmark_line(_index: usize, line: &str) -> String {
+ let width = wordmark_width().max(1);
+ let mut rendered = String::new();
+
+ for (column, ch) in line.chars().enumerate() {
+ 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(),
+ );
+ }
+ }
+
+ rendered
+}
+
+pub(crate) fn wordmark_gradient_color(column: usize, width: usize) -> Rgb {
+ wordmark_gradient_color_for_theme(theme::active_theme(), column, width)
+}
+
+fn wordmark_gradient_color_for_theme(palette: theme::CliTheme, column: usize, width: usize) -> Rgb {
+ if width <= 1 {
+ return palette.wordmark_start;
+ }
+
+ let ratio = column as f32 / (width - 1) as f32;
+ if ratio <= 0.56 {
+ interpolate_rgb(palette.wordmark_start, palette.wordmark_mid, ratio / 0.56)
+ } else {
+ interpolate_rgb(
+ palette.wordmark_mid,
+ palette.wordmark_end,
+ (ratio - 0.56) / 0.44,
+ )
+ }
+}
+
+fn interpolate_rgb(start: Rgb, end: Rgb, ratio: f32) -> Rgb {
+ let ratio = ratio.clamp(0.0, 1.0);
+ Rgb(
+ interpolate_channel(start.0, end.0, ratio),
+ interpolate_channel(start.1, end.1, ratio),
+ interpolate_channel(start.2, end.2, ratio),
+ )
+}
+
+fn interpolate_channel(start: u8, end: u8, ratio: f32) -> u8 {
+ (start as f32 + (end as f32 - start as f32) * ratio).round() as u8
+}
+
+fn tagline_ice_color_for_theme(palette: theme::CliTheme, column: usize, width: usize) -> Rgb {
+ if width <= 1 {
+ return palette.tagline_start;
+ }
+
+ let midpoint = width / 2;
+ if column <= midpoint {
+ let ratio = if midpoint == 0 {
+ 0.0
+ } else {
+ column as f32 / midpoint as f32
+ };
+ interpolate_rgb(palette.tagline_start, palette.tagline_mid, ratio)
+ } else {
+ let tail_width = (width - 1).saturating_sub(midpoint).max(1);
+ let ratio = (column - midpoint) as f32 / tail_width as f32;
+ interpolate_rgb(palette.tagline_mid, palette.tagline_end, ratio)
+ }
+}
+
+fn tagline_texture_color(column: usize, width: usize) -> Rgb {
+ let palette = theme::active_theme();
+ let base = tagline_ice_color_for_theme(palette, column, width);
+ let ratio = if width <= 1 {
+ 0.0
+ } else {
+ column as f32 / (width - 1) as f32
+ };
+ let center_glow = (1.0 - (ratio - 0.5).abs() * 2.0).clamp(0.0, 1.0);
+
+ mix_rgb(base, palette.wordmark_start, center_glow * 0.18)
+}
+
+fn mix_rgb(base: Rgb, overlay: Rgb, amount: f32) -> Rgb {
+ interpolate_rgb(base, overlay, amount)
+}
+
+fn styled_tagline(text: &str) -> String {
+ let width = display_width(text).max(1);
+ let mut rendered = String::new();
+ let mut column = 0usize;
+
+ for ch in text.chars() {
+ 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(),
+ );
+ }
+ column += UnicodeWidthChar::width(ch).unwrap_or(0);
+ }
+
+ rendered
+}
+
+async fn print_status_box(store: &ConfigStore) -> Result<()> {
+ let configs = store.list_configs()?;
+ let active = store.load_active()?;
+ let config_home = display_config_home(store);
+ let Some(active_config) = active.as_ref() else {
+ print_status_box_with_runtime(
+ active.as_ref(),
+ &configs,
+ &config_home,
+ &StatusBoxRuntime::not_configured(),
+ )?;
+ return Ok(());
+ };
+
+ let rendered_lines = print_status_box_with_runtime(
+ active.as_ref(),
+ &configs,
+ &config_home,
+ &StatusBoxRuntime::checking(),
+ )?;
+ let runtime = status_box_runtime(Some(active_config)).await;
+ clear_live_region(rendered_lines, false)?;
+ print_status_box_with_runtime(active.as_ref(), &configs, &config_home, &runtime)?;
+
+ Ok(())
+}
+
+fn print_status_box_with_runtime(
+ active: Option<&Config>,
+ configs: &[ConfigEntry],
+ config_home: &str,
+ runtime: &StatusBoxRuntime,
+) -> Result<usize> {
+ let width = status_box_width();
+
+ println!();
+ println!(
+ "{}",
+ styled_box_title_line(
+ copy(Language::current(), HEADER_TAGLINE, HEADER_TAGLINE_ZH),
+ width
+ )
+ );
+ let details = status_box_details(active, configs, config_home, runtime);
+ let rows = OV_LOGO_LINES.len().max(details.len());
+ let details = center_status_box_details(details, rows);
+ for index in 0..rows {
+ let logo = OV_LOGO_LINES.get(index).copied().unwrap_or("");
+ let detail = details.get(index).unwrap_or(&StatusBoxDetail::Empty);
+ println!("{}", styled_box_content_line(logo, detail, width, index));
+ }
+ println!("{}", styled_box_footer_line(&header_version_text(), width));
+ println!();
+ io::stdout().flush()?;
+ Ok(rows + 4)
+}
+
+#[cfg(test)]
+pub(crate) fn status_box_lines(
+ active: Option<&Config>,
+ configs: &[ConfigEntry],
+ config_home: &str,
+) -> Vec<String> {
+ status_box_lines_with_runtime(active, configs, config_home, &StatusBoxRuntime::unknown())
+}
+
+#[cfg(test)]
+fn status_box_lines_with_runtime(
+ active: Option<&Config>,
+ configs: &[ConfigEntry],
+ config_home: &str,
+ runtime: &StatusBoxRuntime,
+) -> Vec<String> {
+ let width = status_box_width();
+ let details = status_box_details(active, configs, config_home, runtime);
+ let rows = OV_LOGO_LINES.len().max(details.len());
+ let details = center_status_box_details(details, rows);
+ let mut lines = Vec::with_capacity(rows + 2);
+
+ lines.push(box_title_line(HEADER_TAGLINE, width));
+ for index in 0..rows {
+ lines.push(box_content_line(
+ OV_LOGO_LINES.get(index).copied().unwrap_or(""),
+ details
+ .get(index)
+ .map(StatusBoxDetail::plain)
+ .unwrap_or_default()
+ .as_str(),
+ width,
+ ));
+ }
+ lines.push(box_footer_line(&header_version_text(), width));
+ lines
+}
+
+async fn status_box_runtime(active: Option<&Config>) -> StatusBoxRuntime {
+ let Some(config) = active else {
+ return StatusBoxRuntime::not_configured();
+ };
+
+ let client = BaseClient::new(
+ config.url.clone(),
+ config.api_key.clone(),
+ config.agent_id.clone(),
+ config.account.clone(),
+ config.user.clone(),
+ STATUS_BOX_PROBE_TIMEOUT_SECS,
+ config.profile,
+ config.extra_headers.clone(),
+ );
+
+ match client.get::<Value>("/api/v1/system/status", &[]).await {
+ Ok(status) => {
+ let healthy = status_payload_is_healthy(&status);
+ let runtime = StatusBoxRuntime::connected(healthy, None, None)
+ .with_missing_models(extract_models_from_status_payload(&status));
+
+ if runtime.vlm_model.is_some() && runtime.embedding_model.is_some() {
+ runtime
+ } else {
+ runtime.with_missing_models(fetch_observer_models(&client).await)
+ }
+ }
+ Err(_) => match client.get::<Value>("/health", &[]).await {
+ Ok(health) => {
+ let healthy = health
+ .get("healthy")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ StatusBoxRuntime::connected(healthy, None, None)
+ .with_missing_models(fetch_observer_models(&client).await)
+ }
+ Err(_) => StatusBoxRuntime::unreachable(),
+ },
+ }
+}
+
+fn status_payload_is_healthy(value: &Value) -> bool {
+ status_payload_health(value).unwrap_or(true)
+}
+
+fn status_payload_health(value: &Value) -> Option<bool> {
+ if let Some(healthy) = value
+ .get("is_healthy")
+ .or_else(|| value.get("healthy"))
+ .and_then(Value::as_bool)
+ {
+ return Some(healthy);
+ }
+
+ let Some(components) = value.get("components").and_then(Value::as_object) else {
+ return None;
+ };
+
+ if components.is_empty() {
+ return None;
+ }
+
+ Some(components.values().all(|component| {
+ component.get("is_healthy").and_then(Value::as_bool) != Some(false)
+ && component.get("has_errors").and_then(Value::as_bool) != Some(true)
+ }))
+}
+
+async fn fetch_observer_models(client: &BaseClient) -> (Option<String>, Option<String>) {
+ client
+ .get::<Value>("/api/v1/observer/models", &[])
+ .await
+ .map(|models| extract_models_from_status_payload(&models))
+ .unwrap_or((None, None))
+}
+
+fn extract_models_from_status_payload(value: &Value) -> (Option<String>, Option<String>) {
+ let status_text = value
+ .pointer("/components/models/status")
+ .and_then(Value::as_str)
+ .or_else(|| value.get("status").and_then(Value::as_str));
+
+ status_text
+ .map(extract_models_from_status_text)
+ .unwrap_or((None, None))
+}
+
+fn extract_models_from_status_text(status: &str) -> (Option<String>, Option<String>) {
+ (
+ extract_first_model_after_heading(status, "VLM Models:"),
+ extract_first_model_after_heading(status, "Embedding Models:"),
+ )
+}
+
+fn extract_first_model_after_heading(status: &str, heading: &str) -> Option<String> {
+ let (_, section) = status.split_once(heading)?;
+
+ for line in section.lines() {
+ let trimmed = line.trim();
+ if trimmed.ends_with("Models:") && trimmed != heading {
+ break;
+ }
+ if !trimmed.starts_with('|') {
+ continue;
+ }
+
+ let cells = trimmed
+ .trim_matches('|')
+ .split('|')
+ .map(str::trim)
+ .collect::<Vec<_>>();
+ let model = cells.first().copied().unwrap_or_default();
+ if model.is_empty() || model.eq_ignore_ascii_case("model") {
+ continue;
+ }
+
+ return Some(model.to_string());
+ }
+
+ None
+}
+
+pub(crate) fn display_config_home(store: &ConfigStore) -> String {
+ let Some(home) = env::var_os("HOME") else {
+ return store.config_dir().display().to_string();
+ };
+ display_config_home_for_home(store.config_dir(), Path::new(&home))
+}
+
+fn display_config_home_for_home(config_dir: &Path, home: &Path) -> String {
+ match config_dir.strip_prefix(home) {
+ Ok(relative) if relative.as_os_str().is_empty() => "~".to_string(),
+ Ok(relative) => format!("~/{}", relative.display()),
+ Err(_) => config_dir.display().to_string(),
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct StatusBoxRuntime {
+ connection: RuntimeConnectionStatus,
+ vlm_model: Option<String>,
+ embedding_model: Option<String>,
+}
+
+impl StatusBoxRuntime {
+ fn checking() -> Self {
+ Self {
+ connection: RuntimeConnectionStatus::Checking,
+ vlm_model: None,
+ embedding_model: None,
+ }
+ }
+
+ fn not_configured() -> Self {
+ Self {
+ connection: RuntimeConnectionStatus::NotConfigured,
+ vlm_model: None,
+ embedding_model: None,
+ }
+ }
+
+ #[cfg(test)]
+ fn unknown() -> Self {
+ Self {
+ connection: RuntimeConnectionStatus::Unknown,
+ vlm_model: None,
+ embedding_model: None,
+ }
+ }
+
+ fn connected(
+ healthy: bool,
+ vlm_model: Option<String>,
+ embedding_model: Option<String>,
+ ) -> Self {
+ Self {
+ connection: if healthy {
+ RuntimeConnectionStatus::ConnectedHealthy
+ } else {
+ RuntimeConnectionStatus::ConnectedUnhealthy
+ },
+ vlm_model,
+ embedding_model,
+ }
+ }
+
+ fn unreachable() -> Self {
+ Self {
+ connection: RuntimeConnectionStatus::Unreachable,
+ vlm_model: None,
+ embedding_model: None,
+ }
+ }
+
+ fn with_missing_models(mut self, models: (Option<String>, Option<String>)) -> Self {
+ if self.vlm_model.is_none() {
+ self.vlm_model = models.0;
+ }
+ if self.embedding_model.is_none() {
+ self.embedding_model = models.1;
+ }
+ self
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum RuntimeConnectionStatus {
+ Checking,
+ NotConfigured,
+ ConnectedHealthy,
+ ConnectedUnhealthy,
+ Unreachable,
+ #[cfg(test)]
+ Unknown,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SaveAction {
+ SaveAndActivate,
+ SaveOnly,
+ SaveActive,
+ Cancel,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SaveOutcome {
+ Activated,
+ SavedOnly,
+ UpdatedActive,
+}
+
+impl RuntimeConnectionStatus {
+ fn plain(self) -> &'static str {
+ match Language::current() {
+ Language::En => match self {
+ Self::Checking => "Checking...",
+ Self::NotConfigured => "Not configured",
+ Self::ConnectedHealthy => "Connected (Healthy)",
+ Self::ConnectedUnhealthy => "Connected (Unhealthy)",
+ Self::Unreachable => "Unreachable",
+ #[cfg(test)]
+ Self::Unknown => "Unknown",
+ },
+ Language::ZhCn => match self {
+ Self::Checking => "检查中...",
+ Self::NotConfigured => "未配置",
+ Self::ConnectedHealthy => "已连接(健康)",
+ Self::ConnectedUnhealthy => "已连接(不健康)",
+ Self::Unreachable => "无法连接",
+ #[cfg(test)]
+ Self::Unknown => "未知",
+ },
+ }
+ }
+
+ fn styled(self) -> String {
+ match self {
+ Self::Checking => theme::value(self.plain()).bold().to_string(),
+ Self::ConnectedHealthy => theme::success(self.plain()).bold().to_string(),
+ Self::ConnectedUnhealthy => theme::warning(self.plain()).bold().to_string(),
+ Self::Unreachable => theme::error(self.plain()).bold().to_string(),
+ Self::NotConfigured => theme::muted(self.plain()).to_string(),
+ #[cfg(test)]
+ Self::Unknown => theme::muted(self.plain()).to_string(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum StatusBoxDetail {
+ Active { name: String, kind: Option<String> },
+ Status { connection: RuntimeConnectionStatus },
+ Model { label: &'static str, value: String },
+ Saved { count: String },
+ Home { path: String },
+ Empty,
+}
+
+impl StatusBoxDetail {
+ fn plain(&self) -> String {
+ match self {
+ Self::Active { name, kind } => match kind {
+ Some(kind) => format!("{} {name} {kind}", status_label("Active:")),
+ None => format!("{} {name}", status_label("Active:")),
+ },
+ Self::Status { connection } => {
+ format!("{} {}", status_label("Status:"), connection.plain())
+ }
+ Self::Model { label, value } => format!("{label}: {value}"),
+ Self::Saved { count } => format!("{} {count}", status_label("Saved configs:")),
+ Self::Home { path } => format!("{} {path}", status_label("Config home:")),
+ Self::Empty => String::new(),
+ }
+ }
+
+ fn styled(&self) -> String {
+ match self {
+ Self::Active { name, kind } => {
+ let mut rendered = format!(
+ "{} {}",
+ theme::muted(status_label("Active:")),
+ theme::config_name(name).bold()
+ );
+ if let Some(kind) = kind {
+ rendered.push(' ');
+ rendered.push_str(&theme::strong(kind).to_string());
+ }
+ rendered
+ }
+ Self::Status { connection } => {
+ format!(
+ "{} {}",
+ theme::muted(status_label("Status:")),
+ connection.styled()
+ )
+ }
+ Self::Model { label, value } => {
+ let value = if value == unknown_copy() {
+ theme::muted(value).to_string()
+ } else {
+ theme::sky_value(value).bold().to_string()
+ };
+ format!("{} {}", theme::muted(format!("{label}:")), value)
+ }
+ Self::Saved { count } => {
+ format!(
+ "{} {}",
+ theme::muted(status_label("Saved configs:")),
+ theme::strong(count)
+ )
+ }
+ Self::Home { path } => {
+ format!(
+ "{} {}",
+ theme::muted(status_label("Config home:")),
+ theme::sky_value(path).bold()
+ )
+ }
+ Self::Empty => String::new(),
+ }
+ }
+}
+
+fn status_label(label: &'static str) -> &'static str {
+ match (Language::current(), label) {
+ (Language::ZhCn, "Active:") => "当前配置:",
+ (Language::ZhCn, "Status:") => "状态:",
+ (Language::ZhCn, "Saved configs:") => "已保存配置:",
+ (Language::ZhCn, "Config home:") => "配置目录:",
+ _ => label,
+ }
+}
+
+fn status_box_details(
+ active: Option<&Config>,
+ configs: &[ConfigEntry],
+ config_home: &str,
+ runtime: &StatusBoxRuntime,
+) -> Vec<StatusBoxDetail> {
+ let summary = active_summary_lines(active, configs);
+ let active = summary
+ .first()
+ .and_then(|line| active_summary_render_parts(line))
+ .map(|parts| StatusBoxDetail::Active {
+ name: parts.name,
+ kind: parts.kind,
+ })
+ .unwrap_or(StatusBoxDetail::Active {
+ name: "none".to_string(),
+ kind: None,
+ });
+ let saved = summary
+ .get(1)
+ .and_then(|line| saved_summary_render_parts(line))
+ .map(|parts| StatusBoxDetail::Saved { count: parts.count })
+ .unwrap_or(StatusBoxDetail::Saved {
+ count: "0".to_string(),
+ });
+
+ vec![
+ active,
+ StatusBoxDetail::Status {
+ connection: runtime.connection,
+ },
+ StatusBoxDetail::Model {
+ label: "VLM",
+ value: runtime
+ .vlm_model
+ .clone()
+ .unwrap_or_else(|| model_placeholder(runtime.connection)),
+ },
+ StatusBoxDetail::Model {
+ label: "Embedding",
+ value: runtime
+ .embedding_model
+ .clone()
+ .unwrap_or_else(|| model_placeholder(runtime.connection)),
+ },
+ saved,
+ StatusBoxDetail::Home {
+ path: config_home.to_string(),
+ },
+ ]
+}
+
+fn model_placeholder(connection: RuntimeConnectionStatus) -> String {
+ if connection == RuntimeConnectionStatus::Checking {
+ copy(Language::current(), "Checking...", "检查中...").to_string()
+ } else {
+ unknown_copy().to_string()
+ }
+}
+
+fn unknown_copy() -> &'static str {
+ copy(Language::current(), "Unknown", "未知")
+}
+
+fn center_status_box_details(details: Vec<StatusBoxDetail>, rows: usize) -> Vec<StatusBoxDetail> {
+ let top_padding = rows.saturating_sub(details.len()) / 2;
+ let mut centered = Vec::with_capacity(rows);
+ centered.extend(std::iter::repeat_n(StatusBoxDetail::Empty, top_padding));
+ centered.extend(details);
+ centered.resize(rows, StatusBoxDetail::Empty);
+ centered
+}
+
+#[cfg(test)]
+fn box_title_line(title: &str, width: usize) -> String {
+ let inner_width = width.saturating_sub(2);
+ let title = format!(" {title} ");
+ let visible_title = truncate_to_width(&title, inner_width);
+ 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);
+
+ format!(
+ "╭{}{}{}╮",
+ "─".repeat(left),
+ visible_title,
+ "─".repeat(right)
+ )
+}
+
+#[cfg(test)]
+fn box_footer_line(title: &str, width: usize) -> String {
+ let inner_width = width.saturating_sub(2);
+ let title = format!(" {title} ");
+ let visible_title = truncate_to_width(&title, inner_width);
+ let title_width = display_width(&visible_title);
+ let right = inner_width.saturating_sub(title_width).min(5);
+ let left = inner_width.saturating_sub(title_width + right);
+
+ format!(
+ "╰{}{}{}╯",
+ "─".repeat(left),
+ visible_title,
+ "─".repeat(right)
+ )
+}
+
+#[cfg(test)]
+fn box_content_line(left: &str, right: &str, width: usize) -> String {
+ let logo_width = ov_logo_width();
+ let gutter = 3usize;
+ let right_width = width.saturating_sub(4 + logo_width + gutter);
+ format!(
+ "│ {}{}{} │",
+ pad_to_width(left, logo_width),
+ " ".repeat(gutter),
+ pad_to_width(right, right_width)
+ )
+}
+
+fn styled_box_title_line(title: &str, width: usize) -> String {
+ let inner_width = width.saturating_sub(2);
+ let title = format!(" {title} ");
+ let visible_title = truncate_to_width(&title, inner_width);
+ 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();
+
+ format!(
+ "{}{}{}{}{}",
+ "╭".truecolor(red, green, blue),
+ "─".repeat(left).truecolor(red, green, blue),
+ styled_tagline(&visible_title),
+ "─".repeat(right).truecolor(red, green, blue),
+ "╮".truecolor(red, green, blue)
+ )
+}
+
+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 inner_width = width.saturating_sub(2);
+ let title = format!(" {title} ");
+ let visible_title = truncate_to_width(&title, inner_width);
+ let title_width = display_width(&visible_title);
+ let right = inner_width.saturating_sub(title_width).min(5);
+ let left = inner_width.saturating_sub(title_width + right);
+
+ 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)
+ )
+}
+
+fn styled_box_content_line(
+ left: &str,
+ detail: &StatusBoxDetail,
+ width: usize,
+ logo_row: usize,
+) -> String {
+ 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();
+ format!(
+ "{} {}{}{} {}",
+ "│".truecolor(red, green, blue),
+ styled_logo_to_width(left, logo_width, logo_row),
+ " ".repeat(gutter),
+ styled_detail_to_width(detail, right_width),
+ "│".truecolor(red, green, blue)
+ )
+}
+
+fn styled_logo_to_width(line: &str, width: usize, row: usize) -> String {
+ let mut rendered = String::new();
+ let visible = truncate_to_width(line, width);
+
+ for (column, ch) in visible.chars().enumerate() {
+ 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(),
+ );
+ }
+ }
+ rendered.push_str(&" ".repeat(width.saturating_sub(display_width(&visible))));
+ rendered
+}
+
+fn logo_glass_color(_ch: char, column: usize, row: usize, width: usize) -> Rgb {
+ logo_glass_color_for_theme(theme::active_theme(), column, row, width)
+}
+
+fn logo_glass_color_for_theme(
+ palette: theme::CliTheme,
+ column: usize,
+ row: usize,
+ width: usize,
+) -> Rgb {
+ if width <= 1 {
+ return palette.wordmark_start;
+ }
+
+ let column_ratio = column as f32 / (width - 1) as f32;
+ let row_height = OV_LOGO_LINES.len().saturating_sub(1).max(1);
+ let row_ratio = row as f32 / row_height as f32;
+ let ratio = (column_ratio * 0.4 + row_ratio * 0.6).clamp(0.0, 1.0);
+
+ if ratio <= 0.46 {
+ interpolate_rgb(palette.wordmark_start, palette.wordmark_mid, ratio / 0.46)
+ } else {
+ interpolate_rgb(
+ palette.wordmark_mid,
+ palette.logo_end,
+ (ratio - 0.46) / 0.54,
+ )
+ }
+}
+
+fn styled_detail_to_width(detail: &StatusBoxDetail, width: usize) -> String {
+ let plain = truncate_to_width(&detail.plain(), width);
+ let styled = if plain == detail.plain() {
+ detail.styled()
+ } else {
+ theme::muted(&plain).to_string()
+ };
+ format!(
+ "{}{}",
+ styled,
+ " ".repeat(width.saturating_sub(display_width(&plain)))
+ )
+}
+
+fn ov_logo_width() -> usize {
+ OV_LOGO_LINES
+ .iter()
+ .map(|line| display_width(line))
+ .max()
+ .unwrap_or_default()
+}
+
+#[cfg(test)]
+fn pad_to_width(text: &str, width: usize) -> String {
+ let truncated = truncate_to_width(text, width);
+ format!(
+ "{}{}",
+ truncated,
+ " ".repeat(width.saturating_sub(display_width(&truncated)))
+ )
+}
+
+fn truncate_to_width(text: &str, width: usize) -> String {
+ if display_width(text) <= width {
+ return text.to_string();
+ }
+ if width == 0 {
+ return String::new();
+ }
+ if width == 1 {
+ return "…".to_string();
+ }
+ let mut used = 0usize;
+ let mut truncated = String::new();
+ let target_width = width.saturating_sub(display_width("…"));
+ for ch in text.chars() {
+ let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0);
+ if used + ch_width > target_width {
+ break;
+ }
+ truncated.push(ch);
+ used += ch_width;
+ }
+ truncated.push('…');
+ truncated
+}
+
+fn display_width(text: &str) -> usize {
+ UnicodeWidthStr::width(text)
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ActiveSummaryRenderParts {
+ pub(crate) label: &'static str,
+ pub(crate) name: String,
+ pub(crate) kind: Option<String>,
+}
+
+pub(crate) fn active_summary_render_parts(line: &str) -> Option<ActiveSummaryRenderParts> {
+ let value = line.strip_prefix("Active: ")?;
+ let (name, kind) = match value.split_once(" (") {
+ Some((name, kind_tail)) if kind_tail.ends_with(')') => {
+ (name.to_string(), Some(format!("({kind_tail}")))
+ }
+ _ => (value.to_string(), None),
+ };
+
+ Some(ActiveSummaryRenderParts {
+ label: "Active:",
+ name,
+ kind,
+ })
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct SavedSummaryRenderParts {
+ pub(crate) label: &'static str,
+ pub(crate) count: String,
+}
+
+pub(crate) fn saved_summary_render_parts(line: &str) -> Option<SavedSummaryRenderParts> {
+ Some(SavedSummaryRenderParts {
+ label: "Saved configs:",
+ count: line.strip_prefix("Saved configs: ")?.to_string(),
+ })
+}
+
+pub(crate) fn active_summary_lines(
+ active: Option<&Config>,
+ configs: &[ConfigEntry],
+) -> Vec<String> {
+ let active_line = match active {
+ Some(config) => {
+ if let Some(entry) = configs.iter().find(|entry| entry.is_active) {
+ format!("Active: {} ({})", entry.name, kind_label(entry.kind))
+ } else {
+ format!(
+ "Active: unnamed ({})",
+ kind_label(ConfigKind::from_config(config))
+ )
+ }
+ }
+ None => "Active: none".to_string(),
+ };
+
+ vec![active_line, format!("Saved configs: {}", configs.len())]
+}
+
+async fn run_add_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<bool> {
+ enum Stage {
+ Kind,
+ Name,
+ Url,
+ ApiKey,
+ Account,
+ User,
+ Validate,
+ }
+
+ let mut stage = Stage::Kind;
+ let mut kind = ConfigKind::SelfManaged;
+ let mut name: Option<String> = None;
+ let mut url = DEFAULT_SELF_MANAGED_URL.to_string();
+ let mut api_key: Option<String> = None;
+ let mut account: Option<String> = None;
+ let mut user: Option<String> = None;
+ let mut identity_mode: Option<IdentityMode> = None;
+
+ loop {
+ match stage {
+ Stage::Kind => match prompt_select(
+ ui,
+ section_add(),
+ copy(
+ Language::current(),
+ "Where should this CLI connect?",
+ "CLI 要连接到哪里?",
+ ),
+ &provider_labels(Language::current()),
+ 0,
+ &[],
+ )? {
+ PromptResult::Value(0) => {
+ kind = ConfigKind::VolcengineCloud;
+ url = VOLCENGINE_CLOUD_URL.to_string();
+ name = None;
+ api_key = None;
+ account = None;
+ user = None;
+ identity_mode = None;
+ stage = Stage::Name;
+ }
+ PromptResult::Value(1) => {
+ kind = ConfigKind::SelfManaged;
+ url = DEFAULT_SELF_MANAGED_URL.to_string();
+ name = None;
+ api_key = None;
+ account = None;
+ user = None;
+ identity_mode = None;
+ stage = Stage::Name;
+ }
+ PromptResult::Back => return Ok(false),
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ PromptResult::Value(_) => unreachable!("selection is constrained by kind list"),
+ },
+ Stage::Name => {
+ match prompt_add_config_name(ui, section_add(), add_config_name_label())? {
+ PromptResult::Value(value) => {
+ name = value;
+ stage = if kind == ConfigKind::VolcengineCloud {
+ Stage::ApiKey
+ } else {
+ Stage::Url
+ };
+ }
+ PromptResult::Back => {
+ name = None;
+ api_key = None;
+ account = None;
+ user = None;
+ identity_mode = None;
+ url = DEFAULT_SELF_MANAGED_URL.to_string();
+ stage = Stage::Kind;
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Stage::Url => match prompt_text(
+ ui,
+ section_add(),
+ copy(Language::current(), "Server URL", "服务器 URL"),
+ Some(&url),
+ Some(InputValueLabel::Default),
+ false,
+ false,
+ &[],
+ )? {
+ PromptResult::Value(value) => {
+ url = value;
+ stage = Stage::ApiKey;
+ }
+ PromptResult::Back => stage = Stage::Name,
+ 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))
+ };
+
+ let label = if kind == ConfigKind::SelfManaged {
+ api_key_label(self_managed_allows_empty_api_key(&url))
+ } 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,
+ 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)
+ {
+ identity_mode = Some(IdentityMode::LocalNoKey);
+ stage = Stage::Account;
+ } else {
+ identity_mode = None;
+ stage = Stage::Validate;
+ }
+ }
+ PromptResult::Back => {
+ stage = if kind == ConfigKind::VolcengineCloud {
+ Stage::Name
+ } else {
+ Stage::Url
+ };
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Stage::Account => {
+ let mode = identity_mode.unwrap_or(IdentityMode::LocalNoKey);
+ match prompt_identity_value(
+ ui,
+ section_add(),
+ copy(Language::current(), "Account ID", "账户 ID"),
+ mode,
+ )? {
+ PromptResult::Value(value) => {
+ account = Some(value);
+ stage = Stage::User;
+ }
+ PromptResult::Back => {
+ account = None;
+ user = None;
+ stage = Stage::ApiKey;
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Stage::User => {
+ let mode = identity_mode.unwrap_or(IdentityMode::LocalNoKey);
+ match prompt_identity_value(
+ ui,
+ section_add(),
+ copy(Language::current(), "User ID", "用户 ID"),
+ mode,
+ )? {
+ PromptResult::Value(value) => {
+ user = Some(value);
+ stage = Stage::Validate;
+ }
+ PromptResult::Back => {
+ user = None;
+ stage = Stage::Account;
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Stage::Validate => {
+ let draft_name = name
+ .clone()
+ .map(Ok)
+ .unwrap_or_else(|| allocate_config_name(store, kind))?;
+ let draft = ConfigDraft {
+ name: draft_name.clone(),
+ kind,
+ url: url.clone(),
+ api_key: api_key.clone(),
+ account: account.clone(),
+ user: user.clone(),
+ };
+ match validate_draft(ui, section_add(), &draft).await {
+ Ok(ValidatedConfig {
+ config,
+ api_key_role,
+ }) => {
+ if should_prompt_root_identity(
+ api_key_role,
+ false,
+ account.as_deref(),
+ user.as_deref(),
+ ) {
+ identity_mode = Some(IdentityMode::RootKey);
+ stage = Stage::Account;
+ continue;
+ }
+ match prompt_save_action(
+ ui,
+ section_add(),
+ copy(Language::current(), "Save config?", "保存配置?"),
+ SaveActionSet::Add,
+ 0,
+ )? {
+ PromptResult::Value(SaveAction::SaveAndActivate) => {
+ ui.clear()?;
+ save_config(store, &draft_name, &config, true)?;
+ return Ok(true);
+ }
+ PromptResult::Value(SaveAction::SaveOnly) => {
+ ui.clear()?;
+ save_config(store, &draft_name, &config, false)?;
+ return Ok(true);
+ }
+ PromptResult::Value(SaveAction::Cancel) => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ PromptResult::Value(SaveAction::SaveActive) => {
+ unreachable!("add save choices cannot produce active-edit action")
+ }
+ PromptResult::Back => {
+ stage = if identity_mode.is_some() {
+ Stage::User
+ } else {
+ Stage::ApiKey
+ };
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Err(error) => {
+ let helper_lines = vec![
+ theme::error(localized_validation_error(kind, &error)).to_string(),
+ ];
+ let choices: Vec<&str> = if kind == ConfigKind::VolcengineCloud {
+ cloud_validation_failure_choices_for_language(Language::current())
+ .to_vec()
+ } else {
+ self_managed_validation_failure_choices_for_language(Language::current()).to_vec()
+ };
+ match prompt_select(
+ ui,
+ section_add(),
+ copy(
+ Language::current(),
+ "Validation failed. What next?",
+ "验证失败,下一步?",
+ ),
+ &choices,
+ 0,
+ &helper_lines,
+ )? {
+ PromptResult::Value(0) => {
+ stage = if kind == ConfigKind::VolcengineCloud {
+ Stage::ApiKey
+ } else {
+ Stage::Url
+ };
+ }
+ PromptResult::Value(1) => {
+ stage = if kind == ConfigKind::VolcengineCloud {
+ print_cancelled(ui)?;
+ return Ok(true);
+ } else {
+ Stage::ApiKey
+ };
+ }
+ PromptResult::Value(2) if kind == ConfigKind::SelfManaged => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ PromptResult::Back => stage = Stage::ApiKey,
+ PromptResult::Value(_) => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+async fn run_edit_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<bool> {
+ enum Stage {
+ Select,
+ Name,
+ Url,
+ ApiKeyChoice,
+ ApiKeyInput,
+ Account,
+ User,
+ Validate,
+ }
+
+ let configs = store.list_configs()?;
+ if configs.is_empty() {
+ let helper_lines = vec![
+ theme::warning(copy(
+ Language::current(),
+ "No saved configs to edit.",
+ "没有可编辑的配置。",
+ ))
+ .to_string(),
+ ];
+ let _ = prompt_select(
+ ui,
+ section_edit(),
+ copy(Language::current(), "Nothing to edit.", "没有可编辑项。"),
+ &[copy(Language::current(), "Back", "返回")],
+ 0,
+ &helper_lines,
+ )?;
+ return Ok(false);
+ }
+
+ let mut stage = Stage::Select;
+ let mut selected = 0usize;
+ let mut name = String::new();
+ let mut kind = ConfigKind::SelfManaged;
+ let mut url = String::new();
+ let mut 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 api_key_was_entered = false;
+
+ loop {
+ match stage {
+ Stage::Select => match prompt_config_select(
+ ui,
+ section_edit(),
+ copy(Language::current(), "Config to edit", "要编辑的配置"),
+ &configs,
+ )? {
+ PromptResult::Value(index) => {
+ selected = index;
+ let config = &configs[index];
+ name = config.name.clone();
+ kind = config.kind;
+ url = config.config.url.clone();
+ api_key = config.config.api_key.clone();
+ account = config.config.account.clone();
+ user = config.config.user.clone();
+ identity_mode = None;
+ api_key_was_entered = false;
+ stage = Stage::Name;
+ }
+ PromptResult::Back => return Ok(false),
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ },
+ Stage::Name => {
+ match prompt_config_name(
+ ui,
+ section_edit(),
+ copy(Language::current(), "Config name", "配置名称"),
+ Some(&name),
+ )? {
+ PromptResult::Value(value) => {
+ name = value;
+ stage = if kind == ConfigKind::VolcengineCloud {
+ Stage::ApiKeyChoice
+ } else {
+ Stage::Url
+ };
+ }
+ PromptResult::Back => stage = Stage::Select,
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Stage::Url => match prompt_text(
+ ui,
+ section_edit(),
+ copy(Language::current(), "Server URL", "服务器 URL"),
+ Some(&url),
+ Some(InputValueLabel::Current),
+ false,
+ false,
+ &[],
+ )? {
+ PromptResult::Value(value) => {
+ url = value;
+ stage = Stage::ApiKeyChoice;
+ }
+ PromptResult::Back => stage = Stage::Name,
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ },
+ Stage::ApiKeyChoice => {
+ 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());
+ if !has_existing {
+ stage = Stage::ApiKeyInput;
+ continue;
+ }
+
+ match prompt_select(
+ ui,
+ section_edit(),
+ api_key_label(false),
+ &edit_api_key_choice_labels_for_language(
+ kind,
+ has_existing,
+ Language::current(),
+ ),
+ 0,
+ &helper_lines,
+ )? {
+ PromptResult::Value(0) => {
+ api_key_was_entered = false;
+ stage = Stage::Validate;
+ }
+ PromptResult::Value(1) => stage = Stage::ApiKeyInput,
+ PromptResult::Value(_) => {
+ api_key = None;
+ api_key_was_entered = false;
+ if kind == ConfigKind::SelfManaged
+ && 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 = if kind == ConfigKind::VolcengineCloud {
+ Stage::Name
+ } else {
+ Stage::Url
+ };
+ }
+ 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)
+ } 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)
+ };
+ match prompt_text(
+ ui,
+ section_edit(),
+ label,
+ api_key.as_deref(),
+ api_key.as_deref().map(|_| InputValueLabel::Current),
+ allow_empty,
+ 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;
+ }
+ }
+ PromptResult::Back => {
+ stage = if has_existing {
+ Stage::ApiKeyChoice
+ } else if kind == ConfigKind::VolcengineCloud {
+ Stage::Name
+ } else {
+ Stage::Url
+ };
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Stage::Account => {
+ let mode = identity_mode.unwrap_or(IdentityMode::LocalNoKey);
+ match prompt_identity_value(
+ ui,
+ section_edit(),
+ copy(Language::current(), "Account ID", "账户 ID"),
+ mode,
+ )? {
+ PromptResult::Value(value) => {
+ account = Some(value);
+ stage = Stage::User;
+ }
+ PromptResult::Back => {
+ if identity_mode == Some(IdentityMode::RootKey) {
+ account = None;
+ user = None;
+ stage = Stage::ApiKeyInput;
+ } else {
+ stage = Stage::ApiKeyInput;
+ }
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Stage::User => {
+ let mode = identity_mode.unwrap_or(IdentityMode::LocalNoKey);
+ match prompt_identity_value(
+ ui,
+ section_edit(),
+ copy(Language::current(), "User ID", "用户 ID"),
+ mode,
+ )? {
+ PromptResult::Value(value) => {
+ user = Some(value);
+ if identity_mode == Some(IdentityMode::RootKey) {
+ api_key_was_entered = false;
+ }
+ stage = Stage::Validate;
+ }
+ PromptResult::Back => {
+ user = None;
+ stage = Stage::Account;
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Stage::Validate => {
+ let draft = ConfigDraft {
+ name: name.clone(),
+ kind,
+ url: url.clone(),
+ api_key: api_key.clone(),
+ account: account.clone(),
+ user: user.clone(),
+ };
+ match validate_draft(ui, section_edit(), &draft).await {
+ Ok(ValidatedConfig {
+ config,
+ api_key_role,
+ }) => {
+ if should_prompt_root_identity(
+ api_key_role,
+ api_key_was_entered,
+ account.as_deref(),
+ user.as_deref(),
+ ) {
+ identity_mode = Some(IdentityMode::RootKey);
+ stage = Stage::Account;
+ continue;
+ }
+ match prompt_save_action(
+ ui,
+ section_edit(),
+ if configs[selected].is_active {
+ copy(
+ Language::current(),
+ "Save changes to active config?",
+ "保存当前配置的更改?",
+ )
+ } else {
+ copy(Language::current(), "Save changes?", "保存更改?")
+ },
+ if configs[selected].is_active {
+ SaveActionSet::EditActive
+ } else {
+ SaveActionSet::EditInactive
+ },
+ 0,
+ )? {
+ PromptResult::Value(SaveAction::SaveActive) => {
+ ui.clear()?;
+ let original = configs[selected].name.clone();
+ store.save_edited_config(&original, &name, &config)?;
+ print_saved(store, &name, SaveOutcome::UpdatedActive)?;
+ 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)?;
+ return Ok(true);
+ }
+ PromptResult::Value(SaveAction::SaveAndActivate) => {
+ ui.clear()?;
+ let original = configs[selected].name.clone();
+ store.save_edited_config(&original, &name, &config)?;
+ store.activate_config(&name)?;
+ print_saved(store, &name, SaveOutcome::Activated)?;
+ return Ok(true);
+ }
+ PromptResult::Value(SaveAction::Cancel) => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ PromptResult::Back => {
+ stage = if identity_mode.is_some() {
+ Stage::User
+ } else {
+ Stage::ApiKeyChoice
+ };
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ Err(error) => {
+ let helper_lines = vec![
+ theme::error(localized_validation_error(kind, &error)).to_string(),
+ ];
+ let choices = if kind == ConfigKind::VolcengineCloud {
+ cloud_validation_failure_choices_for_language(Language::current())
+ .to_vec()
+ } else {
+ self_managed_validation_failure_choices_for_language(Language::current()).to_vec()
+ };
+ match prompt_select(
+ ui,
+ section_edit(),
+ copy(
+ Language::current(),
+ "Validation failed. What next?",
+ "验证失败,下一步?",
+ ),
+ &choices,
+ 0,
+ &helper_lines,
+ )? {
+ PromptResult::Value(0) => {
+ stage = if kind == ConfigKind::VolcengineCloud {
+ Stage::ApiKeyInput
+ } else {
+ Stage::Url
+ };
+ }
+ PromptResult::Value(1) => {
+ stage = if kind == ConfigKind::VolcengineCloud {
+ print_cancelled(ui)?;
+ return Ok(true);
+ } else {
+ Stage::ApiKeyChoice
+ };
+ }
+ PromptResult::Value(2) if kind == ConfigKind::SelfManaged => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ PromptResult::Back => stage = Stage::ApiKeyChoice,
+ PromptResult::Value(_) => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+fn run_delete_config(store: &ConfigStore, ui: &mut LiveRegion) -> Result<bool> {
+ enum Stage {
+ Select,
+ Confirm,
+ }
+
+ let configs = store.list_configs()?;
+ if configs.is_empty() {
+ let helper_lines = vec![
+ theme::warning(copy(
+ Language::current(),
+ "No saved configs to delete.",
+ "没有可删除的配置。",
+ ))
+ .to_string(),
+ ];
+ let _ = prompt_select(
+ ui,
+ section_delete(),
+ copy(Language::current(), "Nothing to delete.", "没有可删除项。"),
+ &[copy(Language::current(), "Back", "返回")],
+ 0,
+ &helper_lines,
+ )?;
+ return Ok(false);
+ }
+
+ let mut stage = Stage::Select;
+ let mut selected = 0usize;
+
+ loop {
+ match stage {
+ Stage::Select => match prompt_config_select(
+ ui,
+ section_delete(),
+ copy(Language::current(), "Config to delete", "要删除的配置"),
+ &configs,
+ )? {
+ PromptResult::Value(index) => {
+ selected = index;
+ if configs[index].is_active {
+ let helper_lines = active_delete_block_helper_lines();
+ let _ = prompt_select(
+ ui,
+ section_delete(),
+ copy(
+ Language::current(),
+ "Active config cannot be deleted.",
+ "不能删除当前配置。",
+ ),
+ &[copy(Language::current(), "Back", "返回")],
+ 0,
+ &helper_lines,
+ )?;
+ return Ok(false);
+ }
+ stage = Stage::Confirm;
+ }
+ PromptResult::Back => return Ok(false),
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ },
+ Stage::Confirm => {
+ let name = &configs[selected].name;
+ match confirm(ui, section_delete(), &delete_confirm_prompt(name), false)? {
+ PromptResult::Value(true) => {
+ ui.clear()?;
+ store.delete_config(name)?;
+ println!();
+ println!(
+ "{} {}",
+ theme::success("✓"),
+ theme::success(deleted_config_message(name))
+ );
+ println!(
+ "{} {}",
+ theme::muted(copy(Language::current(), "Removed:", "已删除:")),
+ store
+ .saved_config_path(name)?
+ .display()
+ .to_string()
+ .magenta()
+ );
+ println!(
+ "{} {}",
+ theme::muted(copy(Language::current(), "Next:", "下一步:")),
+ next_step_copy()
+ );
+ return Ok(true);
+ }
+ PromptResult::Value(false) => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ PromptResult::Back => stage = Stage::Select,
+ PromptResult::Quit => {
+ print_cancelled(ui)?;
+ return Ok(true);
+ }
+ }
+ }
+ }
+ }
+}
+
+struct ValidatedConfig {
+ config: Config,
+ api_key_role: Option<ApiKeyRole>,
+}
+
+async fn validate_draft(
+ ui: &mut LiveRegion,
+ section: &str,
+ draft: &ConfigDraft,
+) -> Result<ValidatedConfig> {
+ let mut config = build_config(draft)?;
+ let require_api_key = draft.kind == ConfigKind::VolcengineCloud
+ || (draft.kind == ConfigKind::SelfManaged
+ && !self_managed_allows_empty_api_key(&draft.url));
+ ui.render(&status_live_lines(
+ section,
+ copy(
+ Language::current(),
+ "Validating connection...",
+ "正在验证连接...",
+ ),
+ ))?;
+ let api_key_role = if config
+ .api_key
+ .as_deref()
+ .is_some_and(|key| !key.trim().is_empty())
+ {
+ 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 role == Some(ApiKeyRole::Root) {
+ let has_identity = config
+ .account
+ .as_deref()
+ .is_some_and(|value| !value.trim().is_empty())
+ && config
+ .user
+ .as_deref()
+ .is_some_and(|value| !value.trim().is_empty());
+ if has_identity {
+ validate_candidate_config(&config, require_api_key).await?;
+ }
+ } else {
+ config.account = None;
+ config.user = None;
+ }
+ role
+ } else {
+ validate_candidate_config(&config, require_api_key).await?;
+ None
+ };
+ Ok(ValidatedConfig {
+ config,
+ api_key_role,
+ })
+}
+
+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)
+ } else {
+ store.save_named_config(name, config)?;
+ print_saved(store, name, SaveOutcome::SavedOnly)
+ }
+}
+
+fn print_saved(store: &ConfigStore, name: &str, outcome: SaveOutcome) -> Result<()> {
+ println!();
+ let message = match outcome {
+ SaveOutcome::Activated => saved_message_activated(name),
+ SaveOutcome::SavedOnly => saved_message_only(name),
+ SaveOutcome::UpdatedActive => saved_message_updated_active(name),
+ };
+ println!("{} {}", theme::success("✓"), theme::success(message));
+ println!(
+ "{} {}",
+ theme::muted(copy(Language::current(), "Saved to:", "保存到:")),
+ store
+ .saved_config_path(name)?
+ .display()
+ .to_string()
+ .magenta()
+ );
+ match outcome {
+ SaveOutcome::Activated | SaveOutcome::UpdatedActive => {
+ println!(
+ "{} {}",
+ theme::muted(copy(Language::current(), "Active config:", "当前配置:")),
+ store.active_path().display().to_string().magenta()
+ );
+ }
+ SaveOutcome::SavedOnly => {
+ println!(
+ "{} {}",
+ theme::muted(copy(Language::current(), "Activate later:", "稍后启用:")),
+ theme::command("ov config switch")
+ );
+ }
+ }
+ println!(
+ "{} {}",
+ theme::muted(copy(Language::current(), "Next:", "下一步:")),
+ next_step_copy()
+ );
+ Ok(())
+}
+
+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()),
+ }
+}
+
+fn saved_message_activated(name: &str) -> String {
+ match Language::current() {
+ Language::En => format!("Saved config '{name}' and made it active."),
+ Language::ZhCn => format!("已保存配置 '{name}',并设为当前配置。"),
+ }
+}
+
+fn saved_message_only(name: &str) -> String {
+ match Language::current() {
+ Language::En => format!("Saved config '{name}'."),
+ Language::ZhCn => format!("已保存配置 '{name}'。"),
+ }
+}
+
+fn saved_message_updated_active(name: &str) -> String {
+ match Language::current() {
+ Language::En => format!("Saved active config '{name}'."),
+ Language::ZhCn => format!("已保存当前配置 '{name}'。"),
+ }
+}
+
+pub(crate) fn add_config_name_label() -> &'static str {
+ copy(
+ Language::current(),
+ "Config name (optional)",
+ "配置名称(可选)",
+ )
+}
+
+fn add_config_name_helper_lines() -> Vec<String> {
+ vec![
+ theme::muted(copy(
+ Language::current(),
+ "Leave empty to generate one.",
+ "留空将自动生成名称。",
+ ))
+ .to_string(),
+ ]
+}
+
+pub(crate) fn volcengine_api_key_helper_lines() -> Vec<String> {
+ let language = Language::current();
+ vec![
+ format!(
+ "{} {}",
+ theme::muted(copy(language, "Get your API key:", "获取 API Key:")),
+ VOLCENGINE_API_KEY_URL
+ ),
+ theme::muted(copy(
+ language,
+ "Go to User Management → API Key to view and copy your key.",
+ "进入用户管理 → API Key 查看并复制。",
+ ))
+ .to_string(),
+ ]
+}
+
+pub(crate) fn self_managed_api_key_helper_lines(allow_empty: bool) -> Vec<String> {
+ let copy = if allow_empty {
+ copy(
+ Language::current(),
+ "Optional for local servers. Add one if auth is enabled.",
+ "本地服务可不填;如果启用了认证,请填写。",
+ )
+ } else {
+ copy(
+ Language::current(),
+ "Required for remote self-managed servers.",
+ "远程自托管服务需要 API Key。",
+ )
+ };
+ vec![theme::muted(copy).to_string()]
+}
+
+fn prompt_add_config_name(
+ ui: &mut LiveRegion,
+ section: &str,
+ prompt: &str,
+) -> Result<PromptResult<Option<String>>> {
+ let mut error: Option<String> = None;
+ loop {
+ let mut helper_lines = add_config_name_helper_lines();
+ if let Some(value) = error.as_ref() {
+ helper_lines.push(theme::error(value).to_string());
+ }
+
+ match prompt_text(ui, section, prompt, None, None, true, false, &helper_lines)? {
+ PromptResult::Value(value) => {
+ let value = value.trim();
+ if value.is_empty() {
+ return Ok(PromptResult::Value(None));
+ }
+ match validate_config_name(value) {
+ Ok(()) => return Ok(PromptResult::Value(Some(value.to_string()))),
+ Err(next_error) => error = Some(next_error.to_string()),
+ }
+ }
+ PromptResult::Back => return Ok(PromptResult::Back),
+ PromptResult::Quit => return Ok(PromptResult::Quit),
+ }
+ }
+}
+
+pub(crate) fn allocate_config_name(store: &ConfigStore, kind: ConfigKind) -> Result<String> {
+ let prefix = match kind {
+ ConfigKind::VolcengineCloud => "cloud",
+ ConfigKind::SelfManaged => "local",
+ };
+
+ for _ in 0..32 {
+ let suffix = Uuid::new_v4().simple().to_string();
+ let candidate = format!("{prefix}-{}", &suffix[..6]);
+ if !store.saved_config_path(&candidate)?.exists() {
+ return Ok(candidate);
+ }
+ }
+
+ Err(Error::Config(
+ "Could not generate a unique config name. Please enter one manually.".to_string(),
+ ))
+}
+
+fn prompt_config_name(
+ ui: &mut LiveRegion,
+ section: &str,
+ prompt: &str,
+ default: Option<&str>,
+) -> Result<PromptResult<String>> {
+ let mut error: Option<String> = None;
+ loop {
+ let helper_lines: Vec<String> = error
+ .as_ref()
+ .map(|value| vec![theme::error(value).to_string()])
+ .unwrap_or_default();
+ match prompt_text(
+ ui,
+ section,
+ prompt,
+ default,
+ Some(InputValueLabel::Current),
+ false,
+ false,
+ &helper_lines,
+ )? {
+ PromptResult::Value(value) => match validate_config_name(&value) {
+ 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 prompt_identity_value(
+ ui: &mut LiveRegion,
+ section: &str,
+ prompt: &str,
+ 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,
+ )
+}
+
+fn identity_prompt_parts(
+ mode: IdentityMode,
+) -> (Option<&'static str>, Option<InputValueLabel>, Vec<String>) {
+ match mode {
+ IdentityMode::LocalNoKey => (
+ Some("default"),
+ Some(InputValueLabel::Default),
+ vec![
+ theme::muted(copy(
+ Language::current(),
+ "Local no-key identity.",
+ "本地无密钥身份。",
+ ))
+ .to_string(),
+ ],
+ ),
+ IdentityMode::RootKey => (
+ None,
+ None,
+ vec![
+ theme::muted(copy(
+ Language::current(),
+ "Root API keys require an explicit account and user.",
+ "Root API Key 需要明确的账户和用户。",
+ ))
+ .to_string(),
+ ],
+ ),
+ }
+}
+
+fn prompt_config_select(
+ ui: &mut LiveRegion,
+ section: &str,
+ prompt: &str,
+ configs: &[ConfigEntry],
+) -> Result<PromptResult<usize>> {
+ let items: Vec<String> = configs.iter().map(config_select_label).collect();
+ prompt_select(ui, section, prompt, &items, 0, &[])
+}
+
+fn config_select_label(entry: &ConfigEntry) -> String {
+ let label = format!("{} - {}", entry.name, kind_label(entry.kind));
+ if entry.is_active {
+ format!("{} {}", label, theme::error(active_badge()).bold())
+ } else {
+ label
+ }
+}
+
+fn active_badge() -> &'static str {
+ copy(Language::current(), "[Active]", "[当前]")
+}
+
+fn active_delete_block_helper_lines() -> Vec<String> {
+ match Language::current() {
+ Language::En => vec![
+ theme::error("Deleting the active config is blocked.").to_string(),
+ format!(
+ "{} {} {}",
+ theme::muted("Run"),
+ theme::command("ov config switch").bold(),
+ theme::muted("to choose another config, then delete this one.")
+ ),
+ ],
+ Language::ZhCn => vec![
+ theme::error("不能删除当前配置。").to_string(),
+ format!(
+ "{} {} {}",
+ theme::muted("请先运行"),
+ theme::command("ov config switch").bold(),
+ theme::muted("切换到其他配置,然后再删除。")
+ ),
+ ],
+ }
+}
+
+fn delete_confirm_prompt(name: &str) -> String {
+ match Language::current() {
+ Language::En => format!("Delete config '{name}'?"),
+ Language::ZhCn => format!("删除配置 '{name}'?"),
+ }
+}
+
+fn localized_validation_error(kind: ConfigKind, error: &Error) -> String {
+ match Language::current() {
+ Language::En => validation_error_copy(kind, error),
+ Language::ZhCn => match kind {
+ ConfigKind::VolcengineCloud => "验证失败。请检查 API Key 后重试。".to_string(),
+ ConfigKind::SelfManaged => {
+ "验证失败。请检查服务器 URL,以及是否需要 API Key。".to_string()
+ }
+ },
+ }
+}
+
+fn deleted_config_message(name: &str) -> String {
+ match Language::current() {
+ Language::En => format!("Deleted config '{name}'."),
+ Language::ZhCn => format!("已删除配置 '{name}'。"),
+ }
+}
+
+pub(crate) fn add_save_action_labels() -> Vec<&'static str> {
+ vec!["Save and activate", "Save only", "Cancel"]
+}
+
+pub(crate) fn edit_save_action_labels(is_active: bool) -> Vec<&'static str> {
+ if is_active {
+ vec!["Save changes", "Cancel"]
+ } else {
+ vec!["Save only", "Save and activate", "Cancel"]
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SaveActionSet {
+ Add,
+ EditActive,
+ EditInactive,
+}
+
+impl SaveActionSet {
+ fn labels(self, language: Language) -> Vec<&'static str> {
+ match (self, language) {
+ (Self::Add, Language::En) => add_save_action_labels(),
+ (Self::Add, Language::ZhCn) => vec!["保存并设为当前配置", "仅保存", "取消"],
+ (Self::EditActive, Language::En) => edit_save_action_labels(true),
+ (Self::EditActive, Language::ZhCn) => vec!["保存更改", "取消"],
+ (Self::EditInactive, Language::En) => edit_save_action_labels(false),
+ (Self::EditInactive, Language::ZhCn) => {
+ vec!["仅保存", "保存并设为当前配置", "取消"]
+ }
+ }
+ }
+
+ fn action(self, index: usize) -> SaveAction {
+ match (self, index) {
+ (Self::Add, 0) => SaveAction::SaveAndActivate,
+ (Self::Add, 1) => SaveAction::SaveOnly,
+ (Self::Add, _) => SaveAction::Cancel,
+ (Self::EditActive, 0) => SaveAction::SaveActive,
+ (Self::EditActive, _) => SaveAction::Cancel,
+ (Self::EditInactive, 0) => SaveAction::SaveOnly,
+ (Self::EditInactive, 1) => SaveAction::SaveAndActivate,
+ (Self::EditInactive, _) => SaveAction::Cancel,
+ }
+ }
+}
+
+fn prompt_save_action(
+ ui: &mut LiveRegion,
+ section: &str,
+ prompt: &str,
+ action_set: SaveActionSet,
+ default: usize,
+) -> Result<PromptResult<SaveAction>> {
+ let items = action_set.labels(Language::current());
+ match prompt_select(ui, section, prompt, &items, default, &[])? {
+ PromptResult::Value(index) => Ok(PromptResult::Value(action_set.action(index))),
+ PromptResult::Back => Ok(PromptResult::Back),
+ PromptResult::Quit => Ok(PromptResult::Quit),
+ }
+}
+
+fn prompt_select<T: ToString>(
+ ui: &mut LiveRegion,
+ section: &str,
+ prompt: &str,
+ items: &[T],
+ default: usize,
+ helper_lines: &[String],
+) -> Result<PromptResult<usize>> {
+ let items: Vec<String> = items.iter().map(ToString::to_string).collect();
+ let mut selected = default.min(items.len().saturating_sub(1));
+ let raw = RawPrompt::enter(true)?;
+
+ loop {
+ ui.render(&select_live_lines(
+ section,
+ prompt,
+ &items,
+ selected,
+ helper_lines,
+ ))?;
+
+ if let Event::Key(key) = event::read()? {
+ match key.code {
+ KeyCode::Up => {
+ selected = if selected == 0 {
+ items.len().saturating_sub(1)
+ } else {
+ selected - 1
+ };
+ }
+ KeyCode::Down => selected = (selected + 1) % items.len().max(1),
+ KeyCode::Enter => {
+ drop(raw);
+ ui.clear()?;
+ return Ok(PromptResult::Value(selected));
+ }
+ KeyCode::Esc => {
+ drop(raw);
+ ui.clear()?;
+ return Ok(PromptResult::Back);
+ }
+ KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
+ drop(raw);
+ ui.clear()?;
+ return Ok(PromptResult::Quit);
+ }
+ _ => {}
+ }
+ }
+ }
+}
+
+fn prompt_text(
+ ui: &mut LiveRegion,
+ section: &str,
+ prompt: &str,
+ default: Option<&str>,
+ value_label: Option<InputValueLabel>,
+ allow_empty: bool,
+ secret: bool,
+ helper_lines: &[String],
+) -> Result<PromptResult<String>> {
+ let mut error: Option<String> = None;
+ 'attempt: loop {
+ let mut value = String::new();
+ let default_copy = default.unwrap_or_default();
+ ui.render_input(
+ &input_live_lines(
+ section,
+ prompt,
+ default,
+ value_label,
+ secret,
+ helper_lines,
+ error.as_deref(),
+ ),
+ " > ",
+ )?;
+
+ let raw = RawPrompt::enter(false)?;
+ loop {
+ if let Event::Key(key) = event::read()? {
+ match key.code {
+ KeyCode::Enter => {
+ let chosen = if value.trim().is_empty() {
+ default_copy.trim().to_string()
+ } else {
+ value.trim().to_string()
+ };
+ drop(raw);
+ if chosen.is_empty() && !allow_empty {
+ ui.clear()?;
+ error = Some(
+ copy(
+ Language::current(),
+ "Value cannot be empty.",
+ "内容不能为空。",
+ )
+ .to_string(),
+ );
+ continue 'attempt;
+ }
+ ui.clear()?;
+ return Ok(PromptResult::Value(chosen));
+ }
+ KeyCode::Esc => {
+ drop(raw);
+ ui.clear()?;
+ return Ok(PromptResult::Back);
+ }
+ KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
+ drop(raw);
+ ui.clear()?;
+ return Ok(PromptResult::Quit);
+ }
+ KeyCode::Backspace => {
+ if let Some(ch) = value.pop() {
+ raw_write(erase_sequence_for_char(ch, secret))?;
+ io::stdout().flush()?;
+ }
+ }
+ KeyCode::Char(ch) => {
+ if !key.modifiers.contains(KeyModifiers::CONTROL) {
+ value.push(ch);
+ if secret {
+ raw_write("*")?;
+ } else {
+ raw_write(ch.to_string())?;
+ }
+ io::stdout().flush()?;
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+}
+
+fn erase_sequence_for_char(ch: char, secret: bool) -> String {
+ let width = if secret {
+ 1
+ } else {
+ UnicodeWidthChar::width(ch).unwrap_or(1).max(1)
+ };
+ "\x08 \x08".repeat(width)
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum InputValueLabel {
+ Default,
+ Current,
+}
+
+impl InputValueLabel {
+ fn text(self) -> &'static str {
+ match (self, Language::current()) {
+ (Self::Default, Language::En) => "Default:",
+ (Self::Default, Language::ZhCn) => "默认值:",
+ (Self::Current, Language::En) => "Current:",
+ (Self::Current, Language::ZhCn) => "当前值:",
+ }
+ }
+}
+
+fn confirm(
+ ui: &mut LiveRegion,
+ section: &str,
+ prompt: &str,
+ default: bool,
+) -> Result<PromptResult<bool>> {
+ let items = match Language::current() {
+ Language::En => ["Yes", "No"],
+ Language::ZhCn => ["是", "否"],
+ };
+ match prompt_select(ui, section, prompt, &items, usize::from(!default), &[])? {
+ PromptResult::Value(0) => Ok(PromptResult::Value(true)),
+ PromptResult::Value(1) => Ok(PromptResult::Value(false)),
+ PromptResult::Back => Ok(PromptResult::Back),
+ PromptResult::Quit => Ok(PromptResult::Quit),
+ PromptResult::Value(_) => unreachable!("selection is constrained by confirm list"),
+ }
+}
+
+#[derive(Default)]
+struct LiveRegion {
+ lines_drawn: usize,
+ cursor_on_last_line: bool,
+}
+
+impl LiveRegion {
+ fn render(&mut self, lines: &[String]) -> Result<()> {
+ self.clear()?;
+ for line in lines {
+ raw_line(line)?;
+ }
+ io::stdout().flush()?;
+ self.lines_drawn = lines.len();
+ self.cursor_on_last_line = false;
+ Ok(())
+ }
+
+ fn render_input(&mut self, lines: &[String], prompt: &str) -> Result<()> {
+ self.clear()?;
+ for line in lines {
+ raw_line(line)?;
+ }
+ raw_write(prompt)?;
+ io::stdout().flush()?;
+ self.lines_drawn = lines.len() + 1;
+ self.cursor_on_last_line = true;
+ Ok(())
+ }
+
+ fn clear(&mut self) -> Result<()> {
+ clear_live_region(self.lines_drawn, self.cursor_on_last_line)?;
+ self.lines_drawn = 0;
+ self.cursor_on_last_line = false;
+ Ok(())
+ }
+}
+
+pub(crate) fn select_live_lines<T: ToString>(
+ section: &str,
+ prompt: &str,
+ items: &[T],
+ selected: usize,
+ helper_lines: &[String],
+) -> Vec<String> {
+ let mut lines = vec![
+ format!(
+ "{} {}",
+ theme::section_marker("◆").bold(),
+ theme::strong(section)
+ ),
+ String::new(),
+ format!("{} {}", theme::prompt("?").bold(), theme::strong(prompt)),
+ format!(" {}", theme::muted(nav_hint())),
+ ];
+
+ if !helper_lines.is_empty() {
+ lines.push(String::new());
+ lines.extend(helper_lines.iter().map(|line| format!(" {line}")));
+ }
+
+ lines.push(String::new());
+ lines.extend(items.iter().enumerate().map(|(index, item)| {
+ let item = item.to_string();
+ if index == selected {
+ theme::selection(format!(" › {item}")).bold().to_string()
+ } else {
+ format!(" {}", theme::body(item))
+ }
+ }));
+ lines
+}
+
+fn input_live_lines(
+ section: &str,
+ prompt: &str,
+ default: Option<&str>,
+ value_label: Option<InputValueLabel>,
+ secret: bool,
+ helper_lines: &[String],
+ error: Option<&str>,
+) -> Vec<String> {
+ let mut lines = vec![
+ format!(
+ "{} {}",
+ theme::section_marker("◆").bold(),
+ theme::strong(section)
+ ),
+ String::new(),
+ format!("{} {}", theme::prompt("?").bold(), theme::strong(prompt)),
+ format!(" {}", theme::muted(input_hint())),
+ ];
+
+ if !helper_lines.is_empty() {
+ lines.push(String::new());
+ lines.extend(helper_lines.iter().map(|line| format!(" {line}")));
+ }
+
+ if let (Some(default_value), Some(value_label)) = (default, value_label) {
+ let rendered_default = if secret {
+ if default_value.trim().is_empty() {
+ theme::muted("(empty)").to_string()
+ } else {
+ theme::muted("(existing value)").to_string()
+ }
+ } else {
+ theme::muted(default_value).to_string()
+ };
+ lines.push(format!(
+ " {} {}",
+ theme::muted(value_label.text()),
+ rendered_default
+ ));
+ }
+
+ if let Some(error) = error {
+ lines.push(format!(" {}", theme::error(error)));
+ }
+
+ lines.push(String::new());
+ lines
+}
+
+fn status_live_lines(section: &str, status: &str) -> Vec<String> {
+ vec![
+ format!(
+ "{} {}",
+ theme::section_marker("◆").bold(),
+ theme::strong(section)
+ ),
+ String::new(),
+ format!("{} {}", theme::command("…").bold(), theme::strong(status)),
+ ]
+}
+
+fn clear_live_region(count: usize, cursor_on_last_line: bool) -> io::Result<()> {
+ let mut stdout = io::stdout();
+
+ if count == 0 {
+ return Ok(());
+ }
+
+ if cursor_on_last_line {
+ stdout.execute(MoveToColumn(0))?;
+ stdout.execute(Clear(ClearType::CurrentLine))?;
+ for _ in 1..count {
+ stdout.execute(MoveUp(1))?;
+ stdout.execute(MoveToColumn(0))?;
+ stdout.execute(Clear(ClearType::CurrentLine))?;
+ }
+ } else {
+ for _ in 0..count {
+ stdout.execute(MoveToColumn(0))?;
+ stdout.execute(MoveUp(1))?;
+ stdout.execute(MoveToColumn(0))?;
+ stdout.execute(Clear(ClearType::CurrentLine))?;
+ }
+ }
+
+ stdout.execute(MoveToColumn(0))?;
+ Ok(())
+}
+
+fn raw_line(text: impl AsRef<str>) -> io::Result<()> {
+ let mut stdout = io::stdout();
+ stdout.execute(MoveToColumn(0))?;
+ write!(stdout, "{}\r\n", text.as_ref())
+}
+
+fn raw_write(text: impl AsRef<str>) -> io::Result<()> {
+ write!(io::stdout(), "{}", text.as_ref())
+}
+
+fn empty_to_none(value: String) -> Option<String> {
+ let trimmed = value.trim();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed.to_string())
+ }
+}
+
+fn is_blank(value: Option<&str>) -> bool {
+ value.is_none_or(|value| value.trim().is_empty())
+}
+
+fn print_cancelled(ui: &mut LiveRegion) -> Result<()> {
+ ui.clear()?;
+ println!();
+ println!(
+ "{}",
+ theme::warning(copy(
+ Language::current(),
+ "Cancelled. No partial configuration was written.",
+ "已取消。未写入任何未完成配置。",
+ ))
+ );
+ Ok(())
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum PromptResult<T> {
+ Value(T),
+ Back,
+ Quit,
+}
+
+struct RawPrompt {
+ hide_cursor: bool,
+}
+
+impl RawPrompt {
+ fn enter(hide_cursor: bool) -> Result<Self> {
+ enable_raw_mode()?;
+ if hide_cursor {
+ io::stdout().execute(Hide)?;
+ }
+ Ok(Self { hide_cursor })
+ }
+}
+
+impl Drop for RawPrompt {
+ fn drop(&mut self) {
+ let _ = disable_raw_mode();
+ if self.hide_cursor {
+ let _ = io::stdout().execute(Show);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ IdentityMode, InputValueLabel, OV_LOGO_LINES, Rgb, 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,
+ 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,
+ wordmark_gradient_color_for_theme, wordmark_lines, wordmark_width,
+ };
+ use crate::config::Config;
+ use crate::config_wizard::store::{ApiKeyRole, ConfigEntry, ConfigKind, ConfigStore};
+ use crate::theme::{self, ThemeColor};
+ use serde_json::json;
+ use std::fs;
+ use std::path::PathBuf;
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ fn unique_dir(name: &str) -> PathBuf {
+ let suffix = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("clock should be valid")
+ .as_nanos();
+ std::env::temp_dir().join(format!("openviking-wizard-{name}-{suffix}"))
+ }
+
+ #[test]
+ fn wizard_header_is_scrollback_branded() {
+ let header = wizard_header_lines().join("\n");
+
+ assert!(header.contains("█████"));
+ assert!(!header.contains("Context Database for AI Agents"));
+ assert!(!header.contains(".openviking ~ ov config"));
+ assert!(!header.contains("CLI config"));
+ assert!(!header.contains("profile manager"));
+ assert!(!header.contains("↑/↓ choose"));
+ assert!(!header.contains("OpenViking CLI v"));
+ }
+
+ #[test]
+ fn erase_sequence_matches_display_width() {
+ assert_eq!(erase_sequence_for_char('a', false), "\x08 \x08");
+ assert_eq!(erase_sequence_for_char('中', false), "\x08 \x08\x08 \x08");
+ assert_eq!(erase_sequence_for_char('中', true), "\x08 \x08");
+ }
+
+ #[test]
+ fn wizard_header_has_spaced_bands() {
+ let lines = wizard_header_lines();
+
+ assert_eq!(lines[wordmark_lines().len()], "");
+ assert_eq!(lines.len(), wordmark_lines().len() + 1);
+ }
+
+ #[test]
+ fn header_omits_tagline_and_version() {
+ let lines = wizard_header_lines();
+ let header = lines.join("\n");
+
+ assert!(!header.contains("Context Database for AI Agents"));
+ assert!(!header.contains("OpenViking CLI v"));
+ }
+
+ #[test]
+ fn status_box_lines_align_to_wordmark_width_with_tagline_title_and_version_footer() {
+ let config = Config {
+ url: "http://127.0.0.1:1933".to_string(),
+ ..Config::default()
+ };
+ let lines = status_box_lines(
+ Some(&config),
+ &[ConfigEntry {
+ name: "test".to_string(),
+ config: config.clone(),
+ is_active: true,
+ kind: ConfigKind::SelfManaged,
+ }],
+ "~/.openviking",
+ );
+ let version = format!("v{}", env!("OPENVIKING_CLI_VERSION"));
+
+ assert!(lines.len() >= 6);
+ assert!(lines[0].contains("Context Database for AI Agents"));
+ assert!(!lines[0].contains(&version));
+ assert!(
+ lines
+ .last()
+ .expect("footer should render")
+ .contains(&version)
+ );
+ assert!(!lines[0].contains("OpenViking CLI"));
+ assert!(lines[0].starts_with('╭'));
+ assert!(lines[0].ends_with('╮'));
+ assert!(lines.last().expect("footer should render").starts_with('╰'));
+ assert!(lines.last().expect("footer should render").ends_with('╯'));
+ assert_eq!(status_box_width(), wordmark_width());
+ assert_eq!(display_width(&lines[0]), status_box_width());
+ assert!(
+ lines
+ .last()
+ .expect("footer should render")
+ .find(&version)
+ .expect("version should render")
+ > status_box_width() / 2
+ );
+ for line in &lines {
+ assert_eq!(display_width(line), status_box_width(), "{line:?}");
+ }
+ }
+
+ #[test]
+ fn status_box_cjk_lines_align_to_display_width() {
+ let width = status_box_width();
+ let title = box_title_line("AI Agent 上下文数据库", width);
+ let content = box_content_line("", "当前配置: VPS_ROOT (自托管)", width);
+ let footer = box_footer_line("v0.0.0", width);
+
+ for line in [title, content, footer] {
+ assert_eq!(display_width(&line), width, "{line:?}");
+ }
+ }
+
+ #[test]
+ fn status_box_contains_config_status_without_global_controls() {
+ let config = Config {
+ url: "http://127.0.0.1:1933".to_string(),
+ ..Config::default()
+ };
+ let lines = status_box_lines(
+ Some(&config),
+ &[ConfigEntry {
+ name: "orange".to_string(),
+ config: config.clone(),
+ is_active: true,
+ kind: ConfigKind::SelfManaged,
+ }],
+ "~/.openviking",
+ );
+ let text = lines.join("\n");
+
+ assert!(text.contains("Active:"));
+ assert!(text.contains("orange (Self-Managed)"));
+ assert!(text.contains("Status:"));
+ assert!(text.contains("VLM:"));
+ assert!(text.contains("Embedding:"));
+ assert!(text.contains("Saved configs:"));
+ assert!(text.contains("1"));
+ assert!(text.contains("Config home:"));
+ assert!(text.contains("~/.openviking"));
+ assert!(text.contains("Context Database for AI Agents"));
+ assert!(!text.contains("Save policy:"));
+ assert!(!text.contains("validation + explicit save"));
+ assert!(!text.contains("↑/↓ choose"));
+ assert!(!text.contains("Enter select"));
+ assert!(!text.contains("Esc back"));
+ }
+
+ #[test]
+ fn status_box_checking_runtime_renders_immediate_placeholders() {
+ let lines = status_box_lines_with_runtime(
+ None,
+ &[],
+ "~/.openviking",
+ &StatusBoxRuntime::checking(),
+ );
+ let text = lines.join("\n");
+
+ assert!(text.contains("Status: Checking..."));
+ assert!(text.contains("VLM: Checking..."));
+ assert!(text.contains("Embedding: Checking..."));
+ }
+
+ #[test]
+ fn status_box_can_render_healthy_status_and_runtime_models() {
+ let config = Config {
+ url: "http://127.0.0.1:1933".to_string(),
+ ..Config::default()
+ };
+ let runtime = StatusBoxRuntime::connected(
+ true,
+ Some("doubao-seed-2-0-pro-260215".to_string()),
+ Some("doubao-embedding-vision-251215".to_string()),
+ );
+ let lines = status_box_lines_with_runtime(
+ Some(&config),
+ &[ConfigEntry {
+ name: "vps".to_string(),
+ config: config.clone(),
+ is_active: true,
+ kind: ConfigKind::SelfManaged,
+ }],
+ "~/.openviking",
+ &runtime,
+ );
+ let text = lines.join("\n");
+
+ assert!(text.contains("Status: Connected (Healthy)"));
+ assert!(text.contains("VLM: doubao-seed-2-0-pro-260215"));
+ assert!(text.contains("Embedding: doubao-embedding-vision-251215"));
+ }
+
+ #[test]
+ fn status_payload_parser_reuses_ov_status_model_tables() {
+ let payload = json!({
+ "is_healthy": true,
+ "components": {
+ "models": {
+ "name": "models",
+ "is_healthy": true,
+ "status": "\nVLM Models:\n+-------+\n| Model | Provider |\n+-------+\n| doubao-seed-2-0-pro-260215 | volcengine |\n+-------+\n\nEmbedding Models:\n+-------+\n| Model | Provider |\n+-------+\n| doubao-embedding-vision-251215 | volcengine |\n+-------+\n"
+ }
+ }
+ });
+
+ assert_eq!(
+ extract_models_from_status_payload(&payload),
+ (
+ Some("doubao-seed-2-0-pro-260215".to_string()),
+ Some("doubao-embedding-vision-251215".to_string())
+ )
+ );
+ }
+
+ #[test]
+ fn status_payload_health_falls_back_to_component_health() {
+ let payload = json!({
+ "components": {
+ "queue": { "is_healthy": true, "has_errors": false },
+ "models": { "is_healthy": true, "has_errors": false }
+ }
+ });
+
+ assert!(status_payload_is_healthy(&payload));
+ }
+
+ #[test]
+ fn status_box_details_are_vertically_centered_without_label_justification() {
+ let config = Config {
+ url: "http://127.0.0.1:1933".to_string(),
+ ..Config::default()
+ };
+ let lines = status_box_lines(
+ Some(&config),
+ &[ConfigEntry {
+ name: "orange".to_string(),
+ config: config.clone(),
+ is_active: true,
+ kind: ConfigKind::SelfManaged,
+ }],
+ "~/.openviking",
+ );
+
+ let active_index = lines
+ .iter()
+ .position(|line| line.contains("Active:"))
+ .expect("active detail should render");
+
+ assert!(active_index > 2, "details should not start at the top");
+ assert!(
+ active_index + 6 < lines.len() - 1,
+ "details should not end at the bottom"
+ );
+ assert!(lines[active_index].contains("Active: orange (Self-Managed)"));
+ assert!(lines[active_index + 1].contains("Status: Unknown"));
+ assert!(lines[active_index + 2].contains("VLM: Unknown"));
+ assert!(lines[active_index + 3].contains("Embedding: Unknown"));
+ assert!(lines[active_index + 4].contains("Saved configs: 1"));
+ assert!(lines[active_index + 5].contains("Config home: ~/.openviking"));
+ assert!(!lines[active_index + 6].contains("Save policy:"));
+ }
+
+ #[test]
+ fn status_box_uses_filled_logo_instead_of_outline_sail() {
+ let lines = status_box_lines(None, &[], "~/.openviking");
+ let text = lines.join("\n");
+
+ assert!(text.contains("⣿⣿⣿⣧ ⠹⣿⣦⡀"));
+ assert!(text.contains("⢀⣾⡿⠿⠛⢛⣿⣿⣿⣿⣿⣿⣿⣿⡇⢀⣼⠃"));
+ assert!(text.contains("⠠⣶⣾⣿⣿⣿⣶⣤⣀ ⠾⠟⠛⠉⠉ ⣀⣤⣾⡿⠃"));
+ assert!(!text.contains("████ ▓▓▓▓"));
+ assert!(!text.contains("/\\"));
+ assert!(!text.contains("/____\\"));
+ }
+
+ #[test]
+ fn status_box_logo_uses_faceted_sails_with_negative_space() {
+ let logo = OV_LOGO_LINES.join("\n");
+ let split_rows = OV_LOGO_LINES
+ .iter()
+ .filter(|line| visible_group_count(line) >= 2)
+ .count();
+
+ assert_eq!(OV_LOGO_LINES.len(), 14);
+ assert!(ov_logo_width() <= 28);
+ assert!(
+ logo.contains('⣿'),
+ "logo should use high-detail filled facets"
+ );
+ assert!(logo.contains('⠿'), "logo should include sharp cut facets");
+ assert!(logo.contains("⣿⣿⣿⣧ ⠹⣿⣦⡀"));
+ assert!(logo.contains("⢀⣾⡿⠿⠛⢛⣿⣿⣿⣿⣿⣿⣿⣿⡇⢀⣼⠃"));
+ assert!(logo.contains("⠠⣶⣾⣿⣿⣿⣶⣤⣀ ⠾⠟⠛⠉⠉ ⣀⣤⣾⡿⠃"));
+ assert!(
+ split_rows >= 5,
+ "logo should preserve visible internal gaps"
+ );
+ assert!(
+ !logo.contains("████████████████"),
+ "logo should not collapse into a solid block"
+ );
+ }
+
+ fn visible_group_count(line: &str) -> usize {
+ let mut groups = 0;
+ let mut in_group = false;
+ for ch in line.chars() {
+ if ch.is_whitespace() {
+ in_group = false;
+ } else if !in_group {
+ groups += 1;
+ in_group = true;
+ }
+ }
+ groups
+ }
+
+ #[test]
+ fn display_config_home_uses_tilde_for_current_home() {
+ let home = std::env::var_os("HOME").expect("HOME should be set for CLI tests");
+ let dir = PathBuf::from(home).join(".openviking");
+ let store = ConfigStore::for_config_dir(dir.clone());
+
+ assert_eq!(display_config_home(&store), "~/.openviking");
+ }
+
+ #[test]
+ fn wordmark_lines_have_identical_width() {
+ let wordmark = wordmark_lines();
+ let width = display_width(wordmark[0]);
+
+ for line in wordmark {
+ assert_eq!(display_width(line), width, "{line:?} should match");
+ }
+ }
+
+ #[test]
+ fn wordmark_is_subtly_wider_for_viking_readability() {
+ let width = wordmark_width();
+
+ assert!(
+ (79..=83).contains(&width),
+ "wordmark should widen only enough to make VIKING readable; got {width}"
+ );
+ assert!(
+ wordmark_lines()[0].contains("██╗ ██╗ ██╗ ██╗ ██╗ ██╗"),
+ "VIKING should have subtle breathing room without obvious gaps"
+ );
+ }
+
+ #[test]
+ fn wordmark_visible_edges_are_consistent() {
+ let wordmark = wordmark_lines();
+ let width = wordmark_width();
+
+ for line in wordmark {
+ let first_visible = line
+ .chars()
+ .position(|ch| !ch.is_whitespace())
+ .expect("wordmark line should have visible text");
+ assert!(
+ first_visible <= 1,
+ "{line:?} should not protrude or drift horizontally"
+ );
+ assert!(
+ display_width(line.trim_end()) >= width - 1,
+ "{line:?} should reach the right edge"
+ );
+ }
+ }
+
+ #[test]
+ fn wordmark_does_not_use_protruding_corner_glyphs() {
+ let lines = wizard_header_lines();
+ let wordmark = &lines[0..wordmark_lines().len()];
+
+ assert!(!wordmark[0].starts_with('◢'));
+ assert!(!wordmark[0].ends_with('◣'));
+ assert!(!wordmark[wordmark.len() - 1].starts_with('◥'));
+ assert!(!wordmark[wordmark.len() - 1].ends_with('◤'));
+ }
+
+ #[test]
+ fn wordmark_gradient_runs_pearl_jade() {
+ let width = wordmark_width();
+ let palette = theme::active_theme();
+
+ assert_eq!(
+ wordmark_gradient_color_for_theme(palette, 0, width),
+ palette.wordmark_start
+ );
+ assert_eq!(
+ wordmark_gradient_color_for_theme(palette, width - 1, width),
+ palette.wordmark_end
+ );
+ let middle = wordmark_gradient_color_for_theme(palette, width / 2, width);
+ assert!(
+ middle.0 < palette.wordmark_start.0 && middle.1 < palette.wordmark_start.1,
+ "wordmark should visibly darken across the line"
+ );
+ }
+
+ #[test]
+ fn tagline_ice_color_runs_pearl_jade() {
+ let width = display_width("Context Database for AI Agents");
+ let palette = theme::active_theme();
+
+ assert_eq!(
+ tagline_ice_color_for_theme(palette, 0, width),
+ palette.tagline_start
+ );
+ assert_eq!(
+ tagline_ice_color_for_theme(palette, width / 2, width),
+ palette.tagline_mid
+ );
+ assert_eq!(
+ tagline_ice_color_for_theme(palette, width - 1, width),
+ palette.tagline_end
+ );
+ }
+
+ #[test]
+ fn status_box_border_uses_pearl_jade() {
+ assert_eq!(
+ theme::active_theme().border,
+ ThemeColor::TrueColor(Rgb(0, 128, 128))
+ );
+ }
+
+ #[test]
+ fn status_box_footer_version_uses_pearl_jade_accent() {
+ assert_eq!(
+ theme::active_theme().version,
+ ThemeColor::TrueColor(Rgb(0, 128, 128))
+ );
+ }
+
+ #[test]
+ fn status_box_logo_uses_diagonal_pearl_jade_gradient() {
+ let width = ov_logo_width();
+ let palette = theme::active_theme();
+
+ assert_eq!(
+ logo_glass_color_for_theme(palette, 0, 0, width),
+ palette.wordmark_start
+ );
+ assert_eq!(
+ logo_glass_color_for_theme(palette, width - 1, 13, width),
+ palette.logo_end
+ );
+ let middle = logo_glass_color_for_theme(palette, width / 2, 7, width);
+ assert!(
+ middle.1 > palette.logo_end.1 && middle.1 < palette.wordmark_start.1,
+ "logo middle should sit between the light and dark gradient stops"
+ );
+
+ let upper = logo_glass_color_for_theme(palette, width / 2, 1, width);
+ let lower = logo_glass_color_for_theme(palette, width / 2, 12, width);
+ assert!(
+ lower.0 < upper.0 && lower.1 < upper.1 && lower.2 < upper.2,
+ "logo should darken from top-left toward bottom-right"
+ );
+ }
+
+ #[test]
+ fn active_summary_hides_url_and_shows_kind() {
+ let mut config = Config::default();
+ config.url = "http://127.0.0.1:1933".to_string();
+ let lines = active_summary_lines(
+ Some(&config),
+ &[ConfigEntry {
+ name: "local".to_string(),
+ config: config.clone(),
+ is_active: true,
+ kind: ConfigKind::SelfManaged,
+ }],
+ );
+
+ assert_eq!(lines[0], "Active: local (Self-Managed)");
+ assert_eq!(lines[1], "Saved configs: 1");
+ assert!(!lines[0].contains("127.0.0.1"));
+ assert!(!lines[0].starts_with(' '));
+ assert!(!lines[1].starts_with(' '));
+ }
+
+ #[test]
+ fn summary_render_parts_split_config_name_type_and_count() {
+ let active = active_summary_render_parts("Active: test (Self-Managed)")
+ .expect("active summary should split");
+ let saved =
+ saved_summary_render_parts("Saved configs: 2").expect("saved summary should split");
+
+ assert_eq!(active.label, "Active:");
+ assert_eq!(active.name, "test");
+ assert_eq!(active.kind.as_deref(), Some("(Self-Managed)"));
+ assert_eq!(saved.label, "Saved configs:");
+ assert_eq!(saved.count, "2");
+ }
+
+ #[test]
+ fn add_config_name_copy_marks_name_optional() {
+ assert_eq!(add_config_name_label(), "Config name (optional)");
+ }
+
+ #[test]
+ fn add_config_name_rendering_has_no_default_or_current_label() {
+ let lines = input_live_lines(
+ "Create a new OpenViking config.",
+ add_config_name_label(),
+ None,
+ None,
+ false,
+ &["Leave empty to generate one.".to_string()],
+ None,
+ );
+
+ let text = lines.join("\n");
+ assert!(text.contains("Config name (optional)"));
+ assert!(text.contains("Leave empty to generate one."));
+ assert!(!text.contains("Default:"));
+ assert!(!text.contains("Current:"));
+ }
+
+ #[test]
+ fn edit_config_name_rendering_uses_current_label() {
+ let lines = input_live_lines(
+ "Update a saved config.",
+ "Config name",
+ Some("test"),
+ Some(InputValueLabel::Current),
+ false,
+ &[],
+ None,
+ );
+
+ let text = lines.join("\n");
+ assert!(text.contains("Current:"));
+ assert!(text.contains("test"));
+ assert!(!text.contains("Default:"));
+ }
+
+ #[test]
+ fn generated_config_name_is_valid_prefixed_and_non_colliding() {
+ let dir = unique_dir("generated-name");
+ fs::create_dir_all(&dir).expect("dir should exist");
+ let store = ConfigStore::for_config_dir(dir);
+
+ let name = allocate_config_name(&store, ConfigKind::SelfManaged)
+ .expect("generated name should be available");
+
+ assert!(name.starts_with("local-"));
+ assert_eq!(name.len(), "local-".len() + 6);
+ validate_config_name(&name).expect("generated name should be valid");
+ }
+
+ #[test]
+ fn provider_helper_copy_is_minimal_and_self_managed_is_clear() {
+ let cloud = volcengine_api_key_helper_lines();
+ let local_self_managed = self_managed_api_key_helper_lines(true);
+ let remote_self_managed = self_managed_api_key_helper_lines(false);
+
+ assert!(cloud.iter().any(|line| line.contains("Get your API key:")));
+ assert!(cloud.iter().any(|line| {
+ line.contains("Go to User Management → API Key to view and copy your key.")
+ }));
+ assert!(!cloud.iter().any(|line| line.contains("Server URL")));
+ assert!(
+ local_self_managed.iter().any(
+ |line| line.contains("Optional for local servers. Add one if auth is enabled.")
+ )
+ );
+ assert!(
+ remote_self_managed
+ .iter()
+ .any(|line| line.contains("Required for remote self-managed servers."))
+ );
+ assert!(
+ !remote_self_managed
+ .iter()
+ .any(|line| line.contains("Usually not needed locally"))
+ );
+ assert!(
+ !local_self_managed
+ .iter()
+ .chain(remote_self_managed.iter())
+ .any(|line| line.contains(';'))
+ );
+ }
+
+ #[test]
+ fn add_self_managed_api_key_rendering_has_no_existing_value_placeholder() {
+ let lines = input_live_lines(
+ "Create a new OpenViking config.",
+ "API key (optional)",
+ None,
+ None,
+ true,
+ &self_managed_api_key_helper_lines(true),
+ None,
+ );
+ let text = lines.join("\n");
+
+ assert!(!text.contains("(existing value)"));
+ assert!(!text.contains("Default:"));
+ assert!(!text.contains("Current:"));
+ }
+
+ #[test]
+ fn local_no_key_identity_prompt_shows_default_identity() {
+ let (default, value_label, helper_lines) = identity_prompt_parts(IdentityMode::LocalNoKey);
+ let lines = input_live_lines(
+ "Create a new OpenViking config.",
+ "Account ID",
+ default,
+ value_label,
+ false,
+ &helper_lines,
+ None,
+ );
+ let text = lines.join("\n");
+
+ assert!(text.contains("Default:"));
+ assert!(text.contains("default"));
+ assert!(text.contains("Local no-key identity."));
+ assert!(!text.contains("Press Enter"));
+ }
+
+ #[test]
+ fn root_key_identity_prompt_has_no_default_identity() {
+ let (default, value_label, helper_lines) = identity_prompt_parts(IdentityMode::RootKey);
+ let lines = input_live_lines(
+ "Create a new OpenViking config.",
+ "Account ID",
+ default,
+ value_label,
+ false,
+ &helper_lines,
+ None,
+ );
+ let text = lines.join("\n");
+
+ assert!(!text.contains("Default:"));
+ assert!(!text.contains("Current:"));
+ assert!(text.contains("Root API keys require an explicit account and user."));
+ }
+
+ #[test]
+ fn validation_failure_choices_are_kind_specific() {
+ assert_eq!(
+ cloud_validation_failure_choices(),
+ ["Retry API key", "Cancel"]
+ );
+ assert_eq!(
+ self_managed_validation_failure_choices(),
+ ["Edit server URL", "Edit API key", "Cancel"]
+ );
+ assert!(!cloud_validation_failure_choices().contains(&"Edit config name"));
+ }
+
+ #[test]
+ fn config_select_label_marks_active_with_badge() {
+ let config = Config {
+ url: "http://127.0.0.1:1933".to_string(),
+ ..Config::default()
+ };
+ let active = ConfigEntry {
+ name: "VPS".to_string(),
+ config: config.clone(),
+ is_active: true,
+ kind: ConfigKind::SelfManaged,
+ };
+ let inactive = ConfigEntry {
+ name: "local".to_string(),
+ config,
+ is_active: false,
+ kind: ConfigKind::SelfManaged,
+ };
+
+ let active_label = config_select_label(&active);
+ assert!(active_label.contains("VPS - Self-Managed"));
+ assert!(active_label.contains("[Active]"));
+ assert!(!active_label.contains("* "));
+
+ let inactive_label = config_select_label(&inactive);
+ assert_eq!(inactive_label, "local - Self-Managed");
+ assert!(!inactive_label.contains("[Active]"));
+ }
+
+ #[test]
+ fn active_delete_copy_mentions_switch_command() {
+ let copy = active_delete_block_helper_lines().join("\n");
+
+ assert!(copy.contains("Deleting the active config is blocked."));
+ assert!(copy.contains("ov config switch"));
+ assert!(copy.contains("then delete this one"));
+ }
+
+ #[test]
+ fn save_choices_allow_saving_without_activation() {
+ assert_eq!(
+ add_save_action_labels(),
+ ["Save and activate", "Save only", "Cancel"]
+ );
+ assert_eq!(
+ edit_save_action_labels(false),
+ ["Save only", "Save and activate", "Cancel"]
+ );
+ assert_eq!(edit_save_action_labels(true), ["Save changes", "Cancel"]);
+ }
+
+ #[test]
+ fn success_copy_points_to_help_command() {
+ assert!(next_step_copy().contains("ov --help"));
+ assert!(next_step_copy().contains("get started"));
+ }
+
+ #[test]
+ fn edit_api_key_choices_match_kind_and_existing_key_state() {
+ assert!(edit_api_key_choice_labels(ConfigKind::SelfManaged, false).is_empty());
+ assert!(edit_api_key_choice_labels(ConfigKind::VolcengineCloud, false).is_empty());
+ assert_eq!(
+ edit_api_key_choice_labels(ConfigKind::SelfManaged, true),
+ ["Keep existing API key", "Replace API key", "Clear API key"]
+ );
+ assert_eq!(
+ edit_api_key_choice_labels(ConfigKind::VolcengineCloud, true),
+ ["Keep existing API key", "Replace API key"]
+ );
+ }
+
+ #[test]
+ fn replaced_root_key_requires_identity_confirmation() {
+ assert!(should_prompt_root_identity(
+ Some(ApiKeyRole::Root),
+ true,
+ Some("old-account"),
+ Some("old-user"),
+ ));
+ assert!(should_prompt_root_identity(
+ Some(ApiKeyRole::Root),
+ false,
+ Some("old-account"),
+ None,
+ ));
+ assert!(!should_prompt_root_identity(
+ Some(ApiKeyRole::Root),
+ false,
+ Some("old-account"),
+ Some("old-user"),
+ ));
+ assert!(!should_prompt_root_identity(
+ Some(ApiKeyRole::Regular),
+ true,
+ Some("old-account"),
+ Some("old-user"),
+ ));
+ }
+
+ #[test]
+ fn live_select_lines_are_current_step_only() {
+ let lines = select_live_lines(
+ "What would you like to configure?",
+ "Choose action",
+ &["Add config", "Edit config", "Delete config"],
+ 1,
+ &[],
+ );
+
+ assert!(lines[0].contains("What would you like to configure?"));
+ assert!(lines.iter().any(|line| line.contains("› Edit config")));
+ assert!(!lines.iter().any(|line| line.contains("✓ Choose action")));
+ assert!(!lines.iter().any(|line| line.contains("Back")));
+ assert_eq!(lines.len(), 8);
+ }
+
+ #[test]
+ fn wizard_main_actions_stay_focused() {
+ assert_eq!(
+ main_action_labels(),
+ ["Add config", "Edit config", "Delete config"]
+ );
+ }
+}
diff --git a/crates/ov_cli/src/error.rs b/crates/ov_cli/src/error.rs
index 287c348e8..671e8e8b6 100644
--- a/crates/ov_cli/src/error.rs
+++ b/crates/ov_cli/src/error.rs
@@ -31,6 +31,9 @@ pub enum Error {
#[error("Zip error: {0}")]
Zip(#[from] zip::result::ZipError),
+
+ #[error("already reported")]
+ AlreadyReported,
}
pub type Result<T> = std::result::Result<T, Error>;
@@ -83,6 +86,7 @@ impl From<Error> for CliError {
Error::Io(e) => CliError::new(format!("IO error: {}", e)),
Error::Serialization(e) => CliError::new(format!("Serialization error: {}", e)),
Error::Zip(e) => CliError::new(format!("Zip error: {}", e)),
+ Error::AlreadyReported => CliError::new("already reported"),
}
}
}
diff --git a/crates/ov_cli/src/error_classifier.rs b/crates/ov_cli/src/error_classifier.rs
new file mode 100644
index 000000000..a1d050206
--- /dev/null
+++ b/crates/ov_cli/src/error_classifier.rs
@@ -0,0 +1,35 @@
+pub(crate) fn looks_like_auth_error(message: &str) -> bool {
+ let lower = message.to_ascii_lowercase();
+ lower.contains("api key")
+ || lower.contains("unauthorized")
+ || lower.contains("forbidden")
+ || lower.contains("authentication")
+ || lower
+ .split(|ch: char| !ch.is_ascii_alphanumeric())
+ .any(|token| token == "auth")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::looks_like_auth_error;
+
+ #[test]
+ fn detects_auth_errors() {
+ for message in [
+ "API key is invalid",
+ "request was unauthorized",
+ "forbidden",
+ "authentication failed",
+ "auth failed",
+ ] {
+ assert!(looks_like_auth_error(message), "{message}");
+ }
+ }
+
+ #[test]
+ fn avoids_auth_substring_false_positives() {
+ for message in ["author not found", "authority unavailable"] {
+ assert!(!looks_like_auth_error(message), "{message}");
+ }
+ }
+}
diff --git a/crates/ov_cli/src/error_ui.rs b/crates/ov_cli/src/error_ui.rs
new file mode 100644
index 000000000..1ec8b9b93
--- /dev/null
+++ b/crates/ov_cli/src/error_ui.rs
@@ -0,0 +1,588 @@
+use std::ffi::OsString;
+
+use colored::Colorize;
+use unicode_width::UnicodeWidthStr;
+
+use crate::{
+ error::Error,
+ error_classifier::looks_like_auth_error,
+ i18n::{Language, copy},
+ theme,
+};
+
+const CARD_WIDTH: usize = 72;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ErrorAction {
+ command: String,
+ description: String,
+}
+
+impl ErrorAction {
+ pub(crate) fn new(command: impl Into<String>, description: impl Into<String>) -> Self {
+ Self {
+ command: command.into(),
+ description: description.into(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ErrorReport {
+ command: Option<String>,
+ usage: Option<String>,
+ title: String,
+ message: String,
+ suggestion: Option<String>,
+ detail: Option<String>,
+ actions: Vec<ErrorAction>,
+}
+
+impl ErrorReport {
+ pub(crate) fn new(title: impl Into<String>, message: impl Into<String>) -> Self {
+ Self {
+ command: None,
+ usage: None,
+ title: title.into(),
+ message: message.into(),
+ suggestion: None,
+ detail: None,
+ actions: Vec::new(),
+ }
+ }
+
+ pub(crate) fn with_command(mut self, command: impl Into<String>) -> Self {
+ self.command = Some(command.into());
+ self
+ }
+
+ pub(crate) fn with_usage(mut self, usage: impl Into<String>) -> Self {
+ self.usage = Some(usage.into());
+ self
+ }
+
+ pub(crate) fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
+ self.suggestion = Some(suggestion.into());
+ self
+ }
+
+ pub(crate) fn with_detail(mut self, detail: impl Into<String>) -> Self {
+ self.detail = Some(detail.into());
+ self
+ }
+
+ pub(crate) fn with_actions(mut self, actions: Vec<ErrorAction>) -> Self {
+ self.actions = actions;
+ self
+ }
+}
+
+pub(crate) fn print_report(report: &ErrorReport, verbose: bool) {
+ eprint!("{}", render_report(report, verbose));
+}
+
+pub(crate) fn report_for_clap_error(args: &[OsString], clap_output: &str) -> ErrorReport {
+ let language = Language::current();
+ let command = display_command(args);
+ let usage = parse_usage(clap_output);
+
+ if is_setup_cli_command(args) {
+ return ErrorReport::new(
+ copy(language, "Command Error", "命令错误"),
+ copy(
+ language,
+ "Use ov config to add, edit, or delete configs.",
+ "请使用 ov config 添加、编辑或删除配置。",
+ ),
+ )
+ .with_command(command)
+ .with_optional_usage(usage)
+ .with_suggestion("ov config")
+ .with_actions(vec![
+ ErrorAction::new(
+ "ov config",
+ copy(
+ language,
+ "Add, edit, or delete configs",
+ "添加、编辑或删除配置",
+ ),
+ ),
+ ErrorAction::new(
+ "ov config show",
+ copy(language, "Show the active config", "显示当前配置"),
+ ),
+ ErrorAction::new(
+ "ov config validate",
+ copy(language, "Check the active config", "检查当前配置"),
+ ),
+ ]);
+ }
+
+ let unknown = parse_unknown_subcommand(clap_output);
+ let suggestion = parse_clap_subcommand_suggestion(clap_output)
+ .map(|suggested| qualified_suggestion(args, &suggested));
+ let mut actions = Vec::new();
+ if let Some(suggestion) = suggestion.as_ref() {
+ actions.push(ErrorAction::new(
+ suggestion,
+ copy(language, "Run the suggested command", "运行建议的命令"),
+ ));
+ }
+ actions.push(ErrorAction::new(
+ "ov --help",
+ copy(language, "Show all commands", "查看所有命令"),
+ ));
+
+ let message = unknown
+ .map(|value| match language {
+ Language::En => format!("Unknown command: {value}"),
+ Language::ZhCn => format!("未知命令:{value}"),
+ })
+ .unwrap_or_else(|| first_error_line(clap_output));
+
+ let mut report = ErrorReport::new(copy(language, "Command Error", "命令错误"), message)
+ .with_command(command)
+ .with_optional_usage(usage)
+ .with_actions(actions);
+ if let Some(suggestion) = suggestion {
+ report = report.with_suggestion(suggestion);
+ }
+ report
+}
+
+pub(crate) fn report_for_message_error(
+ command: impl Into<String>,
+ title: impl Into<String>,
+ message: impl Into<String>,
+ actions: Vec<ErrorAction>,
+) -> ErrorReport {
+ ErrorReport::new(title, message)
+ .with_command(command)
+ .with_actions(actions)
+}
+
+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::Config(message) => ErrorReport::new(copy(language, "Configuration 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", "显示当前配置")),
+ ]),
+ Error::Network(message) => ErrorReport::new(
+ copy(language, "Connection Error", "连接错误"),
+ copy(
+ language,
+ "Could not reach OpenViking. The server may be offline, or this config points to the wrong URL.",
+ "无法连接 OpenViking。服务器可能未启动,或当前配置指向了错误的 URL。",
+ ),
+ )
+ .with_command(command)
+ .with_detail(message)
+ .with_actions(vec![
+ ErrorAction::new("ov config validate", copy(language, "Check the active config", "检查当前配置")),
+ ErrorAction::new("ov health", copy(language, "Run a quick server health check", "快速检查服务器健康状态")),
+ ErrorAction::new("ov config switch", copy(language, "Switch to another config", "切换到其他配置")),
+ ]),
+ Error::Api(message) if looks_like_auth_error(message) => ErrorReport::new(
+ copy(language, "Authentication Error", "认证错误"),
+ copy(language, "OpenViking rejected the API key for the active config.", "OpenViking 拒绝了当前配置的 API Key。"),
+ )
+ .with_command(command)
+ .with_detail(message)
+ .with_actions(vec![
+ ErrorAction::new("ov config", copy(language, "Edit this config", "编辑这个配置")),
+ ErrorAction::new("ov config switch", copy(language, "Use another config", "使用其他配置")),
+ ]),
+ Error::Api(message) => ErrorReport::new(
+ copy(language, "OpenViking API Error", "OpenViking API 错误"),
+ copy(language, "OpenViking returned an error for this request.", "OpenViking 返回了请求错误。"),
+ )
+ .with_command(command)
+ .with_detail(message)
+ .with_actions(vec![
+ ErrorAction::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::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::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()),
+ Error::Serialization(error) => {
+ ErrorReport::new(copy(language, "Serialization Error", "序列化错误"), copy(language, "OpenViking could not parse structured data.", "OpenViking 无法解析结构化数据。"))
+ .with_command(command)
+ .with_detail(error.to_string())
+ }
+ Error::Zip(error) => ErrorReport::new(copy(language, "Archive Error", "压缩包错误"), copy(language, "OpenViking could not process the archive.", "OpenViking 无法处理压缩包。"))
+ .with_command(command)
+ .with_detail(error.to_string()),
+ Error::AlreadyReported => ErrorReport::new(copy(language, "Command Error", "命令错误"), copy(language, "The command failed.", "命令执行失败。"))
+ .with_command(command),
+ }
+}
+
+pub(crate) fn render_report(report: &ErrorReport, verbose: bool) -> String {
+ let mut output = String::new();
+ let language = Language::current();
+
+ if let Some(command) = report.command.as_deref() {
+ output.push_str(&format!("{}\n\n", theme::strong(command)));
+ }
+ if let Some(usage) = report.usage.as_deref() {
+ output.push_str(&format!(
+ "{} {}\n",
+ theme::warning(copy(language, "Usage:", "用法:")).bold(),
+ theme::strong(usage)
+ ));
+ output.push_str(&format!(
+ "{} {}\n\n",
+ theme::muted(copy(language, "Try:", "可尝试:")),
+ theme::command("ov --help")
+ ));
+ }
+
+ output.push_str(&render_card(report, verbose));
+
+ if !report.actions.is_empty() {
+ output.push_str("\n\n");
+ output.push_str(&format!(
+ "{}\n",
+ theme::strong(copy(language, "Next:", "下一步:"))
+ ));
+ let command_width = report
+ .actions
+ .iter()
+ .map(|action| action.command.width())
+ .max()
+ .unwrap_or_default();
+ for action in &report.actions {
+ output.push_str(&format!(
+ " {}{} {}\n",
+ theme::command(action.command.clone()).bold(),
+ " ".repeat(command_width.saturating_sub(action.command.width())),
+ theme::muted(&action.description)
+ ));
+ }
+ } else {
+ output.push('\n');
+ }
+
+ output
+}
+
+trait OptionalUsage {
+ fn with_optional_usage(self, usage: Option<String>) -> Self;
+}
+
+impl OptionalUsage for ErrorReport {
+ fn with_optional_usage(self, usage: Option<String>) -> Self {
+ if let Some(usage) = usage {
+ self.with_usage(usage)
+ } else {
+ self
+ }
+ }
+}
+
+fn render_card(report: &ErrorReport, verbose: bool) -> String {
+ let language = Language::current();
+ let inner_width = CARD_WIDTH.saturating_sub(4);
+ let title = format!("─ {} ", report.title);
+ let fill = CARD_WIDTH.saturating_sub(2 + title.width());
+ let mut lines = Vec::new();
+
+ lines.extend(wrap_text(&report.message, inner_width));
+ if let Some(suggestion) = report.suggestion.as_deref() {
+ lines.push(String::new());
+ lines.extend(wrap_text(&did_you_mean(language, suggestion), inner_width));
+ }
+ if verbose {
+ if let Some(detail) = report.detail.as_deref() {
+ lines.push(String::new());
+ lines.extend(wrap_text(&detail_line(language, detail), inner_width));
+ }
+ }
+
+ let mut rendered = String::new();
+ rendered.push_str(&format!(
+ "{}{}{}{}\n",
+ theme::error("╭"),
+ theme::error(title).bold(),
+ theme::error("─".repeat(fill)),
+ theme::error("╮")
+ ));
+ for line in lines {
+ rendered.push_str(&render_card_line(&line, inner_width));
+ rendered.push('\n');
+ }
+ rendered.push_str(&format!(
+ "{}{}{}",
+ theme::error("╰"),
+ theme::error("─".repeat(CARD_WIDTH.saturating_sub(2))),
+ theme::error("╯")
+ ));
+ rendered
+}
+
+fn did_you_mean(language: Language, suggestion: &str) -> String {
+ match language {
+ Language::En => format!("Did you mean: {suggestion}"),
+ Language::ZhCn => format!("你是不是想运行:{suggestion}"),
+ }
+}
+
+fn detail_line(language: Language, detail: &str) -> String {
+ match language {
+ Language::En => format!("Detail: {detail}"),
+ Language::ZhCn => format!("详情:{detail}"),
+ }
+}
+
+fn render_card_line(line: &str, inner_width: usize) -> String {
+ let width = line.width();
+ let padding = inner_width.saturating_sub(width);
+ format!(
+ "{} {}{} {}",
+ theme::error("│"),
+ theme::body(line),
+ " ".repeat(padding),
+ theme::error("│")
+ )
+}
+
+fn wrap_text(text: &str, width: usize) -> Vec<String> {
+ if text.is_empty() {
+ return vec![String::new()];
+ }
+
+ let mut lines = Vec::new();
+ let mut current = String::new();
+
+ for word in text.split_whitespace() {
+ let separator = if current.is_empty() { 0 } else { 1 };
+ if !current.is_empty() && current.width() + separator + word.width() > width {
+ lines.push(current);
+ current = String::new();
+ }
+ if !current.is_empty() {
+ current.push(' ');
+ }
+ current.push_str(word);
+ }
+
+ if !current.is_empty() {
+ lines.push(current);
+ }
+ lines
+}
+
+pub(crate) fn display_command(args: &[OsString]) -> String {
+ let mut parts = vec!["ov".to_string()];
+ parts.extend(
+ args.iter()
+ .skip(1)
+ .map(|arg| arg.to_string_lossy().into_owned()),
+ );
+ parts.join(" ")
+}
+
+fn is_setup_cli_command(args: &[OsString]) -> bool {
+ let parts = args
+ .iter()
+ .skip(1)
+ .map(|arg| arg.to_string_lossy())
+ .collect::<Vec<_>>();
+ parts.as_slice() == ["config", "setup-cli"]
+}
+
+fn parse_usage(clap_output: &str) -> Option<String> {
+ clap_output
+ .lines()
+ .find_map(|line| line.trim().strip_prefix("Usage: "))
+ .map(ToString::to_string)
+}
+
+fn parse_unknown_subcommand(clap_output: &str) -> Option<String> {
+ clap_output.lines().find_map(|line| {
+ let trimmed = line.trim();
+ if trimmed.starts_with("error: unrecognized subcommand ") {
+ first_single_quoted(trimmed)
+ } else {
+ None
+ }
+ })
+}
+
+fn parse_clap_subcommand_suggestion(clap_output: &str) -> Option<String> {
+ clap_output.lines().find_map(|line| {
+ let trimmed = line.trim();
+ if trimmed.contains("similar subcommand") {
+ first_single_quoted(trimmed)
+ } else {
+ None
+ }
+ })
+}
+
+fn first_single_quoted(value: &str) -> Option<String> {
+ let start = value.find('\'')?;
+ let rest = &value[start + 1..];
+ let end = rest.find('\'')?;
+ Some(rest[..end].to_string())
+}
+
+fn qualified_suggestion(args: &[OsString], suggested_leaf: &str) -> String {
+ let mut parts = args
+ .iter()
+ .skip(1)
+ .map(|arg| arg.to_string_lossy().into_owned())
+ .collect::<Vec<_>>();
+ if parts.is_empty() {
+ parts.push(suggested_leaf.to_string());
+ } else if let Some(last) = parts.last_mut() {
+ *last = suggested_leaf.to_string();
+ }
+
+ if parts.is_empty() {
+ "ov".to_string()
+ } else {
+ format!("ov {}", parts.join(" "))
+ }
+}
+
+fn first_error_line(clap_output: &str) -> String {
+ 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())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ CARD_WIDTH, ErrorReport, render_report, report_for_clap_error, report_for_runtime_error,
+ };
+ use crate::error::Error;
+ use std::ffi::OsString;
+ use unicode_width::UnicodeWidthStr;
+
+ fn os_args(args: &[&str]) -> Vec<OsString> {
+ args.iter().map(OsString::from).collect()
+ }
+
+ 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 command_typo_uses_clap_suggestion() {
+ let clap_output = "\
+error: unrecognized subcommand 'configure'
+
+ tip: a similar subcommand exists: 'config'
+
+Usage: ov [OPTIONS] <COMMAND>
+";
+ let report = report_for_clap_error(&os_args(&["ov", "configure"]), clap_output);
+ let rendered = strip_ansi(&render_report(&report, false));
+
+ assert!(rendered.contains("ov configure"));
+ assert!(rendered.contains("Usage: ov [OPTIONS] <COMMAND>"));
+ assert!(rendered.contains("Unknown command: configure"));
+ assert!(rendered.contains("Did you mean: ov config"));
+ assert!(rendered.contains("ov --help"));
+ }
+
+ #[test]
+ fn removed_setup_cli_only_suggests_ov_config() {
+ let clap_output = "\
+error: unrecognized subcommand 'setup-cli'
+
+Usage: ov config [OPTIONS] [COMMAND]
+";
+ let report = report_for_clap_error(&os_args(&["ov", "config", "setup-cli"]), clap_output);
+ let rendered = strip_ansi(&render_report(&report, false));
+
+ assert!(rendered.contains("ov config setup-cli"));
+ assert!(rendered.contains("Did you mean: ov config"));
+ assert!(rendered.contains("ov config"));
+ assert!(rendered.contains("ov config show"));
+ assert!(!rendered.contains("ov config setup-cli to initialize"));
+ assert!(!rendered.contains("no longer available"));
+ assert!(!rendered.contains("deprecated"));
+ }
+
+ #[test]
+ fn runtime_api_error_hides_raw_detail_by_default() {
+ let error = Error::Api(
+ "[AuthenticationError] API key invalid. Request ID: 02177930089909800000000000000000"
+ .to_string(),
+ );
+ let report = report_for_runtime_error("ov status", &error);
+ let normal = strip_ansi(&render_report(&report, false));
+ let verbose = strip_ansi(&render_report(&report, true));
+
+ assert!(normal.contains("Authentication Error"));
+ assert!(normal.contains("OpenViking rejected the API key"));
+ assert!(normal.contains("ov config"));
+ assert!(!normal.contains("Request ID"));
+ assert!(!normal.contains("AuthenticationError"));
+
+ assert!(verbose.contains("Detail:"));
+ assert!(verbose.contains("Request ID"));
+ }
+
+ #[test]
+ fn network_error_suggests_validation_and_health_commands() {
+ let error = Error::Network("HTTP request failed: connection refused".to_string());
+ let report = report_for_runtime_error("ov status", &error);
+ let rendered = strip_ansi(&render_report(&report, false));
+
+ assert!(rendered.contains("Connection Error"));
+ assert!(rendered.contains("Could not reach OpenViking"));
+ assert!(rendered.contains("ov config validate"));
+ assert!(rendered.contains("ov health"));
+ assert!(rendered.contains("ov config switch"));
+ }
+
+ #[test]
+ fn chinese_error_card_uses_display_width_for_borders() {
+ let report = ErrorReport::new("命令错误", "未知命令:con").with_suggestion("ov config");
+ let rendered = strip_ansi(&render_report(&report, false));
+
+ for line in rendered
+ .lines()
+ .filter(|line| line.starts_with('╭') || line.starts_with('│') || line.starts_with('╰'))
+ {
+ assert_eq!(line.width(), CARD_WIDTH, "{line}");
+ }
+ }
+}
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index 3f1747807..cc9c8d1c4 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -4,7 +4,9 @@ use crate::client;
use crate::commands;
use crate::config::merge_csv_options;
use crate::error::{Error, Result};
+use crate::theme;
use crate::tui;
+use colored::Colorize;
pub async fn handle_add_resource(
mut path: String,
@@ -251,7 +253,13 @@ pub async fn handle_system(cmd: SystemCommands, ctx: CliContext) -> Result<()> {
commands::system::status(&client, ctx.output_format, ctx.compact).await
}
SystemCommands::Health => {
- let _ = commands::system::health(&client, ctx.output_format, ctx.compact).await?;
+ let _ = commands::system::health(
+ &client,
+ Some(&ctx.config),
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await?;
Ok(())
}
SystemCommands::Consistency { uri } => {
@@ -572,334 +580,439 @@ pub async fn handle_privacy(cmd: PrivacyCommands, ctx: CliContext) -> Result<()>
}
use crate::ConfigCommands;
-use crate::base_client::BaseClient;
use crate::config::Config;
+use crate::config_command_ui::{self, SwitchConfigRow};
+use crate::config_wizard::{self, ConfigStore};
+use crate::i18n::{self, Language};
use crate::output;
-pub async fn handle_config(cmd: ConfigCommands, _ctx: CliContext) -> Result<()> {
+// Config commands intentionally edit the persisted ovcli.conf files. Runtime
+// overrides carried in CliContext should not change what gets shown or saved.
+pub async fn handle_config(cmd: Option<ConfigCommands>, _ctx: CliContext) -> Result<()> {
match cmd {
- ConfigCommands::Show => {
+ Some(ConfigCommands::Show) => {
let config = Config::load()?;
output::output_success(
- &serde_json::to_value(config).unwrap(),
+ &config_wizard::redacted_config_value(&config)?,
output::OutputFormat::Json,
true,
);
Ok(())
}
- ConfigCommands::Validate => match Config::load() {
- Ok(_) => {
- println!("Configuration is valid");
- Ok(())
+ Some(ConfigCommands::Validate) => {
+ let config = Config::load()?;
+ let store = ConfigStore::new()?;
+ let active_name = active_config_name(&store)?;
+ match config_wizard::validate_config(&config).await {
+ Ok(()) => {
+ print!(
+ "{}",
+ config_command_ui::render_validate_success(&config, active_name.as_deref(),)
+ );
+ Ok(())
+ }
+ Err(error) => {
+ print!(
+ "{}",
+ config_command_ui::render_validate_failure(
+ &config,
+ active_name.as_deref(),
+ &error,
+ )
+ );
+ Err(Error::AlreadyReported)
+ }
}
- Err(e) => Err(Error::Config(e.to_string())),
- },
- ConfigCommands::SetupCli => handle_setup_cli().await,
- ConfigCommands::Switch => handle_config_switch().await,
+ }
+ Some(ConfigCommands::Switch) => handle_config_switch().await,
+ None => config_wizard::run_config_wizard().await,
}
}
-/// Interactive setup for CLI configuration
-async fn handle_setup_cli() -> Result<()> {
- use colored::Colorize;
- use rustyline::DefaultEditor;
+pub async fn handle_language(value: Option<String>) -> Result<()> {
+ let language = match value {
+ Some(value) => Language::from_code(&value).ok_or_else(|| {
+ Error::Config(format!(
+ "Unsupported language '{value}'. Use 'en' or 'zh-CN'."
+ ))
+ })?,
+ None => {
+ let current = Language::current();
+ println!("{}", language_title(current));
+ println!(
+ "{} {}",
+ theme::muted(language_label("Current:", "当前语言:", current)),
+ theme::command(current.label()).bold()
+ );
+ println!();
+ let choices = vec![
+ Language::En.label().to_string(),
+ Language::ZhCn.label().to_string(),
+ ];
+ match prompt_select(language_prompt(current), &choices, 0)? {
+ SelectOutcome::Selected(0) => Language::En,
+ SelectOutcome::Selected(1) => Language::ZhCn,
+ SelectOutcome::Back | SelectOutcome::Quit => {
+ println!("{}", theme::muted(language_no_change(current)));
+ return Ok(());
+ }
+ SelectOutcome::Selected(_) => {
+ unreachable!("selection is constrained by language list")
+ }
+ }
+ }
+ };
- println!("{}", "Welcome to OpenViking CLI Setup!".bold().green());
- println!();
+ i18n::save_language(language)?;
+ println!("{}", theme::success(language_saved(language)).bold());
+ Ok(())
+}
- // Load existing config if available
- let mut config = match Config::load_default() {
- Ok(c) => c,
- Err(_) => Config::default(),
- };
+fn language_title(language: Language) -> String {
+ theme::brand_title(match language {
+ Language::En => "OPENVIKING LANGUAGE".to_string(),
+ Language::ZhCn => "OPENVIKING 语言设置".to_string(),
+ })
+ .bold()
+ .to_string()
+}
- let mut rl = DefaultEditor::new()
- .map_err(|e| Error::Config(format!("Failed to initialize input editor: {}", e)))?;
+fn language_prompt(language: Language) -> &'static str {
+ match language {
+ Language::En => "Choose language",
+ Language::ZhCn => "选择语言",
+ }
+}
- // Step 1: Get server URL
- let default_url = config.url.clone();
- let prompt = format!("OpenViking Server URL [{}]: ", default_url);
- let url_input = rl.readline(&prompt).unwrap_or_default();
- let url = if url_input.trim().is_empty() {
- default_url
- } else {
- url_input.trim().to_string()
- };
+fn language_label<'a>(en: &'a str, zh: &'a str, language: Language) -> &'a str {
+ match language {
+ Language::En => en,
+ Language::ZhCn => zh,
+ }
+}
- // Update config with URL immediately for probing
- config.url = url.clone();
+fn language_saved(language: Language) -> &'static str {
+ match language {
+ Language::En => "Language set to English.",
+ Language::ZhCn => "语言已切换为简体中文。",
+ }
+}
- // Step 2: Probe health endpoint
- println!();
- println!("{}", "Probing server health...".blue());
- let probe_result = probe_health(&url, 5.0).await;
+fn language_no_change(language: Language) -> &'static str {
+ match language {
+ Language::En => "Language was not changed.",
+ Language::ZhCn => "语言未更改。",
+ }
+}
- let needs_api_key = match probe_result {
- Ok((healthy, auth_required)) => {
- if healthy {
- println!("{}", "✓ Server is healthy!".green());
- } else {
- println!("{}", "⚠ Server responded but reports unhealthy".yellow());
- }
- auth_required
- }
- Err(e) => {
- println!("{}", format!("⚠ Could not reach server: {}", e).yellow());
- // Default to asking for API key if we can't probe
- true
- }
- };
+/// Interactive configuration switcher
+async fn handle_config_switch() -> Result<()> {
+ let store = ConfigStore::new()?;
+ let configs = store.list_configs()?;
- // Step 3: Ask for API key if needed
- if needs_api_key {
- println!();
- let default_key = config.api_key.clone().unwrap_or_default();
- let prompt = if default_key.is_empty() {
- "API Key (optional, press Enter to skip): ".to_string()
- } else {
- format!("API Key [{}]: ", "*".repeat(default_key.len().min(8)))
- };
- let key_input = rl.readline(&prompt).unwrap_or_default();
- if !key_input.trim().is_empty() {
- config.api_key = Some(key_input.trim().to_string());
- } else if default_key.is_empty() {
- config.api_key = None;
- }
+ if configs.is_empty() {
+ print!("{}", config_command_ui::render_no_saved_configs());
+ return Ok(());
}
- // Step 4: Save config
- println!();
- let config_path = crate::config::default_config_path()?;
- println!(
+ let active = configs.iter().find(|config| config.is_active);
+ print!(
"{}",
- format!("Saving configuration to: {}", config_path.to_string_lossy()).blue()
+ config_command_ui::render_switch_header(
+ active.map(|config| config.name.as_str()),
+ active.map(|config| config.kind),
+ )
);
- config.save_default()?;
-
- // Step 5: Optionally save a named backup
- println!();
- let prompt = "Name this configuration (optional, press Enter to skip): ";
- let name_input = rl.readline(prompt).unwrap_or_default();
- if !name_input.trim().is_empty() {
- let config_name = name_input.trim().to_string();
- if let Some(parent) = config_path.parent() {
- let backup_path = parent.join(format!("ovcli.conf.{}", config_name));
- std::fs::copy(&config_path, &backup_path).map_err(|e| {
- Error::Config(format!("Failed to save configuration backup: {}", e))
- })?;
+
+ loop {
+ let rows: Vec<SwitchConfigRow> = configs
+ .iter()
+ .map(|config| SwitchConfigRow {
+ name: config.name.clone(),
+ kind: config.kind,
+ is_active: config.is_active,
+ })
+ .collect();
+ let labels = config_command_ui::switch_labels(&rows);
+ let language = Language::current();
+ let index = match prompt_select(
+ config_switch_prompt(language, "Choose config", "选择配置"),
+ &labels,
+ 0,
+ )? {
+ SelectOutcome::Selected(index) => index,
+ SelectOutcome::Back | SelectOutcome::Quit => {
+ println!("{}", theme::muted(config_not_changed(language)));
+ return Ok(());
+ }
+ };
+
+ let selected = configs[index].clone();
+ if selected.is_active {
println!(
"{}",
- format!(
- "✓ Configuration saved as backup: {}",
- backup_path.to_string_lossy()
- )
- .green()
+ theme::muted(config_already_active(language, &selected.name))
);
+ return Ok(());
+ }
+
+ let confirmation = switch_confirmation_labels();
+ match switch_confirmation_decision(prompt_select(
+ &config_switch_confirm_prompt(language, &selected.name),
+ &confirmation,
+ 0,
+ )?) {
+ SwitchConfirmationDecision::Confirm => {
+ println!("{}", theme::muted(validating_target_config(language)));
+ if let Err(error) = config_wizard::validate_config(&selected.config).await {
+ print!(
+ "{}",
+ config_command_ui::render_switch_validation_failure(&selected.name, &error,)
+ );
+ return Err(Error::AlreadyReported);
+ }
+ store.activate_config(&selected.name)?;
+ print!(
+ "{}",
+ config_command_ui::render_switch_success(&selected.name)
+ );
+ return Ok(());
+ }
+ SwitchConfirmationDecision::Back => continue,
+ SwitchConfirmationDecision::Quit => {
+ println!("{}", theme::muted(config_not_changed(language)));
+ return Ok(());
+ }
}
}
+}
- println!();
- println!("{}", "✓ Setup complete!".bold().green());
- println!(
- "{}",
- "You can now use the 'ov' command to interact with OpenViking.".dimmed()
- );
- println!(
- "{}",
- "Use 'ov config switch' to switch between saved configurations.".dimmed()
- );
+fn active_config_name(store: &ConfigStore) -> Result<Option<String>> {
+ Ok(store
+ .list_configs()?
+ .into_iter()
+ .find(|entry| entry.is_active)
+ .map(|entry| entry.name))
+}
- Ok(())
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SelectOutcome {
+ Selected(usize),
+ Back,
+ Quit,
}
-/// Probe health endpoint to check server status and auth requirement
-async fn probe_health(base_url: &str, timeout_secs: f64) -> Result<(bool, bool)> {
- let client = BaseClient::new_simple(base_url, timeout_secs);
+fn prompt_select(prompt: &str, items: &[String], default: usize) -> Result<SelectOutcome> {
+ use std::io::{self, Write};
- // First try without API key
- let result: Result<serde_json::Value> = client.get("/health", &[]).await;
+ use crossterm::{
+ cursor,
+ event::{self, Event, KeyCode, KeyModifiers},
+ execute,
+ terminal::{self, Clear, ClearType},
+ };
- match result {
- Ok(value) => {
- let healthy = value
- .get("healthy")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
- Ok((healthy, false))
+ if items.is_empty() {
+ return Ok(SelectOutcome::Back);
+ }
+
+ struct RawGuard {
+ hide_cursor: bool,
+ }
+ impl RawGuard {
+ fn enter() -> Result<Self> {
+ terminal::enable_raw_mode()?;
+ let mut stdout = io::stdout();
+ if let Err(error) = execute!(stdout, cursor::Hide) {
+ let _ = terminal::disable_raw_mode();
+ return Err(error.into());
+ }
+ Ok(Self { hide_cursor: true })
}
- Err(Error::Api(msg)) => {
- // If we get auth-related errors, auth is required
- if msg.contains("401")
- || msg.contains("403")
- || msg.contains("unauthorized")
- || msg.contains("forbidden")
- || msg.contains("AuthenticationError")
- {
- Ok((false, true))
- } else {
- Ok((false, false))
+ }
+ impl Drop for RawGuard {
+ fn drop(&mut self) {
+ let _ = crossterm::terminal::disable_raw_mode();
+ if self.hide_cursor {
+ let _ = execute!(io::stdout(), cursor::Show);
}
}
- Err(_) => Ok((false, true)),
}
-}
-/// Interactive configuration switcher
-async fn handle_config_switch() -> Result<()> {
- use colored::Colorize;
-
- // Step 1: Find all available configurations
- let config_path = crate::config::default_config_path()?;
- let config_dir = config_path
- .parent()
- .ok_or_else(|| Error::Config("Could not determine config directory".to_string()))?;
-
- let mut configs = Vec::new();
-
- if let Ok(entries) = std::fs::read_dir(config_dir) {
- for entry in entries.flatten() {
- let path = entry.path();
- if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
- if filename.starts_with("ovcli.conf.") && filename != "ovcli.conf" {
- if let Some(name) = filename.strip_prefix("ovcli.conf.") {
- // Try to load the config to get its URL for display
- let url = if let Ok(cfg) = Config::from_file(&path.to_string_lossy()) {
- cfg.url.clone()
- } else {
- String::new()
- };
- configs.push((name.to_string(), path, url));
- }
+ let mut selected = default.min(items.len().saturating_sub(1));
+ let mut rendered_lines = 0usize;
+ let _raw_guard = RawGuard::enter()?;
+
+ loop {
+ clear_rendered_lines(rendered_lines)?;
+ let lines = select_lines(prompt, items, selected);
+ rendered_lines = lines.len();
+ print!("{}", live_select_block(&lines));
+ io::stdout().flush()?;
+
+ if let Event::Key(key) = event::read()? {
+ match key.code {
+ KeyCode::Up => {
+ selected = if selected == 0 {
+ items.len().saturating_sub(1)
+ } else {
+ selected - 1
+ };
+ }
+ KeyCode::Down => selected = (selected + 1) % items.len(),
+ KeyCode::Enter | KeyCode::Char('\n') | KeyCode::Char('\r') => {
+ clear_rendered_lines(rendered_lines)?;
+ return Ok(SelectOutcome::Selected(selected));
+ }
+ KeyCode::Esc => {
+ clear_rendered_lines(rendered_lines)?;
+ return Ok(SelectOutcome::Back);
}
+ KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
+ clear_rendered_lines(rendered_lines)?;
+ return Ok(SelectOutcome::Quit);
+ }
+ _ => {}
}
}
}
- if configs.is_empty() {
- println!("{}", "No saved configurations found.".yellow());
- println!(
- "{}",
- "Use 'ov config setup-cli' and save a named configuration first.".dimmed()
- );
- return Ok(());
+ fn clear_rendered_lines(lines: usize) -> Result<()> {
+ if lines == 0 {
+ return Ok(());
+ }
+ let mut stdout = io::stdout();
+ execute!(
+ stdout,
+ cursor::MoveUp(lines as u16),
+ cursor::MoveToColumn(0)
+ )?;
+ for line in 0..lines {
+ execute!(
+ stdout,
+ cursor::MoveToColumn(0),
+ Clear(ClearType::CurrentLine)
+ )?;
+ if line + 1 < lines {
+ execute!(stdout, cursor::MoveDown(1))?;
+ }
+ }
+ execute!(
+ stdout,
+ cursor::MoveUp(lines.saturating_sub(1) as u16),
+ cursor::MoveToColumn(0)
+ )?;
+ Ok(())
}
+}
- // Step 2: Interactive selection using simple numbered menu
- println!("{}", "Select a configuration to use:".bold());
- println!();
+fn live_select_block(lines: &[String]) -> String {
+ if lines.is_empty() {
+ return String::new();
+ }
- for (i, (name, _, url)) in configs.iter().enumerate() {
- if url.is_empty() {
- println!(" {}. {}", i + 1, name.bold());
- } else {
- println!(" {}. {} ({})", i + 1, name.bold(), url.dimmed());
- }
+ let mut rendered = lines.join("\r\n");
+ rendered.push_str("\r\n");
+ rendered
+}
+
+fn switch_confirmation_labels() -> Vec<String> {
+ match Language::current() {
+ Language::En => vec!["Yes".to_string(), "No".to_string()],
+ Language::ZhCn => vec!["是".to_string(), "否".to_string()],
}
+}
- println!();
- println!(
- "{}",
- "Enter '<number>' to use a configuration (e.g. '2')".dimmed()
- );
- println!(
- "{}",
- "Or enter 'del<number>' to delete a configuration (e.g. 'del2')".dimmed()
- );
- println!("{}", "Press Enter without input to cancel".dimmed());
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SwitchConfirmationDecision {
+ Confirm,
+ Back,
+ Quit,
+}
- let mut rl = rustyline::DefaultEditor::new()
- .map_err(|e| Error::Config(format!("Failed to initialize input editor: {}", e)))?;
+fn switch_confirmation_decision(outcome: SelectOutcome) -> SwitchConfirmationDecision {
+ match outcome {
+ SelectOutcome::Selected(0) => SwitchConfirmationDecision::Confirm,
+ SelectOutcome::Selected(_) | SelectOutcome::Back => SwitchConfirmationDecision::Back,
+ SelectOutcome::Quit => SwitchConfirmationDecision::Quit,
+ }
+}
- loop {
- let input = rl.readline("> ").unwrap_or_default();
- let input = input.trim();
+fn select_lines(prompt: &str, items: &[String], selected: usize) -> Vec<String> {
+ let language = Language::current();
+ let mut lines = Vec::new();
+ lines.push(format!(
+ "{} {}",
+ theme::prompt("?").bold(),
+ theme::strong(prompt)
+ ));
+ lines.push(format!(" {}", theme::muted(select_hint(language))));
+ lines.push(String::new());
+ for (index, item) in items.iter().enumerate() {
+ let marker = if index == selected {
+ theme::selection("›").bold().to_string()
+ } else {
+ " ".to_string()
+ };
+ lines.push(format!(
+ " {marker} {}",
+ style_select_item(item, index == selected)
+ ));
+ }
+ lines
+}
- if input.is_empty() {
- println!();
- println!("{}", "Cancelled.".dimmed());
- return Ok(());
- }
+fn style_select_item(item: &str, selected: bool) -> String {
+ if contains_ansi_escape(item) {
+ return item.to_string();
+ }
+ if selected {
+ theme::selection(item).bold().to_string()
+ } else {
+ theme::body(item).to_string()
+ }
+}
- // Check for delete command
- if let Some(num_str) = input
- .strip_prefix("del")
- .or_else(|| input.strip_prefix("Del"))
- {
- if let Ok(idx) = num_str.parse::<usize>() {
- if idx >= 1 && idx <= configs.len() {
- let idx = idx - 1;
- let (name, path, _) = &configs[idx];
- println!();
- println!(
- "{}",
- format!(
- "Are you sure you want to delete configuration '{}'? (y/N)",
- name
- )
- .yellow()
- );
+fn contains_ansi_escape(value: &str) -> bool {
+ value.contains("\u{1b}[")
+}
- let confirm = rl.readline("> ").unwrap_or_default();
- if confirm.trim().eq_ignore_ascii_case("y")
- || confirm.trim().eq_ignore_ascii_case("yes")
- {
- std::fs::remove_file(path).map_err(|e| {
- Error::Config(format!("Failed to delete configuration: {}", e))
- })?;
- println!("{}", format!("✓ Configuration '{}' deleted.", name).green());
- } else {
- println!("{}", "Deletion cancelled.".dimmed());
- }
- return Ok(());
- }
- }
- println!("{}", "Invalid selection. Please try again.".yellow());
- continue;
- }
+fn select_hint(language: Language) -> &'static str {
+ match language {
+ Language::En => "↑/↓ choose · Enter select · Esc back · Ctrl+C exit",
+ Language::ZhCn => "↑/↓ 选择 · Enter 确认 · Esc 返回 · Ctrl+C 退出",
+ }
+}
- // Try to parse as selection number
- if let Ok(idx) = input.parse::<usize>() {
- if idx >= 1 && idx <= configs.len() {
- let idx = idx - 1;
- // Handle switching
- let (name, source_path, _) = &configs[idx];
-
- // First, backup current config as .bak
- if config_path.exists() {
- let backup_path = config_dir.join("ovcli.conf.bak");
- std::fs::copy(&config_path, &backup_path).map_err(|e| {
- Error::Config(format!("Failed to backup current config: {}", e))
- })?;
- }
+fn config_switch_prompt<'a>(language: Language, en: &'a str, zh: &'a str) -> &'a str {
+ language_label(en, zh, language)
+}
- // Copy selected config to main config
- std::fs::copy(source_path, &config_path)
- .map_err(|e| Error::Config(format!("Failed to switch configuration: {}", e)))?;
+fn config_switch_confirm_prompt(language: Language, name: &str) -> String {
+ match language {
+ Language::En => format!("Switch active config to {name}?"),
+ Language::ZhCn => format!("切换当前配置为 {name}?"),
+ }
+}
- println!();
- println!(
- "{}",
- format!("✓ Switched to configuration '{}'", name)
- .bold()
- .green()
- );
- println!(
- "{}",
- format!("Configuration saved to: {}", config_path.to_string_lossy()).dimmed()
- );
+fn config_not_changed(language: Language) -> &'static str {
+ match language {
+ Language::En => "No config was changed.",
+ Language::ZhCn => "配置未更改。",
+ }
+}
- return Ok(());
- }
- }
+fn config_already_active(language: Language, name: &str) -> String {
+ match language {
+ Language::En => format!("Config '{name}' is already active."),
+ Language::ZhCn => format!("配置 '{name}' 已是当前配置。"),
+ }
+}
- println!(
- "{}",
- format!(
- "Invalid selection. Please enter a number between 1 and {}.",
- configs.len()
- )
- .yellow()
- );
+fn validating_target_config(language: Language) -> &'static str {
+ match language {
+ Language::En => "Validating target config...",
+ Language::ZhCn => "正在验证目标配置...",
}
}
@@ -979,7 +1092,10 @@ pub async fn handle_find(
if let Some(ref l) = level {
params.push(format!(
"--level {}",
- l.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(",")
+ l.iter()
+ .map(|v| v.to_string())
+ .collect::<Vec<_>>()
+ .join(",")
));
}
params.push(format!("\"{}\"", query));
@@ -1023,7 +1139,10 @@ pub async fn handle_search(
if let Some(ref l) = level {
params.push(format!(
"--level {}",
- l.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(",")
+ l.iter()
+ .map(|v| v.to_string())
+ .collect::<Vec<_>>()
+ .join(",")
));
}
params.push(format!("\"{}\"", query));
@@ -1249,7 +1368,8 @@ pub async fn handle_health(ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
// Reuse the system health command
- let _ = commands::system::health(&client, ctx.output_format, ctx.compact).await?;
+ let _ = commands::system::health(&client, Some(&ctx.config), ctx.output_format, ctx.compact)
+ .await?;
Ok(())
}
@@ -1276,10 +1396,79 @@ pub async fn handle_tui(uri: String, ctx: CliContext) -> Result<()> {
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 setup-cli` to reconfigure if needed.");
+ println!("\nRun `ov config` to reconfigure if needed.");
std::process::exit(1);
}
}
tui::run_tui(client, &uri).await
}
+
+#[cfg(test)]
+mod config_switch_prompt_tests {
+ use super::*;
+
+ #[test]
+ fn live_select_block_uses_crlf_for_raw_mode_rows() {
+ let lines = vec!["Choose config".to_string(), " › local".to_string()];
+
+ let rendered = live_select_block(&lines);
+
+ assert_eq!(rendered, "Choose config\r\n › local\r\n");
+ assert!(!rendered.contains("config\n"));
+ }
+
+ #[test]
+ fn switch_selector_hint_uses_esc_back_language() {
+ let lines = select_lines("Choose config", &["local".to_string()], 0);
+ let plain = strip_ansi(&lines.join("\n"));
+
+ assert!(plain.contains("Esc back"));
+ assert!(!plain.contains("Esc cancel"));
+ }
+
+ #[test]
+ fn switch_confirmation_labels_are_yes_no_only() {
+ assert_eq!(
+ switch_confirmation_labels(),
+ vec!["Yes".to_string(), "No".to_string()]
+ );
+ }
+
+ #[test]
+ fn switch_confirmation_maps_no_and_esc_to_back_but_ctrl_c_to_quit() {
+ assert_eq!(
+ switch_confirmation_decision(SelectOutcome::Selected(0)),
+ SwitchConfirmationDecision::Confirm
+ );
+ assert_eq!(
+ switch_confirmation_decision(SelectOutcome::Selected(1)),
+ SwitchConfirmationDecision::Back
+ );
+ assert_eq!(
+ switch_confirmation_decision(SelectOutcome::Back),
+ SwitchConfirmationDecision::Back
+ );
+ assert_eq!(
+ switch_confirmation_decision(SelectOutcome::Quit),
+ SwitchConfirmationDecision::Quit
+ );
+ }
+
+ 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}' {
+ for next in chars.by_ref() {
+ if next.is_ascii_alphabetic() {
+ break;
+ }
+ }
+ } else {
+ output.push(ch);
+ }
+ }
+ output
+ }
+}
diff --git a/crates/ov_cli/src/health_ui.rs b/crates/ov_cli/src/health_ui.rs
new file mode 100644
index 000000000..53e2644ac
--- /dev/null
+++ b/crates/ov_cli/src/health_ui.rs
@@ -0,0 +1,360 @@
+use colored::Colorize;
+use serde_json::Value;
+use unicode_width::UnicodeWidthStr;
+
+use crate::{config::Config, i18n::Language, theme};
+
+const LABEL_WIDTH: usize = 14;
+const ACTION_WIDTH: usize = 26;
+
+pub(crate) fn render_health(payload: &Value, config: Option<&Config>) -> String {
+ render_health_with_language(payload, config, Language::current())
+}
+
+pub(crate) fn render_health_with_language(
+ payload: &Value,
+ config: Option<&Config>,
+ language: Language,
+) -> String {
+ let mut lines = Vec::new();
+
+ lines.push(title(language));
+ lines.push(String::new());
+ lines.push(section(match language {
+ Language::En => "Connection",
+ Language::ZhCn => "连接",
+ }));
+ lines.push(detail_line(
+ match language {
+ Language::En => "Status",
+ Language::ZhCn => "状态",
+ },
+ match payload.get("healthy").and_then(Value::as_bool) {
+ Some(true) => healthy_value(match language {
+ Language::En => "Connected (Healthy)",
+ Language::ZhCn => "已连接(健康)",
+ }),
+ Some(false) => warning_value(match language {
+ Language::En => "Connected (Unhealthy)",
+ Language::ZhCn => "已连接(不健康)",
+ }),
+ None => unknown_value(match language {
+ Language::En => "Connected (Unknown)",
+ Language::ZhCn => "已连接(未知)",
+ }),
+ },
+ ));
+ lines.push(detail_line(
+ match language {
+ Language::En => "Server",
+ Language::ZhCn => "服务器",
+ },
+ server_status_value(string_field(payload, "status"), language),
+ ));
+ lines.push(detail_line(
+ match language {
+ Language::En => "Version",
+ Language::ZhCn => "版本",
+ },
+ soft_value(string_field(payload, "version"), language),
+ ));
+ lines.push(detail_line(
+ match language {
+ Language::En => "Auth",
+ Language::ZhCn => "认证",
+ },
+ plain_value(&format_auth_mode(
+ string_field(payload, "auth_mode"),
+ language,
+ )),
+ ));
+ lines.push(String::new());
+ lines.push(section(match language {
+ Language::En => "Identity",
+ Language::ZhCn => "身份",
+ }));
+ lines.push(detail_line(
+ match language {
+ Language::En => "Account",
+ Language::ZhCn => "账户",
+ },
+ plain_or_unknown(
+ identity_field(
+ payload,
+ "account_id",
+ config.and_then(|c| c.account.as_deref()),
+ ),
+ language,
+ ),
+ ));
+ lines.push(detail_line(
+ match language {
+ Language::En => "User",
+ Language::ZhCn => "用户",
+ },
+ plain_or_unknown(
+ identity_field(payload, "user_id", config.and_then(|c| c.user.as_deref())),
+ language,
+ ),
+ ));
+ lines.push(detail_line(
+ match language {
+ Language::En => "Agent",
+ Language::ZhCn => "Agent",
+ },
+ plain_or_unknown(
+ identity_field(
+ payload,
+ "agent_id",
+ config.and_then(|c| c.agent_id.as_deref()),
+ ),
+ language,
+ ),
+ ));
+ lines.push(detail_line(
+ match language {
+ Language::En => "Role",
+ Language::ZhCn => "角色",
+ },
+ role_value(string_field(payload, "role"), language),
+ ));
+ lines.push(String::new());
+ lines.push(section(match language {
+ Language::En => "Details",
+ Language::ZhCn => "详情",
+ }));
+ lines.push(action_line(
+ "ov status",
+ match language {
+ Language::En => "Full system diagnostics",
+ Language::ZhCn => "查看完整系统诊断",
+ },
+ ));
+ lines.push(action_line(
+ "ov config validate",
+ match language {
+ Language::En => "Validate active config",
+ Language::ZhCn => "验证当前配置",
+ },
+ ));
+
+ format!("{}\n", lines.join("\n"))
+}
+
+fn title(language: Language) -> String {
+ theme::brand_title(match language {
+ Language::En => "OPENVIKING HEALTH",
+ Language::ZhCn => "OPENVIKING 健康检查",
+ })
+ .bold()
+ .to_string()
+}
+
+fn section(value: &str) -> String {
+ theme::heading(value).bold().to_string()
+}
+
+fn detail_line(label: &str, value: String) -> String {
+ let label = theme::muted(pad_to_display_width(label, LABEL_WIDTH));
+ format!(" {label}{value}")
+}
+
+fn action_line(command: &str, description: &str) -> String {
+ let command = theme::command(pad_to_display_width(command, ACTION_WIDTH)).bold();
+ format!(" {command}{}", theme::muted(description))
+}
+
+fn pad_to_display_width(value: &str, width: usize) -> String {
+ format!(
+ "{}{}",
+ value,
+ " ".repeat(width.saturating_sub(UnicodeWidthStr::width(value)))
+ )
+}
+
+fn string_field<'a>(payload: &'a Value, key: &str) -> Option<&'a str> {
+ payload.get(key).and_then(Value::as_str)
+}
+
+fn identity_field<'a>(
+ payload: &'a Value,
+ key: &str,
+ config_value: Option<&'a str>,
+) -> Option<&'a str> {
+ string_field(payload, key).or(config_value)
+}
+
+fn format_auth_mode(value: Option<&str>, language: Language) -> String {
+ match value {
+ Some("api_key") => "API key".to_string(),
+ Some("none") => match language {
+ Language::En => "None".to_string(),
+ Language::ZhCn => "无".to_string(),
+ },
+ Some(value) => value.replace('_', " "),
+ None => match language {
+ Language::En => "unknown".to_string(),
+ Language::ZhCn => "未知".to_string(),
+ },
+ }
+}
+
+fn server_status_value(value: Option<&str>, language: Language) -> String {
+ match value {
+ Some("ok") => healthy_value("ok"),
+ Some(value) => warning_value(value),
+ None => unknown_value(unknown(language)),
+ }
+}
+
+fn role_value(value: Option<&str>, language: Language) -> String {
+ match value {
+ Some("admin") => theme::config_name("admin").bold().to_string(),
+ Some(value) => plain_value(value),
+ None => unknown_value(unknown(language)),
+ }
+}
+
+fn plain_or_unknown(value: Option<&str>, language: Language) -> String {
+ match value {
+ Some(value) if !value.is_empty() => plain_value(value),
+ _ => unknown_value(unknown(language)),
+ }
+}
+
+fn plain_value(value: &str) -> String {
+ theme::body(value).to_string()
+}
+
+fn soft_value(value: Option<&str>, language: Language) -> String {
+ match value {
+ Some(value) if !value.is_empty() => theme::value(value).to_string(),
+ _ => unknown_value(unknown(language)),
+ }
+}
+
+fn unknown(language: Language) -> &'static str {
+ match language {
+ Language::En => "unknown",
+ Language::ZhCn => "未知",
+ }
+}
+
+fn healthy_value(value: &str) -> String {
+ theme::success(value).bold().to_string()
+}
+
+fn warning_value(value: &str) -> String {
+ theme::warning(value).bold().to_string()
+}
+
+fn unknown_value(value: &str) -> String {
+ theme::muted(value).to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::config::Config;
+ use crate::i18n::Language;
+ use serde_json::json;
+
+ #[test]
+ fn health_rendering_uses_ansi_styling_without_changing_fields() {
+ let payload = json!({
+ "status": "ok",
+ "healthy": true,
+ "version": "0.0.0+feat.oauth.studio.consent.16fa076",
+ "auth_mode": "api_key",
+ "account_id": "default",
+ "user_id": "haozhe",
+ "agent_id": "default",
+ "role": "admin"
+ });
+
+ colored::control::set_override(true);
+ let rendered = super::render_health(&payload, None);
+ colored::control::unset_override();
+
+ assert!(rendered.contains("\u{1b}["));
+
+ let plain = strip_ansi(&rendered);
+ assert!(plain.contains("OPENVIKING HEALTH"));
+ assert!(plain.contains("Connection"));
+ assert!(plain.contains("Status Connected (Healthy)"));
+ assert!(plain.contains("Server ok"));
+ assert!(plain.contains("Version 0.0.0+feat.oauth.studio.consent.16fa076"));
+ assert!(plain.contains("Auth API key"));
+ assert!(plain.contains("Identity"));
+ assert!(plain.contains("Account default"));
+ assert!(plain.contains("User haozhe"));
+ assert!(plain.contains("Agent default"));
+ assert!(plain.contains("Role admin"));
+ assert!(plain.contains("Details"));
+ assert!(plain.contains("ov status Full system diagnostics"));
+ }
+
+ #[test]
+ fn health_rendering_supports_chinese_labels() {
+ let payload = json!({
+ "status": "ok",
+ "healthy": true,
+ "version": "0.3.18",
+ "auth_mode": "api_key",
+ "account_id": "default",
+ "user_id": "haozhe",
+ "agent_id": "default",
+ "role": "admin"
+ });
+
+ let rendered = super::render_health_with_language(&payload, None, Language::ZhCn);
+ let plain = strip_ansi(&rendered);
+
+ assert!(plain.contains("OPENVIKING 健康检查"));
+ assert!(plain.contains("连接"));
+ assert!(plain.contains("状态"));
+ assert!(plain.contains("已连接(健康)"));
+ assert!(plain.contains("身份"));
+ assert!(plain.contains("详情"));
+ }
+
+ #[test]
+ fn health_rendering_falls_back_to_config_identity_when_payload_omits_identity() {
+ let payload = json!({
+ "status": "ok",
+ "healthy": true,
+ "version": "0.3.18.dev29",
+ "auth_mode": "dev"
+ });
+ let config = Config {
+ account: Some("default".to_string()),
+ user: Some("default".to_string()),
+ ..Config::default()
+ };
+
+ let rendered = super::render_health(&payload, Some(&config));
+ let plain = strip_ansi(&rendered);
+
+ assert!(plain.contains("Account default"));
+ assert!(plain.contains("User default"));
+ }
+
+ 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.is_ascii_alphabetic() {
+ break;
+ }
+ }
+ continue;
+ }
+ output.push(ch);
+ }
+
+ output
+ }
+}
diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rs
new file mode 100644
index 000000000..52b6ac9cf
--- /dev/null
+++ b/crates/ov_cli/src/help_ui.rs
@@ -0,0 +1,2634 @@
+use std::ffi::OsString;
+
+use colored::Colorize;
+use unicode_width::UnicodeWidthStr;
+
+use crate::{
+ i18n::{Language, copy},
+ theme,
+};
+
+const BOX_WIDTH: usize = 74;
+const COMMAND_WIDTH: usize = 16;
+const DESCRIPTION_WIDTH: usize = BOX_WIDTH - COMMAND_WIDTH - 5;
+const COMMAND_HELP_LEFT_WIDTH: usize = 34;
+
+#[derive(Debug, Clone, Copy)]
+struct HelpCommand {
+ name: &'static str,
+ description: &'static str,
+ badge: Option<&'static str>,
+}
+
+#[derive(Debug, Clone, Copy)]
+struct HelpSection {
+ title: &'static str,
+ commands: &'static [HelpCommand],
+}
+
+#[derive(Debug, Clone, Copy)]
+struct HelpItem {
+ label: &'static str,
+ description: &'static str,
+}
+
+#[derive(Debug, Clone, Copy)]
+struct CommandHelpSpec {
+ path: &'static [&'static str],
+ purpose: &'static str,
+ usage: &'static str,
+ examples: &'static [HelpItem],
+ arguments: &'static [HelpItem],
+ common_options: &'static [HelpItem],
+ advanced_options: &'static [HelpItem],
+ subcommands: &'static [HelpItem],
+ next_steps: &'static [HelpItem],
+}
+
+const CORE_WORKFLOW: &[HelpCommand] = &[
+ HelpCommand {
+ name: "add-resource",
+ description: "Add files, folders, URLs, or repos into OpenViking",
+ badge: None,
+ },
+ HelpCommand {
+ name: "find",
+ description: "Retrieve relevant context semantically",
+ badge: None,
+ },
+ HelpCommand {
+ name: "read",
+ description: "Read exact resource content",
+ badge: None,
+ },
+ HelpCommand {
+ name: "write",
+ description: "Update an existing resource",
+ badge: None,
+ },
+ HelpCommand {
+ name: "add-memory",
+ description: "Add a memory directly",
+ badge: None,
+ },
+];
+
+const FILESYSTEM: &[HelpCommand] = &[
+ HelpCommand {
+ name: "ls",
+ description: "List directory contents",
+ badge: None,
+ },
+ HelpCommand {
+ name: "tree",
+ description: "Show a scoped resource tree",
+ badge: None,
+ },
+ HelpCommand {
+ name: "mkdir",
+ description: "Create a directory",
+ badge: None,
+ },
+ HelpCommand {
+ name: "rm",
+ description: "Remove a resource",
+ badge: None,
+ },
+ HelpCommand {
+ name: "mv",
+ description: "Move or rename a resource",
+ badge: None,
+ },
+ HelpCommand {
+ name: "stat",
+ description: "Show resource metadata",
+ badge: None,
+ },
+ HelpCommand {
+ name: "get",
+ description: "Download a file",
+ badge: None,
+ },
+];
+
+const SEARCH_CONTEXT: &[HelpCommand] = &[
+ HelpCommand {
+ name: "find",
+ description: "Semantic retrieval",
+ badge: None,
+ },
+ HelpCommand {
+ name: "search",
+ description: "Context-aware retrieval",
+ badge: Some("experimental"),
+ },
+ HelpCommand {
+ name: "grep",
+ description: "Pattern search",
+ badge: None,
+ },
+ HelpCommand {
+ name: "glob",
+ description: "Glob search",
+ badge: None,
+ },
+ HelpCommand {
+ name: "abstract",
+ description: "Read L0 abstract",
+ badge: None,
+ },
+ HelpCommand {
+ name: "overview",
+ description: "Read L1 overview",
+ badge: None,
+ },
+ HelpCommand {
+ name: "read",
+ description: "Read L2 content",
+ badge: None,
+ },
+];
+
+const CONFIG_STATUS: &[HelpCommand] = &[
+ HelpCommand {
+ name: "config",
+ description: "Manage configs",
+ badge: None,
+ },
+ HelpCommand {
+ name: "config show",
+ description: "Show active config",
+ badge: None,
+ },
+ HelpCommand {
+ name: "config validate",
+ description: "Validate active config",
+ badge: None,
+ },
+ HelpCommand {
+ name: "config switch",
+ description: "Switch active config",
+ badge: None,
+ },
+ HelpCommand {
+ name: "language",
+ description: "Choose CLI display language",
+ badge: None,
+ },
+ HelpCommand {
+ name: "health",
+ description: "Quick health check",
+ badge: None,
+ },
+ HelpCommand {
+ name: "status",
+ description: "Full server status",
+ badge: None,
+ },
+ HelpCommand {
+ name: "wait",
+ description: "Wait for async work",
+ badge: None,
+ },
+ HelpCommand {
+ name: "task",
+ description: "Track async tasks",
+ badge: None,
+ },
+];
+
+const IMPORT_EXPORT_SESSIONS: &[HelpCommand] = &[
+ HelpCommand {
+ name: "import",
+ description: "Import .ovpack",
+ badge: None,
+ },
+ HelpCommand {
+ name: "export",
+ description: "Export context as .ovpack",
+ badge: None,
+ },
+ HelpCommand {
+ name: "backup",
+ description: "Create restore-only backup",
+ badge: None,
+ },
+ HelpCommand {
+ name: "restore",
+ description: "Restore backup",
+ badge: None,
+ },
+ HelpCommand {
+ name: "session",
+ description: "Manage sessions",
+ badge: None,
+ },
+ HelpCommand {
+ name: "privacy",
+ description: "Manage privacy config",
+ badge: None,
+ },
+];
+
+const INTERACTIVE_ADMIN: &[HelpCommand] = &[
+ HelpCommand {
+ name: "tui",
+ description: "Interactive file explorer",
+ badge: None,
+ },
+ HelpCommand {
+ name: "chat",
+ description: "Chat with vikingbot",
+ badge: None,
+ },
+ HelpCommand {
+ name: "admin",
+ description: "Account and user management",
+ badge: None,
+ },
+ HelpCommand {
+ name: "system",
+ description: "System utilities",
+ badge: None,
+ },
+ HelpCommand {
+ name: "reindex",
+ description: "Reindex semantic/vector artifacts",
+ badge: None,
+ },
+ HelpCommand {
+ name: "relations",
+ description: "List resource relations",
+ badge: Some("experimental"),
+ },
+ HelpCommand {
+ name: "link",
+ description: "Create relation links",
+ badge: Some("experimental"),
+ },
+ HelpCommand {
+ name: "unlink",
+ description: "Remove relation links",
+ badge: Some("experimental"),
+ },
+];
+
+const HELP_SECTIONS: &[HelpSection] = &[
+ HelpSection {
+ title: "Core Workflow",
+ commands: CORE_WORKFLOW,
+ },
+ HelpSection {
+ title: "Filesystem",
+ commands: FILESYSTEM,
+ },
+ HelpSection {
+ title: "Search & Context",
+ commands: SEARCH_CONTEXT,
+ },
+ HelpSection {
+ title: "Config & Status",
+ commands: CONFIG_STATUS,
+ },
+ HelpSection {
+ title: "Import, Export & Sessions",
+ commands: IMPORT_EXPORT_SESSIONS,
+ },
+ HelpSection {
+ title: "Interactive & Admin",
+ commands: INTERACTIVE_ADMIN,
+ },
+];
+
+const GLOBAL_OPTIONS: &[HelpItem] = &[
+ HelpItem {
+ label: "-o, --output <table|json>",
+ description: "Choose human table output or machine-readable JSON.",
+ },
+ HelpItem {
+ label: "-c, --compact <bool>",
+ description: "Use compact table/JSON rendering.",
+ },
+ HelpItem {
+ label: "--account <account>",
+ description: "Override X-OpenViking-Account for this command.",
+ },
+ HelpItem {
+ label: "--user <user>",
+ description: "Override X-OpenViking-User for this command.",
+ },
+ HelpItem {
+ label: "--agent-id <agent>",
+ description: "Override X-OpenViking-Agent for this command.",
+ },
+];
+
+const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[
+ CommandHelpSpec {
+ path: &["add-resource"],
+ purpose: "Import a local file, folder, URL, or repository into OpenViking.",
+ usage: "ov add-resource <path-or-url> [--parent <uri>|--to <uri>] [--wait]",
+ examples: &[
+ HelpItem {
+ label: "ov add-resource ./docs --parent viking://projects/acme --wait",
+ description: "Import a folder and wait for processing.",
+ },
+ HelpItem {
+ label: "ov add-resource https://example.com/spec.md --to viking://specs/api.md",
+ description: "Import a URL to an exact target URI.",
+ },
+ ],
+ arguments: &[HelpItem {
+ label: "<path-or-url>",
+ description: "Local path, URL, or repository to import.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "--parent <uri>",
+ description: "Import under an existing directory URI.",
+ },
+ HelpItem {
+ label: "-p, --parent-auto-create <uri>",
+ description: "Create the parent directory if missing.",
+ },
+ HelpItem {
+ label: "--to <uri>",
+ description: "Import to an exact new resource URI.",
+ },
+ HelpItem {
+ label: "--wait",
+ description: "Wait until indexing/processing completes.",
+ },
+ HelpItem {
+ label: "--include / --exclude",
+ description: "Filter files during folder import.",
+ },
+ ],
+ advanced_options: &[
+ HelpItem {
+ label: "--reason <text>",
+ description: "Attach an import reason.",
+ },
+ HelpItem {
+ label: "--instruction <text>",
+ description: "Attach processing instructions.",
+ },
+ HelpItem {
+ label: "--watch-interval <minutes>",
+ description: "Set automatic refresh cadence.",
+ },
+ HelpItem {
+ label: "--progress / --no-progress",
+ description: "Override local upload progress display.",
+ },
+ HelpItem {
+ label: "-v, --verbose",
+ description: "Print upload diagnostics.",
+ },
+ ],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov task list",
+ description: "Inspect async processing tasks.",
+ },
+ HelpItem {
+ label: "ov find \"query\"",
+ description: "Retrieve the imported context.",
+ },
+ HelpItem {
+ label: "ov tree <uri>",
+ description: "Browse where the resource landed.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["add-skill"],
+ purpose: "Import a skill directory, SKILL.md file, or raw skill content.",
+ usage: "ov add-skill <skill-path-or-content> [--wait]",
+ examples: &[
+ HelpItem {
+ label: "ov add-skill ./skills/my-skill --wait",
+ description: "Import a local skill folder.",
+ },
+ HelpItem {
+ label: "ov add-skill ./skills/my-skill/SKILL.md",
+ description: "Import a single skill definition.",
+ },
+ ],
+ arguments: &[HelpItem {
+ label: "<skill-path-or-content>",
+ description: "Skill folder, SKILL.md path, or raw content.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "--wait",
+ description: "Wait until skill processing completes.",
+ },
+ HelpItem {
+ label: "--timeout <seconds>",
+ description: "Maximum wait time when using --wait.",
+ },
+ ],
+ advanced_options: &[
+ HelpItem {
+ label: "--progress / --no-progress",
+ description: "Override local upload progress display.",
+ },
+ HelpItem {
+ label: "-v, --verbose",
+ description: "Print upload diagnostics.",
+ },
+ ],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov find \"skill topic\"",
+ description: "Search imported skill context.",
+ },
+ HelpItem {
+ label: "ov task list",
+ description: "Check processing status.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["ls"],
+ purpose: "List resources under a Viking URI.",
+ usage: "ov ls [uri] [--recursive] [--all]",
+ examples: &[
+ HelpItem {
+ label: "ov ls",
+ description: "List the root scope.",
+ },
+ HelpItem {
+ label: "ov ls viking://projects/acme --recursive",
+ description: "List a subtree recursively.",
+ },
+ ],
+ arguments: &[HelpItem {
+ label: "[uri]",
+ description: "Directory URI to list. Defaults to viking://.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "-r, --recursive",
+ description: "List nested directories recursively.",
+ },
+ HelpItem {
+ label: "-s, --simple",
+ description: "Print only paths.",
+ },
+ HelpItem {
+ label: "-a, --all",
+ description: "Include hidden files.",
+ },
+ HelpItem {
+ label: "-n, --node-limit <n>",
+ description: "Limit number of listed nodes.",
+ },
+ ],
+ advanced_options: &[HelpItem {
+ label: "-l, --abs-limit <n>",
+ description: "Limit abstract text in agent-oriented output.",
+ }],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov tree <uri>",
+ description: "See a hierarchy view.",
+ },
+ HelpItem {
+ label: "ov read <uri>",
+ description: "Read a file resource.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["tree"],
+ purpose: "Show a hierarchical view of resources under a URI.",
+ usage: "ov tree <uri> [--level-limit <n>] [--node-limit <n>]",
+ examples: &[HelpItem {
+ label: "ov tree viking://projects/acme -L 4",
+ description: "Show a project tree up to depth 4.",
+ }],
+ arguments: &[HelpItem {
+ label: "<uri>",
+ description: "Directory URI to inspect.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "-L, --level-limit <n>",
+ description: "Maximum traversal depth.",
+ },
+ HelpItem {
+ label: "-n, --node-limit <n>",
+ description: "Maximum number of nodes.",
+ },
+ HelpItem {
+ label: "-a, --all",
+ description: "Include hidden files.",
+ },
+ ],
+ advanced_options: &[HelpItem {
+ label: "-l, --abs-limit <n>",
+ description: "Limit abstract text in agent-oriented output.",
+ }],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov read <uri>",
+ description: "Open an exact resource.",
+ },
+ HelpItem {
+ label: "ov find \"query\" -u <uri>",
+ description: "Search inside this subtree.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["mkdir"],
+ purpose: "Create a directory in OpenViking.",
+ usage: "ov mkdir <uri> [--description <text>]",
+ examples: &[HelpItem {
+ label: "ov mkdir viking://projects/acme --description \"ACME project context\"",
+ description: "Create a project folder with a description.",
+ }],
+ arguments: &[HelpItem {
+ label: "<uri>",
+ description: "Directory URI to create.",
+ }],
+ common_options: &[HelpItem {
+ label: "--description <text>",
+ description: "Initial directory description.",
+ }],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov add-resource ./docs --parent <uri>",
+ description: "Import content into the new directory.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["rm"],
+ purpose: "Remove a resource from OpenViking.",
+ usage: "ov rm <uri> [--recursive]",
+ examples: &[
+ HelpItem {
+ label: "ov rm viking://scratch/old-note.md",
+ description: "Remove one file resource.",
+ },
+ HelpItem {
+ label: "ov rm viking://scratch --recursive",
+ description: "Remove a directory subtree.",
+ },
+ ],
+ arguments: &[HelpItem {
+ label: "<uri>",
+ description: "Resource URI to remove.",
+ }],
+ common_options: &[HelpItem {
+ label: "-r, --recursive",
+ description: "Required for directory/subtree removal.",
+ }],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov ls <parent-uri>",
+ description: "Confirm the resource is gone.",
+ },
+ HelpItem {
+ label: "ov tree <parent-uri>",
+ description: "Review remaining resources.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["mv"],
+ purpose: "Move or rename a resource.",
+ usage: "ov mv <from-uri> <to-uri>",
+ examples: &[HelpItem {
+ label: "ov mv viking://notes/draft.md viking://notes/final.md",
+ description: "Rename a file resource.",
+ }],
+ arguments: &[
+ HelpItem {
+ label: "<from-uri>",
+ description: "Existing resource URI.",
+ },
+ HelpItem {
+ label: "<to-uri>",
+ description: "Destination URI.",
+ },
+ ],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov stat <to-uri>",
+ description: "Confirm the resource metadata.",
+ },
+ HelpItem {
+ label: "ov read <to-uri>",
+ description: "Read the moved resource.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["stat"],
+ purpose: "Show metadata for one resource.",
+ usage: "ov stat <uri>",
+ examples: &[HelpItem {
+ label: "ov stat viking://projects/acme/spec.md",
+ description: "Inspect resource metadata.",
+ }],
+ arguments: &[HelpItem {
+ label: "<uri>",
+ description: "Resource URI to inspect.",
+ }],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov read <uri>",
+ description: "Read the resource content.",
+ },
+ HelpItem {
+ label: "ov relations <uri>",
+ description: "Inspect related resources.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["read"],
+ purpose: "Read exact L2 file content from a Viking URI.",
+ usage: "ov read <uri>",
+ examples: &[HelpItem {
+ label: "ov read viking://projects/acme/spec.md",
+ description: "Print exact file content.",
+ }],
+ arguments: &[HelpItem {
+ label: "<uri>",
+ description: "File resource URI.",
+ }],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov write <uri> --content \"...\"",
+ description: "Update this resource.",
+ },
+ HelpItem {
+ label: "ov find \"query\" -u <parent-uri>",
+ description: "Find related context nearby.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["abstract"],
+ purpose: "Read L0 abstract content for a directory.",
+ usage: "ov abstract <directory-uri>",
+ examples: &[HelpItem {
+ label: "ov abstract viking://projects/acme",
+ description: "Read the compact directory abstract.",
+ }],
+ arguments: &[HelpItem {
+ label: "<directory-uri>",
+ description: "Directory URI.",
+ }],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov overview <directory-uri>",
+ description: "Read a richer L1 overview.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["overview"],
+ purpose: "Read L1 overview content for a directory.",
+ usage: "ov overview <directory-uri>",
+ examples: &[HelpItem {
+ label: "ov overview viking://projects/acme",
+ description: "Read the directory overview.",
+ }],
+ arguments: &[HelpItem {
+ label: "<directory-uri>",
+ description: "Directory URI.",
+ }],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov read <file-uri>",
+ description: "Open exact L2 content.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["write"],
+ purpose: "Update text content in an existing resource.",
+ usage: "ov write <uri> (--content <text>|--from-file <path>) [--append|--mode <mode>]",
+ examples: &[
+ HelpItem {
+ label: "ov write viking://notes/todo.md --content \"Ship config UX\"",
+ description: "Replace a file with inline text.",
+ },
+ HelpItem {
+ label: "ov write viking://notes/todo.md --from-file ./todo.md --wait",
+ description: "Write from disk and wait for processing.",
+ },
+ ],
+ arguments: &[HelpItem {
+ label: "<uri>",
+ description: "Existing resource URI.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "--content <text>",
+ description: "Inline replacement content.",
+ },
+ HelpItem {
+ label: "--from-file <path>",
+ description: "Read replacement content from disk.",
+ },
+ HelpItem {
+ label: "--append",
+ description: "Append instead of replacing.",
+ },
+ HelpItem {
+ label: "--wait",
+ description: "Wait for async processing.",
+ },
+ ],
+ advanced_options: &[HelpItem {
+ label: "--mode <replace|append|create>",
+ description: "Explicit write mode.",
+ }],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov read <uri>",
+ description: "Confirm the updated content.",
+ },
+ HelpItem {
+ label: "ov task list",
+ description: "Inspect processing if not using --wait.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["get"],
+ purpose: "Download a file resource to a local path.",
+ usage: "ov get <uri> <local-path>",
+ examples: &[HelpItem {
+ label: "ov get viking://assets/logo.png ./logo.png",
+ description: "Download a binary or text file.",
+ }],
+ arguments: &[
+ HelpItem {
+ label: "<uri>",
+ description: "File resource URI.",
+ },
+ HelpItem {
+ label: "<local-path>",
+ description: "Destination path that does not already exist.",
+ },
+ ],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov stat <uri>",
+ description: "Inspect source metadata.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["find"],
+ purpose: "Retrieve relevant OpenViking context semantically.",
+ usage: "ov find <query> [--uri <uri>] [--node-limit <n>]",
+ examples: &[
+ HelpItem {
+ label: "ov find \"deployment rollback steps\"",
+ description: "Search all accessible context.",
+ },
+ HelpItem {
+ label: "ov find \"auth flow\" -u viking://projects/acme -L 1,2",
+ description: "Search a subtree and include overview/file results.",
+ },
+ ],
+ arguments: &[HelpItem {
+ label: "<query>",
+ description: "Natural-language search query.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "-u, --uri <uri>",
+ description: "Limit search to a subtree.",
+ },
+ HelpItem {
+ label: "-n, --node-limit <n>",
+ description: "Maximum number of results.",
+ },
+ HelpItem {
+ label: "-t, --threshold <score>",
+ description: "Minimum relevance score.",
+ },
+ HelpItem {
+ label: "-L, --level <0,1,2>",
+ description: "Filter abstract, overview, or file results.",
+ },
+ ],
+ advanced_options: &[
+ HelpItem {
+ label: "--after <time>",
+ description: "Only include newer results, e.g. 48h or 2026-03-10.",
+ },
+ HelpItem {
+ label: "--before <time>",
+ description: "Only include older results, e.g. 24h or ISO-8601.",
+ },
+ ],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov read <uri>",
+ description: "Open an exact result.",
+ },
+ HelpItem {
+ label: "ov tree <uri>",
+ description: "Explore the result's neighborhood.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["search"],
+ purpose: "Run experimental context-aware retrieval, optionally scoped to a session.",
+ usage: "ov search <query> [--session-id <id>] [--uri <uri>]",
+ examples: &[HelpItem {
+ label: "ov search \"what changed last time?\" --session-id abc123",
+ description: "Search with session context.",
+ }],
+ arguments: &[HelpItem {
+ label: "<query>",
+ description: "Natural-language search query.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "--session-id <id>",
+ description: "Session context for retrieval.",
+ },
+ HelpItem {
+ label: "-u, --uri <uri>",
+ description: "Limit search to a subtree.",
+ },
+ HelpItem {
+ label: "-n, --node-limit <n>",
+ description: "Maximum number of results.",
+ },
+ ],
+ advanced_options: &[
+ HelpItem {
+ label: "-t, --threshold <score>",
+ description: "Minimum relevance score.",
+ },
+ HelpItem {
+ label: "--after / --before",
+ description: "Time-bound results.",
+ },
+ HelpItem {
+ label: "-L, --level <0,1,2>",
+ description: "Filter by context level.",
+ },
+ ],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov session get-session-context <id>",
+ description: "Inspect the session context directly.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["grep"],
+ purpose: "Search resource content with a text pattern.",
+ usage: "ov grep <pattern> [--uri <uri>] [--ignore-case]",
+ examples: &[HelpItem {
+ label: "ov grep \"TODO\" -u viking://projects/acme -i",
+ description: "Find case-insensitive matches in a subtree.",
+ }],
+ arguments: &[HelpItem {
+ label: "<pattern>",
+ description: "Text pattern to search for.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "-u, --uri <uri>",
+ description: "Search root. Defaults to viking://.",
+ },
+ HelpItem {
+ label: "-i, --ignore-case",
+ description: "Match case-insensitively.",
+ },
+ HelpItem {
+ label: "-n, --node-limit <n>",
+ description: "Maximum number of results.",
+ },
+ ],
+ advanced_options: &[
+ HelpItem {
+ label: "-x, --exclude-uri <uri>",
+ description: "Skip matches under a URI prefix.",
+ },
+ HelpItem {
+ label: "-L, --level-limit <n>",
+ description: "Maximum traversal depth.",
+ },
+ ],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov read <uri>",
+ description: "Open a matching resource.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["glob"],
+ purpose: "Find resources by glob pattern.",
+ usage: "ov glob <pattern> [--uri <uri>]",
+ examples: &[HelpItem {
+ label: "ov glob \"**/*.md\" -u viking://projects/acme",
+ description: "Find Markdown files in a project.",
+ }],
+ arguments: &[HelpItem {
+ label: "<pattern>",
+ description: "Glob pattern to match resource paths.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "-u, --uri <uri>",
+ description: "Search root. Defaults to viking://.",
+ },
+ HelpItem {
+ label: "-n, --node-limit <n>",
+ description: "Maximum number of results.",
+ },
+ ],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov read <uri>",
+ description: "Read one matched file.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["session"],
+ purpose: "Manage sessions, messages, archives, and committed session context.",
+ usage: "ov session <subcommand>",
+ examples: &[
+ HelpItem {
+ label: "ov session new",
+ description: "Create a new session.",
+ },
+ HelpItem {
+ label: "ov session add-message <id> --role user --content \"...\"",
+ description: "Append a message.",
+ },
+ ],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[
+ HelpItem {
+ label: "new",
+ description: "Create a session.",
+ },
+ HelpItem {
+ label: "list",
+ description: "List sessions.",
+ },
+ HelpItem {
+ label: "get <id>",
+ description: "Show session details.",
+ },
+ HelpItem {
+ label: "get-session-context <id>",
+ description: "Read merged session context.",
+ },
+ HelpItem {
+ label: "add-message <id>",
+ description: "Append one message.",
+ },
+ HelpItem {
+ label: "commit <id>",
+ description: "Archive messages and extract memories.",
+ },
+ ],
+ next_steps: &[HelpItem {
+ label: "ov session <subcommand> --help",
+ description: "Show exact arguments for a session operation.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["add-memory"],
+ purpose: "Add a memory directly from text or JSON messages.",
+ usage: "ov add-memory <content>",
+ examples: &[
+ HelpItem {
+ label: "ov add-memory \"The deployment owner is Alice\"",
+ description: "Add one plain user memory.",
+ },
+ HelpItem {
+ label: "ov add-memory '{\"role\":\"user\",\"content\":\"remember this\"}'",
+ description: "Add one structured message.",
+ },
+ ],
+ arguments: &[HelpItem {
+ label: "<content>",
+ description: "Plain text, one JSON message, or a JSON message array.",
+ }],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov find \"memory topic\"",
+ description: "Verify the memory is retrievable.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["privacy"],
+ purpose: "Manage privacy config categories, targets, versions, and activation.",
+ usage: "ov privacy <subcommand>",
+ examples: &[
+ HelpItem {
+ label: "ov privacy categories",
+ description: "List privacy categories.",
+ },
+ HelpItem {
+ label: "ov privacy get <category> <target>",
+ description: "Show active values for one target.",
+ },
+ ],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[
+ HelpItem {
+ label: "categories",
+ description: "List categories.",
+ },
+ HelpItem {
+ label: "list <category>",
+ description: "List targets.",
+ },
+ HelpItem {
+ label: "get <category> <target>",
+ description: "Show active config.",
+ },
+ HelpItem {
+ label: "upsert <category> <target>",
+ description: "Update values.",
+ },
+ HelpItem {
+ label: "versions / version / activate",
+ description: "Inspect or activate versions.",
+ },
+ ],
+ next_steps: &[HelpItem {
+ label: "ov privacy <subcommand> --help",
+ description: "Show exact arguments for a privacy operation.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["relations"],
+ purpose: "List relation links for one resource. Experimental.",
+ usage: "ov relations <uri>",
+ examples: &[HelpItem {
+ label: "ov relations viking://projects/acme/spec.md",
+ description: "Inspect linked resources.",
+ }],
+ arguments: &[HelpItem {
+ label: "<uri>",
+ description: "Source resource URI.",
+ }],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov link <from-uri> <to-uri>",
+ description: "Create a relation.",
+ },
+ HelpItem {
+ label: "ov unlink <from-uri> <to-uri>",
+ description: "Remove a relation.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["link"],
+ purpose: "Create one or more relation links between resources. Experimental.",
+ usage: "ov link <from-uri> <to-uri>... [--reason <text>]",
+ examples: &[HelpItem {
+ label: "ov link viking://a.md viking://b.md --reason \"related design\"",
+ description: "Link two resources with a reason.",
+ }],
+ arguments: &[
+ HelpItem {
+ label: "<from-uri>",
+ description: "Source resource URI.",
+ },
+ HelpItem {
+ label: "<to-uri>...",
+ description: "One or more target URIs.",
+ },
+ ],
+ common_options: &[HelpItem {
+ label: "--reason <text>",
+ description: "Why these resources are linked.",
+ }],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov relations <from-uri>",
+ description: "Confirm the relation.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["unlink"],
+ purpose: "Remove one relation link between resources. Experimental.",
+ usage: "ov unlink <from-uri> <to-uri>",
+ examples: &[HelpItem {
+ label: "ov unlink viking://a.md viking://b.md",
+ description: "Remove a relation.",
+ }],
+ arguments: &[
+ HelpItem {
+ label: "<from-uri>",
+ description: "Source resource URI.",
+ },
+ HelpItem {
+ label: "<to-uri>",
+ description: "Target URI to unlink.",
+ },
+ ],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov relations <from-uri>",
+ description: "Confirm the relation is gone.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["export"],
+ purpose: "Export context from a URI as an .ovpack file.",
+ usage: "ov export <uri> <output.ovpack> [--include-vectors]",
+ examples: &[HelpItem {
+ label: "ov export viking://projects/acme ./acme.ovpack",
+ description: "Export a project subtree.",
+ }],
+ arguments: &[
+ HelpItem {
+ label: "<uri>",
+ description: "Source URI to export.",
+ },
+ HelpItem {
+ label: "<output.ovpack>",
+ description: "Output file path.",
+ },
+ ],
+ common_options: &[HelpItem {
+ label: "--include-vectors",
+ description: "Include compatible dense vector snapshots.",
+ }],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov import ./file.ovpack <target-uri>",
+ description: "Import the exported pack elsewhere.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["backup"],
+ purpose: "Create a restore-only backup .ovpack for public OpenViking scopes.",
+ usage: "ov backup <output.ovpack> [--include-vectors]",
+ examples: &[HelpItem {
+ label: "ov backup ./openviking-backup.ovpack --include-vectors",
+ description: "Create a backup with vectors when compatible.",
+ }],
+ arguments: &[HelpItem {
+ label: "<output.ovpack>",
+ description: "Backup file path.",
+ }],
+ common_options: &[HelpItem {
+ label: "--include-vectors",
+ description: "Include compatible dense vector snapshots.",
+ }],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov restore ./openviking-backup.ovpack",
+ description: "Restore this backup later.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["import"],
+ purpose: "Import an .ovpack into a target URI.",
+ usage: "ov import <file.ovpack> <target-uri> [--on-conflict <policy>]",
+ examples: &[HelpItem {
+ label: "ov import ./acme.ovpack viking://imports/acme --on-conflict skip",
+ description: "Import while keeping existing resources.",
+ }],
+ arguments: &[
+ HelpItem {
+ label: "<file.ovpack>",
+ description: "Input pack file.",
+ },
+ HelpItem {
+ label: "<target-uri>",
+ description: "Target parent URI.",
+ },
+ ],
+ common_options: &[
+ HelpItem {
+ label: "--on-conflict <fail|overwrite|skip>",
+ description: "Choose how to handle existing resources.",
+ },
+ HelpItem {
+ label: "--vector-mode <auto|recompute|require>",
+ description: "Choose vector snapshot handling.",
+ },
+ ],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov tree <target-uri>",
+ description: "Inspect imported resources.",
+ },
+ HelpItem {
+ label: "ov find \"query\" -u <target-uri>",
+ description: "Search imported content.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["restore"],
+ purpose: "Restore a backup .ovpack to its original public scope roots.",
+ usage: "ov restore <backup.ovpack> [--on-conflict <policy>]",
+ examples: &[HelpItem {
+ label: "ov restore ./openviking-backup.ovpack --on-conflict fail",
+ description: "Restore only if there are no conflicts.",
+ }],
+ arguments: &[HelpItem {
+ label: "<backup.ovpack>",
+ description: "Backup pack file.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "--on-conflict <fail|overwrite|skip>",
+ description: "Choose how to handle existing resources.",
+ },
+ HelpItem {
+ label: "--vector-mode <auto|recompute|require>",
+ description: "Choose vector snapshot handling.",
+ },
+ ],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov status",
+ description: "Check service health after restore.",
+ },
+ HelpItem {
+ label: "ov tree viking://",
+ description: "Inspect restored resources.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["tui"],
+ purpose: "Open the interactive file explorer.",
+ usage: "ov tui [uri]",
+ examples: &[HelpItem {
+ label: "ov tui viking://projects/acme",
+ description: "Browse a project subtree interactively.",
+ }],
+ arguments: &[HelpItem {
+ label: "[uri]",
+ description: "Start URI. Defaults to /.",
+ }],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov tree <uri>",
+ description: "Use a non-interactive tree view instead.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["chat"],
+ purpose: "Chat with the vikingbot agent.",
+ usage: "ov chat [--message <text>] [--session <id>]",
+ examples: &[
+ HelpItem {
+ label: "ov chat",
+ description: "Start interactive chat.",
+ },
+ HelpItem {
+ label: "ov chat --message \"summarize project ACME\"",
+ description: "Send one message.",
+ },
+ ],
+ arguments: &[],
+ common_options: &[
+ HelpItem {
+ label: "-m, --message <text>",
+ description: "Send one message instead of interactive input.",
+ },
+ HelpItem {
+ label: "-s, --session <id>",
+ description: "Use a specific chat session.",
+ },
+ HelpItem {
+ label: "--no-format",
+ description: "Disable rich formatting.",
+ },
+ ],
+ advanced_options: &[
+ HelpItem {
+ label: "--sender <id>",
+ description: "Set sender ID.",
+ },
+ HelpItem {
+ label: "--stream <bool>",
+ description: "Enable or disable streaming.",
+ },
+ HelpItem {
+ label: "--no-history",
+ description: "Disable command history.",
+ },
+ ],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov find \"topic\"",
+ description: "Search context directly.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["wait"],
+ purpose: "Wait for queued async processing to complete.",
+ usage: "ov wait [--timeout <seconds>]",
+ examples: &[HelpItem {
+ label: "ov wait --timeout 120",
+ description: "Wait up to two minutes.",
+ }],
+ arguments: &[],
+ common_options: &[HelpItem {
+ label: "--timeout <seconds>",
+ description: "Maximum wait time.",
+ }],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov task list",
+ description: "Inspect remaining work.",
+ },
+ HelpItem {
+ label: "ov status",
+ description: "Check backend health.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["task"],
+ purpose: "Inspect and manage async processing tasks.",
+ usage: "ov task <subcommand>",
+ examples: &[
+ HelpItem {
+ label: "ov task list --status failed",
+ description: "List failed tasks.",
+ },
+ HelpItem {
+ label: "ov task status <task-id>",
+ description: "Inspect one task.",
+ },
+ ],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[
+ HelpItem {
+ label: "status <task-id>",
+ description: "Show one task.",
+ },
+ HelpItem {
+ label: "list",
+ description: "List tracked tasks.",
+ },
+ HelpItem {
+ label: "watch <subcommand>",
+ description: "Manage auto-refresh subscriptions.",
+ },
+ ],
+ next_steps: &[HelpItem {
+ label: "ov wait",
+ description: "Wait for queued work.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["status"],
+ purpose: "Show OpenViking server readiness and component status.",
+ usage: "ov status [--verbose]",
+ examples: &[
+ HelpItem {
+ label: "ov status",
+ description: "Check config, connection, models, queue, and component health.",
+ },
+ HelpItem {
+ label: "ov status --verbose",
+ description: "Show full component tables.",
+ },
+ ],
+ arguments: &[],
+ common_options: &[HelpItem {
+ label: "--verbose",
+ description: "Show full component tables instead of the curated diagnostic view.",
+ }],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov health",
+ description: "Run a lightweight connectivity check.",
+ },
+ HelpItem {
+ label: "ov config validate",
+ description: "Validate active CLI config.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["observer"],
+ purpose: "Inspect specific OpenViking server subsystems.",
+ usage: "ov observer <subcommand>",
+ examples: &[
+ HelpItem {
+ label: "ov observer models",
+ description: "Inspect VLM, embedding, and rerank model status.",
+ },
+ HelpItem {
+ label: "ov observer queue",
+ description: "Inspect queue status.",
+ },
+ ],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[
+ HelpItem {
+ label: "queue",
+ description: "Queue status.",
+ },
+ HelpItem {
+ label: "models",
+ description: "Model status.",
+ },
+ HelpItem {
+ label: "transaction",
+ description: "Transaction system status.",
+ },
+ HelpItem {
+ label: "filesystem / retrieval / system",
+ description: "Operational metrics.",
+ },
+ ],
+ next_steps: &[HelpItem {
+ label: "ov status",
+ description: "Return to the full status view.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["health"],
+ purpose: "Run a quick server reachability check.",
+ usage: "ov health",
+ examples: &[HelpItem {
+ label: "ov health",
+ description: "Check whether the active server is reachable.",
+ }],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov config validate",
+ description: "Probe the active config if health fails.",
+ },
+ HelpItem {
+ label: "ov status",
+ description: "Inspect detailed backend status.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["config"],
+ purpose: "Add, edit, delete, show, validate, or switch OpenViking CLI configs.",
+ usage: "ov config [show|validate|switch]",
+ examples: &[
+ HelpItem {
+ label: "ov config",
+ description: "Open the interactive config manager.",
+ },
+ HelpItem {
+ label: "ov config validate",
+ description: "Probe the active config.",
+ },
+ ],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[
+ HelpItem {
+ label: "show",
+ description: "Print active config with secrets redacted.",
+ },
+ HelpItem {
+ label: "validate",
+ description: "Probe the active server/auth config.",
+ },
+ HelpItem {
+ label: "switch",
+ description: "Switch the active saved config.",
+ },
+ ],
+ next_steps: &[
+ HelpItem {
+ label: "ov config validate",
+ description: "Confirm the active config works.",
+ },
+ HelpItem {
+ label: "ov --help",
+ description: "See all commands.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["config", "show"],
+ purpose: "Print the active CLI config with secrets redacted.",
+ usage: "ov config show",
+ examples: &[HelpItem {
+ label: "ov config show",
+ description: "Show the active server URL, config name, and safe fields.",
+ }],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov config",
+ description: "Edit saved configs.",
+ },
+ HelpItem {
+ label: "ov config validate",
+ description: "Probe the active config.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["config", "validate"],
+ purpose: "Parse the active config and probe the configured OpenViking server.",
+ usage: "ov config validate",
+ examples: &[HelpItem {
+ label: "ov config validate",
+ description: "Check active URL, auth, and server reachability.",
+ }],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov config",
+ description: "Fix or replace a failing config.",
+ },
+ HelpItem {
+ label: "ov health",
+ description: "Run a quick health check.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["config", "switch"],
+ purpose: "Switch the active CLI config to a saved config.",
+ usage: "ov config switch",
+ examples: &[HelpItem {
+ label: "ov config switch",
+ description: "Choose a saved config and make it active.",
+ }],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov config show",
+ description: "Confirm the new active config.",
+ },
+ HelpItem {
+ label: "ov config validate",
+ description: "Probe the switched config.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["language"],
+ purpose: "Choose the OpenViking CLI display language.",
+ usage: "ov language [en|zh-CN]",
+ examples: &[
+ HelpItem {
+ label: "ov language",
+ description: "Open the language selector.",
+ },
+ HelpItem {
+ label: "ov language zh-CN",
+ description: "Switch display text to Simplified Chinese.",
+ },
+ ],
+ arguments: &[HelpItem {
+ label: "language",
+ description: "Optional language code: en or zh-CN.",
+ }],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov config",
+ description: "Open the config manager.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["version"],
+ purpose: "Print the OpenViking CLI version.",
+ usage: "ov version",
+ examples: &[HelpItem {
+ label: "ov version",
+ description: "Show the installed CLI version.",
+ }],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[HelpItem {
+ label: "ov --help",
+ description: "See all commands.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["admin"],
+ purpose: "Manage accounts, users, roles, and API keys. Admin/root access required.",
+ usage: "ov admin <subcommand> [--sudo]",
+ examples: &[
+ HelpItem {
+ label: "ov admin list-accounts --sudo",
+ description: "List accounts with the root API key.",
+ },
+ HelpItem {
+ label: "ov admin register-user <account> <user>",
+ description: "Register a user in an account.",
+ },
+ ],
+ arguments: &[],
+ common_options: &[HelpItem {
+ label: "--sudo",
+ description: "Use root_api_key for root-only admin commands.",
+ }],
+ advanced_options: &[],
+ subcommands: &[
+ HelpItem {
+ label: "create-account / delete-account",
+ description: "Create or remove an account.",
+ },
+ HelpItem {
+ label: "list-accounts",
+ description: "List accounts.",
+ },
+ HelpItem {
+ label: "register-user / remove-user",
+ description: "Manage account users.",
+ },
+ HelpItem {
+ label: "set-role / regenerate-key",
+ description: "Manage roles and API keys.",
+ },
+ ],
+ next_steps: &[
+ HelpItem {
+ label: "ov config show",
+ description: "Check whether root_api_key is configured.",
+ },
+ HelpItem {
+ label: "ov admin <subcommand> --help",
+ description: "Show exact arguments for an admin operation.",
+ },
+ ],
+ },
+ CommandHelpSpec {
+ path: &["system"],
+ purpose: "Run server utility, health, consistency, and crypto commands.",
+ usage: "ov system <subcommand>",
+ examples: &[
+ HelpItem {
+ label: "ov system health",
+ description: "Run server health through the system namespace.",
+ },
+ HelpItem {
+ label: "ov system consistency viking://projects/acme",
+ description: "Check filesystem/vector consistency.",
+ },
+ ],
+ arguments: &[],
+ common_options: &[],
+ advanced_options: &[],
+ subcommands: &[
+ HelpItem {
+ label: "wait / status / health",
+ description: "Operational checks.",
+ },
+ HelpItem {
+ label: "consistency <uri>",
+ description: "Check subtree consistency.",
+ },
+ HelpItem {
+ label: "crypto <subcommand>",
+ description: "Key management commands.",
+ },
+ ],
+ next_steps: &[HelpItem {
+ label: "ov status",
+ description: "Use the standard status view.",
+ }],
+ },
+ CommandHelpSpec {
+ path: &["reindex"],
+ purpose: "Reindex semantic/vector artifacts for a URI.",
+ usage: "ov reindex <uri> [--mode <mode>] [--wait <bool>] [--sudo]",
+ examples: &[HelpItem {
+ label: "ov reindex viking://projects/acme --mode vectors_only --wait true",
+ description: "Rebuild vector artifacts and wait.",
+ }],
+ arguments: &[HelpItem {
+ label: "<uri>",
+ description: "Subtree URI to reindex.",
+ }],
+ common_options: &[
+ HelpItem {
+ label: "--mode <mode>",
+ description: "Reindex mode. Defaults to vectors_only.",
+ },
+ HelpItem {
+ label: "--wait <bool>",
+ description: "Wait for completion. Defaults to true.",
+ },
+ HelpItem {
+ label: "--sudo",
+ description: "Use root API key when required.",
+ },
+ ],
+ advanced_options: &[],
+ subcommands: &[],
+ next_steps: &[
+ HelpItem {
+ label: "ov task list",
+ description: "Inspect reindex work.",
+ },
+ HelpItem {
+ label: "ov find \"query\" -u <uri>",
+ description: "Verify retrieval after reindexing.",
+ },
+ ],
+ },
+];
+
+pub(crate) fn is_top_level_help_request(args: &[OsString]) -> bool {
+ if args.len() != 2 {
+ return false;
+ }
+
+ matches!(
+ args[1].to_string_lossy().as_ref(),
+ "--help" | "-h" | "-help" | "help"
+ )
+}
+
+pub(crate) fn render_command_help_request(args: &[OsString]) -> Option<String> {
+ let path = command_help_path(args)?;
+ let spec = command_spec(&path)?;
+ Some(render_command_help(spec))
+}
+
+pub(crate) fn render_top_level_help() -> String {
+ render_top_level_help_with_language(Language::current())
+}
+
+pub(crate) fn render_top_level_help_with_language(language: Language) -> String {
+ let mut lines = Vec::new();
+
+ lines.push(format!(
+ "{} {}",
+ theme::brand_title("OpenViking").bold(),
+ theme::version(version())
+ ));
+ lines.push(
+ theme::heading(copy(
+ language,
+ "Context Database for AI Agents",
+ "AI Agent 上下文数据库",
+ ))
+ .bold()
+ .to_string(),
+ );
+ lines.push(String::new());
+ lines.push(format!(
+ "{}",
+ theme::warning(copy(language, "Usage:", "用法:")).bold()
+ ));
+ lines.push(format!(" {}", theme::strong("ov <command> [options]")));
+ lines.push(String::new());
+ lines.push(format!(
+ "{}",
+ theme::strong(copy(language, "Start here:", "从这里开始:"))
+ ));
+ lines.push(start_here_line(
+ "ov config",
+ copy(
+ language,
+ "Add, edit, or delete configs",
+ "添加、编辑或删除配置",
+ ),
+ ));
+ lines.push(start_here_line(
+ "ov health",
+ copy(language, "Check server reachability", "检查服务器连接"),
+ ));
+ lines.push(start_here_line(
+ "ov status",
+ copy(language, "Inspect server status", "查看服务器状态"),
+ ));
+ lines.push(start_here_line(
+ "ov tui",
+ copy(
+ language,
+ "Browse OpenViking interactively",
+ "交互式浏览 OpenViking",
+ ),
+ ));
+ lines.push(String::new());
+
+ for section in HELP_SECTIONS {
+ lines.extend(section_lines(section));
+ lines.push(String::new());
+ }
+
+ lines.push(format!(
+ "{}",
+ theme::strong(copy(language, "Global options:", "全局选项:"))
+ ));
+ lines.push(option_line(
+ "-o, --output <table|json>",
+ copy(language, "Output format", "输出格式"),
+ ));
+ lines.push(option_line(
+ "-c, --compact",
+ copy(language, "Compact output", "紧凑输出"),
+ ));
+ lines.push(option_line(
+ "--account <account>",
+ copy(language, "Override account", "覆盖账户"),
+ ));
+ lines.push(option_line(
+ "--user <user>",
+ copy(language, "Override user", "覆盖用户"),
+ ));
+ lines.push(option_line(
+ "--agent-id <agent>",
+ copy(language, "Override agent", "覆盖 Agent"),
+ ));
+ lines.push(option_line(
+ "--sudo",
+ copy(
+ language,
+ "Use root API key for admin commands",
+ "管理命令使用 root API Key",
+ ),
+ ));
+ lines.push(option_line(
+ "-h, --help",
+ copy(language, "Show help", "显示帮助"),
+ ));
+ lines.push(option_line(
+ "-V, --version",
+ copy(language, "Show version", "显示版本"),
+ ));
+ lines.push(String::new());
+ lines.push(format!(
+ "{}",
+ theme::strong(copy(language, "More:", "更多:"))
+ ));
+ lines.push(start_here_line(
+ "ov <command> --help",
+ copy(language, "Show command details", "查看命令详情"),
+ ));
+ lines.push(start_here_line(
+ "ov config",
+ copy(language, "Configure the CLI", "配置 CLI"),
+ ));
+
+ format!("{}\n", lines.join("\n"))
+}
+
+fn render_command_help(spec: &CommandHelpSpec) -> String {
+ let mut lines = Vec::new();
+ let language = Language::current();
+ let command = command_display(spec.path);
+
+ lines.push(format!(
+ "{} {} {}",
+ theme::brand_title("OpenViking").bold(),
+ theme::version(version()),
+ theme::muted(format!("· {command}"))
+ ));
+ lines.push(theme::body(localized_command_purpose(spec, language)).to_string());
+ lines.push(String::new());
+ lines.push(format!(
+ "{}",
+ theme::warning(copy(language, "Usage:", "用法:")).bold()
+ ));
+ lines.push(format!(" {}", theme::strong(spec.usage)));
+ push_section(
+ &mut lines,
+ copy(language, "Examples", "示例"),
+ spec.examples,
+ );
+ push_section(
+ &mut lines,
+ copy(language, "Arguments", "参数"),
+ spec.arguments,
+ );
+ push_section(
+ &mut lines,
+ copy(language, "Subcommands", "子命令"),
+ spec.subcommands,
+ );
+ push_section(
+ &mut lines,
+ copy(language, "Common options", "常用选项"),
+ spec.common_options,
+ );
+ push_section(
+ &mut lines,
+ copy(language, "Advanced options", "高级选项"),
+ spec.advanced_options,
+ );
+ push_section(
+ &mut lines,
+ copy(language, "Global options", "全局选项"),
+ GLOBAL_OPTIONS,
+ );
+ push_section(
+ &mut lines,
+ copy(language, "Next", "下一步"),
+ spec.next_steps,
+ );
+
+ format!("{}\n", lines.join("\n"))
+}
+
+fn push_section(lines: &mut Vec<String>, title: &str, items: &[HelpItem]) {
+ if items.is_empty() {
+ return;
+ }
+
+ lines.push(String::new());
+ lines.push(format!("{}", theme::heading(title).bold()));
+ for item in items {
+ lines.push(help_item_line(item));
+ }
+}
+
+fn help_item_line(item: &HelpItem) -> String {
+ let language = Language::current();
+ let description = localized_help_item_description(item.label, item.description, language);
+ if display_width(item.label) > COMMAND_HELP_LEFT_WIDTH {
+ return format!(
+ " {}\n {}",
+ theme::command(item.label),
+ theme::body(description)
+ );
+ }
+
+ format!(
+ " {} {}",
+ theme::command(pad_to_display_width(item.label, COMMAND_HELP_LEFT_WIDTH)),
+ theme::body(description)
+ )
+}
+
+fn localized_command_purpose<'a>(spec: &'a CommandHelpSpec, language: Language) -> &'a str {
+ if language == Language::En {
+ return spec.purpose;
+ }
+ match spec.path {
+ ["config"] => "添加、编辑、删除、显示、验证或切换 OpenViking CLI 配置。",
+ ["config", "show"] => "显示当前 CLI 配置,并隐藏敏感信息。",
+ ["config", "validate"] => "解析当前配置,并探测 OpenViking 服务器。",
+ ["config", "switch"] => "切换到已保存的 CLI 配置。",
+ ["health"] => "快速检查服务器是否可连接。",
+ ["status"] => "查看 OpenViking 服务器诊断状态。",
+ ["language"] => "选择 OpenViking CLI 显示语言。",
+ _ => spec.purpose,
+ }
+}
+
+fn localized_help_item_description<'a>(
+ label: &str,
+ description: &'a str,
+ language: Language,
+) -> &'a str {
+ if language == Language::En {
+ return description;
+ }
+ match label {
+ "ov config" => "打开交互式配置管理。",
+ "ov config validate" => "验证当前配置。",
+ "show" => "显示当前配置,并隐藏敏感信息。",
+ "validate" => "探测当前服务器和认证配置。",
+ "switch" => "切换当前已保存配置。",
+ "ov --help" => "查看所有命令。",
+ "ov health" => "快速健康检查。",
+ "ov status" => "查看详细后端状态。",
+ "ov config show" => "确认新的当前配置。",
+ "ov config switch" => "选择一个已保存配置并设为当前配置。",
+ "ov language" => "打开语言选择器。",
+ "ov language zh-CN" => "将显示语言切换为简体中文。",
+ "language" => "可选语言代码:en 或 zh-CN。",
+ "-o, --output <table|json>" => "选择表格输出或机器可读 JSON。",
+ "-c, --compact <bool>" => "使用紧凑的表格或 JSON 输出。",
+ "--account <account>" => "覆盖本次命令的 X-OpenViking-Account。",
+ "--user <user>" => "覆盖本次命令的 X-OpenViking-User。",
+ "--agent-id <agent>" => "覆盖本次命令的 X-OpenViking-Agent。",
+ "--sudo" => "使用 root API Key 执行管理命令。",
+ _ => description,
+ }
+}
+
+fn start_here_line(command: &str, description: &str) -> String {
+ format!(
+ " {} {}",
+ theme::command(pad_to_display_width(command, 22)).bold(),
+ theme::body(description)
+ )
+}
+
+fn option_line(option: &str, description: &str) -> String {
+ format!(
+ " {} {}",
+ theme::command(pad_to_display_width(option, 26)),
+ theme::body(description)
+ )
+}
+
+fn section_lines(section: &HelpSection) -> Vec<String> {
+ let mut lines = Vec::new();
+ let language = Language::current();
+ let title_text = localized_section_title(section.title, language);
+ let title = format!("─ {title_text} ");
+ let fill = BOX_WIDTH.saturating_sub(2 + display_width(&title));
+ lines.push(format!(
+ "{}{}{}{}",
+ theme::border("╭"),
+ theme::border(title).bold(),
+ theme::border("─".repeat(fill)),
+ theme::border("╮")
+ ));
+
+ for command in section.commands {
+ lines.push(command_line(command));
+ }
+
+ lines.push(format!(
+ "{}{}{}",
+ theme::border("╰"),
+ theme::border("─".repeat(BOX_WIDTH.saturating_sub(2))),
+ theme::border("╯")
+ ));
+ lines
+}
+
+fn command_line(command: &HelpCommand) -> String {
+ let language = Language::current();
+ let command_description =
+ localized_command_description(command.name, command.description, language);
+ let description = match command.badge {
+ Some(badge) => {
+ let used = display_width(command_description)
+ + display_width(localized_badge(badge, language));
+ let spacer = DESCRIPTION_WIDTH.saturating_sub(used).max(1);
+ format!(
+ "{}{}{}",
+ command_description,
+ " ".repeat(spacer),
+ theme::muted(localized_badge(badge, language))
+ )
+ }
+ None => format!(
+ "{}{}",
+ command_description,
+ " ".repeat(DESCRIPTION_WIDTH.saturating_sub(display_width(command_description)))
+ ),
+ };
+
+ format!(
+ "{} {} {} {}",
+ theme::border("│"),
+ theme::command(pad_to_display_width(command.name, COMMAND_WIDTH)).bold(),
+ theme::body(description),
+ theme::border("│")
+ )
+}
+
+fn display_width(value: &str) -> usize {
+ UnicodeWidthStr::width(value)
+}
+
+fn pad_to_display_width(value: &str, width: usize) -> String {
+ format!(
+ "{}{}",
+ value,
+ " ".repeat(width.saturating_sub(display_width(value)))
+ )
+}
+
+fn localized_section_title(title: &str, language: Language) -> &str {
+ if language == Language::En {
+ return title;
+ }
+ match title {
+ "Core Workflow" => "核心流程",
+ "Filesystem" => "文件系统",
+ "Search & Context" => "搜索与上下文",
+ "Config & Status" => "配置与状态",
+ "Import, Export & Sessions" => "导入、导出与会话",
+ "Interactive & Admin" => "交互与管理",
+ _ => title,
+ }
+}
+
+fn localized_badge<'a>(badge: &'a str, language: Language) -> &'a str {
+ match (language, badge) {
+ (Language::ZhCn, "experimental") => "实验性",
+ _ => badge,
+ }
+}
+
+fn localized_command_description<'a>(
+ name: &str,
+ description: &'a str,
+ language: Language,
+) -> &'a str {
+ if language == Language::En {
+ return description;
+ }
+ match name {
+ "add-resource" => "添加文件、文件夹、URL 或仓库",
+ "find" => "语义检索相关上下文",
+ "read" => "读取精确资源内容",
+ "write" => "更新已有资源",
+ "add-memory" => "直接添加记忆",
+ "ls" => "列出目录内容",
+ "tree" => "查看范围内的资源树",
+ "mkdir" => "创建目录",
+ "rm" => "删除资源",
+ "mv" => "移动或重命名资源",
+ "stat" => "查看资源元数据",
+ "get" => "下载文件",
+ "search" => "上下文感知检索",
+ "grep" => "模式搜索",
+ "glob" => "Glob 路径搜索",
+ "overview" => "生成资源概览",
+ "abstract" => "生成资源摘要",
+ "relations" => "列出资源关系",
+ "link" => "创建关系链接",
+ "unlink" => "删除关系链接",
+ "config" => "添加、编辑、删除或切换配置",
+ "config show" => "显示当前配置",
+ "config validate" => "验证当前配置",
+ "config switch" => "切换当前配置",
+ "health" => "快速检查服务器连接",
+ "status" => "查看系统状态",
+ "wait" => "等待异步任务完成",
+ "task" => "查看异步任务",
+ "observer" => "观察服务器组件",
+ "session" => "管理会话",
+ "import" => "导入 .ovpack",
+ "export" => "导出为 .ovpack",
+ "backup" => "创建仅恢复备份",
+ "restore" => "恢复备份",
+ "tui" => "打开交互式浏览器",
+ "chat" => "与 VikingBot 对话",
+ "admin" => "管理账户、用户和 API Key",
+ "system" => "系统维护命令",
+ "privacy" => "管理隐私策略",
+ "reindex" => "重建语义和向量索引",
+ "version" => "显示版本信息",
+ "language" => "选择 CLI 显示语言",
+ _ => description,
+ }
+}
+
+fn command_help_path(args: &[OsString]) -> Option<Vec<String>> {
+ let tokens: Vec<String> = args
+ .iter()
+ .map(|arg| arg.to_string_lossy().to_string())
+ .collect();
+ if tokens.len() < 2 {
+ 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();
+ let mut i = 1;
+ while i < tokens.len() {
+ let token = &tokens[i];
+ if is_help_flag(token) {
+ break;
+ }
+ if token == "--sudo" || token == "--progress" || token == "--no-progress" || token == "-v" {
+ i += 1;
+ continue;
+ }
+ if consumes_value(token) {
+ i += if token.contains('=') { 1 } else { 2 };
+ continue;
+ }
+ if token.starts_with('-') {
+ i += 1;
+ continue;
+ }
+
+ path.push(canonical_command_token(token));
+ if let Some(next) = tokens.get(i + 1) {
+ if is_help_flag(next) {
+ // Explicit help for this top-level command.
+ } 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;
+ }
+ } else {
+ return None;
+ }
+ }
+ break;
+ }
+
+ if path.is_empty() {
+ return None;
+ }
+
+ if has_help_flag || (path.len() == 1 && is_bare_group_help_command(&path[0])) {
+ Some(path)
+ } else {
+ None
+ }
+}
+
+fn command_spec(path: &[String]) -> Option<&'static CommandHelpSpec> {
+ COMMAND_HELP_SPECS.iter().find(|spec| {
+ spec.path.len() == path.len()
+ && spec
+ .path
+ .iter()
+ .zip(path.iter())
+ .all(|(left, right)| left == right)
+ })
+}
+
+fn canonical_command_token(token: &str) -> String {
+ match token {
+ "list" => "ls",
+ "del" | "delete" => "rm",
+ "rename" => "mv",
+ "lang" => "language",
+ other => other,
+ }
+ .to_string()
+}
+
+fn command_display(path: &[&str]) -> String {
+ format!("ov {}", path.join(" "))
+}
+
+fn version() -> String {
+ format!("v{}", env!("OPENVIKING_CLI_VERSION"))
+}
+
+fn allows_curated_nested(command: &str) -> bool {
+ matches!(command, "config")
+}
+
+fn is_bare_group_help_command(command: &str) -> bool {
+ matches!(
+ command,
+ "task" | "session" | "privacy" | "admin" | "system" | "observer"
+ )
+}
+
+fn is_help_flag(token: &str) -> bool {
+ matches!(token, "--help" | "-h" | "-help")
+}
+
+fn consumes_value(token: &str) -> bool {
+ matches!(
+ token,
+ "-o" | "--output" | "-c" | "--compact" | "--account" | "--user" | "--agent-id"
+ ) || token.starts_with("--output=")
+ || token.starts_with("--compact=")
+ || token.starts_with("--account=")
+ || token.starts_with("--user=")
+ || token.starts_with("--agent-id=")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ 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;
+
+ fn os_args(args: &[&str]) -> Vec<OsString> {
+ args.iter().map(OsString::from).collect()
+ }
+
+ 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 detects_only_top_level_help_requests() {
+ 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", "config", "--help"
+ ])));
+ assert!(!is_top_level_help_request(&os_args(&[
+ "ov", "help", "config"
+ ])));
+ assert!(!is_top_level_help_request(&os_args(&["ov", "--version"])));
+ }
+
+ #[test]
+ fn top_level_help_is_grouped_and_promotes_start_here() {
+ let rendered = strip_ansi(&render_top_level_help());
+
+ assert!(rendered.contains("OpenViking v"));
+ assert!(rendered.contains("Context Database for AI Agents"));
+ assert!(rendered.contains("Usage:"));
+ assert!(rendered.contains("ov <command> [options]"));
+ assert!(rendered.contains("Start here:"));
+ assert!(rendered.contains("ov config"));
+ assert!(rendered.contains("ov health"));
+ assert!(rendered.contains("ov status"));
+ assert!(rendered.contains("ov tui"));
+ }
+
+ #[test]
+ fn top_level_help_contains_command_groups_without_flat_commands_heading() {
+ let rendered = strip_ansi(&render_top_level_help());
+
+ for section in [
+ "Core Workflow",
+ "Filesystem",
+ "Search & Context",
+ "Config & Status",
+ "Import, Export & Sessions",
+ "Interactive & Admin",
+ ] {
+ assert!(rendered.contains(section), "missing section: {section}");
+ }
+
+ assert!(rendered.contains("search"));
+ assert!(rendered.contains("experimental"));
+ assert!(rendered.contains("ov <command> --help"));
+ assert!(!rendered.contains("Commands:\n add-resource"));
+ }
+
+ #[test]
+ fn boxed_sections_have_stable_width_after_ansi_is_removed() {
+ let rendered = strip_ansi(&render_top_level_help());
+ for line in rendered
+ .lines()
+ .filter(|line| line.starts_with(['╭', '│', '╰']))
+ {
+ assert_eq!(display_width(line), 74, "bad line width: {line}");
+ }
+ }
+
+ #[test]
+ fn every_top_level_command_in_help_map_has_command_help() {
+ for command in HELP_SECTIONS
+ .iter()
+ .flat_map(|section| section.commands.iter().map(|command| command.name))
+ .filter(|name| !name.contains(' '))
+ {
+ assert!(
+ command_spec(&[command.to_string()]).is_some(),
+ "missing command help for {command}"
+ );
+ }
+ }
+
+ #[test]
+ fn renders_curated_find_help() {
+ let rendered = strip_ansi(
+ &render_command_help_request(&os_args(&["ov", "find", "--help"]))
+ .expect("find help should render"),
+ );
+
+ assert!(rendered.contains("OpenViking v"));
+ assert!(rendered.contains("ov find <query>"));
+ assert!(rendered.contains("Examples"));
+ assert!(rendered.contains("Common options"));
+ assert!(rendered.contains("Next"));
+ assert!(rendered.contains("ov read <uri>"));
+ }
+
+ #[test]
+ fn renders_curated_command_help_for_single_dash_help_alias() {
+ let rendered = strip_ansi(
+ &render_command_help_request(&os_args(&["ov", "find", "-help"]))
+ .expect("find -help should render"),
+ );
+
+ assert!(rendered.contains("OpenViking v"));
+ assert!(rendered.contains("ov find <query>"));
+ assert!(rendered.contains("Usage:"));
+ }
+
+ #[test]
+ fn renders_curated_status_help_with_verbose_option() {
+ let rendered = strip_ansi(
+ &render_command_help_request(&os_args(&["ov", "status", "--help"]))
+ .expect("status help should render"),
+ );
+
+ assert!(rendered.contains("ov status [--verbose]"));
+ assert!(rendered.contains("ov status --verbose"));
+ assert!(rendered.contains("Show full component tables"));
+ }
+
+ #[test]
+ 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"]),
+ ] {
+ let rendered = strip_ansi(
+ &render_command_help_request(&args).expect("config switch help should render"),
+ );
+ assert!(rendered.contains("ov config switch"));
+ assert!(rendered.contains("Switch the active CLI config"));
+ assert!(!rendered.contains("profile"));
+ }
+ }
+
+ #[test]
+ fn renders_curated_group_help_for_config_and_task() {
+ let config = strip_ansi(
+ &render_command_help_request(&os_args(&["ov", "config", "--help"]))
+ .expect("config help should render"),
+ );
+ assert!(config.contains("Subcommands"));
+ assert!(config.contains("show"));
+ assert!(config.contains("validate"));
+ assert!(config.contains("switch"));
+
+ let task = strip_ansi(
+ &render_command_help_request(&os_args(&["ov", "task", "--help"]))
+ .expect("task help should render"),
+ );
+ assert!(task.contains("status <task-id>"));
+ assert!(task.contains("list"));
+ }
+
+ #[test]
+ fn command_help_detection_allows_global_flags_before_command() {
+ let path = command_help_path(&os_args(&[
+ "ov",
+ "--account",
+ "acme",
+ "--user",
+ "u1",
+ "find",
+ "--help",
+ ]))
+ .expect("path should be detected");
+
+ assert_eq!(path, vec!["find"]);
+ }
+
+ #[test]
+ fn bare_command_groups_render_curated_help() {
+ for (command, expected) in [
+ ("task", "Inspect and manage async processing tasks."),
+ (
+ "session",
+ "Manage sessions, messages, archives, and committed session context.",
+ ),
+ (
+ "privacy",
+ "Manage privacy config categories, targets, versions, and activation.",
+ ),
+ ("admin", "Manage accounts, users, roles, and API keys."),
+ (
+ "system",
+ "Run server utility, health, consistency, and crypto commands.",
+ ),
+ ("observer", "Inspect specific OpenViking server subsystems."),
+ ] {
+ let rendered = strip_ansi(
+ &render_command_help_request(&os_args(&["ov", command]))
+ .unwrap_or_else(|| panic!("{command} should render curated help")),
+ );
+
+ assert!(rendered.contains(expected), "missing purpose for {command}");
+ assert!(
+ rendered.contains("Subcommands"),
+ "missing subcommands for {command}"
+ );
+ }
+ }
+
+ #[test]
+ fn bare_command_group_detection_allows_global_flags_before_command() {
+ let rendered = strip_ansi(
+ &render_command_help_request(&os_args(&[
+ "ov",
+ "--account",
+ "acme",
+ "--user",
+ "u1",
+ "task",
+ ]))
+ .expect("bare task help should render with global flags before command"),
+ );
+
+ assert!(rendered.contains("ov task <subcommand>"));
+ }
+
+ #[test]
+ fn bare_config_is_not_intercepted_by_group_help() {
+ assert!(render_command_help_request(&os_args(&["ov", "config"])).is_none());
+ }
+
+ #[test]
+ fn unsupported_nested_help_falls_back_to_clap() {
+ assert!(render_command_help_request(&os_args(&["ov", "task", "list", "--help"])).is_none());
+ }
+}
diff --git a/crates/ov_cli/src/i18n.rs b/crates/ov_cli/src/i18n.rs
new file mode 100644
index 000000000..af2c8e83c
--- /dev/null
+++ b/crates/ov_cli/src/i18n.rs
@@ -0,0 +1,177 @@
+use std::{
+ fs,
+ path::{Path, PathBuf},
+};
+
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ config::default_config_path,
+ error::{Error, Result},
+};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub(crate) enum Language {
+ #[serde(rename = "en")]
+ En,
+ #[serde(rename = "zh-CN")]
+ ZhCn,
+}
+
+impl Language {
+ pub(crate) fn label(self) -> &'static str {
+ match self {
+ Self::En => "English",
+ Self::ZhCn => "简体中文",
+ }
+ }
+
+ pub(crate) fn from_code(value: &str) -> Option<Self> {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "en" | "en-us" | "en_us" => Some(Self::En),
+ "zh" | "zh-cn" | "zh_cn" | "cn" | "chinese" | "中文" | "简体中文" => {
+ Some(Self::ZhCn)
+ }
+ _ => None,
+ }
+ }
+
+ #[cfg(not(test))]
+ pub(crate) fn current() -> Self {
+ load_saved_language()
+ .ok()
+ .flatten()
+ .unwrap_or_else(detect_language_from_env)
+ }
+
+ #[cfg(test)]
+ pub(crate) fn current() -> Self {
+ Self::En
+ }
+}
+
+pub(crate) fn copy<'a>(language: Language, en: &'a str, zh: &'a str) -> &'a str {
+ match language {
+ Language::En => en,
+ Language::ZhCn => zh,
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+struct CliSettings {
+ language: Option<Language>,
+}
+
+pub(crate) fn settings_path() -> Result<PathBuf> {
+ let active_path = default_config_path()?;
+ let config_dir = active_path
+ .parent()
+ .ok_or_else(|| Error::Config("Could not determine config directory".to_string()))?;
+ Ok(config_dir.join("ovcli.settings.conf"))
+}
+
+pub(crate) fn load_saved_language() -> Result<Option<Language>> {
+ let path = settings_path()?;
+ load_saved_language_from_path(&path)
+}
+
+pub(crate) fn save_language(language: Language) -> Result<()> {
+ let path = settings_path()?;
+ save_language_to_path(&path, language)
+}
+
+pub(crate) fn has_saved_language() -> bool {
+ load_saved_language().ok().flatten().is_some()
+}
+
+pub(crate) fn load_saved_language_from_path(path: &Path) -> Result<Option<Language>> {
+ if !path.exists() {
+ return Ok(None);
+ }
+ let content = fs::read_to_string(path)?;
+ let settings: CliSettings = serde_json::from_str(&content)?;
+ Ok(settings.language)
+}
+
+pub(crate) fn save_language_to_path(path: &Path, language: Language) -> Result<()> {
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ let settings = CliSettings {
+ language: Some(language),
+ };
+ fs::write(path, serde_json::to_string_pretty(&settings)?)?;
+ Ok(())
+}
+
+#[cfg(not(test))]
+pub(crate) fn detect_language_from_env() -> Language {
+ for key in ["OPENVIKING_LANG", "LC_ALL", "LC_MESSAGES", "LANG"] {
+ if let Ok(value) = std::env::var(key) {
+ if let Some(language) = language_from_locale(&value) {
+ return language;
+ }
+ }
+ }
+ Language::En
+}
+
+pub(crate) fn language_from_locale(value: &str) -> Option<Language> {
+ let normalized = value.split('.').next().unwrap_or(value);
+ if normalized.to_ascii_lowercase().starts_with("zh") {
+ Some(Language::ZhCn)
+ } else if normalized.to_ascii_lowercase().starts_with("en") {
+ Some(Language::En)
+ } else {
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ Language, copy, language_from_locale, load_saved_language_from_path, save_language_to_path,
+ };
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ fn settings_path(name: &str) -> std::path::PathBuf {
+ let suffix = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("clock should be valid")
+ .as_nanos();
+ std::env::temp_dir()
+ .join(format!("openviking-i18n-{name}-{suffix}"))
+ .join("ovcli.settings.conf")
+ }
+
+ #[test]
+ fn language_settings_save_and_load() {
+ let path = settings_path("save-load");
+
+ assert_eq!(
+ load_saved_language_from_path(&path).expect("missing settings should load"),
+ None
+ );
+
+ save_language_to_path(&path, Language::ZhCn).expect("language should save");
+
+ assert_eq!(
+ load_saved_language_from_path(&path).expect("settings should load"),
+ Some(Language::ZhCn)
+ );
+ }
+
+ #[test]
+ fn locale_detection_supports_chinese_and_english() {
+ assert_eq!(language_from_locale("zh_CN.UTF-8"), Some(Language::ZhCn));
+ assert_eq!(language_from_locale("zh-Hans"), Some(Language::ZhCn));
+ assert_eq!(language_from_locale("en_US.UTF-8"), Some(Language::En));
+ assert_eq!(language_from_locale("fr_FR.UTF-8"), None);
+ }
+
+ #[test]
+ fn copy_returns_language_specific_text() {
+ assert_eq!(copy(Language::En, "Config", "配置"), "Config");
+ assert_eq!(copy(Language::ZhCn, "Config", "配置"), "配置");
+ }
+}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 112c9ff1f..1db23556c 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -2,16 +2,30 @@ mod base_client;
mod client;
mod commands;
mod config;
+mod config_command_ui;
+mod config_wizard;
mod error;
+mod error_classifier;
+mod error_ui;
mod handlers;
+mod health_ui;
+mod help_ui;
+mod i18n;
mod output;
+mod status_ui;
+mod theme;
mod tui;
mod utils;
use clap::{ArgAction, Args, Parser, Subcommand};
+use colored::Colorize;
use config::Config;
+use error::{Error, Result};
use output::OutputFormat;
-use std::ffi::OsString;
+use std::{
+ ffi::OsString,
+ io::{self, IsTerminal},
+};
/// CLI context shared across commands
#[derive(Debug, Clone)]
@@ -120,7 +134,7 @@ struct Cli {
agent_id: Option<String>,
/// Use root API key for admin commands
- #[arg(long)]
+ #[arg(long, global = true, hide = true)]
sudo: bool,
/// Enable HTTP request profiling for this command
@@ -615,7 +629,11 @@ enum Commands {
action: TaskCommands,
},
/// [Status] All OpenViking Server components status
- Status,
+ Status {
+ /// Show full component tables
+ #[arg(long)]
+ verbose: bool,
+ },
/// [Status] Observe OpenViking Server components status
Observer {
#[command(subcommand)]
@@ -623,10 +641,16 @@ enum Commands {
},
/// [Status] Quick health check
Health,
- /// [Status] Configuration management
+ /// [Status] Configuration management; run without a subcommand to add, edit, or delete configs
Config {
#[command(subcommand)]
- action: ConfigCommands,
+ action: Option<ConfigCommands>,
+ },
+ /// [Status] Choose CLI display language
+ #[command(alias = "lang")]
+ Language {
+ /// Language code: en or zh-CN
+ language: Option<String>,
},
/// [Status] Show CLI version
Version,
@@ -997,7 +1021,7 @@ impl Commands {
!matches!(
self,
Commands::Config {
- action: ConfigCommands::SetupCli | ConfigCommands::Switch,
+ action: None | Some(ConfigCommands::Switch),
} | Commands::Version
)
}
@@ -1009,9 +1033,7 @@ enum ConfigCommands {
Show,
/// Validate configuration file
Validate,
- /// Interactive setup to configure CLI
- SetupCli,
- /// Switch between saved configurations
+ /// Switch between saved configs
Switch,
}
@@ -1130,9 +1152,160 @@ fn preprocess_privacy_args(args: Vec<OsString>) -> Vec<OsString> {
preprocess_privacy_upsert_key_flags(args)
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum LanguageGateAction {
+ Continue,
+ Prompt,
+ ExitNonInteractive,
+}
+
+fn language_gate_action(
+ args: &[OsString],
+ has_saved_language: bool,
+ is_interactive: bool,
+) -> LanguageGateAction {
+ if has_saved_language || is_language_command_request(args) {
+ LanguageGateAction::Continue
+ } else if is_interactive {
+ LanguageGateAction::Prompt
+ } else {
+ LanguageGateAction::ExitNonInteractive
+ }
+}
+
+async fn ensure_language_selected_before_command(args: &[OsString]) -> Result<bool> {
+ match language_gate_action(
+ args,
+ i18n::has_saved_language(),
+ io::stdin().is_terminal() && io::stdout().is_terminal(),
+ ) {
+ LanguageGateAction::Continue => Ok(true),
+ LanguageGateAction::Prompt => {
+ handlers::handle_language(None).await?;
+ Ok(i18n::has_saved_language())
+ }
+ LanguageGateAction::ExitNonInteractive => {
+ eprintln!("{}", language_required_message());
+ std::process::exit(2);
+ }
+ }
+}
+
+fn is_language_command_request(args: &[OsString]) -> bool {
+ matches!(
+ first_command_token(args).as_deref(),
+ Some("language" | "lang")
+ )
+}
+
+fn first_command_token(args: &[OsString]) -> Option<String> {
+ let mut index = 1usize;
+
+ while index < args.len() {
+ let token = args[index].to_string_lossy();
+ if token == "--" {
+ return args
+ .get(index + 1)
+ .map(|value| value.to_string_lossy().to_string());
+ }
+ if token == "--compact" || token == "-c" {
+ index += if args
+ .get(index + 1)
+ .is_some_and(|value| is_bool_arg(&value.to_string_lossy()))
+ {
+ 2
+ } else {
+ 1
+ };
+ continue;
+ }
+ if token.starts_with("--") {
+ index += if global_option_takes_value(&token) && !token.contains('=') {
+ 2
+ } else {
+ 1
+ };
+ continue;
+ }
+ if token.starts_with('-') {
+ index += if global_short_option_takes_value(&token) {
+ 2
+ } else {
+ 1
+ };
+ continue;
+ }
+ return Some(token.to_string());
+ }
+
+ None
+}
+
+fn global_option_takes_value(option: &str) -> bool {
+ matches!(option, "--output" | "--account" | "--user" | "--agent-id")
+}
+
+fn global_short_option_takes_value(option: &str) -> bool {
+ matches!(option, "-o")
+}
+
+fn is_bool_arg(value: &str) -> bool {
+ matches!(
+ value,
+ "true" | "false" | "True" | "False" | "TRUE" | "FALSE"
+ )
+}
+
+fn language_required_message() -> String {
+ format!(
+ "{} {}\n{}:\n {}\n {}",
+ theme::brand_title("OpenViking").bold(),
+ theme::body("needs a display language before running commands."),
+ theme::strong("Run one of"),
+ theme::command("ov language en").bold(),
+ theme::command("ov language zh-CN").bold(),
+ )
+}
+
+fn language_command_can_run_picker(has_language_value: bool, is_interactive: bool) -> bool {
+ has_language_value || is_interactive
+}
+
#[tokio::main]
async fn main() {
- let cli = Cli::parse_from(preprocess_privacy_args(std::env::args_os().collect()));
+ let args = preprocess_privacy_args(std::env::args_os().collect());
+ let command_display = error_ui::display_command(&args);
+ match ensure_language_selected_before_command(&args).await {
+ Ok(true) => {}
+ Ok(false) => return,
+ Err(e) => {
+ let report = error_ui::report_for_runtime_error(&command_display, &e);
+ error_ui::print_report(&report, false);
+ std::process::exit(2);
+ }
+ }
+
+ if help_ui::is_top_level_help_request(&args) {
+ print!("{}", help_ui::render_top_level_help());
+ return;
+ }
+ if let Some(help) = help_ui::render_command_help_request(&args) {
+ print!("{help}");
+ return;
+ }
+
+ let cli = match Cli::try_parse_from(args.clone()) {
+ Ok(cli) => cli,
+ Err(error) => {
+ if error.exit_code() == 0 {
+ let _ = error.print();
+ } else {
+ let report = error_ui::report_for_clap_error(&args, &error.to_string());
+ error_ui::print_report(&report, false);
+ }
+ std::process::exit(error.exit_code());
+ }
+ };
let output_format = cli.output;
let compact = cli.compact;
@@ -1142,10 +1315,63 @@ async fn main() {
verbose: cli.verbose,
};
if let Some(message) = legacy_upload_option_error(legacy_upload_options, &cli.command) {
- eprintln!("Error: {}", message);
+ let report = error_ui::report_for_message_error(
+ &command_display,
+ "Command Error",
+ message,
+ vec![
+ error_ui::ErrorAction::new("ov add-resource --help", "Show add-resource options"),
+ error_ui::ErrorAction::new("ov add-skill --help", "Show add-skill options"),
+ ],
+ );
+ error_ui::print_report(&report, false);
std::process::exit(2);
}
+ // Check this before loading config so misplaced --sudo reports the command rule directly.
+ if cli.sudo && !cli.command.is_admin_command() {
+ let language = i18n::Language::current();
+ let (title, message, actions) = match language {
+ i18n::Language::En => (
+ "Command Error",
+ "--sudo is only supported for admin, system, and reindex commands.",
+ vec![
+ error_ui::ErrorAction::new("ov admin --help", "Show admin commands"),
+ error_ui::ErrorAction::new("ov system --help", "Show system commands"),
+ error_ui::ErrorAction::new("ov reindex --help", "Show reindex options"),
+ ],
+ ),
+ i18n::Language::ZhCn => (
+ "命令错误",
+ "--sudo 只支持 admin、system 和 reindex 命令。",
+ vec![
+ error_ui::ErrorAction::new("ov admin --help", "查看管理命令"),
+ error_ui::ErrorAction::new("ov system --help", "查看系统命令"),
+ error_ui::ErrorAction::new("ov reindex --help", "查看重建索引选项"),
+ ],
+ ),
+ };
+ let report = error_ui::report_for_message_error(&command_display, title, message, actions);
+ error_ui::print_report(&report, false);
+ std::process::exit(2);
+ }
+
+ if let Commands::Language { language } = &cli.command {
+ if !language_command_can_run_picker(
+ language.is_some(),
+ io::stdin().is_terminal() && io::stdout().is_terminal(),
+ ) {
+ eprintln!("{}", language_required_message());
+ std::process::exit(2);
+ }
+ if let Err(e) = handlers::handle_language(language.clone()).await {
+ let report = error_ui::report_for_runtime_error(&command_display, &e);
+ error_ui::print_report(&report, cli.verbose);
+ std::process::exit(2);
+ }
+ return;
+ }
+
let config = match if cli.command.requires_cli_config_file() {
Config::load_required()
} else {
@@ -1153,7 +1379,8 @@ async fn main() {
} {
Ok(config) => config,
Err(e) => {
- eprintln!("Error: {}", e);
+ let report = error_ui::report_for_runtime_error(&command_display, &e);
+ error_ui::print_report(&report, cli.verbose);
std::process::exit(2);
}
};
@@ -1169,18 +1396,31 @@ async fn main() {
None,
if cli.profile { Some(true) } else { None },
);
+ let verbose_errors = ctx.is_verbose();
// Check if --sudo is used but root_api_key is not configured
if ctx.sudo && ctx.config.root_api_key.is_none() {
- eprintln!(
- "Error: --sudo requires root_api_key to be configured in ~/.openviking/ovcli.conf"
- );
- std::process::exit(2);
- }
-
- // Check if --sudo is used with non-admin command
- if ctx.sudo && !cli.command.is_admin_command() {
- eprintln!("Error: --sudo is only supported for admin commands (admin, system, reindex)");
+ let language = i18n::Language::current();
+ let (title, message, actions) = match language {
+ i18n::Language::En => (
+ "Configuration Error",
+ "--sudo requires root_api_key in ~/.openviking/ovcli.conf.",
+ vec![
+ error_ui::ErrorAction::new("ov config", "Edit the active config"),
+ error_ui::ErrorAction::new("ov config show", "Show the active config"),
+ ],
+ ),
+ i18n::Language::ZhCn => (
+ "配置错误",
+ "--sudo 需要在 ~/.openviking/ovcli.conf 中配置 root_api_key。",
+ vec![
+ error_ui::ErrorAction::new("ov config", "编辑当前配置"),
+ error_ui::ErrorAction::new("ov config show", "显示当前配置"),
+ ],
+ ),
+ };
+ let report = error_ui::report_for_message_error(&command_display, title, message, actions);
+ error_ui::print_report(&report, false);
std::process::exit(2);
};
@@ -1286,28 +1526,20 @@ async fn main() {
let client = ctx.get_client();
match action {
WatchCommands::Ls { active_only } => {
- commands::watch::ls(
- &client,
- active_only,
- ctx.output_format,
- ctx.compact,
- )
- .await
+ commands::watch::ls(&client, active_only, ctx.output_format, ctx.compact)
+ .await
}
WatchCommands::Show { key } => {
- commands::watch::show(&client, &key, ctx.output_format, ctx.compact)
- .await
+ commands::watch::show(&client, &key, ctx.output_format, ctx.compact).await
}
WatchCommands::Rm { key } => {
commands::watch::rm(&client, &key, ctx.output_format, ctx.compact).await
}
WatchCommands::Pause { key } => {
- commands::watch::pause(&client, &key, ctx.output_format, ctx.compact)
- .await
+ commands::watch::pause(&client, &key, ctx.output_format, ctx.compact).await
}
WatchCommands::Resume { key } => {
- commands::watch::resume(&client, &key, ctx.output_format, ctx.compact)
- .await
+ commands::watch::resume(&client, &key, ctx.output_format, ctx.compact).await
}
WatchCommands::Update {
key,
@@ -1329,20 +1561,22 @@ async fn main() {
.await
}
WatchCommands::Trigger { key } => {
- commands::watch::trigger(
- &client,
- &key,
- ctx.output_format,
- ctx.compact,
- )
- .await
+ commands::watch::trigger(&client, &key, ctx.output_format, ctx.compact)
+ .await
}
}
}
},
- Commands::Status => {
+ Commands::Status { verbose } => {
let client = ctx.get_client();
- commands::observer::system(&client, ctx.output_format, ctx.compact).await
+ commands::system::diagnostic_status(
+ &client,
+ &ctx.config,
+ ctx.output_format,
+ ctx.compact,
+ verbose,
+ )
+ .await
}
Commands::Health => handlers::handle_health(ctx).await,
Commands::System { action } => handlers::handle_system(action, ctx).await,
@@ -1405,15 +1639,24 @@ async fn main() {
cmd.run().await
}
Commands::Config { action } => handlers::handle_config(action, ctx).await,
+ Commands::Language { .. } => unreachable!("language command is handled before config load"),
Commands::Version => {
- println!("CLI: {}", env!("OPENVIKING_CLI_VERSION"));
+ println!(
+ "{} {}",
+ theme::muted("CLI:"),
+ theme::version(env!("OPENVIKING_CLI_VERSION")).bold()
+ );
// Try to get server version from /health endpoint with a short timeout (3 seconds)
let client = ctx.get_client_with_timeout(Some(3.0));
match client.get::<serde_json::Value>("/health", &[]).await {
Ok(health) => {
if let Some(version) = health.get("version").and_then(|v| v.as_str()) {
- println!("Server: {}", version);
+ println!(
+ "{} {}",
+ theme::muted("Server:"),
+ theme::sky_value(version).bold()
+ );
}
}
Err(_) => {
@@ -1456,7 +1699,10 @@ async fn main() {
after,
before,
level,
- } => handlers::handle_find(query, uri, node_limit, threshold, after, before, level, ctx).await,
+ } => {
+ handlers::handle_find(query, uri, node_limit, threshold, after, before, level, ctx)
+ .await
+ }
Commands::Search {
query,
uri,
@@ -1500,7 +1746,10 @@ async fn main() {
};
if let Err(e) = result {
- eprintln!("Error: {}", e);
+ if !matches!(e, Error::AlreadyReported) {
+ let report = error_ui::report_for_runtime_error(&command_display, &e);
+ error_ui::print_report(&report, verbose_errors);
+ }
std::process::exit(1);
}
}
@@ -1508,15 +1757,21 @@ async fn main() {
#[cfg(test)]
mod tests {
use super::{
- Cli, CliContext, Commands, PrivacyCommands, UploadCliOptions, legacy_upload_option_error,
+ 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,
};
- use crate::config::Config;
+ use crate::config::{Config, DEFAULT_SELF_MANAGED_URL};
use crate::handlers;
use crate::output::OutputFormat;
use clap::{CommandFactory, Parser};
use std::ffi::OsString;
+ fn os_args(args: &[&str]) -> Vec<OsString> {
+ args.iter().map(OsString::from).collect()
+ }
+
#[test]
fn cli_parses_global_identity_override_flags() {
let cli = Cli::try_parse_from([
@@ -1546,9 +1801,8 @@ mod tests {
}
#[test]
- fn setup_switch_and_version_do_not_require_existing_cli_config() {
- let setup = Cli::try_parse_from(["ov", "config", "setup-cli"])
- .expect("config setup-cli should parse");
+ fn bare_config_switch_and_version_do_not_require_existing_cli_config() {
+ let setup = Cli::try_parse_from(["ov", "config"]).expect("bare config should parse");
let switch =
Cli::try_parse_from(["ov", "config", "switch"]).expect("config switch should parse");
let version = Cli::try_parse_from(["ov", "version"]).expect("version should parse");
@@ -1596,18 +1850,30 @@ mod tests {
}
#[test]
- fn cli_tree_rejects_upload_and_admin_only_flags_after_subcommand() {
+ fn cli_tree_rejects_upload_flags_after_subcommand() {
assert!(Cli::try_parse_from(["ov", "tree", "viking://", "--progress"]).is_err());
assert!(Cli::try_parse_from(["ov", "tree", "viking://", "--no-progress"]).is_err());
assert!(Cli::try_parse_from(["ov", "tree", "viking://", "--verbose"]).is_err());
- assert!(Cli::try_parse_from(["ov", "tree", "viking://", "--sudo"]).is_err());
+ }
+
+ #[test]
+ fn cli_parses_sudo_as_hidden_global_flag_after_subcommand() {
+ let cli = Cli::try_parse_from(["ov", "tree", "viking://", "--sudo"])
+ .expect("sudo should parse anywhere so runtime can show a precise command error");
+
+ assert!(cli.sudo);
}
#[test]
fn cli_parses_upload_flags_on_upload_commands() {
- let add_resource =
- Cli::try_parse_from(["ov", "add-resource", "./README.md", "--progress", "--verbose"])
- .expect("add-resource upload flags should parse");
+ let add_resource = Cli::try_parse_from([
+ "ov",
+ "add-resource",
+ "./README.md",
+ "--progress",
+ "--verbose",
+ ])
+ .expect("add-resource upload flags should parse");
match add_resource.command {
Commands::AddResource { upload_options, .. } => {
assert!(upload_options.progress);
@@ -1653,9 +1919,8 @@ mod tests {
.expect("hidden legacy flag still parses before runtime validation");
assert!(legacy_upload_option_error(upload_options, &tree.command).is_some());
- let add_resource =
- Cli::try_parse_from(["ov", "--progress", "add-resource", "./README.md"])
- .expect("legacy pre-command upload flags should parse for add-resource");
+ let add_resource = Cli::try_parse_from(["ov", "--progress", "add-resource", "./README.md"])
+ .expect("legacy pre-command upload flags should parse for add-resource");
assert!(legacy_upload_option_error(upload_options, &add_resource.command).is_none());
}
@@ -1667,10 +1932,143 @@ mod tests {
assert!(cli.sudo);
}
+ #[test]
+ fn cli_parses_sudo_after_admin_command() {
+ let cli = Cli::try_parse_from(["ov", "admin", "list-accounts", "--sudo"])
+ .expect("post-command sudo should parse");
+
+ assert!(cli.sudo);
+ }
+
+ #[test]
+ fn cli_config_without_subcommand_parses_as_setup_entrypoint() {
+ Cli::try_parse_from(["ov", "config"]).expect("bare config command should parse");
+ }
+
+ #[test]
+ fn cli_config_single_purpose_subcommands_still_parse() {
+ for subcommand in ["show", "validate", "switch"] {
+ Cli::try_parse_from(["ov", "config", subcommand])
+ .unwrap_or_else(|_| panic!("config {subcommand} should parse"));
+ }
+ }
+
+ #[test]
+ fn cli_config_rejects_removed_setup_cli_subcommand() {
+ assert!(Cli::try_parse_from(["ov", "config", "setup-cli"]).is_err());
+ }
+
+ #[test]
+ fn cli_language_command_and_alias_parse() {
+ let cli = Cli::try_parse_from(["ov", "language", "zh-CN"])
+ .expect("language command should parse");
+ match cli.command {
+ Commands::Language { language } => assert_eq!(language.as_deref(), Some("zh-CN")),
+ _ => panic!("expected language command"),
+ }
+
+ let cli = Cli::try_parse_from(["ov", "lang"]).expect("language alias should parse");
+ match cli.command {
+ Commands::Language { language } => assert!(language.is_none()),
+ _ => panic!("expected language command"),
+ }
+ }
+
+ #[test]
+ fn language_gate_detects_language_command_after_global_flags() {
+ assert!(is_language_command_request(&os_args(&["ov", "language"])));
+ assert!(is_language_command_request(&os_args(&[
+ "ov", "lang", "zh-CN"
+ ])));
+ assert!(is_language_command_request(&os_args(&[
+ "ov", "--output", "json", "language", "en",
+ ])));
+ assert!(is_language_command_request(&os_args(&[
+ "ov",
+ "--output=json",
+ "--compact",
+ "false",
+ "lang",
+ ])));
+ assert!(is_language_command_request(&os_args(&[
+ "ov",
+ "--compact",
+ "lang",
+ ])));
+ assert!(!is_language_command_request(&os_args(&["ov", "status"])));
+ assert!(!is_language_command_request(&os_args(&["ov", "--help"])));
+ }
+
+ #[test]
+ fn language_gate_action_continues_prompts_or_exits() {
+ assert_eq!(
+ language_gate_action(&os_args(&["ov", "status"]), true, false),
+ LanguageGateAction::Continue
+ );
+ assert_eq!(
+ language_gate_action(&os_args(&["ov", "language"]), false, false),
+ LanguageGateAction::Continue
+ );
+ assert_eq!(
+ language_gate_action(&os_args(&["ov", "status"]), false, true),
+ LanguageGateAction::Prompt
+ );
+ assert_eq!(
+ language_gate_action(&os_args(&["ov", "status"]), false, false),
+ LanguageGateAction::ExitNonInteractive
+ );
+ }
+
+ #[test]
+ fn language_gate_message_points_to_explicit_language_commands() {
+ let message = language_required_message();
+
+ assert!(message.contains("ov language en"));
+ assert!(message.contains("ov language zh-CN"));
+ }
+
+ #[test]
+ fn language_command_without_value_requires_interactive_picker() {
+ assert!(language_command_can_run_picker(true, false));
+ assert!(language_command_can_run_picker(false, true));
+ assert!(!language_command_can_run_picker(false, false));
+ }
+
+ #[test]
+ fn first_command_token_skips_global_flags() {
+ assert_eq!(
+ first_command_token(&os_args(&[
+ "ov",
+ "--output",
+ "json",
+ "--account=acme",
+ "--sudo",
+ "admin",
+ ]))
+ .as_deref(),
+ Some("admin")
+ );
+ assert_eq!(
+ first_command_token(&os_args(&["ov", "--help"])).as_deref(),
+ None
+ );
+ }
+
+ #[test]
+ fn cli_status_parses_verbose_flag() {
+ let cli =
+ Cli::try_parse_from(["ov", "status", "--verbose"]).expect("status verbose parses");
+
+ match cli.command {
+ Commands::Status { verbose } => assert!(verbose),
+ _ => panic!("expected status command"),
+ }
+ }
+
#[test]
fn cli_context_overrides_identity_from_cli_flags() {
let config = Config {
- url: "http://localhost:1933".to_string(),
+ url: DEFAULT_SELF_MANAGED_URL.to_string(),
api_key: Some("test-key".to_string()),
root_api_key: None,
account: Some("from-config-account".to_string()),
@@ -1707,7 +2105,7 @@ mod tests {
#[test]
fn cli_context_uses_root_api_key_with_sudo() {
let config = Config {
- url: "http://localhost:1933".to_string(),
+ url: DEFAULT_SELF_MANAGED_URL.to_string(),
api_key: Some("user-key".to_string()),
root_api_key: Some("root-key".to_string()),
account: None,
diff --git a/crates/ov_cli/src/output.rs b/crates/ov_cli/src/output.rs
index 31e7339b6..5de93e958 100644
--- a/crates/ov_cli/src/output.rs
+++ b/crates/ov_cli/src/output.rs
@@ -2,6 +2,9 @@ use serde::Serialize;
use serde_json::{json, Value};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
+use crate::theme;
+use colored::Colorize;
+
const MAX_COL_WIDTH: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq)]
@@ -71,7 +74,12 @@ pub fn output_error(code: &str, message: &str, format: OutputFormat, compact: bo
})
);
} else {
- eprintln!("ERROR[{}]: {}", code, message);
+ eprintln!(
+ "{}[{}]: {}",
+ theme::error("ERROR").bold(),
+ theme::error(code),
+ theme::body(message)
+ );
}
}
@@ -94,7 +102,7 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
// Handle string result
if let Some(s) = value.as_str() {
- println!("{}", s);
+ println!("{}", theme::body(s));
return;
}
@@ -106,7 +114,7 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
return;
}
} else {
- println!("(empty)");
+ println!("{}", theme::muted("(empty)"));
return;
}
}
@@ -138,7 +146,7 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
let status = obj["status"].as_str().unwrap_or("");
println!(
"{}",
- append_profile_section(format!("[{}] ({})\n{}", name, health, status), obj)
+ append_profile_section(render_component_status(name, health, status), obj)
);
return;
}
@@ -161,13 +169,21 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
} else {
"unhealthy"
};
- lines.push(format!("[system] ({})", health));
+ lines.push(format!(
+ "{} {}",
+ theme::heading("[system]").bold(),
+ style_health_label(health)
+ ));
if let Some(errors) = obj.get("errors") {
if let Some(err_list) = errors.as_array() {
let error_strs: Vec<&str> =
err_list.iter().filter_map(|e| e.as_str()).collect();
if !error_strs.is_empty() {
- lines.push(format!("Errors: {}", error_strs.join(", ")));
+ lines.push(format!(
+ "{} {}",
+ theme::error("Errors:").bold(),
+ theme::body(error_strs.join(", "))
+ ));
}
}
}
@@ -281,7 +297,11 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
let formatted_value = format_value(v);
let (content, _) = truncate_string(&formatted_value, is_uri, MAX_COL_WIDTH);
let padded_key = pad_cell(k, max_key_width, false);
- output.push_str(&format!("{} {}\n", padded_key, content));
+ output.push_str(&format!(
+ "{} {}\n",
+ theme::muted(padded_key),
+ style_table_value(&content, is_uri)
+ ));
}
println!("{}", append_profile_section(output, obj));
return;
@@ -400,7 +420,7 @@ fn value_to_table(value: &serde_json::Value, compact: bool) -> Option<String> {
};
let name = obj["name"].as_str().unwrap_or("");
let status = obj["status"].as_str().unwrap_or("");
- return Some(format!("[{}] ({})\n{}", name, health, status));
+ return Some(render_component_status(name, health, status));
}
// Extract list fields
@@ -719,8 +739,8 @@ fn summarize_message_content(parts: Option<&Vec<serde_json::Value>>) -> String {
}
struct ColumnInfo {
- max_width: usize, // Max width for alignment (capped at 120)
- is_numeric: bool, // True if all values in column are numeric
+ max_width: usize, // Max width for alignment (capped at 120)
+ is_numeric: bool, // True if all values in column are numeric
is_unbounded_column: bool, // True if column should respect server-side length
}
@@ -735,7 +755,7 @@ fn format_array_to_table(items: &Vec<serde_json::Value>, compact: bool) -> Optio
let mut output = String::new();
for item in items {
let (content, _) = truncate_string(&format_value(item), false, MAX_COL_WIDTH);
- output.push_str(&format!("{}\n", content));
+ output.push_str(&format!("{}\n", theme::body(content)));
}
return Some(output);
}
@@ -823,7 +843,11 @@ fn format_array_to_table(items: &Vec<serde_json::Value>, compact: bool) -> Optio
let header_cells: Vec<String> = keys
.iter()
.enumerate()
- .map(|(i, k)| pad_cell(k, column_info[i].max_width, false))
+ .map(|(i, k)| {
+ theme::heading(pad_cell(k, column_info[i].max_width, false))
+ .bold()
+ .to_string()
+ })
.collect();
output.push_str(&header_cells.join(" "));
output.push('\n');
@@ -841,13 +865,15 @@ fn format_array_to_table(items: &Vec<serde_json::Value>, compact: bool) -> Optio
let (content, skip_padding) =
truncate_string(&value, info.is_unbounded_column, info.max_width);
- if skip_padding {
+ let padded = if skip_padding {
// Long URI, output as-is without padding
content
} else {
// Normal cell, apply padding and alignment
pad_cell(&content, info.max_width, info.is_numeric)
- }
+ };
+
+ style_table_value(&padded, info.is_unbounded_column).to_string()
})
.collect();
@@ -859,6 +885,42 @@ fn format_array_to_table(items: &Vec<serde_json::Value>, compact: bool) -> Optio
Some(output)
}
+fn render_component_status(name: &str, health: &str, status: &str) -> String {
+ format!(
+ "{} {}\n{}",
+ theme::heading(format!("[{name}]")).bold(),
+ style_health_label(health),
+ theme::body(status)
+ )
+}
+
+fn style_health_label(value: &str) -> String {
+ let styled = match value.to_ascii_lowercase().as_str() {
+ "healthy" | "ok" | "true" => theme::success(value).bold(),
+ "unhealthy" | "error" | "false" => theme::error(value).bold(),
+ _ => theme::warning(value).bold(),
+ };
+ format!("({styled})")
+}
+
+fn style_table_value(value: &str, is_uri: bool) -> String {
+ let trimmed = value.trim();
+ if is_uri
+ || trimmed.starts_with("http://")
+ || trimmed.starts_with("https://")
+ || trimmed.starts_with("~/")
+ {
+ return theme::sky_value(value).bold().to_string();
+ }
+
+ 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(),
+ }
+}
+
fn format_value(v: &serde_json::Value) -> String {
match v {
serde_json::Value::String(s) => s.clone(),
@@ -981,7 +1043,7 @@ mod tests {
]
});
- let rendered = value_to_table_with_profile(&value, true);
+ let rendered = value_to_table_with_profile(&value, true).map(|value| strip_ansi(&value));
assert_eq!(
rendered,
@@ -1001,6 +1063,26 @@ mod tests {
);
}
+ 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.is_ascii_alphabetic() {
+ break;
+ }
+ }
+ continue;
+ }
+ output.push(ch);
+ }
+
+ output
+ }
+
#[test]
fn test_compact_json_lifts_profile_next_to_result_for_list_payloads() {
let value = json!({
diff --git a/crates/ov_cli/src/status_ui.rs b/crates/ov_cli/src/status_ui.rs
new file mode 100644
index 000000000..78f26ecef
--- /dev/null
+++ b/crates/ov_cli/src/status_ui.rs
@@ -0,0 +1,822 @@
+use colored::Colorize;
+use serde_json::Value;
+use unicode_width::UnicodeWidthStr;
+
+use crate::{
+ config::{Config, display_config_home},
+ config_wizard::{ConfigKind, ConfigStore},
+ error::Result,
+ i18n::{Language, copy},
+ theme,
+};
+
+const LABEL_WIDTH: usize = 14;
+const ACTION_WIDTH: usize = 26;
+const COMPONENT_WIDTH: usize = 15;
+const HEALTH_WIDTH: usize = 11;
+
+#[derive(Debug, Clone, Default)]
+pub(crate) struct StatusConfigMeta {
+ pub active_name: Option<String>,
+ pub saved_count: usize,
+}
+
+#[derive(Debug, Clone, Default)]
+struct QueueSummary {
+ pending: Option<u64>,
+ in_progress: Option<u64>,
+ errors: Option<u64>,
+}
+
+pub(crate) fn current_config_meta() -> StatusConfigMeta {
+ let Ok(store) = ConfigStore::new() else {
+ return StatusConfigMeta::default();
+ };
+ let Ok(configs) = store.list_configs() else {
+ return StatusConfigMeta::default();
+ };
+
+ StatusConfigMeta {
+ active_name: configs
+ .iter()
+ .find(|config| config.is_active)
+ .map(|config| config.name.clone()),
+ saved_count: configs.len(),
+ }
+}
+
+pub(crate) fn render_status(
+ payload: &Value,
+ config: &Config,
+ active_name: Option<&str>,
+) -> Result<String> {
+ render_status_with_language(payload, config, active_name, Language::current())
+}
+
+pub(crate) fn render_status_with_language(
+ payload: &Value,
+ config: &Config,
+ active_name: Option<&str>,
+ language: Language,
+) -> Result<String> {
+ let kind = kind_label(ConfigKind::from_config(config), language);
+ let active = active_name.unwrap_or_else(|| unknown(language));
+ let queue = queue_summary(component_status(payload, "queue"));
+ let models = models_summary(component_status(payload, "models"));
+
+ let mut lines = Vec::new();
+ lines.push(status_title(language));
+ lines.push(String::new());
+ lines.push(section_title(copy(language, "Config", "配置")));
+ lines.push(detail_line_styled(
+ copy(language, "Active", "当前配置"),
+ active_config_value(active, kind),
+ ));
+ lines.push(detail_line_styled(
+ copy(language, "Server", "服务器"),
+ path_value(&config.url),
+ ));
+ lines.push(detail_line_styled(
+ copy(language, "Config home", "配置目录"),
+ path_value(&display_config_home()),
+ ));
+ lines.push(String::new());
+ lines.push(section_title(copy(language, "System", "系统")));
+ lines.push(detail_line_styled(
+ copy(language, "Status", "状态"),
+ if system_is_healthy(payload) {
+ status_value(copy(language, "Connected (Healthy)", "已连接(健康)"))
+ } else {
+ unhealthy_value(copy(language, "Connected (Unhealthy)", "已连接(不健康)"))
+ },
+ ));
+ lines.push(detail_line_styled(
+ copy(language, "Pending", "待处理"),
+ activity_count_value(queue.pending),
+ ));
+ lines.push(detail_line_styled(
+ copy(language, "In progress", "处理中"),
+ activity_count_value(queue.in_progress),
+ ));
+ lines.push(detail_line_styled(
+ copy(language, "Errors", "错误"),
+ error_count_value(queue.errors),
+ ));
+ lines.push(String::new());
+ lines.push(section_title(copy(language, "Models", "模型")));
+ lines.push(detail_line_styled(
+ "VLM",
+ model_value(models.vlm.as_deref().unwrap_or_else(|| unknown(language))),
+ ));
+ lines.push(detail_line_styled(
+ copy(language, "Embedding", "Embedding"),
+ model_value(
+ models
+ .embedding
+ .as_deref()
+ .unwrap_or_else(|| unknown(language)),
+ ),
+ ));
+ lines.push(String::new());
+ lines.push(section_title(copy(language, "Components", "组件")));
+ lines.push(component_header_line(language));
+ for component in [
+ "queue",
+ "vikingdb",
+ "models",
+ "lock",
+ "retrieval",
+ "filesystem",
+ ] {
+ lines.push(component_line(
+ component, payload, &queue, &models, language,
+ ));
+ }
+ lines.push(String::new());
+ lines.push(section_title(copy(language, "Details", "详情")));
+ lines.push(action_line(
+ "ov status --verbose",
+ copy(language, "Show full component tables", "显示完整组件表"),
+ ));
+ lines.push(action_line(
+ "ov observer queue",
+ copy(language, "Inspect queue details", "查看队列详情"),
+ ));
+ lines.push(action_line(
+ "ov observer models",
+ copy(language, "Inspect model usage", "查看模型使用情况"),
+ ));
+
+ Ok(format!("{}\n", lines.join("\n")))
+}
+
+pub(crate) fn render_unreachable_status(
+ config: &Config,
+ active_name: Option<&str>,
+ saved_count: usize,
+) -> String {
+ let language = Language::current();
+ let kind = kind_label(ConfigKind::from_config(config), language);
+ let active = active_name.unwrap_or_else(|| unknown(language));
+ let mut lines = Vec::new();
+
+ lines.push(status_title(language));
+ lines.push(String::new());
+ lines.push(section_title(copy(language, "Config", "配置")));
+ lines.push(detail_line_styled(
+ copy(language, "Active", "当前配置"),
+ active_config_value(active, kind),
+ ));
+ lines.push(detail_line_styled(
+ copy(language, "Server", "服务器"),
+ path_value(&config.url),
+ ));
+ lines.push(detail_line_styled(
+ copy(language, "Config home", "配置目录"),
+ path_value(&display_config_home()),
+ ));
+ lines.push(String::new());
+ lines.push(section_title(copy(language, "System", "系统")));
+ lines.push(detail_line_styled(
+ copy(language, "Status", "状态"),
+ error_value(copy(language, "Unreachable", "无法连接")),
+ ));
+ lines.push(detail_line_styled(
+ copy(language, "Saved configs", "已保存配置"),
+ plain_value(&saved_count.to_string()),
+ ));
+ 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", "快速健康检查"),
+ ));
+
+ format!("{}\n", lines.join("\n"))
+}
+
+fn status_title(language: Language) -> String {
+ theme::brand_title(copy(language, "OPENVIKING STATUS", "OPENVIKING 状态"))
+ .bold()
+ .to_string()
+}
+
+fn unknown(language: Language) -> &'static str {
+ copy(language, "unknown", "未知")
+}
+
+fn kind_label(kind: ConfigKind, language: Language) -> &'static str {
+ match language {
+ Language::En => kind.label(),
+ Language::ZhCn => match kind {
+ ConfigKind::VolcengineCloud => "火山引擎云",
+ ConfigKind::SelfManaged => "自托管",
+ },
+ }
+}
+
+fn section_title(title: &str) -> String {
+ theme::heading(title).bold().to_string()
+}
+
+fn detail_line_styled(label: &str, value: String) -> String {
+ let label = theme::muted(pad_to_display_width(label, LABEL_WIDTH));
+ format!(" {label}{value}")
+}
+
+fn action_line(command: &str, description: &str) -> String {
+ let command = theme::command(pad_to_display_width(command, ACTION_WIDTH)).bold();
+ format!(" {command}{}", theme::muted(description))
+}
+
+fn active_config_value(name: &str, kind: &str) -> String {
+ format!(
+ "{} {}",
+ theme::config_name(name).bold(),
+ theme::strong(format!("({kind})"))
+ )
+}
+
+fn path_value(value: &str) -> String {
+ if value == "unknown" || value == "未知" {
+ unknown_value(value)
+ } else {
+ theme::value(value).to_string()
+ }
+}
+
+fn model_value(value: &str) -> String {
+ if value == "unknown" || value == "未知" {
+ unknown_value(value)
+ } else {
+ theme::value(value).bold().to_string()
+ }
+}
+
+fn status_value(value: &str) -> String {
+ theme::success(value).bold().to_string()
+}
+
+fn unhealthy_value(value: &str) -> String {
+ theme::warning(value).bold().to_string()
+}
+
+fn error_value(value: &str) -> String {
+ theme::error(value).bold().to_string()
+}
+
+fn plain_value(value: &str) -> String {
+ theme::body(value).to_string()
+}
+
+fn unknown_value(value: &str) -> String {
+ theme::muted(value).to_string()
+}
+
+fn activity_count_value(value: Option<u64>) -> String {
+ match value {
+ Some(0) => theme::body("0").to_string(),
+ Some(value) => theme::warning(value.to_string()).bold().to_string(),
+ None => unknown_value("unknown"),
+ }
+}
+
+fn error_count_value(value: Option<u64>) -> String {
+ match value {
+ Some(0) => theme::success("0").to_string(),
+ Some(value) => error_value(&value.to_string()),
+ None => unknown_value("unknown"),
+ }
+}
+
+fn component_header_line(language: Language) -> String {
+ let component = theme::muted(pad_to_display_width(
+ copy(language, "Component", "组件"),
+ COMPONENT_WIDTH,
+ ))
+ .bold();
+ let health = theme::muted(pad_to_display_width(
+ copy(language, "Health", "健康"),
+ HEALTH_WIDTH,
+ ))
+ .bold();
+ format!(
+ " {component}{health}{}",
+ theme::muted(copy(language, "Summary", "摘要")).bold()
+ )
+}
+
+fn component_line(
+ component: &str,
+ payload: &Value,
+ queue: &QueueSummary,
+ models: &ModelSummary,
+ language: Language,
+) -> String {
+ let health = component_health(payload, component);
+ let summary = match component {
+ "queue" => queue_component_summary(queue),
+ "vikingdb" => vikingdb_summary(component_status(payload, component)),
+ "models" => models_component_summary(models),
+ "lock" => lock_summary(component_status(payload, component)),
+ "retrieval" => retrieval_summary(component_status(payload, component)),
+ "filesystem" => filesystem_summary(component_status(payload, component)),
+ _ => "unknown".to_string(),
+ };
+
+ let component = theme::command(pad_to_display_width(component, COMPONENT_WIDTH)).bold();
+ let health = styled_health_cell(health, language);
+ let summary = summary_value(&summary);
+ format!(" {component}{health}{summary}")
+}
+
+fn styled_health_cell(health: &str, language: Language) -> String {
+ let translated = match health {
+ "healthy" => copy(language, "healthy", "健康"),
+ "unhealthy" => copy(language, "unhealthy", "异常"),
+ _ => unknown(language),
+ };
+ let cell = pad_to_display_width(translated, HEALTH_WIDTH);
+ match health {
+ "healthy" => theme::success(cell).bold().to_string(),
+ "unhealthy" => theme::warning(cell).bold().to_string(),
+ _ => theme::muted(cell).to_string(),
+ }
+}
+
+fn summary_value(summary: &str) -> String {
+ if summary == "unknown" {
+ unknown_value(summary)
+ } else {
+ theme::body(summary).to_string()
+ }
+}
+
+fn pad_to_display_width(value: &str, width: usize) -> String {
+ format!(
+ "{}{}",
+ value,
+ " ".repeat(width.saturating_sub(UnicodeWidthStr::width(value)))
+ )
+}
+
+fn component_status<'a>(payload: &'a Value, component: &str) -> Option<&'a str> {
+ payload
+ .pointer(&format!("/components/{component}/status"))
+ .and_then(Value::as_str)
+}
+
+fn component_health(payload: &Value, component: &str) -> &'static str {
+ match payload
+ .pointer(&format!("/components/{component}/is_healthy"))
+ .and_then(Value::as_bool)
+ {
+ Some(true) => "healthy",
+ Some(false) => "unhealthy",
+ None => "unknown",
+ }
+}
+
+fn system_is_healthy(payload: &Value) -> bool {
+ if let Some(healthy) = payload
+ .get("is_healthy")
+ .or_else(|| payload.get("healthy"))
+ .and_then(Value::as_bool)
+ {
+ return healthy;
+ }
+
+ let Some(components) = payload.get("components").and_then(Value::as_object) else {
+ return false;
+ };
+ !components.is_empty()
+ && components
+ .values()
+ .all(|component| component.get("is_healthy").and_then(Value::as_bool) != Some(false))
+}
+
+fn queue_summary(status: Option<&str>) -> QueueSummary {
+ let Some(status) = status else {
+ return QueueSummary::default();
+ };
+ let rows = pipe_rows(status);
+ let Some(header) = rows
+ .iter()
+ .find(|row| row.iter().any(|cell| cell == "Pending"))
+ else {
+ return QueueSummary::default();
+ };
+ let Some(total) = rows.iter().find(|row| {
+ row.first()
+ .is_some_and(|cell| cell.eq_ignore_ascii_case("TOTAL"))
+ }) else {
+ return QueueSummary::default();
+ };
+
+ QueueSummary {
+ pending: cell_by_header(header, total, "Pending").and_then(parse_u64),
+ in_progress: cell_by_header(header, total, "In Progress").and_then(parse_u64),
+ errors: cell_by_header(header, total, "Errors").and_then(parse_u64),
+ }
+}
+
+fn queue_component_summary(queue: &QueueSummary) -> String {
+ match (queue.pending, queue.in_progress, queue.errors) {
+ (Some(pending), Some(in_progress), Some(errors)) => {
+ format!("{pending} pending, {in_progress} running, {errors} errors")
+ }
+ _ => "unknown".to_string(),
+ }
+}
+
+#[derive(Debug, Clone, Default)]
+struct ModelSummary {
+ vlm: Option<String>,
+ embedding: Option<String>,
+}
+
+fn models_summary(status: Option<&str>) -> ModelSummary {
+ let Some(status) = status else {
+ return ModelSummary::default();
+ };
+ ModelSummary {
+ vlm: first_model_after_heading(status, "VLM Models:"),
+ embedding: first_model_after_heading(status, "Embedding Models:"),
+ }
+}
+
+fn models_component_summary(models: &ModelSummary) -> String {
+ match (models.vlm.is_some(), models.embedding.is_some()) {
+ (true, true) => "VLM + embedding available".to_string(),
+ (true, false) => "VLM available".to_string(),
+ (false, true) => "embedding available".to_string(),
+ (false, false) => "unknown".to_string(),
+ }
+}
+
+fn first_model_after_heading(status: &str, heading: &str) -> Option<String> {
+ let (_, section) = status.split_once(heading)?;
+ pipe_rows(section).into_iter().find_map(|row| {
+ let first = row.first()?.trim();
+ if first.is_empty()
+ || first == "Model"
+ || first.eq_ignore_ascii_case("provider")
+ || first.contains("----")
+ {
+ return None;
+ }
+ Some(first.to_string())
+ })
+}
+
+fn vikingdb_summary(status: Option<&str>) -> String {
+ let Some(status) = status else {
+ return "unknown".to_string();
+ };
+ let rows = pipe_rows(status);
+ let Some(header) = rows
+ .iter()
+ .find(|row| row.iter().any(|cell| cell == "Vector Count"))
+ else {
+ return "unknown".to_string();
+ };
+ let Some(total) = rows.iter().find(|row| {
+ row.first()
+ .is_some_and(|cell| cell.eq_ignore_ascii_case("TOTAL"))
+ }) else {
+ return "unknown".to_string();
+ };
+
+ let collections = cell_by_header(header, total, "Index Count").and_then(parse_u64);
+ let vectors = cell_by_header(header, total, "Vector Count").and_then(parse_u64);
+ match (collections, vectors) {
+ (Some(collections), Some(vectors)) => format!(
+ "{} {}, {} vectors",
+ collections,
+ pluralize(collections, "collection"),
+ vectors
+ ),
+ _ => "unknown".to_string(),
+ }
+}
+
+fn lock_summary(status: Option<&str>) -> String {
+ let Some(status) = status else {
+ return "unknown".to_string();
+ };
+ if status.contains("No active locks") {
+ return "0 active locks".to_string();
+ }
+ let Some(total_row) = pipe_rows(status).into_iter().find(|row| {
+ row.first()
+ .is_some_and(|cell| cell.to_ascii_uppercase().starts_with("TOTAL"))
+ }) else {
+ return "unknown".to_string();
+ };
+ let count = total_row
+ .first()
+ .and_then(|cell| cell.split_once('('))
+ .and_then(|(_, rest)| rest.split_once(')'))
+ .and_then(|(count, _)| parse_u64(count));
+ match count {
+ Some(count) => format!("{} active {}", count, pluralize(count, "lock")),
+ None => "unknown".to_string(),
+ }
+}
+
+fn retrieval_summary(status: Option<&str>) -> String {
+ let Some(status) = status else {
+ return "unknown".to_string();
+ };
+ let queries = metric_value(status, "Total Queries");
+ let zero_rate = metric_value(status, "Zero-Result Rate");
+ match (queries, zero_rate) {
+ (Some(queries), Some(zero_rate)) => {
+ format!("{queries} queries, {zero_rate} zero-result rate")
+ }
+ _ => "unknown".to_string(),
+ }
+}
+
+fn filesystem_summary(status: Option<&str>) -> String {
+ let Some(status) = status else {
+ return "unknown".to_string();
+ };
+ let mounts = status
+ .lines()
+ .filter(|line| line.starts_with("Mount: "))
+ .count();
+ let total_ops: u64 = pipe_rows(status)
+ .into_iter()
+ .filter(|row| row.first().is_some_and(|cell| cell == "Total Operations"))
+ .filter_map(|row| row.get(1).and_then(|cell| parse_u64(cell)))
+ .sum();
+
+ match (mounts, total_ops) {
+ (0, 0) => "unknown".to_string(),
+ (mounts, 0) => format!("{} {}", mounts, pluralize(mounts as u64, "mount")),
+ (0, total_ops) => format!("{} ops", compact_number(total_ops)),
+ (mounts, total_ops) => format!(
+ "{} {}, {} ops",
+ mounts,
+ pluralize(mounts as u64, "mount"),
+ compact_number(total_ops)
+ ),
+ }
+}
+
+fn metric_value(status: &str, metric: &str) -> Option<String> {
+ pipe_rows(status).into_iter().find_map(|row| {
+ if row.first().is_some_and(|cell| cell == metric) {
+ row.get(1).cloned()
+ } else {
+ None
+ }
+ })
+}
+
+fn pipe_rows(status: &str) -> Vec<Vec<String>> {
+ status
+ .lines()
+ .filter_map(|line| {
+ let trimmed = line.trim();
+ if !trimmed.starts_with('|') {
+ return None;
+ }
+ let cells: Vec<String> = trimmed
+ .trim_matches('|')
+ .split('|')
+ .map(str::trim)
+ .filter(|cell| !cell.is_empty())
+ .map(ToString::to_string)
+ .collect();
+ if cells.is_empty() { None } else { Some(cells) }
+ })
+ .collect()
+}
+
+fn cell_by_header<'a>(header: &[String], row: &'a [String], name: &str) -> Option<&'a str> {
+ let index = header.iter().position(|cell| cell == name)?;
+ row.get(index).map(String::as_str)
+}
+
+fn parse_u64(value: &str) -> Option<u64> {
+ value
+ .chars()
+ .filter(|ch| ch.is_ascii_digit())
+ .collect::<String>()
+ .parse()
+ .ok()
+}
+
+fn pluralize(count: u64, singular: &str) -> String {
+ if count == 1 {
+ singular.to_string()
+ } else {
+ format!("{singular}s")
+ }
+}
+
+fn compact_number(value: u64) -> String {
+ if value >= 1_000_000 {
+ format!("{:.1}M", value as f64 / 1_000_000.0)
+ } else if value >= 1_000 {
+ format!("{:.1}K", value as f64 / 1_000.0)
+ } else {
+ value.to_string()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use crate::config::Config;
+
+ fn sample_config() -> Config {
+ Config {
+ url: "http://127.0.0.1:1933".to_string(),
+ ..Config::default()
+ }
+ }
+
+ fn sample_status_payload() -> serde_json::Value {
+ json!({
+ "is_healthy": true,
+ "components": {
+ "queue": {
+ "name": "queue",
+ "is_healthy": true,
+ "has_errors": false,
+ "status": "\
+ +----------------+---------+-------------+-----------+----------+--------+-------+\n\
+ | Queue | Pending | In Progress | Processed | Requeued | Errors | Total |\n\
+ +----------------+---------+-------------+-----------+----------+--------+-------+\n\
+ | Embedding | 64 | 9 | 3917 | 0 | 0 | 3990 |\n\
+ | Semantic | 0 | 0 | 16 | 0 | 0 | 16 |\n\
+ | TOTAL | 64 | 9 | 3933 | 0 | 0 | 4006 |\n\
+ +----------------+---------+-------------+-----------+----------+--------+-------+"
+ },
+ "vikingdb": {
+ "name": "vikingdb",
+ "is_healthy": true,
+ "has_errors": false,
+ "status": "\
+ +------------+-------------+--------------+--------+\n\
+ | Collection | Index Count | Vector Count | Status |\n\
+ +------------+-------------+--------------+--------+\n\
+ | context | 1 | 6877 | OK |\n\
+ | TOTAL | 1 | 6877 | |\n\
+ +------------+-------------+--------------+--------+"
+ },
+ "models": {
+ "name": "models",
+ "is_healthy": true,
+ "has_errors": false,
+ "status": "\nVLM Models:\n\
+ +----------------------------+------------+-------+\n\
+ | Model | Provider | Calls |\n\
+ +----------------------------+------------+-------+\n\
+ | doubao-seed-2-0-pro-260215 | volcengine | 1989 |\n\
+ +----------------------------+------------+-------+\n\
+ \nEmbedding Models:\n\
+ +--------------------------------+------------+-------+\n\
+ | Model | Provider | Calls |\n\
+ +--------------------------------+------------+-------+\n\
+ | doubao-embedding-vision-251215 | volcengine | 4038 |\n\
+ +--------------------------------+------------+-------+"
+ },
+ "lock": {
+ "name": "lock",
+ "is_healthy": true,
+ "has_errors": false,
+ "status": "\
+ +-------------+-------+----------+\n\
+ | Handle ID | Locks | Duration |\n\
+ +-------------+-------+----------+\n\
+ | b1b3c983... | 1 | 337.6s |\n\
+ | TOTAL (1) | 1 | |\n\
+ +-------------+-------+----------+"
+ },
+ "retrieval": {
+ "name": "retrieval",
+ "is_healthy": true,
+ "has_errors": false,
+ "status": "\
+ +---------------------+-----------------+\n\
+ | Metric | Value |\n\
+ +---------------------+-----------------+\n\
+ | Total Queries | 121 |\n\
+ | Zero-Result Rate | 28.9% |\n\
+ +---------------------+-----------------+"
+ },
+ "filesystem": {
+ "name": "filesystem",
+ "is_healthy": true,
+ "has_errors": false,
+ "status": "Mount: /local (plugin: localfs)\nMount: /queue (plugin: queuefs)\nMount: /serverinfo (plugin: serverinfofs)\nTotal Operations | 967891"
+ }
+ },
+ "errors": []
+ })
+ }
+
+ #[test]
+ fn healthy_payload_renders_selected_status_sections() {
+ let rendered = super::render_status(&sample_status_payload(), &sample_config(), None)
+ .expect("status should render");
+ let rendered = strip_ansi(&rendered);
+
+ assert!(rendered.contains("OPENVIKING STATUS"));
+ assert!(rendered.contains("Config"));
+ assert!(rendered.contains("Active unknown (Self-Managed)"));
+ assert!(rendered.contains("Server http://127.0.0.1:1933"));
+ assert!(rendered.contains("System"));
+ assert!(rendered.contains("Status Connected (Healthy)"));
+ assert!(rendered.contains("Pending 64"));
+ assert!(rendered.contains("In progress 9"));
+ assert!(rendered.contains("Errors 0"));
+ assert!(rendered.contains("Models"));
+ assert!(rendered.contains("VLM doubao-seed-2-0-pro-260215"));
+ assert!(rendered.contains("Embedding doubao-embedding-vision-251215"));
+ assert!(rendered.contains("Components"));
+ assert!(rendered.contains("queue healthy 64 pending, 9 running, 0 errors"));
+ assert!(rendered.contains("vikingdb healthy 1 collection, 6877 vectors"));
+ assert!(rendered.contains("Details"));
+ assert!(rendered.contains("ov status --verbose Show full component tables"));
+ }
+
+ #[test]
+ fn missing_component_text_renders_unknown_safely() {
+ let payload = json!({
+ "is_healthy": true,
+ "components": {
+ "queue": {
+ "name": "queue",
+ "is_healthy": true,
+ "has_errors": false,
+ "status": "not a table"
+ }
+ },
+ "errors": []
+ });
+
+ let rendered = super::render_status(&payload, &sample_config(), Some("local"))
+ .expect("status should render");
+ let rendered = strip_ansi(&rendered);
+
+ assert!(rendered.contains("Active local (Self-Managed)"));
+ assert!(rendered.contains("Pending unknown"));
+ assert!(rendered.contains("queue healthy unknown"));
+ assert!(rendered.contains("models unknown unknown"));
+ }
+
+ #[test]
+ fn default_status_uses_ansi_styling_without_changing_text() {
+ colored::control::set_override(true);
+ let rendered =
+ super::render_status(&sample_status_payload(), &sample_config(), Some("local"))
+ .expect("status should render");
+ colored::control::unset_override();
+
+ assert!(rendered.contains("\u{1b}["));
+
+ let plain = strip_ansi(&rendered);
+ assert!(plain.contains("OPENVIKING STATUS"));
+ assert!(plain.contains("Active local (Self-Managed)"));
+ assert!(plain.contains("queue healthy 64 pending, 9 running, 0 errors"));
+ assert!(plain.contains("ov status --verbose Show full component tables"));
+ }
+
+ 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.is_ascii_alphabetic() {
+ break;
+ }
+ }
+ continue;
+ }
+ output.push(ch);
+ }
+
+ output
+ }
+}
diff --git a/crates/ov_cli/src/theme.rs b/crates/ov_cli/src/theme.rs
new file mode 100644
index 000000000..4e8e4f874
--- /dev/null
+++ b/crates/ov_cli/src/theme.rs
@@ -0,0 +1,272 @@
+use colored::{ColoredString, Colorize};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct Rgb(pub(crate) u8, pub(crate) u8, pub(crate) u8);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum ThemeColor {
+ TrueColor(Rgb),
+}
+
+impl ThemeColor {
+ pub(crate) fn rgb_fallback(&self) -> Rgb {
+ match self {
+ ThemeColor::TrueColor(rgb) => *rgb,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct CliTheme {
+ pub(crate) wordmark_start: Rgb,
+ pub(crate) wordmark_mid: Rgb,
+ pub(crate) wordmark_end: Rgb,
+ pub(crate) logo_end: Rgb,
+ pub(crate) tagline_start: Rgb,
+ pub(crate) tagline_mid: Rgb,
+ pub(crate) tagline_end: Rgb,
+ pub(crate) border: ThemeColor,
+ pub(crate) version: ThemeColor,
+ pub(crate) brand_title: ThemeColor,
+ pub(crate) body: ThemeColor,
+ pub(crate) muted: ThemeColor,
+ pub(crate) command: ThemeColor,
+ pub(crate) heading: ThemeColor,
+ pub(crate) value: ThemeColor,
+ pub(crate) sky_value: ThemeColor,
+ pub(crate) success: ThemeColor,
+ pub(crate) warning: ThemeColor,
+ pub(crate) error: ThemeColor,
+ pub(crate) config_name: ThemeColor,
+ pub(crate) section_marker: ThemeColor,
+ pub(crate) prompt: ThemeColor,
+ pub(crate) selection: ThemeColor,
+}
+
+pub(crate) fn active_theme() -> CliTheme {
+ palette()
+}
+
+pub(crate) fn palette() -> CliTheme {
+ CliTheme {
+ wordmark_start: Rgb(22, 181, 166),
+ wordmark_mid: Rgb(0, 140, 132),
+ wordmark_end: Rgb(5, 86, 80),
+ logo_end: Rgb(5, 86, 80),
+ tagline_start: Rgb(0, 128, 128),
+ tagline_mid: Rgb(0, 112, 190),
+ tagline_end: Rgb(0, 128, 128),
+ border: ThemeColor::TrueColor(Rgb(0, 128, 128)),
+ version: ThemeColor::TrueColor(Rgb(0, 128, 128)),
+ brand_title: ThemeColor::TrueColor(Rgb(0, 128, 128)),
+ body: ThemeColor::TrueColor(Rgb(96, 111, 126)),
+ muted: ThemeColor::TrueColor(Rgb(104, 112, 120)),
+ command: ThemeColor::TrueColor(Rgb(0, 128, 128)),
+ heading: ThemeColor::TrueColor(Rgb(0, 128, 128)),
+ value: ThemeColor::TrueColor(Rgb(0, 112, 190)),
+ sky_value: ThemeColor::TrueColor(Rgb(0, 112, 190)),
+ success: ThemeColor::TrueColor(Rgb(0, 133, 90)),
+ warning: ThemeColor::TrueColor(Rgb(185, 90, 0)),
+ error: ThemeColor::TrueColor(Rgb(212, 60, 55)),
+ config_name: ThemeColor::TrueColor(Rgb(199, 80, 0)),
+ section_marker: ThemeColor::TrueColor(Rgb(139, 92, 246)),
+ prompt: ThemeColor::TrueColor(Rgb(150, 109, 27)),
+ selection: ThemeColor::TrueColor(Rgb(0, 133, 90)),
+ }
+}
+
+pub(crate) fn colorize(text: impl Into<String>, color: ThemeColor) -> ColoredString {
+ let text = text.into();
+ match color {
+ ThemeColor::TrueColor(Rgb(red, green, blue)) => text.truecolor(red, green, blue),
+ }
+}
+
+pub(crate) fn brand_title(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.brand_title)
+}
+
+pub(crate) fn border(text: impl Into<String>) -> ColoredString {
+ colorize(text, active_theme().border)
+}
+
+pub(crate) fn version(text: impl Into<String>) -> ColoredString {
+ colorize(text, active_theme().version)
+}
+
+pub(crate) fn command(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.command)
+}
+
+pub(crate) fn body(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.body)
+}
+
+pub(crate) fn muted(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.muted)
+}
+
+pub(crate) fn heading(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.heading)
+}
+
+pub(crate) fn value(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.value)
+}
+
+pub(crate) fn sky_value(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.sky_value)
+}
+
+pub(crate) fn success(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.success)
+}
+
+pub(crate) fn warning(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.warning)
+}
+
+pub(crate) fn error(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.error)
+}
+
+pub(crate) fn config_name(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.config_name)
+}
+
+pub(crate) fn section_marker(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.section_marker)
+}
+
+pub(crate) fn prompt(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.prompt)
+}
+
+pub(crate) fn selection(text: impl Into<String>) -> ColoredString {
+ let theme = active_theme();
+ colorize(text, theme.selection)
+}
+
+pub(crate) fn strong(text: impl Into<String>) -> ColoredString {
+ body(text).bold()
+}
+
+#[cfg(test)]
+fn relative_luminance(color: Rgb) -> f32 {
+ fn channel(value: u8) -> f32 {
+ let value = value as f32 / 255.0;
+ if value <= 0.03928 {
+ value / 12.92
+ } else {
+ ((value + 0.055) / 1.055).powf(2.4)
+ }
+ }
+ 0.2126 * channel(color.0) + 0.7152 * channel(color.1) + 0.0722 * channel(color.2)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{CliTheme, Rgb, ThemeColor, active_theme, palette, relative_luminance};
+
+ const PALE_PEARL: Rgb = Rgb(234, 253, 247);
+ const WHITE: Rgb = Rgb(255, 255, 255);
+ const BLACK: Rgb = Rgb(0, 0, 0);
+
+ #[test]
+ fn active_theme_uses_the_single_palette() {
+ assert_eq!(active_theme(), palette());
+ }
+
+ fn functional_colors(palette: CliTheme) -> [(&'static str, ThemeColor); 13] {
+ [
+ ("brand_title", palette.brand_title),
+ ("body", palette.body),
+ ("muted", palette.muted),
+ ("command", palette.command),
+ ("heading", palette.heading),
+ ("value", palette.value),
+ ("sky_value", palette.sky_value),
+ ("success", palette.success),
+ ("warning", palette.warning),
+ ("error", palette.error),
+ ("config_name", palette.config_name),
+ ("section_marker", palette.section_marker),
+ ("prompt", palette.prompt),
+ ]
+ }
+
+ fn contrast_ratio(foreground: Rgb, background: Rgb) -> f32 {
+ let foreground = relative_luminance(foreground);
+ let background = relative_luminance(background);
+ let (lighter, darker) = if foreground > background {
+ (foreground, background)
+ } else {
+ (background, foreground)
+ };
+ (lighter + 0.05) / (darker + 0.05)
+ }
+
+ fn assert_min_contrast(name: &str, color: ThemeColor, background: Rgb, minimum: f32) {
+ let ratio = contrast_ratio(color.rgb_fallback(), background);
+ assert!(
+ ratio >= minimum,
+ "{name} contrast {ratio:.2} is below {minimum:.2} against {background:?}"
+ );
+ }
+
+ #[test]
+ fn single_palette_uses_explicit_balanced_functional_colors() {
+ let palette = palette();
+ for (name, color) in functional_colors(palette) {
+ assert_ne!(
+ color.rgb_fallback(),
+ PALE_PEARL,
+ "{name} must not use pale Pearl"
+ );
+ assert_min_contrast(name, color, WHITE, 4.0);
+ assert_min_contrast(name, color, BLACK, 4.0);
+ }
+ }
+
+ #[test]
+ fn single_palette_separates_neutral_text_from_teal_structure() {
+ let palette = palette();
+
+ for (name, color) in [("body", palette.body), ("muted", palette.muted)] {
+ let Rgb(red, green, blue) = color.rgb_fallback();
+ assert!(
+ red >= 80,
+ "{name} should be a readable neutral, not another teal accent"
+ );
+ assert!(
+ green.abs_diff(blue) <= 35,
+ "{name} should stay neutral enough for descriptions"
+ );
+ }
+
+ let Rgb(command_red, command_green, _) = palette.command.rgb_fallback();
+ assert!(
+ command_red < 40 && command_green >= 115,
+ "commands should remain green/teal structure text"
+ );
+
+ let Rgb(sky_red, sky_green, sky_blue) = palette.sky_value.rgb_fallback();
+ assert!(
+ sky_blue > sky_green && sky_blue > sky_red,
+ "model names, paths, and URLs should use a clearer sky-blue value color"
+ );
+ }
+}
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 2fda89404..839d61638 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -1131,7 +1131,7 @@ For memory-related settings, add a `memory` section in `ov.conf`:
### ovcli.conf
-You can edit this file by hand, or generate it interactively with `ov config setup-cli`. If you maintain configurations for multiple servers, switch between them with `ov config switch`.
+You can edit this file by hand, or generate it interactively with `ov config`. If you maintain configurations for multiple servers, switch between them with `ov config switch`.
Config file for the HTTP client (`SyncHTTPClient` / `AsyncHTTPClient`) and CLI to connect to a remote server:
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 8ba94298d..cf70f9412 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -1103,7 +1103,7 @@ openviking-server --config /path/to/ov.conf
### ovcli.conf
-你可以手动编辑此文件,也可以用 `ov config setup-cli` 交互式生成。如果你维护着多个服务端的配置,可以用 `ov config switch` 在它们之间切换。
+你可以手动编辑此文件,也可以用 `ov config` 交互式生成。如果你维护着多个服务端的配置,可以用 `ov config switch` 在它们之间切换。
HTTP 客户端(`SyncHTTPClient` / `AsyncHTTPClient`)和 CLI 工具连接远程服务端的配置文件: