Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(task): add async task tracking for add-resource and add-skill operations (#1763)
zgy9b4373462025
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 2680f68ec..bfc917777 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -576,6 +576,28 @@ impl HttpClient {}}+ // ============ Task Methods ============++ pub async fn get_task(&self, task_id: &str) -> Result<serde_json::Value> {+ let path = format!("/api/v1/tasks/{}", task_id);+ self.get(&path, &[]).await+ }++ pub async fn list_tasks(+ &self,+ task_type: Option<&str>,+ status: Option<&str>,+ ) -> Result<serde_json::Value> {+ let mut params: Vec<(String, String)> = Vec::new();+ if let Some(t) = task_type {+ params.push(("task_type".to_string(), t.to_string()));+ }+ if let Some(s) = status {+ params.push(("status".to_string(), s.to_string()));+ }+ self.get("/api/v1/tasks", ¶ms).await+ }+// ============ Relation Methods ============pub async fn relations(&self, uri: &str) -> Result<serde_json::Value> {diff --git a/crates/ov_cli/src/commands/mod.rs b/crates/ov_cli/src/commands/mod.rsindex b48d32933..90ebb9c72 100644--- a/crates/ov_cli/src/commands/mod.rs+++ b/crates/ov_cli/src/commands/mod.rs@@ -11,3 +11,4 @@ pub mod resources;pub mod search;pub mod session;pub mod system;+pub mod task;diff --git a/crates/ov_cli/src/commands/resources.rs b/crates/ov_cli/src/commands/resources.rsindex 8b5c41307..2d45cb9f0 100644--- a/crates/ov_cli/src/commands/resources.rs+++ b/crates/ov_cli/src/commands/resources.rs@@ -44,10 +44,9 @@ pub async fn add_resource().await?;- // Print helpful message for async processingif !wait && matches!(format, OutputFormat::Table) {eprintln!("Note: Resource is being processed in the background.");- eprintln!("Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.");+ eprintln!("Use 'ov task status <task_id>' to check progress, or 'ov task list' to see all tasks.");}output_success(&result, format, compact);@@ -64,10 +63,9 @@ pub async fn add_skill() -> Result<()> {let result = client.add_skill(data, wait, timeout).await?;- // Print helpful message for async processingif !wait && matches!(format, OutputFormat::Table) {eprintln!("Note: Skill is being processed in the background.");- eprintln!("Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.");+ eprintln!("Use 'ov task status <task_id>' to check progress, or 'ov task list' to see all tasks.");}output_success(&result, format, compact);diff --git a/crates/ov_cli/src/commands/task.rs b/crates/ov_cli/src/commands/task.rsnew file mode 100644index 000000000..45f77132b--- /dev/null+++ b/crates/ov_cli/src/commands/task.rs@@ -0,0 +1,26 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::{OutputFormat, output_success};++pub async fn status(+ client: &HttpClient,+ task_id: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let result = client.get_task(task_id).await?;+ output_success(&result, output_format, compact);+ Ok(())+}++pub async fn list(+ client: &HttpClient,+ task_type: Option<&str>,+ status: Option<&str>,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let result = client.list_tasks(task_type, status).await?;+ output_success(&result, output_format, compact);+ Ok(())+}diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex b780c414d..47426800b 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -543,6 +543,11 @@ enum Commands {#[arg(long)]timeout: Option<f64>,},+ /// [Status] Track async resource processing tasks+ Task {+ #[command(subcommand)]+ action: TaskCommands,+ },/// [Status] All OpenViking Server components statusStatus,/// [Status] Observe OpenViking Server components status@@ -596,6 +601,24 @@ impl Commands {}}+#[derive(Subcommand)]+enum TaskCommands {+ /// Show status of a specific task+ Status {+ /// Task ID returned by add-resource/add-skill+ task_id: String,+ },+ /// List all tracked tasks+ List {+ /// Filter by task type (e.g. add_resource, add_skill, session_commit, reindex)+ #[arg(long)]+ task_type: Option<String>,+ /// Filter by status (pending, running, completed, failed)+ #[arg(long)]+ status: Option<String>,+ },+}+#[derive(Subcommand)]enum SystemCommands {/// Wait for queued async processing to complete@@ -1041,6 +1064,23 @@ async fn main() {let client = ctx.get_client();commands::system::wait(&client, timeout, ctx.output_format, ctx.compact).await}+ Commands::Task { action } => match action {+ TaskCommands::Status { task_id } => {+ let client = ctx.get_client();+ commands::task::status(&client, &task_id, ctx.output_format, ctx.compact).await+ }+ TaskCommands::List { task_type, status } => {+ let client = ctx.get_client();+ commands::task::list(+ &client,+ task_type.as_deref(),+ status.as_deref(),+ ctx.output_format,+ ctx.compact,+ )+ .await+ }+ },Commands::Status => {let client = ctx.get_client();commands::observer::system(&client, ctx.output_format, ctx.compact).awaitdiff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex 0d4328591..72aa043a7 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -6,6 +6,7 @@ Resource Service for OpenViking.Provides resource management operations: add_resource, add_skill, wait_processed."""+import asyncioimport jsonimport timefrom typing import TYPE_CHECKING, Any, Dict, List, Optional@@ -161,7 +162,8 @@ class ResourceService:telemetry = get_current_telemetry()telemetry_id = register_wait_telemetry(wait)request_wait_tracker = get_request_wait_tracker()- if wait and telemetry_id:+ monitor_started = False+ if telemetry_id:request_wait_tracker.register_request(telemetry_id)watch_manager = self._get_watch_manager()watch_enabled = bool(@@ -212,7 +214,9 @@ class ResourceService:**kwargs,)- if wait:+ if result.get("status") == "error":+ return result+ elif wait:wait_start = time.perf_counter()try:with telemetry.measure("resource.wait"):@@ -283,6 +287,24 @@ class ResourceService:logger.warning(f"[ResourceService] Failed to cancel watch task for {to}: {e}")+ if not wait:+ from openviking.service.task_tracker import get_task_tracker++ task_tracker = get_task_tracker()+ root_uri = result.get("root_uri", "")+ task = task_tracker.create(+ "add_resource",+ resource_id=root_uri,+ owner_account_id=ctx.account_id,+ owner_user_id=ctx.user.user_id,+ )+ result["task_id"] = task.task_id+ if telemetry_id:+ monitor_started = True+ asyncio.create_task(self._monitor_queue_processing(task.task_id, telemetry_id))+ else:+ task_tracker.start(task.task_id)+ task_tracker.complete(task.task_id, {"root_uri": root_uri})return resultexcept Exception as exc:telemetry.set_error(@@ -296,7 +318,28 @@ class ResourceService:"resource.request.duration_ms",round((time.perf_counter() - request_start) * 1000, 3),)- get_request_wait_tracker().cleanup(telemetry_id)+ if wait or not telemetry_id or not monitor_started:+ get_request_wait_tracker().cleanup(telemetry_id)+ unregister_wait_telemetry(telemetry_id)++ async def _monitor_queue_processing(self, task_id: str, telemetry_id: str) -> None:+ from openviking.service.task_tracker import get_task_tracker++ task_tracker = get_task_tracker()+ request_wait_tracker = get_request_wait_tracker()+ task_tracker.start(task_id)+ try:+ await request_wait_tracker.wait_for_request(telemetry_id)+ status = request_wait_tracker.build_queue_status(telemetry_id)+ errors = sum(int(group.get("error_count", 0) or 0) for group in status.values())+ if errors:+ task_tracker.fail(task_id, f"queue processing failed: {status}")+ else:+ task_tracker.complete(task_id, {"queue_status": status})+ except Exception as exc:+ task_tracker.fail(task_id, str(exc))+ finally:+ request_wait_tracker.cleanup(telemetry_id)unregister_wait_telemetry(telemetry_id)async def _handle_watch_task_creation(@@ -434,7 +477,8 @@ class ResourceService:self._ensure_initialized()telemetry_id = get_current_telemetry().telemetry_idrequest_wait_tracker = get_request_wait_tracker()- if wait and telemetry_id:+ monitor_started = False+ if telemetry_id:request_wait_tracker.register_request(telemetry_id)try:@@ -468,10 +512,28 @@ class ResourceService:round((time.perf_counter() - wait_start) * 1000, 3),)result["queue_status"] = status+ else:+ from openviking.service.task_tracker import get_task_tracker++ task_tracker = get_task_tracker()+ task = task_tracker.create(+ "add_skill",+ owner_account_id=ctx.account_id,+ owner_user_id=ctx.user.user_id,+ )+ result["task_id"] = task.task_id+ if telemetry_id:+ monitor_started = True+ asyncio.create_task(self._monitor_queue_processing(task.task_id, telemetry_id))+ else:+ task_tracker.start(task.task_id)+ task_tracker.complete(task.task_id, {})return resultfinally:- request_wait_tracker.cleanup(telemetry_id)+ if wait or not telemetry_id or not monitor_started:+ request_wait_tracker.cleanup(telemetry_id)+ unregister_wait_telemetry(telemetry_id)async def build_index(self, resource_uris: List[str], ctx: RequestContext, **kwargsdiff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.pyindex 824653968..27bdad1e7 100644--- a/openviking/service/task_tracker.py+++ b/openviking/service/task_tracker.py@@ -20,6 +20,7 @@ import threadingimport timefrom copy import deepcopyfrom dataclasses import asdict, dataclass, field+from datetime import datetime, timezonefrom enum import Enumfrom typing import Any, Dict, List, Optionalfrom uuid import uuid4@@ -57,6 +58,8 @@ class TaskRecord:"""Serialize for JSON response."""d = asdict(self)d["status"] = self.status.value+ d["created_at_iso"] = datetime.fromtimestamp(self.created_at, tz=timezone.utc).isoformat()+ d["updated_at_iso"] = datetime.fromtimestamp(self.updated_at, tz=timezone.utc).isoformat()d.pop("owner_account_id", None)d.pop("owner_user_id", None)return ddiff --git a/openviking/telemetry/resource_summary.py b/openviking/telemetry/resource_summary.pyindex 5f090f38d..bef74506b 100644--- a/openviking/telemetry/resource_summary.py+++ b/openviking/telemetry/resource_summary.py@@ -41,7 +41,7 @@ def _consume_semantic_dag_stats(telemetry_id: str, root_uri: str | None):def register_wait_telemetry(wait: bool) -> str:"""Register current telemetry collector for async queue consumers when needed."""handle = get_current_telemetry()- if not wait or not handle.telemetry_id:+ if not handle.telemetry_id:return ""if handle.enabled:register_telemetry(handle)diff --git a/tests/server/test_api_resources.py b/tests/server/test_api_resources.pyindex 3f6174ac2..06f7560e9 100644--- a/tests/server/test_api_resources.py+++ b/tests/server/test_api_resources.py@@ -3,6 +3,7 @@"""Tests for resource management endpoints."""+import asyncioimport zipfileimport httpx@@ -627,3 +628,204 @@ async def test_add_resource_rejects_temp_file_id_symlink(body = resp.json()assert body["status"] == "error"assert body["error"]["code"] == "PERMISSION_DENIED"+++async def test_add_resource_async_returns_task_id(+ client: httpx.AsyncClient,+ sample_markdown_file,+ upload_temp_dir,+):+ resp = await client.post(+ "/api/v1/resources",+ json={+ "temp_file_id": sample_markdown_file.name,+ "reason": "test async task tracking",+ "wait": False,+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert "task_id" in body["result"]+ assert body["result"]["task_id"]+++async def test_add_resource_sync_no_task_id(+ client: httpx.AsyncClient,+ sample_markdown_file,+ upload_temp_dir,+):+ resp = await client.post(+ "/api/v1/resources",+ json={+ "temp_file_id": sample_markdown_file.name,+ "reason": "test sync no task_id",+ "wait": True,+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert "task_id" not in body["result"]+++async def test_add_resource_async_task_queryable(+ client: httpx.AsyncClient,+ sample_markdown_file,+ upload_temp_dir,+):+ from openviking.service.task_tracker import reset_task_tracker++ reset_task_tracker()++ resp = await client.post(+ "/api/v1/resources",+ json={+ "temp_file_id": sample_markdown_file.name,+ "reason": "test task queryable",+ "wait": False,+ },+ )+ task_id = resp.json()["result"]["task_id"]++ await asyncio.sleep(2.0)++ task_resp = await client.get(f"/api/v1/tasks/{task_id}")+ assert task_resp.status_code == 200+ result = task_resp.json()["result"]+ assert result["task_id"] == task_id+ assert result["task_type"] == "add_resource"+ assert result["status"] in {"running", "completed", "failed"}+++async def test_add_resource_async_failure_cleans_up_tracker(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+ upload_temp_dir,+):+ """Regression: when wait=False and telemetry_id is registered but processor+ raises before task/monitor creation, RequestWaitTracker and telemetry+ registry must not leak state."""++ from openviking.server.identity import RequestContext, Role+ from openviking.telemetry.registry import _REGISTERED_TELEMETRY+ from openviking.telemetry.request_wait_tracker import get_request_wait_tracker+ from openviking_cli.session.user_id import UserIdentifier++ async def _failing_process_resource(**kwargs):+ raise RuntimeError("processor exploded")++ monkeypatch.setattr(+ service.resources._resource_processor, "process_resource", _failing_process_resource+ )++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)++ rwt_before = set(get_request_wait_tracker()._states.keys())+ tel_before = set(_REGISTERED_TELEMETRY.keys())++ try:+ await service.resources.add_resource(+ path="/tmp/fail_test.md",+ ctx=ctx,+ reason="failure cleanup test",+ wait=False,+ )+ except RuntimeError:+ pass++ rwt_after = set(get_request_wait_tracker()._states.keys())+ tel_after = set(_REGISTERED_TELEMETRY.keys())++ leaked_rwt = rwt_after - rwt_before+ assert not leaked_rwt, f"RequestWaitTracker leaked: {leaked_rwt}"++ leaked_telemetry = tel_after - tel_before+ assert not leaked_telemetry, f"Telemetry registry leaked: {leaked_telemetry}"+++async def test_add_resource_business_error_no_task(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+ upload_temp_dir,+):+ """When process_resource returns status=error, no task should be created."""++ from openviking.service.task_tracker import get_task_tracker++ async def _error_process_resource(**kwargs):+ return {"status": "error", "message": "unsupported format"}++ monkeypatch.setattr(+ service.resources._resource_processor, "process_resource", _error_process_resource+ )++ task_count_before = get_task_tracker().count()++ await client.post(+ "/api/v1/resources",+ json={+ "temp_file_id": "nonexistent",+ "reason": "test business error",+ "wait": False,+ },+ )++ task_count_after = get_task_tracker().count()+ assert task_count_after == task_count_before, "Business error should not create a task"+++async def test_monitor_marks_failed_on_queue_error(+ service,+ monkeypatch,+):+ """When queue processing has errors, _monitor_queue_processing should mark task as failed."""++ from openviking.server.identity import RequestContext, Role+ from openviking.service.task_tracker import get_task_tracker, reset_task_tracker+ from openviking.telemetry.request_wait_tracker import get_request_wait_tracker+ from openviking_cli.session.user_id import UserIdentifier++ reset_task_tracker()++ async def _fake_process_resource(**kwargs):+ return {"status": "success", "root_uri": "viking://resources/queue-err-test"}++ monkeypatch.setattr(+ service.resources._resource_processor, "process_resource", _fake_process_resource+ )++ original_wait_for_request = get_request_wait_tracker().wait_for_request++ async def _mock_wait_then_error(telemetry_id, timeout=None, poll_interval=0.05):+ rwt = get_request_wait_tracker()+ with rwt._lock:+ state = rwt._states.get(telemetry_id)+ if state:+ state.semantic_error_count = 1+ state.semantic_errors.append("semantic processing failed")+ state.pending_semantic_roots.clear()+ state.pending_embedding_roots.clear()+ await original_wait_for_request(telemetry_id, timeout=timeout, poll_interval=0.01)++ monkeypatch.setattr(get_request_wait_tracker(), "wait_for_request", _mock_wait_then_error)++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)+ result = await service.resources.add_resource(+ path="/tmp/queue_err_test.md",+ ctx=ctx,+ reason="queue error test",+ wait=False,+ )++ task_id = result.get("task_id")+ assert task_id, "Expected task_id in result"++ await asyncio.sleep(1.0)++ task = get_task_tracker().get(task_id)+ assert task is not None+ assert task.status.value == "failed", f"Expected failed, got {task.status.value}"+ assert "queue processing failed" in task.errordiff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.pyindex b9ec947e4..43e96ae66 100644--- a/tests/service/test_resource_service_watch.py+++ b/tests/service/test_resource_service_watch.py@@ -230,6 +230,34 @@ class TestWatchTaskConflict:assert "already being monitored" in str(exc_info.value)assert to_uri in str(exc_info.value)+ @pytest.mark.asyncio+ async def test_conflict_does_not_create_async_task(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """A rejected watch request must not leave behind a user-invisible task."""+ from openviking.service.task_tracker import get_task_tracker, reset_task_tracker++ reset_task_tracker()+ to_uri = "viking://resources/conflict_no_task"++ await resource_service.add_resource(+ path="/test/path1",+ ctx=request_context,+ to=to_uri,+ watch_interval=30.0,+ )+ task_count_before = get_task_tracker().count()++ with pytest.raises(ConflictError):+ await resource_service.add_resource(+ path="/test/path2",+ ctx=request_context,+ to=to_uri,+ watch_interval=45.0,+ )++ assert get_task_tracker().count() == task_count_before+@pytest.mark.asyncioasync def test_conflict_when_task_exists_but_hidden_by_permission(self, resource_service: ResourceService, request_context: RequestContextdiff --git a/tests/test_session_task_tracking.py b/tests/test_session_task_tracking.pyindex 1c9b77c7c..c8c2d15b3 100644--- a/tests/test_session_task_tracking.py+++ b/tests/test_session_task_tracking.py@@ -321,3 +321,191 @@ async def test_error_sanitized_in_task(api_client):error = task_resp.json()["result"]["error"]assert "superSecretKey" not in errorassert "[REDACTED]" in error+++# ── add_resource task tracking ──+++async def test_add_resource_async_returns_task_id(api_client):+ """add_resource with wait=False should return a task_id."""+ client, service = api_client++ async def fake_add_resource(**kwargs):+ tracker = get_task_tracker()+ root_uri = "viking://resources/async-test"+ task = tracker.create(+ "add_resource",+ resource_id=root_uri,+ owner_account_id=kwargs["ctx"].account_id,+ owner_user_id=kwargs["ctx"].user.user_id,+ )+ tracker.start(task.task_id)+ tracker.complete(task.task_id, {"root_uri": root_uri})+ return {"status": "success", "root_uri": root_uri, "task_id": task.task_id}++ service.resources.add_resource = fake_add_resource++ from openviking.server.identity import RequestContext, Role+ from openviking_cli.session.user_id import UserIdentifier++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)+ result = await service.resources.add_resource(ctx=ctx, reason="test async resource")++ assert "task_id" in result+ assert result["task_id"]++ task_resp = await client.get(f"/api/v1/tasks/{result['task_id']}")+ assert task_resp.status_code == 200+ task_data = task_resp.json()["result"]+ assert task_data["task_type"] == "add_resource"+++async def test_add_resource_sync_no_task_id(api_client):+ """add_resource with wait=True should NOT return a task_id."""+ client, service = api_client++ async def fake_add_resource(**kwargs):+ root_uri = "viking://resources/sync-test"+ return {"status": "success", "root_uri": root_uri}++ service.resources.add_resource = fake_add_resource++ from openviking.server.identity import RequestContext, Role+ from openviking_cli.session.user_id import UserIdentifier++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)+ result = await service.resources.add_resource(ctx=ctx, reason="test sync resource")++ assert "task_id" not in result+++async def test_add_resource_async_task_lifecycle(api_client):+ """Async add_resource task should transition pending→running→completed."""+ client, service = api_client++ async def fake_add_resource(**kwargs):+ tracker = get_task_tracker()+ root_uri = "viking://resources/test-resource"+ task = tracker.create(+ "add_resource",+ resource_id=root_uri,+ owner_account_id=kwargs["ctx"].account_id,+ owner_user_id=kwargs["ctx"].user.user_id,+ )++ async def _background():+ tracker.start(task.task_id)+ await asyncio.sleep(0.05)+ tracker.complete(task.task_id, {"root_uri": root_uri})++ asyncio.create_task(_background())+ return {"status": "success", "root_uri": root_uri, "task_id": task.task_id}++ service.resources.add_resource = fake_add_resource++ from openviking.server.identity import RequestContext, Role+ from openviking_cli.session.user_id import UserIdentifier++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)+ result = await service.resources.add_resource(ctx=ctx, reason="test lifecycle")++ task_id = result["task_id"]++ task_resp = await client.get(f"/api/v1/tasks/{task_id}")+ assert task_resp.status_code == 200+ assert task_resp.json()["result"]["status"] in {"pending", "running"}++ await asyncio.sleep(0.2)++ task_resp = await client.get(f"/api/v1/tasks/{task_id}")+ assert task_resp.status_code == 200+ task_data = task_resp.json()["result"]+ assert task_data["status"] == "completed"+ assert task_data["task_type"] == "add_resource"+++async def test_add_resource_task_list_filter(api_client):+ """add_resource tasks should appear in task list filtered by type."""+ client, service = api_client++ async def fake_add_resource(**kwargs):+ tracker = get_task_tracker()+ root_uri = "viking://resources/filter-test"+ task = tracker.create(+ "add_resource",+ resource_id=root_uri,+ owner_account_id=kwargs["ctx"].account_id,+ owner_user_id=kwargs["ctx"].user.user_id,+ )+ tracker.start(task.task_id)+ tracker.complete(task.task_id, {"root_uri": root_uri})+ return {"status": "success", "root_uri": root_uri, "task_id": task.task_id}++ service.resources.add_resource = fake_add_resource++ from openviking.server.identity import RequestContext, Role+ from openviking_cli.session.user_id import UserIdentifier++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)+ result = await service.resources.add_resource(ctx=ctx, reason="test list filter")+ task_id = result["task_id"]++ resp = await client.get("/api/v1/tasks", params={"task_type": "add_resource"})+ assert resp.status_code == 200+ tasks = resp.json()["result"]+ matching = [t for t in tasks if t["task_id"] == task_id]+ assert len(matching) >= 1+ assert matching[0]["task_type"] == "add_resource"+++# ── add_skill task tracking ──+++async def test_add_skill_async_returns_task_id(api_client):+ """add_skill with wait=False should return a task_id."""+ client, service = api_client++ async def fake_add_skill(**kwargs):+ tracker = get_task_tracker()+ task = tracker.create(+ "add_skill",+ owner_account_id=kwargs["ctx"].account_id,+ owner_user_id=kwargs["ctx"].user.user_id,+ )+ tracker.start(task.task_id)+ tracker.complete(task.task_id, {})+ return {"status": "success", "task_id": task.task_id}++ service.resources.add_skill = fake_add_skill++ from openviking.server.identity import RequestContext, Role+ from openviking_cli.session.user_id import UserIdentifier++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)+ result = await service.resources.add_skill(data="test skill", ctx=ctx)++ assert "task_id" in result+ assert result["task_id"]++ task_resp = await client.get(f"/api/v1/tasks/{result['task_id']}")+ assert task_resp.status_code == 200+ task_data = task_resp.json()["result"]+ assert task_data["task_type"] == "add_skill"+++async def test_add_skill_sync_no_task_id(api_client):+ """add_skill with wait=True should NOT return a task_id."""+ client, service = api_client++ async def fake_add_skill(**kwargs):+ return {"status": "success"}++ service.resources.add_skill = fake_add_skill++ from openviking.server.identity import RequestContext, Role+ from openviking_cli.session.user_id import UserIdentifier++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)+ result = await service.resources.add_skill(data="test skill", ctx=ctx, wait=True)++ assert "task_id" not in resultdiff --git a/tests/test_task_tracker.py b/tests/test_task_tracker.pyindex 87fd9de2f..e3eaf597f 100644--- a/tests/test_task_tracker.py+++ b/tests/test_task_tracker.py@@ -242,6 +242,10 @@ def test_to_dict(tracker: TaskTracker):assert d["task_type"] == "session_commit"assert d["resource_id"] == "s1"assert isinstance(d["created_at"], float)+ assert isinstance(d["updated_at"], float)+ assert isinstance(d["created_at_iso"], str)+ assert "T" in d["created_at_iso"]+ assert isinstance(d["updated_at_iso"], str)assert "owner_account_id" not in dassert "owner_user_id" not in d