Skip to content

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

feat(web-studio): workspace-first setup and dual-provider experience (#6066)

leowldbd26e83b277d
diff --git a/docs/images/studio-workspace-setup.gif b/docs/images/studio-workspace-setup.gif
new file mode 100644
index 000000000..f9196edd3
Binary files /dev/null and b/docs/images/studio-workspace-setup.gif differ
diff --git a/web-studio/docs/api-contract-audit-evidence.json b/web-studio/docs/api-contract-audit-evidence.json
new file mode 100644
index 000000000..8bb215b8d
--- /dev/null
+++ b/web-studio/docs/api-contract-audit-evidence.json
@@ -0,0 +1,82 @@
+{
+ "date": "2026-10-02",
+ "source_commit": "1394d4769a34058dcd64bd9afcf917d3cae7ab54",
+ "source_declarations": 179,
+ "source_method_path_combinations": 181,
+ "source_schema_paths": 127,
+ "source_schema_operations": 168,
+ "original_snapshots_refreshed": 52,
+ "original_unique_urls": 48,
+ "changed_original_snapshots": [],
+ "incomplete_original_snapshots": [],
+ "newly_documented_operations": [
+ {
+ "method": "POST",
+ "path": "/api/v1/skills/find",
+ "url": "https://docs.volcengine.com/docs/84313/2600959",
+ "runtime_verified": false
+ },
+ {
+ "method": "POST",
+ "path": "/api/v1/skills/validate",
+ "url": "https://docs.volcengine.com/docs/84313/2600960",
+ "runtime_verified": false
+ },
+ {
+ "method": "PUT",
+ "path": "/api/v1/skills/{skill_name}",
+ "url": "https://docs.volcengine.com/docs/84313/2600963",
+ "runtime_verified": false
+ },
+ {
+ "method": "DELETE",
+ "path": "/api/v1/skills/{skill_name}",
+ "url": "https://docs.volcengine.com/docs/84313/2600964",
+ "runtime_verified": false
+ },
+ {
+ "method": "TOP",
+ "path": "DeleteOpenVikingAccount",
+ "url": "https://docs.volcengine.com/docs/84313/2693669",
+ "runtime_verified": false
+ }
+ ],
+ "documentation_url": "https://www.feishu.cn/docx/TEFYdLRGHowqHcxfnrscJd6OnUh",
+ "feishu_readback": {
+ "TEFYdLRGHowqHcxfnrscJd6OnUh": {
+ "verified": true,
+ "chars": 16020,
+ "isError": null
+ },
+ "QSGidE7Z7oPciyxlZMYcUyoRnye": {
+ "verified": true,
+ "chars": 28161,
+ "isError": null
+ },
+ "Kj91dgb78olE3OxGNSRcbLH0npg": {
+ "verified": true,
+ "chars": 61115,
+ "isError": null
+ },
+ "AJLqdk7AfoaB7Uxwufxc9aANnrb": {
+ "verified": true,
+ "chars": 95906,
+ "isError": null
+ },
+ "EuuzdvO1mo4nsdxFU9UcEHqFnKN": {
+ "verified": true,
+ "chars": 80542,
+ "isError": null
+ },
+ "XTObd2zfvotg0zxXzvNcVXT8nQd": {
+ "verified": true,
+ "chars": 64926,
+ "isError": null
+ },
+ "XY1Cdkd27oxZy0x0ZY9cgLHonfe": {
+ "verified": true,
+ "chars": 101876,
+ "isError": null
+ }
+ }
+}
diff --git a/web-studio/docs/api-contract-audit.md b/web-studio/docs/api-contract-audit.md
new file mode 100644
index 000000000..7921317eb
--- /dev/null
+++ b/web-studio/docs/api-contract-audit.md
@@ -0,0 +1,158 @@
+# Web Studio 双版本接口核对与补充
+
+核对日期:2026-10-02。开源服务基准:main `1394d4769a34058dcd64bd9afcf917d3cae7ab54`;该基准保留为历史 API 快照;当前 Studio 实现说明更新于 2026-10-14。云端依据仅为火山官方文档,未采用其他前端项目的内部 Action/IDL。
+
+## 核对结论
+
+原接口调研需要补充,不能直接认定为全量契约和全量兼容。
+
+- 原开源清单包含 179 个路由声明,展开为 181 个方法/路径组合;默认 FastAPI schema 为 127 个路径、168 个操作。源码与该基准一致,未发现新增服务端路由漏入清单。声明、schema、普通用户可访问接口的数量是三个不同口径。
+- 重新完整读取原来的 52 个官方文档快照(去重后 48 个 URL),正文均未变化。另确认 5 个漏入原对照的公开接口,见下表。官方 API 概览未列出所有技能接口,仅看概览会漏项。
+- 技能列表与详情此前已在 Studio 补充报告确认,但未同步到最早的覆盖附录。因此原主覆盖表需要修正 7 项:5 个新发现漏项,加 2 个已有补充未同步项。
+- “公开契约存在”“目标实例曾实测成功”“当前前端已经适配”应分别标注。本次不使用真实凭证执行写入、校验或删除;先前实例证据来自 admin Key,不能外推普通 User、其他版本或其他实例。
+
+## 应修正的完整覆盖表
+
+以下修正取代原表中对应接口的“未确认”描述。公开存在不表示已经运行验证。
+
+| 开源接口 / 云管理能力 | 火山官方契约 | 当前 Studio 使用情况 |
+|---|---|---|
+| GET /api/v1/skills | [get_skills](https://docs.volcengine.com/docs/84313/2600958),User Key、同路径 | 已用于技能页列表及开源 Compile 技能选择;此前已补充,原附录未同步 |
+| GET /api/v1/skills/{skill_name} | [get_skill](https://docs.volcengine.com/docs/84313/2600962),User Key、同路径 | 已用于技能详情;此前已补充,原附录未同步 |
+| POST /api/v1/skills/find | [find_skills](https://docs.volcengine.com/docs/84313/2600959),User Key、同路径 | 未发现现有页面调用;现有通用检索使用 /search/find,不等同于此接口 |
+| POST /api/v1/skills/validate | [validate_skill](https://docs.volcengine.com/docs/84313/2600960),User Key、同路径 | 未发现现有页面调用 |
+| PUT /api/v1/skills/{skill_name} | [update_skill](https://docs.volcengine.com/docs/84313/2600963),User Key、同路径 | 未发现现有页面调用;文件正文编辑不是完整技能替换 |
+| DELETE /api/v1/skills/{skill_name} | [delete_skill](https://docs.volcengine.com/docs/84313/2600964),User Key、同路径 | 未发现现有页面调用;通用文件删除不能代替带隐私清理的技能删除 |
+| DELETE /api/v1/admin/accounts/{account_id} | [DeleteOpenVikingAccount](https://docs.volcengine.com/docs/84313/2693669),企业版、AK/SK TOP 管理面 | 开源管理页已有删除调用;云端管理页当前隐藏,不应沿用 User Key |
+
+## 新增接口的参数与返回值对照
+
+### 技能搜索
+
+| 参数 | 开源 | 火山公开契约 |
+|---|---|---|
+| query | Body string,必填 | 同名、必填 |
+| limit | integer,默认 10 | 同名、默认 10;每个作用域的上限 |
+| score_threshold | float/null,默认 null | 同名、默认 null |
+| level | integer[]/null,默认 null | array/null,默认 null |
+| telemetry | bool/object,默认 false | bool/object,默认 false |
+| target_uri | string/null,默认 null | 同名、默认 null;指定单一根 |
+
+返回封装都是 status/result,可选 telemetry。result 包含 skills[]、total;指定根时返回 root_uri,默认两范围时返回 root_uris。命中条目可含 name、uri、description、score、match_reason、level、abstract、tags、allowed_tools 等。
+
+**明确差异:**开源 `skills.py` 将两范围结果排序后裁剪至 limit;火山文章明确默认两范围各执行 limit,合并后不再次裁剪,total 最多可达 2×limit。前端不能假设返回数不超过 limit,应显式传 target_uri 或按产品要求裁剪。列表/命中总数都不是跨页全量总数。
+
+### 技能校验
+
+| 参数 | 开源 | 火山公开契约 |
+|---|---|---|
+| data | Any,必填 | string/object,必填;SKILL.md 或结构化技能 |
+| strict | bool,默认 false | 同名、默认 false |
+| source_path | string/null,默认 null | 同名、仅回显定位来源 |
+| skill_dir_name | string/null,默认 null | 同名、校验目录名与 name |
+| target_uri | string/null,默认 null | 接收但校验逻辑不使用,不改变规则 |
+
+返回 result.valid、strict、name、description、tags、allowed_tools、body_lines、source_path、skill_dir_name、errors[]、warnings[];错误/警告条目有 rule、message、可选 field。源端通过技能验证服务返回该对象,字段按结果可选。
+
+**不能只检查 HTTP 200 或 status=ok:**结构合法但技能业务校验不通过时仍可成功响应,必须检查 result.valid。CLI 的 skills validate 是本地校验,与这个 HTTP 接口不能混为一谈。
+
+### 技能更新
+
+| 参数 | 开源 | 火山公开契约 |
+|---|---|---|
+| skill_name | Path string,必填 | 同名、必填,须与新内容的 name 一致 |
+| data | Any,可选 | string/object,和 temp_file_id 条件必选 |
+| temp_file_id | string/null,默认 null | 同名;同时传 data 时优先使用临时文件 |
+| from_source | bool,默认 false;与 data/temp_file_id 互斥 | 参数表未描述,不能推定支持从原来源更新 |
+| wait | bool,默认 false | 同名;是否等待语义和索引处理 |
+| timeout | float/null,默认 null | 同名;wait=true 生效,单位秒 |
+| source_metadata | object/null,默认 null | object,可自动生成 |
+| telemetry | bool/object,默认 false | 同名、默认 false |
+| target_uri | string/null,默认 null | 同名;不传先查私有根,再查共享根 |
+
+返回对象可包含 status、action=update、root_uri、uri、name、auxiliary_files;异步路径返回 task_id,等待路径可返回 queue_status。开源也可能带其他处理或清理信息,不能把生成 schema 的 result:any 当成字段完全一致的证明。
+
+两端都是**整体替换**而非局部 patch;新内容没有的旧辅助文件不会保留。恢复/回滚与异步任务语义需要独立处理,不能把 200 视为索引已经完成。
+
+### 技能删除
+
+| 参数 | 开源 | 火山公开契约 |
+|---|---|---|
+| skill_name | Path string,必填 | 同名、必填 |
+| target_uri | Query string/null,默认 null | 同名、默认 null;同名跨作用域时应显式传入 |
+
+两端结果都可有 name、uri、root_uri、privacy_deleted,底层能估算时有 estimated_deleted_count。删除包含技能目录及对应隐私配置,不等同于单独 DELETE /fs。无 target_uri 时优先匹配私有范围,再匹配共享范围。
+
+### 企业版数据空间删除
+
+| 比较项 | 开源管理 API | 火山公开 TOP API |
+|---|---|---|
+| 调用 | DELETE /api/v1/admin/accounts/{account_id} | POST TOP、Version=2025-06-09;删除 Action 需见下方文档冲突 |
+| 鉴权 | ROOT | AK/SK、企业版及删除权限;User Key 不可替代 |
+| 目标参数 | Path account_id | Body ResourceID、OpenVikingAccountID,均为 string、必填;没有同名自动映射 |
+| 成功响应 | HTTP 202,status/result;当前删除服务返回 status=deleting、task_id 等,需跟踪后台清理 | ResponseMetadata/Result,Result.Success 为 bool;未定义开源同样的任务字段 |
+| 对象边界 | 服务内部 Account | 指定云库 ResourceID 下的数据空间;不是整个云库 |
+
+**官方文档存在冲突:**标题、文字、请求示例和响应示例均为 DeleteOpenVikingAccount,但“请求接口”表把 Action 写成 CreateOpenVikingAccount。本表记录原文冲突,不能把创建 Action 当删除接口;实际管理集成前应确认服务端正确 Action。默认空间 default 禁止删除,删除是级联操作。此次没有发出删除请求。
+
+## 已有补充还需明确的差异
+
+| 能力 | 已确认的边界 | 对 Studio 的要求 |
+|---|---|---|
+| 技能列表 | 火山文档说 node_limit 虽被接收,底层仍每范围固定最多 1000;源端将 node_limit 传给底层。两端都可能有私有/共享同名技能 | 用 URI 而非 name 区分对象,不将 node_limit 当可靠分页 |
+| 目录分页 | 源端有 offset/has_more;官方云文档未保证这两个字段。先前实例接受 offset/limit,但未提供可靠 has_more | 页大小不代表读完全部;不能遇到缺少 has_more 就默认为全量 |
+| 任务列表 | 源端普通模式与云文档都为 Task[];只有源端 pagination=cursor 模式才是 {items,has_more,next_cursor} | 当前普通任务页请求普通模式,能兼容数组;不能据此认为 Compile 游标模式兼容 |
+| 高级检索 | 源端 HTTP 字段是 session_id;云 search 主表写 session,其他说明使用 session_id | 不把文档冲突说成已证实的线上差异;须有带真实会话的联调样本 |
+| 配置 | Session 配置、User 默认记忆策略、Account 模板、实例配置分别属于不同对象和授权面 | Session 配置公开不意味着 User Key 能编辑管理配置;现阶段云管理仍隐藏 |
+| 身份与服务识别 | Key 确认身份与判断部署类型是两件事;默认健康字段和版本号不是稳定 provider 标识 | 官方域名可自动识别;自定义域名保留选择。不开启任意跨用户 Header 切换 |
+
+## 当前实现逐功能核对
+
+| 功能 | 当前完成状态 | 未完成或证据边界 |
+|---|---|---|
+| 鉴权 | 火山按官方契约使用 Authorization: Bearer;开源保留 X-API-Key;健康检查、基础请求、权限及扩展探测保持一致 | 官方域名自动识别,自定义火山代理需明确选择服务类型;真实普通 User 仍待联调 |
+| 连接与个人目录身份 | 已在数据 health 返回后同步用户;管理验证不会阻塞数据身份;失败可重新连接 | 自动检测先匹配火山官方域名,其余 HTTP(S) 地址默认开源;自定义火山代理需手动选择。普通 User 的真实实例权限仍未补测 |
+| 我的目录与记忆 | 两种服务复用原 user/resources/agent 命名空间目录树与正文预览;仅接口不兼容的操作按版本限制 | 树状浏览已提供;单次列表最多 500 项,没有可靠的全量游标,不能声称目录完整 |
+| 文件详情、摘要、原文和下载 | 已复用正文预览;两种服务共用文本编辑入口;云端导入和权限管理仍受门禁,保存失败保留编辑内容并显示错误 | 非文本样本、不同权限及版本待测;当前实例扩展读取成功不是稳定公开契约 |
+| 技能列表与详情 | 现有页面使用上述公开读接口,详情显式带 target_uri;两种服务的技能与检索详情均可跳转原文件系统 | 搜索、校验、完整替换、专用删除未接入;这不是当前功能范围的必需项 |
+| 检索 | 复用 find/grep/glob/search;结果有归一化 | 高级参数仍直接透传,未逐参数按 provider 隔离;带 session 的 search 待确认 |
+| 会话基础记录 | 保留列表/详情/context;云端已隐藏 Bot Composer | 火山不请求未确认的 archives;界面明确只展示当前上下文消息,尚未展示历史归档或其摘要 |
+| 会话记忆影响 | 开源保留入口,火山隐藏 | 依赖会话 user.user_id、归档编号和 memory_diff.json;火山不宣称支持 |
+| 任务列表与状态 | 普通数组接口;Task 详情请求 include_events | 当前列表最多取 200,分页是本地切片;include_events 不在云公开参数表中,需兼容缺失 |
+| 任务重试 | 当前仍显示已有重试动作 | URL 资源重试已改为 {path,reason},并检查业务响应后提示成功;真实写入及不同任务类型重试仍需实例验证 |
+| Watches | 云端按列表响应结构探测后展示;修改、触发、删除按钮隐藏 | 历史使用公开任务读取;有真实历史样本前不保证完整语义 |
+| 监控与日志 | 云端按无副作用 GET 的结构与错误分类启用 | 当前实例监控曾通过、audit 曾 ApiBlocked;不能按全局角色或单次 200 开放全部面板 |
+| 首页统计、Bot、Compile、经验分析 | 云端日常导航与深链接已阻止使用开源扩展页面 | 当前实例存在路径/响应或网关不兼容证据;其他实例是否提供这些扩展未知 |
+| 管理及跨设备授权 | 云端隐藏原生管理与 OAuth;开源独立管理凭证控制入口 | 未开发 TOP 管理适配器;不能在浏览器里沿用 User Key 调这些 Action |
+
+## 后续开发顺序
+
+1. 使用真实普通 User Key 验证 Bearer 鉴权、私有目录、共享权限和会话隔离;不以管理员 Key 的结果代替。
+2. 现有目录 500 条和任务 200 条提示已存在;后续增加目录全量浏览,需要全量任务时分 provider 处理游标。
+3. 用普通 User、非空目录、已提交会话和真实异步任务补只读联调;高级检索按参数和模式核对。
+4. 需要技能写操作时再接入上表中的专用接口;TOP 管理作为独立后续能力。
+
+本次完成的是源码、文档和调用契约核对,不是对所有公开接口重新执行端到端测试。不存在“全部云 API 已实测兼容”的结论。仅从公开检索没有定位到某扩展契约,仍保留“未确认”,不改成“不存在”。
+
+## 原文档与代码依据
+
+- [原 API 对照主文档](https://www.feishu.cn/docx/QSGidE7Z7oPciyxlZMYcUyoRnye)
+- [原 Studio 兼容性与实例验证报告](https://www.feishu.cn/docx/XY1Cdkd27oxZy0x0ZY9cgLHonfe)
+- [开源技能路由与请求模型](https://github.com/volcengine/OpenViking/blob/1394d4769a34058dcd64bd9afcf917d3cae7ab54/openviking/server/routers/skills.py)
+- [开源资源请求模型](https://github.com/volcengine/OpenViking/blob/1394d4769a34058dcd64bd9afcf917d3cae7ab54/openviking/server/routers/resources.py)
+- [开源管理删除路由](https://github.com/volcengine/OpenViking/blob/1394d4769a34058dcd64bd9afcf917d3cae7ab54/openviking/server/routers/admin.py)、[删除任务结果](https://github.com/volcengine/OpenViking/blob/1394d4769a34058dcd64bd9afcf917d3cae7ab54/openviking/service/deletion.py)
+- [开源任务列表两种返回模式](https://github.com/volcengine/OpenViking/blob/1394d4769a34058dcd64bd9afcf917d3cae7ab54/openviking/server/routers/tasks.py)
+
+
+## 2026-10-13 UI 范围收敛(覆盖此前导航方案)
+
+当前目标为同一套 Web Studio 兼容两种 API Key,整体 UI 保持最新 main。取消此前的全局功能域切换和独立“我的目录”页;在原页面内部按接口支持范围控制 Tab和动作。文件系统复用原目录树与预览,开源保留 Agent/终端,火山使用相同命名空间目录树和文本预览/编辑,不增加个人/共享 Tab。原侧栏分组、页面布局和开源首页恢复。管理、Gateway和启动配置保留 Provider与权限门禁。
+
+接口鉴权、实例识别、数据/管理凭证隔离和既有契约差异继续有效;本节仅收敛 UI方案,不扩大云端接口兼容声明。详情见 [当前兼容与 UI范围](./main-update-compatibility-2026-10-13.md)。
+
+## 2026-10-14 审查修复
+
+- Gateway 接入最新 main `b8ec9d8210ab5eba3f235c5cf42a3a247223934c` 的 `/gateway/admin/*`、`/access` 和独立管理密钥。开源普通用户与开发模式可进入;对象修改和代他人签发权限由 `/access` 决定。火山连接继续拦截;开源 trusted 可查询访问状态并展示服务端不兼容说明,运行时仍拒绝 trusted。独立 Gateway /studio 宿主识别与专用连接页面保持主干行为。
+- 配置切换、身份切换和组件卸载后取消旧聊天流;每次持久化前再次检查连接,禁止旧消息写入新配置。
+- 火山定时同步保留只读历史查询,写操作继续关闭。
+- 火山 [content/write](https://docs.volcengine.com/docs/84313/2487451) 已有公开契约,恢复原文本编辑入口和同一保存流程;资源 ACL 由服务端校验。读取仍受 10000 行上限约束,未完整读取的正文不能直接覆盖保存。真实云端临时资源写入验证与普通用户权限验证应单独记录,不能由公开契约或 Mock 通过推断已完成。
diff --git a/web-studio/docs/main-update-compatibility-2026-10-13.md b/web-studio/docs/main-update-compatibility-2026-10-13.md
new file mode 100644
index 000000000..2a21ecfd0
--- /dev/null
+++ b/web-studio/docs/main-update-compatibility-2026-10-13.md
@@ -0,0 +1,54 @@
+# Web Studio 双版本兼容与 UI 范围
+
+历史核对日期:2026-10-13,主干基准:`d41cd6db1`。2026-10-14 已合并 `origin/main`(`b8ec9d821`),包含 Gateway 独立宿主与嵌入式管理入口。功能改动位于 `web-studio/`,并复用主干 Gateway URL 校验测试数据。已使用真实火山配置进行 Chrome 读取联调。
+
+## 界面原则
+
+目标是在同一套 Web Studio 中使用开源或火山引擎 API Key。保持最新 main 的侧栏、页面名称、布局和已有操作,只按接口契约与权限显示功能。耦合模块通过页面内的 Tab 隔离,不重新划分整套产品导航。
+
+- 移除“工作区/高级功能/管理”顶部全局切换。
+- 保留 main 的工作区、运维侧栏分组和菜单名称;开源连接保留原有导航。
+- 移除独立“我的目录”页面;旧 `/directory` 地址跳转到 `/filesystem`,旧记忆地址仍定位对应目录。
+- 文件系统统一使用原有目录树、文件预览、搜索及拖拽布局;个人与共享命名空间直接来自根目录接口,不增加云端专属 Tab。开源保留 Agent/终端 Tab;云端不挂载本地 Bot、终端与未适配写操作。
+- 开源默认进入原首页;火山默认进入文件系统。不因 Key 不同更换整体 UI。
+- 恢复任务页统计及会话、监控页面原有布局;保留接口参数修正、缺字段容错和云端操作限制。
+
+## 功能与授权
+
+连接设置支持保存多份配置。添加时填写名称,选择开源服务或火山托管,并保存对应地址及 API Key。火山连接身份由服务端验证返回,添加时无需填写账号和用户;开源配置仍支持 trusted 模式所需的身份输入。新增配置保存后需点击“启用”才生效;编辑已启用配置后,保存会重新连接。删除当前配置前需先启用另一份配置。
+
+配置保存在当前浏览器中;旧连接自动迁移为默认配置。启用时切换整套凭证、重新验证服务,并清除旧查询缓存;下次打开仍使用已启用的配置。配置列表不展示 Key。
+
+火山官方域名的配置统一显示为火山托管,类型标记与鉴权方式保持一致。添加弹窗和连接详情共用地址校验,无效地址不会覆盖当前连接。启用、保存或重新连接后,尚未完成的旧身份切换请求不再回写配置。
+
+| 模块 | 开源 API Key | 火山 API Key |
+|---|---|---|
+| 文件浏览、预览、检索、技能 | 原有界面和操作 | 使用已对齐读取接口;检索与技能详情可跳转文件系统;文本预览与编辑复用原入口;写入由资源 ACL 校验 |
+| 文件系统 Agent/终端 Tab、VikingBot、Compile、经验分析 | 保留 | 不展示、不挂载未适配模块 |
+| 会话 | 原列表、聊天、历史与记忆影响 | 现有上下文记录;不请求未确认的归档接口,不挂载 Bot 输入与记忆影响 |
+| 任务 | 原表格和统计;重试 URL 参数修正为 path | 已适配数组列表;不假定 include_events、游标和缺省字段一致 |
+| Watches、日志、监控 | 保留原功能 | 按读取响应能力启用;Watches 写操作隐藏 |
+| 用户管理、OAuth | 原有管理凭证与角色判断 | 原生管理与 OAuth 隐藏;数据 Key 不授予管理能力 |
+| Gateway | 开源服务可查询 /gateway/admin/access;trusted 仅展示服务端不兼容说明,实际权限由响应决定 | 隐藏导航、拦截深链接与请求 |
+| 启动配置与重启 | ROOT 专属;文件可写及重启能力由响应决定 | 隐藏配置 Tab,不挂载编辑器,不调用开源配置接口 |
+
+Gateway 运行时仍拒绝 trusted 身份模式。Studio 与主干一致,允许开源 trusted 连接进入网关页查询 /gateway/admin/access,并展示服务端的不兼容说明,不授予数据或写入权限。独立 Gateway 的 /studio 入口先无凭证识别宿主,不转发其他配置中保存的 Key;仅显示网关与连接设置。独立管理密钥仅发送到 Gateway 管理接口。
+
+开源启动配置读、预览、保存和重启共享同一授权限制;连接或授权变化时返回连接 Tab并卸载编辑器。云库模型配置属于 AK/SK 管理面,不能复用 User Key或 ov.conf 文件编辑器。
+
+## 接口边界
+
+- 火山使用 Authorization: Bearer;开源使用 X-API-Key。Provider 识别与角色判断分开,Key不跨授权面回退。[云端鉴权](https://docs.volcengine.com/docs/vector_database_vikingdb/APIAuthenticationInstructions?lang=zh)
+- 云库模型信息公开接口为 GetOpenVikingCollection,需要 AK/SK和 ResourceID,并非 ov.conf 的文件版本、预览及重启协议。[库详情](https://docs.volcengine.com/docs/84313/2685089)
+- Working Memory 保留版本差异:开源预设默认关闭,云端创建会话文档仍写默认开启。当前提交调用不透传新 enable_working_memory 参数。[创建会话](https://docs.volcengine.com/docs/84313/2487445)、[提交会话](https://docs.volcengine.com/docs/84313/2487441)
+- 上述云端判断来自公开契约;此前 admin Key成功样本不能证明普通 User隔离或所有实例能力。[原接口审计](./api-contract-audit.md)
+
+## 验证范围
+
+回归开源原有页面、云端文件树和只读预览、统一命名空间目录树、详情跳转、旧链接、Key及连接切换、Gateway深链接、启动配置挂载和请求限制。模拟服务验证请求头与请求范围;真实 Chrome 验证配置保存、启用与刷新,文件树、Markdown 预览与源码、find/search/grep/glob、技能列表、会话列表与当前上下文、任务列表与详情、定时同步、监控六个组件及管理/未兼容页面深链接限制。服务端版本为 v0.4.20.6,身份为 default/wulv;身份标签仅使用 health 响应,未确认时不显示配置默认值。
+
+技能与定时同步为空。初次任务列表包含两条历史失败记录,抽查资源处理任务详情返回 Task not found or expired;再次刷新列表为空。未触发任务重试或删除。未验证线上写操作、普通 User间的权限隔离或本实例未开放的扩展接口。
+
+2026-10-14:目录树与文本编辑保持两种服务 UI 一致;定时同步历史读取不再被写操作门禁隐藏。Gateway 同步最新 main 的嵌入式管理契约与权限 UI。
+
+本轮验证:1026 个单元/组件测试通过,生产构建及改动文件 lint 通过。类型检查仍有仓库已有诊断,本轮未新增。Chrome 验证火山原有目录树、完整原文进入文本编辑器并取消、定时同步页面;目标实例没有定时同步记录,非空历史入口由组件测试验证。真实现有资源未执行保存,云端写入 ACL 与异步结果仍未作为端到端验证通过。
diff --git a/web-studio/src/components/account-switcher.gateway.test.tsx b/web-studio/src/components/account-switcher.gateway.test.tsx
index 3d89ddc6d..517ca5aa4 100644
--- a/web-studio/src/components/account-switcher.gateway.test.tsx
+++ b/web-studio/src/components/account-switcher.gateway.test.tsx
@@ -7,17 +7,26 @@ import {
waitFor,
} from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import type { ReactNode } from 'react'
import { afterEach, expect, it, vi } from 'vitest'
+import type { ConnectionProfile } from '#/lib/connection/profiles'
import { AccountSwitcher } from './account-switcher'
-const { fetchAccounts, fetchUsers, switchAccount, switchIdentity } = vi.hoisted(
- () => ({
- fetchAccounts: vi.fn(),
- fetchUsers: vi.fn(),
- switchAccount: vi.fn(),
- switchIdentity: vi.fn(),
- }),
-)
+const {
+ fetchAccounts,
+ fetchUsers,
+ switchAccount,
+ switchIdentity,
+ activateProfile,
+ savedProfileState,
+} = vi.hoisted(() => ({
+ fetchAccounts: vi.fn(),
+ fetchUsers: vi.fn(),
+ switchAccount: vi.fn(),
+ switchIdentity: vi.fn(),
+ activateProfile: vi.fn(),
+ savedProfileState: { profiles: [] as Array<ConnectionProfile> },
+}))
vi.mock('#/lib/admin', () => ({
fetchAdminAccounts: fetchAccounts,
fetchAdminUsers: fetchUsers,
@@ -25,6 +34,9 @@ vi.mock('#/lib/admin', () => ({
}))
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
+ profiles: savedProfileState.profiles,
+ activeProfileId: 'default',
+ activateProfile,
connection: {
accountId: 'default',
userId: 'root',
@@ -41,10 +53,33 @@ vi.mock('#/hooks/use-app-connection', () => ({
setGeneratedCredential: vi.fn(),
}),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ provider: 'opensource' }),
+}))
+vi.mock('@tanstack/react-router', () => ({
+ Link: ({
+ children,
+ to,
+ ...props
+ }: {
+ children: ReactNode
+ to: string
+ className?: string
+ onClick?: () => void
+ }) => (
+ <a href={to} {...props}>
+ {children}
+ </a>
+ ),
+}))
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}))
-afterEach(cleanup)
+afterEach(() => {
+ cleanup()
+ savedProfileState.profiles = []
+ vi.clearAllMocks()
+})
it('root selects an account through the read-only list without requesting user credentials or offering creation', async () => {
fetchAccounts.mockResolvedValue([
{ accountId: 'default', userCount: 1 },
@@ -74,3 +109,65 @@ it('root selects an account through the read-only list without requesting user c
expect(switchIdentity).not.toHaveBeenCalled()
client.clear()
})
+
+it('keeps saved connections and server account switching available to a gateway root', async () => {
+ savedProfileState.profiles = [
+ {
+ id: 'default',
+ name: 'Open-source default',
+ connection: {
+ accountId: 'default',
+ userId: 'root',
+ apiKey: 'root-login-key',
+ adminApiKey: '',
+ baseUrl: 'http://gateway.test',
+ serviceSelection: 'opensource',
+ },
+ },
+ {
+ id: 'hosted',
+ name: 'Hosted space',
+ connection: {
+ accountId: 'study',
+ userId: 'alice',
+ apiKey: 'hosted-key',
+ adminApiKey: '',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'volcengine',
+ },
+ },
+ ]
+ fetchAccounts.mockResolvedValue([
+ { accountId: 'default', userCount: 1 },
+ { accountId: 'team', userCount: 2 },
+ ])
+ switchAccount.mockResolvedValue(undefined)
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ render(
+ <QueryClientProvider client={client}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ expect(
+ screen.getByRole('button', { name: /Open-source default/ }),
+ ).toBeTruthy()
+ const hosted = screen.getByRole('button', { name: /Hosted space/ })
+ expect(
+ hosted.querySelector('[role="img"][aria-label="provider.hosted"]'),
+ ).toBeTruthy()
+ fireEvent.click(hosted)
+ expect(activateProfile).toHaveBeenCalledWith('hosted')
+ expect(switchAccount).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ await waitFor(() => expect(screen.getByText('team')).toBeTruthy())
+ fireEvent.click(screen.getByText('team'))
+ await waitFor(() => expect(switchAccount).toHaveBeenCalledWith('team'))
+ expect(fetchUsers).not.toHaveBeenCalled()
+ expect(switchIdentity).not.toHaveBeenCalled()
+ client.clear()
+})
diff --git a/web-studio/src/components/account-switcher.hosted.test.tsx b/web-studio/src/components/account-switcher.hosted.test.tsx
new file mode 100644
index 000000000..ec64e6003
--- /dev/null
+++ b/web-studio/src/components/account-switcher.hosted.test.tsx
@@ -0,0 +1,346 @@
+// @vitest-environment jsdom
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, expect, it, vi } from 'vitest'
+import { AccountSwitcher } from './account-switcher'
+
+const { activateProfile, activeState } = vi.hoisted(() => ({
+ activateProfile: vi.fn(),
+ activeState: {
+ provider: 'volcengine' as 'volcengine' | 'opensource',
+ profileId: 'study',
+ },
+}))
+
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ provider: activeState.provider }),
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({
+ connection:
+ activeState.provider === 'opensource'
+ ? {
+ accountId: 'work-memory',
+ userId: 'wangladi',
+ apiKey: 'opensource-key',
+ adminApiKey: '',
+ baseUrl: 'http://devbox.example:1933',
+ serviceSelection: 'opensource',
+ }
+ : {
+ accountId: 'study',
+ userId: 'default',
+ apiKey: 'study-key',
+ adminApiKey: '',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'volcengine',
+ },
+ profiles: [
+ {
+ id: 'study-copy',
+ name: 'Study copy',
+ connection: {
+ accountId: 'study',
+ userId: 'default',
+ apiKey: 'older-study-key',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'volcengine',
+ },
+ },
+ {
+ id: 'study-identical',
+ name: 'Study identical',
+ connection: {
+ accountId: 'study',
+ userId: 'default',
+ apiKey: 'study-key',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'volcengine',
+ },
+ },
+ {
+ id: 'study-same-name',
+ name: 'Study',
+ connection: {
+ accountId: 'study',
+ userId: 'default',
+ apiKey: 'third-study-key',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'volcengine',
+ },
+ },
+ {
+ id: 'study',
+ name: 'Study',
+ connection: {
+ accountId: 'study',
+ userId: 'default',
+ apiKey: 'study-key',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'volcengine',
+ },
+ },
+ {
+ id: 'study-alice',
+ name: 'Study Alice',
+ connection: {
+ accountId: 'study',
+ userId: 'alice',
+ apiKey: 'alice-key',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'volcengine',
+ },
+ },
+ {
+ id: 'default',
+ name: 'Default',
+ connection: {
+ accountId: 'default',
+ userId: 'default',
+ apiKey: 'default-key',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'volcengine',
+ },
+ },
+ {
+ id: 'unconfigured',
+ name: 'Unconfigured',
+ connection: {
+ accountId: 'other',
+ apiKey: '',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'volcengine',
+ },
+ },
+ {
+ id: 'opensource-memory',
+ name: 'Work memory',
+ connection: {
+ accountId: 'work-memory',
+ userId: 'wangladi',
+ apiKey: 'opensource-key',
+ baseUrl: 'http://devbox.example:1933',
+ serviceSelection: 'opensource',
+ },
+ },
+ {
+ id: 'opensource-duplicate',
+ name: 'Duplicate work memory',
+ connection: {
+ accountId: 'work-memory',
+ userId: 'wangladi',
+ apiKey: 'opensource-key',
+ baseUrl: 'http://devbox.example:1933',
+ serviceSelection: 'opensource',
+ },
+ },
+ {
+ id: 'opensource-shared-url',
+ name: 'Open-source shared URL',
+ connection: {
+ accountId: 'study',
+ userId: 'default',
+ apiKey: 'study-key',
+ baseUrl: 'https://hosted.example/openviking',
+ serviceSelection: 'opensource',
+ },
+ },
+ {
+ id: 'opensource-development',
+ name: 'Development server',
+ connection: {
+ accountId: 'default',
+ userId: 'default',
+ apiKey: '',
+ baseUrl: 'http://devbox.example:1934',
+ serviceSelection: 'opensource',
+ },
+ },
+ ],
+ activeProfileId: activeState.profileId,
+ activateProfile,
+ connectionRole: 'user',
+ isConnectionRoleLoading: false,
+ isGatewayHost: false,
+ serverMode: 'api_key',
+ }),
+}))
+vi.mock('@tanstack/react-router', () => ({
+ Link: ({
+ children,
+ to,
+ ...props
+ }: React.PropsWithChildren<{ to: string }>) => (
+ <a href={to} {...props}>
+ {children}
+ </a>
+ ),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+afterEach(() => {
+ cleanup()
+ activateProfile.mockClear()
+ activeState.provider = 'volcengine'
+ activeState.profileId = 'study'
+})
+
+it('keeps distinct keys and users selectable while deduplicating identical hosted connections', async () => {
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /study\/alice/ })).toBeTruthy(),
+ )
+ expect(
+ screen
+ .getAllByRole('button')
+ .filter(
+ (button) =>
+ button.getAttribute('data-slot') !== 'popover-trigger' &&
+ button.querySelector('[role="img"][aria-label="provider.hosted"]'),
+ ),
+ ).toHaveLength(6)
+ const otherKey = screen.getByRole('button', { name: /Study copy/ })
+ expect(otherKey).toBeTruthy()
+ expect(screen.queryByRole('button', { name: /Study identical/ })).toBeNull()
+ const selected = screen
+ .getAllByRole('button')
+ .find((button) => button.hasAttribute('aria-current'))
+ expect(selected?.getAttribute('aria-current')).toBe('true')
+ expect(selected?.textContent).toContain('study/default')
+ expect(selected?.textContent).toContain('Study')
+ expect(screen.getByRole('button', { name: /Unconfigured/ })).toBeTruthy()
+ fireEvent.click(otherKey)
+ expect(activateProfile).toHaveBeenCalledWith('study-copy')
+
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ fireEvent.click(screen.getByRole('button', { name: /study\/alice/ }))
+ expect(activateProfile).toHaveBeenCalledWith('study-alice')
+ client.clear()
+})
+
+it('lists saved open-source connections beside hosted connections without merging providers', async () => {
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+
+ const openSource = await screen.findByRole('button', {
+ name: /Work memory/,
+ })
+ expect(openSource).toBeTruthy()
+ expect(screen.queryByText('Duplicate work memory')).toBeNull()
+ expect(
+ screen
+ .getByRole('button', { name: /Open-source shared URL/ })
+ .querySelector('[role="img"][aria-label="provider.opensource"]'),
+ ).toBeTruthy()
+ expect(
+ screen.getByRole('button', { name: /Development server/ }),
+ ).toBeTruthy()
+ expect(screen.getByRole('button', { name: /study\/alice/ })).toBeTruthy()
+
+ fireEvent.click(openSource)
+ expect(activateProfile).toHaveBeenCalledWith('opensource-memory')
+
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ fireEvent.click(screen.getByRole('button', { name: /Development server/ }))
+ expect(activateProfile).toHaveBeenCalledWith('opensource-development')
+ client.clear()
+})
+
+it('opens the same saved connection list from an open-source profile without admin rights', async () => {
+ activeState.provider = 'opensource'
+ activeState.profileId = 'opensource-memory'
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ const selected = await screen.findByRole('button', { name: /Work memory/ })
+ expect(selected.getAttribute('aria-current')).toBe('true')
+ expect(screen.queryByText('Duplicate work memory')).toBeNull()
+ expect(screen.getByRole('button', { name: /study\/alice/ })).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: /study\/alice/ }))
+ expect(activateProfile).toHaveBeenCalledWith('study-alice')
+ client.clear()
+})
+
+it('distinguishes hosted connections with the same identity and profile name', async () => {
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+
+ const sameNamePattern = (name: string) =>
+ name.includes('study/default') &&
+ name.includes('Study') &&
+ !name.includes('Study copy') &&
+ !name.includes('Study identical')
+ const accessibleNames = new Set<string>()
+ const sameNameOptions = screen.getAllByRole('button', {
+ name: (name) => {
+ if (!sameNamePattern(name)) return false
+ accessibleNames.add(name)
+ return true
+ },
+ })
+ expect(sameNameOptions).toHaveLength(2)
+ expect(accessibleNames.size).toBe(2)
+
+ const otherKey = sameNameOptions.find(
+ (button) => button.getAttribute('aria-current') !== 'true',
+ )
+ expect(otherKey).toBeTruthy()
+ fireEvent.click(otherKey!)
+ expect(activateProfile).toHaveBeenCalledWith('study-same-name')
+
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ const active = screen
+ .getAllByRole('button', { name: sameNamePattern })
+ .find((button) => button.getAttribute('aria-current') === 'true')
+ expect(active).toBeTruthy()
+ fireEvent.click(active!)
+ expect(activateProfile).toHaveBeenCalledWith('study')
+ client.clear()
+})
+
+it('shows a single default for personal hosted connections', async () => {
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /\[default\]/ })).toBeTruthy(),
+ )
+ const hostedDefault = screen.getByRole('button', { name: /\[default\]/ })
+ expect(hostedDefault.textContent).not.toContain('default/default')
+ fireEvent.click(hostedDefault)
+ expect(activateProfile).toHaveBeenCalledWith('default')
+ client.clear()
+})
diff --git a/web-studio/src/components/account-switcher.stale.test.tsx b/web-studio/src/components/account-switcher.stale.test.tsx
new file mode 100644
index 000000000..9a13f8315
--- /dev/null
+++ b/web-studio/src/components/account-switcher.stale.test.tsx
@@ -0,0 +1,155 @@
+// @vitest-environment jsdom
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import type { ReactNode } from 'react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { AccountSwitcher } from './account-switcher'
+
+const { state, fetchAccounts, fetchUsers, switchIdentity } = vi.hoisted(() => ({
+ state: {
+ identityScopeKey: 'source',
+ connection: {
+ accountId: 'default',
+ userId: 'root',
+ apiKey: 'root-key',
+ adminApiKey: 'admin-key',
+ baseUrl: 'http://source.test',
+ serviceSelection: 'opensource' as const,
+ },
+ },
+ fetchAccounts: vi.fn(),
+ fetchUsers: vi.fn(),
+ switchIdentity: vi.fn(),
+}))
+
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({
+ ...state,
+ profiles: [],
+ activeProfileId: 'source',
+ activateProfile: vi.fn(),
+ connectionRole: 'root',
+ isGatewayHost: false,
+ isConnectionRoleLoading: false,
+ serverMode: 'api_key',
+ switchIdentity,
+ setGeneratedCredential: vi.fn(),
+ }),
+}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ provider: 'opensource' }),
+}))
+vi.mock('@tanstack/react-router', () => ({
+ Link: ({
+ children,
+ to,
+ ...props
+ }: {
+ children: ReactNode
+ to: string
+ className?: string
+ onClick?: () => void
+ }) => (
+ <a href={to} {...props}>
+ {children}
+ </a>
+ ),
+}))
+vi.mock('#/lib/admin', () => ({
+ fetchAdminAccounts: fetchAccounts,
+ fetchAdminUsers: fetchUsers,
+ createAdminAccount: vi.fn(),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+let queryClient: QueryClient
+beforeEach(() => {
+ state.identityScopeKey = 'source'
+ vi.clearAllMocks()
+ fetchAccounts.mockResolvedValue([
+ { accountId: 'default', userCount: 1 },
+ { accountId: 'team', userCount: 1 },
+ ])
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+})
+afterEach(() => {
+ cleanup()
+ queryClient.clear()
+})
+
+function renderSwitcher() {
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+}
+
+async function selectTeam() {
+ fireEvent.click(screen.getByText('default'))
+ await waitFor(() => expect(screen.getByText('team')).toBeTruthy())
+ fireEvent.click(screen.getByText('team'))
+ await waitFor(() => expect(fetchUsers).toHaveBeenCalledTimes(1))
+}
+
+const usersWithoutKeys = [
+ {
+ accountId: 'team',
+ userId: 'alice',
+ role: 'user',
+ keyPrefix: 'ovk_123',
+ },
+]
+
+it('does not open the manual key dialog when the profile changed during user lookup', async () => {
+ let finishUsers!: (users: typeof usersWithoutKeys) => void
+ fetchUsers.mockReturnValue(
+ new Promise((resolve) => {
+ finishUsers = resolve
+ }),
+ )
+ const view = renderSwitcher()
+ await selectTeam()
+
+ state.identityScopeKey = 'target'
+ view.rerender(
+ <QueryClientProvider client={queryClient}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+ await act(async () => finishUsers(usersWithoutKeys))
+
+ expect(screen.queryByText('manualSwitch.title')).toBeNull()
+ expect(switchIdentity).not.toHaveBeenCalled()
+})
+
+it('closes an already open manual key dialog when the identity scope changes', async () => {
+ fetchUsers.mockResolvedValue(usersWithoutKeys)
+ const view = renderSwitcher()
+ await selectTeam()
+ await waitFor(() =>
+ expect(screen.getByText('manualSwitch.title')).toBeTruthy(),
+ )
+
+ state.identityScopeKey = 'target'
+ view.rerender(
+ <QueryClientProvider client={queryClient}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+
+ await waitFor(() =>
+ expect(screen.queryByText('manualSwitch.title')).toBeNull(),
+ )
+})
diff --git a/web-studio/src/components/account-switcher.tsx b/web-studio/src/components/account-switcher.tsx
index a5a22479f..dec80c227 100644
--- a/web-studio/src/components/account-switcher.tsx
+++ b/web-studio/src/components/account-switcher.tsx
@@ -1,9 +1,11 @@
import * as React from 'react'
+import { Link } from '@tanstack/react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
Building2Icon,
CheckIcon,
ChevronDownIcon,
+ CodeXmlIcon,
LoaderCircleIcon,
PlusIcon,
SearchIcon,
@@ -26,6 +28,7 @@ import {
PopoverContent,
PopoverTrigger,
} from '#/components/ui/popover'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
import {
createAdminAccount,
@@ -38,7 +41,10 @@ import type {
CreateAccountInput,
} from '#/lib/admin'
import { DEFAULT_USER_ID } from '#/lib/admin-options'
+import { formatHostedIdentity } from '#/lib/connection/identity-label'
+import { connectionProfileFingerprint } from '#/lib/connection/profiles'
import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
+import { ovClient } from '#/lib/ov-client'
import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'
import { cn } from '#/lib/utils'
@@ -53,11 +59,83 @@ export function selectAccountUser(
return candidates[0]
}
+function currentRuntimeIdentity(): string {
+ const options = ovClient.getOptions()
+ const connection = ovClient.getConnection()
+ return JSON.stringify([
+ options.baseUrl,
+ options.apiKeyAuth,
+ connection.accountId,
+ connection.userId,
+ connection.apiKey,
+ connection.adminApiKey,
+ connection.identityHeaders,
+ ])
+}
+
+function ServiceIcon({ hosted }: { hosted: boolean }) {
+ const { t } = useTranslation('accountSwitcher')
+ const label = t(`provider.${hosted ? 'hosted' : 'opensource'}`)
+ return (
+ <span
+ title={label}
+ role="img"
+ aria-label={label}
+ className="inline-flex size-4 shrink-0 items-center justify-center text-sidebar-foreground/70"
+ >
+ {hosted ? (
+ <svg
+ viewBox="0 0 24 24"
+ className="size-3.5 opacity-60"
+ aria-hidden="true"
+ >
+ <g transform="translate(0.349 12.857)">
+ <path
+ d="M0 9.1584H6.34404L3.4718 0.221463C3.41951 0.0533704 3.23825 -0.0376799 3.07094 0.0148491C2.97333 0.0463665 2.89665 0.123409 2.86528 0.221463L0 9.1584Z"
+ fill="#00DCFF"
+ />
+ </g>
+ <g transform="translate(15.771 11.277)">
+ <path
+ d="M0 10.7483H7.36188L3.9842 0.221463C3.93191 0.0533704 3.75065 -0.03768 3.58334 0.0148491C3.48574 0.0463665 3.40905 0.123409 3.37768 0.221463L0 10.7483Z"
+ fill="#00DCFF"
+ />
+ </g>
+ <g transform="translate(7.012 1.716)">
+ <path
+ d="M0 20.3102H13.5804L7.09348 0.219641C7.03771 0.0515485 6.85993 -0.0395018 6.69262 0.0165291C6.59502 0.0480465 6.51833 0.125089 6.48696 0.219641L0 20.3102Z"
+ fill="#006AFF"
+ />
+ </g>
+ <g transform="translate(2.882 6.815)">
+ <path
+ d="M0.00348549 15.2114H10.2829L5.44472 0.219641C5.38895 0.0515482 5.21118 -0.0395018 5.04386 0.0165292C4.94626 0.0480466 4.86958 0.125089 4.83821 0.219641L0 15.2114H0.00348549Z"
+ fill="#006AFF"
+ />
+ </g>
+ <g transform="translate(5.736 9.355)">
+ <path
+ d="M0 12.6725H8.69343L4.64998 0.219641C4.5942 0.0515485 4.41643 -0.0395018 4.24912 0.0165291C4.15152 0.0480465 4.07832 0.125089 4.04694 0.219641L0.00348582 12.6725H0Z"
+ fill="#00DCFF"
+ />
+ </g>
+ </svg>
+ ) : (
+ <CodeXmlIcon className="size-4" strokeWidth={1.8} aria-hidden="true" />
+ )}
+ </span>
+ )
+}
+
export function AccountSwitcher() {
const { t } = useTranslation('accountSwitcher')
const queryClient = useQueryClient()
const {
connection,
+ profiles,
+ activeProfileId,
+ identityScopeKey,
+ activateProfile,
connectionRole,
isConnectionRoleLoading,
isGatewayHost,
@@ -75,12 +153,24 @@ export function AccountSwitcher() {
apiKey: string
userId: string
} | null>(null)
+ const latestIdentityScopeKey = React.useRef(identityScopeKey)
+ latestIdentityScopeKey.current = identityScopeKey
+ const previousIdentityScopeKey = React.useRef(identityScopeKey)
+ React.useLayoutEffect(() => {
+ if (previousIdentityScopeKey.current !== identityScopeKey) {
+ setManualSwitch(null)
+ setOpen(false)
+ }
+ previousIdentityScopeKey.current = identityScopeKey
+ }, [identityScopeKey])
const [createDraft, setCreateDraft] = React.useState<CreateAccountInput>({
accountId: '',
adminUserId: DEFAULT_USER_ID,
})
+ const { provider } = useStudioService()
const capabilities = resolveStudioManagementCapabilities({
+ serviceProvider: provider,
hasControlCredential: Boolean(connection.adminApiKey.trim()),
isRoleLoading: isConnectionRoleLoading,
role: connectionRole,
@@ -137,6 +227,17 @@ export function AccountSwitcher() {
return
}
+ const sourceIdentityScopeKey = identityScopeKey
+ const sourceRuntimeIdentity = currentRuntimeIdentity()
+ const assertCurrentIdentity = () => {
+ if (
+ latestIdentityScopeKey.current !== sourceIdentityScopeKey ||
+ currentRuntimeIdentity() !== sourceRuntimeIdentity
+ ) {
+ throw new Error(t('studio:profiles.connectionChanged'))
+ }
+ }
+
setSwitchingAccountId(accountId)
try {
if (isGatewayHost) {
@@ -146,6 +247,7 @@ export function AccountSwitcher() {
return
}
const users = await fetchAdminUsers(adminConnection, accountId)
+ assertCurrentIdentity()
const firstUser = selectAccountUser(users, connection.userId, false)
if (!firstUser) {
throw new Error(t('errors.noUsers'))
@@ -157,6 +259,7 @@ export function AccountSwitcher() {
: [firstUser]
let switchError: unknown
for (const user of candidates) {
+ assertCurrentIdentity()
try {
await switchIdentity({
accountId,
@@ -172,10 +275,21 @@ export function AccountSwitcher() {
)
return
} catch (error) {
+ // A profile change invalidates this entire selection, including
+ // retries with other users and the manual-key fallback.
+ if (
+ error &&
+ typeof error === 'object' &&
+ 'code' in error &&
+ error.code === 'connectionChanged'
+ ) {
+ throw error
+ }
switchError = error
}
}
+ assertCurrentIdentity()
if (serverMode === 'api_key') {
setOpen(false)
setManualSwitch({
@@ -240,32 +354,160 @@ export function AccountSwitcher() {
})
const accountLabel = connection.accountId || t('unset')
+ const seenProfiles = new Set<string>()
+ const savedProfiles = [...profiles]
+ .sort((a, b) =>
+ a.id === activeProfileId ? -1 : b.id === activeProfileId ? 1 : 0,
+ )
+ .filter((profile) => {
+ const key = connectionProfileFingerprint(profile.connection)
+ if (seenProfiles.has(key)) return false
+ seenProfiles.add(key)
+ return true
+ })
+ const identityFor = (profile: (typeof savedProfiles)[number]) =>
+ profile.connection.serviceSelection === 'volcengine'
+ ? formatHostedIdentity(
+ profile.connection.accountId,
+ profile.connection.userId,
+ )
+ : `${profile.connection.accountId}/${profile.connection.userId}`
+ const summaryFor = (profile: (typeof savedProfiles)[number]) =>
+ JSON.stringify([
+ profile.name,
+ profile.connection.serviceSelection,
+ identityFor(profile),
+ profile.connection.baseUrl.trim().replace(/\/+$/, ''),
+ ])
+ const summaryCounts = new Map<string, number>()
+ for (const profile of savedProfiles) {
+ const summary = summaryFor(profile)
+ summaryCounts.set(summary, (summaryCounts.get(summary) ?? 0) + 1)
+ }
+ const savedConnectionsMenu = (
+ <>
+ <div className="max-h-60 space-y-0.5 overflow-y-auto p-1.5">
+ {savedProfiles.map((profile) => {
+ const active = profile.id === activeProfileId
+ const identity = identityFor(profile)
+ const showProfileId =
+ (summaryCounts.get(summaryFor(profile)) ?? 0) > 1
+ return (
+ <button
+ key={profile.id}
+ type="button"
+ aria-current={active ? 'true' : undefined}
+ onClick={() => {
+ setOpen(false)
+ activateProfile(profile.id)
+ }}
+ className={cn(
+ 'flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ active && 'bg-accent/70',
+ )}
+ >
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-background text-xs font-semibold">
+ {profile.name.charAt(0).toUpperCase()}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="flex min-w-0 items-center gap-1">
+ <span className="min-w-0 truncate text-sm font-medium">
+ {profile.name}
+ </span>
+ <ServiceIcon
+ hosted={
+ profile.connection.serviceSelection === 'volcengine'
+ }
+ />
+ {showProfileId ? (
+ <span
+ className="shrink-0 font-mono text-[10px] text-muted-foreground"
+ title={profile.id}
+ >
+ #{profile.id.slice(0, 8)}
+ </span>
+ ) : null}
+ </span>
+ <span
+ className="block truncate text-xs text-muted-foreground"
+ title={`${identity ? `[${identity}] · ` : ''}${profile.connection.baseUrl}`}
+ >
+ {identity ? `[${identity}] · ` : null}
+ {profile.connection.baseUrl}
+ </span>
+ </span>
+ {active ? <CheckIcon className="size-3.5 shrink-0" /> : null}
+ </button>
+ )
+ })}
+ </div>
+ <p className="border-t px-2.5 py-2 text-xs text-muted-foreground">
+ {t('connections.savedOnly')}
+ </p>
+ <Link
+ to="/config"
+ onClick={() => setOpen(false)}
+ className="flex items-center gap-2 rounded-md px-2.5 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <PlusIcon className="size-4" />
+ {t('connections.add')}
+ </Link>
+ </>
+ )
- if (!canManageAccounts) {
+ if (provider === 'volcengine' || !canManageAccounts) {
return (
- <div
- className="flex h-10 min-w-0 flex-1 items-center gap-2 rounded-lg px-2 text-left group-data-[collapsible=icon]:size-9 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0"
- title={accountLabel}
- >
- <span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-sidebar-border bg-sidebar-accent/50">
- <Building2Icon className="size-4" />
- </span>
- <span className="min-w-0 flex-1 truncate text-sm font-semibold group-data-[collapsible=icon]:hidden">
- {accountLabel}
- </span>
- </div>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ aria-label={t('connections.switch')}
+ className="flex h-10 w-full min-w-0 items-center gap-2 rounded-lg px-1 text-left outline-none transition-colors hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-sidebar-ring group-data-[collapsible=icon]:size-9 group-data-[collapsible=icon]:justify-center"
+ >
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-sidebar-border bg-sidebar-accent/50">
+ <Building2Icon className="size-4" />
+ </span>
+ <span className="flex min-w-0 flex-1 items-center gap-1 group-data-[collapsible=icon]:hidden">
+ <span className="min-w-0 truncate text-sm font-semibold">
+ {(provider === 'volcengine' &&
+ formatHostedIdentity(
+ connection.accountId,
+ connection.userId,
+ )) ||
+ connection.accountId ||
+ t('hosted.currentWorkspace')}
+ </span>
+ {provider !== 'unknown' ? (
+ <ServiceIcon hosted={provider === 'volcengine'} />
+ ) : null}
+ </span>
+ <ChevronDownIcon className="size-4 shrink-0 text-muted-foreground group-data-[collapsible=icon]:hidden" />
+ </PopoverTrigger>
+ <PopoverContent
+ side="bottom"
+ align="start"
+ sideOffset={6}
+ className="w-80 gap-0 p-1.5"
+ >
+ {savedConnectionsMenu}
+ </PopoverContent>
+ </Popover>
)
}
return (
<>
<Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger className="flex h-10 w-full min-w-0 items-center gap-2 rounded-lg px-2 text-left outline-none transition-colors hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-sidebar-ring group-data-[collapsible=icon]:size-9 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0">
+ <PopoverTrigger
+ aria-label={t('connections.switch')}
+ className="flex h-10 w-full min-w-0 items-center gap-2 rounded-lg px-2 text-left outline-none transition-colors hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-sidebar-ring group-data-[collapsible=icon]:size-9 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0"
+ >
<span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-sidebar-border bg-sidebar-accent/50">
<Building2Icon className="size-4" />
</span>
- <span className="min-w-0 flex-1 truncate text-sm font-semibold group-data-[collapsible=icon]:hidden">
- {accountLabel}
+ <span className="flex min-w-0 flex-1 items-center gap-1 group-data-[collapsible=icon]:hidden">
+ <span className="min-w-0 truncate text-sm font-semibold">
+ {accountLabel}
+ </span>
+ {provider === 'opensource' ? <ServiceIcon hosted={false} /> : null}
</span>
<ChevronDownIcon className="size-4 shrink-0 text-muted-foreground group-data-[collapsible=icon]:hidden" />
</PopoverTrigger>
@@ -273,8 +515,15 @@ export function AccountSwitcher() {
side="bottom"
align="start"
sideOffset={6}
- className="w-64 gap-0 p-0"
+ className="max-h-[min(80vh,44rem)] w-80 gap-0 overflow-y-auto p-0"
>
+ <p className="px-4 pt-3 text-xs font-medium text-muted-foreground">
+ {t('connections.title')}
+ </p>
+ {savedConnectionsMenu}
+ <p className="border-t px-4 pt-3 text-xs font-medium text-muted-foreground">
+ {t('serverAccountsTitle')}
+ </p>
<div className="border-b p-2">
<div className="relative">
<SearchIcon className="absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
@@ -326,8 +575,11 @@ export function AccountSwitcher() {
<Building2Icon className="size-3.5" />
</span>
<span className="min-w-0 flex-1">
- <span className="block truncate text-sm font-medium">
- {account.accountId}
+ <span className="flex min-w-0 items-center gap-1">
+ <span className="min-w-0 truncate text-sm font-medium">
+ {account.accountId}
+ </span>
+ <ServiceIcon hosted={false} />
</span>
<span className="block text-xs text-muted-foreground">
{t('memberCount', { count: account.userCount })}
diff --git a/web-studio/src/components/app-shell-recovery.test.tsx b/web-studio/src/components/app-shell-recovery.test.tsx
new file mode 100644
index 000000000..a2f6b5bb5
--- /dev/null
+++ b/web-studio/src/components/app-shell-recovery.test.tsx
@@ -0,0 +1,179 @@
+// @vitest-environment jsdom
+import { useState } from 'react'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { IdentityScopedAppShell } from './app-shell'
+
+const state = vi.hoisted(() => ({
+ pathname: '/filesystem',
+ mode: 'checking',
+ profile: 'one',
+}))
+beforeEach(() =>
+ Object.assign(state, {
+ pathname: '/filesystem',
+ mode: 'checking',
+ profile: 'one',
+ }),
+)
+vi.mock('#/hooks/use-mobile', () => ({ useIsMobile: () => false }))
+vi.mock('#/components/account-switcher', () => ({
+ AccountSwitcher: () => null,
+}))
+vi.mock('#/components/current-user-menu', () => ({
+ CurrentUserMenu: () => null,
+}))
+vi.mock('#/components/generated-credential-dialog', () => ({
+ GeneratedCredentialDialog: () => null,
+}))
+vi.mock('#/components/cross-device-verify-dialog', () => ({
+ CrossDeviceVerifyDialog: () => null,
+}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({
+ ready: state.mode !== 'checking',
+ provider: 'opensource',
+ }),
+}))
+vi.mock('#/hooks/use-studio-capabilities', () => ({
+ useStudioCapabilities: () => ({}),
+}))
+vi.mock('#/routes/gateway/-lib/use-gateway', () => ({
+ useGateway: () => ({ allowed: false }),
+}))
+vi.mock('#/hooks/use-app-connection', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ useAppConnection: () => ({
+ identityScopeKey: `${state.profile}:${state.mode}`,
+ activeProfileId: state.profile,
+ serverMode: state.mode,
+ connection: {
+ baseUrl: 'http://service.test',
+ adminApiKey: '',
+ apiKey: '',
+ accountId: 'default',
+ userId: 'default',
+ },
+ connectionRole: 'unknown',
+ isConnectionRoleLoading: false,
+ }),
+}))
+vi.mock('@tanstack/react-router', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ Link: ({
+ to,
+ children,
+ ...props
+ }: {
+ to: string
+ children?: React.ReactNode
+ }) => (
+ <a href={to} {...props}>
+ {children}
+ </a>
+ ),
+ useNavigate: () => vi.fn(),
+ useRouterState: ({
+ select,
+ }: {
+ select: (state: { location: { pathname: string } }) => unknown
+ }) => select({ location: { pathname: state.pathname } }),
+}))
+afterEach(cleanup)
+it('keeps settings reachable while a health request is pending', () => {
+ state.pathname = '/filesystem'
+ render(
+ <IdentityScopedAppShell>
+ <span data-testid="business-route" />
+ </IdentityScopedAppShell>,
+ )
+ expect(screen.queryByTestId('business-route')).toBeNull()
+ expect(
+ screen
+ .getByRole('button', { name: 'Connection settings' })
+ .getAttribute('href'),
+ ).toBe('/settings')
+})
+it('mounts the configuration screen without waiting for health', () => {
+ state.pathname = '/settings'
+ render(
+ <IdentityScopedAppShell>
+ <span data-testid="connection-settings" />
+ </IdentityScopedAppShell>,
+ )
+ expect(screen.getByTestId('connection-settings')).toBeTruthy()
+})
+
+const RECOVERY_LABELS = {
+ url: 'Recovery URL',
+ key: 'Recovery Key',
+ add: 'Add configuration',
+ dialog: 'Configuration draft',
+}
+
+function RecoveryForm() {
+ const [url, setUrl] = useState('http://saved.test')
+ const [key, setKey] = useState('')
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ <input
+ aria-label={RECOVERY_LABELS.url}
+ value={url}
+ onChange={(event) => setUrl(event.target.value)}
+ />
+ <input
+ aria-label={RECOVERY_LABELS.key}
+ value={key}
+ onChange={(event) => setKey(event.target.value)}
+ />
+ <button onClick={() => setOpen(true)}>{RECOVERY_LABELS.add}</button>
+ {open ? <div role="dialog">{RECOVERY_LABELS.dialog}</div> : null}
+ </>
+ )
+}
+it.each(['offline', 'api_key', 'trusted', 'dev'])(
+ 'retains recovery inputs and the configuration dialog after checking becomes %s',
+ (mode) => {
+ state.pathname = '/settings'
+ const content = () => (
+ <IdentityScopedAppShell>
+ <RecoveryForm />
+ </IdentityScopedAppShell>
+ )
+ const view = render(content())
+ fireEvent.change(screen.getByLabelText('Recovery URL'), {
+ target: { value: 'http://edited.test' },
+ })
+ fireEvent.change(screen.getByLabelText('Recovery Key'), {
+ target: { value: 'synthetic-draft' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Add configuration' }))
+ state.mode = mode
+ view.rerender(content())
+ expect(screen.getByLabelText<HTMLInputElement>('Recovery URL').value).toBe(
+ 'http://edited.test',
+ )
+ expect(screen.getByLabelText<HTMLInputElement>('Recovery Key').value).toBe(
+ 'synthetic-draft',
+ )
+ expect(screen.getByRole('dialog')).toBeTruthy()
+ },
+)
+it('resets settings drafts when a different profile is activated', () => {
+ state.pathname = '/settings'
+ const content = () => (
+ <IdentityScopedAppShell>
+ <RecoveryForm />
+ </IdentityScopedAppShell>
+ )
+ const view = render(content())
+ fireEvent.change(screen.getByLabelText('Recovery URL'), {
+ target: { value: 'http://edited.test' },
+ })
+ state.profile = 'two'
+ view.rerender(content())
+ expect(screen.getByLabelText<HTMLInputElement>('Recovery URL').value).toBe(
+ 'http://saved.test',
+ )
+})
diff --git a/web-studio/src/components/app-shell.test.tsx b/web-studio/src/components/app-shell.test.tsx
index 3c38c5682..e6a4ad321 100644
--- a/web-studio/src/components/app-shell.test.tsx
+++ b/web-studio/src/components/app-shell.test.tsx
@@ -1,14 +1,39 @@
// @vitest-environment jsdom
import { cleanup, render, screen } from '@testing-library/react'
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import {
+ AppShell,
ConnectionScopedRouteContent,
shouldShowGatewayNavigation,
} from './app-shell'
-afterEach(cleanup)
+const bootstrap = vi.hoisted(() => ({ health: vi.fn(), pathname: '/' }))
+vi.mock('#/lib/connection/health', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ fetchServerHealth: bootstrap.health,
+}))
+vi.mock('#/hooks/use-app-connection', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ AppConnectionProvider: () => <span data-testid="connected-provider" />,
+}))
+
+vi.mock('@tanstack/react-router', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ Navigate: ({ to }: { to: string }) => <output>{to}</output>,
+ useNavigate: () => vi.fn(),
+ useRouterState: ({
+ select,
+ }: {
+ select: (state: { location: { pathname: string } }) => unknown
+ }) => select({ location: { pathname: bootstrap.pathname } }),
+}))
+
+afterEach(() => {
+ cleanup()
+ bootstrap.pathname = '/'
+})
describe('ConnectionScopedRouteContent', () => {
it('does not mount route content while the server mode is unresolved', () => {
@@ -35,6 +60,29 @@ describe('ConnectionScopedRouteContent', () => {
)
})
+it('routes first use to the configuration page before mounting business routes', () => {
+ localStorage.clear()
+ sessionStorage.clear()
+ render(
+ <AppShell>
+ <span data-testid="business-route" />
+ </AppShell>,
+ )
+ expect(screen.queryByTestId('business-route')).toBeNull()
+ expect(screen.getByText('/config')).toBeTruthy()
+ expect(localStorage.getItem('ov_console_connection_profiles')).toBeNull()
+})
+
+it('shows the setup wizard at /config even after selecting a workspace', () => {
+ localStorage.clear()
+ sessionStorage.setItem('ov_studio_workspace_selected', 'selected')
+ bootstrap.pathname = '/config'
+ render(<AppShell>{null}</AppShell>)
+ expect(screen.getByRole('heading', { level: 1 }).textContent).toContain(
+ 'Choose a workspace',
+ )
+})
+
describe('gateway navigation', () => {
it.each([
['dev', true, true],
@@ -63,3 +111,25 @@ describe('gateway navigation', () => {
).toBe(true)
})
})
+
+it('opens a fresh standalone Gateway Studio without the data-connection wizard', async () => {
+ localStorage.clear()
+ sessionStorage.clear()
+ window.history.replaceState(null, '', '/studio/')
+ bootstrap.health.mockResolvedValueOnce({
+ service: 'openviking-gateway',
+ auth_mode: 'api_key',
+ })
+ try {
+ render(
+ <AppShell>
+ <span data-testid="business-route" />
+ </AppShell>,
+ )
+ expect(await screen.findByTestId('connected-provider')).toBeTruthy()
+ expect(bootstrap.health).toHaveBeenCalledWith(window.location.origin)
+ expect(screen.queryByRole('heading')).toBeNull()
+ } finally {
+ window.history.replaceState(null, '', '/')
+ }
+})
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index ac2efda7a..e4e7e3836 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -1,10 +1,23 @@
+import { Button } from '#/components/ui/button'
+import studioI18n from '#/i18n'
+import { StudioSetup } from './studio-setup'
+import {
+ needsStudioSetup,
+ studioSetupDestination,
+} from '#/lib/connection/onboarding'
import * as React from 'react'
-import { Link, useNavigate, useRouterState } from '@tanstack/react-router'
+import {
+ Link,
+ Navigate,
+ useNavigate,
+ useRouterState,
+} from '@tanstack/react-router'
import {
MessagesSquareIcon,
BookOpenIcon,
BracesIcon,
BrainIcon,
+ ChevronLeftIcon,
ChevronRightIcon,
ListChecksIcon,
HistoryIcon,
@@ -40,6 +53,7 @@ import { ScrollArea } from '#/components/ui/scroll-area'
import {
Sidebar,
SidebarContent,
+ SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
@@ -59,10 +73,18 @@ import {
AppConnectionProvider,
useAppConnection,
} from '#/hooks/use-app-connection'
-import type { ServerMode } from '#/hooks/use-server-mode'
+import type { ServerMode } from '#/lib/connection/health'
import { cn } from '#/lib/utils'
import { useGateway } from '#/routes/gateway/-lib/use-gateway'
-import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'
+import { fetchServerHealth } from '#/lib/connection/health'
+import { useStudioService } from '#/hooks/use-studio-service'
+import { useStudioCapabilities } from '#/hooks/use-studio-capabilities'
+import { featureForPath, isStudioFeatureVisible } from '#/lib/studio-service'
+import { StudioFeatureBoundary } from './studio-feature-boundary'
+import {
+ canManageStudioGateway,
+ resolveStudioManagementCapabilities,
+} from '#/lib/studio-permissions'
type NavItem = {
icon: React.ComponentType
@@ -268,6 +290,51 @@ function NavGroupItem({ item, pathname, title, t }: NavGroupItemProps) {
}
export function AppShell({ children }: { children: React.ReactNode }) {
+ const navigate = useNavigate()
+ const pathname = useRouterState({
+ select: (state) => state.location.pathname,
+ })
+ const [needsSetup, setNeedsSetup] = React.useState(needsStudioSetup)
+ const [checkingHost, setCheckingHost] = React.useState(
+ () => needsSetup && window.location.pathname.startsWith('/studio'),
+ )
+ React.useEffect(() => {
+ if (!checkingHost) return
+ let cancelled = false
+ void fetchServerHealth(window.location.origin)
+ .then((health) => {
+ if (!cancelled && health.service === 'openviking-gateway')
+ setNeedsSetup(false)
+ })
+ .catch(() => {})
+ .finally(() => {
+ if (!cancelled) setCheckingHost(false)
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [checkingHost])
+ if (checkingHost)
+ return (
+ <div
+ role="status"
+ className="flex min-h-svh items-center justify-center bg-background text-sm text-muted-foreground"
+ >
+ {studioI18n.t('studio:loading')}
+ </div>
+ )
+ if (pathname === '/config')
+ return (
+ <StudioSetup
+ onComplete={(connection) => {
+ setNeedsSetup(false)
+ void navigate({
+ to: studioSetupDestination(connection),
+ })
+ }}
+ />
+ )
+ if (needsSetup) return <Navigate replace to="/config" />
return (
<AppConnectionProvider>
<IdentityScopedAppShell>{children}</IdentityScopedAppShell>
@@ -275,13 +342,45 @@ export function AppShell({ children }: { children: React.ReactNode }) {
)
}
-function IdentityScopedAppShell({ children }: { children: React.ReactNode }) {
- const { identityScopeKey, serverMode } = useAppConnection()
+export function IdentityScopedAppShell({
+ children,
+}: {
+ children: React.ReactNode
+}) {
+ const { identityScopeKey, activeProfileId, serverMode } = useAppConnection()
+ const pathname = useRouterState({
+ select: (state) => state.location.pathname,
+ })
+ const isSettings = pathname === '/settings'
+ // Keep the settings tree stable across health transitions, but reset it when
+ // an actual profile changes. Business routes retain identity isolation.
+ if (serverMode === 'checking' && !isSettings)
+ return (
+ <div
+ role="status"
+ className="flex min-h-svh flex-col items-center justify-center gap-4 bg-background text-sm text-muted-foreground"
+ >
+ {studioI18n.t('studio:loading')}
+ <Button
+ nativeButton={false}
+ variant="outline"
+ render={<Link to="/settings" />}
+ >
+ {studioI18n.t('studio:connectionSettings')}
+ </Button>
+ </div>
+ )
return (
- <AppShellInner key={identityScopeKey}>
- <ConnectionScopedRouteContent serverMode={serverMode}>
- {children}
- </ConnectionScopedRouteContent>
+ <AppShellInner
+ key={isSettings ? `settings:${activeProfileId}` : identityScopeKey}
+ >
+ {isSettings ? (
+ children
+ ) : (
+ <ConnectionScopedRouteContent serverMode={serverMode}>
+ <StudioFeatureBoundary>{children}</StudioFeatureBoundary>
+ </ConnectionScopedRouteContent>
+ )}
</AppShellInner>
)
}
@@ -329,7 +428,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
const agentIntegrationsHref = `https://docs.openviking.ai/${
currentLanguage === 'zh-CN' ? 'zh' : 'en'
}/agent-integrations/01-overview`
- const sdkApiHref = `https://docs.openviking.ai/${
+ const opensourceApiHref = `https://docs.openviking.ai/${
currentLanguage === 'zh-CN' ? 'zh' : 'en'
}/api/01-overview`
const [crossDeviceVerifyOpen, setCrossDeviceVerifyOpen] =
@@ -341,28 +440,56 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
isGatewayHost,
serverMode,
} = useAppConnection()
+ const service = useStudioService()
+ const { provider } = service
+ const sdkApiHref =
+ provider === 'volcengine'
+ ? 'https://docs.volcengine.com/docs/84313/2381937'
+ : opensourceApiHref
const settingsActive = pathname === '/settings'
const usersActive = pathname === '/users' || pathname.startsWith('/users/')
const gatewayActive =
pathname === '/gateway' || pathname.startsWith('/gateway/')
- const capabilities = resolveStudioManagementCapabilities({
+ const permissionInput = {
+ serviceProvider: provider,
hasControlCredential: Boolean(connection.adminApiKey.trim()),
isRoleLoading: isConnectionRoleLoading,
role: connectionRole,
serverMode,
- })
- const crossDeviceVerifyActive =
- pathname === '/oauth/verify' || pathname.startsWith('/oauth/verify/')
- const visibleNavItems = NAV_ITEMS
+ }
const gateway = useGateway()
+ const canManageGateway =
+ service.ready && canManageStudioGateway(permissionInput)
const showGateway = shouldShowGatewayNavigation({
isGatewayHost,
serverMode,
- allowed: gateway.allowed,
+ allowed: canManageGateway && gateway.allowed,
})
- // A standalone gateway serves only its own pages and the connection page.
const navSections = isGatewayHost ? [] : NAV_SECTIONS
- const canManageUsers = !isGatewayHost && capabilities.canManageUsers
+ const { canManageUsers: canManageServiceUsers } =
+ resolveStudioManagementCapabilities({
+ serviceProvider: provider,
+ hasControlCredential: Boolean(connection.adminApiKey.trim()),
+ isRoleLoading: isConnectionRoleLoading,
+ role: connectionRole,
+ serverMode,
+ })
+ const canManageUsers = !isGatewayHost && canManageServiceUsers
+ const crossDeviceVerifyActive =
+ pathname === '/oauth/verify' || pathname.startsWith('/oauth/verify/')
+ const capabilities = useStudioCapabilities()
+ const visibleNavItems = NAV_ITEMS.filter((item) => {
+ const feature = featureForPath(item.to)
+ return (
+ !feature ||
+ (service.ready &&
+ isStudioFeatureVisible(
+ provider,
+ feature,
+ capabilities[feature.id]?.data,
+ ))
+ )
+ })
function openCrossDeviceVerify(): void {
if (crossDeviceVerifyActive) {
@@ -389,66 +516,83 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
>
<Sidebar variant="sidebar" collapsible="icon">
<SidebarHeader className="h-12 border-b border-sidebar-border/70 px-2 py-0">
- <div className="flex h-full items-center justify-between gap-2 group-data-[collapsible=icon]:justify-center">
+ <div className="flex h-full items-center gap-1 group-data-[collapsible=icon]:justify-center">
+ {!isGatewayHost ? (
+ <Link
+ to="/config"
+ aria-label={t('header.backToConfig', { ns: 'appShell' })}
+ title={t('header.backToConfig', { ns: 'appShell' })}
+ className="flex size-7 shrink-0 items-center justify-center text-sidebar-foreground/45 transition-colors hover:text-sidebar-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring group-data-[collapsible=icon]:hidden"
+ >
+ <ChevronLeftIcon
+ className="size-3.5"
+ strokeWidth={1.75}
+ aria-hidden="true"
+ />
+ </Link>
+ ) : null}
<div className="min-w-0 flex-1 group-data-[collapsible=icon]:hidden">
<AccountSwitcher />
</div>
- <SidebarTrigger className="hidden shrink-0 md:inline-flex" />
</div>
</SidebarHeader>
<SidebarContent className="gap-0 py-1">
- {navSections.map((section) => (
- <SidebarGroup key={section.id} className="pb-1">
- <SidebarGroupLabel className="h-7 px-2 pt-2 text-[11px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/45">
- {t(section.titleKey, { ns: 'appShell' })}
- </SidebarGroupLabel>
- <SidebarGroupContent>
- <SidebarMenu>
- {visibleNavItems
- .filter((item) => item.section === section.id)
- .map((item) => {
- const isActive =
- pathname === item.to ||
- pathname.startsWith(`${item.to}/`)
- const title = t(item.titleKey, { ns: 'appShell' })
-
- if (item.children) {
- return (
- <NavGroupItem
- key={item.id}
- item={
- item as NavItem & {
- children: readonly NavSubItem[]
+ {navSections
+ .filter((section) =>
+ visibleNavItems.some((item) => item.section === section.id),
+ )
+ .map((section) => (
+ <SidebarGroup key={section.id} className="pb-1">
+ <SidebarGroupLabel className="h-7 px-2 pt-2 text-[11px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/45">
+ {t(section.titleKey, { ns: 'appShell' })}
+ </SidebarGroupLabel>
+ <SidebarGroupContent>
+ <SidebarMenu>
+ {visibleNavItems
+ .filter((item) => item.section === section.id)
+ .map((item) => {
+ const isActive =
+ pathname === item.to ||
+ pathname.startsWith(`${item.to}/`)
+ const title = t(item.titleKey, { ns: 'appShell' })
+
+ if (item.children) {
+ return (
+ <NavGroupItem
+ key={item.id}
+ item={
+ item as NavItem & {
+ children: readonly NavSubItem[]
+ }
}
- }
- pathname={pathname}
- title={title}
- t={t}
- />
- )
- }
+ pathname={pathname}
+ title={title}
+ t={t}
+ />
+ )
+ }
- const Icon = item.icon
-
- return (
- <SidebarMenuItem key={item.id}>
- <SidebarMenuButton
- render={<Link to={item.to} />}
- isActive={isActive}
- tooltip={title}
- className="h-9"
- >
- <Icon />
- <span>{title}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- )
- })}
- </SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
- ))}
+ const Icon = item.icon
+
+ return (
+ <SidebarMenuItem key={item.id}>
+ <SidebarMenuButton
+ render={<Link to={item.to} />}
+ isActive={isActive}
+ tooltip={title}
+ className="h-9"
+ >
+ <Icon />
+ <span>{title}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ )
+ })}
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </SidebarGroup>
+ ))}
<SidebarGroup className="pb-1">
<SidebarGroupLabel className="h-7 px-2 pt-2 text-[11px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/45">
@@ -499,23 +643,25 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
</SidebarMenuButton>
</SidebarMenuItem>
) : null}
- <SidebarMenuItem hidden={isGatewayHost}>
- <SidebarMenuButton
- onClick={openCrossDeviceVerify}
- isActive={crossDeviceVerifyActive}
- tooltip={t('navigation.crossDeviceVerify.title', {
- ns: 'appShell',
- })}
- className="h-9"
- >
- <KeyRoundIcon />
- <span>
- {t('navigation.crossDeviceVerify.title', {
+ {provider === 'opensource' && !isGatewayHost ? (
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ onClick={openCrossDeviceVerify}
+ isActive={crossDeviceVerifyActive}
+ tooltip={t('navigation.crossDeviceVerify.title', {
ns: 'appShell',
})}
- </span>
- </SidebarMenuButton>
- </SidebarMenuItem>
+ className="h-9"
+ >
+ <KeyRoundIcon />
+ <span>
+ {t('navigation.crossDeviceVerify.title', {
+ ns: 'appShell',
+ })}
+ </span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ ) : null}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
@@ -530,7 +676,11 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
<SidebarMenuButton
render={
<a
- href="https://docs.openviking.ai/"
+ href={
+ provider === 'volcengine'
+ ? sdkApiHref
+ : 'https://docs.openviking.ai/'
+ }
target="_blank"
rel="noreferrer"
/>
@@ -554,30 +704,35 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
<span>{t('footer.sdkApi', { ns: 'appShell' })}</span>
</SidebarMenuButton>
</SidebarMenuItem>
- <SidebarMenuItem>
- <SidebarMenuButton
- render={
- <a
- href={agentIntegrationsHref}
- target="_blank"
- rel="noreferrer"
- />
- }
- tooltip={t('footer.agentIntegrations', {
- ns: 'appShell',
- })}
- className="h-9"
- >
- <BotIcon />
- <span>
- {t('footer.agentIntegrations', { ns: 'appShell' })}
- </span>
- </SidebarMenuButton>
- </SidebarMenuItem>
+ {provider === 'opensource' && !isGatewayHost ? (
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ render={
+ <a
+ href={agentIntegrationsHref}
+ target="_blank"
+ rel="noreferrer"
+ />
+ }
+ tooltip={t('footer.agentIntegrations', {
+ ns: 'appShell',
+ })}
+ className="h-9"
+ >
+ <BotIcon />
+ <span>
+ {t('footer.agentIntegrations', { ns: 'appShell' })}
+ </span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ ) : null}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
+ <SidebarFooter className="hidden items-end border-t border-sidebar-border/70 px-2 py-1 group-data-[collapsible=icon]:items-center md:flex">
+ <SidebarTrigger className="hidden shrink-0 md:inline-flex" />
+ </SidebarFooter>
</Sidebar>
<SidebarInset className="min-h-0 flex-1 overflow-hidden rounded-none border-0 bg-background shadow-none ring-0 md:m-0 md:ml-0">
@@ -654,10 +809,12 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
</ScrollArea>
</SidebarInset>
- <CrossDeviceVerifyDialog
- open={crossDeviceVerifyOpen}
- onOpenChange={setCrossDeviceVerifyOpen}
- />
+ {provider === 'opensource' && !isGatewayHost ? (
+ <CrossDeviceVerifyDialog
+ open={crossDeviceVerifyOpen}
+ onOpenChange={setCrossDeviceVerifyOpen}
+ />
+ ) : null}
<GeneratedCredentialDialog />
</SidebarProvider>
)
diff --git a/web-studio/src/components/current-user-menu.interaction.test.tsx b/web-studio/src/components/current-user-menu.interaction.test.tsx
index d0eee357b..21c299300 100644
--- a/web-studio/src/components/current-user-menu.interaction.test.tsx
+++ b/web-studio/src/components/current-user-menu.interaction.test.tsx
@@ -42,6 +42,10 @@ vi.mock('react-i18next', () => ({
}),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ provider: 'opensource' }),
+}))
+
vi.mock('sonner', () => ({ toast: toastMocks }))
vi.mock('#/hooks/use-app-connection', () => ({
diff --git a/web-studio/src/components/current-user-menu.tsx b/web-studio/src/components/current-user-menu.tsx
index fe08a9706..e8c6c3a2d 100644
--- a/web-studio/src/components/current-user-menu.tsx
+++ b/web-studio/src/components/current-user-menu.tsx
@@ -21,6 +21,7 @@ import {
SelectTrigger,
SelectValue,
} from '#/components/ui/select'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
import { fetchAdminUsers } from '#/lib/admin'
import type { AdminConnection } from '#/lib/admin'
@@ -46,7 +47,9 @@ export function CurrentUserMenu() {
const { accountId, userId } = connection
const accountLabel = accountId || t('header.currentUser.unset')
const userLabel = userId || t('header.currentUser.unset')
+ const { provider } = useStudioService()
const { canManageUsers } = resolveStudioManagementCapabilities({
+ serviceProvider: provider,
hasControlCredential: Boolean(connection.adminApiKey.trim()),
isRoleLoading: isConnectionRoleLoading,
role: connectionRole,
diff --git a/web-studio/src/components/studio-feature-boundary.test.tsx b/web-studio/src/components/studio-feature-boundary.test.tsx
new file mode 100644
index 000000000..2b1bac588
--- /dev/null
+++ b/web-studio/src/components/studio-feature-boundary.test.tsx
@@ -0,0 +1,114 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+import { StudioFeatureBoundary } from './studio-feature-boundary'
+
+const state = vi.hoisted(() => ({
+ pathname: '/compile',
+ provider: 'volcengine',
+ ready: true,
+ capability: 'unavailable',
+ role: 'admin',
+ mode: 'api_key',
+}))
+vi.mock('@tanstack/react-router', () => ({
+ useRouterState: () => state.pathname,
+ Link: ({ children }: { children: React.ReactNode }) => <a>{children}</a>,
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({
+ connection: { adminApiKey: 'mock-admin' },
+ connectionRole: state.role,
+ isConnectionRoleLoading: false,
+ serverMode: state.mode,
+ }),
+}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({
+ provider: state.provider,
+ ready: state.ready,
+ isChecking: false,
+ }),
+}))
+vi.mock('#/hooks/use-studio-capabilities', () => ({
+ useStudioCapabilities: () => ({
+ compile: { data: state.capability, isPending: false, refetch: vi.fn() },
+ }),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (k: string) => k }),
+}))
+afterEach(() => {
+ cleanup()
+ state.provider = 'volcengine'
+ state.ready = true
+ state.mode = 'api_key'
+})
+it('does not mount an incompatible extension or its effects through a deep link', () => {
+ state.pathname = '/compile'
+ state.capability = 'unavailable'
+ render(
+ <StudioFeatureBoundary>
+ <span data-testid="dangerous child" />
+ </StudioFeatureBoundary>,
+ )
+ expect(screen.queryByTestId('dangerous child')).toBeNull()
+ expect(screen.getByText('states.unavailable.title')).toBeTruthy()
+})
+it('does not grant management to a hosted admin data identity', () => {
+ state.pathname = '/users/memory-templates'
+ render(
+ <StudioFeatureBoundary>
+ <span data-testid="management child" />
+ </StudioFeatureBoundary>,
+ )
+ expect(screen.queryByTestId('management child')).toBeNull()
+ expect(screen.getByText('states.managementRequired.title')).toBeTruthy()
+})
+it('keeps public directory access independent of extension capability failures', () => {
+ state.pathname = '/directory'
+ render(
+ <StudioFeatureBoundary>
+ <span data-testid="directory child" />
+ </StudioFeatureBoundary>,
+ )
+ expect(screen.getByTestId('directory child')).toBeTruthy()
+})
+
+it('does not mount personal-directory requests before a custom deployment is identified', () => {
+ state.pathname = '/directory'
+ state.provider = 'unknown'
+ render(
+ <StudioFeatureBoundary>
+ <span data-testid="directory child" />
+ </StudioFeatureBoundary>,
+ )
+ expect(screen.queryByTestId('directory child')).toBeNull()
+ expect(screen.getByText('states.unknownProvider.title')).toBeTruthy()
+})
+
+it.each(['/gateway', '/gateway/upstreams/model', '/gateway/keys'])(
+ 'blocks hosted Gateway deep link %s before mounting children',
+ (pathname) => {
+ state.pathname = pathname
+ render(
+ <StudioFeatureBoundary>
+ <span data-testid="gateway-child" />
+ </StudioFeatureBoundary>,
+ )
+ expect(screen.queryByTestId('gateway-child')).toBeNull()
+ },
+)
+it('allows trusted connections to reach Gateway access verification', () => {
+ Object.assign(state, {
+ pathname: '/gateway',
+ provider: 'opensource',
+ mode: 'trusted',
+ })
+ render(
+ <StudioFeatureBoundary>
+ <span data-testid="gateway-child" />
+ </StudioFeatureBoundary>,
+ )
+ expect(screen.getByTestId('gateway-child')).toBeTruthy()
+})
diff --git a/web-studio/src/components/studio-feature-boundary.tsx b/web-studio/src/components/studio-feature-boundary.tsx
new file mode 100644
index 000000000..3c98eed63
--- /dev/null
+++ b/web-studio/src/components/studio-feature-boundary.tsx
@@ -0,0 +1,109 @@
+import type { ReactNode } from 'react'
+import { Link, useRouterState } from '@tanstack/react-router'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { useStudioService } from '#/hooks/use-studio-service'
+import { featureForPath } from '#/lib/studio-service'
+import { useStudioCapabilities } from '#/hooks/use-studio-capabilities'
+import {
+ canManageStudioGateway,
+ resolveStudioManagementCapabilities,
+} from '#/lib/studio-permissions'
+
+export function StudioFeatureBoundary({ children }: { children: ReactNode }) {
+ const { t } = useTranslation('studio')
+ const pathname = useRouterState({ select: (s) => s.location.pathname })
+ const {
+ connection,
+ connectionRole,
+ isConnectionRoleLoading,
+ isGatewayHost,
+ serverMode,
+ } = useAppConnection()
+ const service = useStudioService()
+ const feature = featureForPath(pathname)
+ const probe = feature && 'probe' in feature ? feature.probe : undefined
+ const cloudProbe =
+ service.ready && service.provider === 'volcengine' && Boolean(probe)
+ const capabilities = useStudioCapabilities()
+ const capability = feature ? capabilities[feature.id] : undefined
+ if (
+ pathname === '/settings' ||
+ pathname === '/' ||
+ (isGatewayHost && feature?.id === 'gateway')
+ )
+ return children
+ let reason: string | undefined
+ if (!service.ready)
+ reason = service.isChecking ? 'checking' : 'connectionFailed'
+ else if (service.provider === 'unknown') reason = 'unknownProvider'
+ else if (feature?.domain === 'management') {
+ const permissions = resolveStudioManagementCapabilities({
+ serviceProvider: service.provider,
+ hasControlCredential: Boolean(connection.adminApiKey.trim()),
+ isRoleLoading: isConnectionRoleLoading,
+ role: connectionRole,
+ serverMode,
+ })
+ if (
+ feature.id === 'gateway' &&
+ service.provider === 'opensource' &&
+ serverMode !== 'api_key' &&
+ serverMode !== 'dev' &&
+ serverMode !== 'trusted'
+ )
+ reason = 'gatewayAuthMode'
+ else if (
+ feature.id === 'gateway'
+ ? !canManageStudioGateway({
+ serviceProvider: service.provider,
+ hasControlCredential: Boolean(connection.adminApiKey.trim()),
+ isRoleLoading: isConnectionRoleLoading,
+ role: connectionRole,
+ serverMode,
+ })
+ : !permissions.canManageUsers
+ )
+ reason = 'managementRequired'
+ } else if (pathname.startsWith('/oauth') && service.provider !== 'opensource')
+ reason = 'unavailable'
+ else if (
+ feature?.domain === 'extensions' &&
+ service.provider !== 'opensource'
+ ) {
+ if (!probe) reason = 'unavailable'
+ else if (capability?.isPending) reason = 'checking'
+ else if (capability?.data !== 'supported')
+ reason = capability?.data ?? 'unknown'
+ }
+ if (!reason) return children
+ return (
+ <section
+ className="mx-auto grid w-full max-w-xl gap-4 rounded-xl border bg-card p-6"
+ aria-live="polite"
+ >
+ <h1 className="text-lg font-medium">{t(`states.${reason}.title`)}</h1>
+ <p className="text-sm text-muted-foreground">
+ {t(`states.${reason}.description`)}
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <Button nativeButton={false} render={<Link to="/settings" />}>
+ {t('connectionSettings')}
+ </Button>
+ <Button
+ nativeButton={false}
+ variant="outline"
+ render={<Link to="/filesystem" />}
+ >
+ {t('directory')}
+ </Button>
+ {cloudProbe && reason !== 'checking' ? (
+ <Button variant="outline" onClick={() => void capability?.refetch()}>
+ {t('retry')}
+ </Button>
+ ) : null}
+ </div>
+ </section>
+ )
+}
diff --git a/web-studio/src/components/studio-setup.test.tsx b/web-studio/src/components/studio-setup.test.tsx
new file mode 100644
index 000000000..a3088f4b0
--- /dev/null
+++ b/web-studio/src/components/studio-setup.test.tsx
@@ -0,0 +1,527 @@
+// @vitest-environment jsdom
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import userEvent from '@testing-library/user-event'
+import { StudioSetup } from './studio-setup'
+
+const mocks = vi.hoisted(() => ({
+ verify: vi.fn(),
+ complete: vi.fn(),
+ language: vi.fn(),
+ theme: vi.fn(),
+}))
+vi.mock('next-themes', () => ({
+ useTheme: () => ({ theme: 'system', setTheme: mocks.theme }),
+}))
+vi.mock('react-i18next', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: {
+ language: 'en',
+ resolvedLanguage: 'en',
+ changeLanguage: mocks.language,
+ },
+ }),
+}))
+vi.mock('#/lib/connection/onboarding', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ markStudioSetupPending: vi.fn(),
+ verifyStudioSetup: mocks.verify,
+ completeStudioSetup: mocks.complete,
+}))
+afterEach(cleanup)
+beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+})
+
+it('deduplicates identical saved connections and keeps the active profile', async () => {
+ const connection = {
+ serviceSelection: 'opensource',
+ baseUrl: 'http://127.0.0.1:1933',
+ apiKey: '',
+ adminApiKey: '',
+ accountId: 'default',
+ userId: 'default',
+ }
+ localStorage.setItem(
+ 'ov_console_connection_profiles',
+ JSON.stringify({
+ activeId: 'second',
+ profiles: [
+ {
+ id: 'first',
+ name: 'Default',
+ connection: { ...connection, userId: '' },
+ },
+ {
+ id: 'second',
+ name: 'Open source',
+ connection: { ...connection, userId: '' },
+ },
+ {
+ id: 'third',
+ name: 'Remote',
+ connection: { ...connection, baseUrl: 'https://remote.test/ov' },
+ },
+ ],
+ }),
+ )
+ render(<StudioSetup onComplete={vi.fn()} />)
+ const selector = screen.getByRole('combobox', {
+ name: 'connectionChoice',
+ })
+ expect(selector.textContent).toContain('Open source')
+ const user = userEvent.setup()
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.click(screen.getByRole('button', { name: 'advanced' }))
+ expect(
+ screen.getByLabelText<HTMLInputElement>('settings:fields.user').value,
+ ).toBe('')
+ fireEvent.click(screen.getByRole('button', { name: 'back' }))
+ await user.click(screen.getByRole('combobox', { name: 'connectionChoice' }))
+ expect(await screen.findAllByRole('option')).toHaveLength(3)
+ expect(screen.getAllByRole('option', { name: 'Open source' })).toHaveLength(1)
+ expect(screen.queryByRole('option', { name: 'Default' })).toBeNull()
+ await user.click(screen.getByRole('option', { name: 'Remote' }))
+ expect(
+ screen.getByRole('combobox', { name: 'connectionChoice' }).textContent,
+ ).toContain('Remote')
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ expect(screen.getAllByText('https://remote.test/ov').length).toBeGreaterThan(
+ 0,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'back' }))
+ await user.click(screen.getByRole('combobox', { name: 'connectionChoice' }))
+ await user.click(await screen.findByRole('option', { name: 'newConnection' }))
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: 'next' }).disabled,
+ ).toBe(true)
+ expect(
+ screen.getByLabelText<HTMLInputElement>('settings:fields.baseUrl').value,
+ ).toBe('')
+})
+it('shows the hosted server address on step one and requires a fresh API key each time', () => {
+ localStorage.setItem(
+ 'ov_console_connection_profiles',
+ JSON.stringify({
+ activeId: 'hosted',
+ profiles: [
+ {
+ id: 'hosted',
+ name: 'Hosted',
+ connection: {
+ serviceSelection: 'volcengine',
+ baseUrl: 'https://saved.hosted.test/ov',
+ apiKey: 'saved-user-key',
+ adminApiKey: 'saved-admin-key',
+ accountId: 'default',
+ userId: 'default',
+ },
+ },
+ ],
+ }),
+ )
+ const first = render(<StudioSetup onComplete={vi.fn()} />)
+ const endpoint = screen.getByLabelText<HTMLInputElement>('hostedEndpoint')
+ expect(endpoint.value).toBe('https://saved.hosted.test/ov')
+ expect(
+ screen.queryByRole('combobox', { name: 'connectionChoice' }),
+ ).toBeNull()
+ fireEvent.change(endpoint, {
+ target: { value: 'https://another.hosted.test/ov' },
+ })
+ expect(endpoint.value).toBe('https://another.hosted.test/ov')
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ expect(
+ screen.queryByRole('combobox', { name: 'connectionChoice' }),
+ ).toBeNull()
+ expect(screen.queryByLabelText('hostedEndpoint')).toBeNull()
+ const key = screen.getByLabelText<HTMLInputElement>(
+ 'settings:fields.userApiKey',
+ )
+ expect(key.value).toBe('')
+ expect(key.autocomplete).toBe('new-password')
+ fireEvent.change(key, { target: { value: 'entered-key' } })
+ first.unmount()
+
+ render(<StudioSetup onComplete={vi.fn()} />)
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ expect(
+ screen.getByLabelText<HTMLInputElement>('settings:fields.userApiKey').value,
+ ).toBe('')
+})
+it('reuses an existing hosted profile only after the user reenters its API key', async () => {
+ localStorage.setItem(
+ 'ov_console_connection_profiles',
+ JSON.stringify({
+ activeId: 'hosted',
+ profiles: [
+ {
+ id: 'hosted',
+ name: 'Hosted',
+ connection: {
+ serviceSelection: 'volcengine',
+ baseUrl: 'https://saved.hosted.test/ov',
+ apiKey: 'saved-user-key',
+ adminApiKey: '',
+ accountId: 'team',
+ userId: 'alice',
+ },
+ },
+ ],
+ }),
+ )
+ mocks.verify.mockImplementation(async (draft) => draft)
+ render(<StudioSetup onComplete={vi.fn()} />)
+ expect(screen.getByLabelText<HTMLInputElement>('hostedEndpoint').value).toBe(
+ 'https://saved.hosted.test/ov',
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ const key = screen.getByLabelText<HTMLInputElement>(
+ 'settings:fields.userApiKey',
+ )
+ expect(key.value).toBe('')
+ fireEvent.change(key, { target: { value: 'saved-user-key' } })
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ await screen.findByRole('status')
+ fireEvent.click(screen.getByRole('button', { name: 'enter' }))
+ expect(mocks.complete).toHaveBeenCalledWith(
+ expect.objectContaining({ apiKey: 'saved-user-key' }),
+ 'studio:providers.volcengine',
+ 'hosted',
+ )
+})
+it('accepts an older hosted profile without an API key after manual verification', async () => {
+ localStorage.setItem(
+ 'ov_console_connection_profiles',
+ JSON.stringify({
+ activeId: 'legacy-hosted',
+ profiles: [
+ {
+ id: 'legacy-hosted',
+ name: 'Hosted',
+ connection: {
+ serviceSelection: 'volcengine',
+ baseUrl: 'https://saved.hosted.test/ov',
+ adminApiKey: '',
+ accountId: 'default',
+ userId: 'default',
+ },
+ },
+ ],
+ }),
+ )
+ const done = vi.fn()
+ mocks.verify.mockImplementation(async (draft) => draft)
+ render(<StudioSetup onComplete={done} />)
+ expect(screen.getByLabelText<HTMLInputElement>('hostedEndpoint').value).toBe(
+ 'https://saved.hosted.test/ov',
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.change(screen.getByLabelText('settings:fields.userApiKey'), {
+ target: { value: 'newly-entered-key' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ await screen.findByRole('status')
+ fireEvent.click(screen.getByRole('button', { name: 'enter' }))
+ expect(mocks.complete).toHaveBeenCalledWith(
+ expect.objectContaining({ apiKey: 'newly-entered-key' }),
+ 'studio:providers.volcengine',
+ undefined,
+ )
+ expect(done).toHaveBeenCalledOnce()
+ expect(screen.queryByRole('alert')).toBeNull()
+})
+it('selects the configured open-source address when switching from hosted', () => {
+ const hosted = {
+ serviceSelection: 'volcengine',
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ apiKey: 'hosted-key',
+ adminApiKey: '',
+ accountId: 'default',
+ userId: 'default',
+ }
+ localStorage.setItem(
+ 'ov_console_connection_profiles',
+ JSON.stringify({
+ activeId: 'hosted',
+ profiles: [
+ { id: 'hosted', name: 'Hosted', connection: hosted },
+ {
+ id: 'opensource',
+ name: 'Open source',
+ connection: {
+ ...hosted,
+ serviceSelection: 'opensource',
+ baseUrl: 'https://configured.example/ov',
+ },
+ },
+ ],
+ }),
+ )
+ render(<StudioSetup onComplete={vi.fn()} />)
+ fireEvent.click(screen.getByLabelText('studio:providers.opensource'))
+ expect(
+ screen.getByRole('combobox', { name: 'connectionChoice' }).textContent,
+ ).toContain('Open source')
+ expect(
+ screen.getAllByTitle('https://configured.example/ov').length,
+ ).toBeGreaterThan(0)
+ expect(screen.queryByLabelText('settings:fields.baseUrl')).toBeNull()
+})
+
+it('offers the local development service when only a hosted link is saved', () => {
+ localStorage.setItem(
+ 'ov_console_connection_profiles',
+ JSON.stringify({
+ activeId: 'hosted',
+ profiles: [
+ {
+ id: 'hosted',
+ name: 'Hosted',
+ connection: {
+ serviceSelection: 'volcengine',
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ apiKey: 'hosted-key',
+ adminApiKey: '',
+ accountId: 'default',
+ userId: 'default',
+ },
+ },
+ ],
+ }),
+ )
+ render(<StudioSetup onComplete={vi.fn()} />)
+ fireEvent.click(screen.getByLabelText('studio:providers.opensource'))
+ expect(
+ screen.getByRole('combobox', { name: 'connectionChoice' }).textContent,
+ ).toContain('Local OpenViking')
+ expect(screen.getAllByTitle('http://127.0.0.1:1933').length).toBeGreaterThan(
+ 0,
+ )
+ expect(screen.queryByLabelText('settings:fields.baseUrl')).toBeNull()
+})
+it('requires a valid new open-source address before continuing', () => {
+ render(<StudioSetup onComplete={vi.fn()} />)
+ const next = screen.getByRole<HTMLButtonElement>('button', { name: 'next' })
+ expect(next.disabled).toBe(true)
+ fireEvent.change(screen.getByLabelText('settings:fields.baseUrl'), {
+ target: { value: 'ftp://invalid.test' },
+ })
+ expect(next.disabled).toBe(true)
+ fireEvent.change(screen.getByLabelText('settings:fields.baseUrl'), {
+ target: { value: 'http://service.test' },
+ })
+ expect(next.disabled).toBe(false)
+ fireEvent.click(next)
+ expect(screen.getByText('http://service.test')).toBeTruthy()
+ expect(screen.queryByLabelText('settings:fields.baseUrl')).toBeNull()
+})
+it('combines preferences, applies changes immediately and retains connection fields when returning', () => {
+ render(<StudioSetup onComplete={vi.fn()} />)
+ fireEvent.click(screen.getByLabelText('中文'))
+ expect(mocks.language).toHaveBeenCalledWith('zh-CN')
+ fireEvent.click(screen.getByLabelText('dark'))
+ expect(mocks.theme).toHaveBeenCalledWith('dark')
+ fireEvent.change(screen.getByLabelText('settings:fields.baseUrl'), {
+ target: { value: 'http://service.test' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.change(screen.getByLabelText('settings:fields.userApiKey'), {
+ target: { value: 'synthetic-key' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'back' }))
+ expect(
+ screen.getByLabelText<HTMLInputElement>('settings:fields.baseUrl').value,
+ ).toBe('http://service.test')
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ expect(
+ screen.getByLabelText<HTMLInputElement>('settings:fields.userApiKey').value,
+ ).toBe('synthetic-key')
+})
+it('keeps advanced fields out of keyboard navigation while collapsed and preserves their values', () => {
+ render(<StudioSetup onComplete={vi.fn()} />)
+ fireEvent.change(screen.getByLabelText('settings:fields.baseUrl'), {
+ target: { value: 'http://service.test' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ const toggle = screen.getByRole('button', { name: 'advanced' })
+ const fields = document.getElementById('setup-advanced-fields')
+ expect(toggle.getAttribute('aria-expanded')).toBe('false')
+ expect(fields?.hasAttribute('inert')).toBe(true)
+ fireEvent.click(toggle)
+ expect(toggle.getAttribute('aria-expanded')).toBe('true')
+ expect(fields?.hasAttribute('inert')).toBe(false)
+ fireEvent.change(screen.getByLabelText('settings:fields.account'), {
+ target: { value: 'team' },
+ })
+ fireEvent.click(toggle)
+ expect(fields?.hasAttribute('inert')).toBe(true)
+ fireEvent.click(toggle)
+ expect(
+ screen.getByLabelText<HTMLInputElement>('settings:fields.account').value,
+ ).toBe('team')
+})
+it('keeps manual account and user fields without a user-directory action', () => {
+ render(<StudioSetup onComplete={vi.fn()} />)
+ fireEvent.change(screen.getByLabelText('settings:fields.baseUrl'), {
+ target: { value: 'http://service.test' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.click(screen.getByRole('button', { name: 'advanced' }))
+ fireEvent.change(screen.getByLabelText('settings:fields.account'), {
+ target: { value: 'work-memory' },
+ })
+ fireEvent.change(screen.getByLabelText('settings:fields.user'), {
+ target: { value: 'wangladi' },
+ })
+ expect(screen.queryByRole('button', { name: 'loadUsers' })).toBeNull()
+ expect(screen.queryByRole('combobox', { name: 'chooseUser' })).toBeNull()
+ expect(
+ screen.getByLabelText<HTMLInputElement>('settings:fields.user').value,
+ ).toBe('wangladi')
+})
+it('enters only after verification, invalidates verification when fields change, and persists on explicit entry', async () => {
+ const done = vi.fn()
+ mocks.verify.mockImplementation(async (draft) => draft)
+ render(<StudioSetup onComplete={done} />)
+ fireEvent.change(screen.getByLabelText('settings:fields.baseUrl'), {
+ target: { value: 'http://service.test' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ await screen.findByRole('status')
+ expect(done).not.toHaveBeenCalled()
+ expect(mocks.complete).not.toHaveBeenCalled()
+ fireEvent.change(screen.getByLabelText('settings:fields.userApiKey'), {
+ target: { value: 'changed' },
+ })
+ expect(screen.queryByRole('status')).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ await screen.findByRole('status')
+ fireEvent.click(screen.getByRole('button', { name: 'enter' }))
+ expect(mocks.complete).toHaveBeenCalledOnce()
+ expect(done).toHaveBeenCalledOnce()
+})
+it('keeps the user in setup on verification failure', async () => {
+ mocks.verify.mockRejectedValueOnce(new Error('Forbidden'))
+ const done = vi.fn()
+ render(<StudioSetup onComplete={done} />)
+ fireEvent.change(screen.getByLabelText('settings:fields.baseUrl'), {
+ target: { value: 'http://service.test' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ await waitFor(() =>
+ expect(screen.getByRole('alert').textContent).toContain('Forbidden'),
+ )
+ expect(done).not.toHaveBeenCalled()
+})
+it('edits the hosted endpoint and uses it for connection verification', async () => {
+ render(<StudioSetup onComplete={vi.fn()} />)
+ fireEvent.click(screen.getByLabelText('studio:providers.volcengine'))
+ expect(
+ screen.queryByRole('combobox', { name: 'connectionChoice' }),
+ ).toBeNull()
+ const endpoint = screen.getByRole<HTMLInputElement>('textbox', {
+ name: 'hostedEndpoint',
+ })
+ expect(endpoint.value).toBe(
+ 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ )
+ fireEvent.change(endpoint, { target: { value: 'invalid-address' } })
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: 'next' }).disabled,
+ ).toBe(true)
+ fireEvent.change(endpoint, { target: { value: 'https://hosted.test/ov' } })
+ expect(endpoint.value).toBe('https://hosted.test/ov')
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: 'next' }).disabled,
+ ).toBe(false)
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ expect(
+ screen.queryByRole('combobox', { name: 'connectionChoice' }),
+ ).toBeNull()
+ expect(screen.queryByLabelText('hostedEndpoint')).toBeNull()
+ expect(screen.getByText('hostedKeyHelp')).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ expect(screen.getByRole('alert').textContent).toBe('keyRequired')
+ expect(document.activeElement).toBe(
+ screen.getByLabelText('settings:fields.userApiKey'),
+ )
+ expect(mocks.verify).not.toHaveBeenCalled()
+ fireEvent.change(screen.getByLabelText('settings:fields.userApiKey'), {
+ target: { value: 'hosted-key' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ await waitFor(() =>
+ expect(mocks.verify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ baseUrl: 'https://hosted.test/ov',
+ apiKey: 'hosted-key',
+ }),
+ expect.any(AbortSignal),
+ ),
+ )
+})
+it('clears the hosted API key when its service address changes', () => {
+ render(<StudioSetup onComplete={vi.fn()} />)
+ fireEvent.click(screen.getByLabelText('studio:providers.volcengine'))
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.change(screen.getByLabelText('settings:fields.userApiKey'), {
+ target: { value: 'old-service-secret' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'back' }))
+ fireEvent.change(screen.getByLabelText('hostedEndpoint'), {
+ target: { value: 'https://another.hosted.test/ov' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ expect(
+ screen.getByLabelText<HTMLInputElement>('settings:fields.userApiKey').value,
+ ).toBe('')
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ expect(screen.getByRole('alert').textContent).toBe('keyRequired')
+ expect(mocks.verify).not.toHaveBeenCalled()
+})
+it('keeps each workspace draft isolated when switching on the first step', () => {
+ render(<StudioSetup onComplete={vi.fn()} />)
+ const url = () =>
+ screen.getByLabelText<HTMLInputElement>('settings:fields.baseUrl')
+ const key = () =>
+ screen.getByLabelText<HTMLInputElement>('settings:fields.userApiKey')
+ fireEvent.change(url(), { target: { value: 'http://oss.test' } })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.change(key(), { target: { value: 'synthetic-oss' } })
+ fireEvent.click(screen.getByRole('button', { name: 'back' }))
+ fireEvent.click(screen.getByLabelText('studio:providers.volcengine'))
+ expect(screen.getByLabelText<HTMLInputElement>('hostedEndpoint').value).toBe(
+ 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ )
+ fireEvent.change(screen.getByLabelText('hostedEndpoint'), {
+ target: { value: 'https://cloud.test/ov' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ expect(screen.queryByLabelText('hostedEndpoint')).toBeNull()
+ expect(key().value).toBe('')
+ fireEvent.change(key(), { target: { value: 'synthetic-cloud' } })
+ fireEvent.click(screen.getByRole('button', { name: 'back' }))
+ fireEvent.click(screen.getByLabelText('studio:providers.opensource'))
+ expect(url().value).toBe('http://oss.test')
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ expect(key().value).toBe('synthetic-oss')
+ fireEvent.click(screen.getByRole('button', { name: 'back' }))
+ fireEvent.click(screen.getByLabelText('studio:providers.volcengine'))
+ expect(screen.getByLabelText<HTMLInputElement>('hostedEndpoint').value).toBe(
+ 'https://cloud.test/ov',
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ expect(key().value).toBe('synthetic-cloud')
+})
diff --git a/web-studio/src/components/studio-setup.tsx b/web-studio/src/components/studio-setup.tsx
new file mode 100644
index 000000000..74b648116
--- /dev/null
+++ b/web-studio/src/components/studio-setup.tsx
@@ -0,0 +1,895 @@
+import { useEffect, useLayoutEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useTheme } from 'next-themes'
+import {
+ ArrowRightIcon,
+ ArrowLeftIcon,
+ CheckIcon,
+ ChevronDownIcon,
+ CloudIcon,
+ ServerIcon,
+ Loader2Icon,
+} from 'lucide-react'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '#/components/ui/select'
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from '#/components/ui/card'
+import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
+import {
+ StudioSetupError,
+ StudioSetupRequestError,
+ studioSetupDestination,
+ CLOUD_SETUP_URL,
+ completeStudioSetup,
+ markStudioSetupPending,
+ savedSetupConnections,
+ verifyStudioSetup,
+} from '#/lib/connection/onboarding'
+import { isValidConnectionUrl } from '#/lib/connection/profiles'
+import type { ConnectionDraft } from '#/hooks/use-app-connection'
+
+const LANGUAGES = [
+ ['zh-CN', '中文'],
+ ['en', 'English'],
+] as const
+const PROVIDERS = [
+ ['opensource', ServerIcon],
+ ['volcengine', CloudIcon],
+] as const
+const THEMES = ['light', 'dark', 'system'] as const
+const ADVANCED_FIELDS = ['adminApiKey', 'accountId', 'userId'] as const
+const NEW_CONNECTION = 'new'
+type SavedConnection = ReturnType<typeof savedSetupConnections>[number]
+
+function withoutCredentials(connection: ConnectionDraft): ConnectionDraft {
+ return { ...connection, apiKey: '', adminApiKey: '' }
+}
+
+function savedConnectionTitle(profile: SavedConnection): string {
+ const identity = [
+ profile.connection.accountId,
+ profile.connection.userId,
+ ].filter((value) => value && value !== 'default')
+ return identity.length
+ ? `${profile.name} · ${identity.join('/')}`
+ : profile.name
+}
+
+function savedConnectionLabel(
+ profile: SavedConnection,
+ profiles: SavedConnection[],
+): string {
+ const title = savedConnectionTitle(profile)
+ const sameLabel = profiles.filter(
+ (candidate) =>
+ savedConnectionTitle(candidate) === title &&
+ candidate.connection.baseUrl === profile.connection.baseUrl,
+ )
+ if (sameLabel.length < 2) return title
+ return `${title} (${sameLabel.findIndex((candidate) => candidate.id === profile.id) + 1})`
+}
+
+function newConnectionDraft(
+ provider: (typeof PROVIDERS)[number][0],
+): ConnectionDraft {
+ return {
+ serviceSelection: provider,
+ baseUrl: provider === 'volcengine' ? CLOUD_SETUP_URL : '',
+ apiKey: '',
+ adminApiKey: '',
+ accountId: 'default',
+ userId: 'default',
+ }
+}
+
+export function StudioSetup({
+ onComplete,
+}: {
+ onComplete: (connection: ConnectionDraft) => void
+}) {
+ const { t, i18n } = useTranslation(['onboarding', 'studio', 'settings'])
+ const { theme, setTheme } = useTheme()
+ const [step, setStep] = useState(0)
+ const [advancedOpen, setAdvancedOpen] = useState(false)
+ const [activeProfileId] = useState(() => {
+ try {
+ return JSON.parse(
+ localStorage.getItem('ov_console_connection_profiles') || '{}',
+ ).activeId as string | undefined
+ } catch {
+ return undefined
+ }
+ })
+ const [savedConnections] = useState(() => {
+ const profiles = savedSetupConnections()
+ if (
+ import.meta.env.DEV &&
+ profiles.length > 0 &&
+ !profiles.some(
+ (profile) => profile.connection.serviceSelection === 'opensource',
+ ) &&
+ ['localhost', '127.0.0.1'].includes(window.location.hostname)
+ ) {
+ profiles.push({
+ id: 'local-openviking',
+ name: 'Local OpenViking',
+ connection: {
+ ...newConnectionDraft('opensource'),
+ baseUrl: 'http://127.0.0.1:1933',
+ },
+ })
+ }
+ const seen = new Set<string>()
+ return profiles
+ .sort((a, b) =>
+ a.id === activeProfileId ? -1 : b.id === activeProfileId ? 1 : 0,
+ )
+ .filter((profile) => {
+ const connection = profile.connection
+ const address = new URL(connection.baseUrl).href.replace(/\/+$/, '')
+ const identity = JSON.stringify([
+ connection.serviceSelection,
+ address,
+ connection.accountId,
+ connection.userId,
+ connection.apiKey,
+ connection.adminApiKey,
+ ])
+ if (seen.has(identity)) return false
+ seen.add(identity)
+ return true
+ })
+ })
+ const initialProfile = savedConnections.at(0)
+ const [selectedConnectionId, setSelectedConnectionId] = useState(() =>
+ initialProfile?.connection.serviceSelection === 'opensource'
+ ? initialProfile.id
+ : NEW_CONNECTION,
+ )
+ const [draft, setDraft] = useState<ConnectionDraft>(() => {
+ if (initialProfile) {
+ return withoutCredentials(initialProfile.connection)
+ }
+ return newConnectionDraft('opensource')
+ })
+ const newDraftsRef = useRef<
+ Partial<Record<(typeof PROVIDERS)[number][0], ConnectionDraft>>
+ >({})
+ const providerSelectionsRef = useRef<
+ Partial<Record<(typeof PROVIDERS)[number][0], string>>
+ >({})
+ const [verified, setVerified] = useState<ConnectionDraft | null>(null)
+ const providerConnections = savedConnections.filter(
+ (profile) => profile.connection.serviceSelection === draft.serviceSelection,
+ )
+ const selectedProfile = providerConnections.find(
+ (profile) => profile.id === selectedConnectionId,
+ )
+ const needsNewAddress =
+ draft.serviceSelection === 'opensource' &&
+ selectedConnectionId === NEW_CONNECTION
+ const canContinue =
+ (draft.serviceSelection === 'opensource' && !needsNewAddress) ||
+ isValidConnectionUrl(draft.baseUrl)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const connectionRevisionRef = useRef(0)
+ const verifiedSelectionRef = useRef<string | null>(null)
+ const abortRef = useRef<AbortController | null>(null)
+ const keyInputRef = useRef<HTMLInputElement>(null)
+ const headingRef = useRef<HTMLHeadingElement>(null)
+ const cardRef = useRef<HTMLDivElement>(null)
+ const cardAnimationRef = useRef<Animation | null>(null)
+ const previousCardHeightRef = useRef<number | null>(null)
+ useEffect(() => {
+ markStudioSetupPending()
+ return () => abortRef.current?.abort()
+ }, [])
+ useEffect(() => {
+ headingRef.current?.focus()
+ }, [step])
+ useLayoutEffect(() => {
+ const card = cardRef.current
+ const previousHeight = previousCardHeightRef.current
+ previousCardHeightRef.current = null
+ if (!card || previousHeight === null) return
+
+ const nextHeight = card.getBoundingClientRect().height
+ if (
+ previousHeight === nextHeight ||
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ )
+ return
+
+ cardAnimationRef.current = card.animate(
+ [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }],
+ { duration: 360, easing: 'cubic-bezier(0.22, 1, 0.36, 1)' },
+ )
+ cardAnimationRef.current.onfinish = () => {
+ cardAnimationRef.current = null
+ }
+ }, [step])
+ function changeStep(nextStep: number) {
+ previousCardHeightRef.current =
+ cardRef.current?.getBoundingClientRect().height ?? null
+ cardAnimationRef.current?.cancel()
+ cardAnimationRef.current = null
+ setStep(nextStep)
+ }
+ const language = (i18n.resolvedLanguage ?? i18n.language).startsWith('zh')
+ ? 'zh-CN'
+ : 'en'
+ function update(next: Partial<ConnectionDraft>) {
+ connectionRevisionRef.current += 1
+ verifiedSelectionRef.current = null
+ setDraft((value) => ({ ...value, ...next }))
+ setVerified(null)
+ setError('')
+ }
+ function selectConnection(id: string) {
+ if (busy || id === selectedConnectionId) return
+ connectionRevisionRef.current += 1
+ verifiedSelectionRef.current = null
+ const provider =
+ draft.serviceSelection === 'volcengine' ? 'volcengine' : 'opensource'
+ if (selectedConnectionId === NEW_CONNECTION)
+ newDraftsRef.current[provider] = draft
+ setSelectedConnectionId(id)
+ providerSelectionsRef.current[provider] = id
+ setDraft(
+ id === NEW_CONNECTION
+ ? (newDraftsRef.current[provider] ?? newConnectionDraft(provider))
+ : withoutCredentials(
+ providerConnections.find((profile) => profile.id === id)!
+ .connection,
+ ),
+ )
+ setVerified(null)
+ setError('')
+ }
+ function switchProvider(provider: (typeof PROVIDERS)[number][0]) {
+ if (busy) return
+ const current =
+ draft.serviceSelection === 'volcengine' ? 'volcengine' : 'opensource'
+ if (provider === current) return
+ connectionRevisionRef.current += 1
+ verifiedSelectionRef.current = null
+ providerSelectionsRef.current[current] = selectedConnectionId
+ if (selectedConnectionId === NEW_CONNECTION)
+ newDraftsRef.current[current] = draft
+ const nextId =
+ provider === 'volcengine'
+ ? NEW_CONNECTION
+ : (providerSelectionsRef.current[provider] ??
+ savedConnections.find(
+ (profile) => profile.connection.serviceSelection === provider,
+ )?.id ??
+ NEW_CONNECTION)
+ setSelectedConnectionId(nextId)
+ const savedHostedConnection = savedConnections.find(
+ (profile) => profile.connection.serviceSelection === 'volcengine',
+ )?.connection
+ setDraft(
+ nextId === NEW_CONNECTION
+ ? (newDraftsRef.current[provider] ??
+ (provider === 'volcengine' && savedHostedConnection
+ ? withoutCredentials(savedHostedConnection)
+ : newConnectionDraft(provider)))
+ : withoutCredentials(
+ savedConnections.find((profile) => profile.id === nextId)!
+ .connection,
+ ),
+ )
+ setVerified(null)
+ setError('')
+ }
+ async function submit(event: React.FormEvent) {
+ event.preventDefault()
+ if (busy) return
+ setError('')
+ if (verified) {
+ if (verifiedSelectionRef.current !== selectedConnectionId) {
+ setVerified(null)
+ setError(t('savedConnectionUnavailable'))
+ return
+ }
+ try {
+ const matchingHostedProfile =
+ verified.serviceSelection === 'volcengine'
+ ? savedSetupConnections().find(
+ (profile) =>
+ profile.connection.serviceSelection === 'volcengine' &&
+ new URL(profile.connection.baseUrl).href.replace(
+ /\/+$/,
+ '',
+ ) === new URL(verified.baseUrl).href.replace(/\/+$/, '') &&
+ typeof profile.connection.apiKey === 'string' &&
+ profile.connection.apiKey.trim() === verified.apiKey,
+ )
+ : undefined
+ completeStudioSetup(
+ verified,
+ t(`studio:providers.${verified.serviceSelection}`),
+ verified.serviceSelection === 'volcengine'
+ ? matchingHostedProfile?.id
+ : selectedConnectionId === NEW_CONNECTION
+ ? undefined
+ : selectedConnectionId,
+ )
+ onComplete(verified)
+ } catch {
+ setError(t('storageError'))
+ }
+ return
+ }
+ if (!isValidConnectionUrl(draft.baseUrl)) {
+ setError(t('studio:profiles.invalidUrl'))
+ return
+ }
+ if (draft.serviceSelection === 'volcengine' && !draft.apiKey.trim()) {
+ setError(t('keyRequired'))
+ keyInputRef.current?.focus()
+ return
+ }
+ const controller = new AbortController()
+ const connectionRevision = connectionRevisionRef.current
+ abortRef.current = controller
+ setBusy(true)
+ try {
+ const result = await verifyStudioSetup(draft, controller.signal)
+ if (
+ !controller.signal.aborted &&
+ connectionRevision === connectionRevisionRef.current
+ ) {
+ setDraft(result)
+ verifiedSelectionRef.current = selectedConnectionId
+ setVerified(result)
+ }
+ } catch (err) {
+ if (!controller.signal.aborted)
+ setError(
+ err instanceof StudioSetupRequestError
+ ? `${t(err.stage === 'health' ? 'healthRequestFailed' : 'dataRequestFailed')} ${err.message}`
+ : err instanceof StudioSetupError
+ ? t(err.code)
+ : err instanceof Error
+ ? err.message
+ : String(err),
+ )
+ } finally {
+ if (abortRef.current === controller) {
+ abortRef.current = null
+ setBusy(false)
+ }
+ }
+ }
+ return (
+ <main className="flex h-svh flex-col items-center overflow-y-auto bg-background px-5 py-6 text-foreground sm:px-8 sm:py-8 lg:pt-[max(2rem,calc((100svh-52rem)/2))]">
+ <div className="w-full max-w-5xl shrink-0">
+ <div className="mb-6 flex items-center gap-3 lg:mb-8">
+ <img src="/ov-logo.png" alt="" className="size-10 rounded-xl" />
+ <span className="text-base font-semibold tracking-tight">
+ {t('brand')}
+ </span>
+ </div>
+ <div className="grid items-start gap-6 lg:grid-cols-[1fr_1.15fr] lg:gap-20">
+ <header className="lg:pt-5">
+ <h1
+ ref={headingRef}
+ tabIndex={-1}
+ className="whitespace-nowrap text-[clamp(1.25rem,3vw,2rem)] leading-tight font-semibold tracking-tight outline-none"
+ >
+ {step === 0 ? t('workspace') : t('connectionTitle')}
+ </h1>
+ <p className="mt-3 max-w-sm text-sm leading-6 text-muted-foreground lg:mt-5 lg:min-h-14 lg:leading-7">
+ {step === 0
+ ? t('welcomeDescription')
+ : t('connectionDescription')}
+ </p>
+ <ol
+ className="mt-5 flex gap-6 lg:mt-12 lg:flex-col lg:gap-7"
+ aria-label={t('steps')}
+ >
+ {[t('workspace'), t('connection')].map((label, index) => (
+ <li
+ key={index}
+ aria-current={step === index ? 'step' : undefined}
+ className="relative flex items-start gap-3"
+ >
+ {index === 0 ? (
+ <span
+ aria-hidden="true"
+ className="absolute left-[11.5px] top-7 hidden h-[calc(100%-4px)] w-px overflow-hidden rounded-full bg-border/70 lg:block"
+ >
+ <span
+ className={`block h-full w-full origin-top bg-foreground/70 transition-transform duration-500 ease-out motion-reduce:transition-none ${step === 1 ? 'scale-y-100' : 'scale-y-0'}`}
+ />
+ </span>
+ ) : null}
+ <span
+ aria-hidden="true"
+ className={`relative z-10 flex size-6 shrink-0 items-center justify-center rounded-full border text-[11px] font-medium transition-colors duration-300 motion-reduce:transition-none ${step >= index ? 'border-foreground bg-foreground text-background' : 'border-border text-muted-foreground'}`}
+ >
+ {step > index ? (
+ <CheckIcon className="size-3" />
+ ) : (
+ index + 1
+ )}
+ </span>
+ <div className="pt-1">
+ <p
+ className={`text-sm font-medium ${step === index ? 'text-foreground' : 'text-muted-foreground'}`}
+ >
+ {label}
+ </p>
+ <p className="mt-1 hidden text-xs leading-5 text-muted-foreground lg:block">
+ {t(index === 0 ? 'workspaceHint' : 'connectionHint')}
+ </p>
+ </div>
+ </li>
+ ))}
+ </ol>
+ </header>
+ <Card
+ ref={cardRef}
+ className="gap-0 overflow-hidden rounded-2xl border-border/70 bg-card py-0 shadow-sm"
+ >
+ <CardHeader className="gap-2 border-b border-border/70 px-6 py-4 sm:px-8 sm:py-5">
+ <CardTitle className="text-lg font-semibold tracking-tight">
+ {step === 0 ? t('workspace') : t('connection')}
+ </CardTitle>
+ <CardDescription className="text-sm leading-6">
+ {t(step === 0 ? 'workspaceHint' : 'connectionHint')}
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="px-6 py-5 sm:px-8">
+ {step === 0 ? (
+ <div className="space-y-4">
+ <fieldset className="space-y-3">
+ <legend className="text-sm font-medium">
+ {t('studio:serviceType')}
+ </legend>
+ <div className="grid grid-cols-2 gap-3">
+ {PROVIDERS.map(([provider, Icon]) => (
+ <label
+ key={provider}
+ className="flex min-h-16 cursor-pointer items-center gap-2.5 rounded-lg border border-border px-3 text-sm font-medium transition-colors hover:bg-muted/40 has-checked:border-foreground has-checked:bg-muted/40 has-focus-visible:ring-2 has-focus-visible:ring-ring"
+ >
+ <input
+ className="sr-only"
+ type="radio"
+ name="provider"
+ value={provider}
+ checked={draft.serviceSelection === provider}
+ onChange={() => switchProvider(provider)}
+ />
+ <Icon
+ aria-hidden="true"
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ {t(`studio:providers.${provider}`)}
+ </label>
+ ))}
+ </div>
+ </fieldset>
+ {draft.serviceSelection === 'opensource' ? (
+ <div className="space-y-2">
+ <p className="text-sm font-medium">
+ {t('connectionChoice')}
+ </p>
+ <Select
+ value={selectedConnectionId}
+ onValueChange={(value) => {
+ if (value) selectConnection(value)
+ }}
+ >
+ <SelectTrigger
+ aria-label={t('connectionChoice')}
+ className="h-11 w-full min-w-0 rounded-lg bg-background px-4 shadow-xs"
+ >
+ <SelectValue>
+ {selectedProfile
+ ? savedConnectionLabel(
+ selectedProfile,
+ providerConnections,
+ )
+ : t('newConnection')}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent
+ align="start"
+ className="w-[var(--anchor-width)] max-w-[calc(100vw-2rem)] rounded-xl border border-border bg-popover p-1 shadow-lg before:hidden"
+ >
+ {providerConnections.map((profile) => (
+ <SelectItem
+ key={profile.id}
+ value={profile.id}
+ className="min-h-10 overflow-hidden rounded-lg px-3 pr-9"
+ title={profile.connection.baseUrl}
+ >
+ <span className="block min-w-0 truncate font-medium">
+ {savedConnectionLabel(
+ profile,
+ providerConnections,
+ )}
+ </span>
+ </SelectItem>
+ ))}
+ <SelectItem
+ value={NEW_CONNECTION}
+ className="min-h-10 rounded-lg px-3 pr-9"
+ >
+ {t('newConnection')}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ {needsNewAddress ? (
+ <div className="space-y-2 pt-2">
+ <label htmlFor="setup-new-url" className="sr-only">
+ {t('settings:fields.baseUrl')}
+ </label>
+ <Input
+ id="setup-new-url"
+ className="h-11 rounded-lg"
+ type="url"
+ value={draft.baseUrl}
+ placeholder="http://127.0.0.1:1933"
+ aria-invalid={
+ Boolean(draft.baseUrl) && !canContinue
+ }
+ aria-describedby="setup-new-url-help"
+ onChange={(event) =>
+ update({ baseUrl: event.target.value })
+ }
+ {...PLAIN_INPUT_PROPS}
+ />
+ <p
+ id="setup-new-url-help"
+ className="text-xs text-muted-foreground"
+ >
+ {draft.baseUrl && !canContinue
+ ? t('studio:profiles.invalidUrl')
+ : t('newAddressHint')}
+ </p>
+ </div>
+ ) : (
+ <p
+ className="line-clamp-2 break-all px-1 pt-1 text-xs text-muted-foreground"
+ title={draft.baseUrl}
+ >
+ {draft.baseUrl}
+ </p>
+ )}
+ </div>
+ ) : (
+ <div className="space-y-2">
+ <label
+ htmlFor="setup-hosted-url"
+ className="text-sm font-medium"
+ >
+ {t('hostedEndpoint')}
+ </label>
+ <Input
+ id="setup-hosted-url"
+ className="h-11 rounded-lg"
+ type="url"
+ value={draft.baseUrl}
+ aria-invalid={Boolean(draft.baseUrl) && !canContinue}
+ onChange={(event) =>
+ update({
+ baseUrl: event.target.value,
+ apiKey: '',
+ adminApiKey: '',
+ })
+ }
+ {...PLAIN_INPUT_PROPS}
+ />
+ {draft.baseUrl && !canContinue ? (
+ <p className="text-xs text-destructive">
+ {t('studio:profiles.invalidUrl')}
+ </p>
+ ) : null}
+ </div>
+ )}
+ <fieldset className="space-y-3">
+ <legend className="text-sm font-medium">
+ {t('language')}
+ </legend>
+ <div className="grid grid-cols-2 gap-3">
+ {LANGUAGES.map(([value, label]) => (
+ <label
+ key={value}
+ className="flex min-h-11 cursor-pointer items-center justify-between gap-3 rounded-lg border border-border px-4 transition-colors hover:bg-muted/40 has-checked:border-foreground has-checked:bg-muted/40 has-focus-visible:ring-2 has-focus-visible:ring-ring has-focus-visible:ring-offset-2"
+ >
+ <input
+ className="sr-only"
+ type="radio"
+ name="language"
+ value={value}
+ checked={language === value}
+ onChange={() => {
+ void i18n.changeLanguage(value)
+ document.documentElement.lang = value
+ }}
+ />
+ <span className="text-sm font-medium">{label}</span>
+ <span
+ aria-hidden="true"
+ className={`flex size-4 items-center justify-center rounded-full border ${language === value ? 'border-foreground bg-foreground text-background' : 'border-muted-foreground/30'}`}
+ >
+ {language === value ? (
+ <CheckIcon className="size-3" />
+ ) : null}
+ </span>
+ </label>
+ ))}
+ </div>
+ </fieldset>
+ <fieldset className="space-y-3">
+ <legend className="text-sm font-medium">
+ {t('theme')}
+ </legend>
+ <div className="grid grid-cols-3 gap-3">
+ {THEMES.map((value) => (
+ <label
+ key={value}
+ className="min-w-0 cursor-pointer rounded-xl border border-border p-2 transition-colors hover:bg-muted/40 has-checked:border-foreground has-checked:bg-muted/30 has-focus-visible:ring-2 has-focus-visible:ring-ring has-focus-visible:ring-offset-2"
+ >
+ <input
+ className="sr-only"
+ type="radio"
+ name="theme"
+ value={value}
+ checked={(theme ?? 'system') === value}
+ onChange={() => setTheme(value)}
+ />
+ <ThemePreview appearance={value} />
+ <span className="mt-2 flex items-center justify-between gap-1 text-xs font-medium sm:text-sm">
+ {t(value)}
+ {(theme ?? 'system') === value ? (
+ <CheckIcon
+ aria-hidden="true"
+ className="size-3.5 shrink-0"
+ />
+ ) : null}
+ </span>
+ </label>
+ ))}
+ </div>
+ </fieldset>
+ <Button
+ className="mt-2 min-h-11 w-full rounded-lg"
+ disabled={!canContinue}
+ onClick={() => changeStep(1)}
+ >
+ {t('next')}
+ <ArrowRightIcon aria-hidden="true" className="size-4" />
+ </Button>
+ </div>
+ ) : (
+ <form
+ onSubmit={(event) => void submit(event)}
+ className="space-y-5"
+ >
+ <fieldset disabled={busy} className="space-y-4">
+ <div className="grid gap-2 text-sm">
+ <span className="font-medium">
+ {t('settings:fields.baseUrl')}
+ </span>
+ <p className="break-all rounded-lg border border-border bg-muted/30 px-4 py-3 text-sm">
+ {draft.baseUrl}
+ </p>
+ </div>
+ <label
+ className="grid gap-2 text-sm font-medium"
+ htmlFor="setup-key"
+ >
+ {t('settings:fields.userApiKey')}
+ <Input
+ ref={keyInputRef}
+ className="h-11 rounded-lg bg-background/60 text-sm"
+ id="setup-key"
+ name="apiKey"
+ type="password"
+ aria-invalid={error === t('keyRequired')}
+ aria-describedby={
+ error === t('keyRequired')
+ ? 'setup-key-error'
+ : undefined
+ }
+ value={draft.apiKey}
+ onChange={(event) =>
+ update({ apiKey: event.target.value })
+ }
+ {...PLAIN_INPUT_PROPS}
+ autoComplete="new-password"
+ />
+ </label>
+ {error === t('keyRequired') ? (
+ <p
+ id="setup-key-error"
+ role="alert"
+ className="text-sm text-destructive"
+ >
+ {error}
+ </p>
+ ) : null}
+ <p className="text-sm text-muted-foreground">
+ {t(
+ draft.serviceSelection === 'volcengine'
+ ? 'hostedKeyHelp'
+ : 'keyHelp',
+ )}
+ </p>
+ {draft.serviceSelection === 'opensource' ? (
+ <div>
+ <button
+ type="button"
+ aria-expanded={advancedOpen}
+ aria-controls="setup-advanced-fields"
+ onClick={() => setAdvancedOpen((open) => !open)}
+ className="flex items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:rounded-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ >
+ <ChevronDownIcon
+ aria-hidden="true"
+ className={`size-3 transition-transform duration-300 motion-reduce:transition-none ${advancedOpen ? 'rotate-180' : ''}`}
+ />
+ {t('advanced')}
+ </button>
+ <div
+ id="setup-advanced-fields"
+ aria-hidden={!advancedOpen}
+ inert={!advancedOpen}
+ className={`grid transition-[grid-template-rows,opacity] duration-300 ease-out motion-reduce:transition-none ${advancedOpen ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0'}`}
+ >
+ <div className="min-h-0 overflow-hidden">
+ <div className="grid gap-3 pt-3">
+ {ADVANCED_FIELDS.map((key) => (
+ <label
+ className="grid gap-2 text-sm"
+ key={key}
+ htmlFor={`setup-${key}`}
+ >
+ {t(
+ `settings:fields.${key === 'accountId' ? 'account' : key === 'userId' ? 'user' : 'rootApiKey'}`,
+ )}
+ <Input
+ id={`setup-${key}`}
+ className="focus-visible:ring-inset"
+ name={key}
+ type={
+ key === 'adminApiKey'
+ ? 'password'
+ : 'text'
+ }
+ value={draft[key]}
+ onChange={(event) =>
+ update({ [key]: event.target.value })
+ }
+ {...PLAIN_INPUT_PROPS}
+ autoComplete={
+ key === 'adminApiKey'
+ ? 'new-password'
+ : 'off'
+ }
+ />
+ </label>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ ) : null}
+ </fieldset>
+ {error && error !== t('keyRequired') ? (
+ <p
+ role="alert"
+ className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 text-sm leading-6 text-destructive"
+ >
+ {t('verifyFailed')} {error}
+ </p>
+ ) : null}
+ {verified ? (
+ <p
+ role="status"
+ className="rounded-lg border border-emerald-600/20 bg-emerald-600/5 p-3 text-sm leading-6 text-emerald-700 dark:text-emerald-400"
+ >
+ {t(
+ studioSetupDestination(verified) === '/users'
+ ? 'verifiedManagement'
+ : 'verified',
+ )}
+ {verified.accountId && verified.userId
+ ? ` ${verified.accountId} / ${verified.userId}`
+ : null}
+ </p>
+ ) : null}
+ <div className="flex gap-3 border-t border-border/70 pt-5">
+ <Button
+ type="button"
+ variant="outline"
+ className="min-h-11 rounded-lg"
+ onClick={() => {
+ abortRef.current?.abort()
+ setBusy(false)
+ changeStep(0)
+ }}
+ >
+ <ArrowLeftIcon aria-hidden="true" className="size-4" />
+ {t('back')}
+ </Button>
+ <Button
+ type="submit"
+ className="min-h-11 flex-1 rounded-lg"
+ disabled={busy || !isValidConnectionUrl(draft.baseUrl)}
+ >
+ {busy ? (
+ <Loader2Icon className="size-4 animate-spin" />
+ ) : null}
+ {t(busy ? 'verifying' : verified ? 'enter' : 'verify')}
+ </Button>
+ </div>
+ </form>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ </main>
+ )
+}
+
+function ThemePreview({ appearance }: { appearance: (typeof THEMES)[number] }) {
+ return (
+ <div
+ aria-hidden="true"
+ className={`relative h-14 overflow-hidden rounded-md border border-black/10 ${appearance === 'light' ? 'bg-[#f9fafb]' : appearance === 'dark' ? 'bg-[#191b20]' : 'bg-[linear-gradient(110deg,#f9fafb_50%,#191b20_50%)]'}`}
+ >
+ <div
+ className={`flex h-4 items-center gap-1 border-b px-2 ${appearance === 'dark' ? 'border-white/10' : 'border-black/10'}`}
+ >
+ {[0, 1, 2].map((dot) => (
+ <span
+ key={dot}
+ className={`size-1 rounded-full ${appearance === 'dark' ? 'bg-white/25' : 'bg-black/20'}`}
+ />
+ ))}
+ </div>
+ <div className="flex h-full">
+ <div
+ className={`w-1/4 border-r p-1.5 ${appearance === 'dark' ? 'border-white/10 bg-white/5' : 'border-black/10 bg-black/[0.03]'}`}
+ >
+ <div
+ className={`mb-1.5 h-1 rounded-full ${appearance === 'dark' ? 'bg-white/20' : 'bg-black/15'}`}
+ />
+ <div
+ className={`h-1 w-2/3 rounded-full ${appearance === 'dark' ? 'bg-white/10' : 'bg-black/10'}`}
+ />
+ </div>
+ <div className="flex-1 space-y-1.5 p-2">
+ <div
+ className={`h-1.5 w-3/5 rounded-full ${appearance === 'dark' ? 'bg-white/35' : 'bg-black/20'}`}
+ />
+ <div
+ className={`h-1 w-full rounded-full ${appearance === 'dark' ? 'bg-white/10' : 'bg-black/10'}`}
+ />
+ <div
+ className={`h-1 w-4/5 rounded-full ${appearance === 'dark' ? 'bg-white/10' : 'bg-black/10'}`}
+ />
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/web-studio/src/components/ui/select.tsx b/web-studio/src/components/ui/select.tsx
index 89d16c581..4290ad026 100644
--- a/web-studio/src/components/ui/select.tsx
+++ b/web-studio/src/components/ui/select.tsx
@@ -82,7 +82,7 @@ function SelectContent({
data-slot="select-content"
data-align-trigger={alignItemWithTrigger}
className={cn(
- "dark isolate z-50 max-h-(--available-height) min-w-(--anchor-width) w-max origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-md text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 animate-none! relative bg-popover/70 before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:rounded-[inherit] before:backdrop-blur-2xl before:backdrop-saturate-150 **:data-[slot$=-item]:focus:bg-foreground/10 **:data-[slot$=-item]:data-highlighted:bg-foreground/10 **:data-[slot$=-separator]:bg-foreground/5 **:data-[slot$=-trigger]:focus:bg-foreground/10 **:data-[slot$=-trigger]:aria-expanded:bg-foreground/10! **:data-[variant=destructive]:focus:bg-foreground/10! **:data-[variant=destructive]:text-accent-foreground! **:data-[variant=destructive]:**:text-accent-foreground!",
+ "isolate z-50 max-h-(--available-height) min-w-(--anchor-width) w-max origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-md text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 animate-none! relative bg-popover/70 before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:rounded-[inherit] before:backdrop-blur-2xl before:backdrop-saturate-150 **:data-[slot$=-item]:focus:bg-foreground/10 **:data-[slot$=-item]:data-highlighted:bg-foreground/10 **:data-[slot$=-separator]:bg-foreground/5 **:data-[slot$=-trigger]:focus:bg-foreground/10 **:data-[slot$=-trigger]:aria-expanded:bg-foreground/10! **:data-[variant=destructive]:focus:bg-foreground/10! **:data-[variant=destructive]:text-accent-foreground! **:data-[variant=destructive]:**:text-accent-foreground!",
className
)}
{...props}
diff --git a/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx b/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx
index 3669ebfc1..3a321c2e8 100644
--- a/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx
+++ b/web-studio/src/hooks/use-app-connection.bootstrap.test.tsx
@@ -1,10 +1,17 @@
// @vitest-environment jsdom
import { createServer } from 'node:http'
import { once } from 'node:events'
-import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { afterEach, expect, it, vi } from 'vitest'
+import { useStudioService } from './use-studio-service'
import { AppConnectionProvider, useAppConnection } from './use-app-connection'
vi.mock('@tanstack/react-router', () => ({
@@ -12,7 +19,10 @@ vi.mock('@tanstack/react-router', () => ({
useRouterState: () => '/home',
}))
-afterEach(cleanup)
+afterEach(() => {
+ cleanup()
+ localStorage.removeItem('ov_console_connection_profiles')
+})
function Identity() {
const { connectionRole, isConnectionRoleLoading, serverMode } =
@@ -104,73 +114,296 @@ it.each(['', 'root-key'])(
},
)
-it.each(['', 'invalid'])(
- 'recognizes gateway health with saved OV key %j',
- async (apiKey) => {
- const requests: string[] = []
- const server = createServer((req, res) => {
- res.setHeader('Access-Control-Allow-Origin', '*')
- res.setHeader(
- 'Access-Control-Allow-Headers',
- 'X-OpenViking-Account, X-OpenViking-User, X-API-Key',
- )
- if (req.method === 'OPTIONS') {
- res.end()
- return
- }
- requests.push(req.url || '')
- res.setHeader('Content-Type', 'application/json')
- // An invalid key only leaves out the identity fields.
- res.end(
- JSON.stringify({
- status: 'ok',
- service: 'openviking-gateway',
- auth_mode: 'api_key',
- openviking_url: 'https://ov.example',
- }),
- )
- })
- server.listen(0, '127.0.0.1')
- await once(server, 'listening')
- const { port } = server.address() as { port: number }
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- })
- localStorage.setItem(
- 'ov_console_connection',
- JSON.stringify({
- baseUrl: `http://127.0.0.1:${port}`,
- accountId: 'default',
- userId: 'default',
- apiKey,
- adminApiKey: '',
+function ConnectionState() {
+ const { connection, connectionRole, isConnectionRoleLoading, serverMode } =
+ useAppConnection()
+ return (
+ <output data-testid="connection-state">
+ {JSON.stringify({
+ mode: serverMode,
+ role: isConnectionRoleLoading ? 'loading' : connectionRole,
+ account: connection.accountId,
+ user: connection.userId,
+ })}
+ </output>
+ )
+}
+
+it('keeps a valid data connection and its resolved identity when a separate control key has expired', async () => {
+ const keys: unknown[] = []
+ const server = createServer((req, res) => {
+ res.setHeader('Access-Control-Allow-Origin', '*')
+ res.setHeader('Access-Control-Allow-Headers', '*')
+ if (req.method === 'OPTIONS') {
+ res.end()
+ return
+ }
+ const key = req.headers['x-api-key']
+ keys.push(key)
+ res.setHeader('Content-Type', 'application/json')
+ res.statusCode = key === 'user-key' ? 200 : 401
+ res.end(
+ JSON.stringify(
+ key === 'user-key'
+ ? {
+ auth_mode: 'api_key',
+ version: '0.4.22',
+ account_id: 'account-a',
+ user_id: 'alice',
+ role: 'user',
+ }
+ : {
+ status: 'error',
+ error: {
+ code: 'UNAUTHENTICATED',
+ message: 'Invalid control key',
+ },
+ },
+ ),
+ )
+ })
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const address = server.address() as { port: number }
+ const client = new QueryClient()
+ localStorage.setItem(
+ 'ov_console_connection',
+ JSON.stringify({
+ baseUrl: `http://127.0.0.1:${address.port}`,
+ accountId: 'default',
+ userId: 'default',
+ apiKey: 'user-key',
+ adminApiKey: 'expired-control-key',
+ }),
+ )
+ try {
+ render(
+ <QueryClientProvider client={client}>
+ <AppConnectionProvider>
+ <ConnectionState />
+ </AppConnectionProvider>
+ </QueryClientProvider>,
+ )
+ await waitFor(() =>
+ expect(
+ JSON.parse(screen.getByTestId('connection-state').textContent),
+ ).toEqual({
+ mode: 'api_key',
+ role: 'unknown',
+ account: 'account-a',
+ user: 'alice',
}),
)
- function Host() {
- const { isGatewayHost, openvikingUrl, serverMode } = useAppConnection()
- return (
- <output>{`${isGatewayHost}:${openvikingUrl}:${serverMode}`}</output>
- )
+ expect(keys[0]).toBe('user-key')
+ expect(keys).toContain('expired-control-key')
+ } finally {
+ cleanup()
+ client.clear()
+ localStorage.removeItem('ov_console_connection')
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+})
+
+function RecoveryState() {
+ const {
+ reconnect,
+ connection,
+ connectionRole,
+ isConnectionRoleLoading,
+ serverMode,
+ } = useAppConnection()
+ const service = useStudioService()
+ return (
+ <>
+ <button onClick={reconnect}>Retry connection</button>
+ <output data-testid="recovery-state">
+ {JSON.stringify({
+ mode: serverMode,
+ role: isConnectionRoleLoading ? 'loading' : connectionRole,
+ account: connection.accountId,
+ user: connection.userId,
+ provider: service.provider,
+ version: service.version,
+ })}
+ </output>
+ </>
+ )
+}
+
+it('reconnects health, auth mode and identity together after a temporary outage without changing credentials', async () => {
+ let healthy = false
+ const server = createServer((req, res) => {
+ res.setHeader('Access-Control-Allow-Origin', '*')
+ res.setHeader('Access-Control-Allow-Headers', '*')
+ if (req.method === 'OPTIONS') {
+ res.end()
+ return
}
- try {
- render(
- <QueryClientProvider client={queryClient}>
- <AppConnectionProvider>
- <Host />
- </AppConnectionProvider>
- </QueryClientProvider>,
- )
- await waitFor(() =>
- expect(
- screen.getByText('true:https://ov.example:api_key'),
- ).toBeTruthy(),
- )
- expect(requests.every((path) => path === '/health')).toBe(true)
- } finally {
- cleanup()
- queryClient.clear()
- localStorage.removeItem('ov_console_connection')
- await new Promise<void>((resolve) => server.close(() => resolve()))
+ res.setHeader('Content-Type', 'application/json')
+ res.statusCode = healthy ? 200 : 503
+ res.end(
+ JSON.stringify(
+ healthy
+ ? {
+ status: 'ok',
+ auth_mode: 'api_key',
+ version: '0.4.22',
+ role: 'user',
+ account_id: 'account-a',
+ user_id: 'alice',
+ }
+ : {
+ status: 'error',
+ error: { code: 'UNAVAILABLE', message: 'Temporary outage' },
+ },
+ ),
+ )
+ })
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const client = new QueryClient()
+ localStorage.setItem(
+ 'ov_console_connection',
+ JSON.stringify({
+ baseUrl: `http://127.0.0.1:${(server.address() as { port: number }).port}`,
+ accountId: 'default',
+ userId: 'default',
+ apiKey: 'user-key',
+ adminApiKey: '',
+ }),
+ )
+ try {
+ render(
+ <QueryClientProvider client={client}>
+ <AppConnectionProvider>
+ <RecoveryState />
+ </AppConnectionProvider>
+ </QueryClientProvider>,
+ )
+ const state = () =>
+ JSON.parse(screen.getByTestId('recovery-state').textContent)
+ await waitFor(() => expect(state().mode).toBe('offline'))
+ expect(state().provider).toBe('unknown')
+ client.setQueryData(['studio-feature', 'previous'], 'supported')
+ healthy = true
+ fireEvent.click(screen.getByRole('button', { name: 'Retry connection' }))
+ await waitFor(() =>
+ expect(state()).toEqual({
+ mode: 'api_key',
+ role: 'user',
+ account: 'account-a',
+ user: 'alice',
+ provider: 'opensource',
+ version: '0.4.22',
+ }),
+ )
+ expect(client.getQueryData(['studio-feature', 'previous'])).toBeUndefined()
+ } finally {
+ cleanup()
+ client.clear()
+ localStorage.removeItem('ov_console_connection')
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+})
+
+it('exposes the resolved data user before a slow management probe completes', async () => {
+ const pendingControl: Array<() => void> = []
+ const readyUsers: string[] = []
+ let controlReleased = false
+ const server = createServer((req, res) => {
+ res.setHeader('Access-Control-Allow-Origin', '*')
+ res.setHeader('Access-Control-Allow-Headers', '*')
+ if (req.method === 'OPTIONS') {
+ res.end()
+ return
}
- },
-)
+ res.setHeader('Content-Type', 'application/json')
+ if (req.url !== '/health') {
+ res.statusCode = 403
+ res.end(JSON.stringify({ error: { code: 'FORBIDDEN' } }))
+ return
+ }
+ if (req.headers['x-api-key'] === 'slow-control') {
+ const reply = () =>
+ res.end(
+ JSON.stringify({
+ auth_mode: 'api_key',
+ version: '0.4.22',
+ role: 'admin',
+ account_id: 'management-account',
+ user_id: 'manager',
+ }),
+ )
+ if (controlReleased) reply()
+ else pendingControl.push(reply)
+ return
+ }
+ res.end(
+ JSON.stringify({
+ auth_mode: 'api_key',
+ version: '0.4.22',
+ role: 'user',
+ account_id: 'account-a',
+ user_id: 'alice',
+ }),
+ )
+ })
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const address = server.address() as { port: number }
+ const client = new QueryClient()
+ localStorage.setItem(
+ 'ov_console_connection',
+ JSON.stringify({
+ baseUrl: `http://127.0.0.1:${address.port}`,
+ accountId: 'default',
+ userId: 'default',
+ apiKey: 'user-key',
+ adminApiKey: 'slow-control',
+ }),
+ )
+ function WorkspaceIdentity() {
+ const service = useStudioService()
+ const { connection, isConnectionRoleLoading } = useAppConnection()
+ if (service.ready) readyUsers.push(connection.userId)
+ return (
+ <output data-testid="workspace-identity">
+ {JSON.stringify({
+ ready: service.ready,
+ user: connection.userId,
+ managementPending: isConnectionRoleLoading,
+ })}
+ </output>
+ )
+ }
+ try {
+ render(
+ <QueryClientProvider client={client}>
+ <AppConnectionProvider>
+ <WorkspaceIdentity />
+ </AppConnectionProvider>
+ </QueryClientProvider>,
+ )
+ await waitFor(() =>
+ expect(
+ JSON.parse(screen.getByTestId('workspace-identity').textContent),
+ ).toEqual({ ready: true, user: 'alice', managementPending: true }),
+ )
+ expect(readyUsers.length).toBeGreaterThan(0)
+ expect(readyUsers.every((user) => user === 'alice')).toBe(true)
+ controlReleased = true
+ for (const release of pendingControl.splice(0)) release()
+ await waitFor(() =>
+ expect(
+ JSON.parse(screen.getByTestId('workspace-identity').textContent),
+ ).toEqual({ ready: true, user: 'alice', managementPending: false }),
+ )
+ expect(readyUsers.every((user) => user === 'alice')).toBe(true)
+ } finally {
+ cleanup()
+ for (const release of pendingControl) release()
+ client.clear()
+ localStorage.removeItem('ov_console_connection')
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+})
diff --git a/web-studio/src/hooks/use-app-connection.host.test.tsx b/web-studio/src/hooks/use-app-connection.host.test.tsx
index 89743a0ee..6de23f410 100644
--- a/web-studio/src/hooks/use-app-connection.host.test.tsx
+++ b/web-studio/src/hooks/use-app-connection.host.test.tsx
@@ -1,11 +1,15 @@
// @vitest-environment jsdom
import { cleanup, render, screen, waitFor } from '@testing-library/react'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import {
+ QueryClient,
+ QueryClientProvider,
+ useQuery,
+} from '@tanstack/react-query'
import { afterEach, expect, it, vi } from 'vitest'
import { AppConnectionProvider, useAppConnection } from './use-app-connection'
const { health } = vi.hoisted(() => ({ health: vi.fn() }))
-vi.mock('./use-server-mode', async (importOriginal) => ({
+vi.mock('#/lib/connection/health', async (importOriginal) => ({
...(await importOriginal<object>()),
fetchServerHealth: health,
}))
@@ -15,10 +19,45 @@ vi.mock('@tanstack/react-router', () => ({
}))
afterEach(() => {
cleanup()
+ health.mockReset()
localStorage.removeItem('ov_console_connection')
window.history.replaceState(null, '', '/')
})
+it('does not show filesystem data cached for the previous user after re-entering from config', () => {
+ const queryClient = new QueryClient()
+ const key = ['viking-fs-ls', 'viking://', {}]
+ queryClient.setQueryData(key, 'previous-user-files')
+ localStorage.setItem(
+ 'ov_console_connection',
+ JSON.stringify({
+ baseUrl: 'https://current-ov.example',
+ accountId: 'default',
+ userId: 'new-user',
+ apiKey: 'new-user-key',
+ adminApiKey: '',
+ }),
+ )
+ health.mockImplementation(() => new Promise(() => {}))
+ function Filesystem() {
+ const { data } = useQuery({
+ queryKey: key,
+ queryFn: () => new Promise<string>(() => {}),
+ staleTime: 30_000,
+ })
+ return <output data-testid="files">{data ?? 'loading'}</output>
+ }
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AppConnectionProvider>
+ <Filesystem />
+ </AppConnectionProvider>
+ </QueryClientProvider>,
+ )
+ expect(screen.getByTestId('files').textContent).toBe('loading')
+ queryClient.clear()
+})
+
it('discovers the Studio gateway origin before using a stale saved Base URL or key', async () => {
window.history.replaceState(null, '', '/studio/')
localStorage.setItem(
@@ -63,6 +102,7 @@ it('discovers the Studio gateway origin before using a stale saved Base URL or k
expect(state.isGatewayHost).toBe(true)
expect(state.connection).toEqual({
baseUrl: window.location.origin,
+ serviceSelection: 'opensource',
accountId: 'default',
userId: 'default',
apiKey: '',
diff --git a/web-studio/src/hooks/use-app-connection.test.ts b/web-studio/src/hooks/use-app-connection.test.ts
index c3fe5a347..d981cfcd2 100644
--- a/web-studio/src/hooks/use-app-connection.test.ts
+++ b/web-studio/src/hooks/use-app-connection.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import {
createConnectionError,
+ createConnectionHealthHeaders,
createManagementAccountConnection,
createIdentityScopeKey,
createConnectionRoleProbeKey,
@@ -279,6 +280,7 @@ describe('synchronizeConnectionRuntime', () => {
)
expect(next).toEqual({
+ serviceSelection: 'auto',
accountId: 'account-b',
adminApiKey: 'root-key',
apiKey: 'account-b-user-key',
@@ -293,6 +295,25 @@ describe('synchronizeConnectionRuntime', () => {
userId: 'bob',
})
})
+
+ it('passes the selected identity to a keyless development service', () => {
+ synchronizeConnectionRuntime(
+ {
+ serviceSelection: 'opensource',
+ accountId: 'work-memory',
+ userId: 'alice',
+ apiKey: '',
+ adminApiKey: '',
+ baseUrl: 'http://127.0.0.1:1933',
+ },
+ 'dev',
+ )
+ expect(ovClient.getConnection()).toMatchObject({
+ accountId: 'work-memory',
+ userId: 'alice',
+ identityHeaders: true,
+ })
+ })
})
describe('resolveConnectionRoleProbeState', () => {
@@ -377,3 +398,46 @@ describe('shouldRedirectToLoginOnApiError', () => {
).toBe(false)
})
})
+
+describe('connection credential planes', () => {
+ it('uses the hosted data credential even when a source control credential remains configured', () => {
+ const connection = {
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ apiKey: 'user-key',
+ adminApiKey: 'expired-control-key',
+ accountId: 'old-account',
+ userId: 'old-user',
+ }
+ expect(createConnectionHealthHeaders(connection, 'data')).toEqual({
+ Authorization: 'Bearer user-key',
+ })
+ expect(createConnectionHealthHeaders(connection, 'control')).toEqual({
+ Authorization: 'Bearer user-key',
+ })
+ expect(
+ createConnectionHealthHeaders({ ...connection, apiKey: '' }, 'data'),
+ ).toEqual({})
+ })
+ it('drops identity assertions when a custom domain is explicitly selected as hosted', () => {
+ const connection = {
+ baseUrl: 'https://proxy.example/openviking',
+ serviceSelection: 'volcengine' as const,
+ apiKey: 'user-key',
+ adminApiKey: '',
+ accountId: 'old-account',
+ userId: 'old-user',
+ }
+ expect(createConnectionHealthHeaders(connection, 'data')).toEqual({
+ Authorization: 'Bearer user-key',
+ })
+ expect(
+ createConnectionHealthHeaders(
+ { ...connection, serviceSelection: 'opensource' },
+ 'data',
+ ),
+ ).toMatchObject({
+ 'X-OpenViking-Account': 'old-account',
+ 'X-OpenViking-User': 'old-user',
+ })
+ })
+})
diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsx
index 5fde6df61..4e8afe326 100644
--- a/web-studio/src/hooks/use-app-connection.tsx
+++ b/web-studio/src/hooks/use-app-connection.tsx
@@ -1,27 +1,40 @@
+import {
+ resolveApiKeyAuth,
+ createConnectionHealthHeaders,
+} from '#/lib/connection/auth'
import * as React from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useNavigate, useRouterState } from '@tanstack/react-router'
import i18n from '#/i18n'
+import { identifyServiceProvider } from '#/lib/studio-service'
import { fetchAdminAccounts } from '#/lib/admin'
import { isOvClientError, ovClient } from '#/lib/ov-client'
+import {
+ readConnectionProfiles,
+ persistConnectionProfiles,
+ updateActiveProfile,
+ normalizeProfileConnection,
+ isValidConnectionUrl,
+} from '#/lib/connection/profiles'
+import type {
+ ConnectionProfile,
+ ConnectionProfiles,
+} from '#/lib/connection/profiles'
import {
- isServerAuthMode,
+ resolveServerAuthMode,
+ resetServerHealthCache,
fetchServerHealth,
normalizeBaseUrl,
-} from './use-server-mode'
-import type { ServerMode } from './use-server-mode'
+ readServerIdentity,
+} from '#/lib/connection/health'
+import type { ServerMode } from '#/lib/connection/health'
-export type ConnectionRole = 'admin' | 'root' | 'unknown' | 'user'
+import type { ConnectionDraft, ConnectionRole } from '#/lib/connection/types'
-export type ConnectionDraft = {
- accountId: string
- adminApiKey: string
- apiKey: string
- baseUrl: string
- userId: string
-}
+export type { ConnectionDraft, ConnectionRole } from '#/lib/connection/types'
+export { createConnectionHealthHeaders } from '#/lib/connection/auth'
export type ConnectionIdentitySummary = {
labelKey: string
@@ -37,6 +50,11 @@ export type GeneratedCredential = {
}
type AppConnectionContextValue = {
+ profiles: Array<ConnectionProfile>
+ activeProfileId: string
+ saveProfile: (profile: ConnectionProfile) => void
+ activateProfile: (id: string) => void
+ deleteProfile: (id: string) => void
clearGeneratedCredential: () => void
connection: ConnectionDraft
connectionRole: ConnectionRole
@@ -46,6 +64,8 @@ type AppConnectionContextValue = {
isGatewayHost: boolean
openvikingUrl: string
openConnectionSettings: () => void
+ reconnect: () => void
+ serverHealth: Record<string, unknown> | null
saveConnection: (next: ConnectionDraft) => void
setGeneratedCredential: (credential: GeneratedCredential) => void
serverMode: ServerMode
@@ -70,6 +90,12 @@ export function createConnectionError(key: ConnectionErrorKey): Error {
return new Error(i18n.t(`connection:errors.${key}`))
}
+function connectionChangedError(): Error & { code: 'connectionChanged' } {
+ return Object.assign(new Error(i18n.t('studio:profiles.connectionChanged')), {
+ code: 'connectionChanged' as const,
+ })
+}
+
const ENV_BASE_URL =
typeof import.meta.env.VITE_OV_BASE_URL === 'string'
? import.meta.env.VITE_OV_BASE_URL.trim()
@@ -153,6 +179,11 @@ function normalizeConnectionDraft(
connection: ConnectionDraft,
): ConnectionDraft {
return {
+ serviceSelection:
+ connection.serviceSelection === 'opensource' ||
+ connection.serviceSelection === 'volcengine'
+ ? connection.serviceSelection
+ : 'auto',
accountId: connection.accountId.trim(),
adminApiKey: connection.adminApiKey.trim(),
apiKey: connection.apiKey.trim(),
@@ -182,6 +213,7 @@ export function createIdentityScopeKey(
const dataKey = connection.apiKey || connection.adminApiKey
return [
normalizeBaseUrl(connection.baseUrl),
+ connection.serviceSelection ?? 'auto',
serverMode,
connection.accountId,
connection.userId,
@@ -195,6 +227,7 @@ export function createConnectionRoleProbeKey(
): string {
return [
normalizeBaseUrl(connection.baseUrl),
+ connection.serviceSelection ?? 'auto',
serverMode,
connection.accountId,
connection.userId,
@@ -274,12 +307,16 @@ function applyConnection(
): void {
ovClient.setOptions({
baseUrl: connection.baseUrl,
+ apiKeyAuth: resolveApiKeyAuth(
+ connection.baseUrl,
+ connection.serviceSelection,
+ ),
})
ovClient.setConnection({
accountId: connection.accountId,
adminApiKey: connection.adminApiKey,
apiKey: connection.apiKey,
- identityHeaders: serverMode === 'trusted',
+ identityHeaders: serverMode === 'trusted' || serverMode === 'dev',
userId: connection.userId,
})
}
@@ -303,30 +340,12 @@ type ConnectionIdentity = {
userId: string
}
-function createConnectionHealthHeaders(
- connection: ConnectionDraft,
- credential: 'control' | 'data' = 'control',
-): Record<string, string> {
- const headers: Record<string, string> = {}
- const apiKey =
- credential === 'data'
- ? connection.apiKey || connection.adminApiKey
- : connection.adminApiKey || connection.apiKey
- if (!apiKey) {
- return headers
- }
- headers['X-API-Key'] = apiKey
- if (connection.accountId) {
- headers['X-OpenViking-Account'] = connection.accountId
- }
- if (connection.userId) {
- headers['X-OpenViking-User'] = connection.userId
- }
- return headers
-}
-
async function canListAccounts(connection: ConnectionDraft): Promise<boolean> {
- if (!connection.adminApiKey) {
+ if (
+ !connection.adminApiKey ||
+ identifyServiceProvider(connection.baseUrl) === 'volcengine' ||
+ connection.serviceSelection === 'volcengine'
+ ) {
return false
}
@@ -368,9 +387,8 @@ async function detectConnectionIdentity(
: healthRole
return {
- accountId: typeof data.account_id === 'string' ? data.account_id : '',
+ ...readServerIdentity(data),
role,
- userId: typeof data.user_id === 'string' ? data.user_id : '',
}
}
@@ -502,6 +520,8 @@ export function AppConnectionProvider({
}) {
const queryClient = useQueryClient()
const authPromptSuppressedUntilRef = React.useRef(0)
+ const connectionRevisionRef = React.useRef(0)
+ const connectionGenerationRef = React.useRef(0)
const hostDiscoveryRef = React.useRef<Promise<Record<
string,
unknown
@@ -511,15 +531,32 @@ export function AppConnectionProvider({
select: (state) => state.location.pathname,
})
const initialConnectionRef = React.useRef<ConnectionDraft | null>(null)
+ const profilesRef = React.useRef<ConnectionProfiles | null>(null)
const synchronizedRoleProbeRef = React.useRef<{
key: string
role: ConnectionRole
} | null>(null)
if (initialConnectionRef.current === null) {
- initialConnectionRef.current = readInitialConnection()
+ // The provider remounts after /config. Filesystem query keys are shared
+ // across profiles, so discard results fetched under the previous identity
+ // before any workspace route can read them.
+ queryClient.clear()
+ profilesRef.current = readConnectionProfiles(readInitialConnection())
+ initialConnectionRef.current = normalizeConnectionDraft(
+ profilesRef.current.profiles.find(
+ (p) => p.id === profilesRef.current!.activeId,
+ )!.connection,
+ )
applyConnection(initialConnectionRef.current, 'checking')
}
+ const [profileState, setProfileState] = React.useState(profilesRef.current!)
+ const storeProfiles = React.useCallback((next: ConnectionProfiles) => {
+ profilesRef.current = next
+ persistConnectionProfiles(next)
+ setProfileState(next)
+ }, [])
+
const [connection, setConnection] = React.useState<ConnectionDraft>(
initialConnectionRef.current,
)
@@ -534,6 +571,24 @@ export function AppConnectionProvider({
),
)
const [serverMode, setServerMode] = React.useState<ServerMode>('checking')
+ const [serverHealth, setServerHealth] = React.useState<{
+ key: string
+ data: Record<string, unknown>
+ } | null>(null)
+ const [connectionAttempt, setConnectionAttempt] = React.useState(0)
+ const reconnect = React.useCallback(() => {
+ connectionRevisionRef.current += 1
+ authPromptSuppressedUntilRef.current =
+ Date.now() + AUTH_PROMPT_SUPPRESSION_MS
+ synchronizedRoleProbeRef.current = null
+ resetServerHealthCache()
+ setServerHealth(null)
+ setServerMode('checking')
+ setConnectionRole('unknown')
+ setConnectionRoleLoading(true)
+ queryClient.clear()
+ setConnectionAttempt((attempt) => attempt + 1)
+ }, [queryClient])
const [isGatewayHost, setIsGatewayHost] = React.useState(false)
const [openvikingUrl, setOpenvikingUrl] = React.useState('')
const [generatedCredential, setGeneratedCredential] =
@@ -550,11 +605,16 @@ export function AppConnectionProvider({
persistConnection(connection)
}, [connection, serverMode])
+ React.useEffect(() => {
+ storeProfiles(updateActiveProfile(profilesRef.current!, connection))
+ }, [connection, storeProfiles])
+
React.useEffect(() => {
let cancelled = false
const isCancelled = () => cancelled
setServerMode('checking')
+ setServerHealth(null)
void (async () => {
// A standalone Studio is bound to the gateway serving /studio. Discover
// that host without forwarding credentials saved for another server.
@@ -576,6 +636,7 @@ export function AppConnectionProvider({
const next = synchronizeConnectionRuntime(
{
...connection,
+ serviceSelection: 'opensource',
baseUrl: window.location.origin,
apiKey: '',
adminApiKey: '',
@@ -585,6 +646,7 @@ export function AppConnectionProvider({
'checking',
)
queryClient.clear()
+ connectionGenerationRef.current += 1
setConnection(next)
return
}
@@ -594,7 +656,7 @@ export function AppConnectionProvider({
// The gateway answers an invalid OV key with health minus identity.
health = await fetchServerHealth(
connection.baseUrl,
- createConnectionHealthHeaders(connection),
+ createConnectionHealthHeaders(connection, 'data'),
)
} catch {
if (!isCancelled()) setServerMode('offline')
@@ -607,9 +669,26 @@ export function AppConnectionProvider({
? health.openviking_url
: '',
)
- setServerMode(
- isServerAuthMode(health.auth_mode) ? health.auth_mode : 'api_key',
- )
+ const mode = resolveServerAuthMode(health)
+ const resolved = synchronizeResolvedDataIdentity(connection, {
+ accountId:
+ typeof health.account_id === 'string' ? health.account_id : '',
+ userId: typeof health.user_id === 'string' ? health.user_id : '',
+ role: isConnectionRole(health.role) ? health.role : 'unknown',
+ })
+ const next = resolved
+ ? synchronizeConnectionRuntime(resolved, mode)
+ : connection
+ if (resolved) {
+ queryClient.clear()
+ connectionGenerationRef.current += 1
+ setConnection(next)
+ }
+ setServerHealth({
+ key: createConnectionRoleProbeKey(next, 'checking'),
+ data: health,
+ })
+ setServerMode(mode)
}
})()
@@ -621,7 +700,9 @@ export function AppConnectionProvider({
connection.adminApiKey,
connection.apiKey,
connection.baseUrl,
+ connection.serviceSelection,
connection.userId,
+ connectionAttempt,
queryClient,
])
@@ -655,37 +736,16 @@ export function AppConnectionProvider({
}
void detectConnectionIdentity(connection)
+ .catch(() => ({
+ accountId: '',
+ role: 'unknown' as const,
+ userId: '',
+ }))
.then(async (controlIdentity) => {
if (isCancelled()) {
return
}
- const dataIdentity =
- connection.apiKey &&
- (controlIdentity.role === 'root' ||
- (controlIdentity.role === 'admin' &&
- controlIdentity.accountId === connection.accountId))
- ? await detectConnectionIdentity(connection, 'data')
- : !connection.adminApiKey
- ? controlIdentity
- : null
- if (isCancelled()) {
- return
- }
-
const { accountId, role } = controlIdentity
- const dataConnection = dataIdentity
- ? synchronizeResolvedDataIdentity(connection, dataIdentity)
- : null
- if (dataConnection) {
- const next = synchronizeConnectionRuntime(dataConnection, serverMode)
- synchronizedRoleProbeRef.current = {
- key: createConnectionRoleProbeKey(next, serverMode),
- role,
- }
- queryClient.clear()
- setConnection(next)
- return
- }
// An account-admin Root key is scoped to its own account. Pin that
// account as the assumed identity so admin and data calls target the
// right tenant instead of failing with a mismatch (the server rejects
@@ -693,6 +753,8 @@ export function AppConnectionProvider({
// key is not account-scoped, so its account selection is left intact.
if (
role === 'admin' &&
+ (!connection.apiKey ||
+ connection.apiKey === connection.adminApiKey) &&
accountId &&
connection.accountId !== accountId
) {
@@ -705,6 +767,7 @@ export function AppConnectionProvider({
role,
}
queryClient.clear()
+ connectionGenerationRef.current += 1
setConnection(next)
return
}
@@ -726,6 +789,7 @@ export function AppConnectionProvider({
connection.adminApiKey,
connection.apiKey,
connection.baseUrl,
+ connection.serviceSelection,
connection.userId,
queryClient,
serverMode,
@@ -751,7 +815,20 @@ export function AppConnectionProvider({
}, [openConnectionSettings])
const value = React.useMemo<AppConnectionContextValue>(() => {
+ const sourceGeneration = connectionGenerationRef.current
+ const sourceProfileId = profileState.activeId
+ const assertSourceConnection = () => {
+ if (
+ sourceGeneration !== connectionGenerationRef.current ||
+ sourceProfileId !== profilesRef.current?.activeId
+ ) {
+ throw connectionChangedError()
+ }
+ }
+
const commitConnection = (next: ConnectionDraft) => {
+ connectionGenerationRef.current += 1
+ connectionRevisionRef.current += 1
authPromptSuppressedUntilRef.current =
Date.now() + AUTH_PROMPT_SUPPRESSION_MS
const normalized = synchronizeConnectionRuntime(next, serverMode)
@@ -759,17 +836,79 @@ export function AppConnectionProvider({
setConnection(normalized)
}
+ const activateConnection = (next: ConnectionDraft) => {
+ connectionGenerationRef.current += 1
+ // Apply the new credentials before any new route effects can issue requests.
+ const normalized = synchronizeConnectionRuntime(next, 'checking')
+ reconnect()
+ setGeneratedCredential(null)
+ setConnection(normalized)
+ }
+
return {
+ profiles: profileState.profiles,
+ activeProfileId: profileState.activeId,
+ saveProfile: (profile) => {
+ if (!isValidConnectionUrl(profile.connection.baseUrl))
+ throw new Error(i18n.t('studio:profiles.invalidUrl'))
+ const normalized = {
+ ...profile,
+ name: profile.name.trim(),
+ connection: normalizeConnectionDraft(
+ normalizeProfileConnection(profile.connection),
+ ),
+ }
+ const current = profilesRef.current!
+ const exists = current.profiles.some((p) => p.id === profile.id)
+ storeProfiles({
+ ...current,
+ profiles: exists
+ ? current.profiles.map((p) =>
+ p.id === profile.id ? normalized : p,
+ )
+ : [...current.profiles, normalized],
+ })
+ if (profile.id === current.activeId)
+ activateConnection(normalized.connection)
+ },
+ activateProfile: (id) => {
+ const current = profilesRef.current!
+ const profile = current.profiles.find((p) => p.id === id)
+ if (!profile || id === current.activeId) return
+ storeProfiles({ ...current, activeId: id })
+ activateConnection(profile.connection)
+ },
+ deleteProfile: (id) => {
+ const current = profilesRef.current!
+ if (id === current.activeId) return
+ storeProfiles({
+ ...current,
+ profiles: current.profiles.filter((p) => p.id !== id),
+ })
+ },
clearGeneratedCredential: () => setGeneratedCredential(null),
connection,
connectionRole,
generatedCredential,
- identityScopeKey: createIdentityScopeKey(connection, serverMode),
+ identityScopeKey:
+ profileState.activeId +
+ '\u0000' +
+ createIdentityScopeKey(connection, serverMode),
isConnectionRoleLoading,
isGatewayHost,
openvikingUrl,
openConnectionSettings,
- saveConnection: commitConnection,
+ reconnect,
+ serverHealth:
+ serverHealth?.key ===
+ createConnectionRoleProbeKey(connection, 'checking')
+ ? serverHealth.data
+ : null,
+ saveConnection: (next) => {
+ if (!isValidConnectionUrl(next.baseUrl))
+ throw new Error(i18n.t('studio:profiles.invalidUrl'))
+ commitConnection(normalizeProfileConnection(next))
+ },
setGeneratedCredential,
serverMode,
switchIdentity: async ({
@@ -778,10 +917,18 @@ export function AppConnectionProvider({
apiKey,
userId,
}) => {
+ assertSourceConnection()
if (serverMode === 'dev' || serverMode === 'checking') {
throw createConnectionError('identitySwitchUnsupported')
}
+ const revision = ++connectionRevisionRef.current
+ const assertCurrentConnection = () => {
+ assertSourceConnection()
+ if (revision !== connectionRevisionRef.current)
+ throw connectionChangedError()
+ }
+
const requested = normalizeConnectionDraft({
...connection,
accountId,
@@ -789,6 +936,7 @@ export function AppConnectionProvider({
userId,
})
const identity = await detectConnectionIdentity(requested, 'data')
+ assertCurrentConnection()
const resolvedIdentity = resolveSwitchedIdentity(
requested,
identity,
@@ -798,6 +946,9 @@ export function AppConnectionProvider({
throw createConnectionError('credentialMismatch')
}
+ if (pathname === '/directory' || pathname === '/memories') {
+ await navigate({ replace: true, to: pathname })
+ }
if (pathname === '/filesystem') {
await navigate({
replace: true,
@@ -805,12 +956,14 @@ export function AppConnectionProvider({
to: '/filesystem',
})
}
+ assertCurrentConnection()
commitConnection({
...requested,
...resolvedIdentity,
})
},
switchManagementAccount: async (accountId) => {
+ assertSourceConnection()
if (connectionRole !== 'root') {
throw createConnectionError('rootRequired')
}
@@ -825,6 +978,8 @@ export function AppConnectionProvider({
}
}, [
connection,
+ profileState,
+ storeProfiles,
connectionRole,
generatedCredential,
isConnectionRoleLoading,
@@ -834,6 +989,8 @@ export function AppConnectionProvider({
openConnectionSettings,
pathname,
queryClient,
+ reconnect,
+ serverHealth,
serverMode,
])
diff --git a/web-studio/src/hooks/use-connection-probe.ts b/web-studio/src/hooks/use-connection-probe.ts
new file mode 100644
index 000000000..49decdc38
--- /dev/null
+++ b/web-studio/src/hooks/use-connection-probe.ts
@@ -0,0 +1,24 @@
+import { keepPreviousData, useQuery } from '@tanstack/react-query'
+import { probeConnection } from '#/lib/connection/probe'
+import { useAppConnection } from './use-app-connection'
+
+export function useConnectionProbe() {
+ const { connection, serverMode } = useAppConnection()
+ return useQuery({
+ enabled: Boolean(connection.baseUrl) && serverMode !== 'checking',
+ placeholderData: keepPreviousData,
+ queryFn: () => probeConnection(connection, serverMode),
+ queryKey: [
+ 'studio-connection-probe',
+ connection.serviceSelection,
+ connection.baseUrl,
+ connection.adminApiKey,
+ connection.apiKey,
+ connection.accountId,
+ connection.userId,
+ serverMode,
+ ],
+ retry: false,
+ staleTime: 15_000,
+ })
+}
diff --git a/web-studio/src/hooks/use-connection-profiles.test.tsx b/web-studio/src/hooks/use-connection-profiles.test.tsx
new file mode 100644
index 000000000..321f02b4c
--- /dev/null
+++ b/web-studio/src/hooks/use-connection-profiles.test.tsx
@@ -0,0 +1,296 @@
+// @vitest-environment jsdom
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ act,
+} from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, expect, it, vi } from 'vitest'
+import { AppConnectionProvider, useAppConnection } from './use-app-connection'
+import { ovClient } from '#/lib/ov-client'
+import { PROFILES_STORAGE_KEY } from '#/lib/connection/profiles'
+import type * as ServerModeModule from '#/lib/connection/health'
+
+const { health } = vi.hoisted(() => ({ health: vi.fn() }))
+vi.mock('@tanstack/react-router', () => ({
+ useNavigate: () => vi.fn(),
+ useRouterState: () => '/settings',
+}))
+vi.mock('#/lib/connection/health', async (original) => ({
+ ...(await original<typeof ServerModeModule>()),
+ fetchServerHealth: health,
+}))
+afterEach(() => {
+ cleanup()
+ localStorage.clear()
+ health.mockReset()
+})
+const source = {
+ baseUrl: 'http://10.0.0.1:1933',
+ serviceSelection: 'opensource' as const,
+ accountId: 'default',
+ userId: 'alice',
+ apiKey: 'source-key',
+ adminApiKey: '',
+}
+function Controls() {
+ const value = useAppConnection()
+ return (
+ <>
+ <output>
+ {JSON.stringify({
+ id: value.activeProfileId,
+ mode: value.serverMode,
+ health: value.serverHealth,
+ connection: value.connection,
+ })}
+ </output>
+ <button
+ onClick={() =>
+ value.saveProfile({
+ id: 'cloud',
+ name: 'Cloud',
+ connection: {
+ ...source,
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ serviceSelection: 'volcengine',
+ apiKey: 'cloud-key',
+ },
+ })
+ }
+ >
+ add
+ </button>
+ <button onClick={() => value.activateProfile('cloud')}>cloud</button>
+ <button onClick={() => value.activateProfile('default')}>source</button>
+ <button onClick={() => value.deleteProfile('default')}>
+ delete active
+ </button>
+ </>
+ )
+}
+function mount(client: QueryClient) {
+ return render(
+ <QueryClientProvider client={client}>
+ <AppConnectionProvider>
+ <Controls />
+ </AppConnectionProvider>
+ </QueryClientProvider>,
+ )
+}
+it('saves without activation, switches credentials, clears cache and restores the enabled profile on reload', async () => {
+ localStorage.setItem('ov_console_connection', JSON.stringify(source))
+ health.mockImplementation(async (_url, headers) => ({
+ auth_mode: 'api_key',
+ version: '0.5.1',
+ role: 'user',
+ account_id: 'default',
+ user_id: headers.Authorization ? 'cloud-user' : 'alice',
+ }))
+ const client = new QueryClient()
+ const view = mount(client)
+ await waitFor(() =>
+ expect(document.querySelector('output')!.textContent).toContain(
+ '"mode":"api_key"',
+ ),
+ )
+ fireEvent.click(screen.getByText('delete active'))
+ expect(
+ JSON.parse(localStorage.getItem(PROFILES_STORAGE_KEY)!).profiles,
+ ).toHaveLength(1)
+ fireEvent.click(screen.getByText('add'))
+ expect(ovClient.getOptions().apiKeyAuth).toBe('header')
+ client.setQueryData(['old-files'], ['private-file'])
+ fireEvent.click(screen.getByText('cloud'))
+ expect(ovClient.getOptions().apiKeyAuth).toBe('bearer')
+ expect(ovClient.getConnection().apiKey).toBe('cloud-key')
+ expect(client.getQueryData(['old-files'])).toBeUndefined()
+ await waitFor(() =>
+ expect(document.querySelector('output')!.textContent).toContain(
+ 'cloud-user',
+ ),
+ )
+ expect(health).toHaveBeenCalledWith(
+ 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ { Authorization: 'Bearer cloud-key' },
+ )
+ view.unmount()
+ mount(client)
+ await waitFor(() =>
+ expect(document.querySelector('output')!.textContent).toContain(
+ '"id":"cloud"',
+ ),
+ )
+ fireEvent.click(screen.getByText('source'))
+ await waitFor(() =>
+ expect(ovClient.getConnection().apiKey).toBe('source-key'),
+ )
+ expect(ovClient.getOptions().apiKeyAuth).toBe('header')
+ client.clear()
+})
+it('ignores an old pending health response after another profile is enabled', async () => {
+ localStorage.setItem('ov_console_connection', JSON.stringify(source))
+ let resolveOld!: (value: unknown) => void
+ health.mockImplementation((url) =>
+ url === source.baseUrl
+ ? new Promise((resolve) => {
+ resolveOld = resolve
+ })
+ : Promise.resolve({ auth_mode: 'api_key', version: 'cloud' }),
+ )
+ const client = new QueryClient()
+ mount(client)
+ fireEvent.click(screen.getByText('add'))
+ fireEvent.click(screen.getByText('cloud'))
+ await waitFor(() =>
+ expect(document.querySelector('output')!.textContent).toContain(
+ '"version":"cloud"',
+ ),
+ )
+ await act(async () =>
+ resolveOld({
+ auth_mode: 'trusted',
+ version: 'old',
+ role: 'user',
+ account_id: 'old-account',
+ user_id: 'old-user',
+ }),
+ )
+ expect(document.querySelector('output')!.textContent).not.toContain(
+ 'old-user',
+ )
+ expect(document.querySelector('output')!.textContent).not.toContain(
+ '"mode":"trusted"',
+ )
+ client.clear()
+})
+
+it('a pending identity switch must not overwrite a newly enabled profile', async () => {
+ localStorage.setItem('ov_console_connection', JSON.stringify(source))
+ let resolveSwitch!: (value: unknown) => void
+ health.mockImplementation((_url, headers) =>
+ headers['X-API-Key'] === 'bob-key'
+ ? new Promise((resolve) => {
+ resolveSwitch = resolve
+ })
+ : Promise.resolve({
+ auth_mode: 'api_key',
+ version: '0.5.1',
+ role: 'user',
+ account_id: 'default',
+ user_id: headers.Authorization ? 'cloud-user' : 'alice',
+ }),
+ )
+ let api!: ReturnType<typeof useAppConnection>
+ function Capture() {
+ api = useAppConnection()
+ return null
+ }
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <AppConnectionProvider>
+ <Capture />
+ </AppConnectionProvider>
+ </QueryClientProvider>,
+ )
+ await waitFor(() => expect(api.serverMode).toBe('api_key'))
+ let switching!: Promise<void | Error>
+ await act(async () => {
+ switching = api
+ .switchIdentity({
+ accountId: 'default',
+ userId: 'bob',
+ apiKey: 'bob-key',
+ })
+ .catch((error: Error) => error)
+ })
+ await act(async () => {
+ api.saveProfile({
+ id: 'cloud',
+ name: 'Cloud',
+ connection: {
+ ...source,
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ serviceSelection: 'volcengine',
+ apiKey: 'cloud-key',
+ },
+ })
+ api.activateProfile('cloud')
+ })
+ await waitFor(() => expect(api.connection.apiKey).toBe('cloud-key'))
+ await act(async () => {
+ resolveSwitch({
+ auth_mode: 'api_key',
+ role: 'user',
+ account_id: 'default',
+ user_id: 'bob',
+ })
+ await switching
+ })
+ expect(await switching).toBeInstanceOf(Error)
+ expect(api.activeProfileId).toBe('cloud')
+ expect(api.connection.apiKey).toBe('cloud-key')
+ client.clear()
+})
+
+it('rejects an identity switch started by an obsolete profile callback', async () => {
+ localStorage.setItem('ov_console_connection', JSON.stringify(source))
+ health.mockImplementation(async (_url, headers) => ({
+ auth_mode: 'api_key',
+ version: '0.5.1',
+ role: 'user',
+ account_id: 'default',
+ user_id: headers.Authorization ? 'cloud-user' : 'alice',
+ }))
+ let api!: ReturnType<typeof useAppConnection>
+ function Capture() {
+ api = useAppConnection()
+ return null
+ }
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <AppConnectionProvider>
+ <Capture />
+ </AppConnectionProvider>
+ </QueryClientProvider>,
+ )
+ await waitFor(() => expect(api.serverMode).toBe('api_key'))
+ const oldSwitchIdentity = api.switchIdentity
+ await act(async () => {
+ api.saveProfile({
+ id: 'cloud',
+ name: 'Cloud',
+ connection: {
+ ...source,
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ serviceSelection: 'volcengine',
+ apiKey: 'cloud-key',
+ },
+ })
+ api.activateProfile('cloud')
+ })
+ await waitFor(() => expect(api.connection.apiKey).toBe('cloud-key'))
+ await expect(
+ oldSwitchIdentity({
+ accountId: 'default',
+ userId: 'bob',
+ apiKey: 'bob-key',
+ }),
+ ).rejects.toMatchObject({ code: 'connectionChanged' })
+ expect(api.activeProfileId).toBe('cloud')
+ expect(api.connection.apiKey).toBe('cloud-key')
+ const saved = JSON.parse(localStorage.getItem(PROFILES_STORAGE_KEY)!)
+ expect(
+ saved.profiles.find((profile: { id: string }) => profile.id === 'cloud')
+ .connection.apiKey,
+ ).toBe('cloud-key')
+ expect(
+ health.mock.calls.some(([, headers]) => headers['X-API-Key'] === 'bob-key'),
+ ).toBe(false)
+ client.clear()
+})
diff --git a/web-studio/src/hooks/use-studio-capabilities.test.tsx b/web-studio/src/hooks/use-studio-capabilities.test.tsx
new file mode 100644
index 000000000..91a785b7c
--- /dev/null
+++ b/web-studio/src/hooks/use-studio-capabilities.test.tsx
@@ -0,0 +1,75 @@
+// @vitest-environment jsdom
+import { createServer } from 'node:http'
+import { once } from 'node:events'
+import { cleanup, renderHook, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import type { ReactNode } from 'react'
+import { expect, it, vi } from 'vitest'
+import { useStudioCapabilities } from './use-studio-capabilities'
+import { ovClient } from '#/lib/ov-client'
+
+const state = vi.hoisted(() => ({ url: '' }))
+vi.mock('./use-app-connection', () => ({
+ useAppConnection: () => ({
+ connection: {
+ baseUrl: state.url,
+ apiKey: 'scoped-data-key',
+ adminApiKey: 'control-key',
+ },
+ identityScopeKey: 'snapshot-scope',
+ }),
+}))
+vi.mock('./use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'volcengine' }),
+}))
+
+it('uses the query credential snapshot and verifies contracts even when gateway errors use HTTP 200', async () => {
+ const requests: Array<{ path: string; key: unknown }> = []
+ const server = createServer((req, res) => {
+ res.setHeader('Access-Control-Allow-Origin', '*')
+ res.setHeader('Access-Control-Allow-Headers', '*')
+ if (req.method === 'OPTIONS') {
+ res.end()
+ return
+ }
+ requests.push({ path: req.url!, key: req.headers['x-api-key'] })
+ res.setHeader('Content-Type', 'application/json')
+ res.end(
+ JSON.stringify(
+ req.url === '/api/v1/watches'
+ ? { status: 'ok', result: { tasks: [] } }
+ : req.url === '/api/v1/console/audit'
+ ? { ResponseMetadata: { Error: { Code: 'ApiBlocked' } } }
+ : { message: 'Generic proxy JSON' },
+ ),
+ )
+ })
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ state.url = `http://127.0.0.1:${(server.address() as { port: number }).port}`
+ const originalConnection = ovClient.getConnection()
+ ovClient.setConnection({ apiKey: 'another-connections-key' })
+ const client = new QueryClient()
+ try {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ )
+ const { result } = renderHook(useStudioCapabilities, { wrapper })
+ await waitFor(() => expect(result.current.monitoring?.isSuccess).toBe(true))
+ expect(result.current.watches?.data).toBe('supported')
+ expect(result.current.requestLogs?.data).toBe('unavailable')
+ expect(result.current.monitoring?.data).toBe('unknown')
+ expect(requests).toHaveLength(3)
+ expect(requests.every((request) => request.key === 'scoped-data-key')).toBe(
+ true,
+ )
+ expect(requests.some((request) => /compile|bot/.test(request.path))).toBe(
+ false,
+ )
+ } finally {
+ cleanup()
+ client.clear()
+ ovClient.setConnection(originalConnection)
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+})
diff --git a/web-studio/src/hooks/use-studio-capabilities.ts b/web-studio/src/hooks/use-studio-capabilities.ts
new file mode 100644
index 000000000..9b2364dd4
--- /dev/null
+++ b/web-studio/src/hooks/use-studio-capabilities.ts
@@ -0,0 +1,29 @@
+import { useQueries } from '@tanstack/react-query'
+import { useAppConnection } from './use-app-connection'
+import { useStudioService } from './use-studio-service'
+import { STUDIO_FEATURES } from '#/lib/studio-service'
+import { fetchStudioCapability } from '#/lib/connection/capabilities'
+
+// Only inexpensive, object-free GETs. Do not probe writes, imports, or search.
+export function useStudioCapabilities() {
+ const { connection, identityScopeKey } = useAppConnection()
+ const service = useStudioService()
+ const features = STUDIO_FEATURES.filter((f) => 'probe' in f)
+ const results = useQueries({
+ queries: features.map((feature) => ({
+ queryKey: ['studio-feature', identityScopeKey, feature.id],
+ enabled: service.ready && service.provider === 'volcengine',
+ queryFn: async ({ signal }: { signal: AbortSignal }) => {
+ return fetchStudioCapability(connection, feature, signal)
+ },
+ retry: false,
+ staleTime: 60_000,
+ })),
+ })
+ const capabilities: Partial<
+ Record<(typeof STUDIO_FEATURES)[number]['id'], (typeof results)[number]>
+ > = Object.fromEntries(
+ features.map((feature, index) => [feature.id, results[index]]),
+ )
+ return capabilities
+}
diff --git a/web-studio/src/hooks/use-studio-service.test.tsx b/web-studio/src/hooks/use-studio-service.test.tsx
new file mode 100644
index 000000000..19699f606
--- /dev/null
+++ b/web-studio/src/hooks/use-studio-service.test.tsx
@@ -0,0 +1,63 @@
+// @vitest-environment jsdom
+import { cleanup, renderHook } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+import { useStudioService } from './use-studio-service'
+
+const state = vi.hoisted(() => ({
+ selection: 'auto',
+ url: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ mode: 'api_key',
+ health: null as Record<string, unknown> | null,
+}))
+vi.mock('./use-app-connection', () => ({
+ useAppConnection: () => ({
+ connection: { baseUrl: state.url, serviceSelection: state.selection },
+ serverMode: state.mode,
+ serverHealth: state.health,
+ }),
+}))
+afterEach(() => {
+ cleanup()
+ state.selection = 'auto'
+ state.url = 'https://api.vikingdb.cn-beijing.volces.com/openviking'
+ state.mode = 'api_key'
+ state.health = null
+})
+it('recognizes an authenticated private deployment without enabling it while offline', () => {
+ state.url = 'http://10.37.244.186:8020'
+ const view = renderHook(useStudioService)
+ expect(view.result.current.provider).toBe('unknown')
+ state.health = { auth_mode: 'api_key', version: '0.5.1.dev32' }
+ view.rerender()
+ expect(view.result.current.provider).toBe('opensource')
+ state.mode = 'offline'
+ view.rerender()
+ expect(view.result.current.provider).toBe('unknown')
+})
+it('identifies a hosted deployment from the connection owner health result', () => {
+ const view = renderHook(useStudioService)
+ expect(view.result.current.ready).toBe(false)
+ state.health = { auth_mode: 'api_key', version: 'v0.4.20.6' }
+ view.rerender()
+ expect(view.result.current.provider).toBe('volcengine')
+ expect(view.result.current.version).toBe('v0.4.20.6')
+})
+it('never classifies an offline connection or non-health JSON as ready', () => {
+ state.selection = 'volcengine'
+ state.mode = 'offline'
+ state.health = { version: 'stale' }
+ const view = renderHook(useStudioService)
+ expect(view.result.current.ready).toBe(false)
+ expect(view.result.current.provider).toBe('unknown')
+ state.mode = 'api_key'
+ state.health = { message: 'proxy' }
+ view.rerender()
+ expect(view.result.current.ready).toBe(false)
+})
+it('does not let a manual override turn an official hosted deployment into native management', () => {
+ state.selection = 'opensource'
+ state.health = { auth_mode: 'api_key', version: 'v0.4.20.6' }
+ expect(renderHook(useStudioService).result.current.provider).toBe(
+ 'volcengine',
+ )
+})
diff --git a/web-studio/src/hooks/use-studio-service.ts b/web-studio/src/hooks/use-studio-service.ts
new file mode 100644
index 000000000..4a078e60c
--- /dev/null
+++ b/web-studio/src/hooks/use-studio-service.ts
@@ -0,0 +1,24 @@
+import { isUsableServerHealth } from '#/lib/connection/health'
+import { useAppConnection } from './use-app-connection'
+import { resolveConfiguredServiceProvider } from '#/lib/studio-service'
+
+// The connection provider owns health, auth mode and reconnection as one lifecycle.
+export function useStudioService() {
+ const { connection, serverHealth, serverMode } = useAppConnection()
+ const ready =
+ serverMode !== 'checking' &&
+ serverMode !== 'offline' &&
+ isUsableServerHealth(serverHealth)
+ return {
+ provider: ready
+ ? resolveConfiguredServiceProvider(
+ connection.baseUrl,
+ connection.serviceSelection,
+ )
+ : ('unknown' as const),
+ ready,
+ isChecking: serverMode === 'checking',
+ version:
+ typeof serverHealth?.version === 'string' ? serverHealth.version : '',
+ }
+}
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index 4a4811148..91e11611a 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -1,3 +1,5 @@
+import onboarding from './en/onboarding'
+import studio from './en/studio'
import vikingbot from './en/vikingbot'
import compile from './en/compile'
import memoryPolicy from './en/user-memory-policy'
@@ -8,6 +10,8 @@ import memoryTemplates from './en/memory-templates'
import gateway from './en/gateway'
const en = {
+ studio,
+ onboarding,
gateway,
compile,
vikingbot,
diff --git a/web-studio/src/i18n/locales/en/activity.ts b/web-studio/src/i18n/locales/en/activity.ts
index fc8299435..915904458 100644
--- a/web-studio/src/i18n/locales/en/activity.ts
+++ b/web-studio/src/i18n/locales/en/activity.ts
@@ -23,6 +23,7 @@ const activity = {
shortcut: '⌘ N to create a new session',
},
chat: {
+ emptyReadDescription: 'This session has no messages yet.',
historyLoadFailed: 'Could not load conversation history: {{error}}',
sendFailed: 'Could not send message: {{error}}',
copy: 'Copy',
diff --git a/web-studio/src/i18n/locales/en/onboarding.ts b/web-studio/src/i18n/locales/en/onboarding.ts
new file mode 100644
index 000000000..70bee3caa
--- /dev/null
+++ b/web-studio/src/i18n/locales/en/onboarding.ts
@@ -0,0 +1,63 @@
+export default {
+ connectionTitle: 'Connect your workspace.',
+ preferencesHint: 'Choose your language and appearance.',
+ connectionHint: 'Connect and verify an OpenViking service.',
+
+ verifiedManagement:
+ 'Management access verified. Open Users to create a User API Key.',
+ brand: 'OpenViking Studio',
+ invalidService:
+ 'This address did not return valid OpenViking service information.',
+ keyRequired: 'This service requires an API Key. Enter it and retry.',
+
+ steps: 'Choose a workspace',
+ workspace: 'Choose a workspace',
+ workspaceHint: 'Choose a saved connection or add a new one.',
+ savedWorkspaces: 'Saved connections',
+ connectionChoice: 'Choose a connection',
+ newConnection: 'Add a new service address',
+ savedConnectionUnavailable:
+ 'This saved connection is unavailable. Choose another one or enter a new API Key.',
+ newAddressHint: 'Enter a valid HTTP or HTTPS address to continue.',
+ hostedEndpoint: 'Service address',
+ preferences: 'Preferences',
+ connection: 'Connect a service',
+ welcome: 'Welcome to\nOpenViking Studio',
+ welcomeDescription:
+ 'Choose a saved connection or add a new one, then set your language and appearance.',
+ connectionDescription:
+ 'Configure and verify your connection to open the appropriate workspace and features.',
+ language: 'Language',
+ theme: 'Appearance',
+ light: 'Light',
+ dark: 'Dark',
+ system: 'System',
+ next: 'Next',
+ back: 'Back',
+ verify: 'Verify connection',
+ verifying: 'Verifying…',
+ verified: 'Connection verified',
+ verifyFailed: 'Connection verification failed:',
+ healthRequestFailed: 'Service health check failed:',
+ dataRequestFailed: 'Memory access check failed:',
+ enter: 'Enter Studio',
+ keyHelp:
+ 'Use the API Key provided by your service. Open-source development mode does not require a key.',
+ hostedKeyHelp: 'Enter your Volcengine User API Key to access your memories.',
+ advanced: 'Advanced open-source connection (optional)',
+ loadUsers: 'Load users in this account',
+ loadingUsers: 'Loading users…',
+ chooseUser: 'Choose a user',
+ noUsers:
+ 'No users were found in this account. Check the account ID or enter a user ID manually.',
+ usersDevMode:
+ 'This service is in development mode and does not provide a user list. Enter the account and user IDs manually to access that space.',
+ usersNeedKey:
+ 'This service requires a Root or admin API key to list users. Enter the key and try again.',
+ usersUnavailable:
+ 'Could not load users. Check the management key and account, or enter a user ID manually.',
+ userSelectionHint:
+ 'Use a management key to load users. In dev mode or without management access, enter the account and user IDs manually. API Key mode also requires that user’s key.',
+ storageError:
+ 'Unable to save your connection. Allow local storage for this site and retry.',
+}
diff --git a/web-studio/src/i18n/locales/en/resources.ts b/web-studio/src/i18n/locales/en/resources.ts
index ae5e3c794..1b7296f4e 100644
--- a/web-studio/src/i18n/locales/en/resources.ts
+++ b/web-studio/src/i18n/locales/en/resources.ts
@@ -420,6 +420,8 @@ const resources = {
},
},
filePreview: {
+ editFailed: 'Unable to load the complete file for editing.',
+ saveFailed: 'Unable to save the file.',
directoryLevels: {
abstractLabel: 'Abstract',
overviewLabel: 'Overview',
@@ -478,6 +480,12 @@ const resources = {
},
},
retrieval: {
+ modeDescriptions: {
+ find: 'Find relevant context by meaning for a standalone query.',
+ search: 'Search by meaning, optionally using session context.',
+ grep: 'Match file contents using text or a regular expression.',
+ glob: 'Find files using a path pattern, such as **/*.md.',
+ },
title: 'Retrieval',
searchPlaceholder: 'Search context',
placeholders: {
diff --git a/web-studio/src/i18n/locales/en/studio.ts b/web-studio/src/i18n/locales/en/studio.ts
new file mode 100644
index 000000000..3417cdee3
--- /dev/null
+++ b/web-studio/src/i18n/locales/en/studio.ts
@@ -0,0 +1,132 @@
+const studio = {
+ profiles: {
+ connectionChanged:
+ 'The connection changed. Select the identity again on the active connection.',
+ identityPending: 'Identity unconfirmed',
+ typeHint:
+ 'Select the service type for this profile. Save to apply changes to the active connection.',
+ title: 'Connection profiles',
+ hint: 'Enable one profile to use its service and credentials. To delete the active profile, enable another first.',
+ add: 'Add profile',
+ edit: 'Edit profile',
+ delete: 'Delete',
+ activate: 'Enable',
+ active: 'Active',
+ name: 'Profile name',
+ save: 'Save',
+ cancel: 'Cancel',
+ saveHint:
+ 'Saving a new profile does not enable it. Changes to the active profile reconnect immediately.',
+ invalidUrl:
+ 'Enter a valid HTTP or HTTPS service address without embedded credentials.',
+ deleteConfirm: 'Delete “{{name}}”? Its saved credentials will be removed.',
+ fields: {
+ baseUrl: 'Service address',
+ apiKey: 'User API Key',
+ adminApiKey: 'Management API Key (optional)',
+ accountId: 'Account ID',
+ userId: 'User ID',
+ },
+ },
+
+ selectSessionRecord:
+ 'Select a session from the list to view its conversation history.',
+ noSessionRecords: 'No session records are accessible to this identity.',
+ sessionRecords: 'Session records',
+ processingTasks: 'Processing tasks',
+ backToFiles: 'Back to files',
+ showOverview: 'Show statistics and queues',
+ hideOverview: 'Hide statistics and queues',
+ connectionSummary: {
+ opensource:
+ 'The workspace is configured for an open-source service. Extensions and management require their own configuration and permissions.',
+ volcengine:
+ 'The workspace is configured for a hosted service. Only verified extensions are shown; a user API key does not grant management access.',
+ unknown:
+ 'Available features appear after connection verification. Select a service type for a custom address.',
+ },
+
+ watchesReadDescription:
+ 'View configured synchronization tasks and their status.',
+ watchesReadEmpty:
+ 'There are no synchronization tasks accessible to this identity.',
+ statistics: 'Statistics',
+ listingLimit: 'This view shows up to 500 entries.',
+ directory: 'My directory',
+ memories: 'Memories',
+ domainsLabel: 'Studio areas',
+ domains: {
+ workspace: 'Workspace',
+ extensions: 'Advanced features',
+ management: 'Management',
+ },
+ providers: {
+ opensource: 'Open source',
+ volcengine: 'Volcengine hosted',
+ unknown: 'Service type unconfirmed',
+ checking: 'Checking connection…',
+ },
+ serviceType: 'Service type',
+ auto: 'Detect automatically',
+ serviceHint:
+ 'Automatic detection uses Volcengine for official endpoints and open source for other addresses. For a hosted proxy, select Volcengine hosted. Features appear after connection verification.',
+ cloudManagement:
+ 'Hosted management requires a separate management service. A data key does not enable management.',
+ connectionSettings: 'Connection settings',
+ retry: 'Retry',
+ loading: 'Loading…',
+ empty: 'This directory is empty.',
+ selectFile: 'Select a file to preview its content.',
+ spaces: 'Directory scope',
+ personal: 'My space',
+ shared: 'Shared resources',
+ back: 'Back',
+ readOnly:
+ 'This workspace is read-only. Shared resources remain separate from your personal space.',
+ directoryDescription:
+ 'Browse your personal context and resources shared with you.',
+ directoryError:
+ 'Unable to open this directory. It may be missing or inaccessible to your identity.',
+ states: {
+ gatewayAuthMode: {
+ title: 'Gateway requires API key authentication',
+ description:
+ 'Connect to an open-source service in API key mode using a verified management key. Trusted mode is not supported by Gateway user binding.',
+ },
+ checking: {
+ title: 'Checking availability',
+ description: 'Verifying this connection and its read capabilities.',
+ },
+ connectionFailed: {
+ title: 'Connection could not be verified',
+ description:
+ 'Check the service URL and API key, then retry in connection settings.',
+ },
+ managementRequired: {
+ title: 'Independent management authorization required',
+ description:
+ 'Native management is available for authorized open-source management connections. Hosted management requires a separate backend.',
+ },
+ unknownProvider: {
+ title: 'Confirm the service type',
+ description:
+ 'This custom address has no confirmed provider. Select the service type in connection settings to continue.',
+ },
+ unavailable: {
+ title: 'This service does not expose this feature',
+ description:
+ 'You can continue browsing your directory and other available features.',
+ },
+ forbidden: {
+ title: 'Your identity cannot access this feature',
+ description:
+ 'This connection does not grant the required read permission.',
+ },
+ unknown: {
+ title: 'Availability is not confirmed',
+ description:
+ 'The extension contract has not been verified for this connection. Your workspace remains available.',
+ },
+ },
+} as const
+export default studio
diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.ts
index 0eeb430c5..87dc0853f 100644
--- a/web-studio/src/i18n/locales/en/workspace.ts
+++ b/web-studio/src/i18n/locales/en/workspace.ts
@@ -12,9 +12,11 @@ const workspace = {
users: 'Users & Permissions',
},
header: {
+ backToConfig: 'Back to workspace setup',
+ chooseWorkspace: 'Choose workspace',
currentUser: {
- account: 'Account',
- accountSummary: 'Account · {{account}}',
+ account: 'Space',
+ accountSummary: 'Space · {{account}}',
keyUnavailable: 'User key unavailable',
loadingUsers: 'Loading users',
loadUsersFailed: 'Failed to load users',
@@ -92,6 +94,7 @@ const workspace = {
loading: 'Loading monitoring data...',
loadFailed: 'Could not load monitoring data',
health: {
+ unknown: 'No data',
healthy: 'Healthy',
unhealthy: 'Unhealthy',
},
@@ -349,6 +352,34 @@ const workspace = {
title: 'Skills',
description:
'View Agent skills available to the current user and workspace.',
+ add: {
+ title: 'Add Skill',
+ description:
+ 'Import a SKILL.md for agents to find and read. Execution is controlled by the agent using it.',
+ scope: 'Add to',
+ scopeDescription: {
+ user: 'Available only to the current user',
+ agent: 'Shared with this account; requires permission',
+ },
+ content: 'SKILL.md content',
+ placeholder:
+ '---\nname: my-skill\ndescription: What this skill does\n---\n\n# My skill',
+ contentHint:
+ 'Paste the complete content or select a local SKILL.md file. This imports one file only.',
+ upload: 'Choose SKILL.md',
+ removeFile: 'Remove file {{fileName}}',
+ warnings: 'Validation notes',
+ failed: 'Could not add Skill',
+ processingFailed: 'Background processing failed',
+ processing: 'Submitted and processing in the background',
+ completed: 'Skill added and processing completed',
+ taskId: 'Task ID',
+ close: 'Close',
+ another: 'Add another',
+ validating: 'Validating…',
+ adding: 'Submitting…',
+ submit: 'Add Skill',
+ },
refresh: 'Refresh',
loading: 'Loading skills...',
empty: 'No skills available',
@@ -654,6 +685,20 @@ const workspace = {
},
accountSwitcher: {
create: 'Create account',
+ connections: {
+ add: 'Add connection',
+ savedOnly: 'Connections saved in Connection Settings',
+ switch: 'Switch connection',
+ title: 'Saved connections',
+ },
+ serverAccountsTitle: 'Server accounts',
+ provider: {
+ hosted: 'Volcengine hosted',
+ opensource: 'Open source',
+ },
+ hosted: {
+ currentWorkspace: 'Current space',
+ },
dialog: {
accountLabel: 'Account',
accountPlaceholder: 'team-account',
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index 036fb8269..b39c4254b 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -1,3 +1,5 @@
+import onboarding from './zh-CN/onboarding'
+import studio from './zh-CN/studio'
import vikingbot from './zh-CN/vikingbot'
import gateway from './zh-CN/gateway'
import compile from './zh-CN/compile'
@@ -8,6 +10,8 @@ import activity from './zh-CN/activity'
import memoryTemplates from './zh-CN/memory-templates'
const zhCN = {
+ studio,
+ onboarding,
gateway,
compile,
vikingbot,
diff --git a/web-studio/src/i18n/locales/zh-CN/activity.ts b/web-studio/src/i18n/locales/zh-CN/activity.ts
index 410837bd1..306d99734 100644
--- a/web-studio/src/i18n/locales/zh-CN/activity.ts
+++ b/web-studio/src/i18n/locales/zh-CN/activity.ts
@@ -23,6 +23,7 @@ const activity = {
shortcut: '⌘ N 新建会话',
},
chat: {
+ emptyReadDescription: '当前会话暂无消息。',
historyLoadFailed: '会话记录加载失败:{{error}}',
sendFailed: '消息发送失败:{{error}}',
copy: '复制',
diff --git a/web-studio/src/i18n/locales/zh-CN/onboarding.ts b/web-studio/src/i18n/locales/zh-CN/onboarding.ts
new file mode 100644
index 000000000..0e267a4bf
--- /dev/null
+++ b/web-studio/src/i18n/locales/zh-CN/onboarding.ts
@@ -0,0 +1,56 @@
+export default {
+ connectionTitle: '连接你的工作区。',
+ preferencesHint: '选择你熟悉的语言与外观。',
+ connectionHint: '连接并验证你的 OpenViking 服务。',
+
+ verifiedManagement: '管理权限验证成功。进入用户管理后可创建用户 API 密钥。',
+ brand: 'OpenViking Studio',
+ invalidService: '这个地址未返回有效的 OpenViking 服务信息。',
+ keyRequired: '此服务需要 API Key,请填写后重试。',
+
+ steps: '选择工作区',
+ workspace: '选择 Workspace',
+ workspaceHint: '选择已有连接,或添加新连接。',
+ savedWorkspaces: '已有连接',
+ connectionChoice: '选择连接',
+ newConnection: '添加新服务地址',
+ savedConnectionUnavailable:
+ '已保存的连接不可用,请重新选择或输入新的 API Key。',
+ newAddressHint: '输入有效的 HTTP 或 HTTPS 地址后可继续。',
+ hostedEndpoint: '服务地址',
+ preferences: '基础偏好',
+ connection: '连接服务',
+ welcome: '欢迎使用\nOpenViking Studio',
+ welcomeDescription: '选择已有连接或添加新连接,再配置语言与外观。',
+ connectionDescription: '配置服务连接。验证成功后,将显示对应的工作区和功能。',
+ language: '语言',
+ theme: '外观',
+ light: '浅色',
+ dark: '暗黑',
+ system: '跟随系统',
+ next: '下一步',
+ back: '上一步',
+ verify: '验证连接',
+ verifying: '正在验证…',
+ verified: '连接验证成功',
+ verifyFailed: '连接验证失败:',
+ healthRequestFailed: '检查服务健康状态时失败:',
+ dataRequestFailed: '检查记忆访问权限时失败:',
+ enter: '进入 Studio',
+ keyHelp: '填写服务提供的 API Key。开源开发模式无需填写。',
+ hostedKeyHelp: '填写火山服务的用户 API Key,以访问当前用户的记忆。',
+ advanced: '开源高级连接配置(选填)',
+ loadUsers: '读取此账号的用户',
+ loadingUsers: '正在读取用户…',
+ chooseUser: '选择用户',
+ noUsers: '该账号下没有可选用户,请检查账号 ID 或手动填写用户 ID。',
+ usersDevMode:
+ '当前服务为开发模式,不提供用户列表。请手动填写账号和用户 ID;服务会按这两个值访问对应空间。',
+ usersNeedKey:
+ '此服务需要 Root 或管理员 API 密钥才能列出用户。填入密钥后再试。',
+ usersUnavailable:
+ '无法读取用户列表,请检查管理密钥和账号,或手动填写用户 ID。',
+ userSelectionHint:
+ '填写管理密钥后可读取用户列表;开发模式或无管理权限时,请手动填写账号和用户 ID。API Key 模式下还需要对应用户的密钥。',
+ storageError: '无法保存配置,请允许此站点使用浏览器本地存储后重试。',
+}
diff --git a/web-studio/src/i18n/locales/zh-CN/resources.ts b/web-studio/src/i18n/locales/zh-CN/resources.ts
index cacaa90ca..88d5fe3ec 100644
--- a/web-studio/src/i18n/locales/zh-CN/resources.ts
+++ b/web-studio/src/i18n/locales/zh-CN/resources.ts
@@ -399,6 +399,8 @@ const resources = {
},
},
filePreview: {
+ editFailed: '无法读取完整文件用于编辑。',
+ saveFailed: '文件保存失败。',
directoryLevels: {
abstractLabel: '摘要',
overviewLabel: '概览',
@@ -457,6 +459,12 @@ const resources = {
},
},
retrieval: {
+ modeDescriptions: {
+ find: '按语义查找相关上下文,适合单次问题。',
+ search: '按语义检索,可结合会话上下文查找相关内容。',
+ grep: '按文本或正则表达式匹配文件内容。',
+ glob: '按路径通配符查找文件,例如 **/*.md。',
+ },
title: '检索',
searchPlaceholder: '输入检索内容',
placeholders: {
diff --git a/web-studio/src/i18n/locales/zh-CN/studio.ts b/web-studio/src/i18n/locales/zh-CN/studio.ts
new file mode 100644
index 000000000..befe7026c
--- /dev/null
+++ b/web-studio/src/i18n/locales/zh-CN/studio.ts
@@ -0,0 +1,114 @@
+const studio = {
+ profiles: {
+ connectionChanged: '连接已切换,请在当前连接上重新选择身份。',
+ identityPending: '身份待确认',
+ typeHint: '为这份配置选择服务类型。保存后应用到当前连接。',
+ title: '连接配置',
+ hint: '启用一份配置,使用对应服务和凭证。删除当前配置前,请先启用另一份配置。',
+ add: '添加配置',
+ edit: '编辑配置',
+ delete: '删除',
+ activate: '启用',
+ active: '已启用',
+ name: '配置名称',
+ save: '保存',
+ cancel: '取消',
+ saveHint: '新增配置保存后需手动启用。编辑已启用配置后,保存会重新连接。',
+ invalidUrl:
+ '请输入有效的 HTTP 或 HTTPS 服务地址,地址中不能包含账号或密码。',
+ deleteConfirm: '删除“{{name}}”?已保存的凭证也会被移除。',
+ fields: {
+ baseUrl: '服务地址',
+ apiKey: '用户 API Key',
+ adminApiKey: '管理 API Key(选填)',
+ accountId: '账号 ID',
+ userId: '用户 ID',
+ },
+ },
+
+ selectSessionRecord: '从左侧选择一个会话,查看其历史消息。',
+ noSessionRecords: '当前身份没有可查看的会话记录。',
+ sessionRecords: '会话记录',
+ processingTasks: '处理任务',
+ backToFiles: '返回文件列表',
+ showOverview: '展开统计与队列',
+ hideOverview: '收起统计与队列',
+ connectionSummary: {
+ opensource:
+ '当前工作区按开源服务展示;服务扩展和管理功能需对应配置与权限。',
+ volcengine:
+ '当前工作区按火山托管服务展示;仅显示检测可用的扩展功能,用户 API Key 不提供管理授权。',
+ unknown: '连接验证成功后会展示对应功能。自定义地址请指定服务类型。',
+ },
+
+ watchesReadDescription: '查看已配置的定时同步任务及运行状态。',
+ watchesReadEmpty: '当前没有可访问的定时同步任务。',
+ statistics: '统计分析',
+ listingLimit: '当前视图最多展示 500 项。',
+ directory: '我的目录',
+ memories: '记忆',
+ domainsLabel: 'Studio 功能域',
+ domains: { workspace: '工作区', extensions: '高级功能', management: '管理' },
+ providers: {
+ opensource: '开源服务',
+ volcengine: '火山托管',
+ unknown: '服务类型待确认',
+ checking: '正在检测连接…',
+ },
+ serviceType: '服务类型',
+ auto: '自动检测',
+ serviceHint:
+ '自动检测优先识别火山官方域名,其余地址默认开源服务。火山代理地址请选择火山托管;连接验证成功后展示对应功能。',
+ cloudManagement:
+ '火山管理功能需要连接独立管理服务。数据 API Key 不会自动开放管理权限。',
+ connectionSettings: '连接设置',
+ retry: '重试',
+ loading: '正在加载…',
+ empty: '当前目录为空。',
+ selectFile: '选择文件以预览内容。',
+ spaces: '目录范围',
+ personal: '我的空间',
+ shared: '共享资源',
+ back: '返回',
+ readOnly: '当前工作区为只读。共享资源与个人空间分开展示。',
+ directoryDescription: '浏览自己的上下文,以及获得授权的共享资源。',
+ directoryError: '无法打开目录:目录可能不存在,或当前身份没有访问权限。',
+ states: {
+ gatewayAuthMode: {
+ title: 'Gateway 需要 API Key 认证模式',
+ description:
+ '请使用已验证的管理凭证连接采用 API Key 模式的开源服务。Gateway 用户绑定暂不支持 trusted 模式。',
+ },
+ checking: {
+ title: '正在验证可用性',
+ description: '正在验证当前连接及读取能力。',
+ },
+ connectionFailed: {
+ title: '连接尚未验证成功',
+ description: '请检查服务地址和 API Key,再到连接设置中重试。',
+ },
+ managementRequired: {
+ title: '需要独立管理授权',
+ description:
+ '开源管理功能需要管理连接与对应权限。火山管理功能需要独立管理后端。',
+ },
+ unknownProvider: {
+ title: '请确认服务类型',
+ description:
+ '该自定义地址没有明确的服务标识,请在连接设置中指定服务类型后继续使用。',
+ },
+ unavailable: {
+ title: '当前服务未开放此功能',
+ description: '你仍可浏览自己的目录并使用其他可用功能。',
+ },
+ forbidden: {
+ title: '当前身份没有访问权限',
+ description: '当前连接没有授予此功能需要的读取权限。',
+ },
+ unknown: {
+ title: '此功能的可用性尚未确认',
+ description: '当前连接的扩展接口契约尚未验证,不影响公共工作区。',
+ },
+ },
+} as const
+export default studio
diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.ts
index a77ae6630..438d138ca 100644
--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts
+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts
@@ -12,9 +12,11 @@ const workspace = {
users: '用户与权限',
},
header: {
+ backToConfig: '返回工作区配置',
+ chooseWorkspace: '重新选择工作区',
currentUser: {
- account: '账号',
- accountSummary: '账号 · {{account}}',
+ account: '空间',
+ accountSummary: '空间 · {{account}}',
keyUnavailable: '用户凭证不可用',
loadingUsers: '正在加载用户',
loadUsersFailed: '用户列表加载失败',
@@ -92,6 +94,7 @@ const workspace = {
loading: '正在加载监控数据...',
loadFailed: '监控数据加载失败',
health: {
+ unknown: '暂无数据',
healthy: '正常',
unhealthy: '异常',
},
@@ -342,6 +345,34 @@ const workspace = {
skillsPage: {
title: '技能',
description: '查看当前用户和当前空间可用的 Agent 技能。',
+ add: {
+ title: '添加 Skill',
+ description:
+ '导入 SKILL.md 供 Agent 检索和读取。是否执行由使用它的 Agent 决定。',
+ scope: '添加到',
+ scopeDescription: {
+ user: '仅当前用户可用',
+ agent: '与当前账号共享,需有相应权限',
+ },
+ content: 'SKILL.md 内容',
+ placeholder:
+ '---\nname: my-skill\ndescription: 说明这个 Skill 的用途\n---\n\n# My skill',
+ contentHint:
+ '粘贴完整内容,或选择本地 SKILL.md 文件。此处只导入单个文件。',
+ upload: '选择 SKILL.md',
+ removeFile: '移除文件 {{fileName}}',
+ warnings: '校验提示',
+ failed: '添加失败',
+ processingFailed: '后台处理失败',
+ processing: '已提交,正在后台处理',
+ completed: 'Skill 已添加并处理完成',
+ taskId: '任务 ID',
+ close: '关闭',
+ another: '继续添加',
+ validating: '正在校验…',
+ adding: '正在提交…',
+ submit: '添加 Skill',
+ },
refresh: '刷新',
loading: '正在加载技能...',
empty: '暂无可用技能',
@@ -627,6 +658,20 @@ const workspace = {
},
accountSwitcher: {
create: '新建账号',
+ connections: {
+ add: '添加连接',
+ savedOnly: '显示连接设置中已保存的连接',
+ switch: '切换连接',
+ title: '已保存的连接',
+ },
+ serverAccountsTitle: '服务端账号',
+ provider: {
+ hosted: '火山托管',
+ opensource: '开源服务',
+ },
+ hosted: {
+ currentWorkspace: '当前空间',
+ },
dialog: {
accountLabel: '账号',
accountPlaceholder: 'team-account',
diff --git a/web-studio/src/lib/admin.test.ts b/web-studio/src/lib/admin.test.ts
index 105645366..c120e9d84 100644
--- a/web-studio/src/lib/admin.test.ts
+++ b/web-studio/src/lib/admin.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as Client from '#/gen/ov-client/client'
-import { fetchAdminUsersPage } from './admin'
+import { fetchAdminUserDirectory, fetchAdminUsersPage } from './admin'
const { getMock } = vi.hoisted(() => ({ getMock: vi.fn() }))
vi.mock('#/gen/ov-client/client', async (importOriginal) => {
@@ -71,3 +71,23 @@ describe('fetchAdminUsersPage', () => {
expect(getMock).toHaveBeenCalledTimes(1)
})
})
+
+it('requests selectable users without credentials', async () => {
+ getMock.mockReset()
+ getMock.mockResolvedValue({
+ status: 200,
+ headers: {},
+ data: {
+ status: 'ok',
+ result: [{ user_id: 'alice', role: 'user', api_key_available: true }],
+ },
+ })
+ const users = await fetchAdminUserDirectory(connection, 'team')
+ expect(getMock).toHaveBeenCalledWith({
+ url: '/api/v1/admin/accounts/{account_id}/users',
+ path: { account_id: 'team' },
+ query: { include_credentials: false },
+ })
+ expect(users).toMatchObject([{ accountId: 'team', userId: 'alice' }])
+ expect(users[0].apiKey).toBeUndefined()
+})
diff --git a/web-studio/src/lib/admin.ts b/web-studio/src/lib/admin.ts
index 3500945a8..144684d64 100644
--- a/web-studio/src/lib/admin.ts
+++ b/web-studio/src/lib/admin.ts
@@ -1,5 +1,7 @@
+import { resolveApiKeyAuth, createApiKeyHeaders } from '#/lib/connection/auth'
+import type { ApiKeyAuth } from '#/lib/connection/auth'
import axios from 'axios'
-import type { ServerMode } from '#/hooks/use-server-mode'
+import type { ServerMode } from '#/lib/connection/health'
import { createClient } from '#/gen/ov-client/client'
import {
@@ -88,6 +90,9 @@ export type StudioConnectionProbe = {
}
export type ProbeConnectionInput = {
+ apiKeyAuth?: ApiKeyAuth
+ skipAdmin?: boolean
+ dataRootUri?: string
accountId: string
adminApiKey: string
apiKey: string
@@ -167,8 +172,9 @@ function createProbeClient(baseUrl: string) {
function setApiKeyHeader(
headers: Record<string, string>,
apiKey: string,
+ auth: ApiKeyAuth = 'header',
): void {
- setOptionalHeader(headers, 'X-API-Key', apiKey)
+ Object.assign(headers, createApiKeyHeaders(apiKey, auth))
}
function probeError(error: unknown): CapabilityProbeResult {
@@ -278,7 +284,11 @@ async function probeDataAccess(
const client = createProbeClient(input.baseUrl)
const headers: Record<string, string> = {}
- setApiKeyHeader(headers, apiKey)
+ setApiKeyHeader(
+ headers,
+ input.apiKey || (input.serverMode === 'trusted' ? input.adminApiKey : ''),
+ input.apiKeyAuth ?? resolveApiKeyAuth(input.baseUrl),
+ )
if (input.serverMode === 'trusted') {
setOptionalHeader(headers, 'X-OpenViking-Account', input.accountId)
@@ -291,7 +301,7 @@ async function probeDataAccess(
params: {
node_limit: 1,
output: 'agent',
- uri: 'viking://',
+ uri: input.dataRootUri ?? 'viking://',
},
})
return {
@@ -307,7 +317,9 @@ export async function probeStudioConnection(
input: ProbeConnectionInput,
): Promise<StudioConnectionProbe> {
const [admin, data] = await Promise.all([
- probeAdminAccess(input),
+ input.skipAdmin
+ ? Promise.resolve({ state: 'skipped' as const })
+ : probeAdminAccess(input),
probeDataAccess(input),
])
return { admin, data }
@@ -391,6 +403,23 @@ export async function fetchAdminUsers(
.filter((item): item is AdminUser => Boolean(item))
}
+/** List selectable identities without returning their API keys to the wizard. */
+export async function fetchAdminUserDirectory(
+ connection: AdminConnection,
+ accountId: string,
+): Promise<AdminUser[]> {
+ const result = await getOvResult<unknown[]>(
+ createAdminClient(connection).get({
+ url: '/api/v1/admin/accounts/{account_id}/users',
+ path: { account_id: accountId },
+ query: { include_credentials: false },
+ }),
+ )
+ return result
+ .map((item) => normalizeUser(accountId, item))
+ .filter((item): item is AdminUser => Boolean(item))
+}
+
export type AdminUserPage = {
users: AdminUser[]
total: number
diff --git a/web-studio/src/lib/connection/auth.ts b/web-studio/src/lib/connection/auth.ts
new file mode 100644
index 000000000..56d8f62cc
--- /dev/null
+++ b/web-studio/src/lib/connection/auth.ts
@@ -0,0 +1,51 @@
+import type { ConnectionDraft } from './types'
+import { resolveConfiguredServiceProvider } from '../studio-service'
+import type { ServiceSelection } from '../studio-service'
+
+export type ApiKeyAuth = 'header' | 'bearer'
+
+export function resolveApiKeyAuth(
+ baseUrl: string,
+ selection: ServiceSelection = 'auto',
+): ApiKeyAuth {
+ return resolveConfiguredServiceProvider(baseUrl, selection) === 'volcengine'
+ ? 'bearer'
+ : 'header'
+}
+
+export function createConnectionHealthHeaders(
+ connection: ConnectionDraft,
+ credential: 'control' | 'data' = 'control',
+): Record<string, string> {
+ const headers: Record<string, string> = {}
+ const auth = resolveApiKeyAuth(
+ connection.baseUrl,
+ connection.serviceSelection,
+ )
+ const apiKey =
+ auth === 'bearer'
+ ? connection.apiKey
+ : credential === 'data'
+ ? connection.apiKey || connection.adminApiKey
+ : connection.adminApiKey || connection.apiKey
+ if (!apiKey) return headers
+ Object.assign(headers, createApiKeyHeaders(apiKey, auth))
+ const isHosted = auth === 'bearer'
+ if (!isHosted && connection.accountId) {
+ headers['X-OpenViking-Account'] = connection.accountId
+ }
+ if (!isHosted && connection.userId) {
+ headers['X-OpenViking-User'] = connection.userId
+ }
+ return headers
+}
+
+export function createApiKeyHeaders(
+ apiKey: string,
+ auth: ApiKeyAuth,
+): Record<string, string> {
+ if (!apiKey.trim()) return {}
+ return auth === 'bearer'
+ ? { Authorization: `Bearer ${apiKey.trim()}` }
+ : { 'X-API-Key': apiKey.trim() }
+}
diff --git a/web-studio/src/lib/connection/capabilities.ts b/web-studio/src/lib/connection/capabilities.ts
new file mode 100644
index 000000000..1857f01ef
--- /dev/null
+++ b/web-studio/src/lib/connection/capabilities.ts
@@ -0,0 +1,48 @@
+import { resolveApiKeyAuth } from './auth'
+import { normalizeOvClientError, createOvClient } from '#/lib/ov-client'
+import {
+ classifyCapabilityError,
+ classifyCapabilityResponse,
+} from '../studio-service'
+import type { CapabilityState, STUDIO_FEATURES } from '../studio-service'
+import type { ConnectionDraft } from './types'
+
+type ProbedFeature = Extract<
+ (typeof STUDIO_FEATURES)[number],
+ { probe: string }
+>
+
+/** Read capability using the caller's immutable connection snapshot. */
+export async function fetchStudioCapability(
+ connection: ConnectionDraft,
+ feature: ProbedFeature,
+ signal: AbortSignal,
+): Promise<CapabilityState> {
+ const auth = resolveApiKeyAuth(
+ connection.baseUrl,
+ connection.serviceSelection,
+ )
+ try {
+ // Capture credentials with the query's scope. A mutable global client
+ // can otherwise attach a new key to an old connection's request.
+ const client = createOvClient({
+ apiKeyStorageKey: '',
+ apiKeyAuth: auth,
+ baseUrl: connection.baseUrl,
+ connection: {
+ apiKey:
+ auth === 'bearer'
+ ? connection.apiKey
+ : connection.apiKey || connection.adminApiKey,
+ },
+ })
+ const response = await client.instance.get(feature.probe, {
+ baseURL: connection.baseUrl.replace(/\/+$/, ''),
+ signal,
+ timeout: 8_000,
+ })
+ return classifyCapabilityResponse(feature.id, response.data)
+ } catch (error) {
+ return classifyCapabilityError(normalizeOvClientError(error))
+ }
+}
diff --git a/web-studio/src/hooks/use-server-mode.test.ts b/web-studio/src/lib/connection/health.test.ts
similarity index 89%
rename from web-studio/src/hooks/use-server-mode.test.ts
rename to web-studio/src/lib/connection/health.test.ts
index c3f8261ee..f2679eb59 100644
--- a/web-studio/src/hooks/use-server-mode.test.ts
+++ b/web-studio/src/lib/connection/health.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { fetchServerHealth } from './use-server-mode'
+import { fetchServerHealth } from '#/lib/connection/health'
const { getHealthMock } = vi.hoisted(() => ({
getHealthMock: vi.fn(),
@@ -32,6 +32,9 @@ describe('fetchServerHealth', () => {
{ auth_mode: 'api_key', role: 'user' },
{ auth_mode: 'api_key', role: 'user' },
])
+ expect(getHealthMock).toHaveBeenCalledWith(
+ expect.objectContaining({ timeout: 10000 }),
+ )
expect(getHealthMock).toHaveBeenCalledTimes(1)
})
diff --git a/web-studio/src/hooks/use-server-mode.ts b/web-studio/src/lib/connection/health.ts
similarity index 51%
rename from web-studio/src/hooks/use-server-mode.ts
rename to web-studio/src/lib/connection/health.ts
index a070bf609..8a0098cbf 100644
--- a/web-studio/src/hooks/use-server-mode.ts
+++ b/web-studio/src/lib/connection/health.ts
@@ -1,3 +1,5 @@
+import type { ConnectionDraft } from './types'
+import { createConnectionHealthHeaders } from './auth'
import { getHealth } from '#/lib/ov-client'
import { createClient } from '#/gen/ov-client/client'
@@ -32,6 +34,13 @@ export function isServerAuthMode(value: unknown): value is ServerAuthMode {
)
}
+function forgetFailedHealthRequest(
+ promise: Promise<Record<string, unknown>>,
+): void {
+ // Reconnection may clear or replace the cached request while this one is pending.
+ if (recentHealthRequest?.promise === promise) recentHealthRequest = undefined
+}
+
export async function fetchServerHealth(
baseUrl: string,
headers: Record<string, string> = {},
@@ -59,6 +68,7 @@ export async function fetchServerHealth(
Accept: 'application/json',
...headers,
},
+ timeout: 10000,
throwOnError: true,
}).then((response) => {
const data = response.data
@@ -76,9 +86,53 @@ export async function fetchServerHealth(
try {
return await promise
} catch (error) {
- if (recentHealthRequest.promise === promise) {
- recentHealthRequest = undefined
- }
+ forgetFailedHealthRequest(promise)
throw error
}
}
+
+export function resetServerHealthCache(): void {
+ recentHealthRequest = undefined
+}
+
+export function resolveServerAuthMode(
+ data: Record<string, unknown>,
+): ServerAuthMode {
+ return isServerAuthMode(data.auth_mode) ? data.auth_mode : 'api_key'
+}
+
+export function isUsableServerHealth(
+ data: unknown,
+): data is Record<string, unknown> {
+ return Boolean(
+ data &&
+ typeof data === 'object' &&
+ !Array.isArray(data) &&
+ (data as Record<string, unknown>).status !== 'error' &&
+ !(data as Record<string, unknown>).error &&
+ (typeof (data as Record<string, unknown>).version === 'string' ||
+ typeof (data as Record<string, unknown>).auth_mode === 'string'),
+ )
+}
+
+export function readServerIdentity(health: Record<string, unknown>) {
+ return {
+ accountId: typeof health.account_id === 'string' ? health.account_id : '',
+ userId: typeof health.user_id === 'string' ? health.user_id : '',
+ }
+}
+
+/** Setup uses an isolated, cancellable request rather than the runtime reuse cache. */
+export async function fetchConnectionHealth(
+ connection: ConnectionDraft,
+ signal: AbortSignal,
+) {
+ const client = createClient({
+ baseURL: normalizeBaseUrl(connection.baseUrl),
+ headers: createConnectionHealthHeaders(connection, 'data'),
+ timeout: 10000,
+ throwOnError: true,
+ })
+ const response = await client.get({ url: '/health', signal })
+ return response.data
+}
diff --git a/web-studio/src/lib/connection/identity-label.ts b/web-studio/src/lib/connection/identity-label.ts
new file mode 100644
index 000000000..9337f8d5c
--- /dev/null
+++ b/web-studio/src/lib/connection/identity-label.ts
@@ -0,0 +1,12 @@
+/** Keep the hosted identity compact without inferring the service edition. */
+export function formatHostedIdentity(
+ accountId?: string | null,
+ userId?: string | null,
+): string | null {
+ const account = accountId?.trim() ?? ''
+ const user = userId?.trim() ?? ''
+ if (!account || !user) return null
+ return account === 'default' && user === 'default'
+ ? 'default'
+ : `${account}/${user}`
+}
diff --git a/web-studio/src/lib/connection/onboarding.test.ts b/web-studio/src/lib/connection/onboarding.test.ts
new file mode 100644
index 000000000..047433c6a
--- /dev/null
+++ b/web-studio/src/lib/connection/onboarding.test.ts
@@ -0,0 +1,323 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ completeStudioSetup,
+ needsStudioSetup,
+ SETUP_STORAGE_KEY,
+ StudioSetupRequestError,
+ WORKSPACE_SESSION_KEY,
+ verifyStudioSetup,
+ studioSetupDestination,
+} from '#/lib/connection/onboarding'
+import { PROFILES_STORAGE_KEY } from '#/lib/connection/profiles'
+import { createClient } from '#/gen/ov-client/client'
+import { OvClientError } from '#/lib/ov-client'
+import type * as ClientModule from '#/gen/ov-client/client'
+
+const get = vi.hoisted(() => vi.fn())
+vi.mock('#/gen/ov-client/client', async (original) => {
+ const actual = await original<typeof ClientModule>()
+ return {
+ ...actual,
+ createClient: vi.fn(
+ (options?: Parameters<typeof actual.createClient>[0]) => ({
+ ...actual.createClient(options),
+ get,
+ }),
+ ),
+ }
+})
+const draft = {
+ serviceSelection: 'opensource' as const,
+ baseUrl: 'http://service.test',
+ apiKey: 'synthetic-key',
+ adminApiKey: '',
+ accountId: 'default',
+ userId: 'default',
+}
+beforeEach(() => {
+ localStorage.clear()
+ sessionStorage.clear()
+ get.mockReset()
+ vi.mocked(createClient).mockClear()
+})
+afterEach(() => vi.unstubAllGlobals())
+describe('first-use detection', () => {
+ it('starts setup for a new tab and retains unfinished setup on reload', () => {
+ expect(needsStudioSetup()).toBe(true)
+ localStorage.setItem(SETUP_STORAGE_KEY, 'pending')
+ localStorage.setItem(
+ PROFILES_STORAGE_KEY,
+ JSON.stringify({ profiles: [{ connection: draft }] }),
+ )
+ expect(needsStudioSetup()).toBe(true)
+ })
+ it('shows workspace choice even when a profile or legacy connection exists', () => {
+ localStorage.setItem('ov_console_connection', JSON.stringify(draft))
+ expect(needsStudioSetup()).toBe(true)
+ localStorage.clear()
+ localStorage.setItem(
+ PROFILES_STORAGE_KEY,
+ JSON.stringify({ profiles: [{ connection: draft }] }),
+ )
+ expect(needsStudioSetup()).toBe(true)
+ })
+ it('does not treat an automatically persisted empty same-origin connection as configured', () => {
+ localStorage.setItem(
+ 'ov_console_connection',
+ JSON.stringify({ ...draft, baseUrl: window.location.origin, apiKey: '' }),
+ )
+ expect(needsStudioSetup()).toBe(true)
+ })
+ it('completes a verified development connection without a key', () => {
+ completeStudioSetup(
+ { ...draft, baseUrl: window.location.origin, apiKey: '' },
+ 'Development',
+ )
+ expect(needsStudioSetup()).toBe(false)
+ expect(sessionStorage.getItem(WORKSPACE_SESSION_KEY)).toBe('selected')
+ localStorage.removeItem(PROFILES_STORAGE_KEY)
+ localStorage.removeItem('ov_console_connection')
+ sessionStorage.removeItem(WORKSPACE_SESSION_KEY)
+ expect(needsStudioSetup()).toBe(true)
+ })
+ it('completes setup when randomUUID is unavailable on an HTTP origin', () => {
+ vi.stubGlobal('crypto', {
+ getRandomValues: (bytes: Uint8Array) => bytes.fill(7),
+ })
+ completeStudioSetup(draft, 'OpenViking')
+ const saved = JSON.parse(localStorage.getItem(PROFILES_STORAGE_KEY) || '{}')
+ expect(saved.profiles).toHaveLength(1)
+ expect(saved.profiles[0].id).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
+ )
+ expect(saved.activeId).toBe(saved.profiles[0].id)
+ expect(needsStudioSetup()).toBe(false)
+ })
+ it('retains other saved workspaces when selecting a new connection', () => {
+ localStorage.setItem(
+ PROFILES_STORAGE_KEY,
+ JSON.stringify({
+ activeId: 'one',
+ profiles: [{ id: 'one', name: 'Original', connection: draft }],
+ }),
+ )
+ completeStudioSetup(
+ {
+ ...draft,
+ serviceSelection: 'volcengine',
+ baseUrl: 'https://hosted.test',
+ },
+ 'Volcengine',
+ )
+ const saved = JSON.parse(localStorage.getItem(PROFILES_STORAGE_KEY) || '{}')
+ expect(saved.profiles).toHaveLength(2)
+ expect(saved.profiles[0].name).toBe('Original')
+ expect(saved.profiles[1].connection.serviceSelection).toBe('volcengine')
+ })
+ it('keeps the selected profile when saved profiles share an address', () => {
+ localStorage.setItem(
+ PROFILES_STORAGE_KEY,
+ JSON.stringify({
+ activeId: 'second',
+ profiles: [
+ { id: 'first', name: 'First', connection: draft },
+ { id: 'second', name: 'Second', connection: draft },
+ ],
+ }),
+ )
+ completeStudioSetup(
+ { ...draft, apiKey: 'updated-key' },
+ 'OpenViking',
+ 'second',
+ )
+ const saved = JSON.parse(localStorage.getItem(PROFILES_STORAGE_KEY) || '{}')
+ expect(saved.activeId).toBe('second')
+ expect(saved.profiles[0].connection.apiKey).toBe('synthetic-key')
+ expect(saved.profiles[1].connection.apiKey).toBe('updated-key')
+ })
+ it('keeps both workspaces when a new connection uses an existing service address', () => {
+ const hosted = {
+ ...draft,
+ serviceSelection: 'volcengine' as const,
+ baseUrl: 'https://hosted.test',
+ }
+ completeStudioSetup({ ...hosted, apiKey: 'alice-key' }, 'Alice')
+ const first = JSON.parse(localStorage.getItem(PROFILES_STORAGE_KEY) || '{}')
+
+ completeStudioSetup({ ...hosted, apiKey: 'bob-key' }, 'Bob')
+ const saved = JSON.parse(localStorage.getItem(PROFILES_STORAGE_KEY) || '{}')
+ expect(saved.profiles).toHaveLength(2)
+ expect(saved.profiles[0]).toEqual(first.profiles[0])
+ expect(saved.profiles[1]).toMatchObject({
+ name: 'Bob',
+ connection: { apiKey: 'bob-key' },
+ })
+ expect(saved.activeId).toBe(saved.profiles[1].id)
+ expect(saved.activeId).not.toBe(first.activeId)
+ })
+})
+describe('verification', () => {
+ it('identifies the failed verification stage and masks credentials', () => {
+ const error = new StudioSetupRequestError(
+ 'health',
+ new OvClientError({
+ code: 'PaymentRequired',
+ message: 'Account check failed for synthetic-key',
+ statusCode: 402,
+ }),
+ draft,
+ )
+ expect(error.stage).toBe('health')
+ expect(error.statusCode).toBe(402)
+ expect(error.message).toContain('HTTP 402')
+ expect(error.message).not.toContain('synthetic-key')
+ })
+ it('uses hosted Bearer credentials and service-returned identity before checking private data', async () => {
+ get
+ .mockResolvedValueOnce({
+ data: {
+ status: 'ok',
+ version: 'cloud',
+ auth_mode: 'api_key',
+ account_id: 'tenant',
+ user_id: 'alice',
+ },
+ })
+ .mockResolvedValueOnce({
+ status: 200,
+ headers: {},
+ data: { status: 'ok', result: [] },
+ })
+ const c = await verifyStudioSetup(
+ {
+ ...draft,
+ serviceSelection: 'volcengine',
+ adminApiKey: 'never-send-control',
+ },
+ new AbortController().signal,
+ )
+ expect(c.userId).toBe('alice')
+ expect(c.adminApiKey).toBe('')
+ expect(vi.mocked(createClient).mock.calls[0][0]?.headers).toEqual({
+ Authorization: 'Bearer synthetic-key',
+ })
+ expect(get.mock.calls[1][0].query.uri).toBe('viking://~/')
+ })
+ it('does not invent a hosted identity when health omits it', async () => {
+ get
+ .mockResolvedValueOnce({
+ data: { version: 'test', auth_mode: 'api_key' },
+ })
+ .mockResolvedValueOnce({
+ status: 200,
+ headers: {},
+ data: { status: 'ok', result: [] },
+ })
+ const connection = await verifyStudioSetup(
+ { ...draft, serviceSelection: 'volcengine' },
+ new AbortController().signal,
+ )
+ expect(connection.accountId).toBe('')
+ expect(connection.userId).toBe('')
+ })
+ it('rejects HTML health responses instead of accepting the Studio URL', async () => {
+ get.mockResolvedValueOnce({ data: '<html></html>' })
+ await expect(
+ verifyStudioSetup(draft, new AbortController().signal),
+ ).rejects.toThrow('invalidService')
+ expect(get).toHaveBeenCalledTimes(1)
+ })
+ it('does not accept a health-only response when data access fails', async () => {
+ get
+ .mockResolvedValueOnce({
+ data: { version: 'test', auth_mode: 'api_key' },
+ })
+ .mockRejectedValueOnce(new Error('Forbidden'))
+ await expect(
+ verifyStudioSetup(draft, new AbortController().signal),
+ ).rejects.toMatchObject({ stage: 'data', message: 'Forbidden' })
+ expect(localStorage.getItem(PROFILES_STORAGE_KEY)).toBeNull()
+ })
+ it('requires a key except in development mode', async () => {
+ get.mockResolvedValueOnce({
+ data: { version: 'test', auth_mode: 'api_key' },
+ })
+ await expect(
+ verifyStudioSetup({ ...draft, apiKey: '' }, new AbortController().signal),
+ ).rejects.toThrow('keyRequired')
+ })
+})
+
+describe('management bootstrap', () => {
+ it.each(['root', 'admin'])(
+ 'verifies %s control access without calling tenant data APIs',
+ async (role) => {
+ get
+ .mockResolvedValueOnce({
+ data: {
+ version: 'test',
+ auth_mode: 'api_key',
+ role,
+ account_id: 'tenant',
+ user_id: 'admin',
+ },
+ })
+ .mockResolvedValueOnce({
+ status: 200,
+ headers: {},
+ data: { status: 'ok', result: [] },
+ })
+ const connection = await verifyStudioSetup(
+ { ...draft, apiKey: '', adminApiKey: 'synthetic-control' },
+ new AbortController().signal,
+ )
+ expect(get.mock.calls[1][0].url).toBe(
+ role === 'root'
+ ? '/api/v1/admin/accounts'
+ : '/api/v1/admin/accounts/{account_id}/users',
+ )
+ expect(studioSetupDestination(connection)).toBe('/users')
+ expect(
+ get.mock.calls.some(([options]) => options.url === '/api/v1/fs/ls'),
+ ).toBe(false)
+ },
+ )
+ it('rejects denied management access and does not save it', async () => {
+ get
+ .mockResolvedValueOnce({
+ data: { version: 'test', auth_mode: 'api_key', role: 'root' },
+ })
+ .mockRejectedValueOnce(new Error('Forbidden'))
+ await expect(
+ verifyStudioSetup(
+ { ...draft, apiKey: '', adminApiKey: 'synthetic-control' },
+ new AbortController().signal,
+ ),
+ ).rejects.toThrow('Forbidden')
+ expect(localStorage.getItem(PROFILES_STORAGE_KEY)).toBeNull()
+ })
+ it('does not use a hosted control credential as a user credential', async () => {
+ get.mockResolvedValueOnce({
+ data: { version: 'test', auth_mode: 'api_key', role: 'root' },
+ })
+ await expect(
+ verifyStudioSetup(
+ {
+ ...draft,
+ serviceSelection: 'volcengine',
+ apiKey: '',
+ adminApiKey: 'synthetic-control',
+ },
+ new AbortController().signal,
+ ),
+ ).rejects.toThrow('keyRequired')
+ expect(get).toHaveBeenCalledTimes(1)
+ })
+ it('keeps data connections on their normal landing page', () => {
+ expect(studioSetupDestination(draft)).toBe('/home')
+ expect(
+ studioSetupDestination({ ...draft, serviceSelection: 'volcengine' }),
+ ).toBe('/filesystem')
+ })
+})
diff --git a/web-studio/src/lib/connection/onboarding.ts b/web-studio/src/lib/connection/onboarding.ts
new file mode 100644
index 000000000..38fc1a4b9
--- /dev/null
+++ b/web-studio/src/lib/connection/onboarding.ts
@@ -0,0 +1,240 @@
+import { resolveConnectionDataRoot } from './probe'
+import type { ConnectionDraft } from '#/lib/connection/types'
+import { createConnectionHealthHeaders } from './auth'
+import { createClient } from '#/gen/ov-client/client'
+import { getOvResult, normalizeOvClientError } from '#/lib/ov-client'
+import { createRandomUuid } from '#/lib/browser-crypto'
+import {
+ resolveServerAuthMode,
+ fetchConnectionHealth,
+ isUsableServerHealth,
+ readServerIdentity,
+} from './health'
+import {
+ isValidConnectionUrl,
+ normalizeProfileConnection,
+ PROFILES_STORAGE_KEY,
+} from '#/lib/connection/profiles'
+
+export const SETUP_STORAGE_KEY = 'ov_studio_setup'
+export const WORKSPACE_SESSION_KEY = 'ov_studio_workspace_selected'
+export class StudioSetupError extends Error {
+ constructor(public readonly code: 'invalidService' | 'keyRequired') {
+ super(code)
+ }
+}
+
+export class StudioSetupRequestError extends Error {
+ readonly stage: 'health' | 'data'
+ readonly statusCode?: number
+
+ constructor(
+ stage: 'health' | 'data',
+ cause: unknown,
+ connection: ConnectionDraft,
+ ) {
+ const error = normalizeOvClientError(cause)
+ let message = error.message
+ for (const secret of [connection.apiKey, connection.adminApiKey]) {
+ if (secret) message = message.replaceAll(secret, '[redacted]')
+ }
+ super(`${error.statusCode ? `HTTP ${error.statusCode}: ` : ''}${message}`, {
+ cause,
+ })
+ this.stage = stage
+ this.statusCode = error.statusCode
+ }
+}
+
+export const CLOUD_SETUP_URL =
+ 'https://api.vikingdb.cn-beijing.volces.com/openviking'
+
+function hasConnection(value: unknown, completed = false): boolean {
+ if (!value || typeof value !== 'object') return false
+ const c = value as Partial<ConnectionDraft>
+ return (
+ typeof c.baseUrl === 'string' &&
+ isValidConnectionUrl(c.baseUrl) &&
+ (completed ||
+ Boolean(
+ (typeof c.apiKey === 'string' && c.apiKey.trim()) ||
+ (typeof c.adminApiKey === 'string' && c.adminApiKey.trim()),
+ ) ||
+ c.baseUrl.replace(/\/+$/, '') !== window.location.origin)
+ )
+}
+
+export function needsStudioSetup(): boolean {
+ try {
+ return sessionStorage.getItem(WORKSPACE_SESSION_KEY) !== 'selected'
+ } catch {
+ return true
+ }
+}
+
+export function savedSetupConnections(): Array<{
+ id: string
+ name: string
+ connection: ConnectionDraft
+}> {
+ try {
+ const saved: unknown = JSON.parse(
+ localStorage.getItem(PROFILES_STORAGE_KEY) || 'null',
+ )
+ if (
+ saved &&
+ typeof saved === 'object' &&
+ 'profiles' in saved &&
+ Array.isArray(saved.profiles)
+ )
+ return saved.profiles.filter(
+ (
+ profile,
+ ): profile is {
+ id: string
+ name: string
+ connection: ConnectionDraft
+ } =>
+ profile &&
+ typeof profile.id === 'string' &&
+ typeof profile.name === 'string' &&
+ hasConnection(profile.connection, true),
+ )
+ const legacy: unknown = JSON.parse(
+ localStorage.getItem('ov_console_connection') || 'null',
+ )
+ if (hasConnection(legacy))
+ return [
+ {
+ id: 'default',
+ name: 'OpenViking',
+ connection: normalizeProfileConnection(legacy as ConnectionDraft),
+ },
+ ]
+ } catch {
+ /* An invalid saved profile must not block a new connection. */
+ }
+ return []
+}
+
+export function markStudioSetupPending() {
+ try {
+ localStorage.setItem(SETUP_STORAGE_KEY, 'pending')
+ } catch {
+ /* Show the setup even without storage. */
+ }
+}
+
+export async function verifyStudioSetup(
+ draft: ConnectionDraft,
+ signal: AbortSignal,
+): Promise<ConnectionDraft> {
+ const connection = normalizeProfileConnection({
+ ...draft,
+ baseUrl: draft.baseUrl.trim().replace(/\/+$/, ''),
+ apiKey: draft.apiKey.trim(),
+ adminApiKey: draft.adminApiKey.trim(),
+ })
+ if (!isValidConnectionUrl(connection.baseUrl))
+ throw new Error('Invalid server URL')
+ if (connection.serviceSelection === 'volcengine') connection.adminApiKey = ''
+ const health = await fetchConnectionHealth(connection, signal).catch(
+ (error: unknown) => {
+ throw new StudioSetupRequestError('health', error, connection)
+ },
+ )
+ if (!isUsableServerHealth(health))
+ throw new StudioSetupError('invalidService')
+ const mode = resolveServerAuthMode(health)
+ if (
+ mode !== 'dev' &&
+ !connection.apiKey &&
+ !(connection.serviceSelection === 'opensource' && connection.adminApiKey)
+ )
+ throw new StudioSetupError('keyRequired')
+ if (connection.serviceSelection === 'volcengine') {
+ connection.accountId = ''
+ connection.userId = ''
+ }
+ const identity = readServerIdentity(health)
+ if (identity.accountId) connection.accountId = identity.accountId
+ if (identity.userId) connection.userId = identity.userId
+ const dataClient = createClient({
+ baseURL: connection.baseUrl,
+ headers: createConnectionHealthHeaders(connection, 'data'),
+ timeout: 10000,
+ throwOnError: true,
+ })
+ const managementOnly =
+ mode === 'api_key' &&
+ connection.serviceSelection === 'opensource' &&
+ !connection.apiKey &&
+ Boolean(connection.adminApiKey)
+ if (managementOnly) {
+ // ROOT cannot call tenant data APIs. Verify control access before letting
+ // a new administrator open Users and mint a separate user credential.
+ if (health.role !== 'root' && health.role !== 'admin')
+ throw new StudioSetupError('keyRequired')
+ await getOvResult(
+ dataClient.get({
+ url:
+ health.role === 'root'
+ ? '/api/v1/admin/accounts'
+ : '/api/v1/admin/accounts/{account_id}/users',
+ path: { account_id: connection.accountId },
+ signal,
+ }),
+ ).catch((error: unknown) => {
+ throw new StudioSetupRequestError('data', error, connection)
+ })
+ } else
+ await getOvResult(
+ dataClient.get({
+ url: '/api/v1/fs/ls',
+ query: {
+ uri: resolveConnectionDataRoot(connection, 'root'),
+ node_limit: 1,
+ output: 'agent',
+ },
+ signal,
+ }),
+ ).catch((error: unknown) => {
+ throw new StudioSetupRequestError('data', error, connection)
+ })
+ signal.throwIfAborted()
+ return connection
+}
+
+export function studioSetupDestination(
+ connection: ConnectionDraft,
+): '/filesystem' | '/users' | '/home' {
+ if (connection.serviceSelection === 'volcengine') return '/filesystem'
+ return !connection.apiKey && connection.adminApiKey ? '/users' : '/home'
+}
+
+export function completeStudioSetup(
+ connection: ConnectionDraft,
+ name: string,
+ selectedProfileId?: string,
+) {
+ // Do not enter the workspace if the browser cannot retain this connection.
+ const saved = savedSetupConnections()
+ const existing = selectedProfileId
+ ? saved.find((profile) => profile.id === selectedProfileId)
+ : undefined
+ const id = existing?.id ?? createRandomUuid()
+ localStorage.setItem(
+ PROFILES_STORAGE_KEY,
+ JSON.stringify({
+ activeId: id,
+ profiles: existing
+ ? saved.map((profile) =>
+ profile.id === id ? { ...profile, connection } : profile,
+ )
+ : [...saved, { id, name, connection }],
+ }),
+ )
+ localStorage.setItem('ov_console_connection', JSON.stringify(connection))
+ localStorage.setItem(SETUP_STORAGE_KEY, 'complete')
+ sessionStorage.setItem(WORKSPACE_SESSION_KEY, 'selected')
+}
diff --git a/web-studio/src/lib/connection/probe.ts b/web-studio/src/lib/connection/probe.ts
new file mode 100644
index 000000000..a9e53032c
--- /dev/null
+++ b/web-studio/src/lib/connection/probe.ts
@@ -0,0 +1,45 @@
+import { probeStudioConnection } from '../admin'
+import { DEFAULT_ACCOUNT_ID, DEFAULT_USER_ID } from '../admin-options'
+import { resolveConfiguredServiceProvider } from '../studio-service'
+import { resolveApiKeyAuth } from './auth'
+import type { ConnectionDraft } from './types'
+import type { ServerMode } from './health'
+
+export function resolveConnectionDataRoot(
+ connection: ConnectionDraft,
+ scope: 'root' | 'user' = 'user',
+): string {
+ if (
+ resolveConfiguredServiceProvider(
+ connection.baseUrl,
+ connection.serviceSelection,
+ ) === 'volcengine'
+ )
+ return 'viking://~/'
+ return scope === 'user' && connection.userId
+ ? `viking://user/${connection.userId}/`
+ : 'viking://'
+}
+
+/** Diagnostic probes intentionally report access states instead of blocking setup. */
+export function probeConnection(
+ connection: ConnectionDraft,
+ serverMode: ServerMode,
+) {
+ return probeStudioConnection({
+ ...connection,
+ apiKeyAuth: resolveApiKeyAuth(
+ connection.baseUrl,
+ connection.serviceSelection,
+ ),
+ accountId: connection.accountId || DEFAULT_ACCOUNT_ID,
+ userId: connection.userId || DEFAULT_USER_ID,
+ skipAdmin:
+ resolveConfiguredServiceProvider(
+ connection.baseUrl,
+ connection.serviceSelection,
+ ) !== 'opensource',
+ dataRootUri: resolveConnectionDataRoot(connection),
+ serverMode,
+ })
+}
diff --git a/web-studio/src/lib/connection/profiles.test.ts b/web-studio/src/lib/connection/profiles.test.ts
new file mode 100644
index 000000000..8261eb786
--- /dev/null
+++ b/web-studio/src/lib/connection/profiles.test.ts
@@ -0,0 +1,94 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it } from 'vitest'
+import {
+ readConnectionProfiles,
+ persistConnectionProfiles,
+ updateActiveProfile,
+ normalizeProfileConnection,
+ isValidConnectionUrl,
+} from '#/lib/connection/profiles'
+import type { ConnectionDraft } from '#/lib/connection/types'
+
+const fallback: ConnectionDraft = {
+ baseUrl: 'http://10.37.244.186:8020',
+ apiKey: 'legacy-key',
+ adminApiKey: 'root-key',
+ accountId: 'default',
+ userId: 'alice',
+}
+afterEach(() => localStorage.clear())
+it('aligns saved and restored provider labels with official hosted authentication', () => {
+ const hosted = {
+ ...fallback,
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ serviceSelection: 'opensource' as const,
+ }
+ expect(normalizeProfileConnection(hosted).serviceSelection).toBe('volcengine')
+ const state = readConnectionProfiles(fallback)
+ state.profiles[0].connection = hosted
+ persistConnectionProfiles(state)
+ expect(
+ readConnectionProfiles(fallback).profiles[0].connection.serviceSelection,
+ ).toBe('volcengine')
+ expect(
+ normalizeProfileConnection({ ...fallback, serviceSelection: 'volcengine' })
+ .serviceSelection,
+ ).toBe('volcengine')
+})
+it.each(['', 'not-url', 'file:///tmp/ov', 'https://name:[email protected]'])(
+ 'rejects invalid or credential-bearing address %s',
+ (value) => {
+ expect(isValidConnectionUrl(value)).toBe(false)
+ },
+)
+it.each([
+ 'http://10.0.0.1:1933',
+ ' https://api.vikingdb.cn-beijing.volces.com/openviking/ ',
+])('accepts service address %s', (value) => {
+ expect(isValidConnectionUrl(value)).toBe(true)
+})
+it('migrates the legacy connection with credentials and an explicit service type', () => {
+ const value = readConnectionProfiles(fallback)
+ expect(value.profiles[0].connection).toEqual({
+ ...fallback,
+ serviceSelection: 'opensource',
+ })
+ expect(
+ readConnectionProfiles({
+ ...fallback,
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ }).profiles[0].connection.serviceSelection,
+ ).toBe('volcengine')
+})
+it('restores the enabled profile instead of overwriting it with startup defaults', () => {
+ const value = readConnectionProfiles(fallback)
+ value.profiles.push({
+ id: 'cloud',
+ name: 'Cloud',
+ connection: {
+ ...fallback,
+ serviceSelection: 'volcengine',
+ apiKey: 'cloud-key',
+ },
+ })
+ value.activeId = 'cloud'
+ persistConnectionProfiles(value)
+ expect(readConnectionProfiles({ ...fallback, apiKey: 'env-key' })).toEqual(
+ value,
+ )
+ const changed = updateActiveProfile(value, {
+ ...value.profiles[1].connection,
+ userId: 'resolved-user',
+ })
+ expect(changed.profiles[0]).toEqual(value.profiles[0])
+ expect(changed.profiles[1].connection.userId).toBe('resolved-user')
+})
+it('recovers a missing active ID and ignores malformed records without losing the legacy key', () => {
+ const value = readConnectionProfiles(fallback)
+ persistConnectionProfiles({ ...value, activeId: 'missing' })
+ expect(readConnectionProfiles(fallback).activeId).toBe('default')
+ localStorage.setItem('ov_console_connection_profiles', '{ broken')
+ expect(readConnectionProfiles(fallback).profiles[0].connection.apiKey).toBe(
+ 'legacy-key',
+ )
+})
diff --git a/web-studio/src/lib/connection/profiles.ts b/web-studio/src/lib/connection/profiles.ts
new file mode 100644
index 000000000..98e682eab
--- /dev/null
+++ b/web-studio/src/lib/connection/profiles.ts
@@ -0,0 +1,142 @@
+import type { ConnectionDraft } from '#/lib/connection/types'
+import { resolveConfiguredServiceProvider } from '../studio-service'
+
+export const PROFILES_STORAGE_KEY = 'ov_console_connection_profiles'
+
+export type ConnectionProfile = {
+ id: string
+ name: string
+ connection: ConnectionDraft
+}
+export type ConnectionProfiles = {
+ activeId: string
+ profiles: Array<ConnectionProfile>
+}
+
+export function isValidConnectionUrl(value: string): boolean {
+ try {
+ const url = new URL(value.trim())
+ return (
+ ['http:', 'https:'].includes(url.protocol) &&
+ !url.username &&
+ !url.password
+ )
+ } catch {
+ return false
+ }
+}
+
+// Display and runtime must use the same provider, including official hosted URLs.
+export function normalizeProfileConnection(
+ connection: ConnectionDraft,
+): ConnectionDraft {
+ const provider = resolveConfiguredServiceProvider(
+ connection.baseUrl,
+ connection.serviceSelection,
+ )
+ return {
+ ...connection,
+ serviceSelection: provider === 'volcengine' ? 'volcengine' : 'opensource',
+ }
+}
+
+export function connectionProfileFingerprint(
+ connection: ConnectionDraft,
+): string {
+ const normalized = normalizeProfileConnection(connection)
+ return JSON.stringify([
+ normalized.serviceSelection,
+ normalized.baseUrl.trim().replace(/\/+$/, ''),
+ normalized.accountId,
+ normalized.userId,
+ normalized.apiKey,
+ normalized.adminApiKey,
+ ])
+}
+
+export function readConnectionProfiles(
+ fallback: ConnectionDraft,
+): ConnectionProfiles {
+ try {
+ const raw: unknown = JSON.parse(
+ localStorage.getItem(PROFILES_STORAGE_KEY) || 'null',
+ )
+ if (
+ raw &&
+ typeof raw === 'object' &&
+ 'profiles' in raw &&
+ 'activeId' in raw &&
+ Array.isArray(raw.profiles)
+ ) {
+ const profiles = raw.profiles.filter(
+ (profile): profile is ConnectionProfile => {
+ if (!profile || typeof profile !== 'object') return false
+ const connection = profile.connection
+ return (
+ typeof profile.id === 'string' &&
+ Boolean(profile.id) &&
+ typeof profile.name === 'string' &&
+ Boolean(profile.name.trim()) &&
+ connection &&
+ typeof connection === 'object' &&
+ ['accountId', 'userId', 'apiKey', 'adminApiKey', 'baseUrl'].every(
+ (key) => typeof connection[key] === 'string',
+ ) &&
+ ['opensource', 'volcengine'].includes(connection.serviceSelection)
+ )
+ },
+ )
+ const unique = profiles
+ .filter(
+ (profile, index) =>
+ profiles.findIndex((p) => p.id === profile.id) === index,
+ )
+ .map((profile) => ({
+ ...profile,
+ connection: normalizeProfileConnection(profile.connection),
+ }))
+ if (unique.length) {
+ return {
+ profiles: unique,
+ activeId: unique.some((p) => p.id === raw.activeId)
+ ? (raw.activeId as string)
+ : unique[0].id,
+ }
+ }
+ }
+ } catch {
+ // Restricted storage or an older malformed value must not lose the legacy connection.
+ }
+ return {
+ activeId: 'default',
+ profiles: [
+ {
+ id: 'default',
+ name: 'Default',
+ connection: normalizeProfileConnection(fallback),
+ },
+ ],
+ }
+}
+
+export function persistConnectionProfiles(value: ConnectionProfiles): void {
+ try {
+ localStorage.setItem(PROFILES_STORAGE_KEY, JSON.stringify(value))
+ } catch {
+ // Match the existing connection persistence in restricted browsers.
+ }
+}
+
+export function updateActiveProfile(
+ value: ConnectionProfiles,
+ connection: ConnectionDraft,
+): ConnectionProfiles {
+ return {
+ ...value,
+ profiles: value.profiles.map((profile) =>
+ profile.id === value.activeId
+ ? { ...profile, connection: normalizeProfileConnection(connection) }
+ : profile,
+ ),
+ }
+}
diff --git a/web-studio/src/lib/connection/types.ts b/web-studio/src/lib/connection/types.ts
new file mode 100644
index 000000000..fc9cdb2e8
--- /dev/null
+++ b/web-studio/src/lib/connection/types.ts
@@ -0,0 +1,12 @@
+import type { ServiceSelection } from '../studio-service'
+
+export type ConnectionRole = 'admin' | 'root' | 'unknown' | 'user'
+
+export type ConnectionDraft = {
+ serviceSelection?: ServiceSelection
+ accountId: string
+ adminApiKey: string
+ apiKey: string
+ baseUrl: string
+ userId: string
+}
diff --git a/web-studio/src/lib/ov-client/client.test.ts b/web-studio/src/lib/ov-client/client.test.ts
index 417a43c95..dbc62cb7a 100644
--- a/web-studio/src/lib/ov-client/client.test.ts
+++ b/web-studio/src/lib/ov-client/client.test.ts
@@ -20,7 +20,7 @@ function readRequestHeader(config: AxiosRequestConfig, name: string): string {
return typeof value === 'string' ? value : ''
}
-function createRecordingClient() {
+function createRecordingClient(baseUrl = 'http://openviking.test') {
const requests: AxiosRequestConfig[] = []
const instance = axios.create({
adapter: async (config) => {
@@ -36,12 +36,45 @@ function createRecordingClient() {
})
const client = createOvClient({
axios: instance,
- baseUrl: 'http://openviking.test',
+ baseUrl,
bindSdkClient: false,
})
return { client, requests }
}
+it('uses the documented hosted Bearer credential and returns to source headers after switching', async () => {
+ const { client, requests } = createRecordingClient(
+ 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ )
+ client.setConnection({ apiKey: 'user-key' })
+ await client.instance.get('/api/v1/fs/ls')
+ expect(readRequestHeader(requests[0], 'Authorization')).toBe(
+ 'Bearer user-key',
+ )
+ expect(readRequestHeader(requests[0], 'X-API-Key')).toBe('')
+ client.setOptions({
+ baseUrl: 'https://proxy.example/openviking',
+ apiKeyAuth: 'bearer',
+ })
+ await client.instance.get('/health', {
+ headers: { Authorization: 'Bearer candidate-key' },
+ })
+ expect(readRequestHeader(requests[1], 'Authorization')).toBe(
+ 'Bearer candidate-key',
+ )
+ client.setOptions({ baseUrl: 'http://localhost:19340' })
+ await client.instance.get('/api/v1/fs/ls')
+ expect(readRequestHeader(requests[2], 'X-API-Key')).toBe('user-key')
+ expect(readRequestHeader(requests[2], 'Authorization')).toBe('')
+ client.setOptions({
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ })
+ client.setConnection({ apiKey: '', adminApiKey: 'source-control-key' })
+ await client.instance.get('/api/v1/fs/ls')
+ expect(readRequestHeader(requests[3], 'Authorization')).toBe('')
+ expect(readRequestHeader(requests[3], 'X-API-Key')).toBe('')
+})
+
describe('createOvClient API key selection', () => {
it('uses the data API key for dashboard metrics when both keys are configured', async () => {
const { client, requests } = createRecordingClient()
diff --git a/web-studio/src/lib/ov-client/client.ts b/web-studio/src/lib/ov-client/client.ts
index 0c9072ee3..b134bdfd6 100644
--- a/web-studio/src/lib/ov-client/client.ts
+++ b/web-studio/src/lib/ov-client/client.ts
@@ -1,4 +1,5 @@
import axios, { AxiosHeaders } from 'axios'
+import { resolveApiKeyAuth } from '#/lib/connection/auth'
import type { InternalAxiosRequestConfig } from 'axios'
import { createClient } from '#/gen/ov-client/client'
@@ -153,6 +154,9 @@ function isEnvelopeError(value: unknown): value is OvErrorEnvelope & {
export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {
const bindSdkClient = options.bindSdkClient ?? false
let runtimeOptions = {
+ apiKeyAuth:
+ options.apiKeyAuth ??
+ resolveApiKeyAuth(normalizeBaseUrl(options.baseUrl)),
apiKeyStorageKey: options.apiKeyStorageKey ?? DEFAULT_API_KEY_STORAGE_KEY,
baseUrl: normalizeBaseUrl(options.baseUrl),
defaultTelemetry: options.defaultTelemetry ?? true,
@@ -184,11 +188,22 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {
headers.set(key, value)
}
- if (!readHeader(headers, 'X-API-Key')?.trim()) {
- const apiKey = shouldUseAdminApiKey(config)
- ? connection.adminApiKey || connection.apiKey
- : connection.apiKey || connection.adminApiKey
- setOptionalHeader(headers, 'X-API-Key', apiKey)
+ const credentialHeader =
+ runtimeOptions.apiKeyAuth === 'bearer' ? 'Authorization' : 'X-API-Key'
+ if (!readHeader(headers, credentialHeader)?.trim()) {
+ const apiKey =
+ runtimeOptions.apiKeyAuth === 'bearer'
+ ? connection.apiKey
+ : shouldUseAdminApiKey(config)
+ ? connection.adminApiKey || connection.apiKey
+ : connection.apiKey || connection.adminApiKey
+ setOptionalHeader(
+ headers,
+ credentialHeader,
+ apiKey && runtimeOptions.apiKeyAuth === 'bearer'
+ ? `Bearer ${apiKey}`
+ : apiKey,
+ )
}
if (connection.identityHeaders) {
if (!readHeader(headers, 'X-OpenViking-Account')?.trim()) {
@@ -290,6 +305,11 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {
): Readonly<typeof runtimeOptions> {
const previousStorageKey = runtimeOptions.apiKeyStorageKey
runtimeOptions = {
+ apiKeyAuth:
+ next.apiKeyAuth ??
+ (next.baseUrl !== undefined
+ ? resolveApiKeyAuth(normalizeBaseUrl(next.baseUrl))
+ : runtimeOptions.apiKeyAuth),
apiKeyStorageKey:
next.apiKeyStorageKey ?? runtimeOptions.apiKeyStorageKey,
baseUrl:
diff --git a/web-studio/src/lib/ov-client/types.ts b/web-studio/src/lib/ov-client/types.ts
index 7304c6388..e97a09691 100644
--- a/web-studio/src/lib/ov-client/types.ts
+++ b/web-studio/src/lib/ov-client/types.ts
@@ -1,6 +1,7 @@
import type { AxiosInstance, AxiosResponse } from 'axios'
import type { Client } from '#/gen/ov-client/client'
+import type { ApiKeyAuth } from '#/lib/connection/auth'
export const DEFAULT_API_KEY_STORAGE_KEY = 'ov_console_api_key'
@@ -13,6 +14,7 @@ export interface OvConnectionState {
}
export interface OvClientOptions {
+ apiKeyAuth?: ApiKeyAuth
apiKeyStorageKey?: string
axios?: AxiosInstance
baseUrl?: string
@@ -29,17 +31,26 @@ export interface OvClientAdapter {
getConnection: () => Readonly<OvConnectionState>
getOptions: () => Readonly<
Required<
- Pick<OvClientOptions, 'apiKeyStorageKey' | 'baseUrl' | 'defaultTelemetry'>
+ Pick<
+ OvClientOptions,
+ 'apiKeyStorageKey' | 'baseUrl' | 'defaultTelemetry' | 'apiKeyAuth'
+ >
>
>
setConnection: (next: Partial<OvConnectionState>) => OvConnectionState
setOptions: (
next: Partial<
- Pick<OvClientOptions, 'apiKeyStorageKey' | 'baseUrl' | 'defaultTelemetry'>
+ Pick<
+ OvClientOptions,
+ 'apiKeyStorageKey' | 'baseUrl' | 'defaultTelemetry' | 'apiKeyAuth'
+ >
>,
) => Readonly<
Required<
- Pick<OvClientOptions, 'apiKeyStorageKey' | 'baseUrl' | 'defaultTelemetry'>
+ Pick<
+ OvClientOptions,
+ 'apiKeyStorageKey' | 'baseUrl' | 'defaultTelemetry' | 'apiKeyAuth'
+ >
>
>
}
diff --git a/web-studio/src/lib/resource-acl.ts b/web-studio/src/lib/resource-acl.ts
index f1c23c7dd..eaf880981 100644
--- a/web-studio/src/lib/resource-acl.ts
+++ b/web-studio/src/lib/resource-acl.ts
@@ -1,5 +1,5 @@
import { createOvClient, getOvResult } from '#/lib/ov-client'
-import type { ConnectionDraft } from '#/hooks/use-app-connection'
+import type { ConnectionDraft } from '#/lib/connection/types'
import type { FSListResult } from '@ov-server/api/v1/fs'
export type AclLevel = 'read' | 'write' | 'manage'
diff --git a/web-studio/src/lib/sessions/api.test.ts b/web-studio/src/lib/sessions/api.test.ts
index fc88829ca..1c6b07dc7 100644
--- a/web-studio/src/lib/sessions/api.test.ts
+++ b/web-studio/src/lib/sessions/api.test.ts
@@ -12,14 +12,17 @@ const {
getSessionBySessionIdMock,
getSessionIdArchiveByArchiveIdMock,
getSessionIdContextMock,
+ getContentReadMock,
} = vi.hoisted(() => ({
getSessionBySessionIdMock: vi.fn(),
getSessionIdArchiveByArchiveIdMock: vi.fn(),
getSessionIdContextMock: vi.fn(),
+ getContentReadMock: vi.fn(),
}))
vi.mock('#/gen/ov-client/sdk.gen', () => ({
deleteSessionBySessionId: vi.fn(),
+ getContentRead: getContentReadMock,
getSessionBySessionId: getSessionBySessionIdMock,
getSessionIdArchiveByArchiveId: getSessionIdArchiveByArchiveIdMock,
getSessionIdContext: getSessionIdContextMock,
@@ -53,6 +56,7 @@ describe('fetchSessionMessages', () => {
getSessionBySessionIdMock.mockReset()
getSessionIdArchiveByArchiveIdMock.mockReset()
getSessionIdContextMock.mockReset()
+ getContentReadMock.mockReset()
})
it('combines completed archives with current context in chronological order', async () => {
@@ -85,6 +89,207 @@ describe('fetchSessionMessages', () => {
})
})
+ it('reads hosted current context without requesting optional archives', async () => {
+ getSessionIdContextMock.mockReturnValue(
+ response({ messages: [message('current', 'readable')] }),
+ )
+ getSessionIdArchiveByArchiveIdMock.mockRejectedValue(
+ new OvClientError({
+ code: 'ApiBlocked',
+ statusCode: 403,
+ message: 'Not exposed',
+ }),
+ )
+ const result = await fetchSessionMessages(
+ 'hosted-session',
+ { commit_count: 2 } as Parameters<typeof fetchSessionMessages>[1],
+ 'none',
+ )
+ expect(result.map(({ id }) => id)).toEqual(['current'])
+ expect(getSessionIdArchiveByArchiveIdMock).not.toHaveBeenCalled()
+ })
+
+ it('keeps readable current messages when context includes a system record', async () => {
+ getSessionIdContextMock.mockReturnValue(
+ response({
+ messages: [
+ { ...message('system', 'instructions'), role: 'system' },
+ message('user', 'question'),
+ { ...message('assistant', 'answer'), role: 'assistant' },
+ ],
+ }),
+ )
+
+ const result = await fetchSessionMessages('s', undefined, 'none')
+
+ expect(result.map(({ id }) => id)).toEqual(['user', 'assistant'])
+ })
+
+ it.each(['api', 'content'] as const)(
+ 'keeps readable %s archive messages when history includes a system record',
+ async (source) => {
+ const messages = [
+ message('user', 'question'),
+ { ...message('system', 'instructions'), role: 'system' },
+ { ...message('assistant', 'answer'), role: 'assistant' },
+ ]
+ getSessionIdContextMock.mockReturnValue(response({ messages: [] }))
+ getSessionIdArchiveByArchiveIdMock.mockReturnValue(response({ messages }))
+ getContentReadMock.mockReturnValue(
+ response(messages.map((row) => JSON.stringify(row)).join('\n')),
+ )
+
+ const result = await fetchSessionMessages(
+ 's',
+ { commit_count: 1, uri: 'viking://user/u/sessions/s' } as Parameters<
+ typeof fetchSessionMessages
+ >[1],
+ source,
+ )
+
+ expect(result.map(({ id }) => id)).toEqual(['user', 'assistant'])
+ },
+ )
+
+ it('loads hosted archives through content read when current context is empty', async () => {
+ getSessionIdContextMock.mockReturnValue(response({ messages: [] }))
+ getContentReadMock.mockReturnValue(
+ response(
+ [
+ message('old-user', 'question'),
+ { ...message('old-assistant', 'answer'), role: 'assistant' },
+ ]
+ .map((row) => JSON.stringify(row))
+ .join('\n') + '\n',
+ ),
+ )
+ const result = await fetchSessionMessages(
+ 'hosted-session',
+ {
+ commit_count: 1,
+ uri: 'viking://user/wulv/sessions/hosted-session/',
+ } as Parameters<typeof fetchSessionMessages>[1],
+ 'content',
+ )
+ expect(result.map(({ id }) => id)).toEqual(['old-user', 'old-assistant'])
+ expect(getSessionIdArchiveByArchiveIdMock).not.toHaveBeenCalled()
+ expect(getContentReadMock).toHaveBeenCalledWith({
+ query: {
+ uri: 'viking://user/wulv/sessions/hosted-session/history/archive_001/messages.jsonl',
+ offset: 0,
+ limit: -1,
+ raw: true,
+ },
+ })
+ })
+
+ it('merges hosted archives in order and deduplicates retained current messages', async () => {
+ getSessionIdContextMock.mockReturnValue(
+ response({ messages: [message('2', 'two'), message('3', 'three')] }),
+ )
+ getContentReadMock
+ .mockReturnValueOnce(response(JSON.stringify(message('1', 'one'))))
+ .mockReturnValueOnce(response(JSON.stringify(message('2', 'two'))))
+ const result = await fetchSessionMessages(
+ 's',
+ { commit_count: 2, uri: 'viking://user/u/sessions/s' } as Parameters<
+ typeof fetchSessionMessages
+ >[1],
+ 'content',
+ )
+ expect(result.map(({ id }) => id)).toEqual(['1', '2', '3'])
+ })
+
+ it('reports malformed archive lines instead of silently showing an empty session', async () => {
+ getSessionIdContextMock.mockReturnValue(response({ messages: [] }))
+ getContentReadMock.mockReturnValue(response('{invalid json}'))
+ await expect(
+ fetchSessionMessages(
+ 's',
+ { commit_count: 1, uri: 'viking://user/u/sessions/s' } as Parameters<
+ typeof fetchSessionMessages
+ >[1],
+ 'content',
+ ),
+ ).rejects.toThrow('archive_001')
+ })
+
+ it.each([
+ response({ content: 'unexpected envelope' }),
+ response(JSON.stringify({ ...message('bad', 'text'), parts: [null] })),
+ ])(
+ 'rejects invalid archive shapes with a useful archive location',
+ async (archive) => {
+ getSessionIdContextMock.mockReturnValue(response({ messages: [] }))
+ getContentReadMock.mockReturnValue(archive)
+ await expect(
+ fetchSessionMessages(
+ 's',
+ {
+ commit_count: 1,
+ uri: 'viking://user/u/sessions/s',
+ } as Parameters<typeof fetchSessionMessages>[1],
+ 'content',
+ ),
+ ).rejects.toThrow('archive_001')
+ },
+ )
+
+ it('preserves access failures instead of treating protected history as empty', async () => {
+ getSessionIdContextMock.mockReturnValue(response({ messages: [] }))
+ getContentReadMock.mockRejectedValue(
+ new OvClientError({
+ code: 'FORBIDDEN',
+ statusCode: 403,
+ message: 'History access denied',
+ }),
+ )
+ await expect(
+ fetchSessionMessages(
+ 's',
+ {
+ commit_count: 1,
+ uri: 'viking://user/u/sessions/s',
+ } as Parameters<typeof fetchSessionMessages>[1],
+ 'content',
+ ),
+ ).rejects.toThrow('History access denied')
+ })
+
+ it.each(['api', 'content'] as const)(
+ 'validates the same message contract for %s archives',
+ async (source) => {
+ const invalid = {
+ ...message('bad', 'text'),
+ parts: [{ type: 'text', text: 123 }],
+ }
+ getSessionIdContextMock.mockReturnValue(response({ messages: [] }))
+ getSessionIdArchiveByArchiveIdMock.mockReturnValue(
+ response({ messages: [invalid] }),
+ )
+ getContentReadMock.mockReturnValue(response(JSON.stringify(invalid)))
+ await expect(
+ fetchSessionMessages(
+ 's',
+ {
+ commit_count: 1,
+ uri: 'viking://user/u/sessions/s',
+ } as Parameters<typeof fetchSessionMessages>[1],
+ source,
+ ),
+ ).rejects.toThrow('invalid message')
+ },
+ )
+
+ it('reports malformed current messages rather than silently dropping them', async () => {
+ getSessionIdContextMock.mockReturnValue(
+ response({ messages: [{ id: 'bad', role: 'user', parts: null }] }),
+ )
+ await expect(fetchSessionMessages('s', undefined, 'none')).rejects.toThrow(
+ 'invalid message',
+ )
+ })
+
it('keeps readable history when an unfinished archive is unavailable', async () => {
getSessionBySessionIdMock.mockReturnValue(response({ commit_count: 2 }))
getSessionIdArchiveByArchiveIdMock
diff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.ts
index 01d7cc5bc..1628d662c 100644
--- a/web-studio/src/lib/sessions/api.ts
+++ b/web-studio/src/lib/sessions/api.ts
@@ -1,3 +1,4 @@
+import { parseSessionArchive, parseSessionMessages } from './parse-messages'
import {
deleteSessionBySessionId,
getContentRead,
@@ -99,18 +100,30 @@ export async function deleteSession(
// Session Messages
// ---------------------------------------------------------------------------
-function isMessage(value: unknown): value is Message {
- return (
- typeof value === 'object' &&
- value !== null &&
- 'id' in value &&
- 'role' in value &&
- 'parts' in value
- )
-}
+export type SessionHistorySource = 'api' | 'content' | 'none'
-function getMessages(value: unknown): Message[] {
- return Array.isArray(value) ? value.filter(isMessage) : []
+async function fetchArchiveFileMessages(
+ session: SessionMeta,
+ archiveId: string,
+): Promise<Message[]> {
+ // Use the server's session URI: hosted user space names need not match user IDs.
+ if (!session.uri) {
+ throw new OvClientError({
+ code: 'INVALID_SESSION_ARCHIVE',
+ message: 'Session URI is missing',
+ })
+ }
+ const result = await getOvResult<unknown>(
+ getContentRead({
+ query: {
+ uri: `${session.uri.replace(/\/+$/, '')}/history/${archiveId}/messages.jsonl`,
+ offset: 0,
+ limit: -1,
+ raw: true,
+ } as Parameters<typeof getContentRead>[0]['query'] & { raw?: boolean },
+ }),
+ )
+ return parseSessionArchive(result, archiveId)
}
function deduplicateMessages(messages: Message[]): Message[] {
@@ -160,6 +173,7 @@ function isMissingArchive(error: unknown): boolean {
export async function fetchSessionMessages(
sessionId: string,
sessionMeta?: SessionMeta,
+ historySource: SessionHistorySource = 'api',
): Promise<Message[]> {
const context = await getOvResult<SessionContextResult>(
getSessionIdContext({
@@ -167,9 +181,12 @@ export async function fetchSessionMessages(
}),
)
+ if (historySource === 'none') return parseSessionMessages(context.messages)
+
let commitCount = 0
+ let session = sessionMeta
try {
- const session = sessionMeta ?? (await fetchSession(sessionId))
+ session ??= await fetchSession(sessionId)
commitCount = Math.max(0, Math.floor(session.commit_count || 0))
} catch {
// Older servers may not expose session details. Current context is still
@@ -185,20 +202,22 @@ export async function fetchSessionMessages(
SESSION_ARCHIVE_CONCURRENCY,
async (archiveId) => {
try {
- return await fetchSessionArchive(sessionId, archiveId)
+ return historySource === 'content'
+ ? await fetchArchiveFileMessages(session!, archiveId)
+ : parseSessionMessages(
+ (await fetchSessionArchive(sessionId, archiveId)).messages,
+ )
} catch (error) {
if (isMissingArchive(error)) return null
throw error
}
},
)
- const archivedMessages = archives.flatMap((archive) =>
- archive ? getMessages(archive.messages) : [],
- )
+ const archivedMessages = archives.flatMap((archive) => archive ?? [])
return deduplicateMessages([
...archivedMessages,
- ...getMessages(context.messages),
+ ...parseSessionMessages(context.messages),
])
}
@@ -238,7 +257,7 @@ export async function fetchSessionFirstTitle(
}
function firstUserTitle(value: unknown): string {
- const first = getMessages(value).find(
+ const first = parseSessionMessages(value).find(
(message) =>
message.role === 'user' &&
message.parts.some((part) => part.type === 'text' && part.text.trim()),
diff --git a/web-studio/src/lib/sessions/history-source.ts b/web-studio/src/lib/sessions/history-source.ts
new file mode 100644
index 000000000..273aab9d8
--- /dev/null
+++ b/web-studio/src/lib/sessions/history-source.ts
@@ -0,0 +1,14 @@
+import { resolveConfiguredServiceProvider } from '../studio-service'
+import type { ConnectionDraft } from '../connection/types'
+import type { SessionHistorySource } from './api'
+
+export function resolveSessionHistorySource(
+ connection: ConnectionDraft,
+): SessionHistorySource {
+ return resolveConfiguredServiceProvider(
+ connection.baseUrl,
+ connection.serviceSelection,
+ ) === 'volcengine'
+ ? 'content'
+ : 'api'
+}
diff --git a/web-studio/src/lib/sessions/parse-messages.ts b/web-studio/src/lib/sessions/parse-messages.ts
new file mode 100644
index 000000000..e93251761
--- /dev/null
+++ b/web-studio/src/lib/sessions/parse-messages.ts
@@ -0,0 +1,86 @@
+import { OvClientError } from '#/lib/ov-client/errors'
+import type { Message } from './types/message'
+
+function invalidMessage(location: string): never {
+ throw new OvClientError({
+ code: 'INVALID_SESSION_MESSAGE',
+ message: `${location}: invalid message`,
+ })
+}
+
+/** Both API and persisted JSONL messages cross the same validation seam. */
+export function parseSessionMessages(
+ value: unknown,
+ location = 'Session messages',
+): Message[] {
+ if (value === undefined) return []
+ if (!Array.isArray(value)) invalidMessage(location)
+ return value.flatMap((message: unknown, index): Message[] => {
+ const at = `${location}, message ${index + 1}`
+ if (
+ !message ||
+ typeof message !== 'object' ||
+ !('id' in message) ||
+ typeof message.id !== 'string' ||
+ !('role' in message) ||
+ (message.role !== 'user' &&
+ message.role !== 'assistant' &&
+ message.role !== 'system') ||
+ !('parts' in message) ||
+ !Array.isArray(message.parts) ||
+ message.parts.some((part: unknown) => {
+ if (
+ !part ||
+ typeof part !== 'object' ||
+ !('type' in part) ||
+ typeof part.type !== 'string'
+ )
+ return true
+ if (part.type === 'text')
+ return !('text' in part) || typeof part.text !== 'string'
+ if (part.type === 'reasoning')
+ return !('reasoning' in part) || typeof part.reasoning !== 'string'
+ return false
+ })
+ )
+ invalidMessage(at)
+ // System records are valid session history, but this UI only renders
+ // user and assistant messages. Never present a system prompt as an answer.
+ if (message.role === 'system') return []
+ return [
+ {
+ ...message,
+ created_at:
+ 'created_at' in message && typeof message.created_at === 'string'
+ ? message.created_at
+ : '',
+ } as Message,
+ ]
+ })
+}
+
+export function parseSessionArchive(
+ value: unknown,
+ archiveId: string,
+): Message[] {
+ if (typeof value !== 'string') {
+ throw new OvClientError({
+ code: 'INVALID_SESSION_ARCHIVE',
+ message: `${archiveId}: expected JSONL content`,
+ })
+ }
+ return value.split(/\r?\n/).flatMap((line, index) => {
+ if (!line.trim()) return []
+ const at = `${archiveId}: line ${index + 1}`
+ let message: unknown
+ try {
+ message = JSON.parse(line)
+ } catch {
+ throw new OvClientError({
+ code: 'INVALID_SESSION_ARCHIVE',
+ message: `${at}: invalid JSON`,
+ })
+ }
+ return parseSessionMessages([message], at)
+ })
+}
diff --git a/web-studio/src/lib/sessions/use-chat-connection.test.tsx b/web-studio/src/lib/sessions/use-chat-connection.test.tsx
new file mode 100644
index 000000000..dbea54445
--- /dev/null
+++ b/web-studio/src/lib/sessions/use-chat-connection.test.tsx
@@ -0,0 +1,90 @@
+// @vitest-environment jsdom
+import { act, renderHook } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+import { useChat } from './use-chat'
+import { ovClient } from '#/lib/ov-client'
+
+const mocks = vi.hoisted(() => ({ stream: vi.fn(), postMessage: vi.fn() }))
+vi.mock('./api', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ sendChatStream: mocks.stream,
+}))
+vi.mock('#/gen/ov-client/sdk.gen', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ postSessionIdMessages: mocks.postMessage,
+}))
+vi.mock('./use-session-titles', () => ({ setSessionTitle: vi.fn() }))
+const originalOptions = ovClient.getOptions()
+afterEach(() => {
+ ovClient.setOptions(originalOptions)
+ vi.clearAllMocks()
+})
+
+it('does not persist a completed stream after its owner unmounts and the connection changes', async () => {
+ let finish!: () => void
+ const pause = new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ let signal!: AbortSignal
+ mocks.stream.mockImplementation(async (_request, abortSignal) => {
+ signal = abortSignal
+ return (async function* () {
+ await pause
+ if (signal.aborted) return
+ yield {
+ data: JSON.stringify({
+ event: 'response',
+ data: { content: 'synthetic source response' },
+ }),
+ }
+ })()
+ })
+ const writes: string[] = []
+ mocks.postMessage.mockImplementation(async () => {
+ writes.push(ovClient.getOptions().baseUrl)
+ return { data: { status: 'ok', result: {} } }
+ })
+ ovClient.setOptions({ baseUrl: 'http://source.example' })
+ const view = renderHook(() =>
+ useChat({ sessionId: 'same-session-id', identityScopeKey: 'source-scope' }),
+ )
+ let sending!: Promise<void>
+ await act(async () => {
+ sending = view.result.current.send('synthetic source message')
+ })
+ view.unmount()
+ ovClient.setOptions({ baseUrl: 'http://other.example' })
+ await act(async () => {
+ finish()
+ await sending
+ })
+ expect(writes).toEqual([])
+})
+
+it('does not send the assistant message to a changed connection after the user write finishes', async () => {
+ mocks.stream.mockResolvedValue(
+ (async function* () {
+ yield {
+ data: JSON.stringify({
+ event: 'response',
+ data: { content: 'synthetic response' },
+ }),
+ }
+ })(),
+ )
+ const writes: string[] = []
+ mocks.postMessage.mockImplementation(async () => {
+ writes.push(ovClient.getOptions().baseUrl)
+ ovClient.setOptions({ baseUrl: 'http://other.example' })
+ return { data: { status: 'ok', result: {} } }
+ })
+ ovClient.setOptions({ baseUrl: 'http://source.example' })
+ const view = renderHook(() =>
+ useChat({ sessionId: 'same-session-id', identityScopeKey: 'source-scope' }),
+ )
+ await act(async () => {
+ await view.result.current.send('synthetic message')
+ })
+ expect(writes).toEqual(['http://source.example'])
+ view.unmount()
+})
diff --git a/web-studio/src/lib/sessions/use-chat.ts b/web-studio/src/lib/sessions/use-chat.ts
index a935a7b10..00441fe13 100644
--- a/web-studio/src/lib/sessions/use-chat.ts
+++ b/web-studio/src/lib/sessions/use-chat.ts
@@ -15,6 +15,7 @@ import { addMessage, sendChatStream, serializeParts } from './api'
import { parseSseStream, streamEventDataToText } from './sse'
import { setSessionTitle } from './use-session-titles'
import { createBrowserId } from '../browser-crypto'
+import { ovClient } from '#/lib/ov-client'
function createUserMessage(content: string): Message {
return {
@@ -187,6 +188,17 @@ export function useChat(options: UseChatOptions): UseChatReturn {
const pendingInitialMessagesRef = useRef<Message[] | undefined>(undefined)
messagesRef.current = messages
+ const ownerRef = useRef(0)
+
+ // Cancel work when its session/identity owner changes or unmounts.
+ useEffect(() => {
+ ownerRef.current += 1
+ return () => {
+ ownerRef.current += 1
+ abortRef.current?.abort()
+ }
+ }, [identityScopeKey, sessionId])
+
// Reset state when sessionId changes
useEffect(() => {
abortRef.current?.abort()
@@ -201,7 +213,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {
setStreamingReasoning('')
setStreamingParts([])
setIteration(0)
- }, [sessionId])
+ }, [identityScopeKey, sessionId])
// Sync initialMessages into state when they load or when switching sessions.
useEffect(() => {
@@ -259,6 +271,16 @@ export function useChat(options: UseChatOptions): UseChatReturn {
const controller = new AbortController()
abortRef.current = controller
+ const owner = ownerRef.current
+ const connectionSnapshot = JSON.stringify([
+ ovClient.getOptions(),
+ ovClient.getConnection(),
+ ])
+ const isCurrent = () =>
+ owner === ownerRef.current &&
+ connectionSnapshot ===
+ JSON.stringify([ovClient.getOptions(), ovClient.getConnection()])
+ const canPersist = () => isCurrent() && !controller.signal.aborted
// Accumulators (mutable for performance during streaming)
let accContent = ''
@@ -505,6 +527,10 @@ export function useChat(options: UseChatOptions): UseChatReturn {
}
}
+ if (!isCurrent()) return
+ if (controller.signal.aborted)
+ throw new DOMException('Aborted', 'AbortError')
+
// Build assistant message and finalize
finishCurrentReasoning()
const assistantMsg = buildAssistantMessage(
@@ -520,10 +546,11 @@ export function useChat(options: UseChatOptions): UseChatReturn {
setMessages((prev) => [...prev, assistantMsg])
// Persist to openviking session (bot doesn't do this automatically)
- if (persistMessages) {
+ if (persistMessages && canPersist()) {
try {
// Sequential: user message must precede assistant message
await addMessage(sessionId, 'user', displayMessage)
+ if (!canPersist()) return
await addMessage(
sessionId,
'assistant',
@@ -536,7 +563,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {
}
// Generate session title on first exchange
- if (sessionId && isFirstExchange) {
+ if (isCurrent() && sessionId && isFirstExchange) {
// Immediate: use first user message as temp title
setSessionTitle(
identityScopeKey,
@@ -545,6 +572,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {
)
}
} catch (err) {
+ if (!isCurrent()) return
if (controller.signal.aborted) {
// Aborted intentionally — still finalize any partial content
if (accContent || accParts.length > 0) {
@@ -572,7 +600,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {
setStatus('error')
}
} finally {
- abortRef.current = null
+ if (abortRef.current === controller) abortRef.current = null
}
},
[identityScopeKey, persistMessages, sessionId, status],
diff --git a/web-studio/src/lib/sessions/use-session-history.test.tsx b/web-studio/src/lib/sessions/use-session-history.test.tsx
new file mode 100644
index 000000000..a224eead8
--- /dev/null
+++ b/web-studio/src/lib/sessions/use-session-history.test.tsx
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+import { cleanup, renderHook, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import type { ReactNode } from 'react'
+import type * as SessionApi from './api'
+import { afterEach, expect, it, vi } from 'vitest'
+import { useSessionMessages } from './use-sessions'
+
+const state = vi.hoisted(() => ({
+ connection: { baseUrl: 'http://oss.test', serviceSelection: 'opensource' },
+ fetchMessages: vi.fn(),
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({ connection: state.connection }),
+}))
+vi.mock('./api', async (original) => ({
+ ...(await original<typeof SessionApi>()),
+ fetchSession: vi.fn().mockResolvedValue({ commit_count: 1 }),
+ fetchSessionMessages: state.fetchMessages,
+}))
+afterEach(cleanup)
+
+it('selects the matching history adapter without requiring the view to know transport', async () => {
+ state.connection = {
+ baseUrl: 'http://oss.test',
+ serviceSelection: 'opensource',
+ }
+ state.fetchMessages.mockImplementation(async (_id, _meta, source) => [
+ { id: source, role: 'user', parts: [{ type: 'text', text: source }] },
+ ])
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ )
+ try {
+ const view = renderHook(() => useSessionMessages('s'), { wrapper })
+ await waitFor(() => expect(view.result.current.data?.[0].id).toBe('api'))
+ state.connection = {
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ serviceSelection: 'opensource',
+ }
+ view.rerender()
+ await waitFor(() =>
+ expect(view.result.current.data?.[0].id).toBe('content'),
+ )
+ state.connection = {
+ baseUrl: 'http://oss.test',
+ serviceSelection: 'opensource',
+ }
+ view.rerender()
+ await waitFor(() => expect(view.result.current.data?.[0].id).toBe('api'))
+ } finally {
+ client.clear()
+ }
+})
diff --git a/web-studio/src/lib/sessions/use-sessions.ts b/web-studio/src/lib/sessions/use-sessions.ts
index fe15e0945..c48abdf3a 100644
--- a/web-studio/src/lib/sessions/use-sessions.ts
+++ b/web-studio/src/lib/sessions/use-sessions.ts
@@ -10,6 +10,8 @@ import {
fetchSessions,
} from './api'
import type { Message } from './types/message'
+import { resolveSessionHistorySource } from './history-source'
+import { useAppConnection } from '#/hooks/use-app-connection'
import type { SessionMemoryDiff } from './memory-diff'
import type { SessionListItem, SessionMeta } from '@ov-server/api/v1/sessions'
@@ -70,17 +72,19 @@ export function useSession(sessionId: string | undefined) {
/** Fetch message history for a session. */
export function useSessionMessages(sessionId: string | undefined) {
+ const { connection } = useAppConnection()
+ const historySource = resolveSessionHistorySource(connection)
const queryClient = useQueryClient()
return useQuery<Message[]>({
- queryKey: [...SESSIONS_KEY, sessionId, 'messages'],
+ queryKey: [...SESSIONS_KEY, sessionId, 'messages', historySource],
queryFn: async () => {
const session = await queryClient.fetchQuery({
queryFn: () => fetchSession(sessionId!),
queryKey: [...SESSIONS_KEY, sessionId],
staleTime: 15_000,
})
- return fetchSessionMessages(sessionId!, session)
+ return fetchSessionMessages(sessionId!, session, historySource)
},
enabled: Boolean(sessionId),
staleTime: 30_000, // cache for 30s to avoid flash on session switch
diff --git a/web-studio/src/lib/studio-permissions.test.ts b/web-studio/src/lib/studio-permissions.test.ts
index 5ca42a35b..6a74c6374 100644
--- a/web-studio/src/lib/studio-permissions.test.ts
+++ b/web-studio/src/lib/studio-permissions.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest'
-import { resolveStudioManagementCapabilities } from './studio-permissions'
+import {
+ canEditStudioConfiguration,
+ canManageStudioGateway,
+ resolveStudioManagementCapabilities,
+} from './studio-permissions'
describe('resolveStudioManagementCapabilities', () => {
it('allows a validated root control credential to manage accounts and users', () => {
@@ -73,3 +77,52 @@ describe('resolveStudioManagementCapabilities', () => {
})
})
})
+
+describe('new management feature permissions', () => {
+ const input = {
+ serviceProvider: 'opensource' as const,
+ hasControlCredential: true,
+ isRoleLoading: false,
+ role: 'root' as const,
+ serverMode: 'api_key' as const,
+ }
+ it('allows trusted Gateway access while configuration requires authenticated trusted ROOT', () => {
+ expect(canManageStudioGateway(input)).toBe(true)
+ expect(canManageStudioGateway({ ...input, serverMode: 'trusted' })).toBe(
+ true,
+ )
+ expect(
+ canEditStudioConfiguration({ ...input, serverMode: 'trusted' }),
+ ).toBe(true)
+ expect(canEditStudioConfiguration({ ...input, role: 'admin' })).toBe(false)
+ })
+ it('allows ordinary API-key users and development mode to query Gateway access', () => {
+ expect(
+ canManageStudioGateway({
+ ...input,
+ role: 'user',
+ hasControlCredential: false,
+ }),
+ ).toBe(true)
+ expect(
+ canManageStudioGateway({
+ ...input,
+ serverMode: 'dev',
+ role: 'unknown',
+ hasControlCredential: false,
+ }),
+ ).toBe(true)
+ expect(canManageStudioGateway({ ...input, isRoleLoading: true })).toBe(
+ false,
+ )
+ })
+ it.each(['volcengine', 'unknown'] as const)(
+ 'never grants %s connections native management',
+ (serviceProvider) => {
+ expect(canManageStudioGateway({ ...input, serviceProvider })).toBe(false)
+ expect(canEditStudioConfiguration({ ...input, serviceProvider })).toBe(
+ false,
+ )
+ },
+ )
+})
diff --git a/web-studio/src/lib/studio-permissions.ts b/web-studio/src/lib/studio-permissions.ts
index 802d5f4bf..5087c8aa9 100644
--- a/web-studio/src/lib/studio-permissions.ts
+++ b/web-studio/src/lib/studio-permissions.ts
@@ -1,5 +1,6 @@
-import type { ConnectionRole } from '#/hooks/use-app-connection'
-import type { ServerMode } from '#/hooks/use-server-mode'
+import type { ServiceProvider } from './studio-service'
+import type { ConnectionRole } from '#/lib/connection/types'
+import type { ServerMode } from '#/lib/connection/health'
export type StudioManagementCapabilities = {
canManageAccounts: boolean
@@ -7,17 +8,24 @@ export type StudioManagementCapabilities = {
}
export function resolveStudioManagementCapabilities({
+ serviceProvider = 'opensource',
hasControlCredential,
isRoleLoading,
role,
serverMode,
}: {
+ serviceProvider?: ServiceProvider
hasControlCredential: boolean
isRoleLoading: boolean
role: ConnectionRole
serverMode: ServerMode
}): StudioManagementCapabilities {
- if (isRoleLoading || serverMode === 'dev' || !hasControlCredential) {
+ if (
+ serviceProvider !== 'opensource' ||
+ isRoleLoading ||
+ serverMode === 'dev' ||
+ !hasControlCredential
+ ) {
return {
canManageAccounts: false,
canManageUsers: false,
@@ -29,3 +37,23 @@ export function resolveStudioManagementCapabilities({
canManageUsers: role === 'root' || role === 'admin',
}
}
+
+type ManagementInput = Parameters<typeof resolveStudioManagementCapabilities>[0]
+
+export function canManageStudioGateway(input: ManagementInput): boolean {
+ return (
+ (input.serviceProvider ?? 'opensource') === 'opensource' &&
+ (input.serverMode === 'dev' ||
+ input.serverMode === 'trusted' ||
+ (input.serverMode === 'api_key' &&
+ !input.isRoleLoading &&
+ input.role !== 'unknown'))
+ )
+}
+
+export function canEditStudioConfiguration(input: ManagementInput): boolean {
+ return (
+ (input.serverMode === 'api_key' || input.serverMode === 'trusted') &&
+ resolveStudioManagementCapabilities(input).canManageAccounts
+ )
+}
diff --git a/web-studio/src/lib/studio-service.test.ts b/web-studio/src/lib/studio-service.test.ts
new file mode 100644
index 000000000..a11a91d19
--- /dev/null
+++ b/web-studio/src/lib/studio-service.test.ts
@@ -0,0 +1,191 @@
+import { describe, expect, it } from 'vitest'
+import {
+ classifyCapabilityError,
+ classifyCapabilityResponse,
+ featureForPath,
+ identifyServiceProvider,
+ isStudioFeatureVisible,
+ resolveConfiguredServiceProvider,
+} from './studio-service'
+import { resolveApiKeyAuth } from '#/lib/connection/auth'
+import { resolveStudioManagementCapabilities } from './studio-permissions'
+
+describe('service and permission boundaries', () => {
+ it.each([
+ 'http://10.37.244.186:8020',
+ 'http://172.16.0.1:1933',
+ 'http://172.31.255.255:1933',
+ 'http://192.168.1.20:1933',
+ 'http://127.0.0.2:1933',
+ 'http://[::1]:1933',
+ 'http://203.0.113.1:1933',
+ 'https://custom.company.example/openviking',
+ 'https://api.vikingdb.cn-beijing.volces.com.evil.example/openviking',
+ ])(
+ 'defaults non-hosted deployment %s to open source with header authentication',
+ (url) => {
+ expect(resolveConfiguredServiceProvider(url)).toBe('opensource')
+ expect(resolveApiKeyAuth(url)).toBe('header')
+ expect(resolveConfiguredServiceProvider(url, 'volcengine')).toBe(
+ 'volcengine',
+ )
+ expect(resolveApiKeyAuth(url, 'volcengine')).toBe('bearer')
+ },
+ )
+ it.each(['not a URL', '', 'file:///tmp/openviking'])(
+ 'keeps ambiguous deployment %s unconfirmed',
+ (url) => {
+ expect(identifyServiceProvider(url)).toBe('unknown')
+ },
+ )
+ it('recognizes the official hosted URL without discarding its path', () => {
+ expect(
+ identifyServiceProvider(
+ 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ ),
+ ).toBe('volcengine')
+ expect(
+ identifyServiceProvider(
+ 'https://api.vikingdb.cn-beijing.volces.com.evil.example/openviking',
+ ),
+ ).toBe('opensource')
+ expect(
+ identifyServiceProvider('https://custom.company.example/openviking'),
+ ).toBe('opensource')
+ expect(identifyServiceProvider('http://localhost:1933')).toBe('opensource')
+ })
+ it.each(['volcengine', 'unknown'] as const)(
+ 'never maps %s admin/root data identity into native management',
+ (serviceProvider) => {
+ for (const role of ['admin', 'root'] as const) {
+ expect(
+ resolveStudioManagementCapabilities({
+ serviceProvider,
+ hasControlCredential: true,
+ isRoleLoading: false,
+ role,
+ serverMode: 'api_key',
+ }),
+ ).toEqual({ canManageAccounts: false, canManageUsers: false })
+ }
+ },
+ )
+ it('distinguishes gateway blocking, user permission and uncertain failure', () => {
+ expect(
+ classifyCapabilityError({
+ statusCode: 403,
+ responseBody: { ResponseMetadata: { Error: { Code: 'ApiBlocked' } } },
+ }),
+ ).toBe('unavailable')
+ expect(
+ classifyCapabilityError({ statusCode: 403, code: 'PERMISSION_DENIED' }),
+ ).toBe('forbidden')
+ expect(classifyCapabilityError({ statusCode: 401 })).toBe('unknown')
+ expect(classifyCapabilityError({ statusCode: 500 })).toBe('unknown')
+ expect(classifyCapabilityError({})).toBe('unknown')
+ })
+ it('guards nested deep links with the same domain as navigation', () => {
+ expect(featureForPath('/users/memory-templates')?.domain).toBe('management')
+ expect(featureForPath('/filesystem')?.domain).toBe('workspace')
+ expect(featureForPath('/directory')?.domain).toBe('workspace')
+ })
+})
+
+describe('hosted feature visibility', () => {
+ const monitoring = featureForPath('/monitoring')!
+ it.each([undefined, 'unknown', 'unavailable', 'forbidden'] as const)(
+ 'hides an extension while its capability is %s',
+ (state) => {
+ expect(isStudioFeatureVisible('volcengine', monitoring, state)).toBe(
+ false,
+ )
+ },
+ )
+ it('shows only confirmed extensions, and keeps public workspace navigation', () => {
+ expect(isStudioFeatureVisible('volcengine', monitoring, 'supported')).toBe(
+ true,
+ )
+ expect(
+ isStudioFeatureVisible(
+ 'volcengine',
+ featureForPath('/compile')!,
+ 'supported',
+ ),
+ ).toBe(false)
+ expect(
+ isStudioFeatureVisible('volcengine', featureForPath('/directory')!),
+ ).toBe(true)
+ expect(
+ isStudioFeatureVisible(
+ 'volcengine',
+ featureForPath('/users')!,
+ 'supported',
+ ),
+ ).toBe(false)
+ expect(isStudioFeatureVisible('unknown', monitoring)).toBe(false)
+ expect(
+ isStudioFeatureVisible('opensource', featureForPath('/filesystem')!),
+ ).toBe(true)
+ })
+})
+
+describe('capability response contracts', () => {
+ it('does not enable a page for generic JSON or a successful HTTP error envelope', () => {
+ expect(classifyCapabilityResponse('watches', { message: 'proxy' })).toBe(
+ 'unknown',
+ )
+ expect(
+ classifyCapabilityResponse('watches', {
+ status: 'error',
+ error: { code: 'ApiBlocked' },
+ }),
+ ).toBe('unavailable')
+ expect(
+ classifyCapabilityResponse('watches', {
+ ResponseMetadata: { Error: { Code: 'ApiBlocked' } },
+ }),
+ ).toBe('unavailable')
+ expect(classifyCapabilityResponse('watches', { result: [] })).toBe(
+ 'unknown',
+ )
+ expect(
+ classifyCapabilityResponse('requestLogs', { result: { enabled: false } }),
+ ).toBe('unavailable')
+ })
+ it('checks the read contract each supported hosted page consumes', () => {
+ expect(
+ classifyCapabilityResponse('watches', {
+ status: 'ok',
+ result: { tasks: [] },
+ }),
+ ).toBe('supported')
+ expect(
+ classifyCapabilityResponse('requestLogs', {
+ result: { items: [], total: 0 },
+ }),
+ ).toBe('supported')
+ expect(
+ classifyCapabilityResponse('monitoring', {
+ result: { components: {}, is_healthy: true },
+ }),
+ ).toBe('supported')
+ expect(
+ classifyCapabilityResponse('monitoring', { result: { status: 'ok' } }),
+ ).toBe('unknown')
+ })
+ it.each(['/home', '/vikingbot', '/compile'])(
+ 'keeps %s hidden until the entire hosted page is adapted',
+ (path) => {
+ expect(
+ isStudioFeatureVisible(
+ 'volcengine',
+ featureForPath(path)!,
+ 'supported',
+ ),
+ ).toBe(false)
+ expect(isStudioFeatureVisible('opensource', featureForPath(path)!)).toBe(
+ true,
+ )
+ },
+ )
+})
diff --git a/web-studio/src/lib/studio-service.ts b/web-studio/src/lib/studio-service.ts
new file mode 100644
index 000000000..9b9fba738
--- /dev/null
+++ b/web-studio/src/lib/studio-service.ts
@@ -0,0 +1,163 @@
+export type ServiceProvider = 'opensource' | 'volcengine' | 'unknown'
+export type ServiceSelection = 'auto' | Exclude<ServiceProvider, 'unknown'>
+export type StudioDomain = 'workspace' | 'extensions' | 'management'
+export type CapabilityState =
+ | 'supported'
+ | 'unavailable'
+ | 'forbidden'
+ | 'unknown'
+
+// URL detection identifies the deployment, not the permissions of its key.
+// Version numbers and encoded key contents are not provider identifiers.
+export function identifyServiceProvider(baseUrl: string): ServiceProvider {
+ try {
+ const { hostname, protocol } = new URL(baseUrl)
+ if (!['http:', 'https:'].includes(protocol)) return 'unknown'
+ if (/^api\.vikingdb\.[a-z0-9-]+\.volces\.com$/.test(hostname)) {
+ return 'volcengine'
+ }
+ // All other HTTP deployments default to open source; hosted proxies can override this.
+ return 'opensource'
+ } catch {
+ // An unfinished URL is not a deployment classification.
+ }
+ return 'unknown'
+}
+
+// Configuration can be edited before authentication succeeds. It does not grant access.
+export function resolveConfiguredServiceProvider(
+ baseUrl: string,
+ selection: ServiceSelection = 'auto',
+): ServiceProvider {
+ const detected = identifyServiceProvider(baseUrl)
+ return detected === 'volcengine'
+ ? detected
+ : selection === 'auto'
+ ? detected
+ : selection
+}
+
+export const STUDIO_FEATURES = [
+ { id: 'filesystem', domain: 'workspace', to: '/filesystem' },
+ { id: 'directory', domain: 'workspace', to: '/directory' },
+ { id: 'memories', domain: 'workspace', to: '/memories' },
+ { id: 'retrieval', domain: 'workspace', to: '/retrieval' },
+ { id: 'skills', domain: 'workspace', to: '/skills' },
+ { id: 'sessions', domain: 'workspace', to: '/sessions' },
+ { id: 'tasks', domain: 'workspace', to: '/tasks' },
+ // These pages need additional endpoints or mutations that have not been
+ // adapted for hosted deployments. One healthy endpoint cannot enable them.
+ { id: 'home', domain: 'extensions', to: '/home' },
+
+ { id: 'vikingbot', domain: 'extensions', to: '/vikingbot' },
+ { id: 'compile', domain: 'extensions', to: '/compile' },
+ { id: 'agentExperience', domain: 'extensions', to: '/agent-experience' },
+ {
+ id: 'requestLogs',
+ domain: 'extensions',
+ to: '/request-logs',
+ probe: '/api/v1/console/audit',
+ },
+ {
+ id: 'watches',
+ domain: 'extensions',
+ to: '/watches',
+ probe: '/api/v1/watches',
+ },
+ {
+ id: 'monitoring',
+ domain: 'extensions',
+ to: '/monitoring',
+ probe: '/api/v1/observer/system',
+ },
+ { id: 'gateway', domain: 'management', to: '/gateway' },
+ { id: 'users', domain: 'management', to: '/users' },
+ { id: 'permissions', domain: 'management', to: '/permissions' },
+] as const satisfies ReadonlyArray<{
+ id: string
+ domain: StudioDomain
+ to: string
+ probe?: string
+}>
+
+export function featureForPath(pathname: string) {
+ return STUDIO_FEATURES.find(
+ (f) => pathname === f.to || pathname.startsWith(`${f.to}/`),
+ )
+}
+
+export function classifyCapabilityError(error: {
+ code?: string
+ statusCode?: number
+ responseBody?: unknown
+}): CapabilityState {
+ const body = error.responseBody as
+ | { ResponseMetadata?: { Error?: { Code?: string } } }
+ | undefined
+ if (
+ error.code === 'ApiBlocked' ||
+ body?.ResponseMetadata?.Error?.Code === 'ApiBlocked'
+ )
+ return 'unavailable'
+ if (error.statusCode === 403) return 'forbidden'
+ // Only used for object-free endpoint probes, never file/stat requests.
+ if (error.statusCode === 404 || error.statusCode === 405) return 'unavailable'
+ return 'unknown'
+}
+
+export function isStudioFeatureVisible(
+ provider: ServiceProvider,
+ feature: (typeof STUDIO_FEATURES)[number],
+ capability?: CapabilityState,
+): boolean {
+ if (feature.domain === 'management') return provider === 'opensource'
+ if (feature.domain !== 'extensions') return true
+ if (provider === 'opensource') return true
+ return (
+ provider === 'volcengine' &&
+ 'probe' in feature &&
+ capability === 'supported'
+ )
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+// A reachable endpoint is not enough: verify the read contract used by its page.
+export function classifyCapabilityResponse(
+ featureId: string,
+ payload: unknown,
+): CapabilityState {
+ if (!isRecord(payload)) return 'unknown'
+ const metadata = payload.ResponseMetadata
+ if (
+ payload.status === 'error' ||
+ payload.error ||
+ (isRecord(metadata) && metadata.Error)
+ ) {
+ const error = isRecord(payload.error) ? payload.error : undefined
+ return classifyCapabilityError({
+ code: typeof error?.code === 'string' ? error.code : undefined,
+ responseBody: payload,
+ })
+ }
+ const result = 'result' in payload ? payload.result : payload
+ if (!isRecord(result)) return 'unknown'
+ if (result.enabled === false) return 'unavailable'
+ switch (featureId) {
+ case 'watches':
+ return Array.isArray(result.tasks) ? 'supported' : 'unknown'
+ case 'requestLogs':
+ return Array.isArray(result.items) && typeof result.total === 'number'
+ ? 'supported'
+ : 'unknown'
+ case 'monitoring':
+ return typeof result.is_healthy === 'boolean' &&
+ isRecord(result.components)
+ ? 'supported'
+ : 'unknown'
+ default:
+ return 'unknown'
+ }
+}
diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.ts
index 9d3d1f9b9..5c91e4f76 100644
--- a/web-studio/src/routeTree.gen.ts
+++ b/web-studio/src/routeTree.gen.ts
@@ -10,6 +10,8 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as PlaygroundRouteImport } from './routes/playground'
+import { Route as MemoriesRouteImport } from './routes/memories'
+import { Route as ConfigRouteImport } from './routes/config'
import { Route as WatchesRouteRouteImport } from './routes/watches/route'
import { Route as VikingbotRouteRouteImport } from './routes/vikingbot/route'
import { Route as UsersRouteRouteImport } from './routes/users/route'
@@ -24,6 +26,7 @@ import { Route as MonitoringRouteRouteImport } from './routes/monitoring/route'
import { Route as HomeRouteRouteImport } from './routes/home/route'
import { Route as GatewayRouteRouteImport } from './routes/gateway/route'
import { Route as FilesystemRouteRouteImport } from './routes/filesystem/route'
+import { Route as DirectoryRouteRouteImport } from './routes/directory/route'
import { Route as AgentExperienceRouteRouteImport } from './routes/agent-experience/route'
import { Route as IndexRouteImport } from './routes/index'
import { Route as VikingbotIndexRouteImport } from './routes/vikingbot/index'
@@ -53,6 +56,16 @@ const PlaygroundRoute = PlaygroundRouteImport.update({
path: '/playground',
getParentRoute: () => rootRouteImport,
} as any)
+const MemoriesRoute = MemoriesRouteImport.update({
+ id: '/memories',
+ path: '/memories',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const ConfigRoute = ConfigRouteImport.update({
+ id: '/config',
+ path: '/config',
+ getParentRoute: () => rootRouteImport,
+} as any)
const WatchesRouteRoute = WatchesRouteRouteImport.update({
id: '/watches',
path: '/watches',
@@ -123,6 +136,11 @@ const FilesystemRouteRoute = FilesystemRouteRouteImport.update({
path: '/filesystem',
getParentRoute: () => rootRouteImport,
} as any)
+const DirectoryRouteRoute = DirectoryRouteRouteImport.update({
+ id: '/directory',
+ path: '/directory',
+ getParentRoute: () => rootRouteImport,
+} as any)
const AgentExperienceRouteRoute = AgentExperienceRouteRouteImport.update({
id: '/agent-experience',
path: '/agent-experience',
@@ -245,6 +263,7 @@ const CompileTasksTaskIdRoute = CompileTasksTaskIdRouteImport.update({
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/agent-experience': typeof AgentExperienceRouteRouteWithChildren
+ '/directory': typeof DirectoryRouteRoute
'/filesystem': typeof FilesystemRouteRoute
'/gateway': typeof GatewayRouteRouteWithChildren
'/home': typeof HomeRouteRoute
@@ -259,6 +278,8 @@ export interface FileRoutesByFullPath {
'/users': typeof UsersRouteRouteWithChildren
'/vikingbot': typeof VikingbotRouteRouteWithChildren
'/watches': typeof WatchesRouteRoute
+ '/config': typeof ConfigRoute
+ '/memories': typeof MemoriesRoute
'/playground': typeof PlaygroundRoute
'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute
'/compile/new': typeof CompileNewRoute
@@ -284,6 +305,7 @@ export interface FileRoutesByFullPath {
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
+ '/directory': typeof DirectoryRouteRoute
'/filesystem': typeof FilesystemRouteRoute
'/home': typeof HomeRouteRoute
'/monitoring': typeof MonitoringRouteRoute
@@ -294,6 +316,8 @@ export interface FileRoutesByTo {
'/skills': typeof SkillsRouteRoute
'/tasks': typeof TasksRouteRoute
'/watches': typeof WatchesRouteRoute
+ '/config': typeof ConfigRoute
+ '/memories': typeof MemoriesRoute
'/playground': typeof PlaygroundRoute
'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute
'/compile/new': typeof CompileNewRoute
@@ -321,6 +345,7 @@ export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
'/agent-experience': typeof AgentExperienceRouteRouteWithChildren
+ '/directory': typeof DirectoryRouteRoute
'/filesystem': typeof FilesystemRouteRoute
'/gateway': typeof GatewayRouteRouteWithChildren
'/home': typeof HomeRouteRoute
@@ -335,6 +360,8 @@ export interface FileRoutesById {
'/users': typeof UsersRouteRouteWithChildren
'/vikingbot': typeof VikingbotRouteRouteWithChildren
'/watches': typeof WatchesRouteRoute
+ '/config': typeof ConfigRoute
+ '/memories': typeof MemoriesRoute
'/playground': typeof PlaygroundRoute
'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute
'/compile/new': typeof CompileNewRoute
@@ -363,6 +390,7 @@ export interface FileRouteTypes {
fullPaths:
| '/'
| '/agent-experience'
+ | '/directory'
| '/filesystem'
| '/gateway'
| '/home'
@@ -377,6 +405,8 @@ export interface FileRouteTypes {
| '/users'
| '/vikingbot'
| '/watches'
+ | '/config'
+ | '/memories'
| '/playground'
| '/agent-experience/$experienceUri'
| '/compile/new'
@@ -402,6 +432,7 @@ export interface FileRouteTypes {
fileRoutesByTo: FileRoutesByTo
to:
| '/'
+ | '/directory'
| '/filesystem'
| '/home'
| '/monitoring'
@@ -412,6 +443,8 @@ export interface FileRouteTypes {
| '/skills'
| '/tasks'
| '/watches'
+ | '/config'
+ | '/memories'
| '/playground'
| '/agent-experience/$experienceUri'
| '/compile/new'
@@ -438,6 +471,7 @@ export interface FileRouteTypes {
| '__root__'
| '/'
| '/agent-experience'
+ | '/directory'
| '/filesystem'
| '/gateway'
| '/home'
@@ -452,6 +486,8 @@ export interface FileRouteTypes {
| '/users'
| '/vikingbot'
| '/watches'
+ | '/config'
+ | '/memories'
| '/playground'
| '/agent-experience/$experienceUri'
| '/compile/new'
@@ -479,6 +515,7 @@ export interface FileRouteTypes {
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
AgentExperienceRouteRoute: typeof AgentExperienceRouteRouteWithChildren
+ DirectoryRouteRoute: typeof DirectoryRouteRoute
FilesystemRouteRoute: typeof FilesystemRouteRoute
GatewayRouteRoute: typeof GatewayRouteRouteWithChildren
HomeRouteRoute: typeof HomeRouteRoute
@@ -493,6 +530,8 @@ export interface RootRouteChildren {
UsersRouteRoute: typeof UsersRouteRouteWithChildren
VikingbotRouteRoute: typeof VikingbotRouteRouteWithChildren
WatchesRouteRoute: typeof WatchesRouteRoute
+ ConfigRoute: typeof ConfigRoute
+ MemoriesRoute: typeof MemoriesRoute
PlaygroundRoute: typeof PlaygroundRoute
CompileNewRoute: typeof CompileNewRoute
OauthConsentRoute: typeof OauthConsentRoute
@@ -510,6 +549,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof PlaygroundRouteImport
parentRoute: typeof rootRouteImport
}
+ '/memories': {
+ id: '/memories'
+ path: '/memories'
+ fullPath: '/memories'
+ preLoaderRoute: typeof MemoriesRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/config': {
+ id: '/config'
+ path: '/config'
+ fullPath: '/config'
+ preLoaderRoute: typeof ConfigRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/watches': {
id: '/watches'
path: '/watches'
@@ -608,6 +661,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof FilesystemRouteRouteImport
parentRoute: typeof rootRouteImport
}
+ '/directory': {
+ id: '/directory'
+ path: '/directory'
+ fullPath: '/directory'
+ preLoaderRoute: typeof DirectoryRouteRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/agent-experience': {
id: '/agent-experience'
path: '/agent-experience'
@@ -856,6 +916,7 @@ const VikingbotRouteRouteWithChildren = VikingbotRouteRoute._addFileChildren(
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
AgentExperienceRouteRoute: AgentExperienceRouteRouteWithChildren,
+ DirectoryRouteRoute: DirectoryRouteRoute,
FilesystemRouteRoute: FilesystemRouteRoute,
GatewayRouteRoute: GatewayRouteRouteWithChildren,
HomeRouteRoute: HomeRouteRoute,
@@ -870,6 +931,8 @@ const rootRouteChildren: RootRouteChildren = {
UsersRouteRoute: UsersRouteRouteWithChildren,
VikingbotRouteRoute: VikingbotRouteRouteWithChildren,
WatchesRouteRoute: WatchesRouteRoute,
+ ConfigRoute: ConfigRoute,
+ MemoriesRoute: MemoriesRoute,
PlaygroundRoute: PlaygroundRoute,
CompileNewRoute: CompileNewRoute,
OauthConsentRoute: OauthConsentRoute,
diff --git a/web-studio/src/routes/-index.test.tsx b/web-studio/src/routes/-index.test.tsx
index ddd46e708..96029cfbc 100644
--- a/web-studio/src/routes/-index.test.tsx
+++ b/web-studio/src/routes/-index.test.tsx
@@ -4,7 +4,13 @@ import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import { Route } from './index'
-const state = vi.hoisted(() => ({ isGatewayHost: false }))
+const state = vi.hoisted(() => ({
+ isGatewayHost: false,
+ provider: 'opensource',
+}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ provider: state.provider }),
+}))
vi.mock('#/hooks/use-app-connection', () => ({ useAppConnection: () => state }))
vi.mock('@tanstack/react-router', async (importOriginal) => ({
...(await importOriginal<object>()),
@@ -23,3 +29,14 @@ it.each([false, true])(
expect(screen.getByText(isGatewayHost ? '/gateway' : '/home')).toBeTruthy()
},
)
+
+it('routes hosted OpenViking connections to the filesystem', async () => {
+ state.isGatewayHost = false
+ state.provider = 'volcengine'
+ const Index = Route.options.component as ComponentType & {
+ preload?: () => Promise<unknown>
+ }
+ await Index.preload?.()
+ render(<Index />)
+ expect(screen.getByText('/filesystem')).toBeTruthy()
+})
diff --git a/web-studio/src/routes/compile/-components/compile-form.test.tsx b/web-studio/src/routes/compile/-components/compile-form.test.tsx
index aa7e51fb1..eb97270b2 100644
--- a/web-studio/src/routes/compile/-components/compile-form.test.tsx
+++ b/web-studio/src/routes/compile/-components/compile-form.test.tsx
@@ -67,6 +67,27 @@ beforeEach(() => {
afterEach(() => {
cleanup()
clients.splice(0).forEach((client) => client.clear())
+ vi.unstubAllGlobals()
+})
+
+it('submits over HTTP origins without crypto.randomUUID', async () => {
+ const getRandomValues = globalThis.crypto.getRandomValues.bind(
+ globalThis.crypto,
+ )
+ vi.stubGlobal('crypto', { getRandomValues })
+ prepareCompileHandoff(
+ 'recovery-test',
+ 'compile --from viking://resources/source --to viking://resources/wiki --skill viking://agent/skills/wiki',
+ )
+ api.createCompile.mockResolvedValueOnce(task)
+
+ const page = mount()
+ page.submit()
+
+ await waitFor(() => expect(api.createCompile).toHaveBeenCalledOnce())
+ expect(api.createCompile.mock.calls[0][1]).toMatch(
+ /^[0-9]+:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
+ )
})
it('recovers an accepted submission after response loss and reload without resubmitting missing args', async () => {
diff --git a/web-studio/src/routes/compile/-components/compile-form.tsx b/web-studio/src/routes/compile/-components/compile-form.tsx
index 71a339622..251bc24be 100644
--- a/web-studio/src/routes/compile/-components/compile-form.tsx
+++ b/web-studio/src/routes/compile/-components/compile-form.tsx
@@ -7,6 +7,7 @@ import { Link, useNavigate, useBlocker } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { isOvClientError } from '#/lib/ov-client'
+import { createRandomUuid } from '#/lib/browser-crypto'
import { FolderOpen, Plus, X } from 'lucide-react'
import { Button } from '#/components/ui/button'
import { Input } from '#/components/ui/input'
@@ -258,7 +259,7 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
const body = submission.current?.request || request()
if (!submission.current)
submission.current = {
- key: recoverKey || `${Date.now()}:${crypto.randomUUID()}`,
+ key: recoverKey || `${Date.now()}:${createRandomUuid()}`,
request: body,
}
const key = submission.current.key
diff --git a/web-studio/src/routes/compile/-lib/terminal.test.ts b/web-studio/src/routes/compile/-lib/terminal.test.ts
index 48be498dd..f167e5987 100644
--- a/web-studio/src/routes/compile/-lib/terminal.test.ts
+++ b/web-studio/src/routes/compile/-lib/terminal.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createInstance } from 'i18next'
import { OvClientError } from '#/lib/ov-client'
import { runCompileCommand, runCompileSubmission } from './terminal'
@@ -15,6 +15,7 @@ const api = vi.hoisted(() => ({
}))
vi.mock('./api', () => api)
beforeEach(() => vi.resetAllMocks())
+afterEach(() => vi.unstubAllGlobals())
describe('Compile terminal regressions', () => {
it('keeps status filters in the executable next-page command', async () => {
@@ -127,6 +128,22 @@ it.each(['INVALID_ARGUMENT', 'INVALID_URI'])(
const retryCommand =
'compile --from viking://resources/a --to viking://resources/b --skill viking://agent/skills/s'
+it('submits over HTTP origins without crypto.randomUUID', async () => {
+ const getRandomValues = globalThis.crypto.getRandomValues.bind(
+ globalThis.crypto,
+ )
+ vi.stubGlobal('crypto', { getRandomValues })
+ api.createCompile.mockResolvedValueOnce({
+ task_id: 'task-1',
+ status: 'pending',
+ })
+
+ await runCompileSubmission(retryCommand, { current: null }, String, vi.fn())
+
+ expect(api.createCompile.mock.calls[0][1]).toMatch(
+ /^[0-9]+:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
+ )
+})
it('recovers a persisted submission after remount without creating again', async () => {
let saved: string | null = null
const save = (key: string | null) => {
diff --git a/web-studio/src/routes/compile/-lib/terminal.ts b/web-studio/src/routes/compile/-lib/terminal.ts
index f8a751768..2c19cbab8 100644
--- a/web-studio/src/routes/compile/-lib/terminal.ts
+++ b/web-studio/src/routes/compile/-lib/terminal.ts
@@ -1,4 +1,5 @@
import { isOvClientError } from '#/lib/ov-client'
+import { createRandomUuid } from '#/lib/browser-crypto'
import {
lookupSubmission,
cancelCompile,
@@ -98,7 +99,7 @@ export async function runCompileSubmission(
throw new CompileCommandError('pendingSubmission')
const submission = pending.current ?? {
raw: input,
- key: restoredKey || `${Date.now()}:${crypto.randomUUID()}`,
+ key: restoredKey || `${Date.now()}:${createRandomUuid()}`,
}
pending.current = submission
saveKey(submission.key)
diff --git a/web-studio/src/routes/config.tsx b/web-studio/src/routes/config.tsx
new file mode 100644
index 000000000..98bbdf069
--- /dev/null
+++ b/web-studio/src/routes/config.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute } from '@tanstack/react-router'
+
+// AppShell renders the connection wizard outside the connected workspace.
+export const Route = createFileRoute('/config')({
+ component: () => null,
+})
diff --git a/web-studio/src/routes/directory/route.tsx b/web-studio/src/routes/directory/route.tsx
new file mode 100644
index 000000000..d3477784e
--- /dev/null
+++ b/web-studio/src/routes/directory/route.tsx
@@ -0,0 +1,5 @@
+import { Navigate, createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/directory')({
+ component: () => <Navigate replace to="/filesystem" />,
+})
diff --git a/web-studio/src/routes/filesystem/-components/context-explorer.tsx b/web-studio/src/routes/filesystem/-components/context-explorer.tsx
index 2ce1ed883..b74f47260 100644
--- a/web-studio/src/routes/filesystem/-components/context-explorer.tsx
+++ b/web-studio/src/routes/filesystem/-components/context-explorer.tsx
@@ -44,7 +44,7 @@ export function ContextExplorerHeader({
hasTasks: boolean
isRefreshing: boolean
isRefreshingTasks: boolean
- onAddResource: () => void
+ onAddResource?: () => void
onOpenProcessingTasks: () => void
onOpenSearch: () => void
onRefresh: () => void
@@ -92,15 +92,17 @@ export function ContextExplorerHeader({
>
<SearchIcon className="size-4" />
</Button>
- <Button
- type="button"
- size="icon-sm"
- variant="ghost"
- title={t('explorer.addResource')}
- onClick={onAddResource}
- >
- <PlusIcon className="size-4" />
- </Button>
+ {onAddResource ? (
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ title={t('explorer.addResource')}
+ onClick={onAddResource}
+ >
+ <PlusIcon className="size-4" />
+ </Button>
+ ) : null}
<Button
type="button"
size="icon-sm"
@@ -143,6 +145,7 @@ export function ContextTree({
onSelectDirectory,
onSelectFile,
selectedFileUri,
+ rootUri = ROOT_URI,
}: {
currentUri: string
expandedKeys: Set<string>
@@ -150,9 +153,10 @@ export function ContextTree({
onSelectDirectory: (entry: VikingFsEntry) => void
onSelectFile: (entry: VikingFsEntry) => void
selectedFileUri?: string | null
+ rootUri?: string
}) {
const { t } = useTranslation('filesystem')
- const rootQuery = useVikingFsList(ROOT_URI, {
+ const rootQuery = useVikingFsList(rootUri, {
output: 'agent',
showAllHidden: true,
nodeLimit: 200,
diff --git a/web-studio/src/routes/filesystem/route.test.tsx b/web-studio/src/routes/filesystem/route.test.tsx
index 63d25dbf7..c3fff53a1 100644
--- a/web-studio/src/routes/filesystem/route.test.tsx
+++ b/web-studio/src/routes/filesystem/route.test.tsx
@@ -16,6 +16,11 @@ import {
import { Route } from './route'
const mocks = vi.hoisted(() => ({
+ provider: 'opensource',
+ uploadProvider: vi.fn(),
+ preview: vi.fn(),
+ agent: vi.fn(),
+ terminal: vi.fn(),
fetchFsStat: vi.fn(),
invalidateList: vi.fn(),
navigate: vi.fn(),
@@ -41,6 +46,9 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ provider: mocks.provider, ready: true }),
+}))
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({ identityScopeKey: 'test' }),
}))
@@ -55,7 +63,13 @@ vi.mock('#/routes/resources/-lib/api', () => ({
}))
vi.mock('#/routes/resources/-hooks/use-resource-upload', () => ({
- ResourceUploadProvider: ({ children }: PropsWithChildren) => children,
+ ResourceUploadProvider: ({
+ children,
+ enabled,
+ }: PropsWithChildren<{ enabled: boolean }>) => {
+ mocks.uploadProvider(enabled)
+ return children
+ },
useResourceUpload: () => ({
activeTaskCount: 0,
hasActiveTasks: false,
@@ -66,9 +80,14 @@ vi.mock('#/routes/resources/-hooks/use-resource-upload', () => ({
}))
vi.mock('#/routes/resources/-components/lazy-file-preview', () => ({
- LazyFilePreview: ({ file }: { file: { uri: string } | null }) => (
- <div data-testid="preview">{file?.uri}</div>
- ),
+ LazyFilePreview: (props: {
+ file: { uri: string } | null
+ readOnly?: boolean
+ defaultReadLimit?: number
+ }) => {
+ mocks.preview(props)
+ return <div data-testid="preview">{props.file?.uri}</div>
+ },
}))
vi.mock('./-components/context-explorer', () => ({
@@ -80,8 +99,10 @@ vi.mock('./-components/context-explorer', () => ({
FilesystemResizeHandle: () => null,
}))
-vi.mock('./-components/agent-panel', () => ({ AgentPanel: () => null }))
-vi.mock('./-components/terminal-panel', () => ({ TerminalPanel: () => null }))
+vi.mock('./-components/agent-panel', () => ({ AgentPanel: mocks.agent }))
+vi.mock('./-components/terminal-panel', () => ({
+ TerminalPanel: mocks.terminal,
+}))
vi.mock('#/routes/resources/-components/find-palette', () => ({
FindPalette: () => null,
}))
@@ -101,12 +122,30 @@ describe('filesystem context tree refresh', () => {
afterEach(cleanup)
beforeEach(() => {
+ mocks.provider = 'opensource'
+ mocks.uploadProvider.mockClear()
+ mocks.preview.mockClear()
+ mocks.agent.mockReset().mockReturnValue(null)
+ mocks.terminal.mockReset().mockReturnValue(null)
mocks.search = { file: firstFile, uri: parentDirectory }
mocks.fetchFsStat.mockReset()
mocks.invalidateList.mockReset().mockResolvedValue(undefined)
mocks.navigate.mockReset()
})
+ it('reuses the same workbench for hosted reads without scope tabs or incompatible local tools', () => {
+ mocks.provider = 'volcengine'
+ render(<FilesystemRoute />)
+ expect(screen.getByTestId('preview').textContent).toBe(firstFile)
+ expect(mocks.preview.mock.lastCall?.[0].readOnly).not.toBe(true)
+ expect(mocks.preview.mock.lastCall?.[0].defaultReadLimit).toBe(10000)
+ expect(mocks.uploadProvider.mock.lastCall?.[0]).toBe(false)
+ expect(mocks.agent).not.toHaveBeenCalled()
+ expect(mocks.terminal).not.toHaveBeenCalled()
+ expect(screen.queryByRole('tab')).toBeNull()
+ expect(screen.queryByText('addResource.title')).toBeNull()
+ })
+
it('clears a deleted selected file from the preview and URL search', async () => {
mocks.fetchFsStat.mockRejectedValue({ statusCode: 404 })
render(<FilesystemRoute />)
diff --git a/web-studio/src/routes/filesystem/route.tsx b/web-studio/src/routes/filesystem/route.tsx
index 3e8ec9b24..2a7c3858c 100644
--- a/web-studio/src/routes/filesystem/route.tsx
+++ b/web-studio/src/routes/filesystem/route.tsx
@@ -13,6 +13,7 @@ import {
import { toast } from 'sonner'
import { Button } from '#/components/ui/button'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
import {
Dialog,
@@ -95,8 +96,9 @@ export const Route = createFileRoute('/filesystem')({
})
function FilesystemRoute() {
+ const { provider } = useStudioService()
return (
- <ResourceUploadProvider>
+ <ResourceUploadProvider enabled={provider === 'opensource'}>
<FilesystemWorkbench />
</ResourceUploadProvider>
)
@@ -104,6 +106,8 @@ function FilesystemRoute() {
function FilesystemWorkbench() {
const { t } = useTranslation(['filesystem', 'resources'])
+ const { provider } = useStudioService()
+ const canUseLocalTools = provider === 'opensource'
const { identityScopeKey } = useAppConnection()
const search = Route.useSearch()
const navigate = useNavigate({ from: Route.fullPath })
@@ -560,10 +564,12 @@ function FilesystemWorkbench() {
<ContextExplorerHeader
activeTaskCount={activeTaskCount}
hasActiveTasks={hasActiveTasks}
- hasTasks={tasks.length > 0}
+ hasTasks={canUseLocalTools && tasks.length > 0}
isRefreshing={listQuery.isFetching}
isRefreshingTasks={isRefreshingTasks}
- onAddResource={() => setUploadDialogOpen(true)}
+ onAddResource={
+ canUseLocalTools ? () => setUploadDialogOpen(true) : undefined
+ }
onOpenProcessingTasks={handleOpenProcessingTasks}
onOpenSearch={handleOpenSearch}
onRefresh={() => void handleRefreshContextTree()}
@@ -614,29 +620,31 @@ function FilesystemWorkbench() {
>
<ClipboardIcon className="size-4" />
</Button>
- <div className="flex shrink-0 items-center gap-1 lg:hidden">
- <Button
- type="button"
- size="icon-sm"
- variant={activePanel === 'terminal' ? 'secondary' : 'ghost'}
- title={t('tabs.terminal')}
- aria-label={t('tabs.terminal')}
- onClick={() => handleOpenActionPanel('terminal')}
- >
- <TerminalIcon className="size-4" />
- </Button>
- <Button
- type="button"
- size="icon-sm"
- variant={activePanel === 'agent' ? 'secondary' : 'ghost'}
- title={t('tabs.agent')}
- aria-label={t('tabs.agent')}
- onClick={() => handleOpenActionPanel('agent')}
- >
- <BotIcon className="size-4" />
- </Button>
- </div>
- {rightCollapsed ? (
+ {canUseLocalTools ? (
+ <div className="flex shrink-0 items-center gap-1 lg:hidden">
+ <Button
+ type="button"
+ size="icon-sm"
+ variant={activePanel === 'terminal' ? 'secondary' : 'ghost'}
+ title={t('tabs.terminal')}
+ aria-label={t('tabs.terminal')}
+ onClick={() => handleOpenActionPanel('terminal')}
+ >
+ <TerminalIcon className="size-4" />
+ </Button>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant={activePanel === 'agent' ? 'secondary' : 'ghost'}
+ title={t('tabs.agent')}
+ aria-label={t('tabs.agent')}
+ onClick={() => handleOpenActionPanel('agent')}
+ >
+ <BotIcon className="size-4" />
+ </Button>
+ </div>
+ ) : null}
+ {canUseLocalTools && rightCollapsed ? (
<Button
type="button"
size="icon-sm"
@@ -652,6 +660,7 @@ function FilesystemWorkbench() {
</div>
<div className="min-h-0 flex-1">
<LazyFilePreview
+ defaultReadLimit={canUseLocalTools ? -1 : 10000}
file={selectedFile}
hideDirectoryHeader
onClose={() => setSelectedFile(null)}
@@ -660,7 +669,7 @@ function FilesystemWorkbench() {
/>
</div>
</main>
- {!rightCollapsed ? (
+ {canUseLocalTools && !rightCollapsed ? (
<FilesystemResizeHandle
active={resizingPane === 'action'}
label={t('resizeAction')}
@@ -668,7 +677,7 @@ function FilesystemWorkbench() {
/>
) : null}
- {!isCompactLayout && !rightCollapsed ? (
+ {!isCompactLayout && canUseLocalTools && !rightCollapsed ? (
<aside className="hidden min-h-0 min-w-0 flex-col bg-muted/15 lg:flex lg:w-[var(--filesystem-right-width)] lg:min-w-[var(--filesystem-right-width)]">
<FilesystemActionPanel
activePanel={activePanel}
@@ -688,7 +697,7 @@ function FilesystemWorkbench() {
) : null}
</div>
- {isCompactLayout ? (
+ {canUseLocalTools && isCompactLayout ? (
<FilesystemMobileActionScreen
activePanel={activePanel}
currentUri={currentUri}
@@ -704,35 +713,39 @@ function FilesystemWorkbench() {
/>
) : null}
- <Dialog
- open={uploadDialogOpen}
- onOpenChange={handleUploadDialogOpenChange}
- >
- <DialogContent className="max-h-[min(86vh,760px)] gap-0 overflow-hidden p-0 sm:max-w-4xl">
- <DialogHeader className="border-b px-6 py-5">
- <DialogTitle className="text-xl">
- {t('addResource.title')}
- </DialogTitle>
- <DialogDescription>
- {t('addResource.description')}
- </DialogDescription>
- </DialogHeader>
- <div className="max-h-[calc(min(86vh,760px)-6rem)] overflow-y-auto px-6 py-5">
- <AddResourceForm
- onSubmitted={() => {
- handleUploadDialogOpenChange(false)
- void invalidateList()
- toast.success(t('addResource.submitted'))
- }}
- />
- </div>
- </DialogContent>
- </Dialog>
- <UploadTaskDialog
- open={taskDialogOpen}
- onOpenChange={setTaskDialogOpen}
- tasks={tasks}
- />
+ {canUseLocalTools ? (
+ <>
+ <Dialog
+ open={uploadDialogOpen}
+ onOpenChange={handleUploadDialogOpenChange}
+ >
+ <DialogContent className="max-h-[min(86vh,760px)] gap-0 overflow-hidden p-0 sm:max-w-4xl">
+ <DialogHeader className="border-b px-6 py-5">
+ <DialogTitle className="text-xl">
+ {t('addResource.title')}
+ </DialogTitle>
+ <DialogDescription>
+ {t('addResource.description')}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="max-h-[calc(min(86vh,760px)-6rem)] overflow-y-auto px-6 py-5">
+ <AddResourceForm
+ onSubmitted={() => {
+ handleUploadDialogOpenChange(false)
+ void invalidateList()
+ toast.success(t('addResource.submitted'))
+ }}
+ />
+ </div>
+ </DialogContent>
+ </Dialog>
+ <UploadTaskDialog
+ open={taskDialogOpen}
+ onOpenChange={setTaskDialogOpen}
+ tasks={tasks}
+ />
+ </>
+ ) : null}
<FindPalette
open={findPaletteOpen}
onClose={() => setFindPaletteOpen(false)}
diff --git a/web-studio/src/routes/gateway/-components/connect-page.test.tsx b/web-studio/src/routes/gateway/-components/connect-page.test.tsx
index bf10116fa..6d4c5a3a8 100644
--- a/web-studio/src/routes/gateway/-components/connect-page.test.tsx
+++ b/web-studio/src/routes/gateway/-components/connect-page.test.tsx
@@ -46,6 +46,10 @@ const api = vi.hoisted(() => ({
const host = vi.hoisted(() => ({ isGatewayHost: false }))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
isGatewayHost: host.isGatewayHost,
diff --git a/web-studio/src/routes/gateway/-components/gateway-enable.test.tsx b/web-studio/src/routes/gateway/-components/gateway-enable.test.tsx
index 462f0d2df..eb0768197 100644
--- a/web-studio/src/routes/gateway/-components/gateway-enable.test.tsx
+++ b/web-studio/src/routes/gateway/-components/gateway-enable.test.tsx
@@ -38,6 +38,10 @@ const state = vi.hoisted(() => ({
getAccess: vi.fn(),
getConnectionInfo: vi.fn(),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
diff --git a/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx b/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx
index a3d0e2740..179bb50c6 100644
--- a/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx
+++ b/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx
@@ -44,6 +44,10 @@ vi.mock('react-i18next', () => ({
i18n: { resolvedLanguage: 'en' },
}),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
diff --git a/web-studio/src/routes/gateway/-components/keys-page.test.tsx b/web-studio/src/routes/gateway/-components/keys-page.test.tsx
index 4c802bc78..e1c46c605 100644
--- a/web-studio/src/routes/gateway/-components/keys-page.test.tsx
+++ b/web-studio/src/routes/gateway/-components/keys-page.test.tsx
@@ -42,6 +42,10 @@ vi.mock('react-i18next', () => ({
i18n: { resolvedLanguage: 'en' },
}),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
diff --git a/web-studio/src/routes/gateway/-components/management-key-dialog.test.tsx b/web-studio/src/routes/gateway/-components/management-key-dialog.test.tsx
index 140395300..58cd9f6cc 100644
--- a/web-studio/src/routes/gateway/-components/management-key-dialog.test.tsx
+++ b/web-studio/src/routes/gateway/-components/management-key-dialog.test.tsx
@@ -113,3 +113,25 @@ it('tolerates browsers that reject session storage', () => {
expect(getManagementKey('https://gateway.example.com')).toBe('')
getter.mockRestore()
})
+
+it('stores the submitted key even when the input changes during verification', async () => {
+ let resolveAccess!: (access: { can_write_objects: boolean }) => void
+ state.getAccess.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveAccess = resolve
+ }),
+ )
+ open()
+ const input = await screen.findByLabelText('management.label')
+ fireEvent.change(input, { target: { value: 'ovgm-submitted' } })
+ fireEvent.click(screen.getByRole('button', { name: 'management.unlock' }))
+ await waitFor(() => expect(state.getAccess).toHaveBeenCalledOnce())
+ fireEvent.change(input, { target: { value: 'ovgm-unverified-edit' } })
+ resolveAccess({ can_write_objects: true })
+ await waitFor(() =>
+ expect(getManagementKey('https://gateway.example.com')).toBe(
+ 'ovgm-submitted',
+ ),
+ )
+})
diff --git a/web-studio/src/routes/gateway/-components/management-key-dialog.tsx b/web-studio/src/routes/gateway/-components/management-key-dialog.tsx
index 7c1970774..a3fd76fa2 100644
--- a/web-studio/src/routes/gateway/-components/management-key-dialog.tsx
+++ b/web-studio/src/routes/gateway/-components/management-key-dialog.tsx
@@ -42,14 +42,14 @@ export function ManagementKeyDialog() {
return () => window.removeEventListener(MANAGEMENT_UNLOCK_EVENT, show)
}, [])
const unlock = useMutation({
- mutationFn: () => getAccess({ ...connection, managementKey: key.trim() }),
+ mutationFn: (candidate: typeof connection) => getAccess(candidate),
// Storing the key changes the query scope, so gateway data reloads with it.
- onSuccess: (access) => {
+ onSuccess: (access, candidate) => {
if (!access.can_write_objects) {
setError(t('management.invalid'))
return
}
- setManagementKey(connection.baseUrl, key.trim())
+ setManagementKey(candidate.baseUrl, candidate.managementKey ?? '')
setOpen(false)
setKey('')
toast.success(t('management.unlocked'))
@@ -73,7 +73,8 @@ export function ManagementKeyDialog() {
className="grid gap-4"
onSubmit={(event) => {
event.preventDefault()
- if (key.trim() && !wrongKey) unlock.mutate()
+ if (key.trim() && !wrongKey)
+ unlock.mutate({ ...connection, managementKey: key.trim() })
}}
>
<details className="text-sm">
diff --git a/web-studio/src/routes/gateway/-components/overview-page.test.tsx b/web-studio/src/routes/gateway/-components/overview-page.test.tsx
index 045e45d44..1933cc9b5 100644
--- a/web-studio/src/routes/gateway/-components/overview-page.test.tsx
+++ b/web-studio/src/routes/gateway/-components/overview-page.test.tsx
@@ -46,6 +46,10 @@ const api = vi.hoisted(() => ({
saveProfile: vi.fn(),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
diff --git a/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx b/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx
index 8a5aba5ed..6abbe96d8 100644
--- a/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx
+++ b/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx
@@ -50,6 +50,10 @@ const translate = vi.hoisted(
: key,
)
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
diff --git a/web-studio/src/routes/gateway/-components/requests-page.test.tsx b/web-studio/src/routes/gateway/-components/requests-page.test.tsx
index 187c03061..ef450d9ec 100644
--- a/web-studio/src/routes/gateway/-components/requests-page.test.tsx
+++ b/web-studio/src/routes/gateway/-components/requests-page.test.tsx
@@ -43,6 +43,10 @@ const api = vi.hoisted(() => ({
}))
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
diff --git a/web-studio/src/routes/gateway/-components/upstreams-pages.test.tsx b/web-studio/src/routes/gateway/-components/upstreams-pages.test.tsx
index 09d54f9be..ac9519810 100644
--- a/web-studio/src/routes/gateway/-components/upstreams-pages.test.tsx
+++ b/web-studio/src/routes/gateway/-components/upstreams-pages.test.tsx
@@ -51,6 +51,10 @@ vi.mock('react-i18next', () => ({
}),
}))
vi.mock('sonner', () => ({ toast }))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
diff --git a/web-studio/src/routes/gateway/-lib/use-gateway.test.tsx b/web-studio/src/routes/gateway/-lib/use-gateway.test.tsx
index 7e9bc8b41..3e6249433 100644
--- a/web-studio/src/routes/gateway/-lib/use-gateway.test.tsx
+++ b/web-studio/src/routes/gateway/-lib/use-gateway.test.tsx
@@ -28,6 +28,10 @@ const api = vi.hoisted(() => ({
listTools: vi.fn(),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
diff --git a/web-studio/src/routes/gateway/-lib/use-gateway.ts b/web-studio/src/routes/gateway/-lib/use-gateway.ts
index 1f494aeaa..489e719a1 100644
--- a/web-studio/src/routes/gateway/-lib/use-gateway.ts
+++ b/web-studio/src/routes/gateway/-lib/use-gateway.ts
@@ -3,6 +3,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { UseQueryOptions } from '@tanstack/react-query'
import { useAppConnection } from '#/hooks/use-app-connection'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useManagementKey } from './management-key'
import {
@@ -86,6 +87,7 @@ export function gatewayQueryKey(
*/
function useGatewayConnection() {
const { connection, isConnectionRoleLoading, serverMode } = useAppConnection()
+ const service = useStudioService()
const { baseUrl, accountId, userId } = connection
const apiKey = connection.adminApiKey || connection.apiKey
const managementKey = useManagementKey(baseUrl)
@@ -115,9 +117,11 @@ function useGatewayConnection() {
* the gateway doesn't support it.
*/
allowed:
- serverMode === 'dev' ||
- serverMode === 'trusted' ||
- Boolean(apiKey.trim()),
+ service.ready &&
+ service.provider === 'opensource' &&
+ (serverMode === 'dev' ||
+ serverMode === 'trusted' ||
+ Boolean(apiKey.trim())),
/** Local development authenticates as default/default without a credential. */
devMode: serverMode === 'dev',
isRoleLoading: isConnectionRoleLoading,
@@ -144,7 +148,11 @@ function useGatewayQuery<T>(
return useQuery<T, GatewayError>({
...options,
queryKey: gatewayQueryKey(scope, resource, ...params),
- queryFn: () => load(connection),
+ queryFn: () => {
+ if (!allowed)
+ throw new Error('Gateway is unavailable for this connection')
+ return load(connection)
+ },
enabled: allowed && options.enabled !== false,
})
}
diff --git a/web-studio/src/routes/gateway/route.test.tsx b/web-studio/src/routes/gateway/route.test.tsx
index eb0ae48ab..0ba97e1ea 100644
--- a/web-studio/src/routes/gateway/route.test.tsx
+++ b/web-studio/src/routes/gateway/route.test.tsx
@@ -29,6 +29,10 @@ const api = vi.hoisted(() => ({
getAccess: vi.fn(),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ ready: true, provider: 'opensource' }),
+}))
+
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
diff --git a/web-studio/src/routes/index.tsx b/web-studio/src/routes/index.tsx
index b13399151..effee65eb 100644
--- a/web-studio/src/routes/index.tsx
+++ b/web-studio/src/routes/index.tsx
@@ -1,3 +1,4 @@
+import { useStudioService } from '#/hooks/use-studio-service'
import { Navigate, createFileRoute } from '@tanstack/react-router'
import { useAppConnection } from '#/hooks/use-app-connection'
@@ -7,6 +8,18 @@ export const Route = createFileRoute('/')({
})
function IndexRoute() {
+ const { provider } = useStudioService()
const { isGatewayHost } = useAppConnection()
- return <Navigate replace to={isGatewayHost ? '/gateway' : '/home'} />
+ return (
+ <Navigate
+ replace
+ to={
+ isGatewayHost
+ ? '/gateway'
+ : provider === 'opensource'
+ ? '/home'
+ : '/filesystem'
+ }
+ />
+ )
}
diff --git a/web-studio/src/routes/memories.tsx b/web-studio/src/routes/memories.tsx
new file mode 100644
index 000000000..37c88b5c7
--- /dev/null
+++ b/web-studio/src/routes/memories.tsx
@@ -0,0 +1,16 @@
+import { Navigate, createFileRoute } from '@tanstack/react-router'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { useStudioService } from '#/hooks/use-studio-service'
+
+export const Route = createFileRoute('/memories')({
+ component: MemoriesRedirect,
+})
+function MemoriesRedirect() {
+ const { connection } = useAppConnection()
+ const { provider } = useStudioService()
+ const uri =
+ provider === 'volcengine'
+ ? 'viking://~/memories/'
+ : `viking://user/${connection.userId}/memories/`
+ return <Navigate replace to="/filesystem" search={{ uri, upload: false }} />
+}
diff --git a/web-studio/src/routes/monitoring/route.tsx b/web-studio/src/routes/monitoring/route.tsx
index 5a0c2a860..e35484cde 100644
--- a/web-studio/src/routes/monitoring/route.tsx
+++ b/web-studio/src/routes/monitoring/route.tsx
@@ -19,6 +19,7 @@ import { useTranslation } from 'react-i18next'
import { Alert, AlertDescription, AlertTitle } from '#/components/ui/alert'
import { Badge } from '#/components/ui/badge'
import { Button } from '#/components/ui/button'
+
import { Card, CardContent, CardHeader, CardTitle } from '#/components/ui/card'
import { useAppConnection } from '#/hooks/use-app-connection'
import { getHealth, getObserverSystem, getOvResult } from '#/lib/ov-client'
@@ -100,21 +101,33 @@ async function fetchMonitoringOverview(): Promise<MonitoringOverview> {
}
}
-function HealthBadge({ healthy, label }: { healthy: boolean; label: string }) {
+function HealthBadge({
+ healthy,
+ label,
+}: {
+ healthy: boolean | undefined
+ label: string
+}) {
return (
<Badge
variant="outline"
className={cn(
'gap-1.5 font-normal',
- healthy
- ? 'border-emerald-500/30 text-emerald-600'
- : 'border-destructive/30 text-destructive',
+ healthy === undefined
+ ? 'text-muted-foreground'
+ : healthy
+ ? 'border-emerald-500/30 text-emerald-600'
+ : 'border-destructive/30 text-destructive',
)}
>
<span
className={cn(
'size-1.5 rounded-full',
- healthy ? 'bg-emerald-500' : 'bg-destructive',
+ healthy === undefined
+ ? 'bg-muted-foreground'
+ : healthy
+ ? 'bg-emerald-500'
+ : 'bg-destructive',
)}
/>
{label}
@@ -295,8 +308,9 @@ function MonitoringRoute() {
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
{MONITOR_TYPES.slice(1).map(([name, Icon]) => {
const component = overview?.components[name]
- const healthy =
- component?.is_healthy === true && !component.has_errors
+ const healthy = component
+ ? component.is_healthy && !component.has_errors
+ : undefined
return (
<button
key={name}
@@ -315,9 +329,11 @@ function MonitoringRoute() {
<HealthBadge
healthy={healthy}
label={
- healthy
- ? t('health.healthy')
- : t('health.unhealthy')
+ healthy === undefined
+ ? t('health.unknown')
+ : healthy
+ ? t('health.healthy')
+ : t('health.unhealthy')
}
/>
</div>
@@ -344,14 +360,18 @@ function MonitoringRoute() {
</div>
<HealthBadge
healthy={
- selectedComponent?.is_healthy === true &&
- !selectedComponent.has_errors
+ selectedComponent
+ ? selectedComponent.is_healthy &&
+ !selectedComponent.has_errors
+ : undefined
}
label={
- selectedComponent?.is_healthy &&
- !selectedComponent.has_errors
- ? t('health.healthy')
- : t('health.unhealthy')
+ !selectedComponent
+ ? t('health.unknown')
+ : selectedComponent.is_healthy &&
+ !selectedComponent.has_errors
+ ? t('health.healthy')
+ : t('health.unhealthy')
}
/>
</div>
diff --git a/web-studio/src/routes/resources/-components/file-preview.test.tsx b/web-studio/src/routes/resources/-components/file-preview.test.tsx
index f8e9447c9..974c5a4e0 100644
--- a/web-studio/src/routes/resources/-components/file-preview.test.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.test.tsx
@@ -11,6 +11,9 @@ import {
import type { PropsWithChildren } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { getContentDownload } from '#/lib/ov-client'
+import { saveFileContent } from '../-lib/api'
+import { toast } from 'sonner'
import type { VikingFsEntry } from '../-types/viking-fm'
import {
FilePreview,
@@ -20,7 +23,11 @@ import {
} from './file-preview'
const previewState = vi.hoisted(() => ({
- override: null as { content: string; fileType: string } | null,
+ override: null as {
+ content: string
+ fileType: string
+ truncated?: boolean
+ } | null,
}))
const previewMocks = vi.hoisted(() => ({
@@ -29,6 +36,25 @@ const previewMocks = vi.hoisted(() => ({
})),
}))
+vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))
+vi.mock('../-lib/api', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ saveFileContent: vi.fn(),
+}))
+vi.mock('#/components/code-editor', async () => {
+ const React = await import('react')
+ return {
+ CodeEditor: React.forwardRef(
+ ({ initialContent }: { initialContent: string }, ref) => {
+ React.useImperativeHandle(ref, () => ({
+ getContent: () => initialContent,
+ }))
+ return <div data-testid="editor-content">{initialContent}</div>
+ },
+ ),
+ }
+})
+
vi.mock('@streamdown/mermaid', () => ({
mermaid: {
getMermaid: () => ({
@@ -980,3 +1006,63 @@ describe('FilePreview JSONL rendering', () => {
expect(screen.queryByText('2')).toBeNull()
})
})
+
+describe('FilePreview complete-content editing', () => {
+ beforeEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ })
+ afterEach(() => {
+ cleanup()
+ previewState.override = null
+ })
+ it('loads the complete original before editing a limited hosted preview', async () => {
+ previewState.override = {
+ content: 'limited preview',
+ fileType: 'text',
+ truncated: true,
+ }
+ vi.mocked(getContentDownload).mockResolvedValue({
+ data: 'complete original\nlast line',
+ } as never)
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <FilePreview file={file} defaultReadLimit={10000} onClose={vi.fn()} />
+ </QueryClientProvider>,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'filePreview.edit' }))
+ expect((await screen.findByTestId('editor-content')).textContent).toBe(
+ 'complete original\nlast line',
+ )
+ expect(getContentDownload).toHaveBeenCalledWith({
+ query: { uri: file.uri },
+ responseType: 'text',
+ throwOnError: true,
+ })
+ vi.mocked(saveFileContent).mockRejectedValue(new Error('Forbidden'))
+ fireEvent.click(screen.getByRole('button', { name: 'filePreview.save' }))
+ await waitFor(() => expect(toast.error).toHaveBeenCalled())
+ expect(screen.getByTestId('editor-content').textContent).toBe(
+ 'complete original\nlast line',
+ )
+ })
+
+ it('does not open an editor when the complete original cannot be read', async () => {
+ previewState.override = {
+ content: 'limited preview',
+ fileType: 'text',
+ truncated: true,
+ }
+ vi.mocked(getContentDownload).mockRejectedValue(new Error('Forbidden'))
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <FilePreview file={file} defaultReadLimit={10000} onClose={vi.fn()} />
+ </QueryClientProvider>,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'filePreview.edit' }))
+ await waitFor(() => expect(toast.error).toHaveBeenCalled())
+ expect(screen.queryByTestId('editor-content')).toBeNull()
+ })
+})
diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsx
index b95543dd3..a58cb2909 100644
--- a/web-studio/src/routes/resources/-components/file-preview.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.tsx
@@ -17,6 +17,7 @@ import remarkBreaks from 'remark-breaks'
import remarkGfm from 'remark-gfm'
import { X, Pencil, Save, XCircle, Loader2 } from 'lucide-react'
import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
import { Button } from '#/components/ui/button'
import { ScrollArea } from '#/components/ui/scroll-area'
@@ -125,6 +126,8 @@ async function ensureLanguage(lang: string): Promise<void> {
}
interface FilePreviewProps {
+ readOnly?: boolean
+ defaultReadLimit?: number
file: VikingFsEntry | null
hideDirectoryHeader?: boolean
onClose: () => void
@@ -1348,6 +1351,8 @@ function JsonlPreview({ content }: { content: string }) {
}
export function FilePreview({
+ readOnly = false,
+ defaultReadLimit,
file,
hideDirectoryHeader = false,
onClose,
@@ -1376,7 +1381,7 @@ export function FilePreview({
resolvedFile,
{
maxAutoReadBytes: LARGE_FILE_PREVIEW_BYTES,
- defaultReadLimit: -1,
+ defaultReadLimit: defaultReadLimit ?? (readOnly ? 10000 : -1),
requireKnownSize: isJsonFile,
},
{
@@ -1392,7 +1397,10 @@ export function FilePreview({
() => memoryFieldsDisplayContent(preview?.content || ''),
[preview?.content],
)
- const frontmatter = useMemo(() => splitMarkdownFrontmatter(displayContent || ''), [displayContent])
+ const frontmatter = useMemo(
+ () => splitMarkdownFrontmatter(displayContent || ''),
+ [displayContent],
+ )
const okfDocument = useMemo(
() =>
file && preview?.fileType === 'markdown'
@@ -1414,10 +1422,15 @@ export function FilePreview({
>(new Set(['abstract', 'overview']))
const [editing, setEditing] = useState(false)
const [saving, setSaving] = useState(false)
+ const [loadingEditor, setLoadingEditor] = useState(false)
+ const [editorContent, setEditorContent] = useState('')
+ const fileUriRef = useRef(file?.uri)
+ fileUriRef.current = file?.uri
const editorRef = useRef<CodeEditorHandle>(null)
const { invalidatePreview } = useInvalidateVikingFs()
const canEdit =
+ !readOnly &&
!file?.isDir &&
preview?.shouldAutoRead &&
(preview.fileType === 'code' ||
@@ -1429,6 +1442,8 @@ export function FilePreview({
setMarkdownMode('preview')
setJsonMode('preview')
setEditing(false)
+ setLoadingEditor(false)
+ setEditorContent('')
setActiveDirectoryLevels(new Set(['abstract', 'overview']))
}, [file?.uri])
@@ -1543,6 +1558,38 @@ export function FilePreview({
}
}, [file, preview?.fileType])
+ const handleEdit = async () => {
+ if (!file || loadingEditor || !canEdit) return
+ const uri = file.uri
+ setLoadingEditor(true)
+ try {
+ // A limited preview must never become a replace write. Download the
+ // complete original content through the authenticated API first.
+ const response = preview.truncated
+ ? await getContentDownload({
+ query: { uri },
+ responseType: 'text',
+ throwOnError: true,
+ })
+ : null
+ if (fileUriRef.current !== uri) return
+ const content = response ? response.data : preview.content
+ if (
+ typeof content !== 'string' ||
+ new Blob([content]).size > LARGE_FILE_PREVIEW_BYTES
+ ) {
+ throw new Error(t('filePreview.largeFileSkipped'))
+ }
+ setEditorContent(content)
+ setEditing(true)
+ } catch (err) {
+ if (fileUriRef.current === uri)
+ toast.error(t('filePreview.editFailed'), { description: String(err) })
+ } finally {
+ if (fileUriRef.current === uri) setLoadingEditor(false)
+ }
+ }
+
const handleSave = async () => {
if (!file || !editorRef.current) return
setSaving(true)
@@ -1551,7 +1598,7 @@ export function FilePreview({
invalidatePreview(file.uri)
setEditing(false)
} catch (err) {
- console.error('Save failed:', err)
+ toast.error(t('filePreview.saveFailed'), { description: String(err) })
} finally {
setSaving(false)
}
@@ -1629,7 +1676,8 @@ export function FilePreview({
<Button
size="sm"
variant="ghost"
- onClick={() => setEditing(true)}
+ disabled={loadingEditor}
+ onClick={() => void handleEdit()}
>
<Pencil className="mr-1 size-3.5" />
{t('filePreview.edit')}
@@ -1662,7 +1710,7 @@ export function FilePreview({
>
<LazyCodeEditor
ref={editorRef}
- initialContent={preview.content}
+ initialContent={editorContent}
filename={file.name}
isDark={isDark}
/>
@@ -1942,7 +1990,12 @@ export function FilePreview({
onNavigate={onNavigate}
rawFrontmatter={okfDocument.rawFrontmatter}
/>
- ) : frontmatter ? <YamlMetadata rawFrontmatter={frontmatter.rawFrontmatter} defaultOpen /> : null}
+ ) : frontmatter ? (
+ <YamlMetadata
+ rawFrontmatter={frontmatter.rawFrontmatter}
+ defaultOpen
+ />
+ ) : null}
<article className="prose prose-sm max-w-none break-words dark:prose-invert dark:prose-pre:bg-muted-foreground/20">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
diff --git a/web-studio/src/routes/resources/-components/lazy-file-preview.tsx b/web-studio/src/routes/resources/-components/lazy-file-preview.tsx
index 95cdc6581..7cfc1da7e 100644
--- a/web-studio/src/routes/resources/-components/lazy-file-preview.tsx
+++ b/web-studio/src/routes/resources/-components/lazy-file-preview.tsx
@@ -10,12 +10,16 @@ const FilePreview = lazy(() =>
)
export function LazyFilePreview({
+ readOnly,
+ defaultReadLimit,
file,
hideDirectoryHeader,
onClose,
onNavigate,
showCloseButton,
}: {
+ readOnly?: boolean
+ defaultReadLimit?: number
file: VikingFsEntry | null
hideDirectoryHeader?: boolean
onClose: () => void
@@ -31,6 +35,8 @@ export function LazyFilePreview({
}
>
<FilePreview
+ readOnly={readOnly}
+ defaultReadLimit={defaultReadLimit}
file={file}
hideDirectoryHeader={hideDirectoryHeader}
onClose={onClose}
diff --git a/web-studio/src/routes/resources/-hooks/use-resource-upload.connection.test.tsx b/web-studio/src/routes/resources/-hooks/use-resource-upload.connection.test.tsx
new file mode 100644
index 000000000..261e5fad1
--- /dev/null
+++ b/web-studio/src/routes/resources/-hooks/use-resource-upload.connection.test.tsx
@@ -0,0 +1,284 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
+import axios, { AxiosHeaders } from 'axios'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios'
+
+import { ovClient } from '#/lib/ov-client'
+import { client as sdkClient } from '#/gen/ov-client/client.gen'
+import {
+ ResourceUploadProvider,
+ useResourceUpload,
+} from './use-resource-upload'
+
+vi.mock('sonner', () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
+}))
+
+const SOURCE_URL = 'http://workspace-a.test'
+const TARGET_URL = 'http://workspace-b.test'
+const originalOptions = ovClient.getOptions()
+const originalConnection = ovClient.getConnection()
+const originalGlobalAdapter = axios.defaults.adapter
+const originalClientAdapter = ovClient.instance.defaults.adapter
+const originalSdkAdapter = sdkClient.getConfig().adapter
+
+type RecordedRequest = {
+ baseUrl: string | undefined
+ credential: string | undefined
+ fileName: string | null
+ path: string | undefined
+ signal: { readonly aborted: boolean } | undefined
+}
+
+function selectWorkspace(baseUrl: string, userId: string) {
+ ovClient.setOptions({ baseUrl, apiKeyAuth: 'header' })
+ ovClient.setConnection({
+ accountId: 'team',
+ adminApiKey: '',
+ apiKey: `fixture-${userId}-key`,
+ identityHeaders: true,
+ userId,
+ })
+}
+
+function response(config: InternalAxiosRequestConfig, result: unknown) {
+ return {
+ config,
+ data: { status: 'ok', result },
+ headers: {},
+ status: 200,
+ statusText: 'OK',
+ }
+}
+
+function recordUploadsWithFirstRequestPaused() {
+ const requests: RecordedRequest[] = []
+ let finishFirstUpload!: () => void
+ const firstUploadPending = new Promise<void>((resolve) => {
+ finishFirstUpload = resolve
+ })
+ const adapter: AxiosAdapter = async (config) => {
+ const file =
+ config.data instanceof FormData ? config.data.get('file') : null
+ const url = new URL(config.url!, config.baseURL || SOURCE_URL)
+ requests.push({
+ baseUrl: url.origin,
+ credential: String(AxiosHeaders.from(config.headers).get('X-API-Key')),
+ fileName: file instanceof File ? file.name : null,
+ path: url.pathname,
+ signal: config.signal,
+ })
+ if (url.pathname === '/api/v1/resources/temp_upload') {
+ if (file instanceof File && file.name === 'first.txt') {
+ // Ignore cancellation deliberately: a response may finish while a
+ // connection changes, so the continuation must also check ownership.
+ await firstUploadPending
+ }
+ return response(config, {
+ temp_file_id: `temp-${file instanceof File ? file.name : 'file'}`,
+ })
+ }
+ if (url.pathname === '/api/v1/resources') {
+ return response(config, {
+ status: 'success',
+ root_uri: 'viking://resources/files',
+ })
+ }
+ return response(config, [])
+ }
+ axios.defaults.adapter = adapter
+ ovClient.instance.defaults.adapter = adapter
+ sdkClient.setConfig({ adapter })
+ return { requests, finishFirstUpload }
+}
+
+beforeEach(() => {
+ selectWorkspace(SOURCE_URL, 'alice')
+})
+
+afterEach(() => {
+ cleanup()
+ axios.defaults.adapter = originalGlobalAdapter
+ ovClient.instance.defaults.adapter = originalClientAdapter
+ sdkClient.setConfig({ adapter: originalSdkAdapter })
+ ovClient.setOptions(originalOptions)
+ ovClient.setConnection(originalConnection)
+ vi.clearAllMocks()
+})
+
+describe('ResourceUploadProvider connection ownership', () => {
+ it('loads server tasks after StrictMode replays the initial mount', async () => {
+ const { requests } = recordUploadsWithFirstRequestPaused()
+ renderHook(() => useResourceUpload(), {
+ reactStrictMode: true,
+ wrapper: ResourceUploadProvider,
+ })
+
+ await waitFor(() =>
+ expect(requests.some((request) => request.path === '/api/v1/tasks')).toBe(
+ true,
+ ),
+ )
+ })
+
+ it('stops the remaining local files when its workspace unmounts during temp upload', async () => {
+ const { requests, finishFirstUpload } =
+ recordUploadsWithFirstRequestPaused()
+ const view = renderHook(() => useResourceUpload(), {
+ wrapper: ResourceUploadProvider,
+ })
+ act(() => {
+ view.result.current.enqueueUploads({
+ commonBody: {},
+ files: [
+ {
+ file: new File(['private A first file'], 'first.txt'),
+ fileType: null,
+ },
+ {
+ file: new File(['private A second file'], 'second.txt'),
+ fileType: null,
+ },
+ ],
+ })
+ })
+ await waitFor(() =>
+ expect(requests.filter((request) => request.fileName)).toHaveLength(1),
+ )
+ expect(
+ requests.find((request) => request.fileName === 'first.txt'),
+ ).toMatchObject({
+ baseUrl: SOURCE_URL,
+ credential: 'fixture-alice-key',
+ })
+
+ view.unmount()
+ expect(
+ requests.find((request) => request.fileName === 'first.txt')?.signal
+ ?.aborted,
+ ).toBe(true)
+ selectWorkspace(TARGET_URL, 'bob')
+ await act(async () => {
+ finishFirstUpload()
+ })
+
+ expect(
+ requests.filter(
+ (request) => request.baseUrl === TARGET_URL && request.fileName,
+ ),
+ ).toEqual([])
+ expect(requests.filter((request) => request.fileName)).toHaveLength(1)
+ expect(
+ requests.filter((request) => request.baseUrl === TARGET_URL),
+ ).toEqual([])
+ expect(
+ requests.filter((request) => request.path === '/api/v1/resources'),
+ ).toEqual([])
+ })
+
+ it.each([
+ ['service URL', () => selectWorkspace(TARGET_URL, 'bob')],
+ [
+ 'API key on the same service',
+ () => ovClient.setConnection({ apiKey: 'fixture-rotated-key' }),
+ ],
+ ] as const)(
+ 'does not import a temporary file after the %s changes before unmount',
+ async (_label, changeConnection) => {
+ const { requests, finishFirstUpload } =
+ recordUploadsWithFirstRequestPaused()
+ const view = renderHook(() => useResourceUpload(), {
+ wrapper: ResourceUploadProvider,
+ })
+ act(() => {
+ view.result.current.enqueueUploads({
+ commonBody: {},
+ files: [
+ {
+ file: new File(['private A first file'], 'first.txt'),
+ fileType: null,
+ },
+ ],
+ })
+ })
+ await waitFor(() =>
+ expect(
+ requests.some((request) => request.fileName === 'first.txt'),
+ ).toBe(true),
+ )
+
+ changeConnection()
+ await act(async () => {
+ finishFirstUpload()
+ })
+
+ expect(
+ requests.filter((request) => request.path === '/api/v1/resources'),
+ ).toEqual([])
+ expect(
+ requests.filter((request) => request.baseUrl === TARGET_URL),
+ ).toEqual([])
+ expect(
+ requests.find((request) => request.fileName === 'first.txt')?.signal
+ ?.aborted,
+ ).toBe(true)
+ },
+ )
+
+ it('uploads and imports both files in order with the original workspace credentials', async () => {
+ const { requests, finishFirstUpload } =
+ recordUploadsWithFirstRequestPaused()
+ const view = renderHook(() => useResourceUpload(), {
+ wrapper: ResourceUploadProvider,
+ })
+ act(() => {
+ view.result.current.enqueueUploads({
+ commonBody: {},
+ files: [
+ {
+ file: new File(['first file'], 'first.txt'),
+ fileType: null,
+ },
+ {
+ file: new File(['second file'], 'second.txt'),
+ fileType: null,
+ },
+ ],
+ })
+ })
+ await waitFor(() =>
+ expect(requests.filter((request) => request.fileName)).toHaveLength(1),
+ )
+ expect(
+ requests.filter((request) => request.path === '/api/v1/resources'),
+ ).toEqual([])
+ await act(async () => {
+ finishFirstUpload()
+ })
+ await waitFor(() =>
+ expect(view.result.current.tasks.map((task) => task.status)).toEqual([
+ 'success',
+ 'success',
+ ]),
+ )
+
+ const writes = requests.filter((request) =>
+ request.path?.startsWith('/api/v1/resources'),
+ )
+ expect(writes.map(({ fileName, path }) => ({ fileName, path }))).toEqual([
+ { fileName: 'first.txt', path: '/api/v1/resources/temp_upload' },
+ { fileName: null, path: '/api/v1/resources' },
+ { fileName: 'second.txt', path: '/api/v1/resources/temp_upload' },
+ { fileName: null, path: '/api/v1/resources' },
+ ])
+ for (const request of writes) {
+ expect(request).toMatchObject({
+ baseUrl: SOURCE_URL,
+ credential: 'fixture-alice-key',
+ })
+ expect(request.signal?.aborted).toBe(false)
+ }
+ })
+})
diff --git a/web-studio/src/routes/resources/-hooks/use-resource-upload.test.tsx b/web-studio/src/routes/resources/-hooks/use-resource-upload.test.tsx
index 28428f65f..6843d1c6a 100644
--- a/web-studio/src/routes/resources/-hooks/use-resource-upload.test.tsx
+++ b/web-studio/src/routes/resources/-hooks/use-resource-upload.test.tsx
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import {
+ act,
cleanup,
fireEvent,
render,
@@ -8,8 +9,10 @@ import {
waitFor,
} from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { toast } from 'sonner'
import i18n from '#/i18n'
+import type * as OvClientModule from '#/lib/ov-client'
import {
ResourceUploadProvider,
useResourceUpload,
@@ -20,7 +23,8 @@ const apiMocks = vi.hoisted(() => ({
postResources: vi.fn(),
}))
-vi.mock('#/lib/ov-client', () => ({
+vi.mock('#/lib/ov-client', async (importOriginal) => ({
+ ...(await importOriginal<typeof OvClientModule>()),
getOvResult: async (value: unknown) => value,
getTasks: apiMocks.getTasks,
isOvClientError: () => false,
@@ -37,6 +41,16 @@ afterEach(() => {
vi.clearAllMocks()
})
+it('does not load upload tasks when the workbench only supports reads', async () => {
+ render(
+ <ResourceUploadProvider enabled={false}>
+ <span data-testid="read-only" />
+ </ResourceUploadProvider>,
+ )
+ await screen.findByTestId('read-only')
+ expect(apiMocks.getTasks).not.toHaveBeenCalled()
+})
+
function UploadHarness({
onAccepted,
onCompleted,
@@ -77,6 +91,60 @@ function UploadHarness({
}
describe('ResourceUploadProvider remote completion', () => {
+ it.each(['resolve', 'reject'] as const)(
+ 'stops remote notifications after unmount when the request later %ss',
+ async (outcome) => {
+ let resolveImport!: (result: { status: string; root_uri: string }) => void
+ let rejectImport!: (error: Error) => void
+ apiMocks.getTasks.mockResolvedValue([])
+ apiMocks.postResources.mockImplementation(
+ () =>
+ new Promise((resolve, reject) => {
+ resolveImport = resolve
+ rejectImport = reject
+ }),
+ )
+ const onAccepted = vi.fn()
+ const onCompleted = vi.fn()
+ const onFailed = vi.fn()
+ const { unmount } = render(
+ <ResourceUploadProvider>
+ <UploadHarness
+ onAccepted={onAccepted}
+ onCompleted={onCompleted}
+ onFailed={onFailed}
+ />
+ </ResourceUploadProvider>,
+ )
+
+ fireEvent.click(screen.getByTestId('start'))
+ await waitFor(() => expect(apiMocks.postResources).toHaveBeenCalledOnce())
+ const signal = apiMocks.postResources.mock.calls[0][0]
+ .signal as AbortSignal
+ expect(signal.aborted).toBe(false)
+ unmount()
+ expect(signal.aborted).toBe(true)
+
+ await act(async () => {
+ if (outcome === 'resolve') {
+ resolveImport({
+ status: 'success',
+ root_uri: 'viking://resources/OpenViking',
+ })
+ } else {
+ rejectImport(new Error('Late import failure'))
+ }
+ })
+
+ expect(onAccepted).not.toHaveBeenCalled()
+ expect(onCompleted).not.toHaveBeenCalled()
+ expect(onFailed).not.toHaveBeenCalled()
+ expect(toast.success).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
+ expect(apiMocks.getTasks).toHaveBeenCalledOnce()
+ },
+ )
+
it('notifies after submission and again after the background task completes', async () => {
let taskStatus = 'processing'
apiMocks.getTasks.mockImplementation(() => [
diff --git a/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx b/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx
index ba7fec916..a7d40a4eb 100644
--- a/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx
+++ b/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx
@@ -4,9 +4,11 @@ import { toast } from 'sonner'
import i18n from '#/i18n'
import {
+ createOvClient,
getTasks,
getOvResult,
isOvClientError,
+ ovClient,
postResourcesTempUpload,
} from '#/lib/ov-client'
import { parseUploadError } from '../-lib/upload'
@@ -118,6 +120,33 @@ const TASK_REFRESH_LIMIT = 50
const ResourceUploadContext =
React.createContext<ResourceUploadContextValue | null>(null)
+function captureUploadConnection() {
+ const options = ovClient.getOptions()
+ const connection = ovClient.getConnection()
+ const client = createOvClient({
+ ...options,
+ apiKeyStorageKey: '',
+ connection,
+ }).client
+
+ return {
+ client,
+ isCurrent() {
+ const currentOptions = ovClient.getOptions()
+ const current = ovClient.getConnection()
+ return (
+ currentOptions.baseUrl === options.baseUrl &&
+ currentOptions.apiKeyAuth === options.apiKeyAuth &&
+ current.accountId === connection.accountId &&
+ current.userId === connection.userId &&
+ current.apiKey === connection.apiKey &&
+ current.adminApiKey === connection.adminApiKey &&
+ current.identityHeaders === connection.identityHeaders
+ )
+ },
+ }
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value)
}
@@ -176,41 +205,85 @@ export function useResourceUpload(): ResourceUploadContextValue {
export function ResourceUploadProvider({
children,
+ enabled = true,
}: {
children: React.ReactNode
+ enabled?: boolean
}) {
const { t } = useTranslation('resources', { i18n })
const [tasks, setTasks] = React.useState<ResourceUploadTask[]>([])
const [remoteState, setRemoteState] =
React.useState<RemoteUploadState>(INITIAL_REMOTE_STATE)
const [isRefreshingTasks, setIsRefreshingTasks] = React.useState(false)
+ const [source] = React.useState(captureUploadConnection)
+ const mountedRef = React.useRef(true)
+ const operationsRef = React.useRef(new Set<AbortController>())
const remoteAbortRef = React.useRef<AbortController | null>(null)
- const refreshInFlightRef = React.useRef(false)
+ const refreshAbortRef = React.useRef<AbortController | null>(null)
const notifiedServerTaskIdsRef = React.useRef<Set<string>>(new Set())
const remoteCompletionCallbacksRef = React.useRef(
new Map<string, { onCompleted?: () => void; onFailed?: () => void }>(),
)
const uploadQueueRef = React.useRef<Promise<void>>(Promise.resolve())
+ const isSourceCurrent = React.useCallback(
+ () => mountedRef.current && source.isCurrent(),
+ [source],
+ )
+
+ const beginOperation = React.useCallback(() => {
+ if (!isSourceCurrent()) return null
+ const controller = new AbortController()
+ operationsRef.current.add(controller)
+ return controller
+ }, [isSourceCurrent])
+
+ const isOperationCurrent = React.useCallback(
+ (controller: AbortController) => {
+ if (controller.signal.aborted) return false
+ if (isSourceCurrent()) return true
+ controller.abort()
+ return false
+ },
+ [isSourceCurrent],
+ )
+
+ React.useEffect(() => {
+ mountedRef.current = true
+ const operations = operationsRef.current
+ const callbacks = remoteCompletionCallbacksRef.current
+ return () => {
+ // Promise queues outlive React; abort requests and stop their continuations.
+ mountedRef.current = false
+ for (const controller of operations) controller.abort()
+ operations.clear()
+ callbacks.clear()
+ remoteAbortRef.current = null
+ }
+ }, [])
+
const updateTask = React.useCallback(
(
taskId: string,
updater: (task: ResourceUploadTask) => ResourceUploadTask,
) => {
+ if (!isSourceCurrent()) return
setTasks((prev) =>
prev.map((task) => (task.id === taskId ? updater(task) : task)),
)
},
- [],
+ [isSourceCurrent],
)
const refreshTasks = React.useCallback(
async (options: RefreshTasksOptions = {}) => {
- if (refreshInFlightRef.current) {
+ if (refreshAbortRef.current && !refreshAbortRef.current.signal.aborted) {
return
}
+ const controller = beginOperation()
+ if (!controller) return
- refreshInFlightRef.current = true
+ refreshAbortRef.current = controller
if (!options.silent) {
setIsRefreshingTasks(true)
}
@@ -218,12 +291,15 @@ export function ResourceUploadProvider({
try {
const result = await getOvResult<TaskListResult>(
getTasks({
+ client: source.client,
+ signal: controller.signal,
query: {
limit: TASK_REFRESH_LIMIT,
task_type: RESOURCE_ADD_TASK_TYPE,
},
}),
)
+ if (!isOperationCurrent(controller)) return
const serverTasks = normalizeTaskList(result)
const fallbackMessages = {
failed: i18n.t('resources:processingTasks.errors.failed'),
@@ -233,17 +309,21 @@ export function ResourceUploadProvider({
mergeServerTasks(prev, serverTasks, fallbackMessages),
)
} catch (error) {
+ if (!isOperationCurrent(controller)) return
if (options.notifyOnError !== false) {
toast.error(getErrorMessage(error), { duration: 5000 })
}
} finally {
- refreshInFlightRef.current = false
- if (!options.silent) {
- setIsRefreshingTasks(false)
+ operationsRef.current.delete(controller)
+ if (refreshAbortRef.current === controller) {
+ refreshAbortRef.current = null
+ if (isOperationCurrent(controller) && !options.silent) {
+ setIsRefreshingTasks(false)
+ }
}
}
},
- [],
+ [beginOperation, isOperationCurrent, source],
)
const processFileUpload = React.useCallback(
@@ -251,8 +331,10 @@ export function ResourceUploadProvider({
taskId: string,
params: UploadBatchItem,
commonBody: ResourceImportCommonBody,
+ controller: AbortController,
) => {
try {
+ if (!isOperationCurrent(controller)) return
updateTask(taskId, (task) => ({
...task,
status: 'uploading',
@@ -261,11 +343,14 @@ export function ResourceUploadProvider({
const uploadResult = await getOvResult<TempUploadResult>(
postResourcesTempUpload({
+ client: source.client,
+ signal: controller.signal,
body: {
file: params.file,
telemetry: true,
},
onUploadProgress: (event: { loaded: number; total?: number }) => {
+ if (!isOperationCurrent(controller)) return
const total = event.total
if (!total) return
updateTask(taskId, (task) => ({
@@ -276,6 +361,7 @@ export function ResourceUploadProvider({
},
}),
)
+ if (!isOperationCurrent(controller)) return
const tempFileId = isRecord(uploadResult)
? uploadResult.temp_file_id
@@ -299,8 +385,10 @@ export function ResourceUploadProvider({
params.file.name,
commonBody,
),
+ { client: source.client, signal: controller.signal },
),
)
+ if (!isOperationCurrent(controller)) return
if (addResult.status === 'error') {
const errors = Array.isArray(addResult.errors) ? addResult.errors : []
@@ -338,6 +426,7 @@ export function ResourceUploadProvider({
}))
toast.success(params.file.name)
} catch (error) {
+ if (!isOperationCurrent(controller)) return
const { errorCode, errorMessage } = parseUploadError(
getErrorMessage(error),
)
@@ -352,12 +441,14 @@ export function ResourceUploadProvider({
toast.error(errorMessage, { duration: 5000 })
}
},
- [refreshTasks, updateTask],
+ [isOperationCurrent, refreshTasks, source, updateTask],
)
const enqueueUploads = React.useCallback(
(params: UploadBatchParams) => {
if (params.files.length === 0) return
+ const controller = beginOperation()
+ if (!controller) return
const createdAt = Date.now()
const nextTasks = params.files.map((item, index) => ({
@@ -381,18 +472,22 @@ export function ResourceUploadProvider({
for (const [index, item] of params.files.entries()) {
const task = nextTasks[index]
uploadQueueRef.current = uploadQueueRef.current.then(() =>
- processFileUpload(task.id, item, params.commonBody),
+ processFileUpload(task.id, item, params.commonBody, controller),
)
}
+ void uploadQueueRef.current.finally(() => {
+ operationsRef.current.delete(controller)
+ })
},
- [processFileUpload],
+ [beginOperation, processFileUpload],
)
const startRemote = React.useCallback(
(params: RemoteStartParams) => {
if (remoteAbortRef.current) return
- const controller = new AbortController()
+ const controller = beginOperation()
+ if (!controller) return
remoteAbortRef.current = controller
const taskId = createTaskId()
@@ -428,9 +523,10 @@ export function ResourceUploadProvider({
const result = await getOvResult<ResourceImportResult>(
postResourceImport(
buildRemoteResourceRequest(params.url, params.commonBody),
- controller.signal,
+ { client: source.client, signal: controller.signal },
),
)
+ if (!isOperationCurrent(controller)) return
if (result.status === 'error') {
const errors = Array.isArray(result.errors) ? result.errors : []
@@ -449,6 +545,7 @@ export function ResourceUploadProvider({
: null
params.onAccepted?.({ rootUri, taskId: serverTaskId })
+ if (!isOperationCurrent(controller)) return
if (serverTaskId) {
if (params.onCompleted || params.onFailed) {
@@ -477,6 +574,7 @@ export function ResourceUploadProvider({
}
params.onCompleted?.()
+ if (!isOperationCurrent(controller)) return
updateTask(taskId, (task) => ({
...task,
@@ -495,6 +593,7 @@ export function ResourceUploadProvider({
})
toast.success(params.url)
} catch (error) {
+ if (!isSourceCurrent()) return
if (controller.signal.aborted) {
params.onFailed?.()
updateTask(taskId, (task) => ({
@@ -531,24 +630,35 @@ export function ResourceUploadProvider({
})
toast.error(errorMessage, { duration: 5000 })
} finally {
- remoteAbortRef.current = null
+ operationsRef.current.delete(controller)
+ if (remoteAbortRef.current === controller) {
+ remoteAbortRef.current = null
+ }
}
})()
},
- [refreshTasks, updateTask],
+ [
+ beginOperation,
+ isOperationCurrent,
+ isSourceCurrent,
+ refreshTasks,
+ source,
+ updateTask,
+ ],
)
const resetRemote = React.useCallback(() => {
+ if (!isSourceCurrent()) return
if (remoteAbortRef.current) {
remoteAbortRef.current.abort()
remoteAbortRef.current = null
}
setRemoteState(INITIAL_REMOTE_STATE)
- }, [])
+ }, [isSourceCurrent])
React.useEffect(() => {
- void refreshTasks({ notifyOnError: false, silent: true })
- }, [refreshTasks, t])
+ if (enabled) void refreshTasks({ notifyOnError: false, silent: true })
+ }, [enabled, refreshTasks, t])
const hasActiveServerTasks = React.useMemo(
() =>
@@ -571,6 +681,7 @@ export function ResourceUploadProvider({
}, [hasActiveServerTasks, refreshTasks])
React.useEffect(() => {
+ if (!isSourceCurrent()) return
if (remoteState.phase !== 'processing' || !remoteState.taskId) {
return
}
@@ -618,9 +729,10 @@ export function ResourceUploadProvider({
: prev,
)
}
- }, [remoteState.phase, remoteState.taskId, t, tasks])
+ }, [isSourceCurrent, remoteState.phase, remoteState.taskId, t, tasks])
React.useEffect(() => {
+ if (!isSourceCurrent()) return
for (const task of tasks) {
if (!task.serverTaskId || isUploadStatusActive(task.status)) {
continue
@@ -640,9 +752,10 @@ export function ResourceUploadProvider({
callbacks.onFailed?.()
}
}
- }, [tasks])
+ }, [isSourceCurrent, tasks])
React.useEffect(() => {
+ if (!isSourceCurrent()) return
for (const task of tasks) {
if (
!task.serverTaskId ||
@@ -660,7 +773,7 @@ export function ResourceUploadProvider({
toast.error(task.errorMessage || task.fileName, { duration: 5000 })
}
}
- }, [tasks])
+ }, [isSourceCurrent, tasks])
const activeTaskCount = React.useMemo(
() => tasks.filter((task) => isUploadStatusActive(task.status)).length,
diff --git a/web-studio/src/routes/resources/-lib/resource-import-api.ts b/web-studio/src/routes/resources/-lib/resource-import-api.ts
index cf135ba51..f16559e63 100644
--- a/web-studio/src/routes/resources/-lib/resource-import-api.ts
+++ b/web-studio/src/routes/resources/-lib/resource-import-api.ts
@@ -1,4 +1,5 @@
import { postResources } from '#/lib/ov-client'
+import type { OvClientAdapter } from '#/lib/ov-client'
import type { ResourceImportRequest } from './resource-import-types'
type GeneratedResourceBody = Parameters<typeof postResources>[0]['body']
@@ -9,10 +10,10 @@ type GeneratedResourceBody = Parameters<typeof postResources>[0]['body']
*/
export function postResourceImport(
body: ResourceImportRequest,
- signal?: AbortSignal,
+ options: { client: OvClientAdapter['client']; signal: AbortSignal },
) {
return postResources({
body: body as GeneratedResourceBody,
- ...(signal ? { signal } : {}),
+ ...options,
})
}
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx b/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx
index 9e08135a6..f57398de5 100644
--- a/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx
+++ b/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx
@@ -124,6 +124,10 @@ export function RetrievalControls({
))}
</div>
+ <p className="text-xs leading-5 text-muted-foreground" aria-live="polite">
+ {t(`modeDescriptions.${mode}`)}
+ </p>
+
<div className="flex flex-wrap items-center gap-2">
<Select
value={String(options.resultCount)}
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.test.tsx b/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.test.tsx
index e9b873b2a..f3c5a662f 100644
--- a/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.test.tsx
+++ b/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.test.tsx
@@ -15,10 +15,17 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { resources } from '#/i18n/resources'
import { RetrievalDetailSheet } from './retrieval-detail-sheet'
+const serviceState = vi.hoisted(() => ({ provider: 'volcengine' }))
+
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => serviceState,
+}))
+
const t = ((key: string) => key) as TFunction<'retrieval'>
afterEach(() => {
cleanup()
+ serviceState.provider = 'volcengine'
})
describe('RetrievalDetailSheet', () => {
@@ -47,6 +54,7 @@ describe('RetrievalDetailSheet', () => {
])(
'links to the selected file with its translated label in %s',
async (lng, label) => {
+ serviceState.provider = 'opensource'
const i18n = createInstance()
await i18n.use(initReactI18next).init({ lng, resources })
const uri = 'viking://resources/guide.md'
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-results.test.tsx b/web-studio/src/routes/retrieval/-components/retrieval-results.test.tsx
index fa1f0c943..f842a924e 100644
--- a/web-studio/src/routes/retrieval/-components/retrieval-results.test.tsx
+++ b/web-studio/src/routes/retrieval/-components/retrieval-results.test.tsx
@@ -10,6 +10,10 @@ import { resources } from '#/i18n/resources'
import { RetrievalResults } from './retrieval-results'
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ provider: 'opensource' }),
+}))
+
const t = ((key: string) => key) as TFunction<'retrieval'>
afterEach(cleanup)
diff --git a/web-studio/src/routes/sessions/-components/thread-draft.test.tsx b/web-studio/src/routes/sessions/-components/thread-draft.test.tsx
index f0bd85865..291c9c867 100644
--- a/web-studio/src/routes/sessions/-components/thread-draft.test.tsx
+++ b/web-studio/src/routes/sessions/-components/thread-draft.test.tsx
@@ -1,10 +1,11 @@
// @vitest-environment jsdom
import { useState } from 'react'
-import { act, cleanup, render } from '@testing-library/react'
+import { act, cleanup, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { Thread } from './thread'
const m = vi.hoisted(() => ({
+ provider: 'opensource',
create: vi.fn(),
history: vi.fn(),
send: vi.fn(),
@@ -13,6 +14,9 @@ const m = vi.hoisted(() => ({
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ provider: m.provider, ready: true }),
+}))
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({ identityScopeKey: 'test' }),
}))
@@ -37,6 +41,8 @@ vi.mock('./composer', () => ({
beforeEach(() => {
vi.clearAllMocks()
+ m.provider = 'opensource'
+ m.onSend = undefined
m.history.mockReturnValue({ isPending: true })
Element.prototype.scrollIntoView = vi.fn()
})
@@ -126,3 +132,15 @@ it('loads persisted history and continues after switching tabs', async () => {
expect(m.create).toHaveBeenCalledExactlyOnceWith('draft')
expect(m.send).toHaveBeenLastCalledWith('second')
})
+
+it('preserves hosted session history without exposing a Bot composer or draft send', () => {
+ m.provider = 'volcengine'
+ m.history.mockReturnValue({ isPending: false, data: [] })
+ render(<Thread sessionId="hosted-session" />)
+ expect(m.history).toHaveBeenLastCalledWith('hosted-session')
+ expect(m.onSend).toBeUndefined()
+ expect(m.send).not.toHaveBeenCalled()
+ expect(m.create).not.toHaveBeenCalled()
+ expect(screen.getByText('chat.emptyReadDescription')).toBeTruthy()
+ expect(screen.queryByText('chat.emptyDescription')).toBeNull()
+})
diff --git a/web-studio/src/routes/sessions/-components/thread-list.tsx b/web-studio/src/routes/sessions/-components/thread-list.tsx
index 96700b96e..740c07f0a 100644
--- a/web-studio/src/routes/sessions/-components/thread-list.tsx
+++ b/web-studio/src/routes/sessions/-components/thread-list.tsx
@@ -20,6 +20,7 @@ import {
AlertDialogTitle,
} from '#/components/ui/alert-dialog'
import { Button } from '#/components/ui/button'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
import {
useCreateSession,
@@ -35,6 +36,7 @@ interface ThreadListProps {
export function ThreadList({ activeSessionId }: ThreadListProps) {
const { i18n, t } = useTranslation('sessions')
+ const { provider } = useStudioService()
const { identityScopeKey } = useAppConnection()
const navigate = useNavigate()
const { data: sessions, isLoading } = useSessionListByRecency()
@@ -92,7 +94,9 @@ export function ThreadList({ activeSessionId }: ThreadListProps) {
<div className="flex h-16 shrink-0 items-center justify-between border-b border-border/70 px-4">
<div className="min-w-0">
<h1 className="text-sm font-semibold text-foreground">
- {t('threadList.title')}
+ {provider === 'volcengine'
+ ? t('studio:sessionRecords')
+ : t('threadList.title')}
</h1>
{!isLoading ? (
<p className="mt-0.5 text-xs text-muted-foreground">
@@ -100,21 +104,23 @@ export function ThreadList({ activeSessionId }: ThreadListProps) {
</p>
) : null}
</div>
- <Button
- type="button"
- size="icon-sm"
- variant="outline"
- disabled={createSession.isPending}
- onClick={handleNewSession}
- aria-label={t('threadList.newSession')}
- title={t('threadList.newSession')}
- >
- {createSession.isPending ? (
- <LoaderCircleIcon className="animate-spin" />
- ) : (
- <PlusIcon />
- )}
- </Button>
+ {provider === 'opensource' ? (
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="outline"
+ disabled={createSession.isPending}
+ onClick={handleNewSession}
+ aria-label={t('threadList.newSession')}
+ title={t('threadList.newSession')}
+ >
+ {createSession.isPending ? (
+ <LoaderCircleIcon className="animate-spin" />
+ ) : (
+ <PlusIcon />
+ )}
+ </Button>
+ ) : null}
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-2">
@@ -132,7 +138,9 @@ export function ThreadList({ activeSessionId }: ThreadListProps) {
{t('threadList.emptyTitle')}
</p>
<p className="mt-1 text-xs leading-5 text-muted-foreground">
- {t('threadList.emptyDescription')}
+ {provider === 'opensource'
+ ? t('threadList.emptyDescription')
+ : t('studio:noSessionRecords')}
</p>
</div>
) : (
@@ -235,9 +243,11 @@ export function ThreadList({ activeSessionId }: ThreadListProps) {
</AlertDialogContent>
</AlertDialog>
- <div className="shrink-0 border-t border-border/70 px-4 py-3 text-[11px] text-muted-foreground">
- {t('threadList.shortcut')}
- </div>
+ {provider === 'opensource' ? (
+ <div className="shrink-0 border-t border-border/70 px-4 py-3 text-[11px] text-muted-foreground">
+ {t('threadList.shortcut')}
+ </div>
+ ) : null}
</aside>
)
}
diff --git a/web-studio/src/routes/sessions/-components/thread.tsx b/web-studio/src/routes/sessions/-components/thread.tsx
index a49f84a40..807c01852 100644
--- a/web-studio/src/routes/sessions/-components/thread.tsx
+++ b/web-studio/src/routes/sessions/-components/thread.tsx
@@ -2,6 +2,7 @@ import { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'
import { CompassIcon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
import { useChat } from '#/lib/sessions/use-chat'
import {
@@ -32,6 +33,8 @@ export function Thread(props: ThreadProps) {
function SessionThread({ sessionId, draft = false, onPersisted }: ThreadProps) {
const { t } = useTranslation('sessions')
+ const service = useStudioService()
+ const canChat = service.ready && service.provider === 'opensource'
const { identityScopeKey } = useAppConnection()
const { getTitle } = useSessionTitles(identityScopeKey)
const title = getTitle(sessionId)
@@ -66,7 +69,7 @@ function SessionThread({ sessionId, draft = false, onPersisted }: ThreadProps) {
const handleSend = useCallback(
async (message: string) => {
- if (!message.trim() || creating.current) return false
+ if (!canChat || !message.trim() || creating.current) return false
if (!persisted.current) {
creating.current = true
setCreationError(undefined)
@@ -88,7 +91,7 @@ function SessionThread({ sessionId, draft = false, onPersisted }: ThreadProps) {
void chat.send(message)
return true
},
- [chat, createSession, sessionId, onPersisted],
+ [canChat, chat, createSession, sessionId, onPersisted],
)
// ---- Auto-scroll ----
@@ -129,7 +132,7 @@ function SessionThread({ sessionId, draft = false, onPersisted }: ThreadProps) {
const isEmpty = chat.messages.length === 0 && !isStreaming
return (
- <div className="relative flex h-full flex-col">
+ <div className="relative flex h-full min-h-0 flex-1 flex-col">
{/* PixelBlast background — deferred until idle */}
{showBackground && isEmpty && (
<div className="pointer-events-none absolute inset-0 z-0 opacity-40">
@@ -151,7 +154,9 @@ function SessionThread({ sessionId, draft = false, onPersisted }: ThreadProps) {
? t('threadList.newSession')
: title || sessionId}
</h2>
- <MemoryImpact session={session} />
+ {service.provider === 'opensource' ? (
+ <MemoryImpact session={session} />
+ ) : null}
</div>
<div
@@ -168,7 +173,7 @@ function SessionThread({ sessionId, draft = false, onPersisted }: ThreadProps) {
{t('chat.historyLoadFailed', { error: historyError.message })}
</div>
) : isEmpty ? (
- <ThreadEmpty />
+ <ThreadEmpty canChat={canChat} />
) : (
<MessageList
messages={chat.messages}
@@ -193,18 +198,20 @@ function SessionThread({ sessionId, draft = false, onPersisted }: ThreadProps) {
{t('chat.sendFailed', { error: creationError || chat.error })}
</div>
)}
- <div className="relative z-10">
- <Composer
- onSend={handleSend}
- onCancel={chat.abort}
- isStreaming={isStreaming}
- />
- </div>
+ {canChat ? (
+ <div className="relative z-10">
+ <Composer
+ onSend={handleSend}
+ onCancel={chat.abort}
+ isStreaming={isStreaming}
+ />
+ </div>
+ ) : null}
</div>
)
}
-function ThreadEmpty() {
+function ThreadEmpty({ canChat }: { canChat: boolean }) {
const { t } = useTranslation('sessions')
return (
@@ -217,7 +224,7 @@ function ThreadEmpty() {
{PRODUCT_NAME}
</h3>
<p className="mt-1 text-sm text-muted-foreground">
- {t('chat.emptyDescription')}
+ {t(canChat ? 'chat.emptyDescription' : 'chat.emptyReadDescription')}
</p>
</div>
</div>
diff --git a/web-studio/src/routes/sessions/index.tsx b/web-studio/src/routes/sessions/index.tsx
index 721273a55..210fa7c6f 100644
--- a/web-studio/src/routes/sessions/index.tsx
+++ b/web-studio/src/routes/sessions/index.tsx
@@ -3,6 +3,7 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { CompassIcon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
import { useCreateSession } from '#/lib/sessions/use-sessions'
import { useSessionTitles } from '#/lib/sessions/use-session-titles'
@@ -22,6 +23,7 @@ export const Route = createFileRoute('/sessions/')({
function SessionsPage() {
const { t } = useTranslation('sessions')
+ const { provider } = useStudioService()
const { s: activeSessionId } = Route.useSearch()
const { identityScopeKey } = useAppConnection()
const navigate = useNavigate()
@@ -36,6 +38,7 @@ function SessionsPage() {
// Cmd+N to create new session
useEffect(() => {
+ if (provider !== 'opensource') return
const handler = (e: KeyboardEvent) => {
if (!(e.metaKey || e.ctrlKey)) return
if (e.key === 'n') {
@@ -45,7 +48,7 @@ function SessionsPage() {
}
document.addEventListener('keydown', handler)
return () => document.removeEventListener('keydown', handler)
- }, [handleNewSession])
+ }, [handleNewSession, provider])
return (
<div className="-mx-4 -my-6 flex h-[calc(100svh-3rem)] min-w-0 overflow-hidden md:-mx-6">
@@ -63,6 +66,7 @@ function SessionsPage() {
function SessionsEmpty() {
const { t } = useTranslation('sessions')
+ const { provider } = useStudioService()
return (
<div className="flex h-full flex-col items-center justify-center gap-6">
@@ -74,18 +78,22 @@ function SessionsEmpty() {
{t('empty.title')}
</h3>
<p className="mt-1 text-sm text-muted-foreground">
- {t('empty.description')}
+ {provider === 'opensource'
+ ? t('empty.description')
+ : t('studio:selectSessionRecord')}
</p>
</div>
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <kbd className="rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px]">
- {COMMAND_KEY_LABEL}
- </kbd>
- <kbd className="rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px]">
- {NEW_SESSION_KEY_LABEL}
- </kbd>
- <span>{t('threadList.newSession')}</span>
- </div>
+ {provider === 'opensource' ? (
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <kbd className="rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px]">
+ {COMMAND_KEY_LABEL}
+ </kbd>
+ <kbd className="rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px]">
+ {NEW_SESSION_KEY_LABEL}
+ </kbd>
+ <span>{t('threadList.newSession')}</span>
+ </div>
+ ) : null}
</div>
)
}
diff --git a/web-studio/src/routes/settings/-components/connection-profiles.test.ts b/web-studio/src/routes/settings/-components/connection-profiles.test.ts
new file mode 100644
index 000000000..deef13b93
--- /dev/null
+++ b/web-studio/src/routes/settings/-components/connection-profiles.test.ts
@@ -0,0 +1,167 @@
+// @vitest-environment jsdom
+import * as React from 'react'
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { ConnectionProfile } from '#/lib/connection/profiles'
+import {
+ ConnectionProfilesList,
+ groupedConnectionProfiles,
+} from './connection-profiles'
+
+const connectionState = vi.hoisted(() => ({
+ profiles: [] as ConnectionProfile[],
+ activeProfileId: 'active',
+ saveProfile: vi.fn(),
+ activateProfile: vi.fn(),
+ deleteProfile: vi.fn(),
+}))
+
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => connectionState,
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+const hosted = (
+ id: string,
+ accountId: string,
+ userId = 'wld2',
+ apiKey = 'key',
+): ConnectionProfile => ({
+ id,
+ name: id,
+ connection: {
+ serviceSelection: 'volcengine',
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ apiKey,
+ adminApiKey: '',
+ accountId,
+ userId,
+ },
+})
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ connectionState.profiles = []
+ connectionState.activeProfileId = 'active'
+})
+afterEach(() => {
+ cleanup()
+ vi.unstubAllGlobals()
+})
+
+it('groups identical connections without losing any saved profile', () => {
+ const profiles = [
+ hosted('duplicate', 'study'),
+ hosted('active', 'study'),
+ hosted('other-user', 'study', 'alice'),
+ hosted('other-space', 'production'),
+ ]
+ expect(
+ groupedConnectionProfiles(profiles, 'active').map((group) =>
+ group.map((profile) => profile.id),
+ ),
+ ).toEqual([['active', 'duplicate'], ['other-user'], ['other-space']])
+})
+
+it('keeps unverified default identities separate when their keys differ', () => {
+ connectionState.profiles = [
+ hosted('active', 'default', 'default', 'first-key'),
+ hosted('other', 'default', 'default', 'second-key'),
+ ]
+
+ expect(
+ groupedConnectionProfiles(
+ connectionState.profiles,
+ connectionState.activeProfileId,
+ ).map((group) => group.map((profile) => profile.id)),
+ ).toEqual([['active'], ['other']])
+
+ render(React.createElement(ConnectionProfilesList))
+ expect(screen.getAllByRole('button', { name: 'profiles.edit' })).toHaveLength(
+ 2,
+ )
+ fireEvent.click(
+ screen.getAllByRole('button', { name: 'profiles.activate' })[1],
+ )
+ expect(connectionState.activateProfile).toHaveBeenCalledWith('other')
+})
+
+it('compacts default/default and shows other hosted account/user identities', () => {
+ connectionState.profiles = [
+ hosted('personal', 'default', 'default'),
+ hosted('enterprise-alice', 'study', 'alice'),
+ hosted('enterprise-bob', 'study', 'bob'),
+ ]
+
+ render(React.createElement(ConnectionProfilesList))
+
+ expect(screen.getByText('[default]')).toBeTruthy()
+ expect(screen.queryByText('[default/default]')).toBeNull()
+ expect(screen.getByText('[study/alice]')).toBeTruthy()
+ expect(screen.getByText('[study/bob]')).toBeTruthy()
+})
+
+it('lets every record in an identical connection group be managed', () => {
+ connectionState.profiles = [
+ hosted('duplicate', 'default', 'default'),
+ hosted('active', 'default', 'default'),
+ ]
+
+ const { container } = render(React.createElement(ConnectionProfilesList))
+ const group = container.querySelector('details')
+ expect(group).not.toBeNull()
+ expect(group?.open).toBe(false)
+ expect(within(group!).getByText('profiles.title · 2')).toBeTruthy()
+ expect(
+ within(group!.querySelector('summary')!).getByText('[default]'),
+ ).toBeTruthy()
+
+ fireEvent.click(group!.querySelector('summary')!)
+ expect(group?.open).toBe(true)
+ expect(within(group!).queryAllByText('[default]')).toHaveLength(3)
+ expect(within(group!).queryByText('[default/default]')).toBeNull()
+ expect(
+ within(group!).getAllByRole('button', { name: 'profiles.edit' }),
+ ).toHaveLength(2)
+ expect(
+ within(group!).getAllByRole('button', { name: 'profiles.delete' }),
+ ).toHaveLength(2)
+ fireEvent.click(
+ within(group!).getAllByRole('button', { name: 'profiles.activate' })[1],
+ )
+ expect(connectionState.activateProfile).toHaveBeenCalledWith('duplicate')
+})
+
+it('creates a connection on HTTP origins without crypto.randomUUID', () => {
+ const getRandomValues = globalThis.crypto.getRandomValues.bind(
+ globalThis.crypto,
+ )
+ vi.stubGlobal('crypto', { getRandomValues })
+
+ render(React.createElement(ConnectionProfilesList))
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.add' }))
+ fireEvent.change(screen.getByLabelText('profiles.name'), {
+ target: { value: 'Local' },
+ })
+ fireEvent.change(screen.getByLabelText('profiles.fields.baseUrl'), {
+ target: { value: 'http://192.0.2.1:1933' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.save' }))
+
+ expect(connectionState.saveProfile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: expect.stringMatching(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
+ ),
+ name: 'Local',
+ }),
+ )
+})
diff --git a/web-studio/src/routes/settings/-components/connection-profiles.tsx b/web-studio/src/routes/settings/-components/connection-profiles.tsx
new file mode 100644
index 000000000..ac92ad6b5
--- /dev/null
+++ b/web-studio/src/routes/settings/-components/connection-profiles.tsx
@@ -0,0 +1,354 @@
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import { ChevronDownIcon } from 'lucide-react'
+import { Button } from '#/components/ui/button'
+import { Badge } from '#/components/ui/badge'
+import { Card, CardContent, CardHeader, CardTitle } from '#/components/ui/card'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '#/components/ui/dialog'
+import { Input } from '#/components/ui/input'
+import { Field, FieldLabel } from '#/components/ui/field'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { createRandomUuid } from '#/lib/browser-crypto'
+import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
+import type { ConnectionProfile } from '#/lib/connection/profiles'
+import { formatHostedIdentity } from '#/lib/connection/identity-label'
+import {
+ connectionProfileFingerprint,
+ isValidConnectionUrl,
+ normalizeProfileConnection,
+} from '#/lib/connection/profiles'
+
+const PROFILE_FIELDS = [
+ 'baseUrl',
+ 'apiKey',
+ 'adminApiKey',
+ 'accountId',
+ 'userId',
+] as const
+
+export function groupedConnectionProfiles(
+ profiles: ConnectionProfile[],
+ activeProfileId: string,
+): ConnectionProfile[][] {
+ const groups = new Map<string, ConnectionProfile[]>()
+ const sorted = [...profiles].sort((a, b) =>
+ a.id === activeProfileId ? -1 : b.id === activeProfileId ? 1 : 0,
+ )
+ for (const profile of sorted) {
+ // Account and user IDs may still be unverified defaults. A different key
+ // must remain a separate connection, even when those labels are identical.
+ const identity = connectionProfileFingerprint(profile.connection)
+ const group = groups.get(identity)
+ if (group) group.push(profile)
+ else groups.set(identity, [profile])
+ }
+ return [...groups.values()]
+}
+
+export function ConnectionProfilesList() {
+ const { t } = useTranslation(['studio', 'settings'])
+ const {
+ profiles = [],
+ activeProfileId,
+ saveProfile,
+ activateProfile,
+ deleteProfile,
+ } = useAppConnection()
+ const [draft, setDraft] = React.useState<ConnectionProfile | null>(null)
+ const [error, setError] = React.useState('')
+ const [deleting, setDeleting] = React.useState<ConnectionProfile | null>(null)
+ const openEditor = (profile: ConnectionProfile) => {
+ setError('')
+ setDraft(profile)
+ }
+ function save(event: React.FormEvent) {
+ event.preventDefault()
+ if (!draft) return
+ if (!isValidConnectionUrl(draft.connection.baseUrl)) {
+ setError(t('profiles.invalidUrl'))
+ return
+ }
+ const connection = normalizeProfileConnection(draft.connection)
+ saveProfile({
+ ...draft,
+ connection: {
+ ...connection,
+ adminApiKey:
+ connection.serviceSelection === 'volcengine'
+ ? ''
+ : connection.adminApiKey,
+ },
+ })
+ setDraft(null)
+ }
+ const identityLabel = (profile: ConnectionProfile) =>
+ profile.connection.serviceSelection === 'volcengine'
+ ? formatHostedIdentity(
+ profile.connection.accountId,
+ profile.connection.userId,
+ )
+ : `${profile.connection.accountId}/${profile.connection.userId}`
+ const renderProfile = (profile: ConnectionProfile) => (
+ <div
+ key={profile.id}
+ className="flex min-w-0 flex-col items-start justify-between gap-3 rounded-md border p-3 sm:flex-row sm:items-center"
+ >
+ <div className="w-full min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium">{profile.name}</span>
+ {identityLabel(profile) && (
+ <span
+ className="font-mono text-xs text-muted-foreground"
+ title={identityLabel(profile) ?? undefined}
+ >
+ [{identityLabel(profile)}]
+ </span>
+ )}
+ <Badge variant="outline">
+ {t(`providers.${profile.connection.serviceSelection}`)}
+ </Badge>
+ {profile.id === activeProfileId && (
+ <Badge>{t('profiles.active')}</Badge>
+ )}
+ </div>
+ <p className="mt-1 break-all text-sm text-muted-foreground">
+ {profile.connection.baseUrl}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ variant="outline"
+ disabled={profile.id === activeProfileId}
+ onClick={() => activateProfile(profile.id)}
+ >
+ {t('profiles.activate')}
+ </Button>
+ <Button variant="outline" onClick={() => openEditor(profile)}>
+ {t('profiles.edit')}
+ </Button>
+ <Button
+ variant="ghost"
+ disabled={profile.id === activeProfileId}
+ onClick={() => setDeleting(profile)}
+ >
+ {t('profiles.delete')}
+ </Button>
+ </div>
+ </div>
+ )
+ return (
+ <>
+ <Card>
+ <CardHeader className="flex flex-wrap items-center justify-between gap-3">
+ <CardTitle>{t('profiles.title')}</CardTitle>
+ <Button
+ onClick={() =>
+ openEditor({
+ id: createRandomUuid(),
+ name: '',
+ connection: {
+ serviceSelection: 'opensource',
+ baseUrl: '',
+ apiKey: '',
+ adminApiKey: '',
+ accountId: 'default',
+ userId: 'default',
+ },
+ })
+ }
+ >
+ {t('profiles.add')}
+ </Button>
+ </CardHeader>
+ <CardContent className="grid gap-3">
+ <p className="text-sm text-muted-foreground">{t('profiles.hint')}</p>
+ {groupedConnectionProfiles(profiles, activeProfileId).map((group) => {
+ if (group.length === 1) return renderProfile(group[0])
+ const primary = group[0]
+ return (
+ <details key={primary.id} className="group rounded-md border">
+ <summary className="flex cursor-pointer list-none items-center justify-between gap-3 p-3 [&::-webkit-details-marker]:hidden">
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium">{primary.name}</span>
+ {identityLabel(primary) && (
+ <span className="font-mono text-xs text-muted-foreground">
+ [{identityLabel(primary)}]
+ </span>
+ )}
+ <Badge variant="outline">
+ {t(`providers.${primary.connection.serviceSelection}`)}
+ </Badge>
+ {group.some(
+ (profile) => profile.id === activeProfileId,
+ ) && <Badge>{t('profiles.active')}</Badge>}
+ <span className="text-xs text-muted-foreground">
+ {t('profiles.title')} · {group.length}
+ </span>
+ </div>
+ <p className="mt-1 break-all text-sm text-muted-foreground">
+ {primary.connection.baseUrl}
+ </p>
+ </div>
+ <ChevronDownIcon className="size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-180" />
+ </summary>
+ <div className="grid gap-2 border-t p-2">
+ {group.map(renderProfile)}
+ </div>
+ </details>
+ )
+ })}
+ </CardContent>
+ </Card>
+ <Dialog
+ open={Boolean(draft)}
+ onOpenChange={(open) => {
+ if (!open) setDraft(null)
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ {t(
+ profiles.some((p) => p.id === draft?.id)
+ ? 'profiles.edit'
+ : 'profiles.add',
+ )}
+ </DialogTitle>
+ <DialogDescription>{t('profiles.saveHint')}</DialogDescription>
+ </DialogHeader>
+ {draft && (
+ <form onSubmit={save} className="grid gap-4">
+ <Field>
+ <FieldLabel htmlFor="profile-name">
+ {t('profiles.name')}
+ </FieldLabel>
+ <Input
+ id="profile-name"
+ required
+ value={draft.name}
+ onChange={(e) => setDraft({ ...draft, name: e.target.value })}
+ {...PLAIN_INPUT_PROPS}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="profile-provider">
+ {t('serviceType')}
+ </FieldLabel>
+ <select
+ id="profile-provider"
+ className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
+ value={draft.connection.serviceSelection}
+ onChange={(e) =>
+ setDraft({
+ ...draft,
+ connection: {
+ ...draft.connection,
+ serviceSelection: e.target.value as
+ | 'opensource'
+ | 'volcengine',
+ },
+ })
+ }
+ >
+ <option value="opensource">
+ {t('providers.opensource')}
+ </option>
+ <option value="volcengine">
+ {t('providers.volcengine')}
+ </option>
+ </select>
+ </Field>
+ {PROFILE_FIELDS.filter(
+ (field) =>
+ draft.connection.serviceSelection === 'opensource' ||
+ field === 'baseUrl' ||
+ field === 'apiKey',
+ ).map((key) => {
+ return (
+ <Field key={key}>
+ <FieldLabel htmlFor={`profile-${key}`}>
+ {t(`profiles.fields.${key}`)}
+ </FieldLabel>
+ <Input
+ id={`profile-${key}`}
+ required={key === 'baseUrl'}
+ type={
+ key === 'apiKey' || key === 'adminApiKey'
+ ? 'password'
+ : 'text'
+ }
+ value={draft.connection[key]}
+ onChange={(e) =>
+ setDraft({
+ ...draft,
+ connection: {
+ ...draft.connection,
+ [key]: e.target.value,
+ },
+ })
+ }
+ {...PLAIN_INPUT_PROPS}
+ />
+ </Field>
+ )
+ })}
+ {error && (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ )}
+ <div className="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setDraft(null)}
+ >
+ {t('profiles.cancel')}
+ </Button>
+ <Button type="submit" disabled={!draft.name.trim()}>
+ {t('profiles.save')}
+ </Button>
+ </div>
+ </form>
+ )}
+ </DialogContent>
+ </Dialog>
+ <Dialog
+ open={Boolean(deleting)}
+ onOpenChange={(open) => {
+ if (!open) setDeleting(null)
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('profiles.delete')}</DialogTitle>
+ <DialogDescription>
+ {t('profiles.deleteConfirm', { name: deleting?.name })}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex justify-end gap-2">
+ <Button variant="outline" onClick={() => setDeleting(null)}>
+ {t('profiles.cancel')}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => {
+ if (deleting) deleteProfile(deleting.id)
+ setDeleting(null)
+ }}
+ >
+ {t('profiles.delete')}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
+}
diff --git a/web-studio/src/routes/settings/-components/server-configuration.test.tsx b/web-studio/src/routes/settings/-components/server-configuration.test.tsx
index 283bdf803..323891dc6 100644
--- a/web-studio/src/routes/settings/-components/server-configuration.test.tsx
+++ b/web-studio/src/routes/settings/-components/server-configuration.test.tsx
@@ -19,6 +19,8 @@ import type { ModelConfig } from '../-lib/config-file-api'
const state = vi.hoisted(() => ({
role: 'root',
+ provider: 'opensource',
+ ready: true,
get: vi.fn(),
save: vi.fn(),
preview: vi.fn(),
@@ -45,6 +47,9 @@ vi.mock('#/components/code-editor', () => ({
/>
),
}))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({ provider: state.provider, ready: state.ready }),
+}))
vi.mock('#/lib/clipboard', () => ({ copyTextToClipboard: state.copy }))
vi.mock('../-lib/config-file-api', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
@@ -80,6 +85,8 @@ afterEach(() => {
cleanup()
vi.resetAllMocks()
state.role = 'root'
+ state.provider = 'opensource'
+ state.ready = true
})
const language = {
model: 'default-model',
@@ -1086,3 +1093,20 @@ it('edits uppercase VikingDB credentials with the correct auth controls', async
state.preview.mock.lastCall![1].embedding.dense.credentials[0],
).toMatchObject({ provider: 'VIKINGDB', sk: 'rotated-sk' })
})
+
+it.each(['volcengine', 'unknown'])(
+ 'does not read server configuration for a %s root identity',
+ (provider) => {
+ state.provider = provider
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <ServerConfigurationEditor />
+ </QueryClientProvider>,
+ )
+ expect(state.get).not.toHaveBeenCalled()
+ expect(state.save).not.toHaveBeenCalled()
+ expect(state.restart).not.toHaveBeenCalled()
+ client.clear()
+ },
+)
diff --git a/web-studio/src/routes/settings/-components/server-configuration.tsx b/web-studio/src/routes/settings/-components/server-configuration.tsx
index b1e90da1b..b5611f970 100644
--- a/web-studio/src/routes/settings/-components/server-configuration.tsx
+++ b/web-studio/src/routes/settings/-components/server-configuration.tsx
@@ -21,6 +21,8 @@ import {
Undo2Icon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
+import { canEditStudioConfiguration } from '#/lib/studio-permissions'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
import { createRandomUuid } from '#/lib/browser-crypto'
import { copyTextToClipboard } from '#/lib/clipboard'
@@ -313,9 +315,19 @@ export function ServerConfigurationEditor() {
identityScopeKey,
isConnectionRoleLoading,
} = useAppConnection()
+ const service = useStudioService()
const allowed =
- connectionRole === 'root' &&
- (serverMode === 'api_key' || serverMode === 'trusted')
+ service.ready &&
+ canEditStudioConfiguration({
+ serviceProvider: service.provider,
+ hasControlCredential: Boolean(connection.adminApiKey.trim()),
+ isRoleLoading: isConnectionRoleLoading,
+ role: connectionRole,
+ serverMode,
+ })
+ function requireAccess() {
+ if (!allowed) throw new Error(t('models.rootRequired'))
+ }
const api = React.useMemo(
() => createConfigFileApi(connection, serverMode === 'trusted'),
[connection, serverMode],
@@ -324,7 +336,10 @@ export function ServerConfigurationEditor() {
const queryKey = ['server-configuration', identityScopeKey]
const query = useQuery({
queryKey,
- queryFn: () => api.get(),
+ queryFn: () => {
+ requireAccess()
+ return api.get()
+ },
enabled: allowed,
retry: false,
})
@@ -343,6 +358,7 @@ export function ServerConfigurationEditor() {
React.useEffect(() => () => restartAbort.current?.abort(), [api])
const restartMutation = useMutation({
mutationFn: async (revision: string) => {
+ requireAccess()
const controller = new AbortController()
restartAbort.current = controller
const accepted = await api.restart(revision)
@@ -361,8 +377,10 @@ export function ServerConfigurationEditor() {
},
})
const mutation = useMutation({
- mutationFn: ({ content }: { content: string; restart?: boolean }) =>
- api.save(content, (baseline ?? query.data)!.revision),
+ mutationFn: ({ content }: { content: string; restart?: boolean }) => {
+ requireAccess()
+ return api.save(content, (baseline ?? query.data)!.revision)
+ },
onSuccess: async (result, variables) => {
queryClient.setQueryData<ConfigFileConfiguration>(queryKey, (previous) =>
previous
@@ -394,7 +412,10 @@ export function ServerConfigurationEditor() {
content: string
changes?: Partial<Record<EditableModelKind, ModelConfig>>
returnToForm?: boolean
- }) => api.preview(content, changes),
+ }) => {
+ requireAccess()
+ return api.preview(content, changes)
+ },
onSuccess: (result, variables) => {
setDraft(result)
setEditor(null)
diff --git a/web-studio/src/routes/settings/-gateway-connection.test.tsx b/web-studio/src/routes/settings/-gateway-connection.test.tsx
index b933c4c23..66e398012 100644
--- a/web-studio/src/routes/settings/-gateway-connection.test.tsx
+++ b/web-studio/src/routes/settings/-gateway-connection.test.tsx
@@ -31,7 +31,7 @@ const { health, saveConnection, navigate, connectionState } = vi.hoisted(
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({ ...connectionState, saveConnection }),
}))
-vi.mock('#/hooks/use-server-mode', async (importOriginal) => ({
+vi.mock('#/lib/connection/health', async (importOriginal) => ({
...(await importOriginal<object>()),
fetchServerHealth: health,
}))
diff --git a/web-studio/src/routes/settings/route.test.tsx b/web-studio/src/routes/settings/route.test.tsx
index ff6efe3a4..9769ed8af 100644
--- a/web-studio/src/routes/settings/route.test.tsx
+++ b/web-studio/src/routes/settings/route.test.tsx
@@ -1,24 +1,64 @@
// @vitest-environment jsdom
import type { ComponentType } from 'react'
-import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { afterEach, expect, it, vi } from 'vitest'
+import userEvent from '@testing-library/user-event'
import { Route } from './route'
-const { probe } = vi.hoisted(() => ({ probe: vi.fn() }))
+const {
+ probe,
+ reconnect,
+ saveConnection,
+ serviceState,
+ config,
+ connectionState,
+ healthState,
+} = vi.hoisted(() => ({
+ connectionState: {
+ baseUrl: '',
+ serviceSelection: 'auto',
+ accountId: 'account-a',
+ userId: 'alice',
+ adminApiKey: '',
+ apiKey: '',
+ },
+ probe: vi.fn(),
+ reconnect: vi.fn(),
+ saveConnection: vi.fn(),
+ serviceState: {
+ provider: 'opensource',
+ ready: true,
+ role: 'user',
+ key: '',
+ },
+ config: { url: 'http://localhost:1933', selection: 'auto' },
+ healthState: { value: null as null | Record<string, unknown> },
+}))
vi.mock('#/lib/admin', () => ({ probeStudioConnection: probe }))
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
connection: {
- baseUrl: 'http://localhost:1933',
- accountId: 'account-a',
- userId: 'alice',
- adminApiKey: '',
- apiKey: '',
+ ...Object.assign(connectionState, {
+ baseUrl: config.url,
+ serviceSelection: config.selection,
+ adminApiKey: serviceState.key,
+ }),
},
serverMode: 'trusted',
- saveConnection: vi.fn(),
+ serverHealth: healthState.value,
+ connectionRole: serviceState.role,
+ isConnectionRoleLoading: false,
+ identityScopeKey: 'settings-test',
+ saveConnection,
+ reconnect,
}),
}))
vi.mock('react-i18next', () => ({
@@ -27,35 +67,248 @@ vi.mock('react-i18next', () => ({
i18n: { resolvedLanguage: 'en' },
}),
}))
-afterEach(cleanup)
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => ({
+ provider: serviceState.provider,
+ ready: serviceState.ready,
+ version: '',
+ isChecking: false,
+ health: { refetch: vi.fn() },
+ }),
+}))
+vi.mock('./-components/server-configuration', () => ({
+ ServerConfigurationEditor: () => <span data-testid="configuration-editor" />,
+}))
+afterEach(() => {
+ cleanup()
+ healthState.value = null
+ saveConnection.mockClear()
+ reconnect.mockClear()
+})
-it('shows the Root key guide for trusted mode even when a capability probe fails', async () => {
+it('preserves the active connection when an invalid address is saved from the details panel', async () => {
probe.mockResolvedValue({
- admin: {
- state: 'error',
- statusCode: 403,
- detail: 'Management unavailable',
- },
- data: { state: 'ok', detailCode: 'tenantDataAvailable' },
+ admin: { state: 'skipped' },
+ data: { state: 'ok' },
})
- const client = new QueryClient({
- defaultOptions: { queries: { retry: false } },
+ const client = new QueryClient()
+ const Settings = Route.options.component as ComponentType & {
+ preload?: () => Promise<unknown>
+ }
+ await Settings.preload?.()
+ render(
+ <QueryClientProvider client={client}>
+ <Settings />
+ </QueryClientProvider>,
+ )
+ fireEvent.change(document.getElementById('settings-base-url')!, {
+ target: { value: 'not-a-url' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'studio:profiles.save' }))
+ expect(screen.getByRole('alert').textContent).toBe(
+ 'studio:profiles.invalidUrl',
+ )
+ expect(saveConnection).not.toHaveBeenCalled()
+ expect(reconnect).not.toHaveBeenCalled()
+ fireEvent.change(document.getElementById('settings-base-url')!, {
+ target: { value: 'https://proxy.example/openviking' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'studio:profiles.save' }))
+ expect(screen.queryByRole('alert')).toBeNull()
+ expect(saveConnection).toHaveBeenCalledWith(
+ expect.objectContaining({ baseUrl: 'https://proxy.example/openviking' }),
+ )
+ expect(reconnect).toHaveBeenCalledTimes(1)
+ client.clear()
+})
+
+it('uses the hosted default address when the Base UI service selector changes', async () => {
+ const user = userEvent.setup()
+ const client = new QueryClient()
+ const Settings = Route.options.component as ComponentType
+ render(
+ <QueryClientProvider client={client}>
+ <Settings />
+ </QueryClientProvider>,
+ )
+ const serviceType = screen.getByRole('combobox', {
+ name: 'studio:serviceType',
})
+ const url = screen.getByLabelText<HTMLInputElement>('fields.baseUrl')
+ fireEvent.change(url, { target: { value: 'https://open-source.example/ov' } })
+ await user.click(serviceType)
+ await user.click(
+ screen.getByRole('option', { name: 'studio:providers.volcengine' }),
+ )
+ expect(url.value).toBe(
+ 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ )
+ expect(url.readOnly).toBe(true)
+ fireEvent.click(screen.getByRole('button', { name: 'studio:profiles.save' }))
+ expect(saveConnection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ serviceSelection: 'volcengine',
+ baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
+ }),
+ )
+ client.clear()
+})
+
+it('shows only the server-resolved identity next to the data key', async () => {
+ probe.mockResolvedValue({
+ admin: { state: 'skipped' },
+ data: { state: 'ok' },
+ })
+ const client = new QueryClient()
const Settings = Route.options.component as ComponentType & {
preload?: () => Promise<unknown>
}
await Settings.preload?.()
+ const content = () => (
+ <QueryClientProvider client={client}>
+ <Settings />
+ </QueryClientProvider>
+ )
+ const view = render(content())
+ expect(
+ await screen.findByText('[studio:profiles.identityPending]'),
+ ).toBeTruthy()
+ expect(screen.queryByText('[account-a/alice]')).toBeNull()
+ healthState.value = { account_id: 'server-account', user_id: 'server-user' }
+ view.rerender(content())
+ expect(await screen.findByText('[server-account/server-user]')).toBeTruthy()
+ fireEvent.change(document.getElementById('settings-user-api-key')!, {
+ target: { value: 'unverified-key' },
+ })
+ expect(screen.getByText('[studio:profiles.identityPending]')).toBeTruthy()
+ client.clear()
+})
+
+it.each([false, undefined, true])(
+ 'requires the Root key in trusted mode regardless of legacy metadata: %s',
+ async (required) => {
+ probe.mockResolvedValue({
+ admin: {
+ state: 'error',
+ statusCode: 403,
+ detail: 'Management unavailable',
+ },
+ data: { state: 'ok', detailCode: 'tenantDataAvailable' },
+ rootApiKeyRequired: required,
+ })
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ const Settings = Route.options.component as ComponentType & {
+ preload?: () => Promise<unknown>
+ }
+ await Settings.preload?.()
+ render(
+ <QueryClientProvider client={client}>
+ <Settings />
+ </QueryClientProvider>,
+ )
+ await waitFor(
+ () => expect(screen.getByText('Management unavailable')).toBeTruthy(),
+ { timeout: 5000 },
+ )
+ expect(
+ Boolean(screen.queryByText('connection.keyGuide.trusted.title')),
+ ).toBe(true)
+ client.clear()
+ },
+)
+
+it('keeps management credentials editable after authentication fails and retries the connection owner', async () => {
+ serviceState.provider = 'unknown'
+ config.url = 'https://custom.example'
+ config.selection = 'opensource'
+ probe.mockResolvedValue({
+ admin: { state: 'skipped' },
+ data: { state: 'skipped' },
+ })
+ const client = new QueryClient()
+ const Settings = Route.options.component as ComponentType
render(
<QueryClientProvider client={client}>
<Settings />
</QueryClientProvider>,
)
- await waitFor(
- () => expect(screen.getByText('Management unavailable')).toBeTruthy(),
- { timeout: 5000 },
+ expect(document.getElementById('settings-root-api-key')).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'studio:retry' }))
+ expect(reconnect).toHaveBeenCalledTimes(1)
+ client.clear()
+ serviceState.provider = 'opensource'
+ config.url = 'http://localhost:1933'
+ config.selection = 'auto'
+})
+
+it('unmounts the configuration editor and resets the active tab when switching to a hosted connection', async () => {
+ Object.assign(serviceState, {
+ provider: 'opensource',
+ ready: true,
+ role: 'root',
+ key: 'root-key',
+ })
+ probe.mockResolvedValue({ admin: { state: 'ok' }, data: { state: 'ok' } })
+ const client = new QueryClient()
+ const Settings = Route.options.component as ComponentType
+ const content = () => (
+ <QueryClientProvider client={client}>
+ <Settings />
+ </QueryClientProvider>
+ )
+ const view = render(content())
+ fireEvent.click(screen.getByRole('tab', { name: 'tabs.configuration' }))
+ expect(await screen.findByTestId('configuration-editor')).toBeTruthy()
+ serviceState.provider = 'volcengine'
+ view.rerender(content())
+ expect(screen.queryByRole('tab', { name: 'tabs.configuration' })).toBeNull()
+ expect(screen.queryByTestId('configuration-editor')).toBeNull()
+ expect(
+ screen
+ .getByRole('tab', { name: 'tabs.connection' })
+ .getAttribute('aria-selected'),
+ ).toBe('true')
+ client.clear()
+ Object.assign(serviceState, { provider: 'opensource', role: 'user', key: '' })
+})
+
+it('preserves an edited URL and user key while health fills in identity', async () => {
+ const originalIdentity = {
+ accountId: connectionState.accountId,
+ userId: connectionState.userId,
+ }
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ const Settings = Route.options.component as ComponentType
+ const content = () => (
+ <QueryClientProvider client={client}>
+ <Settings />
+ </QueryClientProvider>
)
- expect(Boolean(screen.queryByText('connection.keyGuide.trusted.title'))).toBe(
- true,
+ const view = render(content())
+ const url = screen.getByLabelText<HTMLInputElement>('fields.baseUrl')
+ const key = document.getElementById(
+ 'settings-user-api-key',
+ ) as HTMLInputElement
+ fireEvent.change(url, { target: { value: 'http://recovery.test' } })
+ fireEvent.change(key, { target: { value: 'synthetic-draft' } })
+ connectionState.accountId = 'resolved-account'
+ connectionState.userId = 'resolved-user'
+ view.rerender(content())
+ expect(url.value).toBe('http://recovery.test')
+ expect(key.value).toBe('synthetic-draft')
+ fireEvent.click(screen.getByRole('button', { name: 'studio:profiles.save' }))
+ expect(saveConnection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ baseUrl: 'http://recovery.test',
+ apiKey: 'synthetic-draft',
+ accountId: 'resolved-account',
+ userId: 'resolved-user',
+ }),
)
+ Object.assign(connectionState, originalIdentity)
client.clear()
})
diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsx
index 7489b5875..db0e8322c 100644
--- a/web-studio/src/routes/settings/route.tsx
+++ b/web-studio/src/routes/settings/route.tsx
@@ -1,5 +1,5 @@
+import { fetchServerHealth } from '#/lib/connection/health'
import * as React from 'react'
-import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import {
CircleAlertIcon,
@@ -14,7 +14,6 @@ import { useTranslation } from 'react-i18next'
import { Alert, AlertDescription, AlertTitle } from '#/components/ui/alert'
import { Button } from '#/components/ui/button'
-import { fetchServerHealth } from '#/hooks/use-server-mode'
import { Badge } from '#/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '#/components/ui/card'
import {
@@ -24,15 +23,27 @@ import {
FieldLabel,
} from '#/components/ui/field'
import { Input } from '#/components/ui/input'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '#/components/ui/select'
+import { canEditStudioConfiguration } from '#/lib/studio-permissions'
+import { resolveConfiguredServiceProvider } from '#/lib/studio-service'
+import { isValidConnectionUrl } from '#/lib/connection/profiles'
+import { CLOUD_SETUP_URL } from '#/lib/connection/onboarding'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
-import { probeStudioConnection } from '#/lib/admin'
+import { useConnectionProbe } from '#/hooks/use-connection-probe'
import type { CapabilityProbeResult } from '#/lib/admin'
-import { DEFAULT_ACCOUNT_ID, DEFAULT_USER_ID } from '#/lib/admin-options'
import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
import { cn } from '#/lib/utils'
import { localizeCapabilityDetail } from './-lib/localize-capability-probe'
import type { ConnectionDraft } from '#/hooks/use-app-connection'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '#/components/ui/tabs'
+import { ConnectionProfilesList } from './-components/connection-profiles'
import { ServerConfigurationEditor } from './-components/server-configuration'
export const Route = createFileRoute('/settings')({
@@ -41,24 +52,57 @@ export const Route = createFileRoute('/settings')({
function ConnectionSettingsRoute() {
const { t } = useTranslation('settings')
- const { identityScopeKey, isGatewayHost } = useAppConnection()
+ const {
+ identityScopeKey,
+ isGatewayHost,
+ activeProfileId,
+ connection,
+ connectionRole,
+ isConnectionRoleLoading,
+ serverMode,
+ } = useAppConnection()
+ const service = useStudioService()
+ const canConfigure =
+ service.ready &&
+ canEditStudioConfiguration({
+ serviceProvider: service.provider,
+ hasControlCredential: Boolean(connection.adminApiKey.trim()),
+ isRoleLoading: isConnectionRoleLoading,
+ role: connectionRole,
+ serverMode,
+ })
+ const [activeTab, setActiveTab] = React.useState('connection')
+ React.useEffect(() => {
+ setActiveTab('connection')
+ }, [identityScopeKey, canConfigure])
if (isGatewayHost) return <GatewayConnectionSettings />
return (
<div className="flex w-full min-w-0 flex-col gap-5">
<h1 className="text-2xl font-semibold">{t('pageTitle')}</h1>
- <Tabs defaultValue="connection" className="min-w-0 gap-5">
+ <Tabs
+ value={canConfigure ? activeTab : 'connection'}
+ onValueChange={setActiveTab}
+ className="min-w-0 gap-5"
+ >
<TabsList variant="line">
<TabsTrigger value="connection">{t('tabs.connection')}</TabsTrigger>
- <TabsTrigger value="configuration">
- {t('tabs.configuration')}
- </TabsTrigger>
+ {canConfigure ? (
+ <TabsTrigger value="configuration">
+ {t('tabs.configuration')}
+ </TabsTrigger>
+ ) : null}
</TabsList>
<TabsContent value="connection">
- <ConnectionSettingsPanel />
- </TabsContent>
- <TabsContent value="configuration" keepMounted>
- <ServerConfigurationEditor key={identityScopeKey} />
+ <div className="grid gap-5">
+ <ConnectionProfilesList />
+ <ConnectionSettingsPanel key={activeProfileId} />
+ </div>
</TabsContent>
+ {canConfigure ? (
+ <TabsContent value="configuration" keepMounted>
+ <ServerConfigurationEditor key={identityScopeKey} />
+ </TabsContent>
+ ) : null}
</Tabs>
</div>
)
@@ -241,22 +285,18 @@ function CapabilityStatus({
}
function UserApiKeyInput({
- accountId,
+ identity,
id,
onChange,
placeholder,
- userId,
value,
}: {
- accountId: string
+ identity: string
id: string
onChange: (value: string) => void
placeholder: string
- userId: string
value: string
}) {
- const identity = `${accountId || DEFAULT_ACCOUNT_ID}/${userId || DEFAULT_USER_ID}`
-
return (
<div className="flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30">
<span className="shrink-0 rounded-sm bg-muted px-2 py-1 font-mono text-xs text-muted-foreground">
@@ -276,79 +316,103 @@ function UserApiKeyInput({
}
function ConnectionSettingsPanel() {
- const { i18n, t } = useTranslation('settings')
- const { connection, saveConnection, serverMode } = useAppConnection()
+ const { i18n, t } = useTranslation(['settings', 'studio'])
+ const service = useStudioService()
+ const { connection, reconnect, saveConnection, serverMode, serverHealth } =
+ useAppConnection()
const [draft, setDraft] = React.useState<ConnectionDraft>(connection)
- const pendingDraftRef = React.useRef<ConnectionDraft | null>(null)
- const saveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)
- const saveConnectionRef = React.useRef(saveConnection)
-
- React.useEffect(() => {
- saveConnectionRef.current = saveConnection
- }, [saveConnection])
-
+ const previousConnectionRef = React.useRef({ ...connection })
+ const openSourceUrlRef = React.useRef(
+ resolveConfiguredServiceProvider(
+ connection.baseUrl,
+ connection.serviceSelection,
+ ) === 'opensource'
+ ? connection.baseUrl
+ : '',
+ )
+ const [saveError, setSaveError] = React.useState(false)
+ const canEditControlCredential =
+ resolveConfiguredServiceProvider(draft.baseUrl, draft.serviceSelection) ===
+ 'opensource'
React.useEffect(() => {
- if (!pendingDraftRef.current) {
+ const previous = previousConnectionRef.current
+ previousConnectionRef.current = { ...connection }
+ if (
+ previous.baseUrl !== connection.baseUrl ||
+ previous.serviceSelection !== connection.serviceSelection ||
+ previous.apiKey !== connection.apiKey ||
+ previous.adminApiKey !== connection.adminApiKey
+ ) {
+ if (
+ resolveConfiguredServiceProvider(
+ connection.baseUrl,
+ connection.serviceSelection,
+ ) === 'opensource'
+ ) {
+ openSourceUrlRef.current = connection.baseUrl
+ }
setDraft(connection)
+ setSaveError(false)
+ } else if (
+ previous.accountId !== connection.accountId ||
+ previous.userId !== connection.userId
+ ) {
+ // Health may fill in identity while the user edits a recovery address/key.
+ // Update untouched identity fields without replacing the in-progress form.
+ setDraft((current) => ({
+ ...current,
+ accountId:
+ current.accountId === previous.accountId
+ ? connection.accountId
+ : current.accountId,
+ userId:
+ current.userId === previous.userId
+ ? connection.userId
+ : current.userId,
+ }))
}
}, [connection])
- React.useEffect(() => {
- return () => {
- if (saveTimerRef.current) {
- clearTimeout(saveTimerRef.current)
- }
- if (pendingDraftRef.current) {
- saveConnectionRef.current(pendingDraftRef.current)
- }
- }
- }, [])
-
function updateDraft(next: Partial<ConnectionDraft>): void {
- const updated = { ...draft, ...next }
- setDraft(updated)
- pendingDraftRef.current = updated
- if (saveTimerRef.current) {
- clearTimeout(saveTimerRef.current)
+ setSaveError(false)
+ setDraft((current) => ({ ...current, ...next }))
+ }
+
+ function selectServiceType(selection: 'opensource' | 'volcengine'): void {
+ if (
+ resolveConfiguredServiceProvider(
+ draft.baseUrl,
+ draft.serviceSelection,
+ ) === 'opensource' &&
+ selection === 'volcengine'
+ ) {
+ openSourceUrlRef.current = draft.baseUrl
}
- saveTimerRef.current = setTimeout(() => {
- saveTimerRef.current = null
- const pending = pendingDraftRef.current
- pendingDraftRef.current = null
- if (pending) {
- saveConnectionRef.current(pending)
- }
- }, 350)
+ updateDraft({
+ serviceSelection: selection,
+ baseUrl:
+ selection === 'volcengine' ? CLOUD_SETUP_URL : openSourceUrlRef.current,
+ })
}
- const probeQuery = useQuery({
- enabled: Boolean(connection.baseUrl) && serverMode !== 'checking',
- placeholderData: keepPreviousData,
- queryFn: () =>
- probeStudioConnection({
- accountId: connection.accountId || DEFAULT_ACCOUNT_ID,
- adminApiKey: connection.adminApiKey,
- apiKey: connection.apiKey,
- baseUrl: connection.baseUrl,
- serverMode,
- userId: connection.userId || DEFAULT_USER_ID,
- }),
- queryKey: [
- 'studio-connection-probe',
- connection.baseUrl,
- connection.adminApiKey,
- connection.apiKey,
- connection.accountId,
- connection.userId,
- serverMode,
- ],
- retry: false,
- staleTime: 15_000,
- })
+ const resolvedIdentity =
+ draft.baseUrl === connection.baseUrl &&
+ draft.apiKey === connection.apiKey &&
+ draft.serviceSelection === connection.serviceSelection &&
+ (draft.apiKey || draft.adminApiKey === connection.adminApiKey) &&
+ typeof serverHealth?.account_id === 'string' &&
+ serverHealth.account_id &&
+ typeof serverHealth.user_id === 'string' &&
+ serverHealth.user_id
+ ? `${serverHealth.account_id}/${serverHealth.user_id}`
+ : t('studio:profiles.identityPending')
+
+ const probeQuery = useConnectionProbe()
const isDevMode = serverMode === 'dev'
const isUnsupportedAuthMode = serverMode === 'oidc' || serverMode === 'ldap'
const rootApiKey = connection.adminApiKey.trim()
- const hasControlCredential = Boolean(draft.adminApiKey.trim())
+ const hasControlCredential =
+ service.provider === 'opensource' && Boolean(draft.adminApiKey.trim())
const hasDataCredential = Boolean(draft.apiKey.trim())
const adminProbe = probeQuery.data?.admin
const dataProbe = probeQuery.data?.data
@@ -359,33 +423,35 @@ function ConnectionSettingsPanel() {
const trustedCredentialRequired =
serverMode === 'trusted' && !probeQuery.isFetching && !hasControlCredential
const keyGuide =
- serverMode === 'trusted'
- ? trustedCredentialRequired
- ? {
- primary: t('connection.keyGuide.trusted.primary'),
- secondary: t('connection.keyGuide.trusted.secondary'),
- title: t('connection.keyGuide.trusted.title'),
- }
- : null
- : !hasControlCredential && !hasDataCredential
- ? {
- primary: t('connection.keyGuide.empty.primary'),
- secondary: t('connection.keyGuide.empty.secondary'),
- title: t('connection.keyGuide.empty.title'),
- }
- : !hasControlCredential
+ service.provider !== 'opensource'
+ ? null
+ : serverMode === 'trusted'
+ ? trustedCredentialRequired
+ ? {
+ primary: t('connection.keyGuide.trusted.primary'),
+ secondary: t('connection.keyGuide.trusted.secondary'),
+ title: t('connection.keyGuide.trusted.title'),
+ }
+ : null
+ : !hasControlCredential && !hasDataCredential
? {
- primary: t('connection.keyGuide.control.primary'),
- secondary: t('connection.keyGuide.control.secondary'),
- title: t('connection.keyGuide.control.title'),
+ primary: t('connection.keyGuide.empty.primary'),
+ secondary: t('connection.keyGuide.empty.secondary'),
+ title: t('connection.keyGuide.empty.title'),
}
- : !hasDataCredential
+ : !hasControlCredential
? {
- primary: t('connection.keyGuide.data.primary'),
- secondary: t('connection.keyGuide.data.secondary'),
- title: t('connection.keyGuide.data.title'),
+ primary: t('connection.keyGuide.control.primary'),
+ secondary: t('connection.keyGuide.control.secondary'),
+ title: t('connection.keyGuide.control.title'),
}
- : null
+ : !hasDataCredential
+ ? {
+ primary: t('connection.keyGuide.data.primary'),
+ secondary: t('connection.keyGuide.data.secondary'),
+ title: t('connection.keyGuide.data.title'),
+ }
+ : null
return (
<div className="flex w-full min-w-0 flex-col gap-5">
@@ -404,6 +470,61 @@ function ConnectionSettingsPanel() {
</div>
</CardHeader>
<CardContent className="grid gap-4 px-5 py-4">
+ <Field>
+ <FieldLabel htmlFor="settings-service-type">
+ {t('studio:serviceType')}
+ </FieldLabel>
+ <FieldContent>
+ <Select
+ value={
+ draft.serviceSelection === 'auto'
+ ? resolveConfiguredServiceProvider(draft.baseUrl)
+ : draft.serviceSelection
+ }
+ onValueChange={(value) =>
+ selectServiceType(value as 'opensource' | 'volcengine')
+ }
+ >
+ <SelectTrigger
+ id="settings-service-type"
+ className="w-full bg-background"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent
+ align="start"
+ className="w-[var(--anchor-width)]"
+ >
+ <SelectItem value="opensource">
+ {t('studio:providers.opensource')}
+ </SelectItem>
+ <SelectItem value="volcengine">
+ {t('studio:providers.volcengine')}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ {t('studio:profiles.typeHint')}
+ </FieldDescription>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={service.isChecking}
+ onClick={reconnect}
+ >
+ {t('studio:retry')}
+ </Button>
+ <p className="text-sm" aria-live="polite">
+ {t(
+ `studio:providers.${service.isChecking ? 'checking' : service.provider}`,
+ )}{' '}
+ {service.version}
+ </p>
+ <FieldDescription>
+ {t(`studio:connectionSummary.${service.provider}`)}
+ </FieldDescription>
+ </FieldContent>
+ </Field>
<Field>
<FieldLabel htmlFor="settings-base-url">
{t('fields.baseUrl')}
@@ -415,6 +536,12 @@ function ConnectionSettingsPanel() {
onChange={(event) =>
updateDraft({ baseUrl: event.target.value })
}
+ readOnly={
+ resolveConfiguredServiceProvider(
+ draft.baseUrl,
+ draft.serviceSelection,
+ ) === 'volcengine'
+ }
placeholder={t('placeholders.baseUrl')}
inputMode="url"
{...PLAIN_INPUT_PROPS}
@@ -458,39 +585,40 @@ function ConnectionSettingsPanel() {
) : (
<>
<div className="grid gap-4 md:grid-cols-2">
- <Field>
- <FieldLabel htmlFor="settings-root-api-key">
- {t('fields.rootApiKey')}
- </FieldLabel>
- <FieldContent>
- <Input
- id="settings-root-api-key"
- type="password"
- value={draft.adminApiKey}
- onChange={(event) =>
- updateDraft({ adminApiKey: event.target.value })
- }
- placeholder={t('placeholders.adminApiKey')}
- {...PLAIN_INPUT_PROPS}
- />
- <FieldDescription>
- {t(
- serverMode === 'trusted'
- ? 'connection.trustedRootHint'
- : 'connection.rootHint',
- )}
- </FieldDescription>
- </FieldContent>
- </Field>
+ {canEditControlCredential ? (
+ <Field>
+ <FieldLabel htmlFor="settings-root-api-key">
+ {t('fields.rootApiKey')}
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ id="settings-root-api-key"
+ type="password"
+ value={draft.adminApiKey}
+ onChange={(event) =>
+ updateDraft({ adminApiKey: event.target.value })
+ }
+ placeholder={t('placeholders.adminApiKey')}
+ {...PLAIN_INPUT_PROPS}
+ />
+ <FieldDescription>
+ {t(
+ serverMode === 'trusted'
+ ? 'connection.trustedRootHint'
+ : 'connection.rootHint',
+ )}
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ ) : null}
<Field>
<FieldLabel htmlFor="settings-user-api-key">
{t('fields.userApiKey')}
</FieldLabel>
<FieldContent>
<UserApiKeyInput
- accountId={draft.accountId}
+ identity={resolvedIdentity}
id="settings-user-api-key"
- userId={draft.userId}
value={draft.apiKey}
onChange={(apiKey) => updateDraft({ apiKey })}
placeholder={t('placeholders.userApiKey')}
@@ -507,11 +635,13 @@ function ConnectionSettingsPanel() {
</div>
<div className="grid gap-2 md:grid-cols-2">
- <CapabilityStatus
- isLoading={probeQuery.isFetching}
- label={t('health.admin')}
- result={adminProbe}
- />
+ {service.provider === 'opensource' ? (
+ <CapabilityStatus
+ isLoading={probeQuery.isFetching}
+ label={t('health.admin')}
+ result={adminProbe}
+ />
+ ) : null}
<CapabilityStatus
isLoading={probeQuery.isFetching}
label={t('health.data')}
@@ -519,6 +649,11 @@ function ConnectionSettingsPanel() {
/>
</div>
+ {service.provider === 'volcengine' ? (
+ <p className="text-sm text-muted-foreground">
+ {t('studio:cloudManagement')}
+ </p>
+ ) : null}
{(serverMode === 'api_key' || serverMode === 'trusted') &&
keyGuide ? (
<Alert className="border-primary/25 bg-primary/[0.045]">
@@ -551,6 +686,26 @@ function ConnectionSettingsPanel() {
) : null}
</>
)}
+ {saveError && (
+ <p role="alert" className="text-sm text-destructive">
+ {t('studio:profiles.invalidUrl')}
+ </p>
+ )}
+ <div className="flex justify-end">
+ <Button
+ onClick={() => {
+ if (!isValidConnectionUrl(draft.baseUrl)) {
+ setSaveError(true)
+ return
+ }
+ saveConnection(draft)
+ reconnect()
+ }}
+ disabled={JSON.stringify(draft) === JSON.stringify(connection)}
+ >
+ {t('studio:profiles.save')}
+ </Button>
+ </div>
</CardContent>
</Card>
</div>
diff --git a/web-studio/src/routes/skills/-components/add-skill-sheet-connection.test.tsx b/web-studio/src/routes/skills/-components/add-skill-sheet-connection.test.tsx
new file mode 100644
index 000000000..a7ef20a15
--- /dev/null
+++ b/web-studio/src/routes/skills/-components/add-skill-sheet-connection.test.tsx
@@ -0,0 +1,117 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+import { ovClient } from '#/lib/ov-client'
+
+import { AddSkillSheet } from './add-skill-sheet'
+
+const { validateNewSkill, addNewSkill } = vi.hoisted(() => ({
+ validateNewSkill: vi.fn(),
+ addNewSkill: vi.fn(),
+}))
+vi.mock('../-lib/add-skill', () => ({
+ validateNewSkill,
+ addNewSkill,
+ fetchSkillTask: vi.fn(),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+afterEach(() => {
+ cleanup()
+ validateNewSkill.mockReset()
+ addNewSkill.mockReset()
+ vi.restoreAllMocks()
+})
+
+it('does not add a skill after validation resolves for an unmounted workspace', async () => {
+ let finishValidation!: (result: {
+ valid: boolean
+ warnings: []
+ errors: []
+ }) => void
+ validateNewSkill.mockReturnValue(
+ new Promise((resolve) => {
+ finishValidation = resolve
+ }),
+ )
+ const onAdded = vi.fn()
+ const props = { open: true, onOpenChange: vi.fn(), onAdded }
+ const view = render(<AddSkillSheet key="source" {...props} />)
+ const content = screen.getByRole('textbox', { name: 'add.content' })
+ fireEvent.change(content, { target: { value: '# Source skill' } })
+ fireEvent.submit(content.closest('form')!)
+ expect(validateNewSkill).toHaveBeenCalledWith('# Source skill')
+
+ // Workspace switch remounts the sheet while the old validation is pending.
+ view.rerender(<AddSkillSheet key="target" {...props} />)
+ await act(async () => {
+ finishValidation({ valid: true, warnings: [], errors: [] })
+ })
+ expect(addNewSkill).not.toHaveBeenCalled()
+ expect(onAdded).not.toHaveBeenCalled()
+})
+
+it('does not add a skill from a drawer closed during validation', async () => {
+ let finishValidation!: (result: {
+ valid: boolean
+ warnings: []
+ errors: []
+ }) => void
+ validateNewSkill.mockReturnValue(
+ new Promise((resolve) => {
+ finishValidation = resolve
+ }),
+ )
+ const props = { onOpenChange: vi.fn(), onAdded: vi.fn() }
+ const view = render(<AddSkillSheet {...props} open />)
+ const content = screen.getByRole('textbox', { name: 'add.content' })
+ fireEvent.change(content, { target: { value: '# Draft' } })
+ fireEvent.submit(content.closest('form')!)
+ view.rerender(<AddSkillSheet {...props} open={false} />)
+ await act(async () => {
+ finishValidation({ valid: true, warnings: [], errors: [] })
+ })
+ expect(addNewSkill).not.toHaveBeenCalled()
+})
+
+it('does not add a skill when the runtime connection changes before React unmounts the drawer', async () => {
+ let finishValidation!: (result: {
+ valid: boolean
+ warnings: []
+ errors: []
+ }) => void
+ validateNewSkill.mockReturnValue(
+ new Promise((resolve) => {
+ finishValidation = resolve
+ }),
+ )
+ let baseUrl = 'http://source.test'
+ vi.spyOn(ovClient, 'getOptions').mockImplementation(() => ({
+ apiKeyAuth: 'header',
+ apiKeyStorageKey: 'test',
+ baseUrl,
+ defaultTelemetry: false,
+ }))
+ vi.spyOn(ovClient, 'getConnection').mockReturnValue({
+ accountId: 'default',
+ adminApiKey: '',
+ apiKey: 'source-key',
+ identityHeaders: true,
+ userId: 'alice',
+ })
+
+ render(<AddSkillSheet open onOpenChange={vi.fn()} onAdded={vi.fn()} />)
+ const content = screen.getByRole('textbox', { name: 'add.content' })
+ fireEvent.change(content, { target: { value: '# Source skill' } })
+ fireEvent.submit(content.closest('form')!)
+
+ // The client switches synchronously; React may commit the old sheet later.
+ baseUrl = 'http://target.test'
+ await act(async () => {
+ finishValidation({ valid: true, warnings: [], errors: [] })
+ })
+ expect(addNewSkill).not.toHaveBeenCalled()
+})
diff --git a/web-studio/src/routes/skills/-components/add-skill-sheet.test.tsx b/web-studio/src/routes/skills/-components/add-skill-sheet.test.tsx
new file mode 100644
index 000000000..7fbcd7b0e
--- /dev/null
+++ b/web-studio/src/routes/skills/-components/add-skill-sheet.test.tsx
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+
+import * as React from 'react'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { AddSkillSheet } from './add-skill-sheet'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+afterEach(cleanup)
+
+it('clears a previous draft whenever the drawer is reopened', () => {
+ const props = { onOpenChange: vi.fn(), onAdded: vi.fn() }
+ const { rerender } = render(<AddSkillSheet {...props} open />)
+ fireEvent.change(screen.getByRole('textbox', { name: 'add.content' }), {
+ target: { value: 'old skill' },
+ })
+ rerender(<AddSkillSheet {...props} open={false} />)
+ rerender(<AddSkillSheet {...props} open />)
+ expect(
+ screen.getByRole('textbox', {
+ name: 'add.content',
+ }).value,
+ ).toBe('')
+})
+
+it('removes an uploaded file and allows choosing another', async () => {
+ render(<AddSkillSheet open onOpenChange={vi.fn()} onAdded={vi.fn()} />)
+ const input = document.querySelector<HTMLInputElement>('input[type=file]')!
+ const first = new File(['first'], 'first.md', { type: 'text/markdown' })
+ first.text = vi.fn().mockResolvedValue('first')
+ await act(async () => fireEvent.change(input, { target: { files: [first] } }))
+ expect(
+ screen.getByRole('textbox', {
+ name: 'add.content',
+ }).value,
+ ).toBe('first')
+ fireEvent.click(screen.getByRole('button', { name: /add.removeFile/ }))
+ expect(
+ screen.getByRole('textbox', {
+ name: 'add.content',
+ }).value,
+ ).toBe('')
+ const second = new File(['second'], 'second.md', { type: 'text/markdown' })
+ second.text = vi.fn().mockResolvedValue('second')
+ await act(async () =>
+ fireEvent.change(input, { target: { files: [second] } }),
+ )
+ expect(
+ screen.getByRole('textbox', {
+ name: 'add.content',
+ }).value,
+ ).toBe('second')
+})
diff --git a/web-studio/src/routes/skills/-components/add-skill-sheet.tsx b/web-studio/src/routes/skills/-components/add-skill-sheet.tsx
new file mode 100644
index 000000000..f32b017ef
--- /dev/null
+++ b/web-studio/src/routes/skills/-components/add-skill-sheet.tsx
@@ -0,0 +1,373 @@
+import * as React from 'react'
+import { LoaderCircleIcon, UploadIcon, XIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import { Button } from '#/components/ui/button'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '#/components/ui/sheet'
+import { Textarea } from '#/components/ui/textarea'
+import { ovClient } from '#/lib/ov-client'
+
+import {
+ addNewSkill,
+ fetchSkillTask,
+ validateNewSkill,
+} from '../-lib/add-skill'
+import type { SkillScope } from './skill-scope-tabs'
+
+type Phase =
+ | 'idle'
+ | 'validating'
+ | 'adding'
+ | 'processing'
+ | 'completed'
+ | 'failed'
+
+const SCOPES: SkillScope[] = ['user', 'agent']
+
+function currentConnectionIdentity(): string {
+ const options = ovClient.getOptions()
+ const connection = ovClient.getConnection()
+ return JSON.stringify([
+ options.baseUrl,
+ options.apiKeyAuth,
+ connection.accountId,
+ connection.userId,
+ connection.apiKey,
+ connection.adminApiKey,
+ connection.identityHeaders,
+ ])
+}
+
+export function AddSkillSheet({
+ open,
+ onOpenChange,
+ onAdded,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onAdded: (scope: SkillScope) => void
+}) {
+ const { t } = useTranslation('skillsPage')
+ const [content, setContent] = React.useState('')
+ const [fileName, setFileName] = React.useState('')
+ const [scope, setScope] = React.useState<SkillScope>('user')
+ const [phase, setPhase] = React.useState<Phase>('idle')
+ const [taskId, setTaskId] = React.useState('')
+ const [errors, setErrors] = React.useState<string[]>([])
+ const [warnings, setWarnings] = React.useState<string[]>([])
+ const previousOpen = React.useRef(false)
+ const fileInputRef = React.useRef<HTMLInputElement>(null)
+ const operationGeneration = React.useRef(0)
+
+ React.useLayoutEffect(() => {
+ if (!open) operationGeneration.current += 1
+ return () => {
+ // A closed drawer or a workspace change must invalidate pending writes.
+ operationGeneration.current += 1
+ }
+ }, [open])
+
+ const reset = React.useCallback(() => {
+ setContent('')
+ setFileName('')
+ setScope('user')
+ setPhase('idle')
+ setTaskId('')
+ setErrors([])
+ setWarnings([])
+ if (fileInputRef.current) fileInputRef.current.value = ''
+ }, [])
+
+ React.useEffect(() => {
+ if (open && !previousOpen.current) reset()
+ previousOpen.current = open
+ }, [open, reset])
+
+ function removeFile() {
+ setContent('')
+ setFileName('')
+ setPhase('idle')
+ setTaskId('')
+ setErrors([])
+ setWarnings([])
+ if (fileInputRef.current) fileInputRef.current.value = ''
+ }
+
+ React.useEffect(() => {
+ if (phase !== 'processing' || !taskId) return
+ let cancelled = false
+ let timer: ReturnType<typeof setTimeout>
+ async function poll() {
+ try {
+ const task = await fetchSkillTask(taskId)
+ if (cancelled) return
+ if (task.status === 'completed') {
+ setPhase('completed')
+ onAdded(scope)
+ } else if (task.status === 'failed' || task.status === 'cancelled') {
+ setErrors([
+ typeof task.error === 'string' && task.error
+ ? task.error
+ : t('add.processingFailed'),
+ ])
+ setPhase('failed')
+ } else {
+ timer = setTimeout(() => void poll(), 2000)
+ }
+ } catch (error) {
+ if (cancelled) return
+ setErrors([error instanceof Error ? error.message : String(error)])
+ setPhase('failed')
+ }
+ }
+ void poll()
+ return () => {
+ cancelled = true
+ clearTimeout(timer)
+ }
+ }, [phase, taskId, onAdded, scope, t])
+
+ async function submit(event: React.FormEvent<HTMLFormElement>) {
+ event.preventDefault()
+ if (
+ !content.trim() ||
+ phase === 'validating' ||
+ phase === 'adding' ||
+ phase === 'processing'
+ )
+ return
+ setErrors([])
+ setWarnings([])
+ setPhase('validating')
+ const generation = operationGeneration.current
+ const sourceConnectionIdentity = currentConnectionIdentity()
+ try {
+ const validation = await validateNewSkill(content)
+ if (
+ generation !== operationGeneration.current ||
+ sourceConnectionIdentity !== currentConnectionIdentity()
+ )
+ return
+ setWarnings(
+ validation.warnings.map((issue) => issue.message || issue.rule || ''),
+ )
+ if (!validation.valid) {
+ setErrors(
+ validation.errors.map((issue) => issue.message || issue.rule || ''),
+ )
+ setPhase('idle')
+ return
+ }
+ setPhase('adding')
+ const result = await addNewSkill(content, scope)
+ if (generation !== operationGeneration.current) return
+ onAdded(scope)
+ if (result.task_id) {
+ setTaskId(result.task_id)
+ setPhase('processing')
+ } else {
+ setPhase('completed')
+ }
+ } catch (error) {
+ if (generation !== operationGeneration.current) return
+ setErrors([error instanceof Error ? error.message : String(error)])
+ setPhase('failed')
+ }
+ }
+
+ async function loadFile(event: React.ChangeEvent<HTMLInputElement>) {
+ const file = event.target.files?.[0]
+ if (!file) return
+ try {
+ setContent(await file.text())
+ setFileName(file.name)
+ setErrors([])
+ setWarnings([])
+ setPhase('idle')
+ } catch (error) {
+ setErrors([error instanceof Error ? error.message : String(error)])
+ }
+ event.target.value = ''
+ }
+
+ const busy =
+ phase === 'validating' || phase === 'adding' || phase === 'processing'
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent className="gap-0 data-[side=right]:sm:max-w-xl">
+ <SheetHeader className="border-b px-6 py-5">
+ <SheetTitle className="text-lg">{t('add.title')}</SheetTitle>
+ <SheetDescription>{t('add.description')}</SheetDescription>
+ </SheetHeader>
+ <form
+ onSubmit={(event) => void submit(event)}
+ className="flex min-h-0 flex-1 flex-col"
+ >
+ <div className="min-h-0 flex-1 space-y-6 overflow-y-auto px-6 py-5">
+ <fieldset className="grid gap-2" disabled={busy}>
+ <legend className="mb-2 text-sm font-medium">
+ {t('add.scope')}
+ </legend>
+ {SCOPES.map((value) => (
+ <label
+ key={value}
+ className="flex cursor-pointer items-center gap-3 rounded-lg border border-border px-4 py-3 has-checked:border-foreground has-checked:bg-muted/30"
+ >
+ <input
+ type="radio"
+ name="skill-scope"
+ value={value}
+ checked={scope === value}
+ onChange={() => setScope(value)}
+ className="accent-foreground"
+ />
+ <span className="grid gap-0.5">
+ <span className="font-medium">{t(`scopes.${value}`)}</span>
+ <span className="text-xs text-muted-foreground">
+ {t(`add.scopeDescription.${value}`)}
+ </span>
+ </span>
+ </label>
+ ))}
+ </fieldset>
+
+ <div className="grid gap-2">
+ <label htmlFor="skill-content" className="text-sm font-medium">
+ {t('add.content')}
+ </label>
+ <p className="text-xs text-muted-foreground">
+ {t('add.contentHint')}
+ </p>
+ <Textarea
+ id="skill-content"
+ value={content}
+ onChange={(event) => {
+ setContent(event.target.value)
+ setFileName('')
+ setErrors([])
+ setWarnings([])
+ setPhase('idle')
+ }}
+ placeholder={t('add.placeholder')}
+ className="min-h-64 resize-y font-mono text-xs leading-5"
+ spellCheck={false}
+ disabled={busy}
+ />
+ <div className="mt-2 flex min-w-0 flex-wrap items-center gap-2">
+ <label className="inline-flex w-fit cursor-pointer items-center gap-2 rounded-md border px-3 py-2 text-sm hover:bg-muted/50 focus-within:ring-2 focus-within:ring-ring">
+ <UploadIcon className="size-4" />
+ {t('add.upload')}
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".md,text/markdown"
+ className="sr-only"
+ onChange={(event) => void loadFile(event)}
+ disabled={busy}
+ />
+ </label>
+ {fileName ? (
+ <div className="flex min-w-0 items-center gap-1 rounded-md bg-muted px-2 py-1 text-sm">
+ <span className="max-w-56 truncate" title={fileName}>
+ {fileName}
+ </span>
+ <button
+ type="button"
+ onClick={removeFile}
+ disabled={busy}
+ aria-label={t('add.removeFile', { fileName })}
+ className="rounded p-1 hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <XIcon className="size-4" />
+ </button>
+ </div>
+ ) : null}
+ </div>
+ </div>
+
+ {warnings.length > 0 ? (
+ <div
+ role="status"
+ className="rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 text-sm"
+ >
+ <p className="font-medium">{t('add.warnings')}</p>
+ <ul className="mt-1 list-inside list-disc text-muted-foreground">
+ {warnings.map((warning, index) => (
+ <li key={index}>{warning}</li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ {errors.length > 0 ? (
+ <div
+ role="alert"
+ className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive"
+ >
+ <p className="font-medium">
+ {t(taskId ? 'add.processingFailed' : 'add.failed')}
+ </p>
+ <ul className="mt-1 list-inside list-disc">
+ {errors.map((error, index) => (
+ <li key={index}>{error}</li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ {phase === 'processing' || phase === 'completed' ? (
+ <div
+ role="status"
+ className="rounded-lg border bg-muted/30 p-3 text-sm"
+ >
+ <p className="font-medium">
+ {t(
+ phase === 'completed' ? 'add.completed' : 'add.processing',
+ )}
+ </p>
+ {taskId ? (
+ <p className="mt-1 break-all text-xs text-muted-foreground">
+ {t('add.taskId')}: {taskId}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ <SheetFooter className="border-t px-6 py-4 sm:flex-row sm:justify-end">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ >
+ {t('add.close')}
+ </Button>
+ {phase === 'completed' ? (
+ <Button type="button" onClick={reset}>
+ {t('add.another')}
+ </Button>
+ ) : (
+ <Button type="submit" disabled={!content.trim() || busy}>
+ {busy ? (
+ <LoaderCircleIcon className="size-4 animate-spin" />
+ ) : null}
+ {t(
+ phase === 'validating'
+ ? 'add.validating'
+ : phase === 'adding'
+ ? 'add.adding'
+ : 'add.submit',
+ )}
+ </Button>
+ )}
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/web-studio/src/routes/skills/-lib/add-skill.test.ts b/web-studio/src/routes/skills/-lib/add-skill.test.ts
new file mode 100644
index 000000000..d1b246347
--- /dev/null
+++ b/web-studio/src/routes/skills/-lib/add-skill.test.ts
@@ -0,0 +1,47 @@
+import { beforeEach, expect, it, vi } from 'vitest'
+import { ovClient } from '#/lib/ov-client'
+import { addNewSkill, fetchSkillTask, validateNewSkill } from './add-skill'
+
+vi.mock('#/lib/ov-client', () => ({
+ ovClient: { client: { post: vi.fn(), get: vi.fn() } },
+ getOvResult: async (request: Promise<{ data: { result: unknown } }>) =>
+ (await request).data.result,
+}))
+
+beforeEach(() => {
+ vi.resetAllMocks()
+})
+
+it('validates content before adding and sends explicit private or shared targets', async () => {
+ vi.mocked(ovClient.client.post).mockResolvedValue({
+ data: { result: { valid: true, errors: [], warnings: [] } },
+ } as never)
+ await validateNewSkill('---\nname: example\n---')
+ expect(ovClient.client.post).toHaveBeenCalledWith({
+ url: '/api/v1/skills/validate',
+ body: { data: '---\nname: example\n---' },
+ })
+
+ await addNewSkill('private content', 'user')
+ await addNewSkill('shared content', 'agent')
+ expect(ovClient.client.post).toHaveBeenNthCalledWith(2, {
+ url: '/api/v1/skills',
+ body: { data: 'private content', target_uri: 'viking://~/skills' },
+ })
+ expect(ovClient.client.post).toHaveBeenNthCalledWith(3, {
+ url: '/api/v1/skills',
+ body: { data: 'shared content', target_uri: 'viking://agent/skills' },
+ })
+})
+
+it('reads the submitted background task by its ID', async () => {
+ vi.mocked(ovClient.client.get).mockResolvedValue({
+ data: { result: { task_id: 'task-1', status: 'completed' } },
+ } as never)
+ await expect(fetchSkillTask('task-1')).resolves.toMatchObject({
+ status: 'completed',
+ })
+ expect(ovClient.client.get).toHaveBeenCalledWith({
+ url: '/api/v1/tasks/task-1',
+ })
+})
diff --git a/web-studio/src/routes/skills/-lib/add-skill.ts b/web-studio/src/routes/skills/-lib/add-skill.ts
new file mode 100644
index 000000000..1536dcc12
--- /dev/null
+++ b/web-studio/src/routes/skills/-lib/add-skill.ts
@@ -0,0 +1,56 @@
+import { getOvResult, ovClient } from '#/lib/ov-client'
+import type { SkillScope } from '../-components/skill-scope-tabs'
+
+type ValidationIssue = { message?: string; rule?: string }
+
+export type SkillValidation = {
+ valid: boolean
+ name?: string
+ errors: ValidationIssue[]
+ warnings: ValidationIssue[]
+}
+
+export type SkillTask = {
+ task_id: string
+ status:
+ | 'pending'
+ | 'running'
+ | 'cancelling'
+ | 'completed'
+ | 'failed'
+ | 'cancelled'
+ error?: string | null
+}
+
+export async function validateNewSkill(data: string): Promise<SkillValidation> {
+ return getOvResult<SkillValidation>(
+ ovClient.client.post({
+ url: '/api/v1/skills/validate',
+ body: { data },
+ }),
+ )
+}
+
+export async function addNewSkill(
+ data: string,
+ scope: SkillScope,
+): Promise<{ task_id?: string }> {
+ return getOvResult<{ task_id?: string }>(
+ ovClient.client.post({
+ url: '/api/v1/skills',
+ body: {
+ data,
+ target_uri:
+ scope === 'agent' ? 'viking://agent/skills' : 'viking://~/skills',
+ },
+ }),
+ )
+}
+
+export async function fetchSkillTask(taskId: string): Promise<SkillTask> {
+ return getOvResult<SkillTask>(
+ ovClient.client.get({
+ url: `/api/v1/tasks/${encodeURIComponent(taskId)}`,
+ }),
+ )
+}
diff --git a/web-studio/src/routes/skills/route.tsx b/web-studio/src/routes/skills/route.tsx
index 2d9e58574..8a8a2065a 100644
--- a/web-studio/src/routes/skills/route.tsx
+++ b/web-studio/src/routes/skills/route.tsx
@@ -6,6 +6,7 @@ import {
ExternalLinkIcon,
FileCode2Icon,
LoaderCircleIcon,
+ PlusIcon,
RefreshCwIcon,
SparklesIcon,
UserRoundIcon,
@@ -36,6 +37,7 @@ import {
SkillScopeTabs,
getSkillsForScope,
} from './-components/skill-scope-tabs'
+import { AddSkillSheet } from './-components/add-skill-sheet'
import type { SkillScope } from './-components/skill-scope-tabs'
export const Route = createFileRoute('/skills')({
@@ -187,6 +189,7 @@ function SkillsRoute() {
const [selectedSkill, setSelectedSkill] = React.useState<SkillItem | null>(
null,
)
+ const [addOpen, setAddOpen] = React.useState(false)
const skillsQuery = useQuery({
queryFn: fetchSkills,
queryKey: ['skills', identityScopeKey],
@@ -194,6 +197,13 @@ function SkillsRoute() {
})
const skills = skillsQuery.data ?? []
const [activeScope, setActiveScope] = React.useState<SkillScope>('user')
+ const onSkillAdded = React.useCallback(
+ (scope: SkillScope) => {
+ setActiveScope(scope)
+ void skillsQuery.refetch()
+ },
+ [skillsQuery.refetch],
+ )
const visibleSkills = React.useMemo(
() => getSkillsForScope(skills, activeScope),
[activeScope, skills],
@@ -218,18 +228,24 @@ function SkillsRoute() {
{t('description')}
</p>
</div>
- <Button
- type="button"
- variant="outline"
- size="sm"
- disabled={skillsQuery.isFetching}
- onClick={() => void skillsQuery.refetch()}
- >
- <RefreshCwIcon
- className={skillsQuery.isFetching ? 'animate-spin' : undefined}
- />
- {t('refresh')}
- </Button>
+ <div className="flex items-center gap-2">
+ <Button type="button" size="sm" onClick={() => setAddOpen(true)}>
+ <PlusIcon />
+ {t('add.title')}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={skillsQuery.isFetching}
+ onClick={() => void skillsQuery.refetch()}
+ >
+ <RefreshCwIcon
+ className={skillsQuery.isFetching ? 'animate-spin' : undefined}
+ />
+ {t('refresh')}
+ </Button>
+ </div>
</header>
{skillsQuery.isLoading ? (
@@ -273,6 +289,10 @@ function SkillsRoute() {
{t('emptyDescription')}
</p>
</div>
+ <Button type="button" size="sm" onClick={() => setAddOpen(true)}>
+ <PlusIcon />
+ {t('add.title')}
+ </Button>
</Card>
) : (
<div className="grid gap-4">
@@ -365,6 +385,13 @@ function SkillsRoute() {
</div>
)}
+ <AddSkillSheet
+ key={identityScopeKey}
+ open={addOpen}
+ onOpenChange={setAddOpen}
+ onAdded={onSkillAdded}
+ />
+
<Sheet
open={Boolean(selectedSkill)}
onOpenChange={(open) => {
diff --git a/web-studio/src/routes/tasks/route.test.tsx b/web-studio/src/routes/tasks/route.test.tsx
index a0abcc1c5..88f6ebd4d 100644
--- a/web-studio/src/routes/tasks/route.test.tsx
+++ b/web-studio/src/routes/tasks/route.test.tsx
@@ -26,6 +26,7 @@ import {
} from 'vitest'
import { toast } from 'sonner'
+import { postResources } from '#/gen/ov-client'
import { commitSession } from '#/lib/sessions/api'
import { Route } from './route'
import type { TaskRecord } from './-lib/task-record'
@@ -306,21 +307,74 @@ describe('session commit re-trigger feedback', () => {
})
})
-
it('groups processing and total time without inventing legacy timing', async () => {
records = [
- { task_id: 'measured', status: 'completed', task_type: 'add_resource', created_at: 100, updated_at: 700, processing_seconds: 61 },
- { task_id: 'pending', status: 'pending', task_type: 'add_resource', created_at: 100, processing_seconds: 0 },
- { task_id: 'legacy', status: 'completed', task_type: 'add_resource', created_at: 100, updated_at: 700 },
+ {
+ task_id: 'measured',
+ status: 'completed',
+ task_type: 'add_resource',
+ created_at: 100,
+ updated_at: 700,
+ processing_seconds: 61,
+ },
+ {
+ task_id: 'pending',
+ status: 'pending',
+ task_type: 'add_resource',
+ created_at: 100,
+ processing_seconds: 0,
+ },
+ {
+ task_id: 'legacy',
+ status: 'completed',
+ task_type: 'add_resource',
+ created_at: 100,
+ updated_at: 700,
+ },
]
await renderPage()
- const measured = await screen.findByRole('row', { name: 'View details for task measured' })
+ const measured = await screen.findByRole('row', {
+ name: 'View details for task measured',
+ })
expect(within(measured).getByText('1m 1s')).toBeDefined()
expect(within(measured).queryByText(/Waiting Time/)).toBeNull()
expect(screen.getByRole('columnheader', { name: 'Duration' })).toBeDefined()
- expect(within(measured).getByText('1m 1s').closest('td')).toBe(within(measured).getByText('10m').closest('td'))
+ expect(within(measured).getByText('1m 1s').closest('td')).toBe(
+ within(measured).getByText('10m').closest('td'),
+ )
expect(within(measured).getByText('10m')).toBeDefined()
- expect(within(screen.getByRole('row', { name: 'View details for task pending' })).getByText('Not started')).toBeDefined()
- const legacy = screen.getByRole('row', { name: 'View details for task legacy' })
+ expect(
+ within(
+ screen.getByRole('row', { name: 'View details for task pending' }),
+ ).getByText('Not started'),
+ ).toBeDefined()
+ const legacy = screen.getByRole('row', {
+ name: 'View details for task legacy',
+ })
expect(within(legacy).getByText('Not recorded')).toBeDefined()
})
+
+it('retries a URL import using the resource API path field', async () => {
+ records = [
+ {
+ task_id: 'failed-import',
+ task_type: 'add_resource',
+ resource_id: 'https://example.com/article',
+ status: 'failed',
+ created_at: 100,
+ },
+ ]
+ vi.mocked(postResources).mockResolvedValue(
+ {} as Awaited<ReturnType<typeof postResources>>,
+ )
+ const user = await renderPage()
+ await user.click(await screen.findByTitle('Re-trigger Task'))
+ await waitFor(() =>
+ expect(postResources).toHaveBeenCalledWith({
+ body: {
+ path: 'https://example.com/article',
+ reason: 'Re-queued task: failed-import',
+ },
+ }),
+ )
+})
diff --git a/web-studio/src/routes/tasks/route.tsx b/web-studio/src/routes/tasks/route.tsx
index 974f0712f..58e3a4567 100644
--- a/web-studio/src/routes/tasks/route.tsx
+++ b/web-studio/src/routes/tasks/route.tsx
@@ -43,7 +43,7 @@ import {
TableRow,
} from '#/components/ui/table'
import { useAppConnection } from '#/hooks/use-app-connection'
-import { ovClient } from '#/lib/ov-client'
+import { getOvResult, ovClient } from '#/lib/ov-client'
import { postResources } from '#/gen/ov-client'
import { commitSession } from '#/lib/sessions/api'
import { cn } from '#/lib/utils'
@@ -165,12 +165,14 @@ function TasksRoute() {
resourceUri.startsWith('http://') ||
resourceUri.startsWith('https://')
) {
- const res = await postResources({
- body: {
- url: resourceUri,
- reason: `Re-queued task: ${task.task_id}`,
- } as any,
- })
+ const res = await getOvResult(
+ postResources({
+ body: {
+ path: resourceUri,
+ reason: `Re-queued task: ${task.task_id}`,
+ },
+ }),
+ )
return { res, task }
}
@@ -838,7 +840,9 @@ function TasksRoute() {
<TableHead>{t('table.resource')}</TableHead>
<TableHead>{t('labels.queuePipeline')}</TableHead>
<TableHead>{t('table.status')}</TableHead>
- <TableHead title={t('labels.processingDurationHelp')}>{t('labels.timing')}</TableHead>
+ <TableHead title={t('labels.processingDurationHelp')}>
+ {t('labels.timing')}
+ </TableHead>
<TableHead className="text-right">
{t('table.createdAt')}
</TableHead>
@@ -907,12 +911,19 @@ function TasksRoute() {
<TableCell>{renderStatus(task)}</TableCell>
<TableCell className="whitespace-nowrap text-xs tabular-nums">
<div>
- {t('labels.processingDuration')}: <span>{task.status === 'pending' && (task.processing_seconds == null || task.processing_seconds === 0)
- ? t('labels.processingNotStarted')
- : formatTaskProcessingDuration(task) ?? t('labels.timingUnavailable')}</span>
+ {t('labels.processingDuration')}:{' '}
+ <span>
+ {task.status === 'pending' &&
+ (task.processing_seconds == null ||
+ task.processing_seconds === 0)
+ ? t('labels.processingNotStarted')
+ : (formatTaskProcessingDuration(task) ??
+ t('labels.timingUnavailable'))}
+ </span>
</div>
<div className="text-muted-foreground">
- {t('labels.totalDuration')}: <span>{formatTaskDuration(task)}</span>
+ {t('labels.totalDuration')}:{' '}
+ <span>{formatTaskDuration(task)}</span>
</div>
</TableCell>
<TableCell className="whitespace-nowrap text-right text-muted-foreground">
diff --git a/web-studio/src/routes/vikingbot/-api.ts b/web-studio/src/routes/vikingbot/-api.ts
index 8196574b1..67dc3f723 100644
--- a/web-studio/src/routes/vikingbot/-api.ts
+++ b/web-studio/src/routes/vikingbot/-api.ts
@@ -1,5 +1,5 @@
import { getOvResult, ovClient } from '#/lib/ov-client'
-import type { ServerMode } from '#/hooks/use-server-mode'
+import type { ServerMode } from '#/lib/connection/health'
export type Connection = {
id: string
diff --git a/web-studio/src/routes/watches/route.test.tsx b/web-studio/src/routes/watches/route.test.tsx
index 33636cc2c..e7d9579e1 100644
--- a/web-studio/src/routes/watches/route.test.tsx
+++ b/web-studio/src/routes/watches/route.test.tsx
@@ -38,6 +38,11 @@ vi.mock('react-i18next', () => ({
}),
}))
+const service = vi.hoisted(() => ({ provider: 'opensource' }))
+vi.mock('#/hooks/use-studio-service', () => ({
+ useStudioService: () => service,
+}))
+
vi.mock('sonner', () => ({ toast: toastMocks }))
vi.mock('#/hooks/use-app-connection', () => ({
@@ -79,7 +84,8 @@ vi.mock('./-components/edit-watch-dialog', () => ({
}))
vi.mock('./-components/watch-history-sheet', () => ({
- WatchHistorySheet: () => null,
+ WatchHistorySheet: ({ watch }: { watch: WatchTask | null }) =>
+ watch ? <div data-testid="watch-history">{watch.toUri}</div> : null,
}))
vi.mock('./-lib/api', () => apiMocks)
@@ -113,6 +119,7 @@ function renderPage() {
}
beforeEach(() => {
+ service.provider = 'opensource'
apiMocks.fetchWatches.mockResolvedValue([watch])
apiMocks.fetchWatchProcessingHistory.mockResolvedValue([
{ status: 'running', task_id: 'processing-1' },
@@ -128,6 +135,24 @@ afterEach(() => {
})
describe('WatchManagementPage', () => {
+ it('does not offer hosted write actions when only list access is verified', async () => {
+ service.provider = 'volcengine'
+ renderPage()
+ await screen.findByText(watch.path)
+ for (const name of [
+ 'actions.edit',
+ 'actions.trigger',
+ 'actions.more',
+ 'add',
+ ]) {
+ expect(screen.queryByRole('button', { name })).toBeNull()
+ }
+ expect(screen.queryByRole('switch')).toBeNull()
+ expect(screen.getByText('columns.actions')).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'actions.history' }))
+ expect(screen.getByTestId('watch-history').textContent).toBe(watch.toUri)
+ expect(apiMocks.triggerWatch).not.toHaveBeenCalled()
+ })
it('shows edit as a direct row action', async () => {
renderPage()
diff --git a/web-studio/src/routes/watches/route.tsx b/web-studio/src/routes/watches/route.tsx
index 7f489b191..e031a62b8 100644
--- a/web-studio/src/routes/watches/route.tsx
+++ b/web-studio/src/routes/watches/route.tsx
@@ -48,6 +48,7 @@ import {
TableRow,
} from '#/components/ui/table'
import { Switch } from '#/components/ui/switch'
+import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
import {
AddResourceForm,
@@ -102,8 +103,10 @@ function WatchesRoute() {
}
export function WatchManagementPage() {
- const { i18n, t } = useTranslation('watchesPage')
+ const { i18n, t } = useTranslation(['watchesPage', 'studio'])
const { identityScopeKey } = useAppConnection()
+ const { provider } = useStudioService()
+ const readOnly = provider !== 'opensource'
const queryClient = useQueryClient()
const [addOpen, setAddOpen] = React.useState(false)
const [isCreatingWatch, setIsCreatingWatch] = React.useState(false)
@@ -346,7 +349,7 @@ export function WatchManagementPage() {
{t('title')}
</h1>
<p className="max-w-3xl text-sm leading-6 text-muted-foreground">
- {t('description')}
+ {t(readOnly ? 'studio:watchesReadDescription' : 'description')}
</p>
</div>
<div className="flex items-center gap-2">
@@ -362,15 +365,17 @@ export function WatchManagementPage() {
/>
{t('refresh')}
</Button>
- <Button
- type="button"
- size="sm"
- disabled={isCreatingWatch}
- onClick={() => setAddOpen(true)}
- >
- <PlusIcon />
- {t(isCreatingWatch ? 'adding' : 'add')}
- </Button>
+ {!readOnly ? (
+ <Button
+ type="button"
+ size="sm"
+ disabled={isCreatingWatch}
+ onClick={() => setAddOpen(true)}
+ >
+ <PlusIcon />
+ {t(isCreatingWatch ? 'adding' : 'add')}
+ </Button>
+ ) : null}
</div>
</header>
@@ -406,7 +411,7 @@ export function WatchManagementPage() {
<PageState icon={<Clock3Icon />}>
<span>{t('empty')}</span>
<span className="text-xs text-muted-foreground">
- {t('emptyDescription')}
+ {t(readOnly ? 'studio:watchesReadEmpty' : 'emptyDescription')}
</span>
</PageState>
) : (
@@ -458,22 +463,24 @@ export function WatchManagementPage() {
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
- <Switch
- size="sm"
- checked={watch.isActive}
- disabled={updateMutation.isPending}
- aria-label={t(
- watch.isActive
- ? 'actions.disable'
- : 'actions.enable',
- )}
- onCheckedChange={(checked) =>
- updateMutation.mutate({
- input: { isActive: checked },
- taskId: watch.taskId,
- })
- }
- />
+ {!readOnly ? (
+ <Switch
+ size="sm"
+ checked={watch.isActive}
+ disabled={updateMutation.isPending}
+ aria-label={t(
+ watch.isActive
+ ? 'actions.disable'
+ : 'actions.enable',
+ )}
+ onCheckedChange={(checked) =>
+ updateMutation.mutate({
+ input: { isActive: checked },
+ taskId: watch.taskId,
+ })
+ }
+ />
+ ) : null}
<span className="text-xs text-muted-foreground">
{t(
watch.isActive
@@ -492,71 +499,82 @@ export function WatchManagementPage() {
<TableCell className="text-xs text-muted-foreground">
{formatTime(watch.nextExecutionTime)}
</TableCell>
- <TableCell className="whitespace-nowrap">
- <div className="flex flex-wrap justify-end gap-1">
- <ActionButton
- label={t(
- isSyncing ? 'actions.syncing' : 'actions.trigger',
- )}
- disabled={
- !watch.isActive ||
- triggerMutation.isPending ||
- pendingSync !== null
- }
- onClick={() =>
- triggerMutation.mutate({
- baselineExecutionTime: watch.lastExecutionTime,
- taskId: watch.taskId,
- toUri: watch.toUri,
- })
- }
- >
- <RotateCwIcon
- className={isSyncing ? 'animate-spin' : undefined}
- />
- </ActionButton>
- <ActionButton
- label={t('actions.edit')}
- disabled={updateMutation.isPending}
- onClick={() => setEditingWatch(watch)}
- >
- <PencilIcon />
- </ActionButton>
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- type="button"
- size="sm"
- variant="ghost"
- className="h-8 px-2 text-xs"
- aria-label={t('actions.more')}
- title={t('actions.more')}
- />
+ {!readOnly ? (
+ <TableCell className="whitespace-nowrap">
+ <div className="flex flex-wrap justify-end gap-1">
+ <ActionButton
+ label={t(
+ isSyncing ? 'actions.syncing' : 'actions.trigger',
+ )}
+ disabled={
+ !watch.isActive ||
+ triggerMutation.isPending ||
+ pendingSync !== null
+ }
+ onClick={() =>
+ triggerMutation.mutate({
+ baselineExecutionTime: watch.lastExecutionTime,
+ taskId: watch.taskId,
+ toUri: watch.toUri,
+ })
}
>
- <EllipsisIcon />
- <span>{t('actions.more')}</span>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() => setHistoryWatch(watch)}
- >
- <HistoryIcon />
- {t('actions.history')}
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="destructive"
- disabled={deleteMutation.isPending}
- onClick={() => setDeletingWatch(watch)}
+ <RotateCwIcon
+ className={isSyncing ? 'animate-spin' : undefined}
+ />
+ </ActionButton>
+ <ActionButton
+ label={t('actions.edit')}
+ disabled={updateMutation.isPending}
+ onClick={() => setEditingWatch(watch)}
+ >
+ <PencilIcon />
+ </ActionButton>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="h-8 px-2 text-xs"
+ aria-label={t('actions.more')}
+ title={t('actions.more')}
+ />
+ }
>
- <Trash2Icon />
- {t('actions.delete')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </TableCell>
+ <EllipsisIcon />
+ <span>{t('actions.more')}</span>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => setHistoryWatch(watch)}
+ >
+ <HistoryIcon />
+ {t('actions.history')}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ disabled={deleteMutation.isPending}
+ onClick={() => setDeletingWatch(watch)}
+ >
+ <Trash2Icon />
+ {t('actions.delete')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </TableCell>
+ ) : (
+ <TableCell className="text-right">
+ <ActionButton
+ label={t('actions.history')}
+ onClick={() => setHistoryWatch(watch)}
+ >
+ <HistoryIcon />
+ </ActionButton>
+ </TableCell>
+ )}
</TableRow>
)
})}
@@ -631,11 +649,11 @@ export function WatchManagementPage() {
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogCancel disabled={deleteMutation.isPending}>
+ <AlertDialogCancel disabled={readOnly || deleteMutation.isPending}>
{t('cancel')}
</AlertDialogCancel>
<AlertDialogAction
- disabled={deleteMutation.isPending}
+ disabled={readOnly || deleteMutation.isPending}
onClick={(event) => {
event.preventDefault()
if (deletingWatch) {