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
fix: stabilize studio identity and streaming chat (#2435)
yufeng1a1f32bfb6ab
diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.pyindex a5cf2aac5..763ca20a4 100644--- a/bot/tests/test_openviking_api_key_type.py+++ b/bot/tests/test_openviking_api_key_type.py@@ -1,8 +1,11 @@+import jsonfrom pathlib import Pathfrom types import SimpleNamespaceimport pytest-from vikingbot.agent.tools.ov_file import VikingGrepTool, VikingSearchTool+from vikingbot.agent.context import ContextBuilder+from vikingbot.agent.loop import _is_tool_result_success+from vikingbot.agent.tools.ov_file import VikingGrepTool, VikingMemoryCommitTool, VikingSearchToolfrom vikingbot.config.schema import SessionKeyfrom vikingbot.hooks.base import HookContextfrom vikingbot.hooks.builtins.openviking_hooks import OpenVikingCompactHook@@ -25,6 +28,9 @@ class _DummyHTTPClient:def __init__(self, **kwargs):self.kwargs = kwargs+ self.find_calls = []+ self.ls_calls = []+ self.closed = False_DummyHTTPClient.instances.append(self)async def initialize(self):@@ -65,6 +71,11 @@ class _DummyHTTPClient:return Noneasync def find(self, *_args, **_kwargs):+ self.find_calls.append((_args, _kwargs))+ return []++ async def ls(self, path, recursive=False):+ self.ls_calls.append((path, recursive))return []async def search(self, *_args, **_kwargs):@@ -74,6 +85,7 @@ class _DummyHTTPClient:return {"matches": []}async def close(self):+ self.closed = Truereturn None@@ -120,6 +132,12 @@ def test_viking_client_init_root_mode_sets_account_and_user(monkeypatch):assert first.kwargs["user"] == "admin"+def test_tool_result_success_only_treats_standard_error_prefix_as_failure():+ assert _is_tool_result_success("errorCode = 0") is True+ assert _is_tool_result_success("Error budget: 5%") is True+ assert _is_tool_result_success("Error: failed") is False++def test_viking_client_init_user_mode_does_not_set_user_or_account(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))@@ -131,6 +149,68 @@ def test_viking_client_init_user_mode_does_not_set_user_or_account(monkeypatch):assert "account" not in first.kwargs+def test_viking_client_request_connection_uses_active_identity(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))++ client = VikingClient(+ agent_id="workspace#channel",+ connection={+ "server_url": "http://studio.local",+ "api_key": "anonymous-key",+ "account_id": "acct",+ "user_id": "anonymous",+ "agent_id": "web-playground",+ "role": "user",+ "namespace_policy": {+ "isolate_user_scope_by_agent": True,+ "isolate_agent_scope_by_user": True,+ },+ },+ )++ first = _DummyHTTPClient.instances[0]+ assert client.api_key_type == "user"+ assert client.account_id == "acct"+ assert client.admin_user_id == "anonymous"+ assert client.agent_id == "web-playground"+ assert client._apikey_manager is None+ assert client._namespace_policy_loaded is True+ assert client.should_sender_fanout() is False+ assert (+ client._memory_target_uri(None) == "viking://user/anonymous/agent/web-playground/memories/"+ )+ assert first.kwargs == {+ "url": "http://studio.local",+ "api_key": "anonymous-key",+ "profile_enabled": False,+ }+++def test_viking_client_request_connection_preserves_admin_scope(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))++ VikingClient(+ agent_id="workspace#channel",+ connection={+ "server_url": "http://studio.local",+ "api_key": "admin-key",+ "account_id": "acct",+ "user_id": "default",+ "agent_id": "web-playground",+ "role": "admin",+ },+ )++ first = _DummyHTTPClient.instances[0]+ assert first.kwargs == {+ "url": "http://studio.local",+ "api_key": "admin-key",+ "profile_enabled": False,+ "account": "acct",+ "user": "default",+ }++@pytest.mark.asyncioasync def test_commit_user_mode_ignores_user_specific_key_flow(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))@@ -152,6 +232,76 @@ async def test_commit_user_mode_ignores_user_specific_key_flow(monkeypatch):assert result["success"] is True+async def test_commit_request_connection_bypasses_cached_user_key_flow(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))+ client = VikingClient(+ agent_id="workspace",+ connection={+ "server_url": "http://studio.local",+ "api_key": "anonymous-key",+ "account_id": "acct",+ "user_id": "anonymous",+ "agent_id": "web-playground",+ },+ )++ async def _must_not_call(*_args, **_kwargs):+ raise AssertionError("request connection should not call user key management path")++ monkeypatch.setattr(client, "_check_user_exists", _must_not_call)+ monkeypatch.setattr(client, "_initialize_user", _must_not_call)+ monkeypatch.setattr(client, "_get_or_create_user_apikey", _must_not_call)++ result = await client.commit(+ session_id="sess",+ messages=[{"role": "user", "content": "hello", "tools_used": []}],+ user_id="anonymous",+ )++ assert result["success"] is True+ assert [inst.kwargs["api_key"] for inst in _DummyHTTPClient.instances] == ["anonymous-key"]+++async def test_request_connection_search_memory_uses_request_client_only(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))+ client = VikingClient(+ agent_id="workspace",+ connection={+ "server_url": "http://studio.local",+ "api_key": "anonymous-key",+ "account_id": "acct",+ "user_id": "anonymous",+ "agent_id": "web-playground",+ "role": "user",+ "namespace_policy": {+ "isolate_user_scope_by_agent": False,+ "isolate_agent_scope_by_user": False,+ },+ },+ )++ async def _must_not_call(*_args, **_kwargs):+ raise AssertionError("request connection should not call user management path")++ monkeypatch.setattr(client, "_initialize_user", _must_not_call)+ monkeypatch.setattr(client, "_get_or_create_user_apikey", _must_not_call)++ result = await client.search_memory(+ query="php",+ user_ids=["anonymous"],+ agent_user_id="anonymous",+ limit=10,+ )++ assert result == {"user_memory": [], "agent_memory": []}+ first = _DummyHTTPClient.instances[0]+ assert len(first.find_calls) == 2+ assert first.find_calls[0][1]["target_uri"] == "viking://user/anonymous/memories/"+ assert first.find_calls[1][1]["target_uri"] == "viking://agent/web-playground/memories/"++@pytest.mark.asyncioasync def test_commit_root_mode_uses_sender_user_key(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))@@ -1078,3 +1228,97 @@ async def test_openviking_search_user_key_mode_uses_current_user_namespace(monkeassert "viking://user/memories/" in resultassert calls == [("viking://user/memories/", "admin")]+++def test_openviking_search_description_allows_follow_up_memory_queries():+ description = VikingSearchTool().description++ assert "follow-up" in description+ assert "different remembered fact" in description+ assert "before concluding no relevant record exists" in description+ assert "avoid repeated calls with similar queries" not in description.lower()+++async def test_context_reminds_agent_to_search_current_memory_question(tmp_path):+ class _EmptyMemory:+ async def get_viking_memory_context(self, **_kwargs):+ return ""++ context = ContextBuilder(workspace=tmp_path, sender_id="sender-1")+ context._memory = _EmptyMemory()++ user_info = await context._build_user_memory(+ session_key=SessionKey(type="cli", channel_id="default", chat_id="chat-1"),+ current_message="我会哪些语言",+ sender_id="sender-1",+ ov_tools_enable=True,+ is_first_round=False,+ )++ assert "OpenViking Memory Retrieval" in user_info+ assert "use openviking_search for the current question" in user_info+ assert "A previous empty search result does not prove" in user_info+++async def test_openviking_memory_commit_prefers_sender_in_static_multi_user_bot(monkeypatch):+ tool = VikingMemoryCommitTool()+ calls = []++ class _FakeClient:+ admin_user_id = "default"++ async def commit(self, session_id, messages, user_id):+ calls.append((session_id, messages, user_id))+ return {"commit": {"archived": False}}++ async def _fake_get_client(_tool_context):+ return _FakeClient()++ monkeypatch.setattr(tool, "_get_client", _fake_get_client)++ result = await tool.execute(+ SimpleNamespace(+ workspace_id="workspace",+ sender_id="alice",+ session_key=SimpleNamespace(safe_name=lambda: "session-1"),+ openviking_connection=None,+ ),+ messages=[{"role": "user", "content": "remember this"}],+ )++ assert json.loads(result)["status"] == "success"+ assert calls == [+ (+ "session-1",+ [{"role": "user", "content": "remember this"}],+ "alice",+ )+ ]+++async def test_openviking_request_connection_client_is_closed_after_tool_call(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))+ tool = VikingSearchTool()++ result = await tool.execute(+ SimpleNamespace(+ workspace_id="workspace",+ memory_user_ids=None,+ openviking_connection={+ "server_url": "http://studio.local",+ "api_key": "user-key",+ "account_id": "acct",+ "user_id": "alice",+ "agent_id": "web-playground",+ "role": "user",+ },+ ),+ query="hello",+ )++ assert result == "No results found for query: hello"+ assert len(_DummyHTTPClient.instances) == 1+ assert _DummyHTTPClient.instances[0].closed is Truediff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.pyindex a3bb5a8e9..615aa702b 100644--- a/bot/vikingbot/agent/context.py+++ b/bot/vikingbot/agent/context.py@@ -37,6 +37,7 @@ class ContextBuilder:sender_name: str = None,is_group_chat: bool = False,eval: bool = False,+ openviking_connection: dict[str, Any] | None = None,):self.workspace = workspaceself._templates_ensured = False@@ -47,6 +48,7 @@ class ContextBuilder:self._sender_name = sender_nameself._is_group_chat = is_group_chatself._eval = eval+ self._openviking_connection = openviking_connectionself.latest_relevant_memories: str | None = None@property@@ -142,7 +144,9 @@ Skills with available="false" need dependencies installed first - you can try in# Fetch current user's profilestart = _time.time()profile = await self.memory.get_viking_user_profile(- workspace_id=workspace_id, user_id=self._sender_id+ workspace_id=workspace_id,+ user_id=self._sender_id,+ openviking_connection=self._openviking_connection,)cost = round(_time.time() - start, 2)logger.info(@@ -154,7 +158,9 @@ Skills with available="false" need dependencies installed first - you can try in# Fetch additional profiles from profile_user_listif profile_user_list:profiles = await self.memory.get_viking_user_profiles(- workspace_id=workspace_id, user_ids=profile_user_list+ workspace_id=workspace_id,+ user_ids=profile_user_list,+ openviking_connection=self._openviking_connection,)if profiles:parts.append(profiles)@@ -202,6 +208,12 @@ Skills with available="false" need dependencies installed first - you can try inif ov_tools_enable:exp_first_round_only = load_config().ov_server.recall_exp_first_round_only+ parts.append(+ "## OpenViking Memory Retrieval\n"+ "- For questions about the user's remembered facts, preferences, profile, or personal context, use openviking_search for the current question before saying there is no relevant record.\n"+ "- A previous empty search result does not prove that a different follow-up question has no memory; search again when the requested fact changes."+ )+if exp_first_round_only:# Alt mode: skip per-turn recall; inject experience memory once per session.exp_workspace_id = workspace_id@@ -209,7 +221,9 @@ Skills with available="false" need dependencies installed first - you can try inif is_first_round:start = _time.time()exp_memory = await self.memory.get_viking_experience_context(- query=current_message, workspace_id=exp_workspace_id+ query=current_message,+ workspace_id=exp_workspace_id,+ openviking_connection=self._openviking_connection,)cost = round(_time.time() - start, 2)logger.info(@@ -228,6 +242,7 @@ Skills with available="false" need dependencies installed first - you can try inworkspace_id=workspace_id,sender_id=sender_id,user_ids=search_user_ids,+ openviking_connection=self._openviking_connection,)logger.info(f"viking_memory={viking_memory}")cost = round(_time.time() - start, 2)diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex 3dc0343aa..080a9b5b1 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -46,6 +46,13 @@ if TYPE_CHECKING:from vikingbot.cron.service import CronService+def _is_tool_result_success(result: Any) -> bool:+ if result is None or isinstance(result, Exception):+ return False+ text = str(result).lstrip()+ return bool(text) and not text.startswith("Error:")++class AgentLoop:"""The agent loop is the core processing engine.@@ -258,6 +265,58 @@ class AgentLoop:"auto": True,}+ async def _chat_with_stream_events(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]],+ session_key: SessionKey,+ publish_events: bool,+ ) -> tuple[Any, bool, bool]:+ """Call the provider and forward native stream deltas to the bus."""+ streamed_content = False+ streamed_reasoning = False+ response = None++ async for event in self.provider.chat_stream(+ messages=messages,+ tools=tools,+ model=self.model,+ session_id=session_key.safe_name(),+ ):+ if event.type == "content_delta":+ if event.content:+ streamed_content = True+ if publish_events:+ await self.bus.publish_outbound(+ OutboundMessage(+ session_key=session_key,+ content=event.content,+ event_type=OutboundEventType.CONTENT_DELTA,+ )+ )+ elif event.type == "reasoning_delta":+ if event.content:+ streamed_reasoning = True+ if publish_events:+ await self.bus.publish_outbound(+ OutboundMessage(+ session_key=session_key,+ content=event.content,+ event_type=OutboundEventType.REASONING_DELTA,+ )+ )+ elif event.type == "response":+ response = event.response++ if response is None:+ response = await self.provider.chat(+ messages=messages,+ tools=tools,+ model=self.model,+ session_id=session_key.safe_name(),+ )+ return response, streamed_content, streamed_reasoning+def _register_builtin_hooks(self):"""Register built-in hooks."""hook_manager.register_path(self.config.hooks)@@ -281,8 +340,17 @@ class AgentLoop:return self.sandbox_manager.to_workspace_id(session_key)return "shared"- async def _get_ov_client(self, session_key: SessionKey):+ async def _get_ov_client(+ self,+ session_key: SessionKey,+ openviking_connection: dict[str, Any] | None = None,+ ):workspace_id = self._get_ov_workspace_id(session_key)+ if openviking_connection:+ from vikingbot.openviking_mount.ov_server import VikingClient++ return await VikingClient.create(workspace_id, connection=openviking_connection)+client = self._ov_clients.get(workspace_id)if client is None:from vikingbot.openviking_mount.ov_server import VikingClient@@ -364,6 +432,7 @@ class AgentLoop:self,session: Session,provider_name: str | None = None,+ openviking_connection: dict[str, Any] | None = None,) -> list[dict[str, Any]]:if not self._ov_session_context_enabled():return session.get_history(provider_name=provider_name)@@ -371,9 +440,15 @@ class AgentLoop:agents_config = getattr(self.config, "agents", None)token_budget = int(getattr(agents_config, "session_context_token_budget", 12000) or 12000)session_id = get_openviking_session_id(session)+ request_client = Nonetry:- client = await self._get_ov_client(session.key)+ client = await self._get_ov_client(+ session.key,+ openviking_connection=openviking_connection,+ )+ if openviking_connection:+ request_client = clientcontext_payload = await client.get_session_context(session_id=session_id,token_budget=token_budget,@@ -395,6 +470,9 @@ class AgentLoop:"Falling back to local session history.")return session.get_history(provider_name=provider_name)+ finally:+ if request_client is not None:+ await request_client.close()async def _submit_openviking_session(self,@@ -403,6 +481,7 @@ class AgentLoop:force_commit: bool = False,keep_recent_count: int | None = None,commit_message_threshold: int | None = None,+ openviking_connection: dict[str, Any] | None = None,) -> bool:if not self._ov_session_context_enabled():return False@@ -417,6 +496,8 @@ class AgentLoop:kwargs["keep_recent_count"] = keep_recent_countif commit_message_threshold is not None:kwargs["commit_message_threshold"] = commit_message_threshold+ if openviking_connection:+ kwargs["openviking_connection"] = openviking_connectionawait hook_manager.execute_hooks(context=HookContext(@@ -437,12 +518,14 @@ class AgentLoop:force_commit: bool = False,keep_recent_count: int | None = None,commit_message_threshold: int | None = None,+ openviking_connection: dict[str, Any] | None = None,) -> bool:success = await self._submit_openviking_session(session,force_commit=force_commit,keep_recent_count=keep_recent_count,commit_message_threshold=commit_message_threshold,+ openviking_connection=openviking_connection,)if not success:return False@@ -488,6 +571,7 @@ class AgentLoop:force_commit=True,keep_recent_count=int(getattr(agents_config, "commit_keep_recent_count", 10) or 0),commit_message_threshold=self.memory_window,+ openviking_connection=getattr(msg, "openviking_connection", None),)async def _commit_openviking_session(@@ -497,11 +581,13 @@ class AgentLoop:keep_recent_count: int = 0,clear_local_session: bool = False,rotate_session_id: bool = False,+ openviking_connection: dict[str, Any] | None = None,) -> bool:success = await self._submit_openviking_session(session,force_commit=True,keep_recent_count=keep_recent_count,+ openviking_connection=openviking_connection,)if not success:return False@@ -556,6 +642,7 @@ class AgentLoop:ov_tools_enable: bool = True,memory_user_ids: list[str] | None = None,disabled_tools: list[str] | None = None,+ openviking_connection: dict[str, Any] | None = None,) -> tuple[str | None, str | None, list[dict], dict[str, int], int]:"""Run the core agent loop: call LLM, execute tools, repeat until done.@@ -567,6 +654,7 @@ class AgentLoop:ov_tools_enable: Whether to enable OpenViking tools for this sessionmemory_user_ids: List of user IDs for memory retrievaldisabled_tools: Tool names to hide from the model for this request+ openviking_connection: Request-scoped OpenViking identity for toolsReturns:tuple of (final_content, final_reasoning_content, tools_used, token_usage, iteration)@@ -594,14 +682,15 @@ class AgentLoop:))- response = await self.provider.chat(+ tool_definitions = self.tools.get_definitions(+ ov_tools_enable=ov_tools_enable,+ disabled_tools=disabled_tools,+ )+ response, _streamed_content, streamed_reasoning = await self._chat_with_stream_events(messages=messages,- tools=self.tools.get_definitions(- ov_tools_enable=ov_tools_enable,- disabled_tools=disabled_tools,- ),- model=self.model,- session_id=session_key.safe_name(),+ tools=tool_definitions,+ session_key=session_key,+ publish_events=publish_events,)if response.usage:cur_token = response.usage@@ -609,7 +698,7 @@ class AgentLoop:token_usage["completion_tokens"] += cur_token["completion_tokens"]token_usage["total_tokens"] += cur_token["total_tokens"]- if publish_events and response.reasoning_content:+ if publish_events and response.reasoning_content and not streamed_reasoning:await self.bus.publish_outbound(OutboundMessage(session_key=session_key,@@ -639,7 +728,9 @@ class AgentLoop:else "shared")_exp = await self.context.memory.get_viking_experience_context(- query=_query, workspace_id=workspace_id+ query=_query,+ workspace_id=workspace_id,+ openviking_connection=openviking_connection,)logger.info(f"[WRITE_EXP]: write tool detected, exp_found={bool(_exp)}, query={_query[:50]}"@@ -686,6 +777,7 @@ class AgentLoop:sandbox_manager=self.sandbox_manager,sender_id=sender_id,memory_user_ids=memory_user_ids,+ openviking_connection=openviking_connection,)tool_execute_duration = (time.time() - tool_execute_start_time) * 1000return idx, tool_call, result, tool_execute_duration@@ -695,6 +787,16 @@ class AgentLoop:execute_single_tool(idx, tool_call)for idx, tool_call in enumerate(response.tool_calls)]+ if publish_events:+ for tool_call in response.tool_calls:+ args_str = json.dumps(tool_call.arguments, ensure_ascii=False)+ await self.bus.publish_outbound(+ OutboundMessage(+ session_key=session_key,+ content=f"{tool_call.name}({args_str})",+ event_type=OutboundEventType.TOOL_CALL,+ )+ )results = await asyncio.gather(*tool_tasks)# Stage 3: Process results sequentially in original order@@ -704,13 +806,6 @@ class AgentLoop:logger.info(f"[RESULT]: {str(result)[:600]}")if publish_events:- await self.bus.publish_outbound(- OutboundMessage(- session_key=session_key,- content=f"{tool_call.name}({args_str})",- event_type=OutboundEventType.TOOL_CALL,- )- )await self.bus.publish_outbound(OutboundMessage(session_key=session_key,@@ -727,9 +822,7 @@ class AgentLoop:"args": args_str,"result": result,"duration": tool_execute_duration,- "execute_success": True- if result and "Error executing" not in result- else False,+ "execute_success": _is_tool_result_success(result),"input_token": tool_call.tokens,"output_token": cal_str_tokens(result, text_type="mixed"),}@@ -821,6 +914,12 @@ class AgentLoop:disabled_tools = msg.metadata.get("disabled_tools", []) if msg.metadata else []if not isinstance(disabled_tools, list):disabled_tools = []+ openviking_connection = getattr(msg, "openviking_connection", None)+ if openviking_connection is None and msg.metadata:+ openviking_connection = msg.metadata.get("openviking_connection")+ if not isinstance(openviking_connection, dict):+ openviking_connection = None+ msg.openviking_connection = openviking_connection# Get profile_user_list from channel configprofile_user_list = []# Try to get memory_users from message metadata first (CLI mode), then from channel config@@ -871,6 +970,7 @@ class AgentLoop:session,keep_recent_count=0,clear_local_session=True,+ openviking_connection=openviking_connection,)if not committed:return OutboundMessage(@@ -900,6 +1000,7 @@ class AgentLoop:remembered = await self._commit_openviking_session(session,keep_recent_count=self.config.agents.commit_keep_recent_count,+ openviking_connection=openviking_connection,)if not remembered:return OutboundMessage(@@ -969,11 +1070,16 @@ class AgentLoop:sender_name=msg.sender_name,is_group_chat=is_group_chat,eval=self._eval,+ openviking_connection=openviking_connection,)# Build initial messages (use OpenViking session context when enabled)provider_name = self.config.get_provider_name(self.model) if self.config else None- history = await self._build_prompt_history(session, provider_name=provider_name)+ history = await self._build_prompt_history(+ session,+ provider_name=provider_name,+ openviking_connection=openviking_connection,+ )messages = await message_context.build_messages(history=history,current_message=msg.content,@@ -1010,6 +1116,7 @@ class AgentLoop:ov_tools_enable=ov_tools_enable,memory_user_ids=memory_user,disabled_tools=disabled_tools,+ openviking_connection=openviking_connection,)if auto_memory_tool:@@ -1048,6 +1155,7 @@ class AgentLoop:await self._submit_openviking_session_and_clear_if_committed(session,commit_message_threshold=self.memory_window,+ openviking_connection=openviking_connection,)LangfuseClient.get_instance().update_generation_metadata(response_id, response_completeddiff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.pyindex 0fce09c48..80cb2b9dd 100644--- a/bot/vikingbot/agent/memory.py+++ b/bot/vikingbot/agent/memory.py@@ -181,18 +181,26 @@ class MemoryStore:workspace_id: str,sender_id: str,user_ids: list[str] | None = None,+ openviking_connection: dict[str, Any] | None = None,) -> str:client = Nonetry:config = load_config().ov_server- admin_user_id = config.admin_user_id+ admin_user_id = (+ str(openviking_connection.get("user_id"))+ if isinstance(openviking_connection, dict) and openviking_connection.get("user_id")+ else config.admin_user_id+ )# Use provided user_ids or fall back to sender_idsearch_user_ids = user_ids if user_ids else [sender_id]logger.info(f"workspace_id={workspace_id}")logger.info(f"user_ids={search_user_ids}")logger.info(f"admin_user_id={admin_user_id}")- client = await VikingClient.create()+ client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ )result = await client.search_memory(query=current_message,user_ids=search_user_ids,@@ -226,12 +234,20 @@ class MemoryStore:except Exception as e:logger.warning(f"Error closing VikingClient: {e}")- async def get_viking_experience_context(self, query: str, workspace_id: str) -> str:+ async def get_viking_experience_context(+ self,+ query: str,+ workspace_id: str,+ openviking_connection: dict[str, Any] | None = None,+ ) -> str:"""用当前任务 query 检索 experience 记忆,注入到 system prompt。"""client = Nonetry:ov_cfg = load_config().ov_server- client = await VikingClient.create()+ client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ )experiences = await client.search_experiences(query, limit=ov_cfg.exp_recall_limit)logger.info(f"[READ_EXPERIENCE_MEMORY]: found {len(experiences)} experiences, query={query[:50]}"@@ -255,10 +271,18 @@ class MemoryStore:except Exception:pass- async def get_viking_user_profile(self, workspace_id: str, user_id: str) -> str:+ async def get_viking_user_profile(+ self,+ workspace_id: str,+ user_id: str,+ openviking_connection: dict[str, Any] | None = None,+ ) -> str:client = Nonetry:- client = await VikingClient.create()+ client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ )result = await client.read_user_profile(user_id)return result or ""except Exception as e:@@ -271,7 +295,12 @@ class MemoryStore:except Exception as e:logger.warning(f"Error closing VikingClient: {e}")- async def get_viking_user_profiles(self, workspace_id: str, user_ids: list[str]) -> str:+ async def get_viking_user_profiles(+ self,+ workspace_id: str,+ user_ids: list[str],+ openviking_connection: dict[str, Any] | None = None,+ ) -> str:"""Get multiple user profiles concurrently.Args:@@ -286,7 +315,10 @@ class MemoryStore:client = Nonetry:- client = await VikingClient.create()+ client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ )async def fetch_profile(user_id: str) -> tuple[str, str]:"""Fetch a single user profile."""diff --git a/bot/vikingbot/agent/tools/base.py b/bot/vikingbot/agent/tools/base.pyindex e30b011a8..f76b65676 100644--- a/bot/vikingbot/agent/tools/base.py+++ b/bot/vikingbot/agent/tools/base.py@@ -1,6 +1,8 @@"""Base class for agent tools."""+from abc import ABC, abstractmethodfrom dataclasses import dataclass+from typing import Anyfrom vikingbot.config.schema import SessionKeyfrom vikingbot.sandbox.manager import SandboxManager@@ -24,6 +26,9 @@ class ToolContext:and permission checks.memory_user_ids: Optional list of user IDs for memory retrieval. Used byopenviking_search tool to search specific users' memory spaces.+ openviking_connection: Optional request-scoped OpenViking identity. Studio+ requests use this so tools call OpenViking with the same connection+ selected in the browser.Example:>>> context = ToolContext(@@ -38,12 +43,7 @@ class ToolContext:workspace_id: str = sandbox_manager.to_workspace_id(session_key) if sandbox_manager else Nonesender_id: str | None = Nonememory_user_ids: list[str] | None = None---"""Base class for agent tools."""--from abc import ABC, abstractmethod-from typing import Any+ openviking_connection: dict[str, Any] | None = Noneclass Tool(ABC):diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.pyindex cb314bc89..d3041e9e4 100644--- a/bot/vikingbot/agent/tools/ov_file.py+++ b/bot/vikingbot/agent/tools/ov_file.py@@ -16,13 +16,28 @@ from vikingbot.openviking_mount.ov_server import VikingClientclass OVFileTool(Tool, ABC):def __init__(self):super().__init__()- self._client = None+ self._clients = {}++ @staticmethod+ def _has_request_connection(tool_context: ToolContext) -> bool:+ return bool(getattr(tool_context, "openviking_connection", None))async def _get_client(self, tool_context: ToolContext):- del tool_context- if self._client is None:- self._client = await VikingClient.create()- return self._client+ if self._has_request_connection(tool_context):+ return await VikingClient.create(+ tool_context.workspace_id,+ connection=tool_context.openviking_connection,+ )+ cache_key = "__default__"+ client = self._clients.get(cache_key)+ if client is None:+ client = await VikingClient.create(tool_context.workspace_id)+ self._clients[cache_key] = client+ return client++ async def _release_client(self, tool_context: ToolContext, client: VikingClient | None) -> None:+ if client is not None and self._has_request_connection(tool_context):+ await client.close()class VikingListTool(OVFileTool):@@ -57,6 +72,7 @@ class VikingListTool(OVFileTool):async def execute(self, tool_context: "ToolContext", uri: str, recursive: bool = False, **kwargs: Any) -> str:+ client = Nonetry:client = await self._get_client(tool_context)entries = await client.list_resources(path=uri, recursive=recursive)@@ -77,6 +93,8 @@ class VikingListTool(OVFileTool):except Exception as e:logger.exception(f"Error processing message: {e}")return f"Error listing Viking resources: {str(e)}"+ finally:+ await self._release_client(tool_context, client)class VikingSearchTool(OVFileTool):@@ -90,9 +108,10 @@ class VikingSearchTool(OVFileTool):def description(self) -> str:return ("Using query to search for resources (knowledge, code, files, workflow, etc.) in OpenViking. "- "Result: Only URIs and summaries are included here. To view the full content, use openviking_multi_read tool."- "This operation performs semantic retrieval, not full character matching. Please avoid repeated calls with similar queries as much as possible."- "bad-case: after searching with ‘Nate Joanna dog playdate 3:00 pm', another search was performed using 'Nate Joanna dog playdate'."+ "Result: Only URIs and summaries are included here. To view the full content, use openviking_multi_read tool. "+ "This operation performs semantic retrieval, not full character matching. "+ "Avoid duplicate calls with the same intent in the same turn, but do search again for a new user question or a follow-up that asks for a different remembered fact. "+ "For questions about the user's memory, profile, preferences, or personal facts, use this tool before concluding no relevant record exists.")@property@@ -249,6 +268,7 @@ class VikingSearchTool(OVFileTool):min_score: float = 0.35,**kwargs: Any,) -> str:+ client = Nonetry:client = await self._get_client(tool_context)admin_user_id = client.admin_user_id@@ -296,6 +316,8 @@ class VikingSearchTool(OVFileTool):return contentexcept Exception as e:return f"Error searching Viking: {str(e)}"+ finally:+ await self._release_client(tool_context, client)class VikingAddResourceTool(OVFileTool):@@ -336,7 +358,7 @@ class VikingAddResourceTool(OVFileTool):if not local_path.is_file():return f"Error: Not a file: {path}"- client = await VikingClient.create()+ client = await self._get_client(tool_context)result = await client.add_resource(path, description)if result:@@ -350,8 +372,7 @@ class VikingAddResourceTool(OVFileTool):logger.warning(f"Error adding resource: {e}")return f"Error adding resource to Viking: {str(e)}"finally:- if client:- await client.close()+ await self._release_client(tool_context, client)class VikingGrepTool(OVFileTool):@@ -366,7 +387,7 @@ class VikingGrepTool(OVFileTool):return ("Search Viking resources using a regex pattern (like grep).""Result: Only URIs and summaries are included here. To view the full content, use openviking_multi_read tool."- "Please avoid repeated calls with similar queries as much as possible."+ "Avoid duplicate calls with the same intent in the same turn.")@property@@ -399,6 +420,7 @@ class VikingGrepTool(OVFileTool):case_insensitive: bool = False,**kwargs: Any,) -> str:+ client = Nonetry:client = await self._get_client(tool_context)result = await client.grep(@@ -445,6 +467,8 @@ class VikingGrepTool(OVFileTool):return "\n".join(result_lines)except Exception as e:return f"Error searching Viking with grep: {str(e)}"+ finally:+ await self._release_client(tool_context, client)class VikingGlobTool(OVFileTool):@@ -482,6 +506,7 @@ class VikingGlobTool(OVFileTool):async def execute(self, tool_context: "ToolContext", pattern: str, uri: str = "", **kwargs: Any) -> str:+ client = Nonetry:client = await self._get_client(tool_context)result = await client.glob(pattern, uri=uri or None, user_id=client.admin_user_id)@@ -505,6 +530,8 @@ class VikingGlobTool(OVFileTool):return "\n".join(result_lines)except Exception as e:return f"Error searching Viking with glob: {str(e)}"+ finally:+ await self._release_client(tool_context, client)class VikingMemoryCommitTool(OVFileTool):@@ -552,6 +579,13 @@ class VikingMemoryCommitTool(OVFileTool):],}+ @staticmethod+ def _format_commit_error(error: Exception) -> str:+ message = str(error)+ if "<title>403 Forbidden</title>" in message or "<h1>403 Forbidden</h1>" in message:+ return "HTTP 403 Forbidden"+ return message+@propertydef name(self) -> str:return "openviking_memory_commit"@@ -587,12 +621,17 @@ class VikingMemoryCommitTool(OVFileTool):messages: list[dict[str, Any]],**kwargs: Any,) -> str:+ client = Nonetry:- if not tool_context.sender_id:- return "Error committed, sender_id is required."client = await self._get_client(tool_context)+ if self._has_request_connection(tool_context):+ commit_user_id = client.admin_user_id or tool_context.sender_id+ else:+ commit_user_id = tool_context.sender_id or client.admin_user_id+ if not commit_user_id:+ return "Error: user id is required for OpenViking memory commit."session_id = tool_context.session_key.safe_name()- result = await client.commit(session_id, messages, tool_context.sender_id)+ result = await client.commit(session_id, messages, commit_user_id)commit_result = result.get("commit", {}) if isinstance(result, dict) else {}archive_uri = commit_result.get("archive_uri")memory_diff_uri = f"{archive_uri}/memory_diff.json" if archive_uri else None@@ -625,7 +664,9 @@ class VikingMemoryCommitTool(OVFileTool):)except Exception as e:logger.exception(f"Error processing message: {e}")- return f"Error committing to Viking: {str(e)}"+ return f"Error: committing to Viking failed: {self._format_commit_error(e)}"+ finally:+ await self._release_client(tool_context, client)class VikingMultiReadTool(OVFileTool):@@ -660,6 +701,7 @@ class VikingMultiReadTool(OVFileTool):**kwargs: Any,) -> str:level = "read" # 默认获取完整内容+ client = Nonetry:if not uris:return "Error: No URIs provided."@@ -709,3 +751,5 @@ class VikingMultiReadTool(OVFileTool):except Exception as e:logger.exception(f"Error in VikingMultiReadTool: {e}")return f"Error multi-reading Viking resources: {str(e)}"+ finally:+ await self._release_client(tool_context, client)diff --git a/bot/vikingbot/agent/tools/registry.py b/bot/vikingbot/agent/tools/registry.pyindex e85b9b6ea..d2c34c204 100644--- a/bot/vikingbot/agent/tools/registry.py+++ b/bot/vikingbot/agent/tools/registry.py@@ -141,6 +141,7 @@ class ToolRegistry:sandbox_manager: SandboxManager | None = None,sender_id: str | None = None,memory_user_ids: list[str] | None = None,+ openviking_connection: dict[str, Any] | None = None,) -> str:"""Execute a tool by name with given parameters.@@ -152,6 +153,7 @@ class ToolRegistry:sandbox_manager: Sandbox manager for file/shell operations.sender_id: Sender id for the current session.memory_user_ids: List of user IDs for memory retrieval.+ openviking_connection: Request-scoped OpenViking identity.Returns:Tool execution result as string.@@ -168,6 +170,7 @@ class ToolRegistry:sandbox_manager=sandbox_manager,sender_id=sender_id,memory_user_ids=memory_user_ids,+ openviking_connection=openviking_connection,)# Langfuse tool call tracing - automatic for all tools@@ -199,7 +202,7 @@ class ToolRegistry:if tool_span is not None:try:execute_success = not isinstance(result, Exception) and not (- isinstance(result, str) and result.startswith("Error")+ isinstance(result, str) and result.lstrip().startswith("Error:"))output_str = str(result) if result is not None else Noneself.langfuse.end_tool_call(@@ -242,4 +245,4 @@ class ToolRegistry:return len(self._tools)def __contains__(self, name: str) -> bool:- return name in self._tools\ No newline at end of file+ return name in self._toolsdiff --git a/bot/vikingbot/bus/events.py b/bot/vikingbot/bus/events.pyindex 119d33290..958cba488 100644--- a/bot/vikingbot/bus/events.py+++ b/bot/vikingbot/bus/events.py@@ -15,6 +15,8 @@ class OutboundEventType(str, Enum):TOOL_CALL = "tool_call" # Tool being calledTOOL_RESULT = "tool_result" # Result from tool executionREASONING = "reasoning" # Reasoning content+ CONTENT_DELTA = "content_delta" # Streaming response text delta+ REASONING_DELTA = "reasoning_delta" # Streaming reasoning text deltaITERATION = "iteration" # Iteration markerNO_REPLY = "no_reply" # No reply requiredRESPONSE_COMPLETED = "response_completed" # Analytics-only response fact@@ -36,6 +38,7 @@ class InboundMessage:need_reply: bool = Truemedia: list[str] = field(default_factory=list) # Media URLsmetadata: dict[str, Any] = field(default_factory=dict) # Channel-specific data+ openviking_connection: dict[str, Any] | None = None # Internal OpenViking identity@dataclassdiff --git a/bot/vikingbot/channels/openapi.py b/bot/vikingbot/channels/openapi.pyindex b6923db15..2fc009736 100644--- a/bot/vikingbot/channels/openapi.py+++ b/bot/vikingbot/channels/openapi.py@@ -215,6 +215,10 @@ class OpenAPIChannel(BaseChannel):await pending.close_stream()elif msg.event_type == OutboundEventType.REASONING:await pending.add_event("reasoning", msg.content)+ elif msg.event_type == OutboundEventType.CONTENT_DELTA:+ await pending.add_event("content_delta", msg.content)+ elif msg.event_type == OutboundEventType.REASONING_DELTA:+ await pending.add_event("reasoning_delta", msg.content)elif msg.event_type == OutboundEventType.TOOL_CALL:await pending.add_event("tool_call", msg.content)elif msg.event_type == OutboundEventType.TOOL_RESULT:@@ -242,6 +246,10 @@ class OpenAPIChannel(BaseChannel):await pending.close_stream()elif msg.event_type == OutboundEventType.REASONING:await pending.add_event("reasoning", msg.content)+ elif msg.event_type == OutboundEventType.CONTENT_DELTA:+ await pending.add_event("content_delta", msg.content)+ elif msg.event_type == OutboundEventType.REASONING_DELTA:+ await pending.add_event("reasoning_delta", msg.content)elif msg.event_type == OutboundEventType.TOOL_CALL:await pending.add_event("tool_call", msg.content)elif msg.event_type == OutboundEventType.TOOL_RESULT:@@ -442,11 +450,31 @@ class OpenAPIChannel(BaseChannel):self._app.include_router(router, prefix="/bot/v1")logger.info("OpenAPI routes registered at root path")+ def _request_user_id(self, request: ChatRequest) -> str:+ if request.user_id:+ return request.user_id+ if request.openviking_connection and request.openviking_connection.user_id:+ return request.openviking_connection.user_id+ return "anonymous"++ def _request_metadata(self, request: ChatRequest) -> dict[str, Any]:+ disabled_tools = list(request.disabled_tools or [])+ if "message" not in disabled_tools:+ disabled_tools.append("message")+ return {"disabled_tools": disabled_tools}++ def _request_openviking_connection(self, request: ChatRequest) -> dict[str, Any] | None:+ if request.openviking_connection:+ connection = request.openviking_connection.model_dump(exclude_none=True)+ if connection:+ return connection+ return None+async def _handle_chat(self, request: ChatRequest) -> ChatResponse:"""Handle a chat request."""# Generate or use provided session IDsession_id = request.session_id or str(uuid.uuid4())- user_id = request.user_id or "anonymous"+ user_id = self._request_user_id(request)# Create session if newif session_id not in self._sessions:@@ -485,7 +513,8 @@ class OpenAPIChannel(BaseChannel):session_key=session_key,sender_id=user_id,content=content,- metadata={"disabled_tools": request.disabled_tools},+ metadata=self._request_metadata(request),+ openviking_connection=self._request_openviking_connection(request),)await self.bus.publish_inbound(msg)@@ -520,7 +549,7 @@ class OpenAPIChannel(BaseChannel):async def _handle_chat_stream(self, request: ChatRequest) -> StreamingResponse:"""Handle a streaming chat request."""session_id = request.session_id or str(uuid.uuid4())- user_id = request.user_id or "anonymous"+ user_id = self._request_user_id(request)# Create session if newif session_id not in self._sessions:@@ -551,7 +580,8 @@ class OpenAPIChannel(BaseChannel):session_key=session_key,sender_id=user_id,content=request.message,- metadata={"disabled_tools": request.disabled_tools},+ metadata=self._request_metadata(request),+ openviking_connection=self._request_openviking_connection(request),)await self.bus.publish_inbound(msg)@@ -587,7 +617,7 @@ class OpenAPIChannel(BaseChannel):"""Handle a BotChannel chat request."""# Generate or use provided session IDsession_id = request.session_id or str(uuid.uuid4())- user_id = request.user_id or "anonymous"+ user_id = self._request_user_id(request)# Ensure channel has session storageif channel_id not in self._bot_sessions:@@ -631,7 +661,8 @@ class OpenAPIChannel(BaseChannel):sender_id=user_id,content=content,need_reply=request.need_reply,- metadata={"disabled_tools": request.disabled_tools},+ metadata=self._request_metadata(request),+ openviking_connection=self._request_openviking_connection(request),)await self.bus.publish_inbound(msg)@@ -669,7 +700,7 @@ class OpenAPIChannel(BaseChannel):) -> StreamingResponse:"""Handle a BotChannel streaming chat request."""session_id = request.session_id or str(uuid.uuid4())- user_id = request.user_id or "anonymous"+ user_id = self._request_user_id(request)# Ensure channel has session storageif channel_id not in self._bot_sessions:@@ -704,7 +735,8 @@ class OpenAPIChannel(BaseChannel):session_key=session_key,sender_id=user_id,content=request.message,- metadata={"disabled_tools": request.disabled_tools},+ metadata=self._request_metadata(request),+ openviking_connection=self._request_openviking_connection(request),)await self.bus.publish_inbound(msg)@@ -907,4 +939,4 @@ def get_openapi_router(bus: MessageBus, config: Config) -> APIRouter:)logger.info(f"Subscribed to bot_api channel: {channel_id}")- return channel.get_router()\ No newline at end of file+ return channel.get_router()diff --git a/bot/vikingbot/channels/openapi_models.py b/bot/vikingbot/channels/openapi_models.pyindex 102081e79..8e1f258a2 100644--- a/bot/vikingbot/channels/openapi_models.py+++ b/bot/vikingbot/channels/openapi_models.py@@ -23,6 +23,8 @@ class EventType(str, Enum):TOOL_CALL = "tool_call"TOOL_RESULT = "tool_result"REASONING = "reasoning"+ CONTENT_DELTA = "content_delta"+ REASONING_DELTA = "reasoning_delta"ITERATION = "iteration"@@ -44,6 +46,21 @@ class ChatMessage(BaseModel):)+class OpenVikingConnection(BaseModel):+ """OpenViking identity forwarded by the Studio proxy."""++ api_key: Optional[str] = Field(default=None, description="API key from the active client")+ account_id: Optional[str] = Field(default=None, description="Effective account ID")+ user_id: Optional[str] = Field(default=None, description="Effective user ID")+ agent_id: Optional[str] = Field(default=None, description="Effective agent ID")+ role: Optional[str] = Field(default=None, description="Effective OpenViking role")+ namespace_policy: Optional[Dict[str, bool]] = Field(+ default=None,+ description="Effective account namespace policy",+ )+ server_url: Optional[str] = Field(default=None, description="OpenViking server URL")++class ChatRequest(BaseModel):"""Request body for chat endpoint."""@@ -64,6 +81,10 @@ class ChatRequest(BaseModel):default_factory=list,description="Tool names to hide for this request",)+ openviking_connection: Optional[OpenVikingConnection] = Field(+ default=None,+ description="Authenticated OpenViking connection forwarded by the server proxy",+ )class ChatResponse(BaseModel):@@ -183,4 +204,4 @@ class ErrorResponse(BaseModel):error: str = Field(..., description="Error message")code: Optional[str] = Field(default=None, description="Error code")- detail: Optional[str] = Field(default=None, description="Detailed error information")\ No newline at end of file+ detail: Optional[str] = Field(default=None, description="Detailed error information")diff --git a/bot/vikingbot/hooks/builtins/openviking_hooks.py b/bot/vikingbot/hooks/builtins/openviking_hooks.pyindex 51a47459c..ba4555459 100644--- a/bot/vikingbot/hooks/builtins/openviking_hooks.py+++ b/bot/vikingbot/hooks/builtins/openviking_hooks.py@@ -45,8 +45,20 @@ async def get_global_client(workspace_id: str | None) -> VikingClient:class OpenVikingCompactHook(Hook):name = "openviking_compact"- async def _get_client(self, workspace_id: str) -> VikingClient:- return await get_global_client(workspace_id)+ async def _get_client(+ self,+ workspace_id: str,+ openviking_connection: dict[str, Any] | None = None,+ ) -> tuple[VikingClient, bool]:+ if openviking_connection:+ return (+ await VikingClient.create(+ workspace_id,+ connection=openviking_connection,+ ),+ True,+ )+ return await get_global_client(workspace_id), Falseasync def _execute_session_context_commit(self,@@ -288,6 +300,9 @@ class OpenVikingCompactHook(Hook):ov_config = config.ov_serveragents_config = config.agentsadmin_user_id = ov_config.admin_user_id+ openviking_connection = kwargs.get("openviking_connection")+ if not isinstance(openviking_connection, dict):+ openviking_connection = Noneforce_commit = bool(kwargs.get("force_commit", False))keep_recent_count = int(kwargs.get(@@ -301,7 +316,19 @@ class OpenVikingCompactHook(Hook):commit_message_threshold = int(commit_message_threshold)try:- client = await self._get_client(context.workspace_id)+ if openviking_connection:+ client_result = await self._get_client(+ context.workspace_id,+ openviking_connection=openviking_connection,+ )+ else:+ client_result = await self._get_client(context.workspace_id)+ if isinstance(client_result, tuple):+ client, should_close_client = client_result+ else:+ client = client_result+ should_close_client = False+ admin_user_id = getattr(client, "admin_user_id", None) or admin_user_idif getattr(agents_config, "session_context_enabled", False):return await self._execute_session_context_commit(@@ -365,6 +392,9 @@ class OpenVikingCompactHook(Hook):state["last_sync_error"] = str(e)logger.exception(f"Failed to add message to OpenViking: {e}")return {"success": False, "error": str(e)}+ finally:+ if "should_close_client" in locals() and should_close_client:+ await client.close()class OpenVikingPostCallHook(Hook):diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex e28fa4212..7016630b5 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -2,7 +2,7 @@ import asyncioimport jsonimport reimport uuid-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Mapping, Optionalfrom loguru import logger@@ -13,12 +13,28 @@ from vikingbot.openviking_mount.user_apikey_manager import UserApiKeyManagerviking_resource_prefix = "viking://resources/"+def _is_session_key(agent_id: Optional[str]) -> bool:+ return agent_id is not None and "__" in agent_id++class VikingClient:- def __init__(self, workspace_id: Optional[str] = None):+ def __init__(+ self,+ workspace_id: Optional[str] = None,+ *,+ agent_id: Optional[str] = None,+ connection: Optional[Mapping[str, Any]] = None,+ ):+ if agent_id is None:+ agent_id = workspace_id+ if agent_id and "#" in agent_id:+ agent_id = agent_id.split("#", 1)[0]+config = load_config()openviking_config = config.ov_serverself.openviking_config = openviking_config- self.workspace_id = workspace_id+ self.workspace_id = agent_id+ self.agent_id = agent_idself.ov_path = config.ov_data_pathself.mode = openviking_config.modeself.api_key_type = (openviking_config.api_key_type or "root").strip().lower()@@ -28,14 +44,29 @@ class VikingClient:self._apikey_manager = Noneself.admin_user_client = Noneself._user_clients = {}+ self._namespace_policy = {+ "isolate_user_scope_by_agent": False,+ "isolate_agent_scope_by_user": False,+ }+ self._namespace_policy_loaded = False+ self._request_connection = self._normalize_connection(connection)+ self._request_role: str | None = Noneif openviking_config.mode == "local":- self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)+ if agent_id is None or _is_session_key(agent_id):+ self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)+ self.agent_id = "default"+ else:+ self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)self.account_id = "default"self.user_id = "default"self.admin_user_id = "default"return+ if self._request_connection:+ self._configure_request_connection(agent_id)+ return+self.account_id = openviking_config.account_idself.admin_user_id = openviking_config.admin_user_id@@ -56,14 +87,74 @@ class VikingClient:account_id=openviking_config.account_id,)+ @staticmethod+ def _normalize_connection(+ connection: Optional[Mapping[str, Any]],+ ) -> dict[str, Any] | None:+ if not isinstance(connection, Mapping):+ return None+ normalized: dict[str, Any] = {}+ for key in ("api_key", "account_id", "user_id", "agent_id", "role", "server_url"):+ value = connection.get(key)+ if isinstance(value, str) and value.strip():+ normalized[key] = value.strip()+ policy = connection.get("namespace_policy")+ if isinstance(policy, Mapping):+ normalized["namespace_policy"] = {+ "isolate_user_scope_by_agent": bool(+ policy.get("isolate_user_scope_by_agent", False)+ ),+ "isolate_agent_scope_by_user": bool(+ policy.get("isolate_agent_scope_by_user", False)+ ),+ }+ if not normalized.get("api_key"):+ return None+ return normalized++ def _configure_request_connection(self, agent_id: Optional[str]) -> None:+ connection = self._request_connection or {}+ self.mode = "remote"+ request_role = str(connection.get("role") or "").strip().lower()+ self._request_role = request_role or None+ self.api_key_type = "user"+ self.agent_id = connection.get("agent_id") or agent_id+ self.workspace_id = self.agent_id+ self.account_id = connection.get("account_id") or self.openviking_config.account_id+ self.admin_user_id = connection.get("user_id") or self.openviking_config.admin_user_id++ policy = connection.get("namespace_policy")+ if isinstance(policy, dict):+ self._namespace_policy = policy+ self._namespace_policy_loaded = True++ remote_client_kwargs = {+ "url": connection.get("server_url") or self.openviking_config.server_url,+ "api_key": connection["api_key"],+ "profile_enabled": False,+ }+ if request_role != "user" and self.account_id:+ remote_client_kwargs["account"] = self.account_id+ if request_role != "user" and self.admin_user_id:+ remote_client_kwargs["user"] = self.admin_user_id++ self.client = ov.AsyncHTTPClient(**remote_client_kwargs)+async def _initialize(self):"""Initialize the client (must be called after construction)"""await self.client.initialize()+ await self._load_namespace_policy()@classmethod- async def create(cls, workspace_id: Optional[str] = None):+ async def create(+ cls,+ workspace_id: Optional[str] = None,+ *,+ agent_id: Optional[str] = None,+ connection: Optional[Mapping[str, Any]] = None,+ ):"""Factory method to create and initialize a VikingClient instance."""- instance = cls(workspace_id=workspace_id)+ instance = cls(workspace_id=workspace_id, agent_id=agent_id, connection=connection)await instance._initialize()return instance@@ -93,20 +184,78 @@ class VikingClient:}def _is_root_key_mode(self) -> bool:- return self.mode == "remote" and self.api_key_type == "root"+ return (+ self.mode == "remote"+ and self.api_key_type == "root"+ and not self._has_request_connection()+ )def _is_user_key_mode(self) -> bool:- return self.mode == "remote" and self.api_key_type == "user"+ return (+ self.mode == "remote"+ and self.api_key_type == "user"+ and not self._has_request_connection()+ )++ def _has_request_connection(self) -> bool:+ return self._request_connection is not None++ def should_sender_fanout(self) -> bool:+ return self._is_root_key_mode()def _effective_user_id(self, user_id: Optional[str]) -> str:+ if self._has_request_connection():+ return user_id or self.admin_user_idif self._is_user_key_mode():return ""return user_id or self.admin_user_id+ def _effective_session_user_id(self, user_id: Optional[str] = None) -> Optional[str]:+ if self._has_request_connection():+ return self.admin_user_id or user_id+ return user_id or self.admin_user_id++ async def _load_namespace_policy(self) -> None:+ if self._namespace_policy_loaded:+ return++ policy = {+ "isolate_user_scope_by_agent": False,+ "isolate_agent_scope_by_user": False,+ }+ if self._has_request_connection():+ self._namespace_policy = policy+ self._namespace_policy_loaded = True+ return++ if self.mode == "remote" and self.account_id:+ try:+ accounts = await self.client.admin_list_accounts()+ for account in accounts or []:+ if account.get("account_id") == self.account_id:+ policy = {+ "isolate_user_scope_by_agent": bool(+ account.get("isolate_user_scope_by_agent", False)+ ),+ "isolate_agent_scope_by_user": bool(+ account.get("isolate_agent_scope_by_user", False)+ ),+ }+ break+ except Exception as e:+ logger.warning(+ f"Failed to load account namespace policy for {self.account_id}: {e}"+ )++ self._namespace_policy = policy+ self._namespace_policy_loaded = True+def _user_space_fragment(self, user_id: Optional[str]) -> str:effective_user_id = self._effective_user_id(user_id)if not effective_user_id:return ""+ if self._namespace_policy["isolate_user_scope_by_agent"] and self.agent_id:+ return f"{effective_user_id}/agent/{self.agent_id}"return effective_user_iddef _memory_target_uri(self, user_id: Optional[str]) -> str:@@ -118,9 +267,6 @@ class VikingClient:def _skill_memory_uri(self, skill_name: str, user_id: Optional[str] = None) -> str:return f"{self._memory_target_uri(user_id)}skills/{skill_name}.md"- def should_sender_fanout(self) -> bool:- return self._is_root_key_mode()-async def find(self, query: str, target_uri: Optional[str] = None):"""搜索资源"""if target_uri:@@ -225,7 +371,7 @@ class VikingClient:async def _check_user_exists(self, user_id: str) -> bool:"""检查用户是否存在于账户中。"""- if self.mode == "local" or self._is_user_key_mode():+ if self.mode == "local" or self._is_user_key_mode() or self._has_request_connection():return Trueif not user_id:return False@@ -240,7 +386,7 @@ class VikingClient:async def _initialize_user(self, user_id: str, role: str = "user") -> bool:"""初始化用户。"""- if self.mode == "local" or self._is_user_key_mode():+ if self.mode == "local" or self._is_user_key_mode() or self._has_request_connection():return Trueif not user_id:return False@@ -263,7 +409,12 @@ class VikingClient:async def _get_or_create_user_apikey(self, user_id: str, role: str = "user") -> Optional[str]:"""获取或创建用户的 API key。"""- if self._is_user_key_mode() or not self._apikey_manager or not user_id:+ if (+ self._has_request_connection()+ or self._is_user_key_mode()+ or not self._apikey_manager+ or not user_id+ ):return Noneapi_key = self._apikey_manager.get_apikey(user_id)@@ -312,6 +463,7 @@ class VikingClient:client_kwargs = {"url": self.openviking_config.server_url,"api_key": user_api_key,+ "profile_enabled": False,}if effective_user_id == self.admin_user_id:client_kwargs["account"] = self.account_id@@ -324,8 +476,12 @@ class VikingClient:return self.client, Falseasync def search_memory(- self, query: str, user_ids: str | list[str], limit: int = 10- ) -> list[Any]:+ self,+ query: str,+ user_ids: str | list[str],+ limit: int = 10,+ agent_user_id: Optional[str] = None,+ ) -> list[Any] | dict[str, list[Any]]:"""通过上下文消息检索用户 memory。"""def _extract_memories(result: Any) -> list[Any]:@@ -359,6 +515,18 @@ class VikingClient:)all_user_memories.extend(_extract_memories(user_memory))+ if agent_user_id is not None:+ agent_uri = f"viking://agent/{self.agent_id or self.admin_user_id}/memories/"+ agent_memory = await self.client.find(+ query=query,+ target_uri=agent_uri,+ limit=limit,+ )+ return {+ "user_memory": all_user_memories,+ "agent_memory": _extract_memories(agent_memory),+ }+return all_user_memoriesasync def search_experiences(self, query: str, limit: int = 5) -> list[Any]:@@ -415,6 +583,8 @@ class VikingClient:return self.admin_user_client or self.clientasync def _session_client_for_user(self, user_id: Optional[str] = None):+ if self._has_request_connection():+ return self.clientif not user_id or self.mode == "local" or self._is_user_key_mode():return self._session_client(user_id)if user_id == self.admin_user_id and self.admin_user_client:@@ -433,6 +603,9 @@ class VikingClient:client = ov.AsyncHTTPClient(url=self.openviking_config.server_url,api_key=api_key,+ account=self.account_id,+ user=user_id,+ profile_enabled=False,)await client.initialize()self._user_clients[user_id] = client@@ -615,16 +788,17 @@ class VikingClient:keep_recent_count: int = 0,):"""Append messages to a stable session and commit it."""+ session_user_id = self._effective_session_user_id(user_id)appended = await self.append_messages(session_id,messages,- default_user_peer_id=user_id or self.admin_user_id,- session_user_id=user_id,+ default_user_peer_id=session_user_id,+ session_user_id=session_user_id,)commit_result = await self.commit_session(session_id,keep_recent_count=keep_recent_count,- user_id=user_id,+ user_id=session_user_id,)logger.debug(f"Committed OpenViking session {session_id}, "diff --git a/bot/vikingbot/providers/base.py b/bot/vikingbot/providers/base.pyindex 6d00de8f1..c859e7343 100644--- a/bot/vikingbot/providers/base.py+++ b/bot/vikingbot/providers/base.py@@ -1,8 +1,9 @@"""Base LLM provider interface."""+import jsonfrom abc import ABC, abstractmethodfrom dataclasses import dataclass, field-from typing import Any+from typing import Any, AsyncIterator, Callable, Literal@dataclass@@ -31,6 +32,89 @@ class LLMResponse:return len(self.tool_calls) > 0+@dataclass+class LLMStreamEvent:+ """Streaming event emitted by an LLM provider."""++ type: Literal["content_delta", "reasoning_delta", "response"]+ content: str | None = None+ response: LLMResponse | None = None+++def stream_delta_value(delta: Any, name: str) -> str:+ value = getattr(delta, name, None)+ return value if isinstance(value, str) else ""+++def merge_stream_tool_call_delta(+ raw_tool_calls: dict[int, dict[str, Any]],+ delta_tool_call: Any,+) -> None:+ index = getattr(delta_tool_call, "index", None)+ if index is None:+ index = len(raw_tool_calls)+ entry = raw_tool_calls.setdefault(+ int(index),+ {"id": "", "name": "", "arguments": ""},+ )+ tool_call_id = getattr(delta_tool_call, "id", None)+ if tool_call_id:+ entry["id"] = tool_call_id+ function = getattr(delta_tool_call, "function", None)+ if function is None:+ return+ name = getattr(function, "name", None)+ if name:+ entry["name"] += name+ arguments = getattr(function, "arguments", None)+ if arguments:+ entry["arguments"] += arguments+++def build_stream_response(+ *,+ content: str,+ reasoning_content: str,+ raw_tool_calls: dict[int, dict[str, Any]],+ finish_reason: str,+ usage: dict[str, int] | None = None,+ token_counter: Callable[[str, str], int] | None = None,+) -> LLMResponse:+ tool_calls: list[ToolCallRequest] = []+ for index in sorted(raw_tool_calls):+ raw_tool_call = raw_tool_calls[index]+ name = str(raw_tool_call.get("name") or "")+ if not name:+ continue+ raw_arguments = str(raw_tool_call.get("arguments") or "")+ arguments: dict[str, Any]+ if raw_arguments:+ try:+ parsed_arguments = json.loads(raw_arguments)+ arguments = parsed_arguments if isinstance(parsed_arguments, dict) else {}+ except json.JSONDecodeError:+ arguments = {"raw": raw_arguments}+ else:+ arguments = {}+ tokens = token_counter(name, raw_arguments) if token_counter else 0+ tool_calls.append(+ ToolCallRequest(+ id=str(raw_tool_call.get("id") or f"tool_call_{index}"),+ name=name,+ arguments=arguments,+ tokens=tokens,+ )+ )++ return LLMResponse(+ content=content or None,+ tool_calls=tool_calls,+ finish_reason=finish_reason,+ usage=usage or {},+ reasoning_content=reasoning_content or None,+ )++class LLMProvider(ABC):"""Abstract base class for LLM providers.@@ -69,6 +153,29 @@ class LLMProvider(ABC):"""pass+ async def chat_stream(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ session_id: str | None = None,+ ) -> AsyncIterator[LLMStreamEvent]:+ """Stream a chat completion request.++ Providers without native streaming fall back to a single final response event.+ """+ response = await self.chat(+ messages=messages,+ tools=tools,+ model=model,+ max_tokens=max_tokens,+ temperature=temperature,+ session_id=session_id,+ )+ yield LLMStreamEvent(type="response", response=response)+@abstractmethoddef get_default_model(self) -> str:"""Get the default model for this provider."""diff --git a/bot/vikingbot/providers/litellm_provider.py b/bot/vikingbot/providers/litellm_provider.pyindex 6114b0741..6c2610df5 100644--- a/bot/vikingbot/providers/litellm_provider.py+++ b/bot/vikingbot/providers/litellm_provider.py@@ -2,14 +2,22 @@import jsonimport os-from typing import Any+from typing import Any, AsyncIteratorimport litellmfrom litellm import acompletionfrom loguru import loggerfrom vikingbot.integrations.langfuse import LangfuseClient-from vikingbot.providers.base import LLMProvider, LLMResponse, ToolCallRequest+from vikingbot.providers.base import (+ LLMProvider,+ LLMResponse,+ LLMStreamEvent,+ ToolCallRequest,+ build_stream_response,+ merge_stream_tool_call_delta,+ stream_delta_value,+)from vikingbot.providers.registry import find_by_model, find_gatewayfrom vikingbot.utils.helpers import cal_str_tokensfrom vikingbot.utils.tracing import get_current_response_id@@ -339,6 +347,116 @@ class LiteLLMProvider(LLMProvider):finish_reason="error",)+ async def chat_stream(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ session_id: str | None = None,+ ) -> AsyncIterator[LLMStreamEvent]:+ """Send a streaming chat completion request via LiteLLM."""+ model = self._resolve_model(model or self.default_model)+ messages = self._handle_system_message(model, messages)++ kwargs: dict[str, Any] = {+ "model": model,+ "messages": messages,+ "max_tokens": max_tokens,+ "temperature": temperature,+ "stream": True,+ }+ self._apply_model_overrides(model, kwargs)++ if self.api_key:+ kwargs["api_key"] = self.api_key+ if self.api_base:+ kwargs["api_base"] = self.api_base+ if self.extra_headers:+ kwargs["extra_headers"] = self.extra_headers+ if tools:+ kwargs["tools"] = tools+ kwargs["tool_choice"] = "auto"++ content_parts: list[str] = []+ reasoning_parts: list[str] = []+ tool_calls: dict[int, dict[str, Any]] = {}+ finish_reason = "stop"+ usage: dict[str, int] = {}++ try:+ response = await acompletion(**kwargs)+ async for chunk in response:+ if getattr(chunk, "usage", None):+ usage = self._parse_usage(chunk.usage)++ choices = getattr(chunk, "choices", None) or []+ if not choices:+ continue+ choice = choices[0]+ if getattr(choice, "finish_reason", None):+ finish_reason = choice.finish_reason or finish_reason++ delta = getattr(choice, "delta", None)+ if delta is None:+ continue++ reasoning_delta = stream_delta_value(delta, "reasoning_content")+ if reasoning_delta:+ reasoning_parts.append(reasoning_delta)+ yield LLMStreamEvent(type="reasoning_delta", content=reasoning_delta)++ content_delta = stream_delta_value(delta, "content")+ if content_delta:+ content_parts.append(content_delta)+ yield LLMStreamEvent(type="content_delta", content=content_delta)++ for delta_tool_call in getattr(delta, "tool_calls", None) or []:+ merge_stream_tool_call_delta(tool_calls, delta_tool_call)++ response_obj = build_stream_response(+ content="".join(content_parts),+ reasoning_content="".join(reasoning_parts),+ raw_tool_calls=tool_calls,+ finish_reason=finish_reason,+ usage=usage,+ token_counter=self._stream_tool_tokens,+ )+ yield LLMStreamEvent(type="response", response=response_obj)+ except Exception as e:+ yield LLMStreamEvent(+ type="response",+ response=LLMResponse(+ content=f"Error calling LLM in LiteLLM stream: {str(e)}",+ finish_reason="error",+ ),+ )++ @staticmethod+ def _parse_usage(raw_usage: Any) -> dict[str, int]:+ if not raw_usage:+ return {}+ usage = {+ "prompt_tokens": int(getattr(raw_usage, "prompt_tokens", 0) or 0),+ "completion_tokens": int(getattr(raw_usage, "completion_tokens", 0) or 0),+ "total_tokens": int(getattr(raw_usage, "total_tokens", 0) or 0),+ }+ details = getattr(raw_usage, "prompt_tokens_details", None)+ cached = getattr(details, "cached_tokens", 0) if details else 0+ if not cached:+ cached = getattr(raw_usage, "cache_read_input_tokens", 0) or 0+ if cached:+ usage["cache_read_input_tokens"] = int(cached)+ return usage++ @staticmethod+ def _stream_tool_tokens(name: str, raw_arguments: str) -> int:+ tokens = cal_str_tokens(name, text_type="en")+ if raw_arguments:+ tokens += cal_str_tokens(raw_arguments, text_type="mixed")+ return tokens+def _parse_response(self, response: Any) -> LLMResponse:"""Parse LiteLLM response into our standard format."""choice = response.choices[0]diff --git a/bot/vikingbot/providers/vlm_adapter.py b/bot/vikingbot/providers/vlm_adapter.pyindex fdafa5f06..91c02e5c6 100644--- a/bot/vikingbot/providers/vlm_adapter.py+++ b/bot/vikingbot/providers/vlm_adapter.py@@ -5,12 +5,21 @@ LLMProvider interface, so that bot.agents.provider / bot.agents.modelconfiguration semantics are consistent with openviking server's vlm section."""+from collections.abc import AsyncIteratorfrom typing import Anyfrom loguru import loggerfrom vikingbot.integrations.langfuse import LangfuseClient-from vikingbot.providers.base import LLMProvider, LLMResponse, ToolCallRequest+from vikingbot.providers.base import (+ LLMProvider,+ LLMResponse,+ LLMStreamEvent,+ ToolCallRequest,+ build_stream_response,+ merge_stream_tool_call_delta,+ stream_delta_value,+)from vikingbot.utils.tracing import get_current_response_id@@ -91,6 +100,108 @@ class VLMProviderAdapter(LLMProvider):finish_reason="error",)+ async def chat_stream(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ session_id: str | None = None,+ ) -> AsyncIterator[LLMStreamEvent]:+ if getattr(self._vlm, "provider", None) != "volcengine":+ async for event in super().chat_stream(+ messages=messages,+ tools=tools,+ model=model,+ max_tokens=max_tokens,+ temperature=temperature,+ session_id=session_id,+ ):+ yield event+ return++ async for event in self._chat_stream_volcengine(+ messages=messages,+ tools=tools,+ model=model,+ max_tokens=max_tokens,+ temperature=temperature,+ ):+ yield event++ async def _chat_stream_volcengine(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None,+ model: str | None,+ max_tokens: int,+ temperature: float,+ ) -> AsyncIterator[LLMStreamEvent]:+ kwargs: dict[str, Any] = {+ "model": model or getattr(self._vlm, "model", None) or self._default_model,+ "messages": messages,+ "temperature": getattr(self._vlm, "temperature", temperature),+ "max_tokens": getattr(self._vlm, "max_tokens", None) or max_tokens,+ "thinking": {+ "type": "enabled" if getattr(self._vlm, "thinking", False) else "disabled"+ },+ "stream": True,+ }+ if tools:+ kwargs["tools"] = tools+ kwargs["tool_choice"] = "auto"++ content_parts: list[str] = []+ reasoning_parts: list[str] = []+ tool_calls: dict[int, dict[str, Any]] = {}+ finish_reason = "stop"++ try:+ client = self._vlm.get_async_client()+ response = await client.chat.completions.create(**kwargs)+ async for chunk in response:+ choices = getattr(chunk, "choices", None) or []+ if not choices:+ continue+ choice = choices[0]+ if getattr(choice, "finish_reason", None):+ finish_reason = choice.finish_reason or finish_reason+ delta = getattr(choice, "delta", None)+ if delta is None:+ continue++ reasoning_delta = stream_delta_value(delta, "reasoning_content")+ if reasoning_delta:+ reasoning_parts.append(reasoning_delta)+ yield LLMStreamEvent(type="reasoning_delta", content=reasoning_delta)++ content_delta = stream_delta_value(delta, "content")+ if content_delta:+ content_parts.append(content_delta)+ yield LLMStreamEvent(type="content_delta", content=content_delta)++ for delta_tool_call in getattr(delta, "tool_calls", None) or []:+ merge_stream_tool_call_delta(tool_calls, delta_tool_call)++ yield LLMStreamEvent(+ type="response",+ response=build_stream_response(+ content="".join(content_parts),+ reasoning_content="".join(reasoning_parts),+ raw_tool_calls=tool_calls,+ finish_reason=finish_reason,+ ),+ )+ except Exception as e:+ yield LLMStreamEvent(+ type="response",+ response=LLMResponse(+ content=f"Error calling LLM in VLM Adapter stream: {str(e)}",+ finish_reason="error",+ ),+ )+def _convert_response(self, result) -> LLMResponse:"""Convert VLMResponse (or str) to LLMResponse."""if isinstance(result, str):@@ -127,8 +238,7 @@ class VLMProviderAdapter(LLMProvider):output_text = llm_response.content or ""if llm_response.tool_calls:output_text = (- output_text- or f"[Tool calls: {[tc.name for tc in llm_response.tool_calls]}]"+ output_text or f"[Tool calls: {[tc.name for tc in llm_response.tool_calls]}]")update_kwargs: dict[str, Any] = {diff --git a/openviking/server/routers/bot.py b/openviking/server/routers/bot.pyindex 167d47aac..c5c0134ba 100644--- a/openviking/server/routers/bot.py+++ b/openviking/server/routers/bot.py@@ -12,7 +12,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request, statusfrom fastapi.responses import StreamingResponsefrom openviking.server.auth import get_request_context-from openviking.server.identity import RequestContext+from openviking.server.identity import AuthMode, RequestContextfrom openviking_cli.utils.logger import get_loggerrouter = APIRouter(prefix="", tags=["bot"])@@ -22,6 +22,11 @@ logger = get_logger(__name__)# Bot API configuration - set when --with-bot is enabledBOT_API_URL: Optional[str] = None # e.g., "http://localhost:18791"BOT_API_KEY: str = ""+DEFAULT_BOT_AGENT_ID = "web-playground"+DEFAULT_NAMESPACE_POLICY = {+ "isolate_user_scope_by_agent": False,+ "isolate_agent_scope_by_user": False,+}def _create_bot_proxy_client() -> httpx.AsyncClient:@@ -56,6 +61,52 @@ def get_bot_url() -> str:return BOT_API_URL+def _extract_forward_api_key(request: Request) -> str:+ api_key = request.headers.get("X-API-Key") or request.headers.get("x-api-key")+ if api_key:+ return api_key+ authorization = request.headers.get("Authorization") or request.headers.get("authorization")+ if authorization and authorization.lower().startswith("bearer "):+ return authorization[7:].strip()+ return ""+++def _attach_openviking_connection(+ body: dict,+ request: Request,+ ctx: RequestContext,+) -> dict:+ """Attach the authenticated Studio connection to the bot request body.++ The OpenViking proxy authenticates the browser request before forwarding it to+ vikingbot. Bot tools must keep using that same identity instead of falling back+ to vikingbot's static root/user-key configuration.+ """+ enriched = dict(body)+ api_key = _extract_forward_api_key(request)+ auth_mode = AuthMode.API_KEY+ config = getattr(request.app.state, "config", None)+ if config is not None and hasattr(config, "get_effective_auth_mode"):+ auth_mode = config.get_effective_auth_mode()+ if not api_key:+ if auth_mode == AuthMode.DEV:+ enriched.setdefault("user_id", ctx.user.user_id)+ return enriched+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Bot proxy requires a forwardable OpenViking API key.",+ )+ enriched["openviking_connection"] = {+ "api_key": api_key,+ "account_id": ctx.user.account_id,+ "user_id": ctx.user.user_id,+ "agent_id": DEFAULT_BOT_AGENT_ID,+ "role": getattr(ctx.role, "value", str(ctx.role)),+ "namespace_policy": dict(DEFAULT_NAMESPACE_POLICY),+ }+ return enriched++@router.get("/health")async def health_check(request: Request):"""Health check endpoint for Bot API.@@ -118,7 +169,7 @@ async def chat(# Forward to Vikingbot OpenAPIChannel chat endpointresponse = await client.post(f"{bot_url}/bot/v1/chat",- json=body,+ json=_attach_openviking_connection(body, request, _ctx),headers=headers,timeout=300.0, # 5 minute timeout for chat)@@ -226,7 +277,7 @@ async def chat_stream(async with client.stream("POST",f"{bot_url}/bot/v1/chat/stream",- json=body,+ json=_attach_openviking_connection(body, request, _ctx),headers=headers,timeout=300.0,) as response:diff --git a/openviking/service/session_service.py b/openviking/service/session_service.pyindex 0cf5fc38b..daa5f5e52 100644--- a/openviking/service/session_service.py+++ b/openviking/service/session_service.py@@ -6,13 +6,14 @@ Session Service for OpenViking.Provides session management operations: session, sessions, add_message, commit, delete."""+import jsonfrom typing import TYPE_CHECKING, Any, Dict, List, Optionalfrom openviking.core.namespace import canonical_session_urifrom openviking.server.config import ToolOutputExternalizationConfigfrom openviking.server.identity import RequestContext, Rolefrom openviking.service.task_tracker import get_task_tracker-from openviking.session import Session+from openviking.session import Session, SessionMetafrom openviking.session.memory_policy import MemoryPolicyfrom openviking.storage import VikingDBManagerfrom openviking.storage.viking_fs import VikingFS@@ -111,13 +112,56 @@ class SessionService:)@staticmethod- def _assert_session_owner(session: Session, ctx: RequestContext) -> None:- meta = session.meta- if (- meta.created_by_account_id != ctx.account_id- or meta.created_by_user_id != ctx.user.user_id- ):- raise NotFoundError(session.session_id, "session")+ def _session_account_id(meta: SessionMeta) -> str:+ return getattr(meta, "created_by_account_id", "") or getattr(meta, "account_id", "")++ def _session_is_visible_in_account(self, ctx: RequestContext, meta: SessionMeta) -> bool:+ if ctx.role == Role.ROOT:+ return True++ account_id = self._session_account_id(meta)+ return bool(account_id and account_id == ctx.account_id)++ async def _read_session_meta(self, session_id: str, ctx: RequestContext) -> SessionMeta:+ self._ensure_initialized()+ raw = await self._viking_fs.read_file(+ f"{canonical_session_uri(session_id)}/.meta.json",+ ctx=ctx,+ )+ data = json.loads(raw)+ if not data.get("created_by_account_id") and data.get("account_id"):+ data["created_by_account_id"] = data["account_id"]+ return SessionMeta.from_dict(data)++ async def _load_session_meta_for_visibility(+ self, session_id: str, ctx: RequestContext+ ) -> SessionMeta:+ """Read persisted metadata, deriving legacy fields without writing side effects."""+ try:+ meta = await self._read_session_meta(session_id, ctx)+ except Exception:+ session = self.session(ctx, session_id)+ await session.load()+ meta = session.meta+ if not meta.session_id:+ meta.session_id = session_id+ if not meta.created_by_account_id:+ session = self.session(ctx, session_id)+ await session.load()+ meta = session.meta+ if not meta.session_id:+ meta.session_id = session_id+ return meta++ async def _assert_session_visible(self, session_id: str, ctx: RequestContext) -> None:+ if ctx.role == Role.ROOT:+ return+ try:+ meta = await self._load_session_meta_for_visibility(session_id, ctx)+ except Exception as exc:+ raise NotFoundError(session_id, "session") from exc+ if not self._session_is_visible_in_account(ctx, meta):+ raise NotFoundError(session_id, "session")async def create(self,@@ -170,8 +214,9 @@ class SessionService:if not auto_create:raise NotFoundError(session_id, "session")await session.ensure_exists()+ else:+ await self._assert_session_visible(session_id, ctx)await session.load()- self._assert_session_owner(session, ctx)self._record_lifecycle_metric("get", "ok")return sessionexcept Exception:@@ -194,12 +239,13 @@ class SessionService:name = entry.get("name", "")if name in [".", ".."]:continue- try:- session = self.session(ctx, name)- await session.load()- self._assert_session_owner(session, ctx)- except Exception:- continue+ if ctx.role != Role.ROOT:+ try:+ meta = await self._load_session_meta_for_visibility(name, ctx)+ except Exception:+ continue+ if not self._session_is_visible_in_account(ctx, meta):+ continuesessions.append({"session_id": name,diff --git a/openviking/session/session.py b/openviking/session/session.pyindex 1833ae3fc..a4c42c3c2 100644--- a/openviking/session/session.py+++ b/openviking/session/session.py@@ -278,7 +278,8 @@ class SessionMeta:session_id=data.get("session_id", ""),created_at=data.get("created_at", ""),updated_at=data.get("updated_at", ""),- created_by_account_id=data.get("created_by_account_id", ""),+ created_by_account_id=data.get("created_by_account_id", "")+ or data.get("account_id", ""),created_by_user_id=data.get("created_by_user_id", ""),participant_user_ids=list(data.get("participant_user_ids", [])),message_count=data.get("message_count", 0),diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.pyindex db53bbdbc..3c4a60b71 100644--- a/openviking_cli/client/http.py+++ b/openviking_cli/client/http.py@@ -160,7 +160,7 @@ class AsyncHTTPClient(BaseClient):"""effective_user = user if user is not None else user_idprofile_load_requested = profile_enabled is None- should_load_cli_config = (+ should_load_cli_config = profile_enabled is not False and (url is Noneor api_key is Noneor account is Nonediff --git a/tests/api_test/sessions/test_session_commit_used_context.py b/tests/api_test/sessions/test_session_commit_used_context.pyindex 39b60d29c..c4ebc6d83 100644--- a/tests/api_test/sessions/test_session_commit_used_context.py+++ b/tests/api_test/sessions/test_session_commit_used_context.py@@ -224,7 +224,10 @@ class TestSessionCommitUsedContext:def test_get_session_context_nonexistent(self, api_client):ctx_resp = api_client.get_session_context("nonexistent-session-xyz")- assert ctx_resp.status_code == 200+ assert ctx_resp.status_code == 404+ body = ctx_resp.json()+ assert body.get("status") == "error"+ assert body.get("error", {}).get("code") == "NOT_FOUND"def test_session_context_contains_stats(self, api_client):session_id = Nonediff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.pyindex 961535c53..43e445e25 100644--- a/tests/server/test_api_sessions.py+++ b/tests/server/test_api_sessions.py@@ -18,6 +18,7 @@ from openviking.server.config import ServerConfig, ToolOutputExternalizationConffrom openviking.server.dependencies import set_servicefrom openviking.server.identity import RequestContext, Rolefrom openviking.server.routers import sessions as sessions_router+from openviking.session import SessionMetafrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.config import OPENVIKING_CONFIG_ENVfrom openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton@@ -154,6 +155,42 @@ async def test_get_session(client: httpx.AsyncClient):assert body["result"]["session_id"] == session_id+async def test_legacy_session_without_meta_remains_visible_to_owner(service):+ session_id = "legacy-no-meta"+ owner_ctx = RequestContext(+ user=UserIdentifier("acct-legacy", "owner"),+ role=Role.USER,+ )+ session = service.sessions.session(owner_ctx, session_id)+ await session.ensure_exists()+ session.add_message("user", [TextPart("legacy message")], peer_id="owner")+ await service.viking_fs.rm(f"viking://session/{session_id}/.meta.json", ctx=owner_ctx)++ loaded = await service.sessions.get(session_id, owner_ctx, auto_create=False)+ listed = await service.sessions.sessions(owner_ctx)++ assert [part.text for part in loaded.messages[0].parts] == ["legacy message"]+ assert loaded.meta.created_by_account_id == "acct-legacy"+ assert loaded.meta.created_by_user_id == "owner"+ assert any(item["session_id"] == session_id for item in listed)+++def test_session_visibility_is_account_scoped_for_non_root(service):+ ctx = RequestContext(+ user=UserIdentifier("acct-current", "owner"),+ role=Role.USER,+ )+ meta = SessionMeta(created_by_user_id="owner", participant_user_ids=["owner"])++ assert service.sessions._session_is_visible_in_account(ctx, meta) is False++ meta.created_by_account_id = "acct-current"+ meta.created_by_user_id = "someone-else"+ meta.participant_user_ids = ["someone-else"]+ assert service.sessions._session_is_visible_in_account(ctx, meta) is True++async def test_get_session_context(client: httpx.AsyncClient):create_resp = await client.post("/api/v1/sessions", json={})session_id = create_resp.json()["result"]["session_id"]diff --git a/tests/server/test_auth.py b/tests/server/test_auth.pyindex fd453d539..b54556329 100644--- a/tests/server/test_auth.py+++ b/tests/server/test_auth.py@@ -557,6 +557,72 @@ async def test_cross_tenant_session_get_returns_not_found(auth_client: httpx.Asyassert cross_get.json()["error"]["code"] == "NOT_FOUND"+async def test_sessions_are_visible_to_users_within_account(+ auth_client: httpx.AsyncClient, auth_app+):+ """Session access is account-scoped, not user-isolated within an account."""+ manager = auth_app.state.api_key_manager+ account_id = _uid()+ admin_key = await manager.create_account(account_id, "admin_user")+ alice_key = await manager.register_user(account_id, "alice")+ bob_key = await manager.register_user(account_id, "bob")++ alice_create = await auth_client.post(+ "/api/v1/sessions",+ json={},+ headers={"X-API-Key": alice_key},+ )+ assert alice_create.status_code == 200+ alice_session = alice_create.json()["result"]["session_id"]++ bob_create = await auth_client.post(+ "/api/v1/sessions",+ json={},+ headers={"X-API-Key": bob_key},+ )+ assert bob_create.status_code == 200+ bob_session = bob_create.json()["result"]["session_id"]++ alice_list = await auth_client.get(+ "/api/v1/sessions",+ headers={"X-API-Key": alice_key},+ )+ assert alice_list.status_code == 200+ alice_ids = {item["session_id"] for item in alice_list.json()["result"]}+ assert alice_session in alice_ids+ assert bob_session in alice_ids++ bob_list = await auth_client.get(+ "/api/v1/sessions",+ headers={"X-API-Key": bob_key},+ )+ assert bob_list.status_code == 200+ bob_ids = {item["session_id"] for item in bob_list.json()["result"]}+ assert bob_session in bob_ids+ assert alice_session in bob_ids++ admin_list = await auth_client.get(+ "/api/v1/sessions",+ headers={"X-API-Key": admin_key},+ )+ assert admin_list.status_code == 200+ admin_ids = {item["session_id"] for item in admin_list.json()["result"]}+ assert {alice_session, bob_session}.issubset(admin_ids)++ bob_get_alice = await auth_client.get(+ f"/api/v1/sessions/{alice_session}",+ headers={"X-API-Key": bob_key},+ )+ assert bob_get_alice.status_code == 200++ bob_write_alice = await auth_client.post(+ f"/api/v1/sessions/{alice_session}/messages",+ json={"role": "user", "content": "bob writes in same account session"},+ headers={"X-API-Key": bob_key},+ )+ assert bob_write_alice.status_code == 200++async def test_root_tenant_scoped_requests_rejected_in_api_key_mode():"""ROOT API keys cannot access tenant-scoped data APIs in api_key mode."""request = _make_request("/api/v1/resources", auth_enabled=True)diff --git a/tests/server/test_bot_proxy_auth.py b/tests/server/test_bot_proxy_auth.pyindex ceb876d74..67f4844a2 100644--- a/tests/server/test_bot_proxy_auth.py+++ b/tests/server/test_bot_proxy_auth.py@@ -10,6 +10,7 @@ import pytestfrom fastapi import FastAPIimport openviking.server.routers.bot as bot_router_module+from openviking.server.config import ServerConfigfrom openviking.server.identity import AuthMode@@ -81,3 +82,102 @@ async def test_feedback_proxy_forwards_request(monkeypatch):assert forwarded["json"]["response_id"] == "resp-123"assert forwarded["headers"]["X-Gateway-Token"] == "gateway-secret"assert forwarded["timeout"] == 30.0+++async def test_chat_proxy_attaches_authenticated_openviking_connection(monkeypatch):+ forwarded = {}++ class FakeResponse:+ status_code = 200+ text = '{"session_id": "session-1", "message": "ok"}'++ def raise_for_status(self):+ return None++ def json(self):+ return {"session_id": "session-1", "message": "ok"}++ class FakeClient:+ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def post(self, url, json, headers, timeout):+ forwarded["url"] = url+ forwarded["json"] = json+ forwarded["headers"] = headers+ forwarded["timeout"] = timeout+ return FakeResponse()++ monkeypatch.setattr(bot_router_module, "BOT_API_URL", "http://127.0.0.1:18790")+ monkeypatch.setattr(bot_router_module, "BOT_API_KEY", "gateway-secret")+ monkeypatch.setattr(bot_router_module, "_create_bot_proxy_client", lambda: FakeClient())++ app = FastAPI()+ app.state.config = ServerConfig(auth_mode="trusted")+ app.include_router(bot_router_module.router, prefix="/bot/v1")+ transport = httpx.ASGITransport(app=app)++ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ response = await client.post(+ "/bot/v1/chat",+ headers={+ "X-API-Key": "active-user-key",+ "X-OpenViking-Account": "acct",+ "X-OpenViking-User": "alice",+ },+ json={"message": "hello", "user_id": "ignored-by-proxy-identity"},+ )++ assert response.status_code == 200+ assert forwarded["url"] == "http://127.0.0.1:18790/bot/v1/chat"+ assert forwarded["json"]["openviking_connection"] == {+ "api_key": "active-user-key",+ "account_id": "acct",+ "user_id": "alice",+ "agent_id": "web-playground",+ "role": "user",+ "namespace_policy": {+ "isolate_user_scope_by_agent": False,+ "isolate_agent_scope_by_user": False,+ },+ }+ assert forwarded["headers"]["X-Gateway-Token"] == "gateway-secret"+ assert forwarded["timeout"] == 300.0+++async def test_chat_proxy_rejects_authenticated_request_without_forwardable_api_key(monkeypatch):+ class FakeClient:+ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def post(self, *args, **kwargs):+ raise AssertionError("bot gateway should not be called without a forwardable key")++ monkeypatch.setattr(bot_router_module, "BOT_API_URL", "http://127.0.0.1:18790")+ monkeypatch.setattr(bot_router_module, "_create_bot_proxy_client", lambda: FakeClient())++ app = FastAPI()+ app.state.config = ServerConfig(auth_mode="trusted")+ app.include_router(bot_router_module.router, prefix="/bot/v1")+ transport = httpx.ASGITransport(app=app)++ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ response = await client.post(+ "/bot/v1/chat",+ headers={+ "X-OpenViking-Account": "acct",+ "X-OpenViking-User": "alice",+ },+ json={"message": "hello"},+ )++ assert response.status_code == 401+ assert "forwardable OpenViking API key" in response.textdiff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsxindex 6d73ae314..26161c7fb 100644--- a/web-studio/src/components/app-shell.tsx+++ b/web-studio/src/components/app-shell.tsx@@ -45,7 +45,10 @@ import {SidebarProvider,SidebarTrigger,} from '#/components/ui/sidebar'-import { AppConnectionProvider } from '#/hooks/use-app-connection'+import {+ AppConnectionProvider,+ useAppConnection,+} from '#/hooks/use-app-connection'import { cn } from '#/lib/utils'import {useSessionList,@@ -343,6 +346,7 @@ 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,)@@ -350,6 +354,15 @@ function AppShellInner({ children }: { children: React.ReactNode }) {const settingsActive = pathname === '/settings'const oauthSetupActive =pathname === '/oauth/setup' || pathname.startsWith('/oauth/setup/')+ const visibleNavItems = React.useMemo(+ () =>+ connectionRole === 'user'+ ? NAV_ITEMS.filter(+ (item) => item.id !== 'home' && item.id !== 'requestLogs',+ )+ : NAV_ITEMS,+ [connectionRole],+ )function openOAuthSetup(): void {if (oauthSetupActive) {@@ -388,7 +401,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {<SidebarGroup><SidebarGroupContent><SidebarMenu>- {NAV_ITEMS.map((item) => {+ {visibleNavItems.map((item) => {const isActive =pathname === item.to || pathname.startsWith(`${item.to}/`)const title = t(item.titleKey, { ns: 'appShell' })diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsxindex f19533bd2..c4b30f20f 100644--- a/web-studio/src/hooks/use-app-connection.tsx+++ b/web-studio/src/hooks/use-app-connection.tsx@@ -7,6 +7,8 @@ import { isOvClientError, ovClient } from '#/lib/ov-client'import { detectServerMode, normalizeBaseUrl } from './use-server-mode'import type { ServerMode } from './use-server-mode'+export type ConnectionRole = 'admin' | 'root' | 'unknown' | 'user'+export type ConnectionDraft = {accountId: stringadminApiKey: string@@ -24,12 +26,15 @@ export type ConnectionIdentitySummary = {type AppConnectionContextValue = {connection: ConnectionDraft+ connectionRole: ConnectionRole+ isConnectionRoleLoading: booleanopenConnectionSettings: () => voidsaveConnection: (next: ConnectionDraft) => voidserverMode: ServerMode}const CONNECTION_STORAGE_KEY = 'ov_console_connection'+const AUTH_PROMPT_SUPPRESSION_MS = 10000const ENV_BASE_URL =typeof import.meta.env.VITE_OV_BASE_URL === 'string'@@ -67,6 +72,15 @@ function isBrowser(): boolean {return typeof window !== 'undefined'}+function isConnectionRole(value: unknown): value is ConnectionRole {+ return (+ value === 'root' ||+ value === 'admin' ||+ value === 'user' ||+ value === 'unknown'+ )+}+function readStoredConnection(): Partial<ConnectionDraft> {if (!isBrowser()) {return {}@@ -140,6 +154,26 @@ function applyConnection(})}+async function detectConnectionRole(+ connection: ConnectionDraft,+): Promise<ConnectionRole> {+ const headers: Record<string, string> = {}+ const apiKey = connection.apiKey || connection.adminApiKey+ if (apiKey) {+ headers['X-API-Key'] = apiKey+ }++ const response = await fetch(`${connection.baseUrl}/health`, { headers })+ if (!response.ok) {+ return 'unknown'+ }++ const data = (await response.json().catch(() => null)) as {+ role?: unknown+ } | null+ return isConnectionRole(data?.role) ? data.role : 'unknown'+}+function readInitialConnection(): ConnectionDraft {const storedConnection = readStoredConnection()const adminApiKey =@@ -209,6 +243,7 @@ export function AppConnectionProvider({children: React.ReactNode}) {const queryClient = useQueryClient()+ const authPromptSuppressedUntilRef = React.useRef(0)const navigate = useNavigate()const pathname = useRouterState({select: (state) => state.location.pathname,@@ -222,6 +257,10 @@ export function AppConnectionProvider({const [connection, setConnection] = React.useState<ConnectionDraft>(initialConnectionRef.current,)+ const [connectionRole, setConnectionRole] =+ React.useState<ConnectionRole>('unknown')+ const [isConnectionRoleLoading, setConnectionRoleLoading] =+ React.useState(false)const [serverMode, setServerMode] = React.useState<ServerMode>('checking')const openConnectionSettings = React.useCallback(() => {@@ -251,13 +290,52 @@ export function AppConnectionProvider({}}, [connection.baseUrl])+ React.useEffect(() => {+ let cancelled = false+ const apiKey = connection.apiKey || connection.adminApiKey++ setConnectionRole('unknown')+ setConnectionRoleLoading(Boolean(connection.baseUrl && apiKey))+ if (!connection.baseUrl || !apiKey) {+ return () => {+ cancelled = true+ }+ }++ void detectConnectionRole(connection)+ .then((role) => {+ if (cancelled) {+ return+ }+ setConnectionRole(role)+ setConnectionRoleLoading(false)+ })+ .catch(() => {+ if (!cancelled) {+ setConnectionRole('unknown')+ setConnectionRoleLoading(false)+ }+ })++ return () => {+ cancelled = true+ }+ }, [+ connection.accountId,+ connection.adminApiKey,+ connection.apiKey,+ connection.baseUrl,+ connection.userId,+ ])+React.useEffect(() => {const interceptorId = ovClient.instance.interceptors.response.use((response) => response,(error) => {if (isOvClientError(error) &&- (error.statusCode === 401 || error.statusCode === 403)+ (error.statusCode === 401 || error.statusCode === 403) &&+ Date.now() >= authPromptSuppressedUntilRef.current) {openConnectionSettings()}@@ -273,11 +351,25 @@ export function AppConnectionProvider({const value = React.useMemo<AppConnectionContextValue>(() => ({connection,+ connectionRole,+ isConnectionRoleLoading,openConnectionSettings,- saveConnection: (next) => setConnection(normalizeConnectionDraft(next)),+ saveConnection: (next) => {+ authPromptSuppressedUntilRef.current =+ Date.now() + AUTH_PROMPT_SUPPRESSION_MS+ void queryClient.cancelQueries()+ setConnection(normalizeConnectionDraft(next))+ },serverMode,}),- [connection, openConnectionSettings, serverMode],+ [+ connection,+ connectionRole,+ isConnectionRoleLoading,+ openConnectionSettings,+ queryClient,+ serverMode,+ ],)return (diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.tsindex 24fe424d3..62a0942e7 100644--- a/web-studio/src/i18n/locales/en.ts+++ b/web-studio/src/i18n/locales/en.ts@@ -234,6 +234,7 @@ const en = {toast: {accountCreated: 'Account created',connectionSaved: 'Connection saved',+ copyFailed: 'Copy failed',copied: 'Copied',dataKeySelected: 'User API key selected',keyRegenerated: 'API key regenerated',@@ -731,6 +732,32 @@ const en = {placeholder: 'Enter a CLI command, e.g. /status',suggestionsTitle: 'Command suggestions',suggestionsHint: '↑↓ select · Tab complete · Enter run',+ quickStart: {+ title: 'Quick start',+ addResource: {+ title: 'Add a resource',+ command: '/add-resource',+ code: 'Import docs or files into viking://resources',+ },+ addMemory: {+ title: 'Add memory',+ command: 'Agent remembers from chat',+ code: 'Send a message in the Agent panel, then commit the session',+ },+ find: {+ title: 'Find related context',+ command: '/find openviking value',+ code: 'Search resources, memories, and skills from the current scope',+ },+ },+ commandGroups: {+ core: 'Core commands',+ filesystem: 'Filesystem',+ search: 'Search and summaries',+ status: 'Status',+ resource: 'Resource paths',+ history: 'History',+ },groupLabels: {resources: 'resource',memories: 'memory',diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.tsindex d077f8e4a..6e1db02f3 100644--- a/web-studio/src/i18n/locales/zh-CN.ts+++ b/web-studio/src/i18n/locales/zh-CN.ts@@ -234,6 +234,7 @@ const zhCN = {toast: {accountCreated: 'Account 已创建',connectionSaved: '连接已保存',+ copyFailed: '复制失败',copied: '已复制',dataKeySelected: '已选择 User API key',keyRegenerated: 'API key 已重新生成',@@ -712,6 +713,32 @@ const zhCN = {placeholder: '输入 CLI 命令,例如 /status',suggestionsTitle: '命令建议',suggestionsHint: '↑↓ 选择 · Tab 补全 · Enter 执行',+ quickStart: {+ title: '快速开始',+ addResource: {+ title: '添加资源',+ command: '/add-resource',+ code: '导入文档或文件到 viking://resources',+ },+ addMemory: {+ title: '添加记忆',+ command: 'Agent 对话后自动沉淀',+ code: '在 Agent 面板发送消息,然后提交会话',+ },+ find: {+ title: '查找相关上下文',+ command: '/find openviking 价值',+ code: '在当前范围内搜索资源、记忆和技能',+ },+ },+ commandGroups: {+ core: '核心命令',+ filesystem: '文件系统',+ search: '搜索与摘要',+ status: '状态',+ resource: '资源路径',+ history: '历史记录',+ },groupLabels: {resources: '资源',memories: '记忆',diff --git a/web-studio/src/lib/ov-client/client.ts b/web-studio/src/lib/ov-client/client.tsindex 79a19428e..bfe5601a0 100644--- a/web-studio/src/lib/ov-client/client.ts+++ b/web-studio/src/lib/ov-client/client.ts@@ -20,7 +20,6 @@ const DEFAULT_TELEMETRY_PATHS = new Set([])const CONTROL_PLANE_PREFIXES = ['/api/v1/admin', '/api/v1/console'] as constconst SESSION_COMMIT_PATH = /^\/api\/v1\/sessions\/[^/]+\/commit$/-function isBrowser(): boolean {return typeof window !== 'undefined'}diff --git a/web-studio/src/lib/sessions/types/chat.ts b/web-studio/src/lib/sessions/types/chat.tsindex d4d89f184..aa75ef2bf 100644--- a/web-studio/src/lib/sessions/types/chat.ts+++ b/web-studio/src/lib/sessions/types/chat.ts@@ -30,6 +30,8 @@ export interface ChatState {streamingToolCalls: StreamToolCall[]/** Reasoning content from the current streaming round. */streamingReasoning: string+ /** Ordered event parts observed during the current streaming round. */+ streamingParts: Message['parts']/** Current iteration index. */iteration: number}diff --git a/web-studio/src/lib/sessions/types/message.ts b/web-studio/src/lib/sessions/types/message.tsindex a2e449488..5496708f6 100644--- a/web-studio/src/lib/sessions/types/message.ts+++ b/web-studio/src/lib/sessions/types/message.ts@@ -4,6 +4,13 @@ export interface TextPart {text: string}+/** Reasoning/thinking content part used by the chat UI during streaming. */+export interface ReasoningPart {+ type: 'reasoning'+ reasoning: string+ is_running?: boolean+}+/** Context reference part (memory / resource / skill). */export interface ContextPart {type: 'context'@@ -27,7 +34,7 @@ export interface ToolPart {completion_tokens?: number}-export type MessagePart = TextPart | ContextPart | ToolPart+export type MessagePart = TextPart | ReasoningPart | ContextPart | ToolPart/** A single message in a session (matches backend Message.to_dict()). */export interface Message {diff --git a/web-studio/src/lib/sessions/use-chat.ts b/web-studio/src/lib/sessions/use-chat.tsindex c064e77f5..e8b31d6ca 100644--- a/web-studio/src/lib/sessions/use-chat.ts+++ b/web-studio/src/lib/sessions/use-chat.ts@@ -1,9 +1,15 @@import { useCallback, useEffect, useRef, useState } from 'react'import type { ChatStatus, StreamToolCall } from './types/chat'-import type { Message, MessagePart, TextPart, ToolPart } from './types/message'+import type {+ Message,+ MessagePart,+ ContextPart,+ ReasoningPart,+ TextPart,+ ToolPart,+} from './types/message'import { addMessage, sendChatStream, serializeParts } from './api'-import { generateTitle } from './generate-title'import { parseSseStream, streamEventDataToText } from './sse'import { setSessionTitle } from './use-session-titles'import { createBrowserId } from '../browser-crypto'@@ -42,6 +48,33 @@ function dedupeToolCalls(toolCalls: StreamToolCall[]): StreamToolCall[] {return result}+function isToolErrorResult(result?: string): boolean {+ return Boolean(result?.trimStart().toLowerCase().startsWith('error'))+}++function clonePart(part: MessagePart): MessagePart {+ switch (part.type) {+ case 'text':+ return { ...part } satisfies TextPart+ case 'reasoning':+ return { ...part } satisfies ReasoningPart+ case 'tool':+ return {+ ...part,+ tool_input: part.tool_input ? { ...part.tool_input } : undefined,+ } satisfies ToolPart+ case 'context':+ return { ...part } satisfies ContextPart+ }+}++function waitForNextFrame(): Promise<void> {+ if (typeof window === 'undefined') return Promise.resolve()+ return new Promise((resolve) => {+ window.requestAnimationFrame(() => resolve())+ })+}+type SendOptions = {displayMessage?: string}@@ -49,8 +82,21 @@ type SendOptions = {function buildAssistantMessage(content: string,toolCalls: StreamToolCall[],+ orderedParts?: MessagePart[],): Message {- const parts: MessagePart[] = []+ const parts: MessagePart[] = orderedParts?.length ? [...orderedParts] : []++ if (parts.length > 0) {+ if (content && !parts.some((part) => part.type === 'text')) {+ parts.push({ type: 'text', text: content } satisfies TextPart)+ }+ return {+ id: createBrowserId('msg'),+ role: 'assistant',+ parts,+ created_at: new Date().toISOString(),+ }+ }// Tool parts first (matches backend ordering)for (const tc of toolCalls) {@@ -60,7 +106,7 @@ function buildAssistantMessage(tool_name: tc.name,tool_uri: '',skill_uri: '',- tool_status: 'completed',+ tool_status: isToolErrorResult(tc.result) ? 'error' : 'completed',tool_output: tc.result,}try {@@ -99,6 +145,7 @@ export interface UseChatReturn {streamingContent: stringstreamingToolCalls: StreamToolCall[]streamingReasoning: string+ streamingParts: MessagePart[]iteration: numbersend: (message: string, options?: SendOptions) => Promise<void>abort: () => void@@ -117,6 +164,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {StreamToolCall[]>([])const [streamingReasoning, setStreamingReasoning] = useState('')+ const [streamingParts, setStreamingParts] = useState<MessagePart[]>([])const [iteration, setIteration] = useState(0)const abortRef = useRef<AbortController | null>(null)@@ -137,6 +185,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {setStreamingContent('')setStreamingToolCalls([])setStreamingReasoning('')+ setStreamingParts([])setIteration(0)}, [sessionId])@@ -173,15 +222,16 @@ export function useChat(options: UseChatOptions): UseChatReturn {setStreamingContent('')setStreamingToolCalls([])setStreamingReasoning('')+ setStreamingParts([])setIteration(0)}, [abort, initialMessages])const send = useCallback(- async (message: string, options?: SendOptions) => {+ async (message: string, sendOptions?: SendOptions) => {if (status === 'streaming') returnconst isFirstExchange = messagesRef.current.length === 0- const displayMessage = options?.displayMessage ?? message+ const displayMessage = sendOptions?.displayMessage ?? messageconst userMsg = createUserMessage(displayMessage)setMessages((prev) => [...prev, userMsg])@@ -190,6 +240,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {setStreamingContent('')setStreamingToolCalls([])setStreamingReasoning('')+ setStreamingParts([])setIteration(0)const controller = new AbortController()@@ -199,8 +250,81 @@ export function useChat(options: UseChatOptions): UseChatReturn {let accContent = ''let accReasoning = ''const accToolCalls: StreamToolCall[] = []+ const accParts: MessagePart[] = []let lastToolCall: StreamToolCall | null = null+ let currentReasoningPart: ReasoningPart | null = null+ let currentTextPart: TextPart | null = nulllet currentIteration = 0+ let lastPaintAt = 0+ let publishScheduled = false+ let publishFrameId: number | null = null++ const publishStreamingPartsNow = () => {+ if (publishFrameId !== null && typeof window !== 'undefined') {+ window.cancelAnimationFrame(publishFrameId)+ }+ publishFrameId = null+ publishScheduled = false+ setStreamingParts(accParts.map(clonePart))+ }++ const publishStreamingParts = () => {+ if (publishScheduled) return+ publishScheduled = true+ if (typeof window === 'undefined') {+ queueMicrotask(publishStreamingPartsNow)+ return+ }+ publishFrameId = window.requestAnimationFrame(publishStreamingPartsNow)+ }++ const yieldToRenderer = async () => {+ const now =+ typeof performance !== 'undefined' ? performance.now() : Date.now()+ if (now - lastPaintAt < 16) return+ lastPaintAt = now+ await waitForNextFrame()+ }++ const appendReasoning = (text: string, replaceIfEmpty: boolean) => {+ if (!text) return+ if (!currentReasoningPart || accParts.at(-1) !== currentReasoningPart) {+ currentReasoningPart = {+ type: 'reasoning',+ reasoning: '',+ is_running: true,+ }+ accParts.push(currentReasoningPart)+ }+ currentReasoningPart.reasoning =+ replaceIfEmpty && !currentReasoningPart.reasoning+ ? text+ : currentReasoningPart.reasoning + text+ publishStreamingParts()+ }++ const appendText = (text: string) => {+ if (!text) return+ if (!currentTextPart || accParts.at(-1) !== currentTextPart) {+ currentTextPart = { type: 'text', text: '' }+ accParts.push(currentTextPart)+ }+ currentTextPart.text += text+ currentReasoningPart = null+ publishStreamingParts()+ }++ const setFinalText = (text: string) => {+ if (!text) return+ if (currentTextPart) {+ currentTextPart.text = text+ } else {+ currentTextPart = { type: 'text', text }+ accParts.push(currentTextPart)+ }+ currentReasoningPart = null+ publishStreamingPartsNow()+ }try {const response = await sendChatStream(@@ -223,14 +347,20 @@ export function useChat(options: UseChatOptions): UseChatReturn {}case 'content_delta': {- accContent += streamEventDataToText(event.data)+ const delta = streamEventDataToText(event.data)+ accContent += deltasetStreamingContent(accContent)+ appendText(delta)+ await yieldToRenderer()break}case 'reasoning_delta': {- accReasoning += streamEventDataToText(event.data)+ const delta = streamEventDataToText(event.data)+ accReasoning += deltasetStreamingReasoning(accReasoning)+ appendReasoning(delta, false)+ await yieldToRenderer()break}@@ -239,6 +369,8 @@ export function useChat(options: UseChatOptions): UseChatReturn {if (!accReasoning) {accReasoning = streamEventDataToText(event.data)setStreamingReasoning(accReasoning)+ appendReasoning(accReasoning, true)+ await yieldToRenderer()}break}@@ -267,14 +399,47 @@ export function useChat(options: UseChatOptions): UseChatReturn {iteration: currentIteration,}accToolCalls.push(lastToolCall)+ const toolPart: ToolPart = {+ type: 'tool',+ tool_id: createBrowserId('tool'),+ tool_name: name,+ tool_uri: '',+ skill_uri: '',+ tool_status: 'running',+ }+ try {+ toolPart.tool_input = JSON.parse(args) as Record<string, unknown>+ } catch {+ if (args) toolPart.tool_input = { raw: args }+ }+ accParts.push(toolPart)+ currentReasoningPart = null+ currentTextPart = nullsetStreamingToolCalls(dedupeToolCalls(accToolCalls))+ publishStreamingParts()+ await yieldToRenderer()break}case 'tool_result': {- if (lastToolCall) {- lastToolCall.result = streamEventDataToText(event.data)+ const pendingToolCall = accToolCalls.find((tc) => !tc.result)+ const pendingToolPart = accParts.find(+ (part): part is ToolPart =>+ part.type === 'tool' &&+ (part.tool_status === 'running' || part.tool_status === 'pending'),+ )+ if (pendingToolCall) {+ const result = streamEventDataToText(event.data)+ pendingToolCall.result = result+ if (pendingToolPart) {+ pendingToolPart.tool_output = result+ pendingToolPart.tool_status = isToolErrorResult(result)+ ? 'error'+ : 'completed'+ }setStreamingToolCalls(dedupeToolCalls(accToolCalls))+ publishStreamingParts()+ await yieldToRenderer()}break}@@ -283,6 +448,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {// Final complete response — overrides accumulated deltasaccContent = streamEventDataToText(event.data)setStreamingContent(accContent)+ setFinalText(accContent)break}}@@ -292,10 +458,12 @@ export function useChat(options: UseChatOptions): UseChatReturn {const assistantMsg = buildAssistantMessage(accContent,dedupeToolCalls(accToolCalls),+ accParts,)setStreamingContent('')setStreamingToolCalls([])setStreamingReasoning('')+ setStreamingParts([])setStatus('idle')setMessages((prev) => [...prev, assistantMsg])@@ -319,14 +487,6 @@ export function useChat(options: UseChatOptions): UseChatReturn {if (sessionId && isFirstExchange) {// Immediate: use first user message as temp titlesetSessionTitle(sessionId, displayMessage.slice(0, 20))- // Async: ask AI for a better title- generateTitle(displayMessage, accContent)- .then((title) => {- if (title) setSessionTitle(sessionId, title)- })- .catch(() => {- /* non-blocking */- })}} catch (err) {if (controller.signal.aborted) {@@ -335,10 +495,12 @@ export function useChat(options: UseChatOptions): UseChatReturn {const partialMsg = buildAssistantMessage(accContent,dedupeToolCalls(accToolCalls),+ accParts,)setStreamingContent('')setStreamingToolCalls([])setStreamingReasoning('')+ setStreamingParts([])setMessages((prev) => [...prev, partialMsg])}setStatus('idle')@@ -361,6 +523,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {streamingContent,streamingToolCalls,streamingReasoning,+ streamingParts,iteration,send,abort,diff --git a/web-studio/src/routes/home/route.tsx b/web-studio/src/routes/home/route.tsxindex cfa054bca..645a6a79d 100644--- a/web-studio/src/routes/home/route.tsx+++ b/web-studio/src/routes/home/route.tsx@@ -15,6 +15,7 @@ import {fetchConsoleTokenSeries,} from './-lib/api'import { isDisabledPayload } from './-lib/format'+import { useAppConnection } from '#/hooks/use-app-connection'export const Route = createFileRoute('/home')({component: HomePage,@@ -22,20 +23,26 @@ export const Route = createFileRoute('/home')({function HomePage() {const { t } = useTranslation('home')+ const { connectionRole, isConnectionRoleLoading } = useAppConnection()+ const isRegularUser = connectionRole === 'user'+ const canQueryAdminMetrics = !isConnectionRoleLoading && !isRegularUserconst dashboard = useQuery({+ enabled: canQueryAdminMetrics,queryFn: fetchConsoleDashboardSummary,queryKey: ['console-dashboard-summary'],refetchInterval: 30_000,})const tokenSeries = useQuery({+ enabled: canQueryAdminMetrics,queryFn: fetchConsoleTokenSeries,queryKey: ['console-token-series', 'last-14-days'],refetchInterval: 60_000,})const contextCommits = useQuery({+ enabled: canQueryAdminMetrics,queryFn: fetchConsoleContextCommits,queryKey: ['console-context-commits', 'last-365-days'],refetchInterval: 60_000,@@ -44,6 +51,19 @@ function HomePage() {const summary = dashboard.dataconst usageDisabled = isDisabledPayload(summary)+ if (isRegularUser) {+ 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>+ )+ }+return (<div className="flex flex-col gap-5 pb-8"><div className="grid gap-4 md:grid-cols-3">diff --git a/web-studio/src/routes/playground/-components/agent-panel.tsx b/web-studio/src/routes/playground/-components/agent-panel.tsxindex 0a47f59ad..4c56c9468 100644--- a/web-studio/src/routes/playground/-components/agent-panel.tsx+++ b/web-studio/src/routes/playground/-components/agent-panel.tsx@@ -270,10 +270,8 @@ export function AgentPanel({streaming={isStreaming? {- content: chat.streamingContent,iteration: chat.iteration,- reasoning: chat.streamingReasoning,- toolCalls: chat.streamingToolCalls,+ parts: chat.streamingParts,}: undefined}diff --git a/web-studio/src/routes/playground/-components/terminal-panel.tsx b/web-studio/src/routes/playground/-components/terminal-panel.tsxindex e419282bb..5adce39c5 100644--- a/web-studio/src/routes/playground/-components/terminal-panel.tsx+++ b/web-studio/src/routes/playground/-components/terminal-panel.tsx@@ -1,19 +1,39 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import {+ ArrowRightIcon,CheckCircle2Icon,+ HistoryIcon,Loader2Icon,SendIcon,SparklesIcon,TerminalIcon,+ TrashIcon,XCircleIcon,} from 'lucide-react'import { Button } from '#/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from '#/components/ui/dialog'+import { useAppConnection } from '#/hooks/use-app-connection'+import {+ getHealth,+ getOvResult,+ getSystemStatus,+ postSystemWait,+} from '#/lib/ov-client'import { cn } from '#/lib/utils'import {+ fetchDirectoryLevelContent,fetchFileContent,fetchFsList,+ fetchFsStat,+ fetchFsTree,fetchSearch,} from '#/routes/resources/-lib/api'import { normalizeDirUri } from '#/routes/resources/-lib/normalize'@@ -21,18 +41,145 @@ import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'import { ROOT_URI, TERMINAL_COMMANDS } from '../-lib/constants'import type {+ ResourceRef,ResourceOpenHandler,+ TerminalCommandGroup,TerminalCommandView,TerminalEntry,} from '../-lib/types'import {cleanVikingUri,entryToRef,+ readStoredJsonArray,+ removeStoredValue,searchResultToRefs,visibleContextEntries,+ writeStoredJson,} from '../-lib/utils'import { ResourceRefList } from './resource-ref-list'+const TERMINAL_COMMAND_HISTORY_STORAGE_KEY =+ 'openviking.playground.terminalCommandHistory'+const TERMINAL_ENTRY_HISTORY_STORAGE_KEY =+ 'openviking.playground.terminalEntryHistory'+const TERMINAL_COMMAND_HISTORY_LIMIT = 50+const TERMINAL_ENTRY_HISTORY_LIMIT = 100+const URI_ARGUMENT_COMMANDS = new Set([+ '/abstract',+ '/ls',+ '/overview',+ '/read',+ '/stat',+ '/tree',+])++type TerminalSuggestionGroup = TerminalCommandGroup | 'history' | 'resource'++type TerminalSuggestion = Omit<TerminalCommandView, 'group'> & {+ group: TerminalSuggestionGroup+ id: string+}++type TerminalQuickStartExample = {+ action?: () => void+ command: string+ code: string+ key: string+ title: string+}++function loadCommandHistory(): string[] {+ return readStoredJsonArray(+ TERMINAL_COMMAND_HISTORY_STORAGE_KEY,+ (item) => {+ if (typeof item !== 'string') return undefined+ const trimmed = item.trim()+ return trimmed || undefined+ },+ TERMINAL_COMMAND_HISTORY_LIMIT,+ )+}++function persistCommandHistory(history: string[]): void {+ writeStoredJson(+ TERMINAL_COMMAND_HISTORY_STORAGE_KEY,+ history.slice(0, TERMINAL_COMMAND_HISTORY_LIMIT),+ )+}++function normalizeRefs(value: unknown): ResourceRef[] | undefined {+ if (!Array.isArray(value)) return undefined+ const refs = value+ .filter(+ (item): item is ResourceRef =>+ typeof item === 'object' &&+ item !== null &&+ typeof (item as ResourceRef).uri === 'string',+ )+ .map((item) => ({+ label: typeof item.label === 'string' ? item.label : undefined,+ meta: typeof item.meta === 'string' ? item.meta : undefined,+ uri: item.uri,+ }))+ return refs.length > 0 ? refs : undefined+}++function loadTerminalHistory(): TerminalEntry[] {+ return readStoredJsonArray(+ TERMINAL_ENTRY_HISTORY_STORAGE_KEY,+ (item): TerminalEntry | undefined => {+ if (typeof item !== 'object' || item === null) return undefined+ const record = item as Record<string, unknown>+ if (+ typeof record.id !== 'string' ||+ typeof record.title !== 'string' ||+ !['command', 'error', 'info', 'success'].includes(String(record.kind)) ||+ (record.body !== undefined && typeof record.body !== 'string')+ ) {+ return undefined+ }+ return {+ body: typeof record.body === 'string' ? record.body : undefined,+ id: record.id,+ kind: record.kind as TerminalEntry['kind'],+ refs: normalizeRefs(record.refs),+ title: record.title,+ }+ },+ TERMINAL_ENTRY_HISTORY_LIMIT,+ true,+ )+}++function persistTerminalHistory(history: TerminalEntry[]): void {+ writeStoredJson(+ TERMINAL_ENTRY_HISTORY_STORAGE_KEY,+ history.slice(-TERMINAL_ENTRY_HISTORY_LIMIT),+ )+}++function clearPersistedTerminalHistory(): void {+ removeStoredValue(TERMINAL_ENTRY_HISTORY_STORAGE_KEY)+}++function extractVikingUris(text: string): string[] {+ return text.match(/viking:\/\/[^\s,,))\]}】'"`]+/g) ?? []+}++function formatJson(value: unknown): string {+ return JSON.stringify(value, null, 2)+}++function parseWaitTimeout(body: string): number | undefined {+ const trimmed = body.trim()+ if (!trimmed) return undefined+ const match = trimmed.match(/^(?:--timeout\s+)?(\d+(?:\.\d+)?)$/)+ if (!match) {+ throw new Error('Usage: /wait [--timeout seconds]')+ }+ return Number(match[1])+}+export function TerminalPanel({currentUri,entries,@@ -47,28 +194,34 @@ export function TerminalPanel({openingUri: string | null}) {const { t } = useTranslation('playground')+ const { connectionRole } = useAppConnection()const [command, setCommand] = useState('')const [running, setRunning] = useState(false)const [suggestionsOpen, setSuggestionsOpen] = useState(false)const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(0)- const [history, setHistory] = useState<TerminalEntry[]>(() => [- {- id: 'welcome',- kind: 'info',- title: t('terminal.welcomeTitle'),- body: t('terminal.welcomeBody'),- },- ])+ const [commandHistory, setCommandHistory] = useState(loadCommandHistory)+ const [history, setHistory] = useState(loadTerminalHistory)+ const [historyOpen, setHistoryOpen] = useState(false)+ const inputRef = useRef<HTMLInputElement>(null)const scrollRef = useRef<HTMLDivElement>(null)const commands = useMemo<TerminalCommandView[]>(() =>- TERMINAL_COMMANDS.map((item) => ({+ TERMINAL_COMMANDS.filter(+ (item) =>+ !item.adminOnly ||+ connectionRole === 'admin' ||+ connectionRole === 'root',+ ).map((item) => ({...item,- description: t(`terminal.commands.${item.key}.description`),- usage: t(`terminal.commands.${item.key}.usage`),+ description: t(`terminal.commands.${item.key}.description`, {+ defaultValue: item.command,+ }),+ usage: t(`terminal.commands.${item.key}.usage`, {+ defaultValue: item.insertText.trim(),+ }),})),- [t],+ [connectionRole, t],)const groupLabels = useMemo(@@ -80,16 +233,126 @@ export function TerminalPanel({[t],)- const suggestions = useMemo(() => {- const query = command.trimStart().toLowerCase()- if (!query || query === '/') return commands- if (!query.startsWith('/')) return []- return commands.filter(- (item) =>- item.command.toLowerCase().startsWith(query) ||- item.description.toLowerCase().includes(query.slice(1)),+ const resourceCandidates = useMemo(() => {+ const candidates = new Set<string>([currentUri, ROOT_URI])+ for (const entry of visibleContextEntries(entries)) {+ const ref = entryToRef(entry)+ candidates.add(ref.uri)+ }+ for (const item of history) {+ for (const ref of item.refs ?? []) {+ candidates.add(ref.uri)+ }+ if (item.body) {+ for (const uri of extractVikingUris(item.body)) candidates.add(uri)+ }+ for (const uri of extractVikingUris(item.title)) candidates.add(uri)+ }+ for (const item of commandHistory) {+ for (const uri of extractVikingUris(item)) candidates.add(uri)+ }+ return Array.from(candidates).filter(Boolean).sort()+ }, [commandHistory, currentUri, entries, history])++ const suggestions = useMemo<TerminalSuggestion[]>(() => {+ const rawQuery = command.trimStart()+ const query = rawQuery.toLowerCase()+ const commandMatches =+ !query || query === '/'+ ? commands.map((item) => ({+ ...item,+ id: `command:${item.command}`,+ }))+ : query.startsWith('/')+ ? commands+ .filter(+ (item) =>+ item.command.toLowerCase().startsWith(query) ||+ item.description.toLowerCase().includes(query.slice(1)),+ )+ .map((item) => ({+ ...item,+ id: `command:${item.command}`,+ }))+ : []++ const activeCommand = [...commands]+ .sort((a, b) => b.command.length - a.command.length)+ .find(+ (item) =>+ rawQuery === item.command || rawQuery.startsWith(`${item.command} `),+ )+ const resourceMatches =+ activeCommand && URI_ARGUMENT_COMMANDS.has(activeCommand.command)+ ? resourceCandidates+ .filter((uri) => {+ const argQuery = rawQuery+ .slice(activeCommand.command.length)+ .trimStart()+ .toLowerCase()+ if (!argQuery) return true+ return (+ uri.toLowerCase().startsWith(argQuery) ||+ uri.toLowerCase().includes(argQuery)+ )+ })+ .slice(0, 12)+ .map((uri) => ({+ ...activeCommand,+ command: uri,+ description: t('terminal.resourceSuggestion'),+ group: 'resource' as const,+ id: `resource:${activeCommand.command}:${uri}`,+ insertText: `${activeCommand.command} ${uri}`,+ usage: `${activeCommand.command} ${uri}`,+ }))+ : []++ const historyMatches = commandHistory+ .filter((item) => {+ const lower = item.toLowerCase()+ return lower !== query && lower.startsWith(query)+ })+ .slice(0, 8)+ .map((item) => ({+ adminOnly: false,+ command: item,+ description: t('terminal.historySuggestion'),+ executable: false,+ group: 'history' as const,+ id: `history:${item}`,+ insertText: item,+ key: 'history',+ usage: item,+ }))++ const seen = new Set<string>()+ return [...commandMatches, ...resourceMatches, ...historyMatches].filter(+ (item) => {+ if (seen.has(item.insertText)) return false+ seen.add(item.insertText)+ return true+ },)- }, [command, commands])+ }, [command, commandHistory, commands, resourceCandidates, t])++ const groupedSuggestions = useMemo(() => {+ const order: TerminalSuggestionGroup[] = [+ 'core',+ 'filesystem',+ 'search',+ 'status',+ 'resource',+ 'history',+ ]+ return order+ .map((group) => ({+ group,+ items: suggestions.filter((item) => item.group === group),+ label: t(`terminal.commandGroups.${group}`),+ }))+ .filter((group) => group.items.length > 0)+ }, [suggestions, t])useEffect(() => {setActiveSuggestionIndex(0)@@ -103,13 +366,35 @@ export function TerminalPanel({}, [history.length, running])const append = useCallback((entry: Omit<TerminalEntry, 'id'>) => {- setHistory((prev) => [- ...prev,- {- ...entry,- id: `${Date.now()}-${prev.length}`,- },- ])+ setHistory((prev) => {+ const next = [+ ...prev,+ {+ ...entry,+ id: `${Date.now()}-${prev.length}`,+ },+ ].slice(-TERMINAL_ENTRY_HISTORY_LIMIT)+ persistTerminalHistory(next)+ return next+ })+ }, [])++ const clearHistory = useCallback(() => {+ setHistory([])+ clearPersistedTerminalHistory()+ }, [])++ const rememberCommand = useCallback((raw: string) => {+ const trimmed = raw.trim()+ if (!trimmed) return+ setCommandHistory((prev) => {+ const next = [+ trimmed,+ ...prev.filter((item) => item.toLowerCase() !== trimmed.toLowerCase()),+ ].slice(0, TERMINAL_COMMAND_HISTORY_LIMIT)+ persistCommandHistory(next)+ return next+ })}, [])const runCommand = useCallback(@@ -118,6 +403,7 @@ export function TerminalPanel({if (!trimmed || running) returnappend({ kind: 'command', title: trimmed })+ rememberCommand(trimmed)setCommand('')setRunning(true)@@ -138,14 +424,42 @@ export function TerminalPanel({switch (name) {case '/status': {const root = await fetchFsList(ROOT_URI, { nodeLimit: 12 })+ const status =+ await getOvResult<Record<string, unknown>>(getSystemStatus())append({- body: t('terminal.onlineBody', { count: root.entries.length }),+ body: `${t('terminal.onlineBody', { count: root.entries.length })}\n\n${formatJson(status)}`,kind: 'success',refs: root.entries.slice(0, 6).map(entryToRef),title: t('terminal.onlineTitle'),})return}+ case '/health': {+ const health =+ await getOvResult<Record<string, unknown>>(getHealth())+ append({+ body: formatJson(health),+ kind: 'success',+ title: 'health',+ })+ return+ }+ case '/wait': {+ const timeout = parseWaitTimeout(body)+ const result = await getOvResult<unknown>(+ postSystemWait({+ body: {+ timeout,+ },+ }),+ )+ append({+ body: formatJson(result),+ kind: 'success',+ title: 'wait',+ })+ return+ }case '/ls': {const target = body ? normalizeDirUri(body) : currentUriconst result = body@@ -167,6 +481,38 @@ export function TerminalPanel({})return}+ case '/tree': {+ const target = body ? normalizeDirUri(body) : currentUri+ const result = await fetchFsTree(target, {+ nodeLimit: 80,+ output: 'agent',+ showAllHidden: true,+ })+ const visibleEntries = visibleContextEntries(result.nodes)+ append({+ body: t('terminal.lsBody', {+ count: visibleEntries.length,+ uri: target,+ }),+ kind: 'success',+ refs: visibleEntries.map(entryToRef),+ title: `tree ${target}`,+ })+ return+ }+ case '/stat': {+ if (!body) throw new Error(t('terminal.enterUri'))+ const uri = cleanVikingUri(body)+ if (!uri) throw new Error(t('terminal.enterUri'))+ const entry = await fetchFsStat(uri, { throwOnError: true })+ append({+ body: formatJson(entry),+ kind: 'success',+ refs: [entryToRef(entry)],+ title: `stat ${uri}`,+ })+ return+ }case '/read': {if (!body) throw new Error(t('terminal.readUsage'))const uri = cleanVikingUri(body)@@ -184,6 +530,22 @@ export function TerminalPanel({})return}+ case '/abstract':+ case '/overview': {+ if (!body) throw new Error(t('terminal.enterUri'))+ const uri = cleanVikingUri(body)+ if (!uri) throw new Error(t('terminal.enterUri'))+ const level = name === '/abstract' ? 'abstract' : 'overview'+ const content = await fetchDirectoryLevelContent(uri, level)+ await onOpenResource(uri)+ append({+ body: content || t('terminal.fileEmpty'),+ kind: 'success',+ refs: [{ uri }],+ title: `${name.slice(1)} ${uri}`,+ })+ return+ }case '/find':case '/search': {if (!body) throw new Error(t('terminal.searchUsage', { name }))@@ -235,151 +597,361 @@ export function TerminalPanel({onOpenAddResource,onOpenResource,running,+ rememberCommand,t,],)- const acceptSuggestion = useCallback((suggestion: TerminalCommandView) => {+ const acceptSuggestion = useCallback((suggestion: { insertText: string }) => {setCommand(suggestion.insertText)setSuggestionsOpen(false)+ window.requestAnimationFrame(() => {+ const input = inputRef.current+ input?.focus()+ input?.setSelectionRange(+ suggestion.insertText.length,+ suggestion.insertText.length,+ )+ })}, [])+ const runSuggestion = useCallback(+ (suggestion: TerminalSuggestion) => {+ setSuggestionsOpen(false)+ if (suggestion.executable) {+ void runCommand(suggestion.insertText)+ return+ }+ setCommand(suggestion.insertText)+ },+ [runCommand],+ )+const quickCommands = commands.filter((item) =>- ['/status', '/ls', '/search', '/read', '/add-resource'].includes(- item.command,- ),+ ['/status', '/find', '/search', '/add-resource'].includes(item.command),+ )++ const quickStartExamples = useMemo<TerminalQuickStartExample[]>(+ () => [+ {+ action: () => void runCommand('/add-resource'),+ code: t('terminal.quickStart.addResource.code'),+ command: t('terminal.quickStart.addResource.command'),+ key: 'add-resource',+ title: t('terminal.quickStart.addResource.title'),+ },+ {+ code: t('terminal.quickStart.addMemory.code'),+ command: t('terminal.quickStart.addMemory.command'),+ key: 'add-memory',+ title: t('terminal.quickStart.addMemory.title'),+ },+ {+ action: () => void runCommand('/find openviking 有什么价值?'),+ code: t('terminal.quickStart.find.code'),+ command: t('terminal.quickStart.find.command'),+ key: 'find',+ title: t('terminal.quickStart.find.title'),+ },+ ],+ [runCommand, t],)return (- <div className="flex min-h-0 flex-1 flex-col">- <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto px-4 py-4">- <div className="space-y-3">- {history.map((entry) => (- <TerminalHistoryItem- key={entry.id}- entry={entry}- onOpenResource={onOpenResource}- openingUri={openingUri}- />- ))}- {running ? (- <div className="flex items-center gap-2 rounded-lg border bg-background px-3 py-2 text-xs text-muted-foreground">- <Loader2Icon className="size-3.5 animate-spin" />- {t('terminal.running')}- </div>- ) : null}- </div>- </div>- <div className="border-t bg-background/80 p-3">- <div className="mb-2 flex flex-wrap gap-1.5">- {quickCommands.map((item) => (- <button- key={item.command}+ <>+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="border-b bg-background/70 px-4 py-3">+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <TerminalIcon className="size-3.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate">+ {t('terminal.header')}+ </span>+ <Buttontype="button"- className="rounded-md border bg-muted/40 px-2 py-1 font-mono text-[11px] text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground"- onClick={() => acceptSuggestion(item)}+ variant="ghost"+ size="icon-sm"+ className="size-7 shrink-0"+ title={t('terminal.history')}+ onClick={() => setHistoryOpen(true)}>- {item.command}- </button>- ))}+ <HistoryIcon className="size-3.5" />+ </Button>+ </div></div>- <form- className="relative flex items-center gap-2 rounded-lg border bg-muted/30 px-2 py-2"- onSubmit={(event) => {- event.preventDefault()- void runCommand(command)- }}+ <div+ ref={scrollRef}+ className="min-h-0 flex-1 overflow-y-auto px-4 py-4">- <input- value={command}- onBlur={() => {- window.setTimeout(() => setSuggestionsOpen(false), 120)- }}- onChange={(event) => {- setCommand(event.target.value)- setSuggestionsOpen(true)- }}- onFocus={() => setSuggestionsOpen(true)}- onKeyDown={(event) => {- if (!suggestionsOpen || suggestions.length === 0) return- if (event.key === 'ArrowDown') {- event.preventDefault()- setActiveSuggestionIndex((current) =>- Math.min(current + 1, suggestions.length - 1),- )- return- }- if (event.key === 'ArrowUp') {- event.preventDefault()- setActiveSuggestionIndex((current) => Math.max(current - 1, 0))- return- }- if (event.key === 'Tab') {- event.preventDefault()- acceptSuggestion(suggestions[activeSuggestionIndex])- return- }- if (event.key === 'Enter' && command.trim() === '/') {- event.preventDefault()- acceptSuggestion(suggestions[activeSuggestionIndex])- return- }- if (event.key === 'Escape') {- setSuggestionsOpen(false)- }+ <div className="space-y-3">+ {history.length === 0 && !running ? (+ <TerminalQuickStart+ examples={quickStartExamples}+ title={t('terminal.quickStart.title')}+ />+ ) : null}+ {history.map((entry) => (+ <TerminalHistoryItem+ key={entry.id}+ entry={entry}+ onOpenResource={onOpenResource}+ openingUri={openingUri}+ />+ ))}+ {running ? (+ <div className="flex items-center gap-2 rounded-lg border bg-background px-3 py-2 text-xs text-muted-foreground">+ <Loader2Icon className="size-3.5 animate-spin" />+ {t('terminal.running')}+ </div>+ ) : null}+ </div>+ </div>+ <div className="border-t bg-background/80 p-3">+ <div className="mb-2 flex flex-wrap gap-1.5">+ {quickCommands.map((item) => (+ <button+ key={item.command}+ type="button"+ className="rounded-md border bg-muted/40 px-2 py-1 font-mono text-[11px] text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground"+ onClick={() => acceptSuggestion(item)}+ >+ {item.command}+ </button>+ ))}+ </div>+ <form+ className="relative flex items-center gap-2 rounded-lg border bg-muted/30 px-2 py-2"+ onSubmit={(event) => {+ event.preventDefault()+ void runCommand(command)}}- placeholder={t('terminal.placeholder')}- className="h-8 min-w-0 flex-1 bg-transparent font-mono text-sm outline-none placeholder:text-muted-foreground/60"- />- {suggestionsOpen && suggestions.length > 0 ? (- <div className="absolute bottom-[calc(100%+0.5rem)] left-0 right-0 z-20 overflow-hidden rounded-lg border bg-popover shadow-xl">- <div className="border-b px-3 py-2 text-[11px] font-medium text-muted-foreground">- {t('terminal.suggestionsTitle')}+ >+ <input+ ref={inputRef}+ value={command}+ onBlur={() => {+ window.setTimeout(() => setSuggestionsOpen(false), 120)+ }}+ onChange={(event) => {+ setCommand(event.target.value)+ setSuggestionsOpen(true)+ }}+ onFocus={() => setSuggestionsOpen(true)}+ onKeyDown={(event) => {+ if (!suggestionsOpen || suggestions.length === 0) return+ if (event.key === 'ArrowDown') {+ event.preventDefault()+ setActiveSuggestionIndex((current) =>+ Math.min(current + 1, suggestions.length - 1),+ )+ return+ }+ if (event.key === 'ArrowUp') {+ event.preventDefault()+ setActiveSuggestionIndex((current) =>+ Math.max(current - 1, 0),+ )+ return+ }+ if (event.key === 'Tab') {+ event.preventDefault()+ acceptSuggestion(suggestions[activeSuggestionIndex])+ return+ }+ if (+ event.key === 'ArrowRight' &&+ event.currentTarget.selectionStart === command.length &&+ event.currentTarget.selectionEnd === command.length+ ) {+ event.preventDefault()+ acceptSuggestion(suggestions[activeSuggestionIndex])+ return+ }+ if (event.key === 'Enter') {+ event.preventDefault()+ if (command.trim() === '/') {+ acceptSuggestion(suggestions[activeSuggestionIndex])+ return+ }+ runSuggestion(suggestions[activeSuggestionIndex])+ return+ }+ if (event.key === 'Escape') {+ setSuggestionsOpen(false)+ }+ }}+ placeholder={t('terminal.placeholder')}+ className="h-8 min-w-0 flex-1 bg-transparent font-mono text-sm outline-none placeholder:text-muted-foreground/60"+ />+ {suggestionsOpen && suggestions.length > 0 ? (+ <div className="absolute bottom-[calc(100%+0.5rem)] left-0 right-0 z-20 overflow-hidden rounded-lg border bg-popover shadow-xl">+ <div className="border-b px-3 py-2 text-[11px] font-medium text-muted-foreground">+ {t('terminal.suggestionsTitle')}+ </div>+ <div className="max-h-64 overflow-y-auto p-1">+ {(() => {+ let suggestionIndex = 0+ return groupedSuggestions.map((group) => (+ <div key={group.group} className="py-1 first:pt-0">+ <div className="px-2 pb-1 pt-1 text-[10px] font-semibold text-muted-foreground">+ {group.label}+ </div>+ {group.items.map((suggestion) => {+ const index = suggestionIndex+ suggestionIndex += 1+ return (+ <button+ key={suggestion.id}+ type="button"+ className={cn(+ 'flex w-full min-w-0 items-start gap-3 rounded-md px-2 py-2 text-left transition-colors',+ index === activeSuggestionIndex+ ? 'bg-primary/10 text-foreground'+ : 'hover:bg-muted/60',+ )}+ onClick={() => acceptSuggestion(suggestion)}+ onMouseDown={(event) => event.preventDefault()}+ onMouseEnter={() =>+ setActiveSuggestionIndex(index)+ }+ >+ <span className="w-24 shrink-0 font-mono text-xs font-semibold text-primary">+ {suggestion.command}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-xs text-foreground">+ {suggestion.description}+ </span>+ <span className="mt-0.5 block truncate font-mono text-[11px] text-muted-foreground">+ {suggestion.usage}+ </span>+ </span>+ </button>+ )+ })}+ </div>+ ))+ })()}+ </div>+ <div className="border-t px-3 py-1.5 text-[10px] text-muted-foreground">+ {t('terminal.suggestionsHint')}+ </div></div>- <div className="max-h-64 overflow-y-auto p-1">- {suggestions.map((suggestion, index) => (- <button- key={suggestion.command}- type="button"- className={cn(- 'flex w-full min-w-0 items-start gap-3 rounded-md px-2 py-2 text-left transition-colors',- index === activeSuggestionIndex- ? 'bg-primary/10 text-foreground'- : 'hover:bg-muted/60',- )}- onClick={() => acceptSuggestion(suggestion)}- onMouseDown={(event) => event.preventDefault()}- onMouseEnter={() => setActiveSuggestionIndex(index)}- >- <span className="w-24 shrink-0 font-mono text-xs font-semibold text-primary">- {suggestion.command}- </span>- <span className="min-w-0 flex-1">- <span className="block text-xs text-foreground">- {suggestion.description}- </span>- <span className="mt-0.5 block truncate font-mono text-[11px] text-muted-foreground">- {suggestion.usage}- </span>- </span>- </button>+ ) : null}+ <Button+ type="submit"+ size="icon-sm"+ disabled={running || !command.trim()}+ >+ <SendIcon className="size-4" />+ </Button>+ </form>+ </div>+ </div>+ <Dialog open={historyOpen} onOpenChange={setHistoryOpen}>+ <DialogContent className="gap-4 sm:max-w-2xl">+ <DialogHeader>+ <div className="flex items-start gap-3">+ <div className="min-w-0 flex-1">+ <DialogTitle>{t('terminal.historyTitle')}</DialogTitle>+ <DialogDescription>+ {t('terminal.historyDescription')}+ </DialogDescription>+ </div>+ {history.length > 0 ? (+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ className="size-7 shrink-0"+ title={t('terminal.clearHistory')}+ onClick={clearHistory}+ >+ <TrashIcon className="size-3.5" />+ </Button>+ ) : null}+ </div>+ </DialogHeader>+ <div className="max-h-[460px] overflow-y-auto pr-1">+ {history.length === 0 ? (+ <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">+ {t('terminal.noHistory')}+ </div>+ ) : (+ <div className="space-y-3">+ {history.map((entry) => (+ <TerminalHistoryItem+ key={`dialog-${entry.id}`}+ entry={entry}+ onOpenResource={onOpenResource}+ openingUri={openingUri}+ />))}</div>- <div className="border-t px-3 py-1.5 text-[10px] text-muted-foreground">- {t('terminal.suggestionsHint')}+ )}+ </div>+ </DialogContent>+ </Dialog>+ </>+ )+}++function TerminalQuickStart({+ examples,+ title,+}: {+ examples: TerminalQuickStartExample[]+ title: string+}) {+ return (+ <section className="space-y-3 py-3">+ <div className="text-xs font-semibold text-muted-foreground">{title}</div>+ <div className="space-y-2">+ {examples.map((example) => {+ const content = (+ <>+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-background text-muted-foreground">+ <ArrowRightIcon className="size-4" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex flex-wrap items-center gap-2">+ <span className="text-sm font-medium text-foreground">+ {example.title}+ </span>+ <span className="rounded-md border bg-background px-2 py-0.5 font-mono text-xs font-semibold">+ {example.command}+ </span>+ </span>+ <span className="mt-1 block truncate font-mono text-xs text-muted-foreground">+ {example.code}+ </span>+ </span>+ </>+ )++ if (!example.action) {+ return (+ <div+ key={example.key}+ className="flex min-w-0 items-center gap-3 rounded-lg bg-muted/40 px-3 py-3"+ >+ {content}</div>- </div>- ) : null}- <Button- type="submit"- size="icon-sm"- disabled={running || !command.trim()}- >- <SendIcon className="size-4" />- </Button>- </form>+ )+ }++ return (+ <button+ key={example.key}+ type="button"+ className="flex w-full min-w-0 items-center gap-3 rounded-lg bg-muted/40 px-3 py-3 text-left transition-colors hover:bg-muted/70"+ onClick={example.action}+ >+ {content}+ </button>+ )+ })}</div>- </div>+ </section>)}diff --git a/web-studio/src/routes/playground/-lib/constants.ts b/web-studio/src/routes/playground/-lib/constants.tsindex 7dad63f15..c38b23dcb 100644--- a/web-studio/src/routes/playground/-lib/constants.ts+++ b/web-studio/src/routes/playground/-lib/constants.ts@@ -20,10 +20,89 @@ export const PLAYGROUND_RIGHT_WIDTH = {export const PLAYGROUND_MAIN_MIN_WIDTH = 420export const TERMINAL_COMMANDS: TerminalCommandSuggestion[] = [- { command: '/status', key: 'status', insertText: '/status' },- { command: '/ls', key: 'ls', insertText: '/ls ' },- { command: '/search', key: 'search', insertText: '/search ' },- { command: '/find', key: 'find', insertText: '/find ' },- { command: '/read', key: 'read', insertText: '/read ' },- { command: '/add-resource', key: 'addResource', insertText: '/add-resource' },+ {+ command: '/add-resource',+ executable: true,+ group: 'core',+ key: 'addResource',+ insertText: '/add-resource',+ },+ {+ command: '/find',+ executable: true,+ group: 'core',+ key: 'find',+ insertText: '/find ',+ },+ {+ command: '/read',+ executable: true,+ group: 'core',+ key: 'read',+ insertText: '/read ',+ },+ {+ command: '/ls',+ executable: true,+ group: 'filesystem',+ key: 'ls',+ insertText: '/ls ',+ },+ {+ command: '/tree',+ executable: true,+ group: 'filesystem',+ key: 'tree',+ insertText: '/tree ',+ },+ {+ command: '/stat',+ executable: true,+ group: 'filesystem',+ key: 'stat',+ insertText: '/stat ',+ },+ {+ command: '/search',+ executable: true,+ group: 'search',+ key: 'search',+ insertText: '/search ',+ },+ {+ command: '/abstract',+ executable: true,+ group: 'search',+ key: 'abstract',+ insertText: '/abstract ',+ },+ {+ command: '/overview',+ executable: true,+ group: 'search',+ key: 'overview',+ insertText: '/overview ',+ },+ {+ command: '/health',+ executable: true,+ group: 'status',+ key: 'health',+ insertText: '/health',+ },+ {+ command: '/status',+ executable: true,+ group: 'status',+ key: 'status',+ insertText: '/status',+ },+ {+ adminOnly: true,+ command: '/wait',+ executable: true,+ group: 'status',+ key: 'wait',+ insertText: '/wait ',+ },]diff --git a/web-studio/src/routes/playground/-lib/types.ts b/web-studio/src/routes/playground/-lib/types.tsindex a1a1e9cf2..cc39bb1cb 100644--- a/web-studio/src/routes/playground/-lib/types.ts+++ b/web-studio/src/routes/playground/-lib/types.ts@@ -24,19 +24,16 @@ export type TerminalEntry = {refs?: ResourceRef[]}-export type TerminalCommandKey =- | 'status'- | 'ls'- | 'search'- | 'find'- | 'read'- | 'addResource'+export type TerminalCommandGroup = 'core' | 'filesystem' | 'search' | 'status'export type TerminalCommandSuggestion = {+ adminOnly?: booleancommand: string+ group: TerminalCommandGroup/** i18n subkey under `playground.terminal.commands`. */- key: TerminalCommandKey+ key: stringinsertText: string+ executable?: boolean}/** A {@link TerminalCommandSuggestion} with its label/usage resolved via i18n. */diff --git a/web-studio/src/routes/playground/-lib/utils.ts b/web-studio/src/routes/playground/-lib/utils.tsindex 128df2d9d..d7f7899a4 100644--- a/web-studio/src/routes/playground/-lib/utils.ts+++ b/web-studio/src/routes/playground/-lib/utils.ts@@ -37,25 +37,57 @@ export function readStoredNumber(return Number.isFinite(value) ? clampNumber(value, min, max) : fallback}-export function readPlaygroundAgentSessionIds(): string[] {+export function readStoredJsonArray<T>(+ key: string,+ validator: (value: unknown) => T | undefined,+ limit?: number,+ fromEnd = false,+): T[] {if (typeof window === 'undefined') return []try {- const raw = window.localStorage.getItem(- PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY,- )- const parsed = raw ? (JSON.parse(raw) as unknown) : []+ const raw = window.localStorage.getItem(key)+ const parsed: unknown = raw ? JSON.parse(raw) : []if (!Array.isArray(parsed)) return []-- return parsed.filter(- (sessionId): sessionId is string =>- typeof sessionId === 'string' && sessionId.length > 0,- )+ const values = parsed.flatMap((item) => {+ const value = validator(item)+ return value === undefined ? [] : [value]+ })+ if (limit === undefined) return values+ return fromEnd ? values.slice(-limit) : values.slice(0, limit)} catch {return []}}+export function writeStoredJson(key: string, value: unknown): void {+ if (typeof window === 'undefined') return+ try {+ window.localStorage.setItem(key, JSON.stringify(value))+ } catch {+ // Ignore storage failures in restricted browser contexts.+ }+}++export function removeStoredValue(key: string): void {+ if (typeof window === 'undefined') return+ try {+ window.localStorage.removeItem(key)+ } catch {+ // Ignore storage failures in restricted browser contexts.+ }+}++export function readPlaygroundAgentSessionIds(): string[] {+ return readStoredJsonArray(+ PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY,+ (sessionId) =>+ typeof sessionId === 'string' && sessionId.length > 0+ ? sessionId+ : undefined,+ )+}+export function registerPlaygroundAgentSessionId(sessionId: string): string[] {const trimmed = sessionId.trim()if (typeof window === 'undefined') return trimmed ? [trimmed] : []@@ -66,14 +98,7 @@ export function registerPlaygroundAgentSessionId(sessionId: string): string[] {...readPlaygroundAgentSessionIds().filter((item) => item !== trimmed),].slice(0, 50)- try {- window.localStorage.setItem(- PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY,- JSON.stringify(next),- )- } catch {- // Ignore storage failures in restricted browser contexts.- }+ writeStoredJson(PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY, next)return next}diff --git a/web-studio/src/routes/sessions/-components/message-list.tsx b/web-studio/src/routes/sessions/-components/message-list.tsxindex 0b4d4a0c3..ff62bf5f5 100644--- a/web-studio/src/routes/sessions/-components/message-list.tsx+++ b/web-studio/src/routes/sessions/-components/message-list.tsx@@ -3,8 +3,7 @@ import { CheckIcon, CopyIcon, UserIcon } from 'lucide-react'import { useTranslation } from 'react-i18next'import { resolvePublicAsset } from '#/lib/public-path'-import type { StreamToolCall } from '#/lib/sessions/types/chat'-import type { Message } from '#/lib/sessions/types/message'+import type { Message, MessagePart, ToolPart } from '#/lib/sessions/types/message'import { MarkdownContent, ReasoningBlock, ToolCallBlock } from './message-parts'const OPENVIKING_ICON_SRC = resolvePublicAsset('favicon-32.png')@@ -41,7 +40,8 @@ function CopyButton({ text }: { text: string }) {/** Extract all text content from a message's parts. */function getTextFromParts(message: Message): string {- return message.parts+ const parts = Array.isArray(message.parts) ? message.parts : []+ return parts.filter((p) => p.type === 'text').map((p) => (p as { text: string }).text).join('\n')@@ -105,9 +105,7 @@ interface MessageListProps {layout?: 'default' | 'expanded'messages: Message[]streaming?: {- content: string- toolCalls: StreamToolCall[]- reasoning: string+ parts?: MessagePart[]iteration: number}onResourceClick?: (uri: string) => void@@ -120,10 +118,11 @@ export function MessageList({streaming,}: MessageListProps) {const isExpanded = layout === 'expanded'+ const safeMessages = Array.isArray(messages) ? messages : []return (<>- {messages.map((msg, idx) => {- const prev = idx > 0 ? messages[idx - 1] : null+ {safeMessages.map((msg, idx) => {+ const prev = idx > 0 ? safeMessages[idx - 1] : nullconst sameRole = prev?.role === msg.rolereturn msg.role === 'user' ? (<UserMessage@@ -218,10 +217,18 @@ const AssistantMessage = memo(function AssistantMessage({>{!compact ? <BotAvatar compact={expanded} /> : <div className="w-6 shrink-0" />}<div className="relative max-w-full min-w-0 flex-1 rounded-2xl rounded-tl-sm bg-background/95 px-4 py-3 text-sm shadow-sm ring-1 ring-border/30">- {message.parts.map((part, i) => {+ {(Array.isArray(message.parts) ? message.parts : []).map((part, i) => {switch (part.type) {case 'text':return <MarkdownContent key={i} content={part.text} />+ case 'reasoning':+ return (+ <ReasoningBlock+ key={i}+ reasoning={part.reasoning}+ isRunning={false}+ />+ )case 'tool':return (<ToolCallBlock@@ -254,22 +261,19 @@ const AssistantMessage = memo(function AssistantMessage({// ---------------------------------------------------------------------------function StreamingAssistantMessage({- content,expanded,- toolCalls,- reasoning,+ parts = [],iteration,onResourceClick,}: {- content: stringexpanded?: boolean- toolCalls: StreamToolCall[]- reasoning: string+ parts?: MessagePart[]iteration: numberonResourceClick?: (uri: string) => void}) {const { t } = useTranslation('sessions')- const hasContent = content || toolCalls.length > 0 || reasoning+ const safeParts = Array.isArray(parts) ? parts : []+ const hasContent = safeParts.length > 0return (<div className={`${expanded ? 'w-full' : 'w-full max-w-3xl'} mb-5 flex gap-2 items-start`}>@@ -283,33 +287,60 @@ function StreamingAssistantMessage({</div>)}- <ReasoningBlock reasoning={reasoning} isRunning />+ {safeParts.map((part, i) => renderStreamingPart(part, i, onResourceClick))}- {toolCalls.map((tc, i) => {- let args: Record<string, unknown> = {}- try {- args = JSON.parse(tc.arguments) as Record<string, unknown>- } catch {- if (tc.arguments) args = { raw: tc.arguments }- }- return (- <ToolCallBlock- key={i}- toolName={tc.name}- args={args}- result={tc.result}- isRunning={!tc.result}- onResourceClick={onResourceClick}- />- )- })}-- {content ? (- <MarkdownContent content={content} isStreaming />- ) : !hasContent ? (+ {!hasContent ? (<TypingIndicator />) : null}</div></div>)}++function renderStreamingPart(+ part: MessagePart,+ index: number,+ onResourceClick?: (uri: string) => void,+) {+ switch (part.type) {+ case 'reasoning':+ return (+ <ReasoningBlock+ key={index}+ reasoning={part.reasoning}+ isRunning={part.is_running ?? true}+ />+ )+ case 'tool':+ return (+ <StreamingToolPart+ key={index}+ part={part}+ onResourceClick={onResourceClick}+ />+ )+ case 'text':+ return <MarkdownContent key={index} content={part.text} isStreaming />+ case 'context':+ return null+ }+}++function StreamingToolPart({+ part,+ onResourceClick,+}: {+ part: ToolPart+ onResourceClick?: (uri: string) => void+}) {+ return (+ <ToolCallBlock+ toolName={part.tool_name}+ args={part.tool_input}+ result={part.tool_output}+ isError={part.tool_status === 'error'}+ isRunning={part.tool_status === 'running' || part.tool_status === 'pending'}+ onResourceClick={onResourceClick}+ />+ )+}diff --git a/web-studio/src/routes/sessions/-components/thread.tsx b/web-studio/src/routes/sessions/-components/thread.tsxindex f6b1bee31..6baf956f4 100644--- a/web-studio/src/routes/sessions/-components/thread.tsx+++ b/web-studio/src/routes/sessions/-components/thread.tsx@@ -57,9 +57,7 @@ export function Thread({ sessionId }: ThreadProps) {})}, [chat.messages.length,- chat.streamingContent,- chat.streamingToolCalls,- chat.streamingReasoning,+ chat.streamingParts,])const [showBackground, setShowBackground] = useState(false)@@ -116,9 +114,7 @@ export function Thread({ sessionId }: ThreadProps) {streaming={isStreaming? {- content: chat.streamingContent,- toolCalls: chat.streamingToolCalls,- reasoning: chat.streamingReasoning,+ parts: chat.streamingParts,iteration: chat.iteration,}: undefineddiff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsxindex f1e5bcee9..41039db90 100644--- a/web-studio/src/routes/settings/route.tsx+++ b/web-studio/src/routes/settings/route.tsx@@ -152,6 +152,38 @@ function maskApiKey(value: string | undefined): string {return `${value.slice(0, 10)}...${value.slice(-6)}`}+async function copyTextToClipboard(value: string): Promise<void> {+ try {+ await navigator.clipboard.writeText(value)+ return+ } catch {+ // Clipboard API is unavailable on non-secure dev URLs such as http://10.x.x.x.+ }++ if (typeof document === 'undefined') {+ throw new Error('Clipboard is unavailable')+ }++ const textArea = document.createElement('textarea')+ textArea.value = value+ textArea.setAttribute('readonly', '')+ textArea.style.position = 'fixed'+ textArea.style.left = '-9999px'+ textArea.style.top = '0'+ document.body.appendChild(textArea)+ textArea.focus()+ textArea.select()++ try {+ const copied = document.execCommand('copy')+ if (!copied) {+ throw new Error('Clipboard copy failed')+ }+ } finally {+ document.body.removeChild(textArea)+ }+}+function resolveKeyLabel(user: AdminUser): string {return user.apiKey ? maskApiKey(user.apiKey) : user.keyPrefix || '-'}@@ -196,8 +228,12 @@ function KeyResultCard({}async function copyKey(): Promise<void> {- await navigator.clipboard.writeText(result.apiKey)- toast.success(t('toast.copied'))+ try {+ await copyTextToClipboard(result.apiKey)+ toast.success(t('toast.copied'))+ } catch {+ toast.error(t('toast.copyFailed'))+ }}return (@@ -1068,8 +1104,12 @@ function SettingsRoute() {if (!value) {return}- await navigator.clipboard.writeText(value)- toast.success(t('toast.copied'))+ try {+ await copyTextToClipboard(value)+ toast.success(t('toast.copied'))+ } catch {+ toast.error(t('toast.copyFailed'))+ }}return (