Skip to content

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

feat(gateway): quick mode on the Studio overview and lost management key docs (#6107)

t0saki1c7b86d09041
diff --git a/docs/en/api/25-gateway.md b/docs/en/api/25-gateway.md
index b0159ee8f..fc91ac102 100644
--- a/docs/en/api/25-gateway.md
+++ b/docs/en/api/25-gateway.md
@@ -204,7 +204,7 @@ Check `reason`, not the text of `detail`. When the server does not have the gate
| HTTP | `reason` | Meaning and fix |
| --- | --- | --- |
-| 401 | `management_key_invalid` | The management key is wrong. Ask the deployer for the current one. |
+| 401 | `management_key_invalid` | The management key is wrong. Ask the deployer for the current one, or see [Lost the management key](../guides/22-gateway-operations.md#lost-the-management-key). |
| 403 | `management_key_required` | A management key is set, and changing upstreams or context profiles requires it. |
| 401 | `openviking_http_401` | OpenViking rejected the API key. Use a currently valid key. |
| 401 | `openviking_identity_missing` | OpenViking returned no user for this key. |
diff --git a/docs/en/guides/15-gateway.md b/docs/en/guides/15-gateway.md
index 1c0a081f0..00d05be63 100644
--- a/docs/en/guides/15-gateway.md
+++ b/docs/en/guides/15-gateway.md
@@ -212,7 +212,7 @@ For a server bound to `127.0.0.1` with the default local authentication.
1. **Turn the gateway on.** Run `openviking-server init` and answer yes to **Enable OpenViking Gateway on the same port?**. With an existing configuration, choose **Update gateway** from the menu. You can also merge `{"gateway": {"enabled": true}}` into `ov.conf`.
2. **Start or restart** `openviking-server`.
3. **Open the gateway in Studio.** Open <http://127.0.0.1:1933/studio/> and choose **OpenViking Gateway** in the sidebar. No key is needed. If the default account has no upstreams yet, the gateway imports the server's VLM settings as upstreams at startup and creates a context profile, so the first two steps of the **Get started** checklist on the Overview tab are already done. An imported Coding Plan upstream needs your confirmation before use; see [Import OpenViking model settings](22-gateway-operations.md#import-openviking-model-settings). If nothing could be imported, add an upstream as described in [Upstreams](22-gateway-operations.md#upstreams).
-4. **Issue a gateway key.** On the Keys tab, choose **Issue key**, enter a name, pick the context profile and an upstream, and issue it. The key reads and writes memory as the local `default` user. The **Copy your gateway key** dialog shows the full `ovgw_…` key only once, so copy it before you close the dialog.
+4. **Issue a gateway key.** On the Overview tab, choose **Get a key** in the **Quick mode** card, or issue one by hand: on the Keys tab, choose **Issue key**, enter a name, pick the context profile and an upstream, and issue it. The key reads and writes memory as the local `default` user. The **Copy your gateway key** dialog shows the full `ovgw_…` key only once, so copy it before you close the dialog.
Then [send a test request](#send-a-test-request) to `http://127.0.0.1:1933/gateway`.
diff --git a/docs/en/guides/22-gateway-operations.md b/docs/en/guides/22-gateway-operations.md
index c7944604b..a6dddac11 100644
--- a/docs/en/guides/22-gateway-operations.md
+++ b/docs/en/guides/22-gateway-operations.md
@@ -42,6 +42,16 @@ To set one:
There is no command-line flag for the management key, because flags show up in process lists and shell history. Setting, changing or removing it takes a restart. It does not revoke issued gateway keys or change existing upstreams and context profiles.
+#### Lost the management key
+
+Look where the gateway reads it from:
+
+- The `OPENVIKING_GATEWAY_MANAGEMENT_KEY` environment variable wins over the files. Compose usually sets it in the `.env` file next to `docker-compose.yml`; Helm reads it from the `management-key` entry of the Secret named in `gateway.existingSecret`.
+- Otherwise it is `gateway.management_key` in `ov.conf` (embedded) or `management_key` in `gateway.conf` (standalone). A value written as `$VAR` lives in that environment variable.
+- On an embedded gateway, root can also open `ov.conf` in Studio under **Settings** → **Server configuration** → **File editor**. Keys generated by `openviking-server init` and by Studio's **Enable gateway** are stored there in plain text.
+
+If you can't recover it, put a new value of at least 32 characters in the same place (for example from `openssl rand -base64 32`) and restart. Issued gateway keys, upstreams and context profiles are unaffected. An empty environment variable does not clear the value in the file; unset the variable instead.
+
### Encryption
The gateway encrypts stored credentials and conversation state with OpenViking's own encryption (see the [Encryption guide](08-encryption.md)):
@@ -368,7 +378,7 @@ Users see only their own requests; account admins and root see the whole account
The **Overview** tab summarizes the latest 10,000 requests within the log retention period (30 days by default):
-- Until the first request arrives, a **Get started** checklist, in the order upstream → context profile → key → client.
+- Until the first request arrives, a **Get started** checklist, in the order upstream → context profile → key → client. Until the first key exists, its **Quick mode** card does the first three steps in one click: it imports OpenViking's VLM settings when no upstream is usable, creates a context profile with the recommended settings when there is none, and issues a key for the current user. Outside local dev mode, root picks the key's user in the issue dialog instead.
- **Requests**: the number of model requests, when the last one arrived, and their output tokens.
- **First-call cache hit rate**: the share of input tokens served from the provider's prompt cache on the first model call of each new user message. This is the most important sign of a healthy gateway. It should stay close to what the provider reaches without the gateway. A clear drop usually means the history the gateway sends no longer matches the previous request; see [The first-call cache hit rate dropped](#the-first-call-cache-hit-rate-dropped).
- **Within-turn cache hit rate**: the same for later calls in a turn, such as tool steps and OpenViking tool rounds. It is usually high.
@@ -790,7 +800,7 @@ When an embedded gateway cannot start, the whole OpenViking Server stops. Read t
| The gateway does not support Trusted mode (`trusted_mode_unsupported`) | Switch the server to `api_key` authentication. |
| The gateway cannot reach OpenViking (`openviking_unreachable`) | Standalone gateways only: check `openviking_url` (in `gateway.conf` or `OPENVIKING_GATEWAY_OPENVIKING_URL`) and the network. |
-If the Upstreams and Profiles tabs are read-only, the deployer set a gateway management key: choose **Enter gateway management key** to unlock them. An OpenViking root or admin API key does not unlock editing. After the management key is changed (`management_key_invalid`), Studio locks again.
+If the Upstreams and Profiles tabs are read-only, the deployer set a gateway management key: choose **Enter gateway management key** to unlock them. An OpenViking root or admin API key does not unlock editing. After the management key is changed (`management_key_invalid`), Studio locks again. If nobody has the key, see [Lost the management key](#lost-the-management-key).
### Issuing a key fails
diff --git a/docs/zh/api/25-gateway.md b/docs/zh/api/25-gateway.md
index a6a4a7086..e454af42e 100644
--- a/docs/zh/api/25-gateway.md
+++ b/docs/zh/api/25-gateway.md
@@ -204,7 +204,7 @@ curl -X POST "$SERVER_URL/gateway/admin/keys?account_id=team" \
| HTTP | `reason` | 含义和处理 |
| --- | --- | --- |
-| 401 | `management_key_invalid` | 管理密钥不正确。向部署者确认当前的管理密钥。 |
+| 401 | `management_key_invalid` | 管理密钥不正确。向部署者确认当前的管理密钥,或者见[忘记网关管理密钥](../guides/22-gateway-operations.md#忘记网关管理密钥)。 |
| 403 | `management_key_required` | 已设置管理密钥,修改上游或上下文配置时必须带上它。 |
| 401 | `openviking_http_401` | OpenViking 拒绝了 API 密钥。换用当前有效的密钥。 |
| 401 | `openviking_identity_missing` | OpenViking 没有返回这把密钥对应的用户。 |
diff --git a/docs/zh/guides/15-gateway.md b/docs/zh/guides/15-gateway.md
index e51cc98b2..08a3a4b30 100644
--- a/docs/zh/guides/15-gateway.md
+++ b/docs/zh/guides/15-gateway.md
@@ -212,7 +212,7 @@ Claude Code、Codex 和 pi 需要按项目区分记忆,或者要求每次工
1. **开启网关。** 运行 `openviking-server init`,在 **Enable OpenViking Gateway on the same port?** 处回答 yes;已有配置时,在菜单中选择 **Update gateway**。也可以直接把 `{"gateway": {"enabled": true}}` 合并进 `ov.conf`。
2. **启动或重启** `openviking-server`。
3. **在 Studio 中打开网关。** 打开 <http://127.0.0.1:1933/studio/>,在侧边栏选择 **OpenViking 网关**,不用填写密钥。默认账号还没有上游时,网关启动时会把服务端的 VLM 配置导入为上游,并创建一份上下文配置,所以“概览”标签页的**快速开始**清单前两步已经完成。导入的 Coding Plan 上游需要你确认后才能使用,见[导入 OpenViking 模型配置](22-gateway-operations.md#导入-openviking-模型配置);没有可导入的配置时,按[上游](22-gateway-operations.md#上游)手动添加。
-4. **签发网关密钥。** 在“密钥”标签页点**签发密钥**,填写名称,选择上下文配置和上游,然后签发。这个密钥以本地 `default` 用户的身份读写记忆。**复制网关密钥**对话框只显示一次完整的 `ovgw_…` 密钥,关闭前先复制。
+4. **签发网关密钥。** 在“概览”标签页的**快速模式**卡片中点**一键生成密钥**;也可以手动签发:在“密钥”标签页点**签发密钥**,填写名称,选择上下文配置和上游,然后签发。这个密钥以本地 `default` 用户的身份读写记忆。**复制网关密钥**对话框只显示一次完整的 `ovgw_…` 密钥,关闭前先复制。
然后向 `http://127.0.0.1:1933/gateway` [发送测试请求](#发送测试请求)。
diff --git a/docs/zh/guides/22-gateway-operations.md b/docs/zh/guides/22-gateway-operations.md
index b89b46768..41fcf0d5f 100644
--- a/docs/zh/guides/22-gateway-operations.md
+++ b/docs/zh/guides/22-gateway-operations.md
@@ -42,6 +42,16 @@ description: 用 Docker Compose、Helm 或独立进程部署 OpenViking 网关
管理密钥不提供命令行参数,因为命令行参数会出现在进程列表和 shell 历史里。设置、更换或去掉管理密钥后需要重启,这不会吊销已签发的网关密钥,也不会改动已有的上游和上下文配置。
+#### 忘记网关管理密钥
+
+到网关读取它的位置查找:
+
+- 环境变量 `OPENVIKING_GATEWAY_MANAGEMENT_KEY` 优先于配置文件。Compose 部署一般写在 `docker-compose.yml` 旁边的 `.env` 里;Helm 从 `gateway.existingSecret` 指定的 Secret 中读取 `management-key` 字段。
+- 没有设置环境变量时,看 `ov.conf` 的 `gateway.management_key`(嵌入)或 `gateway.conf` 的 `management_key`(独立)。值写成 `$VAR` 时,密钥在对应的环境变量里。
+- 嵌入部署的 root 还可以在 Studio 的**设置** → **服务端配置** → **文件编辑**中查看 `ov.conf`。`openviking-server init` 和 Studio **开启网关**生成的密钥都以明文保存在这里。
+
+实在找不回来,就在原来的位置换一个至少 32 个字符的新值(可以用 `openssl rand -base64 32` 生成),然后重启。已签发的网关密钥、上游和上下文配置都不受影响。把环境变量设为空字符串不会清除文件里的值,需要删掉这个变量。
+
### 加密
网关用 OpenViking 自己的加密功能保护已存的凭证和对话状态(见[加密指南](08-encryption.md)):
@@ -368,7 +378,7 @@ ov.example.com {
**概览**标签页汇总日志保留期(默认 30 天)内最新的 10,000 条请求:
-- 第一个请求到达之前,显示**快速开始**清单,顺序是“上游 → 上下文配置 → 签发密钥 → 接入”。
+- 第一个请求到达之前,显示**快速开始**清单,顺序是“上游 → 上下文配置 → 签发密钥 → 接入”。还没有密钥时,清单里的**快速模式**卡片一键完成前三步:没有可用上游时导入 OpenViking 的 VLM 配置,没有上下文配置时用推荐设置新建一份,再为当前用户签发密钥。本地 dev 模式以外,root 改为在签发对话框里选择密钥归属的用户。
- **请求数**:模型请求的数量、最近一次请求的时间,以及这些请求的输出 token。
- **首次调用缓存命中率**:每条新用户消息的第一次模型调用中,命中服务商提示缓存的输入 token 所占比例。这是判断网关是否健康最重要的指标,应该接近不经过网关时服务商能达到的水平;明显下降通常说明网关发送的历史和上一次对不上了,见[首次调用缓存命中率下降](#首次调用缓存命中率下降)。
- **轮内缓存命中率**:同一轮里后续调用的命中率,例如工具步骤和 OpenViking 工具的往返,通常很高。
@@ -790,7 +800,7 @@ URL 必须是 HTTP(S),不能含凭证、查询参数或 fragment。未知字
| 网关不支持 Trusted 模式(`trusted_mode_unsupported`) | 把 Server 改为 `api_key` 认证。 |
| 网关连不上 OpenViking(`openviking_unreachable`) | 只出现在独立网关:检查 `openviking_url`(`gateway.conf` 或 `OPENVIKING_GATEWAY_OPENVIKING_URL`)和网络。 |
-“上游”和“上下文配置”标签页只读,是因为部署者设置了网关管理密钥:点**输入网关管理密钥**解锁。OpenViking 的 root 或 admin API 密钥不能解锁编辑;管理密钥被更换后(`management_key_invalid`),Studio 会重新锁定。
+“上游”和“上下文配置”标签页只读,是因为部署者设置了网关管理密钥:点**输入网关管理密钥**解锁。OpenViking 的 root 或 admin API 密钥不能解锁编辑;管理密钥被更换后(`management_key_invalid`),Studio 会重新锁定。没人记得密钥时,见[忘记网关管理密钥](#忘记网关管理密钥)。
### 签发密钥失败
diff --git a/web-studio/src/i18n/locales/en/gateway/common.ts b/web-studio/src/i18n/locales/en/gateway/common.ts
index 3282eb497..42907921c 100644
--- a/web-studio/src/i18n/locales/en/gateway/common.ts
+++ b/web-studio/src/i18n/locales/en/gateway/common.ts
@@ -64,15 +64,20 @@ const common = {
"Whoever deployed this gateway sets the gateway management key. It's needed only to change upstreams and profiles, and it's neither your OpenViking API key nor a gateway key used by clients.",
where: 'Where can I find it?',
prefix:
- 'Keys generated by openviking-server init or openviking-gateway init start with ovgm_.',
+ "Keys generated by openviking-server init, openviking-gateway init or Studio's Enable gateway start with ovgm_.",
environment: 'Or this environment variable, which overrides both files:',
+ studio:
+ 'Root can view ov.conf in Settings → Server configuration → File editor.',
+ reset:
+ "Can't find it? Put a new key of at least 32 characters in the same place and restart.",
+ resetDocs: 'See the operations guide',
keyPlaceholder: '<at least 32 characters>',
session:
'Kept only in this browser tab. Closing the tab locks editing again.',
wrongKey:
"That's a gateway key for clients. Enter the gateway management key instead.",
invalid:
- "That gateway management key is incorrect. Check with whoever deployed this gateway. Note that it isn't your OpenViking admin API key.",
+ "That gateway management key is incorrect. If it was changed or lost, see “Where can I find it?” above. Note that it isn't your OpenViking admin API key.",
unlock: 'Unlock',
unlocked: 'Unlocked. You can now edit upstreams and profiles.',
lock: 'Lock',
@@ -82,7 +87,7 @@ const common = {
readOnly:
'Upstreams and profiles are provided by your gateway admin. You can view and test them, and pick them when issuing a key.',
adminReadOnly:
- 'OpenViking admins and root also need the gateway management key to change them.',
+ 'OpenViking admins and root also need the gateway management key to change them. If you deployed this server, the key is in ov.conf gateway.management_key.',
shared:
"You're editing settings shared by everyone in this account. Changes apply to every key that uses them as soon as you save.",
publicTitle: 'This gateway is open to every OpenViking Cloud user',
@@ -150,12 +155,12 @@ const common = {
"ov.conf was saved, but Studio couldn't confirm the restart: {{message}}. Check the server, then choose Retry.",
keyTitle: 'Save your gateway management key',
keyOnce:
- 'Studio shows it only this once. You need it to change upstreams and context profiles; this browser tab stays unlocked until you close it.',
+ 'Studio saved it to gateway.management_key in ov.conf; root can view it later in Settings → Server configuration. You need it to change upstreams and context profiles; this browser tab stays unlocked until you close it.',
copyKey: 'Copy gateway management key',
copyFailed:
"Couldn't copy. The key is selected; press Ctrl+C or ⌘C to copy it.",
keyOnceManual:
- 'Studio shows it only this once. You need it to change upstreams and context profiles; after you restart the server, choose Enter gateway management key on the gateway page and paste it.',
+ 'Studio saved it to gateway.management_key in ov.conf; root can view it later in Settings → Server configuration. You need it to change upstreams and context profiles; after you restart the server, choose Enter gateway management key on the gateway page and paste it.',
keySaved: 'I saved it',
continue: 'I saved it, open the gateway',
},
@@ -165,7 +170,7 @@ const common = {
management_key_required:
'Upstreams and profiles are provided by your gateway admin. Enter the gateway management key to change them.',
management_key_invalid:
- 'The gateway management key is incorrect. Check with whoever deployed this gateway.',
+ 'The gateway management key is incorrect. Unlock again with the current key; “Where can I find it?” in the unlock dialog lists where it is stored.',
vlm_import_forbidden:
'You do not have permission to import OpenViking model settings.',
vlm_import_unavailable:
diff --git a/web-studio/src/i18n/locales/en/gateway/overview.ts b/web-studio/src/i18n/locales/en/gateway/overview.ts
index ef89438bf..a7c1ca3a7 100644
--- a/web-studio/src/i18n/locales/en/gateway/overview.ts
+++ b/web-studio/src/i18n/locales/en/gateway/overview.ts
@@ -64,6 +64,28 @@ const overview = {
action: 'Open setup guides',
},
},
+ quick: {
+ title: 'Quick mode',
+ description:
+ 'Skip the steps below and get a gateway key that works right away.',
+ upstreamImport:
+ "Upstream: import the OpenViking server's model settings, reusing its API key and quota",
+ upstreamUse: 'Upstream: use {{names}} ({{models}}, {{protocol}})',
+ profileCreate:
+ 'Context profile: create “{{name}}” with the recommended settings',
+ profileUse: 'Context profile: use “{{name}}”',
+ keySelf: 'Key: issued for {{user}}',
+ keyPick: 'Key: choose the OpenViking user who owns it in the next step',
+ action: 'Get a key',
+ running: 'Generating…',
+ retry: 'Try again',
+ locked:
+ 'Creating a context profile or importing models needs the gateway management key.',
+ noUsable:
+ "OpenViking's model settings have no model the gateway can relay directly. Fix the issues listed below, or add an upstream yourself in step 1.",
+ keyName: 'Quick mode',
+ divider: 'Or set up step by step',
+ },
kpi: {
requests: {
label: 'Requests',
diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/common.ts b/web-studio/src/i18n/locales/zh-CN/gateway/common.ts
index c7d4f3904..4d9ac2d08 100644
--- a/web-studio/src/i18n/locales/zh-CN/gateway/common.ts
+++ b/web-studio/src/i18n/locales/zh-CN/gateway/common.ts
@@ -64,13 +64,16 @@ const common = {
'网关管理密钥由部署这台网关的人设置,用来修改上游和上下文配置。它不是 OpenViking API 密钥,也不是客户端用的网关密钥。',
where: '在哪里找?',
prefix:
- 'openviking-server init 和 openviking-gateway init 生成的值以 ovgm_ 开头。',
+ 'openviking-server init、openviking-gateway init 和 Studio“开启网关”生成的值都以 ovgm_ 开头。',
environment: '也可能设在环境变量里,它优先于配置文件:',
+ studio: 'Root 可以在“设置 → 服务端配置 → 文件编辑”中查看 ov.conf。',
+ reset: '实在找不到,就在原来的位置换一个至少 32 个字符的新密钥,然后重启。',
+ resetDocs: '查看运维文档',
keyPlaceholder: '<至少 32 个字符>',
session: '只保存在当前浏览器标签页,关闭后自动锁定。',
wrongKey: '这是网关密钥(给客户端用的),请输入网关管理密钥。',
invalid:
- '网关管理密钥不正确。请向部署这台网关的人确认。注意,这里要填的不是 OpenViking 的管理员 API 密钥。',
+ '网关管理密钥不正确。如果密钥被更换或遗失,请看上方的“在哪里找?”。注意,这里要填的不是 OpenViking 的管理员 API 密钥。',
unlock: '解锁',
unlocked: '已解锁,现在可以修改上游和上下文配置',
lock: '锁定',
@@ -78,7 +81,8 @@ const common = {
expired: '网关管理密钥已失效,上游和上下文配置恢复为只读。',
readOnly:
'上游和上下文配置由网关管理员统一提供。你可以查看、测试连接,并在签发密钥时选用。',
- adminReadOnly: 'OpenViking 的管理员和 Root 也需要网关管理密钥才能修改。',
+ adminReadOnly:
+ 'OpenViking 的管理员和 Root 也需要网关管理密钥才能修改。如果这台服务是你部署的,密钥在 ov.conf 的 gateway.management_key 里。',
shared:
'你正在修改本账号所有用户共用的配置,保存后立即对使用它的密钥生效。',
publicTitle: '这台网关对所有 OpenViking 商业版用户开放',
@@ -143,11 +147,11 @@ const common = {
'ov.conf 已保存,但无法确认服务是否重启成功:{{message}}。请检查服务状态,然后点“重试”。',
keyTitle: '保存网关管理密钥',
keyOnce:
- '密钥只显示这一次。修改上游和上下文配置时需要它;关闭这个浏览器标签页之前,当前页面保持解锁。',
+ '密钥已写入 ov.conf 的 gateway.management_key,Root 之后可以在“设置 → 服务端配置”中查看。修改上游和上下文配置时需要它;关闭这个浏览器标签页之前,当前页面保持解锁。',
copyKey: '复制网关管理密钥',
copyFailed: '复制失败,密钥已选中,请按 Ctrl+C 或 ⌘C 复制。',
keyOnceManual:
- '密钥只显示这一次。修改上游和上下文配置时需要它;重启服务后,在网关页面点“输入网关管理密钥”并粘贴。',
+ '密钥已写入 ov.conf 的 gateway.management_key,Root 之后可以在“设置 → 服务端配置”中查看。修改上游和上下文配置时需要它;重启服务后,在网关页面点“输入网关管理密钥”并粘贴。',
keySaved: '已保存',
continue: '已保存,打开网关',
},
@@ -156,7 +160,8 @@ const common = {
reasons: {
management_key_required:
'上游和上下文配置由网关管理员统一提供,输入网关管理密钥后才能修改。',
- management_key_invalid: '网关管理密钥不正确,请向部署这台网关的人确认。',
+ management_key_invalid:
+ '网关管理密钥不正确,请用当前的密钥重新解锁。解锁对话框的“在哪里找?”列出了它的存放位置。',
vlm_import_forbidden: '你没有导入 OpenViking 模型配置的权限。',
vlm_import_unavailable:
'这台网关不在 OpenViking 服务内运行,读不到服务端的模型配置,请手动添加上游。',
diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/overview.ts b/web-studio/src/i18n/locales/zh-CN/gateway/overview.ts
index ae39e9bfa..ed40dd84b 100644
--- a/web-studio/src/i18n/locales/zh-CN/gateway/overview.ts
+++ b/web-studio/src/i18n/locales/zh-CN/gateway/overview.ts
@@ -61,6 +61,25 @@ const overview = {
action: '查看接入指南',
},
},
+ quick: {
+ title: '快速模式',
+ description: '跳过下面的步骤,一键拿到可以直接使用的网关密钥。',
+ upstreamImport:
+ '上游:导入 OpenViking 服务端的模型配置,沿用它的 API Key 和额度',
+ upstreamUse: '上游:使用 {{names}}({{models}},{{protocol}})',
+ profileCreate: '上下文配置:用推荐设置新建“{{name}}”',
+ profileUse: '上下文配置:使用“{{name}}”',
+ keySelf: '密钥:为 {{user}} 签发',
+ keyPick: '密钥:下一步选择密钥归属的 OpenViking 用户',
+ action: '一键生成密钥',
+ running: '生成中…',
+ retry: '重试',
+ locked: '创建上下文配置或导入模型需要网关管理密钥。',
+ noUsable:
+ 'OpenViking 的模型配置里没有网关能直接转发的模型。处理下面列出的问题,或者在第 1 步手动添加上游。',
+ keyName: '快速模式',
+ divider: '或者按步骤手动配置',
+ },
kpi: {
requests: {
label: '请求数',
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 179bb50c6..687294149 100644
--- a/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx
+++ b/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx
@@ -243,7 +243,10 @@ describe('snippetModel', () => {
})
})
-function renderIssueDialog(upstreams: Upstream[] = [deepseek]) {
+function renderIssueDialog(
+ upstreams: Upstream[] = [deepseek],
+ defaults?: React.ComponentProps<typeof KeysIssueDialog>['defaults'],
+) {
const onIssued = vi.fn()
const onOpenChange = vi.fn()
const client = new QueryClient({
@@ -257,6 +260,7 @@ function renderIssueDialog(upstreams: Upstream[] = [deepseek]) {
profiles={[profile]}
upstreams={upstreams}
onIssued={onIssued}
+ defaults={defaults}
/>
</QueryClientProvider>,
)
@@ -623,6 +627,25 @@ describe('KeysIssueDialog', () => {
})
})
+ it('starts from the given defaults', async () => {
+ api.issueKey.mockResolvedValue({})
+ renderIssueDialog([deepseek, openai], {
+ name: 'Quick mode',
+ policy_id: 'p1',
+ upstream_ids: ['u2'],
+ })
+ await waitFor(() => expect(userPicker().textContent).toContain('alice'))
+ submit()
+
+ await waitFor(() =>
+ expect(api.issueKey).toHaveBeenCalledWith(expect.anything(), {
+ ...request,
+ name: 'Quick mode',
+ upstream_ids: ['u2'],
+ }),
+ )
+ })
+
it('explains a rejected OpenViking key next to that field', async () => {
api.issueKey.mockRejectedValue(
new GatewayError(
diff --git a/web-studio/src/routes/gateway/-components/keys-issue-dialog.tsx b/web-studio/src/routes/gateway/-components/keys-issue-dialog.tsx
index e170aee3c..67de8d4ce 100644
--- a/web-studio/src/routes/gateway/-components/keys-issue-dialog.tsx
+++ b/web-studio/src/routes/gateway/-components/keys-issue-dialog.tsx
@@ -145,6 +145,8 @@ type KeysIssueDialogProps = {
upstreams: Upstream[]
/** Receives the new key, whose secret is only available now. */
onIssued: (issued: IssuedKey) => void
+ /** Initial name, profile, upstreams and models instead of an empty form. */
+ defaults?: Partial<Omit<KeyRequest, keyof KeyOwner>>
}
/**
@@ -159,6 +161,7 @@ export function KeysIssueDialog({
profiles,
upstreams,
onIssued,
+ defaults,
}: KeysIssueDialogProps) {
const { t } = useTranslation('gateway')
const {
@@ -181,6 +184,7 @@ export function KeysIssueDialog({
policy_id: profiles.length === 1 ? profiles[0].id : '',
upstream_ids: upstreams.length === 1 ? [upstreams[0].id] : [],
models: [],
+ ...defaults,
}))
/** 'key' once the admin switches to pasting, or the server asks for it. */
const [chosenMode, setChosenMode] = React.useState<'user' | 'key'>('user')
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 58cd9f6cc..c2a7c461d 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
@@ -10,6 +10,7 @@ import {
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type * as Api from '../-lib/api'
import { GatewayError } from '../-lib/api'
+import { gatewayDocsUrl } from '../-lib/client-guides'
import {
getManagementKey,
lockManagementKey,
@@ -38,7 +39,10 @@ vi.mock('../-lib/use-gateway', () => ({
}),
}))
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: { resolvedLanguage: 'en' },
+ }),
}))
vi.mock('sonner', () => ({
toast: { success: state.success, error: state.error },
@@ -60,6 +64,17 @@ function open() {
)
requestManagementUnlock()
}
+it('explains where to find a lost key and links to the operations guide', async () => {
+ open()
+ fireEvent.click(await screen.findByText('management.where'))
+ expect(screen.getByText('management.studio')).toBeTruthy()
+ expect(screen.getByText(/management\.reset\b/)).toBeTruthy()
+ expect(
+ screen
+ .getByRole('link', { name: 'management.resetDocs' })
+ .getAttribute('href'),
+ ).toBe(gatewayDocsUrl('operations', 'en'))
+})
it('rejects client keys in the management field without sending them', async () => {
open()
const input = await screen.findByLabelText('management.label')
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 a3fd76fa2..6ee80bab9 100644
--- a/web-studio/src/routes/gateway/-components/management-key-dialog.tsx
+++ b/web-studio/src/routes/gateway/-components/management-key-dialog.tsx
@@ -13,6 +13,7 @@ import {
DialogFooter,
} from '#/components/ui/dialog'
import { getAccess, toGatewayError } from '../-lib/api'
+import { gatewayDocsUrl } from '../-lib/client-guides'
import {
MANAGEMENT_UNLOCK_EVENT,
setManagementKey,
@@ -27,7 +28,7 @@ const MANAGEMENT_CONFIGS = [
]
export function ManagementKeyDialog() {
- const { t } = useTranslation('gateway')
+ const { t, i18n } = useTranslation('gateway')
const { connection } = useGateway()
const [open, setOpen] = React.useState(false)
const [key, setKey] = React.useState('')
@@ -91,7 +92,19 @@ export function ManagementKeyDialog() {
{t('management.environment')}{' '}
<code>OPENVIKING_GATEWAY_MANAGEMENT_KEY</code>
</li>
+ <li>{t('management.studio')}</li>
<li>{t('management.prefix')}</li>
+ <li>
+ {t('management.reset')}{' '}
+ <a
+ href={gatewayDocsUrl('operations', i18n.resolvedLanguage)}
+ target="_blank"
+ rel="noreferrer"
+ className="font-medium text-foreground underline underline-offset-4"
+ >
+ {t('management.resetDocs')}
+ </a>
+ </li>
</ul>
</details>
<SettingField
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 1933cc9b5..03adefcc1 100644
--- a/web-studio/src/routes/gateway/-components/overview-page.test.tsx
+++ b/web-studio/src/routes/gateway/-components/overview-page.test.tsx
@@ -15,6 +15,7 @@ import {
render,
screen,
waitFor,
+ within,
} from '@testing-library/react'
import { toast } from 'sonner'
import {
@@ -32,8 +33,16 @@ import i18n from '#/i18n'
import { GatewayError } from '../-lib/api'
import type * as Api from '../-lib/api'
-import type { LogRecord, Overview, Profile } from '../-lib/api'
+import type {
+ GatewayAccess,
+ IssuedKey,
+ LogRecord,
+ Overview,
+ Profile,
+ Upstream,
+} from '../-lib/api'
import { PROFILE_DEFAULTS } from '../-lib/profile-schema'
+import { UPSTREAM_DEFAULTS } from '../-lib/upstream-schema'
import { OverviewPage } from './overview-page'
const api = vi.hoisted(() => ({
@@ -44,7 +53,12 @@ const api = vi.hoisted(() => ({
listProfiles: vi.fn(),
listKeys: vi.fn(),
saveProfile: vi.fn(),
+ importVlm: vi.fn(),
+ issueKey: vi.fn(),
+ listKeyUsers: vi.fn(),
+ getConnectionInfo: vi.fn(),
}))
+const host = vi.hoisted(() => ({ serverMode: 'api_key', gatewayHost: false }))
vi.mock('#/hooks/use-studio-service', () => ({
useStudioService: () => ({ ready: true, provider: 'opensource' }),
@@ -61,7 +75,8 @@ vi.mock('#/hooks/use-app-connection', () => ({
},
connectionRole: 'admin',
isConnectionRoleLoading: false,
- serverMode: 'api_key',
+ serverMode: host.serverMode,
+ isGatewayHost: host.gatewayHost,
}),
}))
vi.mock('../-lib/api', async (importOriginal) => ({
@@ -209,6 +224,12 @@ afterAll(async () => {
beforeEach(() => {
vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
for (const mock of Object.values(api)) mock.mockReset()
+ host.serverMode = 'api_key'
+ host.gatewayHost = false
+ api.getConnectionInfo.mockResolvedValue({
+ base_url: 'http://gateway.test:1933',
+ public_url_configured: true,
+ })
api.getAccess.mockResolvedValue({
managed: false,
can_write_objects: true,
@@ -401,3 +422,244 @@ describe('OverviewPage', () => {
await i18n.changeLanguage('en')
})
})
+
+const ARK: Upstream = {
+ ...UPSTREAM_DEFAULTS,
+ id: 'vlm-ark',
+ revision: 1,
+ name: 'vlm-ark',
+ protocol: 'chat',
+ base_url: 'https://ark.example.com/api/v3',
+ models: ['doubao-seed-1-6'],
+ has_api_key: true,
+}
+const CODING_PLAN: Upstream = {
+ ...ARK,
+ id: 'vlm-kimi',
+ name: 'vlm-kimi',
+ coding_plan: true,
+}
+const DEFAULT_PROFILE: Profile = {
+ ...PROFILE_DEFAULTS,
+ id: 'default',
+ revision: 1,
+}
+const ISSUED: IssuedKey = {
+ id: 'k1',
+ revision: 1,
+ name: 'Quick mode',
+ policy_id: 'default',
+ upstream_ids: ['vlm-ark'],
+ models: [],
+ user_id: 'default',
+ prefix: 'ovgw_quick12',
+ created_at: NOW,
+ key: 'ovgw_quickSecret',
+}
+const QUICK_REQUEST = {
+ name: 'Quick mode',
+ policy_id: 'default',
+ upstream_ids: ['vlm-ark'],
+ models: [],
+}
+const LOCKED: GatewayAccess = {
+ managed: true,
+ can_write_objects: false,
+ can_import_vlm: false,
+ can_issue_for_others: false,
+ role: 'user',
+ account_id: 'acme',
+ user_id: 'alice',
+ warnings: [],
+}
+
+const quickButton = () => screen.findByRole('button', { name: 'Get a key' })
+
+describe('OverviewPage quick mode', () => {
+ beforeEach(() => {
+ api.getOverview.mockResolvedValue(EMPTY_OVERVIEW)
+ })
+
+ it('issues a key with the seeded upstream and profile in one request', async () => {
+ host.serverMode = 'dev'
+ api.listUpstreams.mockResolvedValue([ARK])
+ api.listProfiles.mockResolvedValue([DEFAULT_PROFILE])
+ api.issueKey.mockResolvedValue(ISSUED)
+ renderOverview()
+
+ expect(
+ await screen.findByText(
+ 'Upstream: use vlm-ark (doubao-seed-1-6, Chat Completions)',
+ ),
+ ).toBeTruthy()
+ expect(screen.getByText('Context profile: use “Default”')).toBeTruthy()
+ expect(screen.getByText('Or set up step by step')).toBeTruthy()
+ api.listKeys.mockResolvedValue([ISSUED])
+ fireEvent.click(await quickButton())
+
+ const dialog = await screen.findByRole('dialog')
+ expect(within(dialog).getByText('ovgw_quickSecret')).toBeTruthy()
+ expect(api.issueKey).toHaveBeenCalledTimes(1)
+ expect(api.issueKey.mock.calls[0][1]).toEqual(QUICK_REQUEST)
+ expect(api.importVlm).not.toHaveBeenCalled()
+ expect(api.saveProfile).not.toHaveBeenCalled()
+ // A chat-only key opens on the chat client, with the model filled in.
+ const snippet = within(dialog).getAllByText(/v1\/chat\/completions/)[0]
+ expect(snippet.textContent).toContain('doubao-seed-1-6')
+ expect(snippet.textContent).toContain('http://gateway.test:1933')
+
+ expect(await screen.findByText('3 of 4 done')).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Get a key' })).toBeNull()
+ expect(screen.getByRole('dialog')).toBe(dialog)
+ })
+
+ it('imports, creates the default profile and issues; a retry skips the import', async () => {
+ let stored: Upstream[] = []
+ api.listUpstreams.mockImplementation(async () => stored)
+ api.importVlm.mockImplementation(async () => {
+ stored = [ARK]
+ return {
+ imported: [{ id: 'vlm-ark', name: 'vlm-ark' }],
+ needs_confirmation: [],
+ skipped: [],
+ }
+ })
+ api.saveProfile
+ .mockRejectedValueOnce(new GatewayError('Invalid', 422))
+ .mockResolvedValue(DEFAULT_PROFILE)
+ api.issueKey.mockResolvedValue(ISSUED)
+ renderOverview()
+
+ expect(
+ await screen.findByText(
+ "Upstream: import the OpenViking server's model settings, reusing its API key and quota",
+ ),
+ ).toBeTruthy()
+ expect(
+ screen.getByText(
+ 'Context profile: create “Default” with the recommended settings',
+ ),
+ ).toBeTruthy()
+ expect(screen.getByText('Key: issued for admin')).toBeTruthy()
+ fireEvent.click(await quickButton())
+ expect(
+ await screen.findByText(
+ 'The gateway rejected these settings. Check the values and try again.',
+ ),
+ ).toBeTruthy()
+ expect(api.issueKey).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }))
+ expect(await screen.findByText('ovgw_quickSecret')).toBeTruthy()
+ expect(api.importVlm).toHaveBeenCalledTimes(1)
+ expect(api.saveProfile).toHaveBeenCalledTimes(2)
+ const [, id, settings] = api.saveProfile.mock.calls[1]
+ expect(id).toBe('default')
+ expect(settings).toEqual(PROFILE_DEFAULTS)
+ expect(api.issueKey.mock.calls[0][1]).toEqual(QUICK_REQUEST)
+ const order = [api.importVlm, api.saveProfile, api.issueKey].map(
+ (mock) => mock.mock.invocationCallOrder[0],
+ )
+ expect(order).toEqual([...order].sort((a, b) => a - b))
+ })
+
+ it('stops after an import that yields only an unconfirmed Coding Plan', async () => {
+ let stored: Upstream[] = []
+ api.listUpstreams.mockImplementation(async () => stored)
+ api.importVlm.mockImplementation(async () => {
+ stored = [CODING_PLAN]
+ return {
+ imported: [],
+ needs_confirmation: [{ id: 'vlm-kimi', name: 'vlm-kimi' }],
+ skipped: [],
+ }
+ })
+ renderOverview()
+
+ fireEvent.click(await quickButton())
+ expect(
+ await screen.findByText(/no model the gateway can relay directly/),
+ ).toBeTruthy()
+ const review = screen
+ .getAllByText('Review')
+ .map((node) => node.closest('a')?.getAttribute('href'))
+ expect(review).toContain('/gateway/upstreams/vlm-kimi')
+ expect(api.saveProfile).not.toHaveBeenCalled()
+ expect(api.issueKey).not.toHaveBeenCalled()
+ })
+
+ it('lets root pick the user in a prefilled issue dialog', async () => {
+ api.getAccess.mockResolvedValue({
+ managed: false,
+ can_write_objects: true,
+ can_import_vlm: true,
+ can_issue_for_others: true,
+ role: 'root',
+ account_id: 'acme',
+ user_id: 'admin',
+ warnings: [],
+ })
+ api.listUpstreams.mockResolvedValue([ARK, CODING_PLAN])
+ api.listProfiles.mockResolvedValue([DEFAULT_PROFILE])
+ api.listKeyUsers.mockResolvedValue([
+ { user_id: 'alice', role: 'user', api_key_available: true },
+ ])
+ renderOverview()
+
+ expect(
+ await screen.findByText(
+ 'Key: choose the OpenViking user who owns it in the next step',
+ ),
+ ).toBeTruthy()
+ fireEvent.click(await quickButton())
+ const dialog = await screen.findByRole('dialog')
+ expect(within(dialog).getByText('Issue a gateway key')).toBeTruthy()
+ expect(within(dialog).getByLabelText('Name')).toBe(
+ within(dialog).getByDisplayValue('Quick mode'),
+ )
+ expect(
+ within(dialog).getByRole('combobox', { name: 'Context profile' })
+ .textContent,
+ ).toContain('Default')
+ const checked = within(dialog)
+ .getAllByRole('checkbox')
+ .map((box) => box.getAttribute('aria-checked'))
+ expect(checked).toEqual(['true', 'false'])
+ expect(api.issueKey).not.toHaveBeenCalled()
+ })
+
+ it('issues while locked when an upstream and a profile exist', async () => {
+ api.getAccess.mockResolvedValue(LOCKED)
+ api.listUpstreams.mockResolvedValue([ARK])
+ api.listProfiles.mockResolvedValue([DEFAULT_PROFILE])
+ api.issueKey.mockResolvedValue({ ...ISSUED, user_id: 'alice' })
+ renderOverview()
+
+ fireEvent.click(await quickButton())
+ await waitFor(() => expect(api.issueKey).toHaveBeenCalledTimes(1))
+ expect(api.issueKey.mock.calls[0][1]).toEqual(QUICK_REQUEST)
+ })
+
+ it('offers unlocking while locked without a profile', async () => {
+ api.getAccess.mockResolvedValue(LOCKED)
+ api.listUpstreams.mockResolvedValue([ARK])
+ renderOverview()
+
+ const locked = await screen.findByText(
+ 'Creating a context profile or importing models needs the gateway management key.',
+ )
+ expect(
+ within(locked.closest('section') as HTMLElement).getByRole('button'),
+ ).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Get a key' })).toBeNull()
+ })
+
+ it('stays hidden on a standalone gateway that is locked without upstreams', async () => {
+ host.gatewayHost = true
+ api.getAccess.mockResolvedValue(LOCKED)
+ renderOverview()
+
+ expect(await screen.findByText('0 of 4 done')).toBeTruthy()
+ expect(screen.queryByText('Quick mode')).toBeNull()
+ })
+})
diff --git a/web-studio/src/routes/gateway/-components/overview-quick-start.tsx b/web-studio/src/routes/gateway/-components/overview-quick-start.tsx
new file mode 100644
index 000000000..2f09fdcb2
--- /dev/null
+++ b/web-studio/src/routes/gateway/-components/overview-quick-start.tsx
@@ -0,0 +1,210 @@
+import { useMutation } from '@tanstack/react-query'
+import { LoaderCircleIcon, ZapIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import { Button } from '#/components/ui/button'
+
+import {
+ importVlm,
+ issueKey,
+ listProfiles,
+ listUpstreams,
+ saveProfile,
+ toGatewayError,
+} from '../-lib/api'
+import type {
+ IssuedKey,
+ KeyRequest,
+ Profile,
+ Upstream,
+ VlmImportResult,
+} from '../-lib/api'
+import { protocolLabel } from '../-lib/localize'
+import { PROFILE_DEFAULTS } from '../-lib/profile-schema'
+import {
+ QUICK_PROFILE_ID,
+ isQuickUsable,
+ quickProfile,
+} from '../-lib/quick-start'
+import type { QuickPlan } from '../-lib/quick-start'
+import { servedModels } from '../-lib/upstream-schema'
+import { useGateway } from '../-lib/use-gateway'
+import { ManagementUnlockButton } from './access-notices'
+import { issueProblem } from './keys-issue-dialog'
+import { Notice } from './notice'
+import { ImportResultNotice } from './upstreams-page'
+
+const MODEL_PREVIEW = 3
+
+type Outcome =
+ | {
+ kind: 'issued'
+ issued: IssuedKey
+ profile: Profile
+ upstreams: Upstream[]
+ }
+ | { kind: 'pick'; request: KeyRequest }
+ | { kind: 'noUsable'; result: VlmImportResult }
+
+type OverviewQuickStartProps = {
+ plan: QuickPlan
+ onIssued: (
+ issued: IssuedKey,
+ profileName: string,
+ upstreams: Upstream[],
+ ) => void
+ /** Root picks the key's user in the issue dialog, prefilled with this request. */
+ onPickUser: (request: KeyRequest) => void
+}
+
+/**
+ * One click from an empty gateway to a working key: imports OpenViking's
+ * model settings when no upstream is usable, creates the recommended profile
+ * when there is none, then issues a key for the current identity.
+ */
+export function OverviewQuickStart({
+ plan,
+ onIssued,
+ onPickUser,
+}: OverviewQuickStartProps) {
+ const { t, i18n } = useTranslation('gateway')
+ const { connection, access, invalidate } = useGateway()
+ const list = new Intl.ListFormat(i18n.resolvedLanguage)
+
+ const run = useMutation({
+ mutationFn: async (): Promise<Outcome> => {
+ let upstreams = await listUpstreams(connection)
+ let usable = upstreams.filter(isQuickUsable)
+ if (!usable.length) {
+ const result = await importVlm(connection)
+ upstreams = await listUpstreams(connection)
+ usable = upstreams.filter(isQuickUsable)
+ if (!usable.length) return { kind: 'noUsable', result }
+ }
+ const profile =
+ quickProfile(await listProfiles(connection)) ??
+ (await saveProfile(connection, QUICK_PROFILE_ID, {
+ ...PROFILE_DEFAULTS,
+ name: t('profiles.defaultName'),
+ }))
+ const request: KeyRequest = {
+ name: t('overview.quick.keyName'),
+ policy_id: profile.id,
+ upstream_ids: usable.map((upstream) => upstream.id),
+ models: [],
+ }
+ if (plan.pickUser) return { kind: 'pick', request }
+ const issued = await issueKey(connection, request)
+ return { kind: 'issued', issued, profile, upstreams }
+ },
+ onSuccess: async (outcome) => {
+ if (outcome.kind === 'issued') {
+ // The card goes away with the refreshed key list; the secret stays.
+ onIssued(outcome.issued, outcome.profile.name, outcome.upstreams)
+ await invalidate('upstreams', 'profiles', 'keys', 'overview', 'tools')
+ } else if (outcome.kind === 'pick') {
+ await invalidate('upstreams', 'profiles')
+ onPickUser(outcome.request)
+ } else {
+ await invalidate('upstreams')
+ }
+ },
+ onError: (error) =>
+ invalidate(
+ 'upstreams',
+ 'profiles',
+ // A stale /access offered the import; the refreshed one hides it.
+ ...(toGatewayError(error).reason === 'vlm_import_forbidden'
+ ? (['access'] as const)
+ : []),
+ ),
+ })
+ const noUsable = run.data?.kind === 'noUsable' ? run.data.result : undefined
+ const failed = run.isError || Boolean(noUsable)
+
+ const models = [...new Set(plan.upstreams.flatMap(servedModels))]
+ const upstreamLine = plan.upstreams.length
+ ? t('overview.quick.upstreamUse', {
+ names: list.format(plan.upstreams.map((upstream) => upstream.name)),
+ models:
+ list.format(models.slice(0, MODEL_PREVIEW)) +
+ (models.length > MODEL_PREVIEW ? '…' : ''),
+ protocol: list.format([
+ ...new Set(
+ plan.upstreams.map((upstream) =>
+ protocolLabel(t, upstream.protocol),
+ ),
+ ),
+ ]),
+ })
+ : t('overview.quick.upstreamImport')
+ const lines = [
+ upstreamLine,
+ plan.profile
+ ? t('overview.quick.profileUse', { name: plan.profile.name })
+ : t('overview.quick.profileCreate', { name: t('profiles.defaultName') }),
+ plan.pickUser
+ ? t('overview.quick.keyPick')
+ : t('overview.quick.keySelf', {
+ user: access?.user_id ?? connection.userId,
+ }),
+ ]
+
+ return (
+ <section className="grid gap-3 rounded-lg border border-primary/30 bg-background/70 p-4">
+ <div className="grid gap-1">
+ <p className="flex items-center gap-2 font-medium">
+ <ZapIcon className="size-4 text-primary" />
+ {t('overview.quick.title')}
+ </p>
+ <p className="text-sm text-muted-foreground">
+ {t('overview.quick.description')}
+ </p>
+ </div>
+ <ul className="grid list-inside list-disc gap-0.5 text-sm text-muted-foreground">
+ {lines.map((line) => (
+ <li key={line}>{line}</li>
+ ))}
+ </ul>
+ {run.isError ? (
+ <Notice tone="danger">{issueProblem(t, run.error).message}</Notice>
+ ) : null}
+ {noUsable ? (
+ <>
+ <Notice tone="warning">{t('overview.quick.noUsable')}</Notice>
+ <ImportResultNotice result={noUsable} onDismiss={run.reset} />
+ </>
+ ) : null}
+ {plan.runnable ? (
+ <div className="flex justify-end">
+ <Button
+ type="button"
+ size="sm"
+ disabled={run.isPending}
+ onClick={() => run.mutate()}
+ >
+ {run.isPending ? (
+ <LoaderCircleIcon className="animate-spin" />
+ ) : (
+ <ZapIcon />
+ )}
+ {t(
+ run.isPending
+ ? 'overview.quick.running'
+ : failed
+ ? 'overview.quick.retry'
+ : 'overview.quick.action',
+ )}
+ </Button>
+ </div>
+ ) : (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="text-sm text-muted-foreground">
+ {t('overview.quick.locked')}
+ </p>
+ <ManagementUnlockButton />
+ </div>
+ )}
+ </section>
+ )
+}
diff --git a/web-studio/src/routes/gateway/-components/overview-setup.tsx b/web-studio/src/routes/gateway/-components/overview-setup.tsx
index 30093c7e2..3124851ce 100644
--- a/web-studio/src/routes/gateway/-components/overview-setup.tsx
+++ b/web-studio/src/routes/gateway/-components/overview-setup.tsx
@@ -1,4 +1,4 @@
-import type * as React from 'react'
+import * as React from 'react'
import { Link } from '@tanstack/react-router'
import {
ArrowRightIcon,
@@ -17,16 +17,23 @@ import {
CardHeader,
CardTitle,
} from '#/components/ui/card'
+import { useAppConnection } from '#/hooks/use-app-connection'
import { cn } from '#/lib/utils'
+import type { IssuedKey, KeyRequest, Upstream } from '../-lib/api'
+import { quickPlan } from '../-lib/quick-start'
import { NEW_ID } from '../-lib/search'
import {
+ useConnectionInfo,
useGateway,
useKeys,
useProfiles,
useUpstreams,
} from '../-lib/use-gateway'
import { ManagementUnlockButton } from './access-notices'
+import { KeysIssueDialog } from './keys-issue-dialog'
+import { KeysSecretDialog } from './keys-secret-dialog'
+import { OverviewQuickStart } from './overview-quick-start'
import { RecommendedProfileButton } from './recommended-profile-button'
type StepState = 'done' | 'current' | 'todo'
@@ -96,17 +103,45 @@ function SetupStep({
)
}
+type QuickIssued = {
+ issued: IssuedKey
+ profileName?: string
+ upstreams: Upstream[]
+}
+
/**
* Checklist from an empty gateway to the first request: add an upstream,
* create a context profile (one click with recommended settings), issue a
- * key, connect a client. A step is done once its list is non-empty.
+ * key, connect a client. A step is done once its list is non-empty. Before
+ * the first key, quick mode does the first three steps in one click.
*/
export function OverviewSetup() {
const { t } = useTranslation('gateway')
- const { readOnly } = useGateway()
+ const { access, readOnly } = useGateway()
+ const { isGatewayHost } = useAppConnection()
const upstreams = useUpstreams()
const profiles = useProfiles()
const keys = useKeys()
+ const connectionInfo = useConnectionInfo()
+ const plan = quickPlan({
+ keys: keys.data,
+ upstreams: upstreams.data,
+ profiles: profiles.data,
+ access,
+ readOnly,
+ gatewayHost: isGatewayHost,
+ })
+ // Dialogs live here: the quick-mode card goes away once a key exists.
+ const [issueDefaults, setIssueDefaults] = React.useState<KeyRequest | null>(
+ null,
+ )
+ const [issueSession, setIssueSession] = React.useState(0)
+ const [issued, setIssued] = React.useState<QuickIssued | null>(null)
+ const [secretOpen, setSecretOpen] = React.useState(false)
+ const showSecret = (next: QuickIssued) => {
+ setIssued(next)
+ setSecretOpen(true)
+ }
const counts = [upstreams.data, profiles.data, keys.data].map(
(list) => list?.length,
@@ -122,8 +157,9 @@ export function OverviewSetup() {
: index === current
? 'current'
: 'todo'
+ // Quick mode, when offered, holds the only primary button.
const variantOf = (index: number) =>
- index === current ? 'default' : 'outline'
+ index === current && !plan.shown ? 'default' : 'outline'
const [upstreamCount = 0, profileCount = 0, keyCount = 0] = counts
// Upstreams imported from the server's VLM settings carry a `vlm-` id.
const importedCount =
@@ -167,7 +203,26 @@ export function OverviewSetup() {
</CardAction>
) : null}
</CardHeader>
- <CardContent>
+ <CardContent className="grid gap-4">
+ {plan.shown ? (
+ <>
+ <OverviewQuickStart
+ plan={plan}
+ onIssued={(key, profileName, list) =>
+ showSecret({ issued: key, profileName, upstreams: list })
+ }
+ onPickUser={(request) => {
+ setIssueSession((session) => session + 1)
+ setIssueDefaults(request)
+ }}
+ />
+ <div className="flex items-center gap-3 text-xs text-muted-foreground">
+ <span className="h-px flex-1 bg-border" />
+ {t('overview.quick.divider')}
+ <span className="h-px flex-1 bg-border" />
+ </div>
+ </>
+ ) : null}
<ol className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
<SetupStep
number={1}
@@ -334,6 +389,35 @@ export function OverviewSetup() {
</SetupStep>
</ol>
</CardContent>
+ <KeysIssueDialog
+ key={issueSession}
+ open={issueDefaults !== null}
+ onOpenChange={(open) => {
+ if (!open) setIssueDefaults(null)
+ }}
+ profiles={profiles.data ?? []}
+ upstreams={upstreams.data ?? []}
+ defaults={issueDefaults ?? undefined}
+ onIssued={(key) => {
+ setIssueDefaults(null)
+ showSecret({
+ issued: key,
+ profileName: profiles.data?.find(
+ (profile) => profile.id === key.policy_id,
+ )?.name,
+ upstreams: upstreams.data ?? [],
+ })
+ }}
+ />
+ <KeysSecretDialog
+ open={secretOpen}
+ issued={issued?.issued ?? null}
+ baseUrl={connectionInfo.data?.base_url ?? ''}
+ profileName={issued?.profileName}
+ upstreams={issued?.upstreams ?? []}
+ onDone={() => setSecretOpen(false)}
+ onClosed={() => setIssued(null)}
+ />
</Card>
)
}
diff --git a/web-studio/src/routes/gateway/-components/upstreams-page.tsx b/web-studio/src/routes/gateway/-components/upstreams-page.tsx
index 0e8efed1e..6034f7416 100644
--- a/web-studio/src/routes/gateway/-components/upstreams-page.tsx
+++ b/web-studio/src/routes/gateway/-components/upstreams-page.tsx
@@ -317,7 +317,7 @@ export function UpstreamsPage() {
}
/** What an import of OpenViking's model settings saved, and what needs a look. */
-function ImportResultNotice({
+export function ImportResultNotice({
result,
onDismiss,
}: {
diff --git a/web-studio/src/routes/gateway/-lib/quick-start.test.ts b/web-studio/src/routes/gateway/-lib/quick-start.test.ts
new file mode 100644
index 000000000..92ce41d30
--- /dev/null
+++ b/web-studio/src/routes/gateway/-lib/quick-start.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it } from 'vitest'
+
+import type { GatewayAccess, GatewayKey, Profile, Upstream } from './api'
+import { PROFILE_DEFAULTS } from './profile-schema'
+import { isQuickUsable, quickPlan, quickProfile } from './quick-start'
+import type { QuickInputs } from './quick-start'
+import { UPSTREAM_DEFAULTS } from './upstream-schema'
+
+function upstream(overrides: Partial<Upstream> = {}): Upstream {
+ return {
+ ...UPSTREAM_DEFAULTS,
+ id: 'vlm-ark',
+ revision: 1,
+ name: 'vlm-ark',
+ base_url: 'https://ark.example.com/api/v3',
+ models: ['doubao-seed-1-6'],
+ has_api_key: true,
+ ...overrides,
+ }
+}
+
+function profile(id: string, name: string): Profile {
+ return { ...PROFILE_DEFAULTS, id, name, revision: 1 }
+}
+
+const access = (overrides: Partial<GatewayAccess> = {}): GatewayAccess => ({
+ managed: false,
+ can_write_objects: true,
+ can_import_vlm: true,
+ can_issue_for_others: false,
+ role: 'user',
+ account_id: 'default',
+ user_id: 'default',
+ warnings: [],
+ ...overrides,
+})
+
+const key: GatewayKey = {
+ id: 'k1',
+ revision: 1,
+ name: 'Laptop',
+ policy_id: 'default',
+ upstream_ids: ['vlm-ark'],
+ models: [],
+ user_id: 'default',
+ prefix: 'ovgw_Ab3dE9x',
+ created_at: 1_700_000_000,
+}
+
+const usable = upstream()
+const recommended = profile('default', 'Default')
+const locked = access({
+ managed: true,
+ can_write_objects: false,
+ can_import_vlm: false,
+})
+
+function inputs(overrides: Partial<QuickInputs> = {}): QuickInputs {
+ return {
+ keys: [],
+ upstreams: [],
+ profiles: [],
+ access: access(),
+ readOnly: false,
+ gatewayHost: false,
+ ...overrides,
+ }
+}
+
+describe('isQuickUsable', () => {
+ it('accepts an enabled managed upstream with a key and models', () => {
+ expect(isQuickUsable(usable)).toBe(true)
+ expect(
+ isQuickUsable(upstream({ models: [], aliases: { fast: 'x' } })),
+ ).toBe(true)
+ expect(
+ isQuickUsable(upstream({ coding_plan: true, allow_coding_plan: true })),
+ ).toBe(true)
+ })
+
+ it.each([
+ ['disabled', { enabled: false }],
+ ['passthrough', { auth_mode: 'passthrough' as const }],
+ ['without an API key', { has_api_key: false }],
+ ['an unconfirmed Coding Plan', { coding_plan: true }],
+ ['without model names', { models: [] }],
+ ])('rejects an upstream %s', (_label, overrides) => {
+ expect(isQuickUsable(upstream(overrides))).toBe(false)
+ })
+})
+
+describe('quickProfile', () => {
+ it('prefers the default profile, else the first by name', () => {
+ const b = profile('p2', 'Beta')
+ const a = profile('p1', 'Alpha')
+ expect(quickProfile([b, recommended, a])).toBe(recommended)
+ expect(quickProfile([b, a])).toBe(a)
+ expect(quickProfile([])).toBeUndefined()
+ })
+})
+
+describe('quickPlan', () => {
+ it.each<
+ [string, Partial<QuickInputs>, { shown: boolean; runnable: boolean }]
+ >([
+ [
+ 'dev mode after seeding',
+ { upstreams: [usable], profiles: [recommended] },
+ { shown: true, runnable: true },
+ ],
+ ['an empty gateway that can import', {}, { shown: true, runnable: true }],
+ [
+ 'once a key exists',
+ { keys: [key], upstreams: [usable], profiles: [recommended] },
+ { shown: false, runnable: true },
+ ],
+ ['while keys load', { keys: undefined }, { shown: false, runnable: true }],
+ [
+ 'locked with an upstream and a profile',
+ {
+ access: locked,
+ readOnly: true,
+ upstreams: [usable],
+ profiles: [recommended],
+ },
+ { shown: true, runnable: true },
+ ],
+ [
+ 'locked without a profile on an embedded gateway',
+ { access: locked, readOnly: true, upstreams: [usable] },
+ { shown: true, runnable: false },
+ ],
+ [
+ 'locked without an upstream on an embedded gateway',
+ { access: locked, readOnly: true, profiles: [recommended] },
+ { shown: true, runnable: false },
+ ],
+ [
+ 'locked without an upstream on a standalone gateway',
+ { access: locked, readOnly: true, gatewayHost: true },
+ { shown: false, runnable: false },
+ ],
+ [
+ 'locked with an upstream but no profile on a standalone gateway',
+ {
+ access: locked,
+ readOnly: true,
+ gatewayHost: true,
+ upstreams: [usable],
+ },
+ { shown: true, runnable: false },
+ ],
+ [
+ 'a user who can neither import nor finds an upstream',
+ { access: access({ can_import_vlm: false }) },
+ { shown: false, runnable: false },
+ ],
+ [
+ 'only an unconfirmed Coding Plan upstream, without import',
+ {
+ access: access({ can_import_vlm: false }),
+ upstreams: [upstream({ coding_plan: true })],
+ profiles: [recommended],
+ },
+ { shown: false, runnable: false },
+ ],
+ ])('%s', (_label, overrides, expected) => {
+ const plan = quickPlan(inputs(overrides))
+ expect({ shown: plan.shown, runnable: plan.runnable }).toEqual(expected)
+ })
+
+ it('reports the upstreams, profile and owner it will use', () => {
+ const blocked = upstream({ id: 'cp', coding_plan: true })
+ const plan = quickPlan(
+ inputs({ upstreams: [blocked, usable], profiles: [recommended] }),
+ )
+ expect(plan.upstreams).toEqual([usable])
+ expect(plan.profile).toBe(recommended)
+ expect(plan.pickUser).toBe(false)
+ })
+
+ it('lets root outside dev mode pick the user', () => {
+ const root = access({ role: 'root', can_issue_for_others: true })
+ const devRoot = access({ role: 'root' })
+ expect(quickPlan(inputs({ access: root })).pickUser).toBe(true)
+ expect(quickPlan(inputs({ access: devRoot })).pickUser).toBe(false)
+ })
+})
diff --git a/web-studio/src/routes/gateway/-lib/quick-start.ts b/web-studio/src/routes/gateway/-lib/quick-start.ts
new file mode 100644
index 000000000..4c74f6fd2
--- /dev/null
+++ b/web-studio/src/routes/gateway/-lib/quick-start.ts
@@ -0,0 +1,73 @@
+import type { GatewayAccess, GatewayKey, Profile, Upstream } from './api'
+import { servedModels } from './upstream-schema'
+
+/** Id of the context profile quick mode creates and prefers. */
+export const QUICK_PROFILE_ID = 'default'
+
+/** An upstream a new key can relay to without further setup. */
+export function isQuickUsable(upstream: Upstream): boolean {
+ return (
+ upstream.enabled &&
+ upstream.auth_mode === 'managed' &&
+ upstream.has_api_key &&
+ servedModels(upstream).length > 0 &&
+ !(upstream.coding_plan && !upstream.allow_coding_plan)
+ )
+}
+
+/** The profile quick mode uses: `default`, else the first by name. */
+export function quickProfile(profiles: Profile[]): Profile | undefined {
+ return (
+ profiles.find((profile) => profile.id === QUICK_PROFILE_ID) ??
+ [...profiles].sort((a, b) => a.name.localeCompare(b.name))[0]
+ )
+}
+
+export type QuickInputs = {
+ keys: GatewayKey[] | undefined
+ upstreams: Upstream[] | undefined
+ profiles: Profile[] | undefined
+ access: GatewayAccess | undefined
+ readOnly: boolean
+ /** Studio is served by a standalone gateway, which can't import VLM settings. */
+ gatewayHost: boolean
+}
+
+export type QuickPlan = {
+ shown: boolean
+ /** Can run now; otherwise only unlocking the management key is offered. */
+ runnable: boolean
+ /** Usable upstreams the key will get; empty means import first. */
+ upstreams: Upstream[]
+ /** Existing profile to use; undefined means create the default one. */
+ profile?: Profile
+ /** Root outside dev mode can't hold a key, so it picks the key's user. */
+ pickUser: boolean
+}
+
+/** Whether and how the overview offers one-click setup before the first key. */
+export function quickPlan({
+ keys,
+ upstreams,
+ profiles,
+ access,
+ readOnly,
+ gatewayHost,
+}: QuickInputs): QuickPlan {
+ const usable = (upstreams ?? []).filter(isQuickUsable)
+ const profile = quickProfile(profiles ?? [])
+ const hasUpstream = usable.length > 0
+ const runnable =
+ (hasUpstream || Boolean(access?.can_import_vlm)) &&
+ (Boolean(profile) || !readOnly)
+ const locked = Boolean(access?.managed) && readOnly
+ const unlockable = locked && !runnable && (hasUpstream || !gatewayHost)
+ const loaded = Boolean(keys && upstreams && profiles && access)
+ return {
+ shown: loaded && !keys?.length && (runnable || unlockable),
+ runnable,
+ upstreams: usable,
+ profile,
+ pickUser: access?.role === 'root' && Boolean(access.can_issue_for_others),
+ }
+}