Skip to content

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

fix(cli): poll task status for add-resource --wait (#6487)

zhanglistare15732a8eeb6
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 4da5cee75..ac5c0e10f 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -916,7 +916,7 @@ impl HttpClient {
// A declared Connector add_type sends the path verbatim as a remote
// source; never interpret it as a local file to upload.
- if add_type.is_none() && path_obj.exists() {
+ let submitted: Value = if add_type.is_none() && path_obj.exists() {
if path_obj.is_dir() {
let source_name = path_obj
.file_name()
@@ -941,7 +941,7 @@ impl HttpClient {
"parent": effective_parent,
"reason": reason,
"instruction": instruction,
- "wait": wait,
+ "wait": false,
"strict": strict,
"ignore_dirs": ignore_dirs,
"include": include,
@@ -976,7 +976,7 @@ impl HttpClient {
"parent": effective_parent,
"reason": reason,
"instruction": instruction,
- "wait": wait,
+ "wait": false,
"strict": strict,
"ignore_dirs": ignore_dirs,
"include": include,
@@ -999,7 +999,7 @@ impl HttpClient {
"parent": effective_parent,
"reason": reason,
"instruction": instruction,
- "wait": wait,
+ "wait": false,
"strict": strict,
"ignore_dirs": ignore_dirs,
"include": include,
@@ -1020,7 +1020,7 @@ impl HttpClient {
"parent": effective_parent,
"reason": reason,
"instruction": instruction,
- "wait": wait,
+ "wait": false,
"strict": strict,
"ignore_dirs": ignore_dirs,
"include": include,
@@ -1032,6 +1032,158 @@ impl HttpClient {
}));
self.post("/api/v1/resources", &body).await
+ }?;
+
+ if !wait {
+ return Ok(submitted);
+ }
+ let task_id = submitted
+ .get("task_id")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty())
+ .ok_or_else(|| {
+ Error::Client(
+ "Import response has no task_id; cannot wait for completion. \
+ Check 'ov task list' before submitting again."
+ .to_string(),
+ )
+ })?;
+ self.wait_for_resource_task(
+ task_id,
+ tokio::signal::ctrl_c(),
+ std::time::Duration::from_secs(1),
+ )
+ .await
+ }
+
+ /// Wait without an overall deadline. Each status GET retains the ordinary
+ /// HTTP timeout. Consecutive observation failures are bounded, and retries
+ /// never resubmit the import.
+ async fn wait_for_resource_task(
+ &self,
+ task_id: &str,
+ interrupted: impl std::future::Future<Output = std::io::Result<()>>,
+ interval: std::time::Duration,
+ ) -> Result<Value> {
+ tokio::pin!(interrupted);
+ let observation_error = |error: Error| {
+ let code = Some(error.code().to_string());
+ let (message, details, status) = match error {
+ Error::Api {
+ message,
+ details,
+ status,
+ ..
+ } => (message, details, status),
+ other => (other.to_string(), None, None),
+ };
+ Error::Api {
+ code,
+ message: format!(
+ "{message}; task continues on the server; check with: ov task status {task_id}"
+ ),
+ details: Some(json!({"task_id": task_id, "details": details})),
+ status,
+ }
+ };
+ let poll = async {
+ let mut retry_delay = interval;
+ let mut failures = 0;
+ loop {
+ let task = match self.get_task(task_id).await {
+ Ok(task) => {
+ retry_delay = interval;
+ failures = 0;
+ task
+ }
+ Err(err)
+ if matches!(
+ err,
+ Error::Timeout(_)
+ | Error::Network(_)
+ | Error::Api {
+ status: Some(429 | 502 | 503 | 504),
+ ..
+ }
+ ) =>
+ {
+ failures += 1;
+ if failures >= 10 {
+ return Err(observation_error(err));
+ }
+ tokio::time::sleep(retry_delay).await;
+ retry_delay = (retry_delay * 2).min(interval * 5);
+ continue;
+ }
+ Err(err) => return Err(observation_error(err)),
+ };
+ match task.get("status").and_then(Value::as_str) {
+ Some("completed") => {
+ let mut result = task.get("result").cloned().ok_or_else(|| {
+ observation_error(Error::Parse(format!(
+ "Completed task {task_id} has no result"
+ )))
+ })?;
+ if !result.is_object() {
+ return Err(observation_error(Error::Parse(format!(
+ "Completed task {task_id} has an invalid result"
+ ))));
+ }
+ // Return the task result plus task_id for inspection.
+ // The server's wait=true response omits this extra field.
+ result["task_id"] = json!(task_id);
+ return Ok(result);
+ }
+ Some("cancelled") => {
+ // 服务端取消任务时会清空 result 和 error,需显式保留取消语义。
+ return Err(Error::Api {
+ code: Some("CANCELLED".into()),
+ message: format!(
+ "Task {task_id} cancelled; check with: ov task status {task_id}"
+ ),
+ details: Some(json!({"task_id": task_id, "status": "cancelled"})),
+ status: None,
+ });
+ }
+ Some("failed") => {
+ let result = &task["result"];
+ return Err(Error::Api {
+ code: result["code"].as_str().map(str::to_string),
+ message: format!(
+ "Task {task_id} failed: {}",
+ task["error"]
+ .as_str()
+ .unwrap_or("resource processing failed")
+ ),
+ details: Some(json!({
+ "task_id": task_id,
+ "status": "failed",
+ "details": result.get("details"),
+ })),
+ status: None,
+ });
+ }
+ Some("pending" | "running" | "cancelling") => {}
+ _ => {
+ return Err(observation_error(Error::Parse(format!(
+ "Task {task_id} returned an invalid status"
+ ))));
+ }
+ }
+ tokio::time::sleep(interval).await;
+ }
+ };
+ tokio::select! {
+ result = poll => result,
+ signal = &mut interrupted => {
+ signal.map_err(|error| observation_error(Error::Io(error)))?;
+ Err(Error::Api {
+ code: Some("INTERRUPTED".into()),
+ message: format!("Stopped waiting. The server task was not cancelled. Check progress with: ov task status {task_id}"),
+ details: Some(json!({"task_id": task_id})),
+ status: None,
+ })
+ }
}
}
@@ -2112,6 +2264,9 @@ impl HttpClient {
}
}
+#[cfg(test)]
+mod resource_wait_tests;
+
#[cfg(test)]
mod tests {
use super::{BaseClient, HttpClient, TimeoutConfig};
diff --git a/crates/ov_cli/src/client/resource_wait_tests.rs b/crates/ov_cli/src/client/resource_wait_tests.rs
new file mode 100644
index 000000000..56933a704
--- /dev/null
+++ b/crates/ov_cli/src/client/resource_wait_tests.rs
@@ -0,0 +1,356 @@
+use super::HttpClient;
+use serde_json::{Value, json};
+use std::time::Duration;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+
+async fn bounded<T>(future: impl std::future::Future<Output = T>) -> T {
+ tokio::time::timeout(Duration::from_secs(20), future)
+ .await
+ .expect("resource wait test timed out")
+}
+
+fn task(status: &str) -> Value {
+ json!({"status":"ok","result":{
+ "status":status, "error":null,
+ "result":{"context_count":10,"code":"MODEL_ERROR","details":{"model":"test"}}
+ }})
+}
+
+// Record real HTTP requests; delayed replies do not block accepting retries.
+async fn server(
+ responses: Vec<(u16, Value, u64)>,
+) -> (HttpClient, tokio::task::JoinHandle<Vec<String>>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let client = HttpClient::new(
+ format!("http://{}", listener.local_addr().unwrap()),
+ None,
+ None,
+ None,
+ None,
+ 1.0,
+ false,
+ None,
+ );
+ let peer = tokio::spawn(bounded(async move {
+ let mut requests = Vec::new();
+ let mut writers = Vec::new();
+ for (status, body, delay) in responses {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut request = Vec::new();
+ loop {
+ let mut bytes = [0; 4096];
+ let count = socket.read(&mut bytes).await.unwrap();
+ assert!(count > 0);
+ request.extend_from_slice(&bytes[..count]);
+ if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
+ let headers = String::from_utf8_lossy(&request[..end]);
+ let length = headers
+ .lines()
+ .filter_map(|l| l.split_once(':'))
+ .find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
+ .map(|(_, v)| v.trim().parse::<usize>().unwrap())
+ .unwrap_or(0);
+ if request.len() >= end + 4 + length {
+ break;
+ }
+ }
+ }
+ requests.push(String::from_utf8_lossy(&request).into_owned());
+ writers.push(tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(delay)).await;
+ let body = body.to_string();
+ let response = format!(
+ "HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\n\
+ Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = socket.write_all(response.as_bytes()).await;
+ }));
+ }
+ for writer in writers {
+ writer.await.unwrap();
+ }
+ requests
+ }));
+ (client, peer)
+}
+
+async fn submit(
+ client: &HttpClient,
+ path: &str,
+ add_type: Option<String>,
+ wait: bool,
+) -> crate::error::Result<Value> {
+ bounded(client.add_resource(
+ path,
+ add_type,
+ Some("viking://resources/demo/docs".into()),
+ None,
+ None,
+ "",
+ "",
+ wait,
+ false,
+ None,
+ None,
+ None,
+ true,
+ 0.0,
+ "semantic_and_vectors".into(),
+ None,
+ Vec::new(),
+ "replace".into(),
+ None,
+ false,
+ false,
+ ))
+ .await
+}
+
+#[tokio::test]
+async fn submits_once_and_polls_file_directory_url_and_connector() {
+ let dir = tempfile::tempdir().unwrap();
+ let file = dir.path().join("doc.md");
+ std::fs::write(&file, "# Example").unwrap();
+ for (path, add_type, local) in [
+ (file.to_str().unwrap(), None, true),
+ (dir.path().to_str().unwrap(), None, true),
+ ("https://example.com/docs", None, false),
+ ("tos://bucket/docs", Some("tos".into()), false),
+ ] {
+ let mut replies = Vec::new();
+ if local {
+ replies.push((
+ 200,
+ json!({"status":"ok","result":{"temp_file_id":"upload"}}),
+ 0,
+ ));
+ }
+ replies.extend([
+ (
+ 200,
+ json!({"status":"ok","result":{"task_id":"task-import"}}),
+ 0,
+ ),
+ (200, task("pending"), 0),
+ (200, task("running"), 0),
+ (200, task("completed"), 0),
+ ]);
+ let (client, peer) = server(replies).await;
+ let result = submit(&client, path, add_type, true).await.unwrap();
+ assert_eq!(result["task_id"], "task-import");
+ assert_eq!(result["context_count"], 10);
+ let requests = bounded(peer).await.unwrap();
+ let imports: Vec<_> = requests
+ .iter()
+ .filter(|r| r.starts_with("POST /api/v1/resources HTTP"))
+ .collect();
+ assert_eq!(imports.len(), 1);
+ let body: Value =
+ serde_json::from_str(imports[0].split("\r\n\r\n").nth(1).unwrap()).unwrap();
+ assert_eq!(body["wait"], false);
+ assert_eq!(body["to"], "viking://resources/demo/docs");
+ assert_eq!(
+ requests
+ .iter()
+ .filter(|r| r.starts_with("GET /api/v1/tasks/task-import"))
+ .count(),
+ 3
+ );
+ }
+}
+
+#[tokio::test]
+async fn no_wait_returns_without_polling() {
+ let (client, peer) = server(vec![(
+ 200,
+ json!({"status":"ok","result":{"task_id":"task-import"}}),
+ 0,
+ )])
+ .await;
+ assert_eq!(
+ submit(&client, "https://example.com/docs", None, false)
+ .await
+ .unwrap()["task_id"],
+ "task-import"
+ );
+ assert_eq!(bounded(peer).await.unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn retries_timeouts_rate_limits_and_gateway_errors_without_resubmitting() {
+ for (status, delay) in [(200, 3000), (429, 0), (502, 0), (503, 0), (504, 0)] {
+ let (client, peer) = server(vec![
+ (
+ 200,
+ json!({"status":"ok","result":{"task_id":"task-import"}}),
+ 0,
+ ),
+ (status, task("running"), delay),
+ (200, task("completed"), 0),
+ ])
+ .await;
+ assert_eq!(
+ submit(&client, "https://example.com/docs", None, true)
+ .await
+ .unwrap()["task_id"],
+ "task-import"
+ );
+ let requests = bounded(peer).await.unwrap();
+ assert_eq!(requests.len(), 3);
+ assert!(requests[0].starts_with("POST "));
+ assert!(
+ requests[1..]
+ .iter()
+ .all(|r| r.starts_with("GET /api/v1/tasks/"))
+ );
+ }
+}
+
+#[tokio::test]
+async fn stops_after_ten_failures_and_resets_counter_after_success() {
+ for recovers in [false, true] {
+ let failure = (
+ 503,
+ json!({"error":{"code":"UNAVAILABLE","message":"offline"}}),
+ 0,
+ );
+ let mut replies = vec![failure.clone(); 9];
+ if recovers {
+ replies.push((200, task("running"), 0));
+ replies.extend(vec![failure; 9]);
+ replies.push((200, task("completed"), 0));
+ } else {
+ replies.push(failure);
+ }
+ let count = replies.len();
+ let (client, peer) = server(replies).await;
+ let result = bounded(client.wait_for_resource_task(
+ "task-import",
+ std::future::pending(),
+ Duration::from_millis(1),
+ ))
+ .await;
+ if recovers {
+ assert_eq!(result.unwrap()["task_id"], "task-import");
+ } else {
+ let error = result.unwrap_err();
+ assert_eq!(error.code(), "UNAVAILABLE");
+ assert!(error.to_string().contains("ov task status task-import"));
+ }
+ let requests = bounded(peer).await.unwrap();
+ assert_eq!(requests.len(), count);
+ assert!(requests.iter().all(|r| r.starts_with("GET /api/v1/tasks/")));
+ }
+}
+
+#[tokio::test]
+async fn authentication_and_malformed_status_errors_include_recovery_command() {
+ for (status, response) in [
+ (
+ 403,
+ json!({"error":{"code":"FORBIDDEN","message":"Access denied","details":{"reason":"revoked"}}}),
+ ),
+ (200, task("unknown")),
+ (
+ 200,
+ json!({"status":"ok","result":{"status":"completed","result":[]}}),
+ ),
+ (200, json!({"status":"ok","result":{"status":"completed"}})),
+ ] {
+ let (client, peer) = server(vec![(status, response, 0)]).await;
+ let error = bounded(client.wait_for_resource_task(
+ "task-import",
+ std::future::pending(),
+ Duration::from_millis(1),
+ ))
+ .await
+ .unwrap_err();
+ assert!(error.to_string().contains("ov task status task-import"));
+ if status == 403 {
+ assert_eq!(error.code(), "FORBIDDEN");
+ match error {
+ crate::error::Error::Api {
+ status, details, ..
+ } => {
+ assert_eq!(status, Some(403));
+ assert_eq!(details.unwrap()["details"]["reason"], "revoked");
+ }
+ other => panic!("{other}"),
+ }
+ }
+ assert_eq!(bounded(peer).await.unwrap().len(), 1);
+ }
+}
+
+#[tokio::test]
+async fn failed_tasks_are_terminal() {
+ let (client, peer) = server(vec![(200, task("failed"), 0)]).await;
+ let error = bounded(client.wait_for_resource_task(
+ "task-import",
+ std::future::pending(),
+ Duration::from_millis(1),
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(error.code(), "MODEL_ERROR");
+ assert!(error.to_string().contains("failed: resource processing failed"));
+ assert!(!error.to_string().contains("continues"));
+ assert_eq!(bounded(peer).await.unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn cancelled_tasks_surface_a_cancelled_code() {
+ // 使用 mark_cancelled 的真实响应形状:result 和 error 均为空。
+ let (client, peer) = server(vec![(
+ 200,
+ json!({"status":"ok","result":{"status":"cancelled","error":null,"result":null}}),
+ 0,
+ )])
+ .await;
+ let error = bounded(client.wait_for_resource_task(
+ "task-import",
+ std::future::pending(),
+ Duration::from_millis(1),
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(error.code(), "CANCELLED");
+ assert!(error.to_string().contains("ov task status task-import"));
+ assert!(!error.to_string().contains("cancelled: cancelled"));
+ match error {
+ crate::error::Error::Api { message, details, status, .. } => {
+ assert_eq!(message, "Task task-import cancelled; check with: ov task status task-import");
+ assert_eq!(details.unwrap(), json!({"task_id": "task-import", "status": "cancelled"}));
+ assert_eq!(status, None);
+ }
+ other => panic!("{other}"),
+ }
+ assert_eq!(bounded(peer).await.unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn connection_failures_are_bounded() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let client = HttpClient::new(
+ format!("http://{}", listener.local_addr().unwrap()),
+ None,
+ None,
+ None,
+ None,
+ 1.0,
+ false,
+ None,
+ );
+ drop(listener);
+ let error = bounded(client.wait_for_resource_task(
+ "task-import",
+ std::future::pending(),
+ Duration::from_millis(1),
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(error.code(), "UNAVAILABLE");
+ assert!(error.to_string().contains("ov task status task-import"));
+}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 521a1176b..75b22baa4 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -4046,6 +4046,20 @@ async fn main() {
};
if let Err(e) = result {
+ if e.code() == "INTERRUPTED" {
+ if matches!(output_format, OutputFormat::Json) {
+ error_ui::print_runtime_error(
+ &command_display,
+ &e,
+ output_format,
+ compact,
+ verbose_errors,
+ );
+ } else if let Error::Api { message, .. } = &e {
+ eprintln!("{message}");
+ }
+ std::process::exit(130);
+ }
if !matches!(e, Error::AlreadyReported) {
error_ui::print_runtime_error(
&command_display,
diff --git a/crates/ov_cli/tests/resource_wait_interrupt.rs b/crates/ov_cli/tests/resource_wait_interrupt.rs
new file mode 100644
index 000000000..553d3fc2c
--- /dev/null
+++ b/crates/ov_cli/tests/resource_wait_interrupt.rs
@@ -0,0 +1,111 @@
+//! Exercise the real process exit path without cancelling the server task.
+#![cfg(unix)]
+
+use serde_json::json;
+use std::process::Stdio;
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::TcpListener,
+ process::Command,
+ sync::oneshot,
+ time::{Duration, timeout},
+};
+
+async fn read_request(stream: &mut tokio::net::TcpStream) -> String {
+ let mut request = Vec::new();
+ loop {
+ let mut chunk = [0; 4096];
+ let size = stream.read(&mut chunk).await.unwrap();
+ assert!(size > 0);
+ request.extend_from_slice(&chunk[..size]);
+ if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
+ let headers = String::from_utf8_lossy(&request[..end]);
+ let length = headers
+ .lines()
+ .filter_map(|line| line.split_once(':'))
+ .find(|(key, _)| key.eq_ignore_ascii_case("content-length"))
+ .map(|(_, value)| value.trim().parse::<usize>().unwrap())
+ .unwrap_or(0);
+ if request.len() >= end + 4 + length {
+ return String::from_utf8(request).unwrap();
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn ctrl_c_exits_130_without_cancelling_server_task() {
+ timeout(Duration::from_secs(20), async {
+ for (config_output, cli_output) in [("table", None), ("table", Some("json")), ("json", None)] {
+ let json_output = cli_output.unwrap_or(config_output) == "json";
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let (status_tx, status_rx) = oneshot::channel();
+ let (finish_tx, finish_rx) = oneshot::channel();
+ let server = tokio::spawn(async move {
+ let (mut submit, _) = listener.accept().await.unwrap();
+ let request = read_request(&mut submit).await;
+ assert!(request.starts_with("POST /api/v1/resources HTTP"));
+ let body: serde_json::Value =
+ serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap();
+ assert_eq!(body["wait"], false);
+ let response = json!({"status":"ok","result":{"task_id":"task-import"}}).to_string();
+ submit.write_all(format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}",
+ response.len()
+ ).as_bytes()).await.unwrap();
+ let (mut status, _) = listener.accept().await.unwrap();
+ assert!(read_request(&mut status).await.starts_with("GET /api/v1/tasks/task-import"));
+ status_tx.send(()).unwrap();
+ // Keep this status GET in flight until the interrupted CLI exits.
+ finish_rx.await.unwrap();
+ let listener = listener.into_std().unwrap();
+ assert!(matches!(listener.accept(), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock),
+ "CLI must neither resubmit nor cancel the task");
+ });
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join("ovcli.conf"), json!({"url":url,"output":config_output}).to_string()).unwrap();
+ std::fs::create_dir(dir.path().join(".openviking")).unwrap();
+ std::fs::write(dir.path().join(".openviking/ovcli.settings.conf"),
+ json!({"language":"en"}).to_string()).unwrap();
+ let mut args = vec!["add-resource", "https://example.com/docs",
+ "--to", "viking://resources/demo/docs", "--wait"];
+ if let Some(format) = cli_output {
+ args.extend(["--output", format]);
+ }
+ let child = Command::new(env!("CARGO_BIN_EXE_ov"))
+ // Isolate saved language settings from the user's real home.
+ .env("HOME", dir.path())
+ .env("OPENVIKING_CLI_CONFIG_FILE", dir.path().join("ovcli.conf"))
+ .env("OPENVIKING_LANG", "en")
+ .env("NO_COLOR", "1")
+ .args(&args)
+ .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped())
+ .kill_on_drop(true).spawn().unwrap();
+ status_rx.await.unwrap();
+ let signal = Command::new("kill").args(["-INT", &child.id().unwrap().to_string()])
+ .status().await.unwrap();
+ assert!(signal.success());
+ let output = child.wait_with_output().await.unwrap();
+ assert_eq!(output.status.code(), Some(130), "{output:?}");
+ assert!(output.stdout.is_empty());
+ let stderr = String::from_utf8(output.stderr).unwrap();
+ if json_output {
+ // 显式参数或配置选择 JSON 时,stderr 必须是完整错误 envelope。
+ let envelope: serde_json::Value = serde_json::from_str(&stderr)
+ .unwrap_or_else(|e| panic!("stderr must be a JSON envelope ({e}): {stderr}"));
+ assert_eq!(envelope["ok"], false, "{stderr}");
+ assert_eq!(envelope["error"]["code"], "INTERRUPTED", "{stderr}");
+ assert_eq!(envelope["error"]["details"]["task_id"], "task-import", "{stderr}");
+ assert!(envelope["error"]["message"]
+ .as_str().unwrap().contains("ov task status task-import"), "{stderr}");
+ } else {
+ assert!(stderr.contains("ov task status task-import"), "{stderr}");
+ assert_eq!(stderr.lines().count(), 1, "{stderr}");
+ assert!(!stderr.contains("INVALID_ARGUMENT") && !stderr.contains("Client error"));
+ }
+ finish_tx.send(()).unwrap();
+ server.await.unwrap();
+ }
+ }).await.expect("SIGINT integration test exceeded 20s");
+}
diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.md
index 10d0d5138..bb4b52b5e 100644
--- a/docs/en/api/02-resources.md
+++ b/docs/en/api/02-resources.md
@@ -503,6 +503,12 @@ fmt.Println(result["task_id"])
**CLI**
+`ov add-resource --wait` submits once and polls the task without an overall
+deadline. Status-query timeouts, network errors, and HTTP 429/502/503/504
+retry; 10 consecutive failures exit with a task recovery command.
+Ctrl+C stops waiting without cancelling the task (exit 130).
+The completed CLI result retains `task_id`.
+
```bash
# Add local file
ov add-resource ./documents/guide.md --reason "User guide"
diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.md
index 4a56b6e2e..7b1fad739 100644
--- a/docs/zh/api/02-resources.md
+++ b/docs/zh/api/02-resources.md
@@ -502,6 +502,11 @@ fmt.Println(result["task_id"])
**CLI**
+`ov add-resource --wait` 只提交一次,再轮询任务,不设置整体等待期限。
+状态查询超时、网络错误及 HTTP 429/502/503/504 会重试;连续 10 次失败后
+退出并提供任务查询命令。Ctrl+C 仅停止等待,不取消任务,退出码为 130。
+完成后 CLI 结果保留 `task_id`。
+
```bash
# 添加本地文件
ov add-resource ./documents/guide.md --reason "User guide"