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: improve playground bot flow (#2381)
yufengc9abc2e8af9b
diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex 3668083a4..3dc0343aa 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -225,6 +225,39 @@ class AgentLoop:))+ async def _publish_auto_memory_context(+ self,+ session_key: SessionKey,+ query: str,+ result: str,+ ) -> dict[str, Any]:+ """Expose automatic OpenViking memory lookup using the existing tool event stream."""+ args_str = json.dumps({"query": query}, ensure_ascii=False)+ await self.bus.publish_outbound(+ OutboundMessage(+ session_key=session_key,+ content=f"openviking_search({args_str})",+ event_type=OutboundEventType.TOOL_CALL,+ )+ )+ await self.bus.publish_outbound(+ OutboundMessage(+ session_key=session_key,+ content=result,+ event_type=OutboundEventType.TOOL_RESULT,+ )+ )+ return {+ "tool_name": "openviking_search",+ "args": args_str,+ "result": result,+ "duration": 0,+ "execute_success": True,+ "input_token": cal_str_tokens(query, text_type="mixed"),+ "output_token": cal_str_tokens(result, text_type="mixed"),+ "auto": True,+ }+def _register_builtin_hooks(self):"""Register built-in hooks."""hook_manager.register_path(self.config.hooks)@@ -951,6 +984,13 @@ class AgentLoop:memory_users=memory_user,)relevant_memories = message_context.latest_relevant_memories+ auto_memory_tool = None+ if ov_tools_enable and relevant_memories:+ auto_memory_tool = await self._publish_auto_memory_context(+ session_key=session_key,+ query=msg.content,+ result=relevant_memories,+ )# logger.info(f"New messages: {json.dumps(messages, indent=4)}")# Run agent loop within a stable response identity for tracing/tool spans.@@ -972,6 +1012,9 @@ class AgentLoop:disabled_tools=disabled_tools,)+ if auto_memory_tool:+ tools_used = [auto_memory_tool, *(tools_used or [])]+# Log response previewpreview = final_content[:300] + "..." if len(final_content) > 300 else final_contentlogger.info(f"Response to {msg.session_key}: {preview}")diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.pyindex 78c18f911..20309500a 100644--- a/bot/vikingbot/agent/memory.py+++ b/bot/vikingbot/agent/memory.py@@ -20,6 +20,50 @@ class MemoryStore:self.memory_file = self.memory_dir / "MEMORY.md"self.history_file = self.memory_dir / "HISTORY.md"+ @staticmethod+ def _get_score(memory: Any) -> float:+ raw_score = (+ memory.get("score", 0) if isinstance(memory, dict) else getattr(memory, "score", 0.0)+ )+ try:+ return float(raw_score)+ except (TypeError, ValueError):+ return 0.0++ @classmethod+ def _limit_memory_groups(+ cls,+ result: dict[str, list[Any]],+ limit: int,+ ) -> dict[str, list[Any]]:+ user_memories = result.get("user_memory", [])+ agent_memories = result.get("agent_memory", [])+ ranked: list[tuple[float, str, int, Any]] = []++ for group, memories in (+ ("user_memory", user_memories),+ ("agent_memory", agent_memories),+ ):+ for index, memory in enumerate(memories):+ ranked.append((cls._get_score(memory), group, index, memory))++ selected = {+ (group, index)+ for _, group, index, _ in sorted(ranked, key=lambda item: item[0], reverse=True)[:limit]+ }+ return {+ "user_memory": [+ memory+ for index, memory in enumerate(user_memories)+ if ("user_memory", index) in selected+ ],+ "agent_memory": [+ memory+ for index, memory in enumerate(agent_memories)+ if ("agent_memory", index) in selected+ ],+ }+def read_long_term(self) -> str:if self.memory_file.exists():return self.memory_file.read_text(encoding="utf-8")@@ -153,10 +197,11 @@ class MemoryStore:query=current_message,user_ids=search_user_ids,agent_user_id=admin_user_id,- limit=30,+ limit=10,)if not result:return ""+ result = self._limit_memory_groups(result, limit=10)# Log raw search results for debuggingmemory_list = []diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.pyindex ed09a093e..be0547e07 100644--- a/bot/vikingbot/agent/tools/ov_file.py+++ b/bot/vikingbot/agent/tools/ov_file.py@@ -264,7 +264,7 @@ class VikingSearchTool(OVFileTool):results = await client.search(query,target_uri=client._memory_target_uri(memory_user_id),- limit=20,+ limit=10,user_id=admin_user_id,)filtered_items = self._filter_search_items(results, min_score=min_score)@@ -279,7 +279,7 @@ class VikingSearchTool(OVFileTool):results = await client.search(query,target_uri=target_uri,- limit=20,+ limit=10,user_id=admin_user_id,)@@ -509,6 +509,48 @@ class VikingGlobTool(OVFileTool):class VikingMemoryCommitTool(OVFileTool):"""Tool to commit messages to OpenViking session."""+ async def _get_commit_task_result(+ self,+ client: VikingClient,+ task_id: str | None,+ attempts: int = 20,+ interval: float = 0.5,+ ) -> dict[str, Any] | None:+ if not task_id:+ return None+ get_task = getattr(client.client, "get_task", None)+ if not callable(get_task):+ return None++ task = None+ for _ in range(attempts):+ task = await get_task(task_id)+ if isinstance(task, dict) and task.get("status") in {"completed", "failed"}:+ return task+ await asyncio.sleep(interval)+ return task if isinstance(task, dict) else None++ @staticmethod+ def _extract_memory_diff_uris(diff: Any) -> dict[str, list[str]]:+ operations = diff.get("operations", {}) if isinstance(diff, dict) else {}+ return {+ "added_uris": [+ item["uri"]+ for item in operations.get("adds", [])+ if isinstance(item, dict) and item.get("uri")+ ],+ "updated_uris": [+ item["uri"]+ for item in operations.get("updates", [])+ if isinstance(item, dict) and item.get("uri")+ ],+ "deleted_uris": [+ item["uri"]+ for item in operations.get("deletes", [])+ if isinstance(item, dict) and item.get("uri")+ ],+ }+@propertydef name(self) -> str:return "openviking_memory_commit"@@ -549,8 +591,37 @@ class VikingMemoryCommitTool(OVFileTool):return "Error committed, sender_id is required."client = await self._get_client(tool_context)session_id = tool_context.session_key.safe_name()- await client.commit(session_id, messages, tool_context.sender_id)- return f"Successfully committed to session {session_id}"+ result = await client.commit(session_id, messages, tool_context.sender_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+ task_id = commit_result.get("task_id")+ task = await self._get_commit_task_result(client, task_id)+ changed_uris = {"added_uris": [], "updated_uris": [], "deleted_uris": []}++ if task and task.get("status") == "completed" and memory_diff_uri:+ raw_diff = await client.read_content(memory_diff_uri, level="read")+ if raw_diff:+ try:+ changed_uris = self._extract_memory_diff_uris(json.loads(raw_diff))+ except json.JSONDecodeError:+ logger.warning(f"Failed to parse memory diff from {memory_diff_uri}")++ return json.dumps(+ {+ "status": "success",+ "session_id": session_id,+ "message_count": len(messages),+ "archived": commit_result.get("archived"),+ **changed_uris,+ "archive_uri": archive_uri,+ "memory_diff_uri": memory_diff_uri,+ "task_id": task_id,+ "task_status": task.get("status") if isinstance(task, dict) else None,+ },+ ensure_ascii=False,+ indent=2,+ )except Exception as e:logger.exception(f"Error processing message: {e}")return f"Error committing to Viking: {str(e)}"diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsxindex db557a244..778b618f9 100644--- a/web-studio/src/components/app-shell.tsx+++ b/web-studio/src/components/app-shell.tsx@@ -91,9 +91,9 @@ const NAV_ITEMS: readonly NavItem[] = [},{icon: PlugZapIcon,- id: 'studio',- titleKey: 'navigation.studio.title',- to: '/studio',+ id: 'playground',+ titleKey: 'navigation.playground.title',+ to: '/playground',},{icon: FolderTreeIcon,diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsxindex ea435695c..7f2fbce96 100644--- a/web-studio/src/hooks/use-app-connection.tsx+++ b/web-studio/src/hooks/use-app-connection.tsx@@ -55,7 +55,7 @@ const ENV_USER =const DEFAULT_CONNECTION: ConnectionDraft = {accountId: ENV_ACCOUNT || 'default',- agentId: ENV_AGENT || 'web-studio',+ agentId: ENV_AGENT || 'web-playground',apiKey: ENV_API_KEY,baseUrl: ovClient.getOptions().baseUrl,userId: ENV_USER || 'default',@@ -114,6 +114,17 @@ function normalizeConnectionDraft(}}+function resolveIdentityField(+ envValue: string,+ storedValue: string | undefined,+ defaultValue: string,+): string {+ if (envValue) {+ return envValue+ }+ return storedValue || defaultValue+}+function applyConnection(connection: ConnectionDraft): void {ovClient.setOptions({baseUrl: connection.baseUrl,@@ -128,21 +139,29 @@ function applyConnection(connection: ConnectionDraft): void {function readInitialConnection(): ConnectionDraft {const storedConnection = readStoredConnection()+ const apiKey =+ ENV_API_KEY ||+ ovClient.getConnection().apiKey ||+ storedConnection.apiKey ||+ DEFAULT_CONNECTION.apiKeyreturn normalizeConnectionDraft({...DEFAULT_CONNECTION,...storedConnection,- accountId:- ENV_ACCOUNT || storedConnection.accountId || DEFAULT_CONNECTION.accountId,+ accountId: resolveIdentityField(+ ENV_ACCOUNT,+ storedConnection.accountId,+ DEFAULT_CONNECTION.accountId,+ ),agentId:ENV_AGENT || storedConnection.agentId || DEFAULT_CONNECTION.agentId,- apiKey:- ENV_API_KEY ||- ovClient.getConnection().apiKey ||- storedConnection.apiKey ||- DEFAULT_CONNECTION.apiKey,+ apiKey,baseUrl:ENV_BASE_URL || storedConnection.baseUrl || DEFAULT_CONNECTION.baseUrl,- userId: ENV_USER || storedConnection.userId || DEFAULT_CONNECTION.userId,+ userId: resolveIdentityField(+ ENV_USER,+ storedConnection.userId,+ DEFAULT_CONNECTION.userId,+ ),})}diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.tsindex a6f6f2ad1..b84673f63 100644--- a/web-studio/src/i18n/locales/en.ts+++ b/web-studio/src/i18n/locales/en.ts@@ -6,7 +6,7 @@ const en = {github: 'GitHub',},header: {- defaultTitle: 'OpenViking Studio',+ defaultTitle: 'OpenViking Playground',},navigation: {home: {@@ -30,14 +30,14 @@ const en = {sessions: {title: 'Sessions',},- studio: {+ playground: {title: 'Playground',},},sidebar: {loadingSessions: 'Loading...',noSessions: 'No sessions',- workspaceGroupLabel: 'OpenViking Studio',+ workspaceGroupLabel: 'OpenViking Playground',},},common: {@@ -82,7 +82,7 @@ const en = {},agentId: {label: 'Agent',- placeholder: 'web-studio',+ placeholder: 'web-playground',},apiKey: {label: 'API Key',@@ -128,7 +128,7 @@ const en = {connection: {adminError: 'Could not load admin identities: {{message}}',description:- 'Select the account and user that Studio should send with OpenViking requests.',+ 'Select the account and user that Playground should send with OpenViking requests.',noKey:'Enter an API key with admin access to load account and user choices.',title: 'Connection settings',@@ -181,12 +181,12 @@ const en = {},page: {description:- 'Configure the active OpenViking identity and manage accounts, users, and API keys from Studio.',+ 'Configure the active OpenViking identity and manage accounts, users, and API keys from Playground.',title: 'Connection & Identity',},placeholders: {account: 'team-account',- agent: 'web-studio',+ agent: 'web-playground',apiKey: 'Enter X-API-Key or Bearer token',baseUrl: 'http://127.0.0.1:1933',user: 'default',@@ -294,7 +294,7 @@ const en = {title: 'Playground',},requestLogs: {- description: 'Inspect Studio requests, status, and latency.',+ description: 'Inspect Playground requests, status, and latency.',title: 'Request Logs',},resources: {@@ -315,7 +315,7 @@ const en = {page: {description:'Aligned with the product overview: menu entries, context data volume, today tokens, today retrievals, agent access, token trend, and context commit stats.',- eyebrow: 'OpenViking Studio',+ eyebrow: 'OpenViking Playground',settings: 'Connection & Settings',title: 'Overview',},@@ -370,7 +370,7 @@ const en = {description: 'Failed to load audited request logs from the server.',title: 'Request failed',},- eyebrow: 'Studio telemetry',+ eyebrow: 'Playground telemetry',filters: {all: 'All logs',apiTypePlaceholder: 'API type',@@ -710,6 +710,7 @@ const en = {toolCall: 'Tool call',toolInput: 'Input',toolResult: 'Result',+ loadMoreRefs: 'Load {{count}} more ({{remaining}} remaining)',toolStatus: {completed: 'Completed',failed: 'Failed',@@ -745,7 +746,7 @@ const en = {scopesLabel: 'Scopes',scopesNone: '(none)',signInRequired:- 'Sign in to OpenViking Studio (Connection & Identity) or paste an API key below to authorize this client.',+ 'Sign in to OpenViking Playground (Connection & Identity) or paste an API key below to authorize this client.',openConnectionDialog: 'Open Connection & Identity',authorize: 'Authorize',deny: 'Deny',@@ -771,10 +772,10 @@ const en = {verifyError: 'Authorization failed: {{message}}',noApiKey: 'No API key available. Select an identity or paste a key.',signInRequired:- 'Sign in to OpenViking Studio (Connection & Identity) or paste an API key below to verify.',+ 'Sign in to OpenViking Playground (Connection & Identity) or paste an API key below to verify.',},},- studio: {+ playground: {copyUri: 'Copy current URI',copied: 'URI copied',resizeContext: 'Resize context tree width',@@ -805,7 +806,7 @@ const en = {autoRetrieve: 'The Agent retrieves on its own from messages and tools',history: 'Session history',newSession: 'New session',- creating: 'Creating Studio session...',+ creating: 'Creating Playground session...',detectingBot: 'Detecting bot mode...',createFailed: 'Failed to create session: {{error}}',retry: 'Retry',@@ -816,8 +817,8 @@ const en = {loadingSessions: 'Loading sessions...',noSessions: 'No session history yet',createTimeout:- 'Creating the Studio session timed out. Check your connection settings and try again.',- newSessionTitle: 'New Studio session',+ 'Creating the Playground session timed out. Check your connection settings and try again.',+ newSessionTitle: 'New Playground session',botPrompt: {title: 'Please enable bot mode',description:diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.tsindex fbbcf3709..823224eaf 100644--- a/web-studio/src/i18n/locales/zh-CN.ts+++ b/web-studio/src/i18n/locales/zh-CN.ts@@ -6,7 +6,7 @@ const zhCN = {github: 'GitHub',},header: {- defaultTitle: 'OpenViking Studio',+ defaultTitle: 'OpenViking Playground',},navigation: {home: {@@ -30,14 +30,14 @@ const zhCN = {sessions: {title: '会话',},- studio: {+ playground: {title: '实验场',},},sidebar: {loadingSessions: '加载中...',noSessions: '暂无会话',- workspaceGroupLabel: 'OpenViking Studio',+ workspaceGroupLabel: 'OpenViking Playground',},},common: {@@ -82,7 +82,7 @@ const zhCN = {},agentId: {label: 'Agent',- placeholder: 'web-studio',+ placeholder: 'web-playground',},apiKey: {label: 'API Key',@@ -128,7 +128,7 @@ const zhCN = {connection: {adminError: '加载 admin 身份失败:{{message}}',description:- '选择 Studio 调用 OpenViking API 时要携带的 account 和 user。',+ '选择 Playground 调用 OpenViking API 时要携带的 account 和 user。',noKey:'输入具备 admin 权限的 API key 后,可以加载 account 和 user 可选项。',title: '连接设置',@@ -181,12 +181,12 @@ const zhCN = {},page: {description:- '在 Studio 中配置当前 OpenViking 身份,并管理 accounts、users 和 API keys。',+ '在 Playground 中配置当前 OpenViking 身份,并管理 accounts、users 和 API keys。',title: '连接与身份',},placeholders: {account: 'team-account',- agent: 'web-studio',+ agent: 'web-playground',apiKey: '输入 X-API-Key 或 Bearer token',baseUrl: 'http://127.0.0.1:1933',user: 'default',@@ -294,7 +294,7 @@ const zhCN = {title: 'Playground',},requestLogs: {- description: '查看 Studio 发出的请求、状态与耗时。',+ description: '查看 Playground 发出的请求、状态与耗时。',title: '请求日志',},resources: {@@ -315,7 +315,7 @@ const zhCN = {page: {description:'按产品需求对齐首页内容:菜单入口、上下文数据量、今日 tokens、今日检索、Agent 访问、tokens 趋势和上下文提交统计。',- eyebrow: 'OpenViking Studio',+ eyebrow: 'OpenViking Playground',settings: '连接与设置',title: 'Overview',},@@ -365,7 +365,7 @@ const zhCN = {description: '无法从服务端加载审计请求日志。',title: '请求失败',},- eyebrow: 'Studio 遥测',+ eyebrow: 'Playground 遥测',filters: {all: '所有日志',apiTypePlaceholder: 'API 类型',@@ -465,8 +465,7 @@ const zhCN = {'directlyUploadMedia.hint':'开启时,媒体文件(图片、音频、视频)原样存储。关闭后,媒体文件会先通过 AI 视觉/音频管道提取内容再存储。',createParent: '自动创建父文件夹',- 'createParent.hint':- '开启时,若目标父目录不存在则自动创建。',+ 'createParent.hint': '开启时,若目标父目录不存在则自动创建。',reason: '添加原因','reason.placeholder': '为什么要添加这个资源?',instruction: '处理指令',@@ -699,6 +698,7 @@ const zhCN = {toolCall: '工具调用',toolInput: '输入',toolResult: '结果',+ loadMoreRefs: '加载更多 {{count}} 条(剩余 {{remaining}} 条)',toolStatus: {completed: '完成',failed: '失败',@@ -731,7 +731,7 @@ const zhCN = {scopesLabel: '权限范围',scopesNone: '(无)',signInRequired:- '请先在“连接与身份”中登录 OpenViking Studio,或在下方临时粘贴 API key 完成授权。',+ '请先在“连接与身份”中登录 OpenViking Playground,或在下方临时粘贴 API key 完成授权。',openConnectionDialog: '打开连接与身份',authorize: '授权',deny: '拒绝',@@ -754,10 +754,10 @@ const zhCN = {verifyError: '授权失败:{{message}}',noApiKey: '没有可用的 API key。请选择一个身份或粘贴 key。',signInRequired:- '请先在“连接与身份”中登录 OpenViking Studio,或在下方临时粘贴 API key 完成授权。',+ '请先在“连接与身份”中登录 OpenViking Playground,或在下方临时粘贴 API key 完成授权。',},},- studio: {+ playground: {copyUri: '复制当前 URI',copied: '已复制 URI',resizeContext: '调整上下文目录宽度',@@ -788,7 +788,7 @@ const zhCN = {autoRetrieve: 'Agent 会根据消息和工具自主检索',history: '历史会话',newSession: '新建会话',- creating: '正在创建 Studio 会话...',+ creating: '正在创建 Playground 会话...',detectingBot: '正在检测 bot 模式...',createFailed: '创建会话失败:{{error}}',retry: '重试',@@ -798,8 +798,8 @@ const zhCN = {'这里只展示实验场右侧 Agent 使用过的会话;新建会话会开启一个空白 Agent 上下文。',loadingSessions: '正在加载会话...',noSessions: '暂无历史会话',- createTimeout: '创建 Studio 会话超时,请检查连接设置后重试。',- newSessionTitle: '新建 Studio 会话',+ createTimeout: '创建 Playground 会话超时,请检查连接设置后重试。',+ newSessionTitle: '新建 Playground 会话',botPrompt: {title: '请开启 bot 模式',description:diff --git a/web-studio/src/lib/ov-client/client.ts b/web-studio/src/lib/ov-client/client.tsindex e07b5a9db..a169fa44f 100644--- a/web-studio/src/lib/ov-client/client.ts+++ b/web-studio/src/lib/ov-client/client.ts@@ -19,7 +19,7 @@ const DEFAULT_TELEMETRY_PATHS = new Set(['/api/v1/resources',])const SESSION_COMMIT_PATH = /^\/api\/v1\/sessions\/[^/]+\/commit$/-const WEB_STUDIO_AGENT_ID = 'web-studio'+const WEB_PLAYGROUND_AGENT_ID = 'web-playground'function isBrowser(): boolean {return typeof window !== 'undefined'@@ -157,7 +157,7 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {options.connection?.apiKey ??readSessionStorage(runtimeOptions.apiKeyStorageKey),accountId: options.connection?.accountId ?? '',- agentId: options.connection?.agentId ?? WEB_STUDIO_AGENT_ID,+ agentId: options.connection?.agentId ?? WEB_PLAYGROUND_AGENT_ID,userId: options.connection?.userId ?? '',}@@ -180,7 +180,10 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {setOptionalHeader(headers, 'X-API-Key', connection.apiKey)setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)setOptionalHeader(headers, 'X-OpenViking-User', connection.userId)- headers.set('X-OpenViking-Agent', connection.agentId || WEB_STUDIO_AGENT_ID)+ headers.set(+ 'X-OpenViking-Agent',+ connection.agentId || WEB_PLAYGROUND_AGENT_ID,+ )config.headers = headersmaybeInjectTelemetry(config, runtimeOptions.defaultTelemetry)@@ -253,7 +256,7 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {connection = {apiKey: '',accountId: '',- agentId: WEB_STUDIO_AGENT_ID,+ agentId: WEB_PLAYGROUND_AGENT_ID,userId: '',}persistApiKey()diff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.tsindex 94ad6989d..7828afb12 100644--- a/web-studio/src/lib/sessions/api.ts+++ b/web-studio/src/lib/sessions/api.ts@@ -149,7 +149,7 @@ function buildFetchHeaders(): Record<string, string> {if (conn.apiKey) headers['X-API-Key'] = conn.apiKeyif (conn.accountId) headers['X-OpenViking-Account'] = conn.accountIdif (conn.userId) headers['X-OpenViking-User'] = conn.userId- headers['X-OpenViking-Agent'] = conn.agentId || 'web-studio'+ headers['X-OpenViking-Agent'] = conn.agentId || 'web-playground'return headers}@@ -185,10 +185,15 @@ export async function sendChatStream(signal?: AbortSignal,): Promise<Response> {const baseUrl = ovClient.getOptions().baseUrl+ const conn = ovClient.getConnection()const response = await fetch(`${baseUrl}/bot/v1/chat/stream`, {method: 'POST',headers: buildFetchHeaders(),- body: JSON.stringify({ ...request, stream: true }),+ body: JSON.stringify({+ ...request,+ user_id: request.user_id || conn.userId || undefined,+ stream: true,+ }),signal,})@@ -206,8 +211,12 @@ export async function sendChatStream(export async function sendChat(request: BotChatRequest,): Promise<BotChatResponse> {+ const conn = ovClient.getConnection()const response = await postBotV1Chat({- body: request,+ body: {+ ...request,+ user_id: request.user_id || conn.userId || undefined,+ },throwOnError: true,} as unknown as NonNullable<Parameters<typeof postBotV1Chat<true>>[0]>)diff --git a/web-studio/src/lib/sessions/types/chat.ts b/web-studio/src/lib/sessions/types/chat.tsindex 4f38b7fbc..d4d89f184 100644--- a/web-studio/src/lib/sessions/types/chat.ts+++ b/web-studio/src/lib/sessions/types/chat.ts@@ -15,6 +15,7 @@ export type ChatStatus = 'idle' | 'streaming' | 'error'export interface StreamToolCall {name: stringarguments: string+ iteration?: numberresult?: string}diff --git a/web-studio/src/lib/sessions/use-chat.ts b/web-studio/src/lib/sessions/use-chat.tsindex 7a0317ea0..c064e77f5 100644--- a/web-studio/src/lib/sessions/use-chat.ts+++ b/web-studio/src/lib/sessions/use-chat.ts@@ -17,6 +17,31 @@ function createUserMessage(content: string): Message {}}+function toolCallKey(toolCall: StreamToolCall): string {+ return `${toolCall.iteration ?? 0}\u0000${toolCall.name}\u0000${toolCall.arguments}`+}++function dedupeToolCalls(toolCalls: StreamToolCall[]): StreamToolCall[] {+ const result: StreamToolCall[] = []+ const byKey = new Map<string, StreamToolCall>()++ for (const toolCall of toolCalls) {+ const key = toolCallKey(toolCall)+ const existing = byKey.get(key)+ if (!existing) {+ const next = { ...toolCall }+ byKey.set(key, next)+ result.push(next)+ continue+ }+ if (!existing.result && toolCall.result) {+ existing.result = toolCall.result+ }+ }++ return result+}+type SendOptions = {displayMessage?: string}@@ -175,6 +200,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {let accReasoning = ''const accToolCalls: StreamToolCall[] = []let lastToolCall: StreamToolCall | null = null+ let currentIteration = 0try {const response = await sendChatStream(@@ -189,7 +215,10 @@ export function useChat(options: UseChatOptions): UseChatReturn {case 'iteration': {const data = streamEventDataToText(event.data)const match = data.match(/(\d+)/)- if (match) setIteration(Number(match[1]))+ if (match) {+ currentIteration = Number(match[1])+ setIteration(currentIteration)+ }break}@@ -220,16 +249,32 @@ export function useChat(options: UseChatOptions): UseChatReturn {const parenIdx = raw.indexOf('(')const name = parenIdx > 0 ? raw.slice(0, parenIdx) : rawconst args = parenIdx > 0 ? raw.slice(parenIdx + 1, -1) : ''- lastToolCall = { name, arguments: args }+ const duplicate = accToolCalls.find(+ (tc) =>+ tc.iteration === currentIteration &&+ tc.name === name &&+ tc.arguments === args &&+ !tc.result,+ )+ if (duplicate) {+ lastToolCall = duplicate+ setStreamingToolCalls(dedupeToolCalls(accToolCalls))+ break+ }+ lastToolCall = {+ name,+ arguments: args,+ iteration: currentIteration,+ }accToolCalls.push(lastToolCall)- setStreamingToolCalls([...accToolCalls])+ setStreamingToolCalls(dedupeToolCalls(accToolCalls))break}case 'tool_result': {if (lastToolCall) {lastToolCall.result = streamEventDataToText(event.data)- setStreamingToolCalls([...accToolCalls])+ setStreamingToolCalls(dedupeToolCalls(accToolCalls))}break}@@ -244,12 +289,15 @@ export function useChat(options: UseChatOptions): UseChatReturn {}// Build assistant message and finalize- const assistantMsg = buildAssistantMessage(accContent, accToolCalls)- setMessages((prev) => [...prev, assistantMsg])- setStatus('idle')+ const assistantMsg = buildAssistantMessage(+ accContent,+ dedupeToolCalls(accToolCalls),+ )setStreamingContent('')setStreamingToolCalls([])setStreamingReasoning('')+ setStatus('idle')+ setMessages((prev) => [...prev, assistantMsg])// Persist to openviking session (bot doesn't do this automatically)if (persistMessages) {@@ -284,7 +332,13 @@ export function useChat(options: UseChatOptions): UseChatReturn {if (controller.signal.aborted) {// Aborted intentionally — still finalize any partial contentif (accContent) {- const partialMsg = buildAssistantMessage(accContent, accToolCalls)+ const partialMsg = buildAssistantMessage(+ accContent,+ dedupeToolCalls(accToolCalls),+ )+ setStreamingContent('')+ setStreamingToolCalls([])+ setStreamingReasoning('')setMessages((prev) => [...prev, partialMsg])}setStatus('idle')diff --git a/web-studio/src/lib/viking-uri.ts b/web-studio/src/lib/viking-uri.tsindex 084d0753f..f7e199dc6 100644--- a/web-studio/src/lib/viking-uri.ts+++ b/web-studio/src/lib/viking-uri.ts@@ -57,7 +57,7 @@ export function joinUri(baseUri: string, child: string): string {/*** Matches `viking://` URIs inside arbitrary text. Stops at whitespace, quotes,* brackets and the punctuation that commonly trails a URI in prose. Shared so- * the sessions view and the studio playground extract URIs identically.+ * the sessions view and the playground extract URIs identically.*/export const VIKING_URI_RE = /viking:\/\/[^\s,,。;;'"`<>()\]}\\]+/gdiff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.tsindex e195a2941..d67d1998a 100644--- a/web-studio/src/routeTree.gen.ts+++ b/web-studio/src/routeTree.gen.ts@@ -9,12 +9,12 @@// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.import { Route as rootRouteImport } from './routes/__root'-import { Route as StudioRouteRouteImport } from './routes/studio/route'import { Route as SettingsRouteRouteImport } from './routes/settings/route'import { Route as SessionsRouteRouteImport } from './routes/sessions/route'import { Route as RetrievalRouteRouteImport } from './routes/retrieval/route'import { Route as ResourcesRouteRouteImport } from './routes/resources/route'import { Route as RequestLogsRouteRouteImport } from './routes/request-logs/route'+import { Route as PlaygroundRouteRouteImport } from './routes/playground/route'import { Route as HomeRouteRouteImport } from './routes/home/route'import { Route as IndexRouteImport } from './routes/index'import { Route as SessionsIndexRouteImport } from './routes/sessions/index'@@ -23,11 +23,6 @@ import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'import { Route as OauthSetupRouteImport } from './routes/oauth/setup'import { Route as OauthConsentRouteImport } from './routes/oauth/consent'-const StudioRouteRoute = StudioRouteRouteImport.update({- id: '/studio',- path: '/studio',- getParentRoute: () => rootRouteImport,-} as any)const SettingsRouteRoute = SettingsRouteRouteImport.update({id: '/settings',path: '/settings',@@ -53,6 +48,11 @@ const RequestLogsRouteRoute = RequestLogsRouteRouteImport.update({path: '/request-logs',getParentRoute: () => rootRouteImport,} as any)+const PlaygroundRouteRoute = PlaygroundRouteRouteImport.update({+ id: '/playground',+ path: '/playground',+ getParentRoute: () => rootRouteImport,+} as any)const HomeRouteRoute = HomeRouteRouteImport.update({id: '/home',path: '/home',@@ -92,12 +92,12 @@ const OauthConsentRoute = OauthConsentRouteImport.update({export interface FileRoutesByFullPath {'/': typeof IndexRoute'/home': typeof HomeRouteRoute+ '/playground': typeof PlaygroundRouteRoute'/request-logs': typeof RequestLogsRouteRoute'/resources': typeof ResourcesRouteRouteWithChildren'/retrieval': typeof RetrievalRouteRoute'/sessions': typeof SessionsRouteRouteWithChildren'/settings': typeof SettingsRouteRoute- '/studio': typeof StudioRouteRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/setup': typeof OauthSetupRoute'/oauth/verify': typeof OauthVerifyRoute@@ -107,10 +107,10 @@ export interface FileRoutesByFullPath {export interface FileRoutesByTo {'/': typeof IndexRoute'/home': typeof HomeRouteRoute+ '/playground': typeof PlaygroundRouteRoute'/request-logs': typeof RequestLogsRouteRoute'/retrieval': typeof RetrievalRouteRoute'/settings': typeof SettingsRouteRoute- '/studio': typeof StudioRouteRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/setup': typeof OauthSetupRoute'/oauth/verify': typeof OauthVerifyRoute@@ -121,12 +121,12 @@ export interface FileRoutesById {__root__: typeof rootRouteImport'/': typeof IndexRoute'/home': typeof HomeRouteRoute+ '/playground': typeof PlaygroundRouteRoute'/request-logs': typeof RequestLogsRouteRoute'/resources': typeof ResourcesRouteRouteWithChildren'/retrieval': typeof RetrievalRouteRoute'/sessions': typeof SessionsRouteRouteWithChildren'/settings': typeof SettingsRouteRoute- '/studio': typeof StudioRouteRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/setup': typeof OauthSetupRoute'/oauth/verify': typeof OauthVerifyRoute@@ -138,12 +138,12 @@ export interface FileRouteTypes {fullPaths:| '/'| '/home'+ | '/playground'| '/request-logs'| '/resources'| '/retrieval'| '/sessions'| '/settings'- | '/studio'| '/oauth/consent'| '/oauth/setup'| '/oauth/verify'@@ -153,10 +153,10 @@ export interface FileRouteTypes {to:| '/'| '/home'+ | '/playground'| '/request-logs'| '/retrieval'| '/settings'- | '/studio'| '/oauth/consent'| '/oauth/setup'| '/oauth/verify'@@ -166,12 +166,12 @@ export interface FileRouteTypes {| '__root__'| '/'| '/home'+ | '/playground'| '/request-logs'| '/resources'| '/retrieval'| '/sessions'| '/settings'- | '/studio'| '/oauth/consent'| '/oauth/setup'| '/oauth/verify'@@ -182,12 +182,12 @@ export interface FileRouteTypes {export interface RootRouteChildren {IndexRoute: typeof IndexRouteHomeRouteRoute: typeof HomeRouteRoute+ PlaygroundRouteRoute: typeof PlaygroundRouteRouteRequestLogsRouteRoute: typeof RequestLogsRouteRouteResourcesRouteRoute: typeof ResourcesRouteRouteWithChildrenRetrievalRouteRoute: typeof RetrievalRouteRouteSessionsRouteRoute: typeof SessionsRouteRouteWithChildrenSettingsRouteRoute: typeof SettingsRouteRoute- StudioRouteRoute: typeof StudioRouteRouteOauthConsentRoute: typeof OauthConsentRouteOauthSetupRoute: typeof OauthSetupRouteOauthVerifyRoute: typeof OauthVerifyRoute@@ -195,13 +195,6 @@ export interface RootRouteChildren {declare module '@tanstack/react-router' {interface FileRoutesByPath {- '/studio': {- id: '/studio'- path: '/studio'- fullPath: '/studio'- preLoaderRoute: typeof StudioRouteRouteImport- parentRoute: typeof rootRouteImport- }'/settings': {id: '/settings'path: '/settings'@@ -237,6 +230,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof RequestLogsRouteRouteImportparentRoute: typeof rootRouteImport}+ '/playground': {+ id: '/playground'+ path: '/playground'+ fullPath: '/playground'+ preLoaderRoute: typeof PlaygroundRouteRouteImport+ parentRoute: typeof rootRouteImport+ }'/home': {id: '/home'path: '/home'@@ -316,12 +316,12 @@ const SessionsRouteRouteWithChildren = SessionsRouteRoute._addFileChildren(const rootRouteChildren: RootRouteChildren = {IndexRoute: IndexRoute,HomeRouteRoute: HomeRouteRoute,+ PlaygroundRouteRoute: PlaygroundRouteRoute,RequestLogsRouteRoute: RequestLogsRouteRoute,ResourcesRouteRoute: ResourcesRouteRouteWithChildren,RetrievalRouteRoute: RetrievalRouteRoute,SessionsRouteRoute: SessionsRouteRouteWithChildren,SettingsRouteRoute: SettingsRouteRoute,- StudioRouteRoute: StudioRouteRoute,OauthConsentRoute: OauthConsentRoute,OauthSetupRoute: OauthSetupRoute,OauthVerifyRoute: OauthVerifyRoute,diff --git a/web-studio/src/routes/studio/-components/agent-panel.tsx b/web-studio/src/routes/playground/-components/agent-panel.tsxsimilarity index 94%rename from web-studio/src/routes/studio/-components/agent-panel.tsxrename to web-studio/src/routes/playground/-components/agent-panel.tsxindex 4973f4215..34d123a06 100644--- a/web-studio/src/routes/studio/-components/agent-panel.tsx+++ b/web-studio/src/routes/playground/-components/agent-panel.tsx@@ -36,8 +36,8 @@ import { MessageList } from '#/routes/sessions/-components/message-list'import type { ResourceOpenHandler } from '../-lib/types'import {getErrorMessage,- readStudioAgentSessionIds,- registerStudioAgentSessionId,+ readPlaygroundAgentSessionIds,+ registerPlaygroundAgentSessionId,withTimeout,} from '../-lib/utils'@@ -50,7 +50,7 @@ export function AgentPanel({onOpenResource: ResourceOpenHandleronSessionChange: (sessionId: string) => void}) {- const { t } = useTranslation('studio')+ const { t } = useTranslation('playground')const [sessionId, setSessionId] = useState(initialSessionId ?? '')const [historyOpen, setHistoryOpen] = useState(false)const [sessionError, setSessionError] = useState<string | null>(null)@@ -60,14 +60,14 @@ export function AgentPanel({const createSession = useCreateSession()const { data: sessions, isLoading: isLoadingSessions } = useSessionList()const { getTitle } = useSessionTitles()- const [studioSessionIds, setStudioSessionIds] = useState<string[]>(() =>- readStudioAgentSessionIds(),+ const [playgroundSessionIds, setPlaygroundSessionIds] = useState<string[]>(+ () => readPlaygroundAgentSessionIds(),)const { data: historyMessages } = useSessionMessages(sessionId || undefined)const chat = useChat({initialMessages: historyMessages,persistMessages: Boolean(sessionId),- sessionId: sessionId || 'studio-preview',+ sessionId: sessionId || 'playground-preview',})const scrollRef = useRef<HTMLDivElement>(null)const bottomRef = useRef<HTMLDivElement>(null)@@ -85,7 +85,9 @@ export function AgentPanel({12_000,t('agent.createTimeout'),)- setStudioSessionIds(registerStudioAgentSessionId(result.session_id))+ setPlaygroundSessionIds(+ registerPlaygroundAgentSessionId(result.session_id),+ )setSessionId(result.session_id)onSessionChange(result.session_id)} catch (error) {@@ -111,7 +113,9 @@ export function AgentPanel({12_000,t('agent.createTimeout'),)- setStudioSessionIds(registerStudioAgentSessionId(result.session_id))+ setPlaygroundSessionIds(+ registerPlaygroundAgentSessionId(result.session_id),+ )setSessionTitle(result.session_id, t('agent.newSessionTitle'))setSessionId(result.session_id)onSessionChange(result.session_id)@@ -130,7 +134,7 @@ export function AgentPanel({creationStartedRef.current = truesetSessionError(null)setIsCreatingSession(false)- setStudioSessionIds(registerStudioAgentSessionId(nextSessionId))+ setPlaygroundSessionIds(registerPlaygroundAgentSessionId(nextSessionId))setSessionId(nextSessionId)onSessionChange(nextSessionId)setHistoryOpen(false)@@ -149,7 +153,7 @@ export function AgentPanel({useEffect(() => {if (sessionId) {- setStudioSessionIds(registerStudioAgentSessionId(sessionId))+ setPlaygroundSessionIds(registerPlaygroundAgentSessionId(sessionId))}}, [sessionId])@@ -177,12 +181,12 @@ export function AgentPanel({(sessions ?? []).map((session) => [session.session_id, session]),)- return studioSessionIds+ return playgroundSessionIds.map((sessionId) => sessionById.get(sessionId)).filter((session): session is NonNullable<typeof session> =>Boolean(session),)- }, [sessions, studioSessionIds])+ }, [sessions, playgroundSessionIds])return (<>@@ -260,6 +264,7 @@ export function AgentPanel({<AgentEmptyState onSend={send} />) : (<MessageList+ layout="expanded"messages={chat.messages}onResourceClick={onOpenResource}streaming={@@ -373,7 +378,7 @@ export function BotModePrompt({detail: stringonRetry: () => void}) {- const { t } = useTranslation('studio')+ const { t } = useTranslation('playground')return (<div className="flex h-full items-center justify-center"><div className="grid max-w-md gap-4 rounded-xl border border-primary/25 bg-primary/5 p-5 text-sm">@@ -416,7 +421,7 @@ export function AgentEmptyState({}: {onSend: (message: string) => void}) {- const { t } = useTranslation('studio')+ const { t } = useTranslation('playground')const prompts = t('agent.empty.prompts', {returnObjects: true,}) as string[]diff --git a/web-studio/src/routes/studio/-components/context-explorer.tsx b/web-studio/src/routes/playground/-components/context-explorer.tsxsimilarity index 98%rename from web-studio/src/routes/studio/-components/context-explorer.tsxrename to web-studio/src/routes/playground/-components/context-explorer.tsxindex da7b31f02..16345d4fb 100644--- a/web-studio/src/routes/studio/-components/context-explorer.tsx+++ b/web-studio/src/routes/playground/-components/context-explorer.tsx@@ -38,7 +38,7 @@ export function ContextExplorerHeader({onAddResource: () => voidonRefresh: () => void}) {- const { t } = useTranslation('studio')+ const { t } = useTranslation('playground')return (<div className="border-b px-3 py-3"><div className="flex items-center gap-2">@@ -120,7 +120,7 @@ export function ContextTree({onSelectFile: (entry: VikingFsEntry) => voidselectedFileUri?: string | null}) {- const { t } = useTranslation('studio')+ const { t } = useTranslation('playground')return (<div className="h-full overflow-auto px-2 py-2 font-mono">{NAMESPACES.map((item) => {@@ -147,7 +147,7 @@ export function ContextTree({)}-export function StudioResizeHandle({+export function PlaygroundResizeHandle({active,label,onPointerDown,diff --git a/web-studio/src/routes/studio/-components/resource-ref-list.tsx b/web-studio/src/routes/playground/-components/resource-ref-list.tsxsimilarity index 100%rename from web-studio/src/routes/studio/-components/resource-ref-list.tsxrename to web-studio/src/routes/playground/-components/resource-ref-list.tsxdiff --git a/web-studio/src/routes/studio/-components/terminal-panel.tsx b/web-studio/src/routes/playground/-components/terminal-panel.tsxsimilarity index 99%rename from web-studio/src/routes/studio/-components/terminal-panel.tsxrename to web-studio/src/routes/playground/-components/terminal-panel.tsxindex 1833ddb51..e419282bb 100644--- a/web-studio/src/routes/studio/-components/terminal-panel.tsx+++ b/web-studio/src/routes/playground/-components/terminal-panel.tsx@@ -46,7 +46,7 @@ export function TerminalPanel({onOpenResource: ResourceOpenHandleropeningUri: string | null}) {- const { t } = useTranslation('studio')+ const { t } = useTranslation('playground')const [command, setCommand] = useState('')const [running, setRunning] = useState(false)const [suggestionsOpen, setSuggestionsOpen] = useState(false)diff --git a/web-studio/src/routes/studio/-lib/constants.ts b/web-studio/src/routes/playground/-lib/constants.tssimilarity index 61%rename from web-studio/src/routes/studio/-lib/constants.tsrename to web-studio/src/routes/playground/-lib/constants.tsindex 195d13a40..7dad63f15 100644--- a/web-studio/src/routes/studio/-lib/constants.ts+++ b/web-studio/src/routes/playground/-lib/constants.ts@@ -1,21 +1,23 @@import type { TerminalCommandSuggestion } from './types'export const ROOT_URI = 'viking://'-export const STUDIO_LEFT_WIDTH_STORAGE_KEY = 'web-studio-playground-left-width'-export const STUDIO_RIGHT_WIDTH_STORAGE_KEY =- 'web-studio-playground-right-width'-export const STUDIO_AGENT_SESSIONS_STORAGE_KEY = 'web-studio-agent-sessions'-export const STUDIO_LEFT_WIDTH = {+export const PLAYGROUND_LEFT_WIDTH_STORAGE_KEY =+ 'openviking.playground.leftWidth'+export const PLAYGROUND_RIGHT_WIDTH_STORAGE_KEY =+ 'openviking.playground.rightWidth'+export const PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY =+ 'openviking.playground.agentSessions'+export const PLAYGROUND_LEFT_WIDTH = {default: 330,max: 620,min: 240,}-export const STUDIO_RIGHT_WIDTH = {+export const PLAYGROUND_RIGHT_WIDTH = {default: 430,max: 680,min: 320,}-export const STUDIO_MAIN_MIN_WIDTH = 420+export const PLAYGROUND_MAIN_MIN_WIDTH = 420export const TERMINAL_COMMANDS: TerminalCommandSuggestion[] = [{ command: '/status', key: 'status', insertText: '/status' },diff --git a/web-studio/src/routes/studio/-lib/types.ts b/web-studio/src/routes/playground/-lib/types.tssimilarity index 84%rename from web-studio/src/routes/studio/-lib/types.tsrename to web-studio/src/routes/playground/-lib/types.tsindex d5f148fdc..b6b1965f6 100644--- a/web-studio/src/routes/studio/-lib/types.ts+++ b/web-studio/src/routes/playground/-lib/types.ts@@ -1,11 +1,11 @@import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'-export type StudioPanel = 'agent' | 'terminal'+export type PlaygroundPanel = 'agent' | 'terminal'-export type StudioSearch = {+export type PlaygroundSearch = {uri?: stringfile?: string- panel?: StudioPanel+ panel?: PlaygroundPanelsession?: string}@@ -33,7 +33,7 @@ export type TerminalCommandKey =export type TerminalCommandSuggestion = {command: string- /** i18n subkey under `studio.terminal.commands`. */+ /** i18n subkey under `playground.terminal.commands`. */key: TerminalCommandKeyinsertText: string}diff --git a/web-studio/src/routes/studio/-lib/utils.ts b/web-studio/src/routes/playground/-lib/utils.tssimilarity index 91%rename from web-studio/src/routes/studio/-lib/utils.tsrename to web-studio/src/routes/playground/-lib/utils.tsindex 9acd7667d..128df2d9d 100644--- a/web-studio/src/routes/studio/-lib/utils.ts+++ b/web-studio/src/routes/playground/-lib/utils.ts@@ -9,7 +9,7 @@ import type { FindResultItem, GroupedFindResult } from '#/lib/retrieval'import { cleanVikingUri } from '#/lib/viking-uri'-import { ROOT_URI, STUDIO_AGENT_SESSIONS_STORAGE_KEY } from './constants'+import { ROOT_URI, PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY } from './constants'import type { ResourceRef } from './types'export { cleanVikingUri }@@ -37,11 +37,13 @@ export function readStoredNumber(return Number.isFinite(value) ? clampNumber(value, min, max) : fallback}-export function readStudioAgentSessionIds(): string[] {+export function readPlaygroundAgentSessionIds(): string[] {if (typeof window === 'undefined') return []try {- const raw = window.localStorage.getItem(STUDIO_AGENT_SESSIONS_STORAGE_KEY)+ const raw = window.localStorage.getItem(+ PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY,+ )const parsed = raw ? (JSON.parse(raw) as unknown) : []if (!Array.isArray(parsed)) return []@@ -54,19 +56,19 @@ export function readStudioAgentSessionIds(): string[] {}}-export function registerStudioAgentSessionId(sessionId: string): string[] {+export function registerPlaygroundAgentSessionId(sessionId: string): string[] {const trimmed = sessionId.trim()if (typeof window === 'undefined') return trimmed ? [trimmed] : []- if (!trimmed) return readStudioAgentSessionIds()+ if (!trimmed) return readPlaygroundAgentSessionIds()const next = [trimmed,- ...readStudioAgentSessionIds().filter((item) => item !== trimmed),+ ...readPlaygroundAgentSessionIds().filter((item) => item !== trimmed),].slice(0, 50)try {window.localStorage.setItem(- STUDIO_AGENT_SESSIONS_STORAGE_KEY,+ PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY,JSON.stringify(next),)} catch {@@ -150,7 +152,7 @@ export function isDirectoryLevelFile(uri: string): boolean {return name === '_abstract.md' || name === '_overview.md'}-export function normalizeStudioResourceUri(uri: string): string {+export function normalizePlaygroundResourceUri(uri: string): string {const normalized = uri.endsWith('/')? normalizeDirUri(uri): normalizeFileUri(uri)diff --git a/web-studio/src/routes/studio/route.tsx b/web-studio/src/routes/playground/route.tsxsimilarity index 82%rename from web-studio/src/routes/studio/route.tsxrename to web-studio/src/routes/playground/route.tsxindex 104c644d6..c60bf3ff1 100644--- a/web-studio/src/routes/studio/route.tsx+++ b/web-studio/src/routes/playground/route.tsx@@ -13,7 +13,6 @@ import {DialogHeader,DialogTitle,} from '#/components/ui/dialog'-import { cn } from '#/lib/utils'import { FilePreview } from '#/routes/resources/-components/file-preview'import { AddResourceForm } from '#/routes/resources/-components/add-resource-page'import { ResourceUploadProvider } from '#/routes/resources/-hooks/use-resource-upload'@@ -35,33 +34,32 @@ import {ContextExplorerHeader,ContextTree,PanelTab,- StudioResizeHandle,+ PlaygroundResizeHandle,} from './-components/context-explorer'import { TerminalPanel } from './-components/terminal-panel'import {ROOT_URI,- STUDIO_LEFT_WIDTH,- STUDIO_LEFT_WIDTH_STORAGE_KEY,- STUDIO_MAIN_MIN_WIDTH,- STUDIO_RIGHT_WIDTH,- STUDIO_RIGHT_WIDTH_STORAGE_KEY,+ PLAYGROUND_LEFT_WIDTH,+ PLAYGROUND_LEFT_WIDTH_STORAGE_KEY,+ PLAYGROUND_MAIN_MIN_WIDTH,+ PLAYGROUND_RIGHT_WIDTH,+ PLAYGROUND_RIGHT_WIDTH_STORAGE_KEY,} from './-lib/constants'-import type { StudioPanel, StudioSearch } from './-lib/types'+import type { PlaygroundPanel, PlaygroundSearch } from './-lib/types'import {- buildBreadcrumbs,clampNumber,cleanVikingUri,createEntryFromUri,getAncestorUris,isDirectoryLevelFile,mergeExpanded,- normalizeStudioResourceUri,+ normalizePlaygroundResourceUri,readStoredNumber,visibleContextEntries,} from './-lib/utils'-export const Route = createFileRoute('/studio')({- validateSearch: (search: Record<string, unknown>): StudioSearch => ({+export const Route = createFileRoute('/playground')({+ validateSearch: (search: Record<string, unknown>): PlaygroundSearch => ({file: typeof search.file === 'string' ? search.file : undefined,panel:search.panel === 'agent' || search.panel === 'terminal'@@ -70,19 +68,19 @@ export const Route = createFileRoute('/studio')({session: typeof search.session === 'string' ? search.session : undefined,uri: typeof search.uri === 'string' ? search.uri : undefined,}),- component: StudioRoute,+ component: PlaygroundRoute,})-function StudioRoute() {+function PlaygroundRoute() {return (<ResourceUploadProvider>- <StudioWorkbench />+ <PlaygroundWorkbench /></ResourceUploadProvider>)}-function StudioWorkbench() {- const { t } = useTranslation('studio')+function PlaygroundWorkbench() {+ const { t } = useTranslation('playground')const search = Route.useSearch()const navigate = useNavigate({ from: Route.fullPath })const initialCurrentUri = useMemo(@@ -102,7 +100,7 @@ function StudioWorkbench() {const [expandedKeys, setExpandedKeys] = useState<Set<string>>(() => new Set(getAncestorUris(initialCurrentUri)),)- const [activePanel, setActivePanel] = useState<StudioPanel>(+ const [activePanel, setActivePanel] = useState<PlaygroundPanel>(search.panel ?? 'agent',)const [uploadDialogOpen, setUploadDialogOpen] = useState(false)@@ -110,18 +108,18 @@ function StudioWorkbench() {const layoutRef = useRef<HTMLDivElement>(null)const [leftWidth, setLeftWidth] = useState(() =>readStoredNumber(- STUDIO_LEFT_WIDTH_STORAGE_KEY,- STUDIO_LEFT_WIDTH.default,- STUDIO_LEFT_WIDTH.min,- STUDIO_LEFT_WIDTH.max,+ PLAYGROUND_LEFT_WIDTH_STORAGE_KEY,+ PLAYGROUND_LEFT_WIDTH.default,+ PLAYGROUND_LEFT_WIDTH.min,+ PLAYGROUND_LEFT_WIDTH.max,),)const [rightWidth, setRightWidth] = useState(() =>readStoredNumber(- STUDIO_RIGHT_WIDTH_STORAGE_KEY,- STUDIO_RIGHT_WIDTH.default,- STUDIO_RIGHT_WIDTH.min,- STUDIO_RIGHT_WIDTH.max,+ PLAYGROUND_RIGHT_WIDTH_STORAGE_KEY,+ PLAYGROUND_RIGHT_WIDTH.default,+ PLAYGROUND_RIGHT_WIDTH.min,+ PLAYGROUND_RIGHT_WIDTH.max,),)const [resizingPane, setResizingPane] = useState<'context' | 'action' | null>(@@ -144,7 +142,7 @@ function StudioWorkbench() {const syncSearch = useCallback((next: {file?: string- panel?: StudioPanel+ panel?: PlaygroundPanelsession?: stringuri?: string}) => {@@ -184,7 +182,7 @@ function StudioWorkbench() {if (!cleaned) returnsetOpeningUri(cleaned)- const targetUri = normalizeStudioResourceUri(cleaned)+ const targetUri = normalizePlaygroundResourceUri(cleaned)try {const stat = await fetchFsStat(targetUri, { throwOnError: true })const isDir = stat.isDir || targetUri.endsWith('/')@@ -276,26 +274,22 @@ function StudioWorkbench() {)const handlePanelChange = useCallback(- (panel: StudioPanel) => {+ (panel: PlaygroundPanel) => {setActivePanel(panel)syncSearch({ panel })},[syncSearch],)- const breadcrumbs = useMemo(() => {- const targetUri = selectedFile?.uri ?? currentUri- const isFile = selectedFile ? !selectedFile.isDir : false- return buildBreadcrumbs(targetUri, isFile)- }, [currentUri, selectedFile])-const selectedUri = selectedFile?.uri ?? currentUri+ const displayUri =+ selectedUri === ROOT_URI ? selectedUri : selectedUri.replace(/\/$/, '')const entries = visibleContextEntries(listQuery.data?.entries ?? [])const layoutStyle = useMemo(() =>({- '--studio-left-width': `${leftWidth}px`,- '--studio-right-width': `${rightWidth}px`,+ '--playground-left-width': `${leftWidth}px`,+ '--playground-right-width': `${rightWidth}px`,}) as CSSProperties,[leftWidth, rightWidth],)@@ -318,16 +312,20 @@ function StudioWorkbench() {) => {if (!layoutRect) {return side === 'left'- ? STUDIO_LEFT_WIDTH.max- : STUDIO_RIGHT_WIDTH.max+ ? PLAYGROUND_LEFT_WIDTH.max+ : PLAYGROUND_RIGHT_WIDTH.max}const hardMax =- side === 'left' ? STUDIO_LEFT_WIDTH.max : STUDIO_RIGHT_WIDTH.max+ side === 'left'+ ? PLAYGROUND_LEFT_WIDTH.max+ : PLAYGROUND_RIGHT_WIDTH.maxconst availableMax =- layoutRect.width - currentOppositeWidth - STUDIO_MAIN_MIN_WIDTH+ layoutRect.width - currentOppositeWidth - PLAYGROUND_MAIN_MIN_WIDTHreturn Math.max(- side === 'left' ? STUDIO_LEFT_WIDTH.min : STUDIO_RIGHT_WIDTH.min,+ side === 'left'+ ? PLAYGROUND_LEFT_WIDTH.min+ : PLAYGROUND_RIGHT_WIDTH.min,Math.min(hardMax, availableMax),)}@@ -337,12 +335,12 @@ function StudioWorkbench() {if (pane === 'context') {const nextWidth = clampNumber(startLeftWidth + deltaX,- STUDIO_LEFT_WIDTH.min,+ PLAYGROUND_LEFT_WIDTH.min,getMaxWidth('left', rightWidthRef.current),)setLeftWidth(nextWidth)window.localStorage.setItem(- STUDIO_LEFT_WIDTH_STORAGE_KEY,+ PLAYGROUND_LEFT_WIDTH_STORAGE_KEY,String(nextWidth),)return@@ -350,12 +348,12 @@ function StudioWorkbench() {const nextWidth = clampNumber(startRightWidth - deltaX,- STUDIO_RIGHT_WIDTH.min,+ PLAYGROUND_RIGHT_WIDTH.min,getMaxWidth('right', leftWidthRef.current),)setRightWidth(nextWidth)window.localStorage.setItem(- STUDIO_RIGHT_WIDTH_STORAGE_KEY,+ PLAYGROUND_RIGHT_WIDTH_STORAGE_KEY,String(nextWidth),)}@@ -396,7 +394,7 @@ function StudioWorkbench() {className="flex min-h-0 flex-1 flex-col border-t bg-background lg:flex-row"style={layoutStyle}>- <aside className="flex min-h-[260px] min-w-0 flex-col border-b bg-muted/20 lg:min-h-0 lg:w-[var(--studio-left-width)] lg:min-w-[var(--studio-left-width)] lg:border-b-0">+ <aside className="flex min-h-[260px] min-w-0 flex-col border-b bg-muted/20 lg:min-h-0 lg:w-[var(--playground-left-width)] lg:min-w-[var(--playground-left-width)] lg:border-b-0"><ContextExplorerHeaderisRefreshing={listQuery.isFetching}onAddResource={() => setUploadDialogOpen(true)}@@ -418,7 +416,7 @@ function StudioWorkbench() {/></div></aside>- <StudioResizeHandle+ <PlaygroundResizeHandleactive={resizingPane === 'context'}label={t('resizeContext')}onPointerDown={(event) => handleResizeStart('context', event)}@@ -426,32 +424,14 @@ function StudioWorkbench() {<main className="flex min-h-[420px] min-w-0 flex-1 flex-col border-b lg:min-h-0 lg:border-b-0"><div className="flex min-h-14 items-center gap-3 border-b px-4">- <nav className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto whitespace-nowrap text-sm">- {breadcrumbs.map((crumb, index) => (- <span- key={crumb.uri}- className="flex shrink-0 items-center gap-1.5"- >- {index > 0 ? (- <span className="font-mono text-xs text-muted-foreground/60">- /- </span>- ) : null}- <button- type="button"- className={cn(- 'rounded px-1.5 py-1 font-mono text-xs transition-colors hover:bg-muted',- index === breadcrumbs.length - 1- ? 'font-semibold text-foreground'- : 'text-muted-foreground',- )}- onClick={() => void revealResource(crumb.uri)}- >- {crumb.label}- </button>- </span>- ))}- </nav>+ <button+ type="button"+ className="min-w-0 flex-1 truncate rounded px-1.5 py-1 text-left font-mono text-xs font-semibold text-foreground transition-colors hover:bg-muted"+ title={selectedUri}+ onClick={() => void revealResource(selectedUri)}+ >+ {displayUri}+ </button><Buttontype="button"size="icon-sm"@@ -473,13 +453,13 @@ function StudioWorkbench() {/></div></main>- <StudioResizeHandle+ <PlaygroundResizeHandleactive={resizingPane === 'action'}label={t('resizeAction')}onPointerDown={(event) => handleResizeStart('action', event)}/>- <aside className="flex min-h-[460px] min-w-0 flex-col bg-muted/15 lg:min-h-0 lg:w-[var(--studio-right-width)] lg:min-w-[var(--studio-right-width)]">+ <aside className="flex min-h-[460px] min-w-0 flex-col bg-muted/15 lg:min-h-0 lg:w-[var(--playground-right-width)] lg:min-w-[var(--playground-right-width)]"><div className="flex h-14 items-center border-b px-3"><div className="inline-flex rounded-lg border bg-background p-1"><PanelTabdiff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsxindex 97cf97cd6..2b3152569 100644--- a/web-studio/src/routes/resources/-components/file-preview.tsx+++ b/web-studio/src/routes/resources/-components/file-preview.tsx@@ -132,7 +132,7 @@ const DIRECTORY_LEVEL_META: Array<{]const JSONL_MESSAGE_PREVIEW_LIMIT = 720-const JSONL_TOOLCALL_STORAGE_KEY = 'web-studio-jsonl-toolcall'+const JSONL_TOOLCALL_STORAGE_KEY = 'openviking.playground.jsonlToolCall'type JsonlRecord = {error: Error | nulldiff --git a/web-studio/src/routes/resources/-components/viking-file-manager.tsx b/web-studio/src/routes/resources/-components/viking-file-manager.tsxindex 8ac0315d3..bd686d417 100644--- a/web-studio/src/routes/resources/-components/viking-file-manager.tsx+++ b/web-studio/src/routes/resources/-components/viking-file-manager.tsx@@ -61,8 +61,8 @@ function isDirectoryUri(uri: string): boolean {return uri.endsWith('/')}-const TREE_WIDTH_STORAGE_KEY = 'web-studio-resource-tree-width'-const TREE_HEIGHT_STORAGE_KEY = 'web-studio-resource-tree-height'+const TREE_WIDTH_STORAGE_KEY = 'openviking.playground.resourceTree.width'+const TREE_HEIGHT_STORAGE_KEY = 'openviking.playground.resourceTree.height'function clampNumber(value: number, min: number, max: number): number {return Math.min(Math.max(value, min), max)@@ -431,7 +431,7 @@ export function VikingFileManager({)return (- <div className="web-studio-resource-fs -mx-4 -my-6 flex h-[calc(100svh-3rem)] flex-col md:-mx-6">+ <div className="web-playground-resource-fs -mx-4 -my-6 flex h-[calc(100svh-3rem)] flex-col md:-mx-6"><div ref={layoutRef} className="flex min-h-0 flex-1 flex-col md:flex-row"><sectionclassName="flex h-[var(--resource-tree-height)] min-h-[190px] min-w-0 flex-col bg-muted/30 md:h-auto md:min-h-0 md:w-[var(--resource-tree-width)] md:min-w-[var(--resource-tree-width)]"diff --git a/web-studio/src/routes/retrieval/-constants/retrieval.ts b/web-studio/src/routes/retrieval/-constants/retrieval.tsindex 5c66c5f2b..30f0f7ada 100644--- a/web-studio/src/routes/retrieval/-constants/retrieval.ts+++ b/web-studio/src/routes/retrieval/-constants/retrieval.ts@@ -9,7 +9,7 @@ export const DEFAULT_RETRIEVAL_SCOPE = 'all'export const DEFAULT_CUSTOM_PATH_INPUT = 'resources/'export const LAST_RETRIEVAL_SEARCH_KEY =- 'openviking.web-studio.retrieval.lastSearch'+ 'openviking.playground.retrieval.lastSearch'export const KNOWN_VIKING_SCOPES = new Set(['agent',diff --git a/web-studio/src/routes/sessions/-components/composer.tsx b/web-studio/src/routes/sessions/-components/composer.tsxindex 899e28dd6..c1eebe592 100644--- a/web-studio/src/routes/sessions/-components/composer.tsx+++ b/web-studio/src/routes/sessions/-components/composer.tsx@@ -55,7 +55,8 @@ export function Composer({<div className={cn(isCompact ? 'px-3 pb-3 pt-2' : 'px-4 pb-4 pt-2')}><divclassName={cn(- 'mx-auto w-full max-w-3xl border border-border/50 bg-background/95',+ 'mx-auto w-full border border-border/50 bg-background/95',+ isCompact ? 'max-w-none' : 'max-w-3xl',isCompact ? 'rounded-xl' : 'rounded-2xl','shadow-lg shadow-black/8 dark:shadow-black/25',)}diff --git a/web-studio/src/routes/sessions/-components/message-list.tsx b/web-studio/src/routes/sessions/-components/message-list.tsxindex 295fb9ee9..0b4d4a0c3 100644--- a/web-studio/src/routes/sessions/-components/message-list.tsx+++ b/web-studio/src/routes/sessions/-components/message-list.tsx@@ -47,11 +47,11 @@ function getTextFromParts(message: Message): string {.join('\n')}-function stripStudioContextSuffix(text: string): string {+function stripPlaygroundContextSuffix(text: string): string {return text.replace(/\n\n当前选中的上下文资源:\s*viking:\/\/[\s\S]*$/u, '').replace(- /\n\n当前用户在 Studio 中选中的上下文资源是:\s*viking:\/\/[\s\S]*$/u,+ /\n\n当前用户在 Playground 中选中的上下文资源是:\s*viking:\/\/[\s\S]*$/u,'',)}@@ -88,10 +88,11 @@ function TypingIndicator() {// BotAvatar — product brand avatar// ----------------------------------------------------------------------------function BotAvatar() {+function BotAvatar({ compact }: { compact?: boolean }) {+ const sizeClass = compact ? 'size-6' : 'size-7'return (- <div className="flex size-7 shrink-0 items-center justify-center rounded-full ring-1 ring-border/20 overflow-hidden">- <img src={OPENVIKING_ICON_SRC} alt="OpenViking" className="size-7" />+ <div className={`flex ${sizeClass} shrink-0 items-center justify-center rounded-full ring-1 ring-border/20 overflow-hidden`}>+ <img src={OPENVIKING_ICON_SRC} alt="OpenViking" className={sizeClass} /></div>)}@@ -101,6 +102,7 @@ function BotAvatar() {// ---------------------------------------------------------------------------interface MessageListProps {+ layout?: 'default' | 'expanded'messages: Message[]streaming?: {content: string@@ -112,22 +114,30 @@ interface MessageListProps {}export function MessageList({+ layout = 'default',messages,onResourceClick,streaming,}: MessageListProps) {+ const isExpanded = layout === 'expanded'return (<>{messages.map((msg, idx) => {const prev = idx > 0 ? messages[idx - 1] : nullconst sameRole = prev?.role === msg.rolereturn msg.role === 'user' ? (- <UserMessage key={msg.id} message={msg} compact={sameRole} />+ <UserMessage+ key={msg.id}+ message={msg}+ compact={sameRole}+ expanded={isExpanded}+ />) : (<AssistantMessagekey={msg.id}message={msg}compact={sameRole}+ expanded={isExpanded}onResourceClick={onResourceClick}/>)@@ -135,6 +145,7 @@ export function MessageList({{streaming && (<StreamingAssistantMessage{...streaming}+ expanded={isExpanded}onResourceClick={onResourceClick}/>)}@@ -147,25 +158,27 @@ export function MessageList({// ---------------------------------------------------------------------------const UserMessage = memo(function UserMessage({+ expanded,message,compact,}: {+ expanded?: booleanmessage: Messagecompact?: boolean}) {- const text = stripStudioContextSuffix(getTextFromParts(message))+ const text = stripPlaygroundContextSuffix(getTextFromParts(message))return (<div- className={`group/msg flex w-full max-w-3xl gap-3 justify-end ${compact ? 'mb-1.5' : 'mb-5'}`}+ className={`${expanded ? 'w-full' : 'w-full max-w-3xl'} group/msg flex gap-2 justify-end ${compact ? 'mb-1.5' : 'mb-5'}`}>- <div className="flex items-end gap-1.5 self-end">+ <div className="flex items-end gap-1.5 self-end opacity-0 transition-opacity group-hover/msg:opacity-100"><span className="text-[10px] text-muted-foreground/40 opacity-0 transition-opacity group-hover/msg:opacity-100 select-none">{formatRelativeTime(message.created_at)}</span><CopyButton text={text} /></div>- <div className="max-w-[75%] space-y-1.5">+ <div className={expanded ? 'max-w-[88%] space-y-1.5' : 'max-w-[75%] space-y-1.5'}>{text && (<div className="whitespace-pre-wrap rounded-2xl rounded-tr-sm border border-border/70 bg-muted/70 px-4 py-2.5 text-sm leading-6 text-foreground shadow-sm">{text}@@ -173,11 +186,11 @@ const UserMessage = memo(function UserMessage({)}</div>{!compact && (- <div className="flex size-7 shrink-0 items-center justify-center rounded-full border border-border/70 bg-muted/60">+ <div className="flex size-6 shrink-0 items-center justify-center rounded-full border border-border/70 bg-muted/60"><UserIcon className="size-3.5 text-muted-foreground" /></div>)}- {compact && <div className="w-7 shrink-0" />}+ {compact && <div className="w-6 shrink-0" />}</div>)})@@ -187,10 +200,12 @@ const UserMessage = memo(function UserMessage({// ---------------------------------------------------------------------------const AssistantMessage = memo(function AssistantMessage({+ expanded,message,compact,onResourceClick,}: {+ expanded?: booleanmessage: Messagecompact?: booleanonResourceClick?: (uri: string) => void@@ -199,10 +214,10 @@ const AssistantMessage = memo(function AssistantMessage({return (<div- className={`group/msg flex w-full max-w-3xl gap-3 items-start ${compact ? 'mb-1.5' : 'mb-5'}`}+ className={`${expanded ? 'w-full' : 'w-full max-w-3xl'} group/msg flex gap-2 items-start ${compact ? 'mb-1.5' : 'mb-5'}`}>- {!compact ? <BotAvatar /> : <div className="w-7 shrink-0" />}- <div className="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">+ {!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) => {switch (part.type) {case 'text':@@ -223,12 +238,12 @@ const AssistantMessage = memo(function AssistantMessage({return null}})}- </div>- <div className="flex items-end gap-1.5 self-end">- <CopyButton text={textContent} />- <span className="text-[10px] text-muted-foreground/40 opacity-0 transition-opacity group-hover/msg:opacity-100 select-none">- {formatRelativeTime(message.created_at)}- </span>+ <div className="absolute right-2 top-2 flex items-center gap-1.5 rounded-lg bg-background/85 px-1.5 py-1 opacity-0 shadow-sm ring-1 ring-border/40 backdrop-blur transition-opacity group-hover/msg:opacity-100">+ <CopyButton text={textContent} />+ <span className="text-[10px] text-muted-foreground/60 select-none">+ {formatRelativeTime(message.created_at)}+ </span>+ </div></div></div>)@@ -240,12 +255,14 @@ const AssistantMessage = memo(function AssistantMessage({function StreamingAssistantMessage({content,+ expanded,toolCalls,reasoning,iteration,onResourceClick,}: {content: string+ expanded?: booleantoolCalls: StreamToolCall[]reasoning: stringiteration: number@@ -255,8 +272,8 @@ function StreamingAssistantMessage({const hasContent = content || toolCalls.length > 0 || reasoningreturn (- <div className="mb-5 flex w-full max-w-3xl gap-3 items-start">- <BotAvatar />+ <div className={`${expanded ? 'w-full' : 'w-full max-w-3xl'} mb-5 flex gap-2 items-start`}>+ <BotAvatar compact={expanded} /><div className="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">{iteration > 1 && (<div className="mb-2">diff --git a/web-studio/src/routes/sessions/-components/message-parts.tsx b/web-studio/src/routes/sessions/-components/message-parts.tsxindex e583b9e04..0dec044e8 100644--- a/web-studio/src/routes/sessions/-components/message-parts.tsx+++ b/web-studio/src/routes/sessions/-components/message-parts.tsx@@ -1,9 +1,11 @@+import { useEffect, useMemo, useState } from 'react'import { Streamdown } from 'streamdown'import { code } from '@streamdown/code'import { cjk } from '@streamdown/cjk'import { useTranslation } from 'react-i18next'import {CheckCircle2Icon,+ ChevronDownIcon,CircleAlertIcon,FileTextIcon,LoaderIcon,@@ -14,6 +16,7 @@ import { cn } from '#/lib/utils'import { cleanVikingUri, VIKING_URI_RE } from '#/lib/viking-uri'const plugins = { code, cjk }+const TOOL_REF_PAGE_SIZE = 5// ---------------------------------------------------------------------------// MarkdownContent@@ -118,7 +121,14 @@ export function ToolCallBlock({onResourceClick,}: ToolCallBlockProps) {const { t } = useTranslation('sessions')- const refs = extractVikingUris(result)+ const refs = useMemo(() => extractVikingUris(result), [result])+ const [visibleRefCount, setVisibleRefCount] = useState(TOOL_REF_PAGE_SIZE)+ const visibleRefs = refs.slice(0, visibleRefCount)+ const hiddenRefCount = Math.max(0, refs.length - visibleRefs.length)++ useEffect(() => {+ setVisibleRefCount(TOOL_REF_PAGE_SIZE)+ }, [result])return (<details className="my-2 rounded-lg border border-border/30 bg-muted/20">@@ -162,7 +172,7 @@ export function ToolCallBlock({</pre>{refs.length > 0 && onResourceClick ? (<div className="mt-2 grid gap-1.5">- {refs.map((uri) => (+ {visibleRefs.map((uri) => (<buttonkey={uri}type="button"@@ -175,6 +185,21 @@ export function ToolCallBlock({</span></button>))}+ {hiddenRefCount > 0 ? (+ <button+ type="button"+ className="inline-flex h-8 items-center justify-center gap-1.5 rounded-md border border-dashed bg-background px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:border-primary/50 hover:bg-primary/5 hover:text-primary"+ onClick={() =>+ setVisibleRefCount((count) => count + TOOL_REF_PAGE_SIZE)+ }+ >+ <ChevronDownIcon className="size-3.5" />+ {t('chat.loadMoreRefs', {+ count: Math.min(TOOL_REF_PAGE_SIZE, hiddenRefCount),+ remaining: hiddenRefCount,+ })}+ </button>+ ) : null}</div>) : null}</div>@@ -204,16 +229,16 @@ function extractVikingUris(text: string | undefined): string[] {const parsed = parseJsonResult(text)if (parsed !== undefined) {collectStructuredUris(parsed, seen)+ return [...seen]}- // Always scan the raw text too: URIs embedded in free-text fields or under- // keys other than `uri` are invisible to the structured pass. The Set keeps- // the two passes deduped.- const matches = text.match(VIKING_URI_RE) ?? []- for (const match of matches) {- const uri = cleanVikingUri(match)- if (uri) seen.add(uri)+ // Non-JSON tool results may contain XML/plain-text snippets with URI refs.+ if (text.includes('<memory')) {+ collectMemoryBlockUrisFromText(text, seen)+ if (seen.size > 0) return [...seen]}++ collectUrisFromText(text, seen)return [...seen]}@@ -228,23 +253,74 @@ function parseJsonResult(text: string): unknown {}}-function collectStructuredUris(value: unknown, seen: Set<string>): void {+function collectStructuredUris(+ value: unknown,+ seen: Set<string>,+ path: string[] = [],+): void {+ if (typeof value === 'string') {+ collectUrisFromText(value, seen)+ return+ }+if (Array.isArray(value)) {- for (const item of value) collectStructuredUris(item, seen)+ const parentKey = path[path.length - 1]+ if (isUriArrayKey(parentKey)) {+ for (const item of value) {+ if (typeof item !== 'string') continue+ const uri = cleanVikingUri(item)+ if (uri) seen.add(uri)+ }+ return+ }++ for (const item of value) collectStructuredUris(item, seen, path)return}if (!value || typeof value !== 'object') returnfor (const [key, nested] of Object.entries(value)) {- if (key === 'uri' && typeof nested === 'string') {+ if (isUriScalarKey(key) && typeof nested === 'string') {const uri = cleanVikingUri(nested)if (uri) seen.add(uri)continue}if (Array.isArray(nested) || (nested && typeof nested === 'object')) {- collectStructuredUris(nested, seen)+ collectStructuredUris(nested, seen, [...path, key])+ continue}++ if (typeof nested === 'string') {+ collectUrisFromText(nested, seen)+ }+ }+}++function collectUrisFromText(text: string, seen: Set<string>): void {+ const matches = text.match(VIKING_URI_RE) ?? []+ for (const match of matches) {+ const uri = cleanVikingUri(match)+ if (uri) seen.add(uri)}}++function collectMemoryBlockUrisFromText(text: string, seen: Set<string>): void {+ const memoryBlocks = text.match(/<memory\b[\s\S]*?<\/memory>/g) ?? []+ for (const block of memoryBlocks) {+ const uriMatch = block.match(/<uri>([\s\S]*?)<\/uri>/)+ if (!uriMatch) continue+ const uri = cleanVikingUri(uriMatch[1])+ if (uri) seen.add(uri)+ }+}++function isUriScalarKey(key: string): boolean {+ if (key === 'target_uri') return false+ return key === 'uri' || key.endsWith('_uri')+}++function isUriArrayKey(key: string | undefined): boolean {+ return Boolean(key && (key === 'uris' || key.endsWith('_uris')))+}diff --git a/web-studio/src/routes/settings/-lib/admin.ts b/web-studio/src/routes/settings/-lib/admin.tsindex 7aba35b92..b6ae5d879 100644--- a/web-studio/src/routes/settings/-lib/admin.ts+++ b/web-studio/src/routes/settings/-lib/admin.ts@@ -85,7 +85,7 @@ function setOptionalHeader(function createAdminClient(connection: AdminConnection) {const headers: Record<string, string> = {Accept: 'application/json',- 'X-OpenViking-Agent': connection.agentId.trim() || 'web-studio',+ 'X-OpenViking-Agent': connection.agentId.trim() || 'web-playground',}setOptionalHeader(headers, 'X-API-Key', connection.apiKey)setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsxindex d65ddde0a..d9bc1ea4d 100644--- a/web-studio/src/routes/settings/route.tsx+++ b/web-studio/src/routes/settings/route.tsx@@ -533,7 +533,7 @@ function SettingsRoute() {const adminConnection = React.useMemo<AdminConnection>(() => ({accountId: draft.accountId || DEFAULT_ACCOUNT_ID,- agentId: draft.agentId || 'web-studio',+ agentId: draft.agentId || 'web-playground',apiKey: draft.apiKey,baseUrl: draft.baseUrl,userId: draft.userId || DEFAULT_USER_ID,diff --git a/web-studio/src/styles.css b/web-studio/src/styles.cssindex 90f333882..006b6886b 100644--- a/web-studio/src/styles.css+++ b/web-studio/src/styles.css@@ -176,12 +176,12 @@hide internal scrollbars — iOS/Atlas pattern is overlay scroll onlyon active gesture, not a persistent track. */@media (max-width: 767px) {- .web-studio-resource-fs ::-webkit-scrollbar {+ .web-playground-resource-fs ::-webkit-scrollbar {width: 0;height: 0;background: transparent;}- .web-studio-resource-fs * {+ .web-playground-resource-fs * {scrollbar-width: none;}}@@ -193,7 +193,7 @@page-level scrollbar, and the inner panes already overlay-scroll ongesture. */@media (display-mode: standalone) {- body:has(.web-studio-resource-fs)+ body:has(.web-playground-resource-fs)[data-slot='scroll-area-scrollbar'][data-orientation='vertical'] {display: none;}