Skip to content

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

feat: open studio metrics to users (#2882)

yufeng65f80c46c840
diff --git a/openviking/observability/usage_audit/api_service.py b/openviking/observability/usage_audit/api_service.py
index 05db1863d..95e517bcc 100644
--- a/openviking/observability/usage_audit/api_service.py
+++ b/openviking/observability/usage_audit/api_service.py
@@ -12,7 +12,7 @@ from __future__ import annotations
from datetime import date, datetime
from typing import Any
-from openviking.server.identity import RequestContext
+from openviking.server.identity import RequestContext, Role
from openviking_cli.exceptions import InvalidArgumentError
from .inventory import ContextInventoryProvider
@@ -37,6 +37,18 @@ class UsageAuditQueryService:
def _resolve_tz(self, timezone_name: str | None):
return resolve_user_timezone(timezone_name, fallback=self._default_tz)
+ @staticmethod
+ def _usage_user_id(ctx: RequestContext) -> str | None:
+ if ctx.role in (Role.ROOT, Role.ADMIN):
+ return None
+ return ctx.user.user_id
+
+ @staticmethod
+ def _audit_user_id(ctx: RequestContext) -> str | None:
+ if ctx.role in (Role.ROOT, Role.ADMIN):
+ return None
+ return ctx.user.user_id
+
def today(self, timezone_name: str | None = None) -> str:
"""Return today's date in the viewer's timezone (or the default)."""
tz = self._resolve_tz(timezone_name)
@@ -49,11 +61,12 @@ class UsageAuditQueryService:
tz = self._resolve_tz(timezone_name)
today = datetime.now(tz).date().isoformat()
context_counts = await self._inventory.get_counts(ctx)
+ user_id = self._usage_user_id(ctx)
today_tokens = await self._store.get_today_tokens(
- account_id=ctx.account_id, user_date=today, tz=tz
+ account_id=ctx.account_id, user_date=today, tz=tz, user_id=user_id
)
today_retrievals = await self._store.get_today_retrievals(
- account_id=ctx.account_id, user_date=today, tz=tz
+ account_id=ctx.account_id, user_date=today, tz=tz, user_id=user_id
)
return {
"context_counts": context_counts,
@@ -79,6 +92,7 @@ class UsageAuditQueryService:
end_user_date=end_date,
bucket=bucket,
tz=tz,
+ user_id=self._usage_user_id(ctx),
)
return {"start_date": start_date, "end_date": end_date, "bucket": bucket, "items": items}
@@ -100,6 +114,7 @@ class UsageAuditQueryService:
end_user_date=end_date,
bucket=bucket,
tz=tz,
+ user_id=self._usage_user_id(ctx),
)
return {"start_date": start_date, "end_date": end_date, "bucket": bucket, "items": items}
@@ -120,6 +135,7 @@ class UsageAuditQueryService:
"""
return await self._store.query_audit_logs(
account_id=ctx.account_id,
+ user_id=self._audit_user_id(ctx),
request_id=request_id,
statuses=statuses,
api_types=api_types,
diff --git a/openviking/observability/usage_audit/sqlite_store.py b/openviking/observability/usage_audit/sqlite_store.py
index 16027b9be..67d469fa3 100644
--- a/openviking/observability/usage_audit/sqlite_store.py
+++ b/openviking/observability/usage_audit/sqlite_store.py
@@ -307,16 +307,27 @@ class SQLiteUsageAuditStore:
# ------------------------------------------------------------------
async def get_today_tokens(
- self, *, account_id: str, user_date: str, tz: tzinfo
+ self,
+ *,
+ account_id: str,
+ user_date: str,
+ tz: tzinfo,
+ user_id: str | None = None,
) -> dict[str, int]:
async with self._lock:
- return await asyncio.to_thread(self._get_today_tokens_sync, account_id, user_date, tz)
+ return await asyncio.to_thread(
+ self._get_today_tokens_sync, account_id, user_date, tz, user_id
+ )
- def _get_today_tokens_sync(self, account_id: str, user_date: str, tz: tzinfo) -> dict[str, int]:
+ def _get_today_tokens_sync(
+ self, account_id: str, user_date: str, tz: tzinfo, user_id: str | None
+ ) -> dict[str, int]:
assert self._conn is not None
day = date.fromisoformat(user_date)
utc_start, utc_end = _user_day_window_utc(day, tz)
- rows = self._fetch_hourly_token_rows(account_id, utc_start, utc_end)
+ rows = self._fetch_hourly_token_rows(
+ account_id, utc_start, utc_end, user_id=user_id
+ )
result = {"vlm_input": 0, "vlm_output": 0, "embedding_input": 0}
for source, token_type, _, _, total in rows:
key = f"{source}_{token_type}"
@@ -326,21 +337,28 @@ class SQLiteUsageAuditStore:
return result
async def get_today_retrievals(
- self, *, account_id: str, user_date: str, tz: tzinfo
+ self,
+ *,
+ account_id: str,
+ user_date: str,
+ tz: tzinfo,
+ user_id: str | None = None,
) -> dict[str, int]:
async with self._lock:
return await asyncio.to_thread(
- self._get_today_retrievals_sync, account_id, user_date, tz
+ self._get_today_retrievals_sync, account_id, user_date, tz, user_id
)
def _get_today_retrievals_sync(
- self, account_id: str, user_date: str, tz: tzinfo
+ self, account_id: str, user_date: str, tz: tzinfo, user_id: str | None
) -> dict[str, int]:
assert self._conn is not None
day = date.fromisoformat(user_date)
utc_start, utc_end = _user_day_window_utc(day, tz)
result = {"find": 0, "search": 0}
- for operation, total in self._fetch_hourly_retrieval_rows(account_id, utc_start, utc_end):
+ for operation, total in self._fetch_hourly_retrieval_rows(
+ account_id, utc_start, utc_end, user_id=user_id
+ ):
if operation in result:
result[operation] += total
result["total"] = sum(result.values())
@@ -354,6 +372,7 @@ class SQLiteUsageAuditStore:
end_user_date: str,
bucket: str,
tz: tzinfo,
+ user_id: str | None = None,
) -> list[dict[str, Any]]:
async with self._lock:
return await asyncio.to_thread(
@@ -363,6 +382,7 @@ class SQLiteUsageAuditStore:
end_user_date,
bucket,
tz,
+ user_id,
)
def _get_token_series_sync(
@@ -372,6 +392,7 @@ class SQLiteUsageAuditStore:
end_user_date: str,
bucket: str,
tz: tzinfo,
+ user_id: str | None,
) -> list[dict[str, Any]]:
assert self._conn is not None
start_day = date.fromisoformat(start_user_date)
@@ -383,7 +404,7 @@ class SQLiteUsageAuditStore:
for d in _date_range(start_user_date, end_user_date)
}
for source, token_type, date_utc, hour_utc, total in self._fetch_hourly_token_rows(
- account_id, utc_start, utc_end
+ account_id, utc_start, utc_end, user_id=user_id
):
local_date = (
datetime(
@@ -414,6 +435,7 @@ class SQLiteUsageAuditStore:
end_user_date: str,
bucket: str,
tz: tzinfo,
+ user_id: str | None = None,
) -> list[dict[str, Any]]:
async with self._lock:
return await asyncio.to_thread(
@@ -423,6 +445,7 @@ class SQLiteUsageAuditStore:
end_user_date,
bucket,
tz,
+ user_id,
)
def _get_context_commit_heatmap_sync(
@@ -432,6 +455,7 @@ class SQLiteUsageAuditStore:
end_user_date: str,
bucket: str,
tz: tzinfo,
+ user_id: str | None,
) -> list[dict[str, Any]]:
assert self._conn is not None
bucket_size = 4 if bucket == "4h" else 1
@@ -443,11 +467,13 @@ class SQLiteUsageAuditStore:
for event_date in _date_range(start_user_date, end_user_date):
for hour in range(0, 24, bucket_size):
rows[(event_date, hour)] = self._empty_context_row(event_date, hour)
+ user_filter, user_params = self._user_scope_sql(user_id)
cur = self._conn.execute(
"""
SELECT date_utc, hour_utc, operation, SUM(count) AS total
FROM usage_context_write_bucket
WHERE account_id = ?
+ {user_filter}
AND (
date_utc > ? OR (date_utc = ? AND hour_utc >= ?)
)
@@ -455,9 +481,10 @@ class SQLiteUsageAuditStore:
date_utc < ? OR (date_utc = ? AND hour_utc < ?)
)
GROUP BY date_utc, hour_utc, operation
- """,
+ """.format(user_filter=user_filter),
(
account_id,
+ *user_params,
utc_start.date().isoformat(),
utc_start.date().isoformat(),
utc_start.hour,
@@ -488,23 +515,31 @@ class SQLiteUsageAuditStore:
return [rows[key] for key in sorted(rows) if key[0] in in_range]
def _fetch_hourly_token_rows(
- self, account_id: str, utc_start: datetime, utc_end: datetime
+ self,
+ account_id: str,
+ utc_start: datetime,
+ utc_end: datetime,
+ *,
+ user_id: str | None = None,
) -> list[tuple[str, str, str, int, int]]:
"""Return rows [(source, token_type, date_utc, hour_utc, total)]."""
assert self._conn is not None
utc_start_d = utc_start.date().isoformat()
utc_end_d = utc_end.date().isoformat()
+ user_filter, user_params = self._user_scope_sql(user_id)
cur = self._conn.execute(
"""
SELECT source, token_type, date_utc, hour_utc, SUM(token_count) AS total
FROM usage_token_hourly
WHERE account_id = ?
+ {user_filter}
AND (date_utc > ? OR (date_utc = ? AND hour_utc >= ?))
AND (date_utc < ? OR (date_utc = ? AND hour_utc < ?))
GROUP BY source, token_type, date_utc, hour_utc
- """,
+ """.format(user_filter=user_filter),
(
account_id,
+ *user_params,
utc_start_d,
utc_start_d,
utc_start.hour,
@@ -525,24 +560,32 @@ class SQLiteUsageAuditStore:
]
def _fetch_hourly_retrieval_rows(
- self, account_id: str, utc_start: datetime, utc_end: datetime
+ self,
+ account_id: str,
+ utc_start: datetime,
+ utc_end: datetime,
+ *,
+ user_id: str | None = None,
) -> list[tuple[str, int]]:
"""Return [(operation, total_request_count)] for successful retrievals."""
assert self._conn is not None
utc_start_d = utc_start.date().isoformat()
utc_end_d = utc_end.date().isoformat()
+ user_filter, user_params = self._user_scope_sql(user_id)
cur = self._conn.execute(
"""
SELECT operation, SUM(request_count) AS total
FROM usage_retrieval_hourly
WHERE account_id = ?
+ {user_filter}
AND status = 'success'
AND (date_utc > ? OR (date_utc = ? AND hour_utc >= ?))
AND (date_utc < ? OR (date_utc = ? AND hour_utc < ?))
GROUP BY operation
- """,
+ """.format(user_filter=user_filter),
(
account_id,
+ *user_params,
utc_start_d,
utc_start_d,
utc_start.hour,
@@ -553,6 +596,12 @@ class SQLiteUsageAuditStore:
)
return [(str(row["operation"]), int(row["total"] or 0)) for row in cur.fetchall()]
+ @staticmethod
+ def _user_scope_sql(user_id: str | None) -> tuple[str, tuple[str, ...]]:
+ if not user_id:
+ return "", ()
+ return "AND user_id = ?", (user_id,)
+
@staticmethod
def _empty_context_row(event_date: str, hour: int) -> dict[str, Any]:
return {
@@ -569,6 +618,7 @@ class SQLiteUsageAuditStore:
self,
*,
account_id: str,
+ user_id: str | None = None,
request_id: str | None = None,
statuses: list[str] | None = None,
api_types: list[str] | None = None,
@@ -579,6 +629,7 @@ class SQLiteUsageAuditStore:
return await asyncio.to_thread(
self._query_audit_logs_sync,
account_id,
+ user_id,
request_id,
statuses or [],
api_types or [],
@@ -589,6 +640,7 @@ class SQLiteUsageAuditStore:
def _query_audit_logs_sync(
self,
account_id: str,
+ user_id: str | None,
request_id: str | None,
statuses: list[str],
api_types: list[str],
@@ -598,6 +650,9 @@ class SQLiteUsageAuditStore:
assert self._conn is not None
where = ["account_id = ?"]
params: list[Any] = [account_id]
+ if user_id:
+ where.append("user_id = ?")
+ params.append(user_id)
if request_id:
where.append("request_id = ?")
params.append(request_id)
diff --git a/openviking/observability/usage_audit/store.py b/openviking/observability/usage_audit/store.py
index 2ea423719..c42ff89ec 100644
--- a/openviking/observability/usage_audit/store.py
+++ b/openviking/observability/usage_audit/store.py
@@ -27,14 +27,24 @@ class UsageAuditStore(Protocol):
"""Persist a batch of observability events."""
async def get_today_tokens(
- self, *, account_id: str, user_date: str, tz: tzinfo
+ self,
+ *,
+ account_id: str,
+ user_date: str,
+ tz: tzinfo,
+ user_id: str | None = None,
) -> dict[str, int]:
- """Return token totals for one account and viewer-local date."""
+ """Return token totals for one account/user scope and viewer-local date."""
async def get_today_retrievals(
- self, *, account_id: str, user_date: str, tz: tzinfo
+ self,
+ *,
+ account_id: str,
+ user_date: str,
+ tz: tzinfo,
+ user_id: str | None = None,
) -> dict[str, int]:
- """Return successful find/search counts for one account and date."""
+ """Return successful find/search counts for one account/user scope and date."""
async def get_token_series(
self,
@@ -44,8 +54,9 @@ class UsageAuditStore(Protocol):
end_user_date: str,
bucket: str,
tz: tzinfo,
+ user_id: str | None = None,
) -> list[dict[str, Any]]:
- """Return token series rows for a viewer-local date range."""
+ """Return token series rows for a viewer-local date range and user scope."""
async def get_context_commit_heatmap(
self,
@@ -55,13 +66,15 @@ class UsageAuditStore(Protocol):
end_user_date: str,
bucket: str,
tz: tzinfo,
+ user_id: str | None = None,
) -> list[dict[str, Any]]:
- """Return context write bucket rows for a viewer-local date range."""
+ """Return context write bucket rows for a viewer-local date range and user scope."""
async def query_audit_logs(
self,
*,
account_id: str,
+ user_id: str | None = None,
request_id: str | None = None,
statuses: list[str] | None = None,
api_types: list[str] | None = None,
diff --git a/openviking/server/routers/console.py b/openviking/server/routers/console.py
index 4a7a01ff6..706ef96d5 100644
--- a/openviking/server/routers/console.py
+++ b/openviking/server/routers/console.py
@@ -51,7 +51,7 @@ async def dashboard_summary(
None,
description="IANA viewer timezone (e.g. Asia/Shanghai). Defaults to server tz.",
),
- _ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),
+ _ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN, Role.USER),
):
"""Return Dashboard top-card data."""
service = _runtime_service(request)
@@ -70,7 +70,7 @@ async def token_series(
None,
description="IANA viewer timezone (e.g. Asia/Shanghai). Defaults to server tz.",
),
- _ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),
+ _ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN, Role.USER),
):
"""Return token usage trend for a date range."""
service = _runtime_service(request)
@@ -96,7 +96,7 @@ async def context_commits(
None,
description="IANA viewer timezone (e.g. Asia/Shanghai). Defaults to server tz.",
),
- _ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),
+ _ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN, Role.USER),
):
"""Return context write heatmap rows for a date range."""
service = _runtime_service(request)
@@ -120,7 +120,7 @@ async def audit_logs(
request_id: Optional[str] = Query(None),
status: Optional[list[str]] = Query(None),
api_type: Optional[list[str]] = Query(None),
- _ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),
+ _ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN, Role.USER),
):
"""Return filtered request audit logs."""
service = _runtime_service(request)
diff --git a/tests/observability/test_console_router.py b/tests/observability/test_console_router.py
index 15e343c86..0859fd9e8 100644
--- a/tests/observability/test_console_router.py
+++ b/tests/observability/test_console_router.py
@@ -130,7 +130,32 @@ async def test_console_router_splits_audit_filters():
@pytest.mark.asyncio
-async def test_console_router_rejects_regular_user():
+async def test_console_router_allows_regular_user_dashboard_metrics():
+ service = FakeConsoleService()
+ transport = httpx.ASGITransport(
+ app=_app_with_runtime(FakeRuntime(service), request_context=_user_ctx)
+ )
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ summary = await client.get("/api/v1/console/dashboard/summary")
+ tokens = await client.get(
+ "/api/v1/console/tokens",
+ params={"start_date": "2026-05-01", "end_date": "2026-05-12"},
+ )
+ commits = await client.get(
+ "/api/v1/console/context-commits",
+ params={"start_date": "2026-05-01", "end_date": "2026-05-12"},
+ )
+
+ assert summary.status_code == 200
+ assert tokens.status_code == 200
+ assert commits.status_code == 200
+ assert service.dashboard_call["ctx"].role == Role.USER
+ assert service.token_series_call["ctx"].role == Role.USER
+ assert service.context_commits_call["ctx"].role == Role.USER
+
+
+async def test_console_router_allows_regular_user_scoped_audit_logs():
service = FakeConsoleService()
transport = httpx.ASGITransport(
app=_app_with_runtime(FakeRuntime(service), request_context=_user_ctx)
@@ -138,9 +163,9 @@ async def test_console_router_rejects_regular_user():
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
response = await client.get("/api/v1/console/audit")
- assert response.status_code == 403
- assert response.json()["error"]["code"] == "PERMISSION_DENIED"
- assert service.audit_call is None
+ assert response.status_code == 200
+ assert response.json()["status"] == "ok"
+ assert service.audit_call["ctx"].role == Role.USER
@pytest.mark.asyncio
diff --git a/tests/observability/test_usage_audit_api_service.py b/tests/observability/test_usage_audit_api_service.py
new file mode 100644
index 000000000..ab47e1994
--- /dev/null
+++ b/tests/observability/test_usage_audit_api_service.py
@@ -0,0 +1,91 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from openviking.observability.usage_audit.api_service import UsageAuditQueryService
+from openviking.server.identity import RequestContext, Role
+from openviking_cli.session.user_id import UserIdentifier
+
+
+class FakeStore:
+ def __init__(self) -> None:
+ self.audit_call: dict[str, Any] | None = None
+ self.token_series_call: dict[str, Any] | None = None
+
+ async def get_token_series(self, **kwargs):
+ self.token_series_call = kwargs
+ return []
+
+ async def query_audit_logs(self, **kwargs):
+ self.audit_call = kwargs
+ return {"total": 0, "success_rate": 0.0, "page": 1, "page_size": 10, "items": []}
+
+
+class FakeInventory:
+ async def get_counts(self, _ctx):
+ return {}
+
+
+async def test_admin_metrics_and_audit_logs_are_account_wide():
+ store = FakeStore()
+ service = UsageAuditQueryService(store=store, inventory=FakeInventory(), timezone_name="UTC")
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="acct-1", user_id="admin-1"),
+ role=Role.ADMIN,
+ )
+
+ await service.token_series(
+ ctx=ctx,
+ start_date="2026-05-01",
+ end_date="2026-05-01",
+ bucket="day",
+ )
+ await service.audit_logs(
+ ctx=ctx,
+ request_id=None,
+ statuses=[],
+ api_types=[],
+ page=1,
+ page_size=10,
+ )
+
+ assert store.token_series_call is not None
+ assert store.audit_call is not None
+ assert store.token_series_call["user_id"] is None
+ assert store.audit_call["user_id"] is None
+
+
+async def test_regular_user_metrics_and_audit_logs_use_current_identity():
+ store = FakeStore()
+ service = UsageAuditQueryService(store=store, inventory=FakeInventory(), timezone_name="UTC")
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="acct-1", user_id="alice"),
+ role=Role.USER,
+ )
+
+ await service.token_series(
+ ctx=ctx,
+ start_date="2026-05-01",
+ end_date="2026-05-01",
+ bucket="day",
+ )
+ await service.audit_logs(
+ ctx=ctx,
+ request_id=None,
+ statuses=[],
+ api_types=[],
+ page=1,
+ page_size=10,
+ )
+
+ assert store.token_series_call is not None
+ assert store.audit_call is not None
+ assert store.token_series_call["user_id"] == "alice"
+ assert store.audit_call["user_id"] == "alice"
diff --git a/tests/observability/test_usage_audit_store.py b/tests/observability/test_usage_audit_store.py
index bd07a0504..ae59ad40e 100644
--- a/tests/observability/test_usage_audit_store.py
+++ b/tests/observability/test_usage_audit_store.py
@@ -20,6 +20,7 @@ def _event(
payload: dict,
*,
ts: datetime | None = None,
+ user_id: str = "user-1",
) -> ObservabilityEvent:
return ObservabilityEvent(
event_name=event_name,
@@ -27,7 +28,7 @@ def _event(
timestamp=ts or datetime(2026, 5, 12, 1, 2, 3, tzinfo=timezone.utc),
request_id=payload.get("request_id"),
account_id="acct-1",
- user_id="user-1",
+ user_id=user_id,
)
@@ -124,6 +125,16 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):
"completion_tokens": 0,
},
),
+ _event(
+ "embedding.call",
+ {
+ "provider": "p",
+ "model_name": "e",
+ "prompt_tokens": 100,
+ "completion_tokens": 0,
+ },
+ user_id="user-2",
+ ),
_event(
"http.request",
{
@@ -134,6 +145,17 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):
"duration_seconds": 0.1,
},
),
+ _event(
+ "http.request",
+ {
+ "request_id": "req-search-user-2",
+ "method": "POST",
+ "route": "/api/v1/search/search",
+ "status": "200",
+ "duration_seconds": 0.1,
+ },
+ user_id="user-2",
+ ),
_event(
"http.request",
{
@@ -144,6 +166,17 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):
"duration_seconds": 0.1,
},
),
+ _event(
+ "http.request",
+ {
+ "request_id": "req-message-user-2",
+ "method": "POST",
+ "route": "/api/v1/sessions/{session_id}/messages",
+ "status": "200",
+ "duration_seconds": 0.1,
+ },
+ user_id="user-2",
+ ),
_event(
"http.request",
{
@@ -179,6 +212,14 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):
assert await store.get_today_tokens(
account_id="acct-1", user_date="2026-05-12", tz=UTC
+ ) == {
+ "vlm_input": 3,
+ "vlm_output": 2,
+ "embedding_input": 105,
+ "total": 110,
+ }
+ assert await store.get_today_tokens(
+ account_id="acct-1", user_id="user-1", user_date="2026-05-12", tz=UTC
) == {
"vlm_input": 3,
"vlm_output": 2,
@@ -187,6 +228,13 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):
}
assert await store.get_today_retrievals(
account_id="acct-1", user_date="2026-05-12", tz=UTC
+ ) == {
+ "find": 1,
+ "search": 1,
+ "total": 2,
+ }
+ assert await store.get_today_retrievals(
+ account_id="acct-1", user_id="user-1", user_date="2026-05-12", tz=UTC
) == {
"find": 1,
"search": 0,
@@ -199,11 +247,31 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):
bucket="hour",
tz=UTC,
)
+ account_commits = commits
+ commits = await store.get_context_commit_heatmap(
+ account_id="acct-1",
+ user_id="user-1",
+ start_user_date="2026-05-12",
+ end_user_date="2026-05-12",
+ bucket="hour",
+ tz=UTC,
+ )
+ assert any(
+ row["hour"] == 1 and row["session_add_message"] == 2 for row in account_commits
+ )
assert any(row["hour"] == 1 and row["session_add_message"] == 1 for row in commits)
audit = await store.query_audit_logs(account_id="acct-1")
+ assert audit["total"] == 4
+ assert audit["success_rate"] == 1.0
+ assert {item["api_type"] for item in audit["items"]} == {
+ "search.find",
+ "search.search",
+ "sessions",
+ }
+ audit = await store.query_audit_logs(account_id="acct-1", user_id="user-1")
assert audit["total"] == 2
assert audit["success_rate"] == 1.0
- assert {item["api_type"] for item in audit["items"]} == {"search.find", "sessions"}
+ assert {item["request_id"] for item in audit["items"]} == {"req-find", "req-message"}
finally:
await store.close()
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index 19bea98dd..3e225e83f 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -346,7 +346,6 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
select: (state) => state.location.pathname,
})
const { setTheme, resolvedTheme } = useTheme()
- const { connectionRole } = useAppConnection()
const currentLanguage = resolveLanguage(
i18n.resolvedLanguage ?? i18n.language,
)
@@ -355,15 +354,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
const settingsActive = pathname === '/settings'
const crossDeviceVerifyActive =
pathname === '/oauth/verify' || pathname.startsWith('/oauth/verify/')
- const visibleNavItems = React.useMemo(
- () =>
- connectionRole === 'admin' || connectionRole === 'root'
- ? NAV_ITEMS
- : NAV_ITEMS.filter(
- (item) => item.id !== 'home' && item.id !== 'requestLogs',
- ),
- [connectionRole],
- )
+ const visibleNavItems = NAV_ITEMS
function openCrossDeviceVerify(): void {
if (crossDeviceVerifyActive) {
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index 858a88ea7..36881fa74 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -182,8 +182,10 @@ const en = {
title: 'User management',
},
page: {
- description:
+ adminDescription:
'Configure the active OpenViking Studio identity and manage accounts, users, and API keys.',
+ description:
+ 'Configure the OpenViking Studio server URL and API key, then view data for the current identity.',
title: 'Connection & Identity',
},
placeholders: {
@@ -309,7 +311,7 @@ const en = {
requestLogs: {
clear: 'Clear',
description:
- 'Inspect server-side audited API requests, including status, latency, and request identifiers.',
+ 'Inspect server-side audited API requests for the current identity, including status, latency, and request identifiers.',
disabled: {
description:
'Usage/Audit is not initialized, so server-side request logs are unavailable.',
@@ -351,6 +353,11 @@ const en = {
refresh: 'Refresh',
reset: 'Reset',
searchPlaceholder: 'Filter method, path, or status',
+ scope: {
+ currentIdentity: 'Current scope: Current API key identity',
+ currentIdentityWithName:
+ 'Current scope: Current API key identity ({{identity}})',
+ },
status: {
error: 'ERR',
pending: 'PENDING',
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index 904591001..6d86998f5 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -182,8 +182,10 @@ const zhCN = {
title: '用户管理',
},
page: {
+ adminDescription:
+ '配置当前 OpenViking Studio 身份,并管理账号、用户和 API key。',
description:
- '配置当前 OpenViking Studio 身份,并管理 accounts、users 和 API keys。',
+ '配置当前 OpenViking Studio 的服务地址和 API key,查看当前身份下的数据。',
title: '连接与身份',
},
placeholders: {
@@ -305,7 +307,8 @@ const zhCN = {
},
requestLogs: {
clear: '清空',
- description: '查看服务端审计到的 API 请求,包括状态、耗时和请求标识。',
+ description:
+ '查看当前身份下服务端审计到的 API 请求,包括状态、耗时和请求标识。',
disabled: {
description: 'Usage/Audit 未初始化,暂无服务端请求日志。',
title: '审计日志不可用',
@@ -345,6 +348,10 @@ const zhCN = {
refresh: '刷新',
reset: '重置',
searchPlaceholder: '筛选方法、路径或状态码',
+ scope: {
+ currentIdentity: '当前范围:当前 API key 身份',
+ currentIdentityWithName: '当前范围:当前 API key 身份({{identity}})',
+ },
status: {
error: 'ERR',
pending: 'PENDING',
diff --git a/web-studio/src/lib/ov-client/client.test.ts b/web-studio/src/lib/ov-client/client.test.ts
new file mode 100644
index 000000000..029e503ea
--- /dev/null
+++ b/web-studio/src/lib/ov-client/client.test.ts
@@ -0,0 +1,99 @@
+import axios from 'axios'
+import type { AxiosRequestConfig } from 'axios'
+import { describe, expect, it } from 'vitest'
+
+import { createOvClient } from './client'
+
+function readRequestHeader(config: AxiosRequestConfig, name: string): string {
+ const headers = config.headers as
+ | { get?: (headerName: string) => unknown }
+ | Record<string, unknown>
+ | undefined
+ if (!headers) {
+ return ''
+ }
+ if ('get' in headers && typeof headers.get === 'function') {
+ const value = headers.get(name)
+ return typeof value === 'string' ? value : ''
+ }
+ const value = headers[name] ?? headers[name.toLowerCase()]
+ return typeof value === 'string' ? value : ''
+}
+
+function createRecordingClient() {
+ const requests: AxiosRequestConfig[] = []
+ const instance = axios.create({
+ adapter: async (config) => {
+ requests.push(config)
+ return {
+ config,
+ data: { result: {}, status: 'ok' },
+ headers: {},
+ status: 200,
+ statusText: 'OK',
+ }
+ },
+ })
+ const client = createOvClient({
+ axios: instance,
+ baseUrl: 'http://openviking.test',
+ bindSdkClient: false,
+ })
+ return { client, requests }
+}
+
+describe('createOvClient API key selection', () => {
+ it('uses the data API key for dashboard metrics when both keys are configured', async () => {
+ const { client, requests } = createRecordingClient()
+ client.setConnection({
+ adminApiKey: 'admin-key',
+ apiKey: 'user-key',
+ })
+
+ await client.instance.get('/api/v1/console/dashboard/summary')
+ await client.instance.get('/api/v1/console/tokens')
+ await client.instance.get('/api/v1/console/context-commits')
+
+ expect(readRequestHeader(requests[0], 'X-API-Key')).toBe('user-key')
+ expect(readRequestHeader(requests[1], 'X-API-Key')).toBe('user-key')
+ expect(readRequestHeader(requests[2], 'X-API-Key')).toBe('user-key')
+ })
+
+ it('uses the data API key for scoped audit logs when both keys are configured', async () => {
+ const { client, requests } = createRecordingClient()
+ client.setConnection({
+ adminApiKey: 'admin-key',
+ apiKey: 'user-key',
+ })
+
+ await client.instance.get('/api/v1/console/audit')
+
+ expect(readRequestHeader(requests[0], 'X-API-Key')).toBe('user-key')
+ })
+
+ it('keeps admin endpoints on the admin API key', async () => {
+ const { client, requests } = createRecordingClient()
+ client.setConnection({
+ adminApiKey: 'admin-key',
+ apiKey: 'user-key',
+ })
+
+ await client.instance.get('/api/v1/admin/accounts')
+
+ expect(readRequestHeader(requests[0], 'X-API-Key')).toBe('admin-key')
+ })
+
+ it('falls back to the admin API key for console data when no data key is configured', async () => {
+ const { client, requests } = createRecordingClient()
+ client.setConnection({
+ adminApiKey: 'admin-key',
+ apiKey: '',
+ })
+
+ await client.instance.get('/api/v1/console/dashboard/summary')
+ await client.instance.get('/api/v1/console/audit')
+
+ expect(readRequestHeader(requests[0], 'X-API-Key')).toBe('admin-key')
+ expect(readRequestHeader(requests[1], 'X-API-Key')).toBe('admin-key')
+ })
+})
diff --git a/web-studio/src/lib/ov-client/client.ts b/web-studio/src/lib/ov-client/client.ts
index e893a774c..d39148a46 100644
--- a/web-studio/src/lib/ov-client/client.ts
+++ b/web-studio/src/lib/ov-client/client.ts
@@ -18,7 +18,7 @@ const DEFAULT_TELEMETRY_PATHS = new Set([
'/api/v1/search/search',
'/api/v1/resources',
])
-const CONTROL_PLANE_PREFIXES = ['/api/v1/admin', '/api/v1/console'] as const
+const ADMIN_CONTROL_PLANE_PREFIXES = ['/api/v1/admin'] as const
const SESSION_COMMIT_PATH = /^\/api\/v1\/sessions\/[^/]+\/commit$/
function isBrowser(): boolean {
return typeof window !== 'undefined'
@@ -120,7 +120,9 @@ function shouldInjectTelemetry(
function shouldUseAdminApiKey(config: InternalAxiosRequestConfig): boolean {
const pathname = resolvePathname(config.url)
- return CONTROL_PLANE_PREFIXES.some((prefix) => pathname.startsWith(prefix))
+ return ADMIN_CONTROL_PLANE_PREFIXES.some((prefix) =>
+ pathname.startsWith(prefix),
+ )
}
function maybeInjectTelemetry(
@@ -182,10 +184,9 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {
headers.set(key, value)
}
- const apiKey =
- shouldUseAdminApiKey(config) && connection.adminApiKey
- ? connection.adminApiKey
- : connection.apiKey
+ const apiKey = shouldUseAdminApiKey(config)
+ ? connection.adminApiKey || connection.apiKey
+ : connection.apiKey || connection.adminApiKey
setOptionalHeader(headers, 'X-API-Key', apiKey)
if (connection.identityHeaders) {
setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)
diff --git a/web-studio/src/routes/home/-components/context-commits-panel.tsx b/web-studio/src/routes/home/-components/context-commits-panel.tsx
index bc5a62e42..7bc8cba90 100644
--- a/web-studio/src/routes/home/-components/context-commits-panel.tsx
+++ b/web-studio/src/routes/home/-components/context-commits-panel.tsx
@@ -49,11 +49,13 @@ function ContextCommitStat({ label, value }: { label: string; value: string }) {
export function ContextCommitsPanel({
data,
+ disabled: disabledProp,
isError,
isLoading,
t,
}: {
data: ConsoleSeries<ContextCommitItem> | undefined
+ disabled?: boolean
isError: boolean
isLoading: boolean
t: HomeT
@@ -93,7 +95,7 @@ export function ContextCommitsPanel({
[items],
)
const stats = useMemo(() => computeCommitHeatmapStats(items), [items])
- const disabled = isDisabledPayload(data)
+ const disabled = Boolean(disabledProp) || isDisabledPayload(data)
const rangeLabel =
data?.start_date && data.end_date
? `${data.start_date} - ${data.end_date}`
diff --git a/web-studio/src/routes/home/-components/token-trend-panel.tsx b/web-studio/src/routes/home/-components/token-trend-panel.tsx
index 3e831c1bb..3b0e64680 100644
--- a/web-studio/src/routes/home/-components/token-trend-panel.tsx
+++ b/web-studio/src/routes/home/-components/token-trend-panel.tsx
@@ -28,17 +28,19 @@ import { EmptyState, Panel, SectionHeading } from './panel'
export function TokenTrendPanel({
data,
+ disabled: disabledProp,
isError,
isLoading,
t,
}: {
data: ConsoleSeries<TokenSeriesItem> | undefined
+ disabled?: boolean
isError: boolean
isLoading: boolean
t: HomeT
}) {
const items = normalizeTokenSeries(data?.items)
- const disabled = isDisabledPayload(data)
+ const disabled = Boolean(disabledProp) || isDisabledPayload(data)
const rangeLabel =
data?.start_date && data.end_date
? `${data.start_date} - ${data.end_date}`
diff --git a/web-studio/src/routes/home/route.tsx b/web-studio/src/routes/home/route.tsx
index a99aefa00..593c4e22d 100644
--- a/web-studio/src/routes/home/route.tsx
+++ b/web-studio/src/routes/home/route.tsx
@@ -16,91 +16,119 @@ import {
} from './-lib/api'
import { isDisabledPayload } from './-lib/format'
import { useAppConnection } from '#/hooks/use-app-connection'
+import type {
+ ConnectionDraft,
+ ConnectionRole,
+} from '#/hooks/use-app-connection'
export const Route = createFileRoute('/home')({
component: HomePage,
})
+function hashSecret(value: string): string {
+ let hash = 0x811c9dc5
+ for (let index = 0; index < value.length; index += 1) {
+ hash ^= value.charCodeAt(index)
+ hash = Math.imul(hash, 0x01000193)
+ }
+ return (hash >>> 0).toString(36)
+}
+
+function getMetricsScopeKey(
+ connection: ConnectionDraft,
+ connectionRole: ConnectionRole,
+) {
+ const metricsKey = connection.apiKey || connection.adminApiKey
+ return {
+ accountId: connection.accountId,
+ baseUrl: connection.baseUrl,
+ keyHash: metricsKey ? hashSecret(metricsKey) : 'none',
+ keySource: connection.apiKey
+ ? 'api'
+ : connection.adminApiKey
+ ? 'admin'
+ : 'none',
+ role: connectionRole,
+ userId: connection.userId,
+ }
+}
+
function HomePage() {
const { t } = useTranslation('home')
- const { connectionRole, isConnectionRoleLoading } = useAppConnection()
- const hasAdminRole = connectionRole === 'admin' || connectionRole === 'root'
- const canQueryAdminMetrics = !isConnectionRoleLoading && hasAdminRole
+ const { connection, connectionRole, isConnectionRoleLoading } =
+ useAppConnection()
+ const canQueryMetrics =
+ !isConnectionRoleLoading && connectionRole !== 'unknown'
+ const metricsScopeKey = getMetricsScopeKey(connection, connectionRole)
const dashboard = useQuery({
- enabled: canQueryAdminMetrics,
+ enabled: canQueryMetrics,
queryFn: fetchConsoleDashboardSummary,
- queryKey: ['console-dashboard-summary'],
+ queryKey: ['console-dashboard-summary', metricsScopeKey],
refetchInterval: 30_000,
})
const tokenSeries = useQuery({
- enabled: canQueryAdminMetrics,
+ enabled: canQueryMetrics,
queryFn: fetchConsoleTokenSeries,
- queryKey: ['console-token-series', 'last-14-days'],
+ queryKey: ['console-token-series', 'last-14-days', metricsScopeKey],
refetchInterval: 60_000,
})
const contextCommits = useQuery({
- enabled: canQueryAdminMetrics,
+ enabled: canQueryMetrics,
queryFn: fetchConsoleContextCommits,
- queryKey: ['console-context-commits', 'last-365-days'],
+ queryKey: ['console-context-commits', 'last-365-days', metricsScopeKey],
refetchInterval: 60_000,
})
const summary = dashboard.data
- const usageDisabled = isDisabledPayload(summary)
-
- if (!isConnectionRoleLoading && !hasAdminRole) {
- return (
- <div className="flex min-h-[calc(100svh-8rem)] items-center justify-center px-4 py-10">
- <section className="w-full max-w-xl rounded-lg border bg-card px-6 py-5 shadow-sm">
- <h1 className="text-lg font-semibold">{t('limited.title')}</h1>
- <p className="mt-2 text-sm leading-6 text-muted-foreground">
- {t('limited.description')}
- </p>
- </section>
- </div>
- )
- }
+ const metricsUnavailable =
+ (!isConnectionRoleLoading && connectionRole === 'unknown') ||
+ isDisabledPayload(summary)
+ const isMetricsLoading = isConnectionRoleLoading || dashboard.isLoading
+ const isSeriesLoading = isConnectionRoleLoading || tokenSeries.isLoading
+ const isCommitsLoading = isConnectionRoleLoading || contextCommits.isLoading
return (
<div className="flex flex-col gap-5 pb-8">
<div className="grid gap-4 md:grid-cols-3">
<ContextDataPanel
data={summary?.context_counts}
- disabled={usageDisabled}
+ disabled={metricsUnavailable}
isError={dashboard.isError}
- isLoading={dashboard.isLoading}
+ isLoading={isMetricsLoading}
t={t}
/>
<TodayTokensPanel
data={summary?.today_tokens}
- disabled={usageDisabled}
+ disabled={metricsUnavailable}
isError={dashboard.isError}
- isLoading={dashboard.isLoading}
+ isLoading={isMetricsLoading}
t={t}
/>
<TodayRetrievalsPanel
data={summary?.today_retrievals}
- disabled={usageDisabled}
+ disabled={metricsUnavailable}
isError={dashboard.isError}
- isLoading={dashboard.isLoading}
+ isLoading={isMetricsLoading}
t={t}
/>
</div>
<TokenTrendPanel
data={tokenSeries.data}
+ disabled={metricsUnavailable}
isError={tokenSeries.isError}
- isLoading={tokenSeries.isLoading}
+ isLoading={isSeriesLoading}
t={t}
/>
<ContextCommitsPanel
data={contextCommits.data}
+ disabled={metricsUnavailable}
isError={contextCommits.isError}
- isLoading={contextCommits.isLoading}
+ isLoading={isCommitsLoading}
t={t}
/>
</div>
diff --git a/web-studio/src/routes/index.tsx b/web-studio/src/routes/index.tsx
index 36e09dd22..c39811878 100644
--- a/web-studio/src/routes/index.tsx
+++ b/web-studio/src/routes/index.tsx
@@ -1,26 +1,9 @@
import { Navigate, createFileRoute } from '@tanstack/react-router'
-import { useAppConnection } from '#/hooks/use-app-connection'
-
export const Route = createFileRoute('/')({
component: IndexRoute,
})
function IndexRoute() {
- const { connectionRole, isConnectionRoleLoading } = useAppConnection()
-
- if (isConnectionRoleLoading) {
- return null
- }
-
- return (
- <Navigate
- replace
- to={
- connectionRole === 'admin' || connectionRole === 'root'
- ? '/home'
- : '/playground'
- }
- />
- )
+ return <Navigate replace to="/home" />
}
diff --git a/web-studio/src/routes/request-logs/route.tsx b/web-studio/src/routes/request-logs/route.tsx
index 367488afb..d6e5376dd 100644
--- a/web-studio/src/routes/request-logs/route.tsx
+++ b/web-studio/src/routes/request-logs/route.tsx
@@ -1,6 +1,6 @@
import * as React from 'react'
import { useQuery } from '@tanstack/react-query'
-import { createFileRoute } from '@tanstack/react-router'
+import { Navigate, createFileRoute } from '@tanstack/react-router'
import { ActivityIcon, BarChart3Icon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
@@ -10,24 +10,44 @@ import { DEFAULT_FILTERS, DEFAULT_PAGE_SIZE } from './-constants/audit'
import { fetchAuditLogs, isZeroResultCombination } from './-lib/api'
import { formatPercent } from './-lib/format'
import type { AuditFilters, LogTypeFilter } from './-types/audit'
+import { useAppConnection } from '#/hooks/use-app-connection'
export const Route = createFileRoute('/request-logs')({
component: RequestLogsRoute,
})
+function hashSecret(value: string): string {
+ let hash = 0x811c9dc5
+ for (let index = 0; index < value.length; index += 1) {
+ hash ^= value.charCodeAt(index)
+ hash = Math.imul(hash, 0x01000193)
+ }
+ return (hash >>> 0).toString(36)
+}
+
function RequestLogsRoute() {
const { t } = useTranslation('requestLogs')
+ const { connection, connectionRole, isConnectionRoleLoading } =
+ useAppConnection()
const [draftFilters, setDraftFilters] =
React.useState<AuditFilters>(DEFAULT_FILTERS)
const [filters, setFilters] = React.useState<AuditFilters>(DEFAULT_FILTERS)
const [page, setPage] = React.useState(1)
const [pageSize, setPageSize] = React.useState(DEFAULT_PAGE_SIZE)
const zeroResult = isZeroResultCombination(filters)
+ const canQueryAudit = !isConnectionRoleLoading && connectionRole !== 'unknown'
+ const auditScopeKey = {
+ accountId: connection.accountId,
+ baseUrl: connection.baseUrl,
+ keyHash: hashSecret(connection.adminApiKey || connection.apiKey),
+ role: connectionRole,
+ userId: connection.userId,
+ }
const audit = useQuery({
- enabled: !zeroResult,
+ enabled: canQueryAudit && !zeroResult,
queryFn: () => fetchAuditLogs(filters, page, pageSize),
- queryKey: ['console-audit-logs', filters, page, pageSize],
+ queryKey: ['console-audit-logs', auditScopeKey, filters, page, pageSize],
refetchInterval: 30_000,
})
@@ -35,6 +55,15 @@ function RequestLogsRoute() {
const disabled = audit.data?.enabled === false
const total = zeroResult ? 0 : (audit.data?.total ?? 0)
const pageCount = Math.max(1, Math.ceil(total / pageSize))
+ const identityParts = [connection.accountId, connection.userId].filter(
+ Boolean,
+ )
+ const scopeLabel =
+ identityParts.length > 0
+ ? t('scope.currentIdentityWithName', {
+ identity: identityParts.join(' / '),
+ })
+ : t('scope.currentIdentity')
const handleSearch = () => {
setFilters({ ...draftFilters })
@@ -64,8 +93,16 @@ function RequestLogsRoute() {
setPage(1)
}
+ if (!isConnectionRoleLoading && !canQueryAudit) {
+ return <Navigate replace to="/home" />
+ }
+
return (
<div className="flex w-full min-w-0 flex-col gap-5">
+ <div className="rounded-md border border-border/70 bg-muted/30 px-3 py-2 text-sm text-muted-foreground">
+ {scopeLabel}
+ </div>
+
<div className="grid gap-3 md:grid-cols-2">
<MetricCard
label={t('metrics.total')}
diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsx
index 1d379ab9a..333ab1473 100644
--- a/web-studio/src/routes/settings/route.tsx
+++ b/web-studio/src/routes/settings/route.tsx
@@ -590,7 +590,8 @@ function AddUserDialog({
function SettingsRoute() {
const { t } = useTranslation('settings')
const queryClient = useQueryClient()
- const { connection, saveConnection, serverMode } = useAppConnection()
+ const { connection, connectionRole, saveConnection, serverMode } =
+ useAppConnection()
const [draft, setDraft] = React.useState<ConnectionDraft>(connection)
const [managedAccountIds, setManagedAccountIds] = React.useState<string[]>([
connection.accountId || DEFAULT_ACCOUNT_ID,
@@ -642,6 +643,8 @@ function SettingsRoute() {
const hasAdminAccess =
serverMode !== 'dev' && probeQuery.data?.admin.state === 'ok'
+ const showAdminDescription =
+ hasAdminAccess || connectionRole === 'admin' || connectionRole === 'root'
const hasSavedAdminApiKey = Boolean(draft.adminApiKey.trim())
const showAdminCredentialFields =
serverMode !== 'dev' && (hasAdminAccess || hasSavedAdminApiKey)
@@ -969,7 +972,9 @@ function SettingsRoute() {
{t('page.title')}
</h1>
<p className="max-w-3xl text-sm leading-6 text-muted-foreground">
- {t('page.description')}
+ {showAdminDescription
+ ? t('page.adminDescription')
+ : t('page.description')}
</p>
</header>