Skip to content

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

feat(cli): add OVPack progress feedback (#6675)

Lusen Dongd4a50718f216
diff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rs
index cba371bf9..fa6e0d120 100644
--- a/crates/ov_cli/src/base_client.rs
+++ b/crates/ov_cli/src/base_client.rs
@@ -16,6 +16,68 @@ use crate::error::{Error, Result};
const GATEWAY_MARKER_HEADER: &str = "X-VikingBot-Gateway";
const GATEWAY_TOKEN_HEADER: &str = "X-Gateway-Token";
+#[cfg(test)]
+thread_local! {
+ static LAST_TEST_PROGRESS: std::cell::RefCell<Option<ProgressBar>> = const { std::cell::RefCell::new(None) };
+}
+
+pub(crate) fn progress_spinner(message: impl Into<String>) -> ProgressBar {
+ let progress = ProgressBar::new_spinner();
+ progress.set_message(message.into());
+ progress.enable_steady_tick(std::time::Duration::from_millis(100));
+ #[cfg(test)]
+ LAST_TEST_PROGRESS.with(|slot| slot.borrow_mut().replace(progress.clone()));
+ progress
+}
+
+pub(crate) struct ProgressGuard(Option<ProgressBar>, &'static str);
+
+impl ProgressGuard {
+ pub(crate) fn new(message: impl Into<String>, failure_message: &'static str) -> Self {
+ Self(Some(progress_spinner(message)), failure_message)
+ }
+
+ pub(crate) fn set_message(&self, message: &'static str) {
+ self.0.as_ref().unwrap().set_message(message);
+ }
+
+ pub(crate) fn finish(mut self, message: &'static str) {
+ self.0.take().unwrap().finish_with_message(message);
+ }
+}
+
+impl Drop for ProgressGuard {
+ fn drop(&mut self) {
+ if let Some(progress) = self.0.take() {
+ progress.abandon_with_message(self.1);
+ }
+ }
+}
+
+#[cfg(test)]
+pub(crate) fn take_test_progress() -> Option<ProgressBar> {
+ LAST_TEST_PROGRESS.with(|slot| slot.borrow_mut().take())
+}
+
+#[cfg(test)]
+pub(crate) async fn spawn_test_response(status: &'static str, body: &'static str) -> String {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::net::TcpListener;
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let (mut connection, _) = listener.accept().await.unwrap();
+ let mut request = vec![0; 8192];
+ let _ = connection.read(&mut request).await.unwrap();
+ let response = format!(
+ "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()
+ );
+ connection.write_all(response.as_bytes()).await.unwrap();
+ });
+ format!("http://{address}")
+}
+
fn parse_ignore_dirs(ignore_dirs: Option<&str>) -> Vec<String> {
ignore_dirs
.map(|s| {
@@ -799,6 +861,30 @@ mod tests {
));
}
+ #[tokio::test]
+ async fn upload_progress_reports_failure_for_http_error() {
+ let base_url = spawn_test_response(
+ "400 Bad Request",
+ r#"{"error":{"code":"BAD_REQUEST","message":"invalid archive"}}"#,
+ )
+ .await;
+ let client = BaseClient::new(base_url, None, None, None, None, 5.0, false, None);
+ let uploader = FileUploader::new(&client);
+ let file = tempfile::NamedTempFile::new().expect("temporary upload should be created");
+ std::fs::write(file.path(), b"invalid").expect("temporary upload should be written");
+
+ let _ = take_test_progress();
+ let error = uploader
+ .upload_temp_file_with_progress(file.path(), false)
+ .await
+ .expect_err("HTTP error should fail upload");
+ let progress = take_test_progress().expect("upload progress should be recorded");
+
+ assert!(matches!(error, Error::Api { status: Some(400), .. }));
+ assert!(progress.is_finished());
+ assert_eq!(progress.message(), "Upload failed");
+ }
+
#[test]
fn unwrap_success_envelope_drops_null_profile_for_value_results() {
let body = json!({
@@ -1129,14 +1215,11 @@ impl<'a> FileUploader<'a> {
file_path: &Path,
verbose: bool,
) -> Result<String> {
- use indicatif::ProgressBar;
-
let url = format!("{}/api/v1/resources/temp_upload", self.client.base_url);
let file_name = file_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("temp_upload.zip");
-
let file_content = tokio::fs::read(file_path).await?;
let file_size = file_content.len() as u64;
@@ -1148,16 +1231,16 @@ impl<'a> FileUploader<'a> {
);
}
- let pb = ProgressBar::new_spinner();
- pb.set_message(format!(
- "Uploading {} ({:.2} MB)...",
- file_name,
- file_size as f64 / 1024.0 / 1024.0
- ));
- pb.enable_steady_tick(std::time::Duration::from_millis(100));
+ let progress = ProgressGuard::new(
+ format!(
+ "Uploading {} ({:.2} MB)...",
+ file_name,
+ file_size as f64 / 1024.0 / 1024.0
+ ),
+ "Upload failed",
+ );
let part = reqwest::multipart::Part::bytes(file_content).file_name(file_name.to_string());
-
let part = part
.mime_str("application/octet-stream")
.map_err(|e| Error::from_reqwest("Failed to set mime type", e))?;
@@ -1184,13 +1267,13 @@ impl<'a> FileUploader<'a> {
.await
.map_err(|e| Error::from_reqwest("File upload failed", e))?;
- pb.finish_with_message("Upload complete");
-
let result: Value = self.client.handle_response(response).await?;
- result
+ let temp_file_id = result
.get("temp_file_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
- .ok_or_else(|| Error::Parse("Missing temp_file_id in response".to_string()))
+ .ok_or_else(|| Error::Parse("Missing temp_file_id in response".to_string()))?;
+ progress.finish("Upload complete");
+ Ok(temp_file_id)
}
}
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index b6712c518..de193a0c2 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -7,6 +7,7 @@ use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
pub use crate::base_client::{BaseClient, FileUploader, TimeoutConfig};
+use crate::base_client::ProgressGuard;
use crate::error::{Error, Result};
/// Drop null-valued keys (and an empty `args` object) from a request body before
@@ -1496,6 +1497,7 @@ impl HttpClient {
body: serde_json::Value,
to: &str,
default_name: &str,
+ show_progress: bool,
) -> Result<String> {
let url = format!("{}{}", self.base.base_url, endpoint);
let request = self
@@ -1505,6 +1507,9 @@ impl HttpClient {
.headers(self.base.build_headers())
.json(&body)
.query(&[("profile", "0")]);
+ let progress = show_progress.then(|| {
+ ProgressGuard::new("Preparing OVPack on server", "OVPack download failed")
+ });
let response = self
.base
.send_request(request, "HTTP request failed")
@@ -1516,10 +1521,12 @@ impl HttpClient {
.bytes()
.await
.map_err(|e| Error::from_reqwest("Failed to read error response", e))?;
-
return Err(crate::base_client::api_error_from_body(&bytes, status));
}
+ if let Some(progress) = &progress {
+ progress.set_message("Downloading OVPack");
+ }
let bytes = response
.bytes()
.await
@@ -1537,17 +1544,37 @@ impl HttpClient {
if let Some(parent) = final_path.parent() {
std::fs::create_dir_all(parent)?;
}
-
std::fs::write(&final_path, bytes)?;
+ if let Some(progress) = progress {
+ progress.finish("OVPack download complete");
+ }
+
Ok(final_path.to_string_lossy().to_string())
}
+ async fn post_pack_operation(
+ &self,
+ endpoint: &str,
+ body: &serde_json::Value,
+ show_progress: bool,
+ message: &str,
+ ) -> Result<serde_json::Value> {
+ let processing = show_progress
+ .then(|| ProgressGuard::new(message, "OVPack processing failed"));
+ let result = self.post(endpoint, body).await?;
+ if let Some(processing) = processing {
+ processing.finish("OVPack processing complete");
+ }
+ Ok(result)
+ }
+
pub async fn export_ovpack(
&self,
uri: &str,
to: &str,
include_vectors: bool,
+ show_progress: bool,
) -> Result<String> {
let body = serde_json::json!({
"uri": uri,
@@ -1558,16 +1585,22 @@ impl HttpClient {
.split('/')
.last()
.unwrap_or("export");
- self.download_pack("/api/v1/pack/export", body, to, base_name)
+ self.download_pack("/api/v1/pack/export", body, to, base_name, show_progress)
.await
}
- pub async fn backup_ovpack(&self, to: &str, include_vectors: bool) -> Result<String> {
+ pub async fn backup_ovpack(
+ &self,
+ to: &str,
+ include_vectors: bool,
+ show_progress: bool,
+ ) -> Result<String> {
self.download_pack(
"/api/v1/pack/backup",
serde_json::json!({"include_vectors": include_vectors}),
to,
"openviking-backup",
+ show_progress,
)
.await
}
@@ -1578,6 +1611,7 @@ impl HttpClient {
parent: &str,
on_conflict: Option<&str>,
vector_mode: Option<&str>,
+ show_progress: bool,
) -> Result<serde_json::Value> {
let file_path_obj = Path::new(file_path);
@@ -1591,7 +1625,12 @@ impl HttpClient {
return Err(Error::Client(format!("Path is not a file: {}", file_path)));
}
- let temp_file_id = self.upload_temp_file(file_path_obj).await?;
+ let temp_file_id = if show_progress {
+ self.upload_temp_file_with_progress(file_path_obj, false)
+ .await?
+ } else {
+ self.upload_temp_file(file_path_obj).await?
+ };
let conflict_policy = on_conflict.unwrap_or("fail");
let body = serde_json::json!({
"temp_file_id": temp_file_id,
@@ -1599,7 +1638,13 @@ impl HttpClient {
"on_conflict": conflict_policy,
"vector_mode": vector_mode.unwrap_or("auto"),
});
- self.post("/api/v1/pack/import", &body).await
+ self.post_pack_operation(
+ "/api/v1/pack/import",
+ &body,
+ show_progress,
+ "Validating and importing OVPack on server",
+ )
+ .await
}
pub async fn restore_ovpack(
@@ -1607,6 +1652,7 @@ impl HttpClient {
file_path: &str,
on_conflict: Option<&str>,
vector_mode: Option<&str>,
+ show_progress: bool,
) -> Result<serde_json::Value> {
let file_path_obj = Path::new(file_path);
@@ -1620,14 +1666,25 @@ impl HttpClient {
return Err(Error::Client(format!("Path is not a file: {}", file_path)));
}
- let temp_file_id = self.upload_temp_file(file_path_obj).await?;
+ let temp_file_id = if show_progress {
+ self.upload_temp_file_with_progress(file_path_obj, false)
+ .await?
+ } else {
+ self.upload_temp_file(file_path_obj).await?
+ };
let conflict_policy = on_conflict.unwrap_or("fail");
let body = serde_json::json!({
"temp_file_id": temp_file_id,
"on_conflict": conflict_policy,
"vector_mode": vector_mode.unwrap_or("auto"),
});
- self.post("/api/v1/pack/restore", &body).await
+ self.post_pack_operation(
+ "/api/v1/pack/restore",
+ &body,
+ show_progress,
+ "Validating and restoring OVPack on server",
+ )
+ .await
}
// ============ Admin Methods ============
@@ -2286,7 +2343,9 @@ mod resource_wait_tests;
#[cfg(test)]
mod tests {
use super::{BaseClient, HttpClient, TimeoutConfig};
- use crate::base_client::api_error_from_envelope;
+ use crate::base_client::{
+ api_error_from_envelope, spawn_test_response, take_test_progress,
+ };
use reqwest::StatusCode;
use serde_json::{Map, json};
use std::collections::HashMap;
@@ -2803,6 +2862,7 @@ mod tests {
.to_str()
.expect("tempdir path should be valid"),
false,
+ false,
)
.await
.expect("pack export should retry through gateway");
@@ -3091,6 +3151,33 @@ mod tests {
assert!(cancel_request.starts_with("POST /api/v1/tasks/cmp_1/cancel "));
}
+ #[tokio::test]
+ async fn ovpack_download_progress_reports_failure_for_http_error() {
+ let base_url = spawn_test_response(
+ "500 Internal Server Error",
+ r#"{"error":{"code":"INTERNAL_ERROR","message":"export failed"}}"#,
+ )
+ .await;
+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);
+ let destination = tempfile::tempdir().expect("download directory should be created");
+
+ let _ = take_test_progress();
+ let error = client
+ .export_ovpack(
+ "viking://resources/demo",
+ destination.path().to_str().unwrap(),
+ false,
+ true,
+ )
+ .await
+ .expect_err("HTTP error should fail download");
+ let progress = take_test_progress().expect("download progress should be recorded");
+
+ assert!(matches!(error, crate::error::Error::Api { status: Some(500), .. }));
+ assert!(progress.is_finished());
+ assert_eq!(progress.message(), "OVPack download failed");
+ }
+
#[tokio::test]
async fn admin_request_payloads_are_sent() {
let (base_url, request_rx) = spawn_request_capture_server().await;
diff --git a/crates/ov_cli/src/commands/pack.rs b/crates/ov_cli/src/commands/pack.rs
index 4c1c52d46..24f3b15ff 100644
--- a/crates/ov_cli/src/commands/pack.rs
+++ b/crates/ov_cli/src/commands/pack.rs
@@ -10,7 +10,14 @@ pub async fn export(
format: OutputFormat,
compact: bool,
) -> Result<()> {
- let file_path = client.export_ovpack(uri, to, include_vectors).await?;
+ let file_path = client
+ .export_ovpack(
+ uri,
+ to,
+ include_vectors,
+ matches!(format, OutputFormat::Table),
+ )
+ .await?;
// Output success message with the file path
let result = serde_json::json!({
@@ -29,7 +36,9 @@ pub async fn backup(
format: OutputFormat,
compact: bool,
) -> Result<()> {
- let file_path = client.backup_ovpack(to, include_vectors).await?;
+ let file_path = client
+ .backup_ovpack(to, include_vectors, matches!(format, OutputFormat::Table))
+ .await?;
let result = serde_json::json!({
"file": file_path,
@@ -50,7 +59,13 @@ pub async fn import(
compact: bool,
) -> Result<()> {
let result = client
- .import_ovpack(file_path, target, on_conflict, vector_mode)
+ .import_ovpack(
+ file_path,
+ target,
+ on_conflict,
+ vector_mode,
+ matches!(format, OutputFormat::Table),
+ )
.await?;
output_success(&result, format, compact);
Ok(())
@@ -65,7 +80,12 @@ pub async fn restore(
compact: bool,
) -> Result<()> {
let result = client
- .restore_ovpack(file_path, on_conflict, vector_mode)
+ .restore_ovpack(
+ file_path,
+ on_conflict,
+ vector_mode,
+ matches!(format, OutputFormat::Table),
+ )
.await?;
output_success(&result, format, compact);
Ok(())