Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(web,server,core): import a provider's whole model listing when adding a group (#368)

Yaowei Zheng6089f7de705e
diff --git a/changelog/unreleased/2026-08-20-model-list-import.md b/changelog/unreleased/2026-08-20-model-list-import.md
new file mode 100644
index 00000000..b788fcf0
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-model-list-import.md
@@ -0,0 +1,20 @@
+# Add-group dialog imports a provider's whole model listing
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `web`, `server`, `core`
+- **PR:** [#368](https://github.com/Prism-Shadow/penguin-harness/pull/368)
+
+[中文版](2026-08-20-model-list-import.zh.md)
+
+The models page's "add group" dialog gained two modes. **Create only** keeps the light path: a valid name hands off to that group's add-model dialog. **Import models** fills the brand-new group from its endpoint in the add-model dialog's field rhythm — API key first, then the base URL with the detect action at its top-right and the in-field protocol picker as manual override; once a protocol is determined, **Import all models** fetches every model id the endpoint serves and appends them all as entries of the new group in one save, each carrying the base URL, protocol, and typed key inline.
+
+## Details
+
+- Listing rides on AgentHub 0.4.5's `listModels()` (agenthub [#183](https://github.com/Prism-Shadow/agenthub/pull/183)): core exposes a thin `listEndpointModels` wrapper over `AutoLLMClient`, and the server serves it as `POST /api/projects/:p/models/list` (owner-only, same base-URL validation and DTO discipline as `/detect`; listings are bounded at 20s).
+- An omitted API key follows the same environment chain as the connectivity test (`OPENAI_API_KEY` / `ANTHROPIC_API_KEY` per protocol). Keys travel only in request headers upstream and are never echoed.
+- Ids come back in the endpoint's own order. An entry is skipped and counted in the success toast when its id duplicates one already taken (within the listing, or an already-configured `(provider, model_id)` pair) or when the config could not hold it — empty, over the 200-character id bound, or carrying control characters — so one bad entry never sinks the whole import.
+- Only the id is taken from the endpoint: pricing, context window and display name stay empty rather than recording provider-reported numbers against the catalog's own pricing convention, and an imported model claims no vision support until it is probed or switched on, exactly like a model added to a user-defined group by hand.
+- A failed detection turns the protocol suffix amber and blocks nothing: the protocol can be picked by hand, or the dialog switched back to create-only. A protocol with no models endpoint (AgentHub `UnsupportedOperationError`) or an empty listing is reported inside the dialog; nothing is persisted until the listing succeeded.
+- User-defined group headers gained a **Delete group** action: one confirmation naming the group and its model count, then one table write removes every model in it, dropping a default/vision-model pointer into the deleted group the same way single-model delete does. Built-in groups are unaffected.
+- The connectivity test and the vision probe now send the lowest thinking level (`low`) instead of disabling thinking — several reasoning endpoints reject a request that turns thinking off outright, which failed the probe on the knob it sent rather than on the endpoint.
diff --git a/changelog/unreleased/2026-08-20-model-list-import.zh.md b/changelog/unreleased/2026-08-20-model-list-import.zh.md
new file mode 100644
index 00000000..9af98070
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-model-list-import.zh.md
@@ -0,0 +1,20 @@
+# 新增分组对话框可一键导入供应商全部模型
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `web`, `server`, `core`
+- **PR:** [#368](https://github.com/Prism-Shadow/penguin-harness/pull/368)
+
+[English](2026-08-20-model-list-import.md)
+
+模型页「新增分组」对话框改为两种模式。**仅新增分组**保留轻量路径:名称合法即进入该分组的新增模型对话框。**导入模型**沿用新增模型对话框的字段节奏按端点填满全新分组——先填 API key,再填 base URL,其右上方是「检测协议」动作,输入框内嵌的协议菜单可手动改选;协议确定后,**「批量导入模型」**获取该端点服务的全部模型 id,并在一次保存中把它们全部作为新分组的条目写入,每条内联携带 base URL、协议与所填 key。
+
+## 细节
+
+- 列表能力来自 AgentHub 0.4.5 的 `listModels()`(agenthub [#183](https://github.com/Prism-Shadow/agenthub/pull/183)):core 暴露对 `AutoLLMClient` 的薄封装 `listEndpointModels`,server 以 `POST /api/projects/:p/models/list` 对外提供(仅 owner,base URL 校验与 DTO 约束同 `/detect`;列表请求限时 20s)。
+- 省略 API key 时沿用连通性测试的环境变量链(按协议读取 `OPENAI_API_KEY` / `ANTHROPIC_API_KEY`)。key 只出现在上游请求头中,绝不回显。
+- 模型 id 按端点返回顺序保留。当某条 id 与已占用的 id 重复(列表内部重复,或与已配置的 `(provider, model_id)` 对撞),或配置根本无法承载(为空、超过 200 字符的 id 长度上限、含控制字符)时,该条会被跳过并计入成功提示,单个坏条目不会让整次导入失败。
+- 端点那边只取 id:价格、上下文窗口与显示名一律留空,不把供应商自报的数字写进遵循内置目录定价约定的字段;导入的模型在被探测或手动打开之前不声明视觉能力——与手动往自建分组添加模型完全一致。
+- 检测失败只把协议后缀转为琥珀色、不阻塞任何操作:可手动选定协议,或切回仅新增分组。协议不支持列出模型(AgentHub `UnsupportedOperationError`)或列表为空时,错误在对话框内呈现;列表成功之前不落盘任何内容。
+- 自建分组的组头新增**「删除分组」**动作:一次确认(写明分组与组内模型数)后,一次整表写入移除组内全部模型;指向被删分组的默认模型 / vision 模型指针按单模型删除的既有规则一并清除。内置分组不受影响。
+- 连通性测试与视觉探测改为发送最低思考等级(`low`)而非关闭思考——部分推理端点会拒绝显式关闭思考的请求,导致探测败在自己所发的参数而非端点本身。
diff --git a/packages/core/src/llm/index.ts b/packages/core/src/llm/index.ts
index a763affe..63316da0 100644
--- a/packages/core/src/llm/index.ts
+++ b/packages/core/src/llm/index.ts
@@ -22,6 +22,8 @@ export {
toolDefinitionsToSchemas,
buildUniConfig,
} from "./generative-model.js";
+export { listEndpointModels } from "./list-models.js";
+export type { ListEndpointModelsOptions } from "./list-models.js";
export { ToolCallIdAllocator, stripToolCallIdSuffix } from "./tool-call-ids.js";
export {
DEFAULT_CONTEXT_WINDOW,
diff --git a/packages/core/src/llm/list-models.ts b/packages/core/src/llm/list-models.ts
new file mode 100644
index 00000000..0cf83f79
--- /dev/null
+++ b/packages/core/src/llm/list-models.ts
@@ -0,0 +1,44 @@
+/**
+ * Endpoint model listing — the thin core wrapper over `AutoLLMClient.listModels()`.
+ *
+ * Exists so hosts (the server's models routes) can enumerate what an endpoint serves
+ * without depending on AgentHub directly: core mediates the AgentHub boundary, AgentHub
+ * owns the client and the per-protocol `/models` call. Routed through a **generic protocol
+ * client type** (`openai-responses` / `ant-messages` / `openai-chat`), the listing is the
+ * endpoint's whole catalog; routed through a vendor-pinned type, AgentHub filters the ids
+ * down to that client's own models, and a client with no models endpoint rejects with its
+ * `UnsupportedOperationError` (recognizable by `err.name`).
+ *
+ * Credential semantics mirror the connectivity test: an omitted `apiKey` lets the wrapped
+ * SDK read the protocol's own environment variable (`OPENAI_API_KEY` / `ANTHROPIC_API_KEY`),
+ * and a missing credential surfaces as the SDK's own construction/request error — callers
+ * collapse errors into their outcome shape, nothing is caught here.
+ */
+import { AutoLLMClient } from "@prismshadow/agenthub";
+
+/** One endpoint listing request: which protocol to speak, and the credential/URL to speak it with. */
+export interface ListEndpointModelsOptions {
+ /** AgentHub client type to route through (the add-group flow passes a detected generic protocol). */
+ clientType: string;
+ /** Plaintext API key; omitted = the SDK's environment fallback for the protocol. */
+ apiKey?: string;
+ /** Endpoint base URL; omitted = the vendor default of the routed client. */
+ baseUrl?: string;
+}
+
+/**
+ * Lists the model ids the endpoint serves, in the order the endpoint returned them.
+ * Throws whatever AgentHub or the wrapped SDK throws (unsupported operation, auth,
+ * network); bounding the call in time is the caller's concern.
+ */
+export async function listEndpointModels(options: ListEndpointModelsOptions): Promise<string[]> {
+ const client = new AutoLLMClient({
+ // AutoLLMClient routes by clientType when given one; model is its fallback routing key
+ // and must still be a string, so the client type doubles as it.
+ model: options.clientType,
+ clientType: options.clientType,
+ ...(options.apiKey ? { apiKey: options.apiKey } : {}),
+ ...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
+ });
+ return client.listModels();
+}
diff --git a/packages/core/test/list-endpoint-models.test.ts b/packages/core/test/list-endpoint-models.test.ts
new file mode 100644
index 00000000..5f964d69
--- /dev/null
+++ b/packages/core/test/list-endpoint-models.test.ts
@@ -0,0 +1,67 @@
+/**
+ * listEndpointModels: the thin AgentHub wrapper — routes by the given client type,
+ * forwards credential/base URL only when present, and returns the listing verbatim
+ * (order preserved, no dedup: presentation policy belongs to callers).
+ */
+import { describe, expect, it, vi } from "vitest";
+
+const captured = vi.hoisted(() => ({
+ options: [] as Record<string, unknown>[],
+ listing: ["gpt-a", "gpt-b", "gpt-a"],
+ fail: undefined as Error | undefined,
+}));
+
+vi.mock("@prismshadow/agenthub", async (importOriginal) => {
+ const mod = await importOriginal<typeof import("@prismshadow/agenthub")>();
+ class FakeAutoLLMClient {
+ constructor(options: Record<string, unknown>) {
+ captured.options.push(options);
+ }
+ async listModels(): Promise<string[]> {
+ if (captured.fail) throw captured.fail;
+ return captured.listing;
+ }
+ }
+ return { ...mod, AutoLLMClient: FakeAutoLLMClient };
+});
+
+const { listEndpointModels } = await import("../src/llm/list-models.js");
+
+describe("listEndpointModels", () => {
+ it("routes by the client type (model doubles as the routing key) and returns the listing verbatim", async () => {
+ captured.options.length = 0;
+ const models = await listEndpointModels({
+ clientType: "openai-chat",
+ apiKey: "sk-list-1",
+ baseUrl: "https://gw.example/v1",
+ });
+ expect(models).toEqual(["gpt-a", "gpt-b", "gpt-a"]);
+ expect(captured.options).toEqual([
+ {
+ model: "openai-chat",
+ clientType: "openai-chat",
+ apiKey: "sk-list-1",
+ baseUrl: "https://gw.example/v1",
+ },
+ ]);
+ });
+
+ it("omits absent credential and base URL so the SDK's environment fallback applies", async () => {
+ captured.options.length = 0;
+ await listEndpointModels({ clientType: "ant-messages" });
+ expect(captured.options).toEqual([{ model: "ant-messages", clientType: "ant-messages" }]);
+ });
+
+ it("propagates AgentHub errors unchanged (callers collapse them into their outcome shape)", async () => {
+ captured.fail = Object.assign(new Error("listing models is not supported"), {
+ name: "UnsupportedOperationError",
+ });
+ try {
+ await expect(listEndpointModels({ clientType: "claude-5" })).rejects.toMatchObject({
+ name: "UnsupportedOperationError",
+ });
+ } finally {
+ captured.fail = undefined;
+ }
+ });
+});
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index 59fbc3ff..98fc8fe0 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -97,8 +97,11 @@ Probes are minimal invalid requests (`{}` bodies): they cost no tokens and need
The probe credential is resolved server-side in three layers: the API key typed in the dialog, else the key already stored for this entry, else the environment variable belonging to the protocol **that probe** speaks — `ANTHROPIC_API_KEY` for `ant-messages`, `OPENAI_API_KEY` for the two OpenAI protocols, the same variables the saved model would read. Resolution happens per probe precisely because the protocol is the thing being determined. None of these values are ever sent to the browser or echoed in the response. Detection still works with no credential anywhere — a protocol-shaped `401` identifies the route perfectly well — but an authenticated probe is far likelier to draw that protocol-shaped answer than the generic `401` or gateway HTML an anonymous request often gets.
The manual override is the protocol path shown inside the right edge of the base URL field (`/responses`, `/v1/messages`, `/chat/completions`) — the path the client appends to your URL, which is one-to-one with the protocol. Clicking it opens a menu of the three protocols with the path each one appends, and picking one wins over detection — so an endpoint you already know the protocol of never has to be probed at all. Whenever detection fails — unreachable, timed out, non-API answers, or none of the three paths served — the suffix turns amber and one toast says the same thing: the protocol could not be detected, check the API key and the base URL. The per-protocol probe outcomes are still reported by the endpoint for debugging. Entries from before this feature keep `client_type = "openai"` — still an alias of `openai-chat` — and are only rewritten when you pick a protocol or a detection run applies. Detection is exposed as `POST /api/projects/:id/models/detect` (owner only, see [Server API](/server-api)).
+
Nothing is inferred from the model id in these groups. Typing `claude-sonnet-5` into a custom group does not imply the Anthropic client or its `ANTHROPIC_*` key — custom and user-defined groups always fall back to the compatible client (`openai-chat`), and that is what the API-key hint reflects. Detection is an accuracy improvement on top, never a gate: if it comes back empty the model still saves, on `openai-chat`, with a toast saying so. Vendor and gateway groups are unaffected — their ids are catalog-known, so they keep routing by id or by their preset pin.
+The add-group dialog offers two modes under the name field. **Create only** is the light path: a valid name hands off to that group's add-model dialog. **Import models** fills the brand-new group from its endpoint, in the add-model dialog's field rhythm — API key first, then the base URL with **Detect** at its top-right and the in-field protocol picker as manual override. Once a protocol is determined (detected or picked), **Import all models** appears: it asks the endpoint for every model id it serves (`POST /api/projects/:id/models/list`, owner only — AgentHub's `listModels()` on that protocol client, bounded at 20s) and saves them all as entries of the new group in one table write — base URL, protocol, and the typed key inline on each — in the endpoint's own order. An id the config cannot hold (empty, over 200 characters, or carrying control characters) or one already taken is skipped and counted in the toast, so a single bad entry never sinks the import. Only the id is taken from the endpoint: pricing, context window and display name stay empty, and an imported model claims no vision support until you probe it or switch it on — the same start a model added to the group by hand gets. An empty key follows the same per-protocol environment fallback as everywhere else. A failed detection turns the suffix amber and blocks nothing — pick the protocol by hand or switch back to create-only; listing failures (a protocol with no models endpoint, an empty listing) stay inside the dialog and persist nothing.
+
### Vision detection
"Supports vision" can be left off and asked of the model instead: **Detect** next to the switch sends one 1x1 PNG with a one-word prompt and turns the switch on if the model answers. A model that answers specifically that it will not take an image turns the switch off — that is a real answer, not an error — while a probe that fails on auth or the network leaves the switch exactly as you had it and shows the usual "check the API key and the base URL".
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index d0ce6482..59b85ba2 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -97,8 +97,11 @@ Custom 与自建分组走 AgentHub 的通用协议客户端,Web 对话框会
探测所用凭据在服务端按三层依次解析:对话框里填的 API Key,其次该条目已保存的密钥,最后是**当前这个探测**所用协议对应的环境变量——`ant-messages` 读 `ANTHROPIC_API_KEY`,两个 OpenAI 协议读 `OPENAI_API_KEY`,与保存后模型实际读取的是同一批变量。之所以逐个探测分别解析,正是因为协议本身还没确定。这些值都不会回传浏览器,也不会出现在响应里。完全没有凭据时检测同样可用——协议形态的 `401` 足以认出路由——但带上鉴权的探测,远比匿名请求更容易拿到那种协议形态的应答,而不是笼统的 `401` 或网关 HTML。
手动覆盖入口是 base URL 输入框右端内嵌的那段协议路径(`/responses`、`/v1/messages`、`/chat/completions`)——客户端会追加到你填的 URL 之后,与协议一一对应。点开它即列出三种协议及各自追加的路径,手动选择优先于检测结果——已经知道协议的端点根本不必探测。只要检测失败——连不上、超时、返回的不是 API 响应、三条路径都没提供——该后缀就转为琥珀色,并统一以 toast 提示同一句话:无法检测接口协议,请检查 API Key 与 base URL。逐个协议的探测结果仍由该接口返回,便于排查。此前创建的条目保留 `client_type = "openai"`(仍是 `openai-chat` 的别名),只有手动选择或检测生效时才会改写。检测能力以 `POST /api/projects/:id/models/detect` 暴露(仅 owner,见 [Server API](/server-api))。
+
这些分组不会从 model id 推断任何东西。在自定义分组里填 `claude-sonnet-5` 不代表就走 Anthropic 客户端、读 `ANTHROPIC_*`——Custom 与自建分组一律回退到兼容客户端(`openai-chat`),API Key 提示也据此显示。检测只是锦上添花,不是关卡:若检测无结果,模型仍会按 `openai-chat` 保存,并以 toast 说明。厂商与网关分组不受影响——它们的 id 在内置目录里,仍按 id 路由或沿用预设。
+「新增分组」对话框在分组名下方提供两种模式。**仅新增分组**是轻量路径:名称合法即进入该分组的新增模型对话框。**导入模型**按端点填满全新分组,沿用新增模型对话框的字段节奏——先填 API key,再填 base URL,其右上方是「检测协议」,输入框内嵌的协议菜单可手动改选。协议确定后(检测命中或手动选定)出现**「批量导入模型」**:向端点询问它服务的全部模型 id(`POST /api/projects/:id/models/list`,仅 owner——在该协议客户端上调用 AgentHub 的 `listModels()`,限时 20s),并在一次整表写入中把它们全部存为新分组的条目——base URL、协议与所填 key 内联在每条上——顺序保持端点返回的顺序。配置无法承载的 id(为空、超过 200 字符、含控制字符)以及已被占用的 id 会被跳过并计入 toast,因此单个坏条目不会让整次导入失败。端点那边只取 id:价格、上下文窗口与显示名一律留空;导入的模型在你探测或手动打开之前不声明视觉能力——与手动往该分组添加模型的起点完全一致。key 留空时沿用各处一致的按协议环境变量回退。检测失败只把后缀转为琥珀色、不阻塞任何操作——可手动选协议继续,或切回仅新增分组;列表失败(协议不支持列出模型、列表为空)只在对话框内呈现且不落盘。
+
### 视觉能力检测
「支持视觉」可以先不开,交给模型自己回答:开关旁边的「检测」会发送一张 1x1 的 PNG 和一句一个词的提示,模型能正常作答就把开关打开。若模型明确回答不接受图片,则关闭开关——这是一个真实答案,不是错误;而因鉴权或网络失败的探测则什么都不改动,只显示那句「请检查 API Key 与 base URL」。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 81fdca03..b6a131af 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -122,6 +122,7 @@ Member writes are owner-only. The member routes also answer `403 desktop_single_
| PUT | /api/projects/:projectId/models | Full-table replace, keyed by `(provider, modelId)` |
| POST | /api/projects/:projectId/models/test | Connectivity test: `{provider, modelId, …}` → `{ok, latencyMs?, message?}` |
| POST | /api/projects/:projectId/models/detect | Protocol auto-detection for a custom base URL: probes `openai-responses` → `ant-messages` → `openai-chat` in order and reports the first served protocol: `{baseUrl, apiKey?, …}` → `{detected?, probes}` |
+| POST | /api/projects/:projectId/models/list | Endpoint model listing for the add-group import: the ids the endpoint serves on a detected protocol: `{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}` |
| POST | /api/projects/:projectId/models/detect-vision | Vision capability probe: sends one 1x1 image on this model's credential (a real, billed completion): `{provider, modelId, apiKey?, baseUrl?, clientType?}` → `{outcome: supported\|unsupported\|failed, message?}` |
Every endpoint that names a model takes the complete `(provider, modelId)` pair. Nothing is inferred: a request carrying only one half is a 400, never a lookup. Where the reference itself is optional (Session creation, Schedules), omitting both halves selects the Project's default model.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 2f452730..411ee746 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -122,6 +122,7 @@ curl -c cookies.txt -H "Content-Type: application/json" \
| PUT | /api/projects/:projectId/models | 全表替换,条目以 `(provider, modelId)` 为键 |
| POST | /api/projects/:projectId/models/test | 连通性测试:`{provider, modelId, …}` → `{ok, latencyMs?, message?}` |
| POST | /api/projects/:projectId/models/detect | 自定义 base URL 的协议自动检测:按 `openai-responses` → `ant-messages` → `openai-chat` 顺序探测并返回第一个被提供的协议:`{baseUrl, apiKey?, …}` → `{detected?, probes}` |
+| POST | /api/projects/:projectId/models/list | 新增分组导入所用的端点模型列表:按检测出的协议列出端点服务的全部模型 id:`{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}` |
| POST | /api/projects/:projectId/models/detect-vision | 视觉能力探测:用该模型的凭据发送一张 1x1 图片(一次真实计费的补全):`{provider, modelId, apiKey?, baseUrl?, clientType?}` → `{outcome: supported\|unsupported\|failed, message?}` |
所有涉及模型的接口都要求完整的 `(provider, modelId)` 二元组,不做任何推断:只带一半的请求一律 400,绝不会退化为一次查找。模型引用本身可省略的场景(创建 Session、定时任务)省略的是整对,两半都不给即选用 Project 默认模型。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 8887edd0..829a4690 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -572,6 +572,31 @@ export interface ModelProtocolDetectResponse {
probes: ModelProtocolProbeDto[];
}
+/**
+ * Endpoint model listing (POST /api/projects/:p/models/list, owner): given a base URL and
+ * the protocol `/detect` reported, returns every model id the endpoint serves (AgentHub's
+ * `listModels()` on the routed client). Used by the add-group dialog to import a provider's
+ * whole listing in one go; the ids come back in the endpoint's own order.
+ */
+export interface EndpointModelListRequest {
+ /** Endpoint base URL (as typed in the add-group dialog). */
+ baseUrl: string;
+ /** AgentHub client type to speak (normally a detected generic protocol; whole-endpoint listings need one). */
+ clientType: string;
+ /** Newly entered API key (plaintext); omitted = the SDK's environment fallback for the protocol. */
+ apiKey?: string;
+}
+
+/** Listing outcome: model ids on success, a truncated provider/SDK reason otherwise. */
+export interface EndpointModelListResponse {
+ ok: boolean;
+ /** The model ids the endpoint serves, in the order the endpoint returned them (ok only). */
+ models?: string[];
+ /** The routed client has no models endpoint (AgentHub UnsupportedOperationError) — callers offer the manual path. */
+ unsupported?: boolean;
+ message?: string;
+}
+
/**
* PUT /api/projects/:p/models/default (owner): narrow default-model switch — flips the same
* top-level `default_model` the models page's whole-table PUT writes, without resending the
diff --git a/packages/server/src/http/routes/models.ts b/packages/server/src/http/routes/models.ts
index 2802b73e..ca7e8722 100644
--- a/packages/server/src/http/routes/models.ts
+++ b/packages/server/src/http/routes/models.ts
@@ -2,7 +2,7 @@
* Model & credential config routes:
* GET|PUT /api/projects/:p/models, PUT /api/projects/:p/models/default,
* POST /api/projects/:p/models/test, POST /api/projects/:p/models/detect,
- * POST /api/projects/:p/models/detect-vision (the model
+ * POST /api/projects/:p/models/list, POST /api/projects/:p/models/detect-vision (the model
* reference `(provider, modelId)` is sent as a pair in the request body, avoiding
* URL-encoding issues). Any member can read (api_key is masked); only the owner can
* modify, test, or detect.
@@ -10,6 +10,7 @@
import { Hono } from "hono";
import type {
DefaultModelResponse,
+ EndpointModelListRequest,
ModelProtocolDetectRequest,
ModelRefDto,
ModelsUpdateRequest,
@@ -280,6 +281,28 @@ export function modelsRoutes(deps: AppDeps): Hono<AppEnv> {
return c.json(await deps.projectConfigService.detectProtocol(projectId, req));
});
+ // Endpoint model listing (owner): given a base URL plus the protocol /detect reported,
+ // returns every model id the endpoint serves (AgentHub's listModels() on the routed
+ // client) so the add-group dialog can import a provider's whole listing in one go.
+ // Owner-only and server-fetches-a-caller-URL for exactly the reasons /detect documents
+ // above; like /detect, the reply is reduced to a DTO (ids / outcome flags / truncated
+ // reason) and the key travels only in request headers upstream.
+ app.post("/list", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ const body = await readJson(c);
+ const req: EndpointModelListRequest = {
+ baseUrl: requireString(body, "baseUrl", { minLen: 1, maxLen: 2000 }),
+ clientType: requireString(body, "clientType", { minLen: 1, maxLen: 64 }),
+ };
+ if (!isHttpUrl(req.baseUrl)) throw badRequest("baseUrl must be an absolute http(s) URL.");
+ if (body.apiKey !== undefined) {
+ if (typeof body.apiKey !== "string") throw badRequest("apiKey must be a string.");
+ if (body.apiKey) req.apiKey = body.apiKey;
+ }
+ return c.json(await deps.projectConfigService.listEndpointModels(req));
+ });
+
/**
* Vision capability probe (owner only). Body mirrors the connectivity test's, since the
* probe is one real completion on the same credential — see detectVision. Owner-only for
diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.ts
index 38ee1212..991e6962 100644
--- a/packages/server/src/services/project-config-service.ts
+++ b/packages/server/src/services/project-config-service.ts
@@ -31,6 +31,7 @@ import {
DEFAULT_CHAT_THINKING_LEVELS,
GenerativeModel,
canonicalClientType,
+ listEndpointModels as coreListEndpointModels,
catalogEntryFor,
defaultProjectConfig,
imageUrlMessage,
@@ -43,6 +44,8 @@ import {
import type { LLMOutcome, ModelRef, OmniMessage, ProjectConfig } from "@prismshadow/penguin-core";
import type {
ChatDefaultsDto,
+ EndpointModelListRequest,
+ EndpointModelListResponse,
ModelInfo,
ModelPricingDto,
ModelProtocolDetectRequest,
@@ -132,6 +135,13 @@ function showRef(provider: string, modelId: string): string {
const PROBE_PROMPT =
'ping - reply with the single word "pong" and nothing else. Do not think or explain.\n<think></think>';
+/**
+ * Endpoint model-listing bound: the SDK paginates `/models` under the hood, so one slow
+ * or endless gateway must not pin the add-group dialog — 20s matches the connectivity
+ * test's request timeout.
+ */
+const LIST_MODELS_TIMEOUT_MS = 20_000;
+
/**
* Speed probe prompt: a one-word answer can't be timed (a compliant model emits 1-3
* tokens, and the window is then dominated by the final usage chunk's round trip), so
@@ -393,15 +403,15 @@ export class ProjectConfigService {
* Model connectivity test: the model reference `(provider, modelId)` is submitted
* as a pair in the request body; sends one minimal request using that model's
* config (optionally overridden with an unsaved apiKey / baseUrl) — no tools, no
- * system prompt, thinking disabled, a tiny output cap, 20s timeout — just to see
- * whether the endpoint answers. The model id sent to AgentHub is `modelId`
- * itself (the upstream id verbatim; client_type inference follows it).
+ * system prompt, thinking at the lowest level, a tiny output cap, 20s timeout —
+ * just to see whether the endpoint answers. The model id sent to AgentHub is
+ * `modelId` itself (the upstream id verbatim; client_type inference follows it).
*
- * A reasoning-heavy model may ignore the disabled thinking level and burn the
- * whole tiny output cap on thinking (finish_reason=length with no text — AgentHub
- * raises EmptyResponseError, collapsed to a malformed outcome): the endpoint
- * demonstrably streamed model output, which is everything a connectivity test
- * proves, so that case counts as ok too (see probeVerdict).
+ * A reasoning-heavy model can spend the whole tiny output cap on thinking
+ * (finish_reason=length with no text — AgentHub raises EmptyResponseError,
+ * collapsed to a malformed outcome): the endpoint demonstrably streamed model
+ * output, which is everything a connectivity test proves, so that case counts as
+ * ok too (see probeVerdict).
*
* Never throws: the LLM layer collapses auth/parameter/network errors into an
* `LLMOutcome`, which is translated here into ok / message. Consumes very few
@@ -440,7 +450,9 @@ export class ProjectConfigService {
...(baseUrl ? { baseUrl } : {}),
...(clientType ? { clientType } : {}),
tools: [],
- thinkingLevel: "none",
+ // The lowest real level, not "none": several reasoning endpoints reject a request
+ // that disables thinking outright, and a probe must not fail on the knob it sends.
+ thinkingLevel: "low",
maxTokens: VISION_PROBE_MAX_TOKENS,
requestTimeoutMs: VISION_PROBE_TIMEOUT_MS,
});
@@ -506,7 +518,9 @@ export class ProjectConfigService {
...(clientType ? { clientType } : {}),
...(fastMode ? { fastMode: true } : {}),
tools: [],
- thinkingLevel: "none",
+ // The lowest real level, not "none": several reasoning endpoints reject a request
+ // that disables thinking outright, and a probe must not fail on the knob it sends.
+ thinkingLevel: "low",
// Speed mode pairs a raised cap with a prompt that keeps generating (see
// SPEED_PROBE_PROMPT), so the stream lasts long enough for TTFT/TPS to describe
// decoding rather than one round trip; the plain connectivity test keeps the
@@ -584,6 +598,50 @@ export class ProjectConfigService {
return detectModelProtocol({ baseUrl: req.baseUrl, ...(apiKey ? { apiKey } : {}) });
}
+ /**
+ * Endpoint model listing for the add-group import (see EndpointModelListRequest). All
+ * parameters come from the request — a group being created has no stored entry to fall
+ * back to; an omitted key follows the same environment chain as the connectivity test
+ * (the wrapped SDK reads the protocol's own variable). Never throws: SDK construction
+ * and request failures collapse into `{ ok:false, message }`, an AgentHub
+ * UnsupportedOperationError additionally sets `unsupported` so the dialog can point at
+ * the manual path, and a listing that outlives LIST_MODELS_TIMEOUT_MS is reported as
+ * timed out. Nothing cancels the request behind it: the race only stops waiting, and a
+ * later rejection is already handled by the race itself. The listing is returned
+ * verbatim; dedup against the config is the caller's policy, exactly like the probe
+ * routes never write anything either.
+ */
+ async listEndpointModels(
+ req: EndpointModelListRequest,
+ listImpl: typeof coreListEndpointModels = coreListEndpointModels,
+ timeoutMs: number = LIST_MODELS_TIMEOUT_MS,
+ ): Promise<EndpointModelListResponse> {
+ const clientType = canonicalClientType(req.clientType) ?? req.clientType;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const listing = listImpl({
+ clientType,
+ baseUrl: req.baseUrl,
+ ...(req.apiKey ? { apiKey: req.apiKey } : {}),
+ });
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error("model listing timed out")), timeoutMs);
+ timer.unref?.();
+ });
+ const models = await Promise.race([listing, timeout]);
+ return { ok: true, models };
+ } catch (err) {
+ const unsupported = err instanceof Error && err.name === "UnsupportedOperationError";
+ return {
+ ok: false,
+ ...(unsupported ? { unsupported: true } : {}),
+ message: (err instanceof Error ? err.message : String(err)).slice(0, 300),
+ };
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+ }
+
/**
* GET models view: masks credential (inline fields), flags the default Model;
* the group is the entry's `provider` field, looked up in the built-in catalog by
@@ -856,11 +914,10 @@ export function isProbeContent(msg: OmniMessage): boolean {
/**
* Probe verdict from the terminal LLM outcome. `completed` always passes. A `malformed`
* ending after genuine streamed content also passes: the typical case is a reasoning-heavy
- * model that ignores the disabled thinking level and burns the probe's tiny max_tokens
- * entirely on thinking (finish_reason=length -> AgentHub's EmptyResponseError) — the
- * endpoint, credential, and model id all demonstrably work, which is what a connectivity
- * test measures. Everything else (auth/parameter failures, timeouts, malformed with nothing
- * received) fails with the outcome's message.
+ * model that spends the probe's tiny max_tokens entirely on thinking (finish_reason=length ->
+ * AgentHub's EmptyResponseError) — the endpoint, credential, and model id all demonstrably
+ * work, which is what a connectivity test measures. Everything else (auth/parameter failures,
+ * timeouts, malformed with nothing received) fails with the outcome's message.
*/
export function probeVerdict(
outcome: LLMOutcome,
diff --git a/packages/server/test/models-list.test.ts b/packages/server/test/models-list.test.ts
new file mode 100644
index 00000000..d07246ff
--- /dev/null
+++ b/packages/server/test/models-list.test.ts
@@ -0,0 +1,135 @@
+/**
+ * Endpoint model listing (POST /api/projects/:p/models/list): the service collapses every
+ * failure into `{ ok:false }` (UnsupportedOperationError additionally flagged, listings
+ * bounded in time), and the route validates shape/ownership before anything is fetched.
+ */
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { mkdtemp, rm } from "node:fs/promises";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { EndpointModelListResponse, ProjectCreateResponse } from "../src/api/types.js";
+import { ProjectConfigService } from "../src/services/project-config-service.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+describe("ProjectConfigService.listEndpointModels", () => {
+ let root: string;
+ let service: ProjectConfigService;
+
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(tmpdir(), "penguin-models-list-"));
+ service = new ProjectConfigService(root);
+ });
+ afterEach(async () => {
+ await rm(root, { recursive: true, force: true });
+ });
+
+ const req = { baseUrl: "https://gw.example/v1", clientType: "openai", apiKey: "sk-l1" };
+
+ it("returns the listing verbatim and canonicalizes the legacy openai spelling", async () => {
+ const calls: unknown[] = [];
+ const res = await service.listEndpointModels(req, async (options) => {
+ calls.push(options);
+ return ["m-b", "m-a", "m-b"];
+ });
+ expect(res).toEqual({ ok: true, models: ["m-b", "m-a", "m-b"] });
+ expect(calls).toEqual([
+ { clientType: "openai-chat", baseUrl: "https://gw.example/v1", apiKey: "sk-l1" },
+ ]);
+ });
+
+ it("omits an absent key so the SDK's environment fallback applies", async () => {
+ const calls: Record<string, unknown>[] = [];
+ await service.listEndpointModels(
+ { baseUrl: req.baseUrl, clientType: "ant-messages" },
+ async (options) => {
+ calls.push(options as unknown as Record<string, unknown>);
+ return [];
+ },
+ );
+ expect(calls[0]).toEqual({ clientType: "ant-messages", baseUrl: "https://gw.example/v1" });
+ });
+
+ it("flags AgentHub's UnsupportedOperationError so the dialog can point at the manual path", async () => {
+ const res = await service.listEndpointModels(req, async () => {
+ throw Object.assign(new Error("Claude5Client cannot list models"), {
+ name: "UnsupportedOperationError",
+ });
+ });
+ expect(res.ok).toBe(false);
+ expect(res.unsupported).toBe(true);
+ expect(res.message).toBe("Claude5Client cannot list models");
+ });
+
+ it("collapses SDK failures into ok:false with the reason truncated", async () => {
+ const res = await service.listEndpointModels(req, async () => {
+ throw new Error("x".repeat(400));
+ });
+ expect(res.ok).toBe(false);
+ expect(res.unsupported).toBeUndefined();
+ expect(res.message).toHaveLength(300);
+ });
+
+ it("reports a listing that outlives the bound as timed out", async () => {
+ const res = await service.listEndpointModels(req, () => new Promise<string[]>(() => {}), 10);
+ expect(res).toEqual({ ok: false, message: "model listing timed out" });
+ });
+});
+
+describe("POST /api/projects/:p/models/list route validation", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let projectId: string;
+ const url = () => `/api/projects/${projectId}/models/list`;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const { cookie } = await provisionUser(t.app, "alice");
+ api = apiClient(t.app, cookie);
+ const created = (await (
+ await api.post("/api/projects", { projectId: "alice-list", name: "List project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("rejects a non-http(s) base URL and a missing clientType before anything is fetched", async () => {
+ const noProto = await api.post(url(), { baseUrl: "gw.example/v1", clientType: "openai-chat" });
+ expect(noProto.status).toBe(400);
+ const noType = await api.post(url(), { baseUrl: "https://gw.example/v1" });
+ expect(noType.status).toBe(400);
+ const badKey = await api.post(url(), {
+ baseUrl: "https://gw.example/v1",
+ clientType: "openai-chat",
+ apiKey: 42,
+ });
+ expect(badKey.status).toBe(400);
+ });
+
+ it("is owner-only, like the other probe routes", async () => {
+ const { cookie } = await provisionUser(t.app, "bob");
+ const member = apiClient(t.app, cookie);
+ const res = await member.post(url(), {
+ baseUrl: "https://gw.example/v1",
+ clientType: "openai-chat",
+ });
+ expect([403, 404]).toContain(res.status);
+ });
+
+ it("responds with the service's DTO shape (fed by a stubbed lister)", async () => {
+ const original = t.deps.projectConfigService.listEndpointModels.bind(
+ t.deps.projectConfigService,
+ );
+ t.deps.projectConfigService.listEndpointModels = (r) => original(r, async () => ["m-1", "m-2"]);
+ const res = await api.post(url(), {
+ baseUrl: "https://gw.example/v1",
+ clientType: "openai-chat",
+ apiKey: "sk-route-1",
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as EndpointModelListResponse;
+ expect(body).toEqual({ ok: true, models: ["m-1", "m-2"] });
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index daf67eb2..c320b334 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -32,6 +32,8 @@ import type {
DefaultModelResponse,
DefaultModelUpdateRequest,
DirListResponse,
+ EndpointModelListRequest,
+ EndpointModelListResponse,
FilesStatRequest,
FilesStatResponse,
GoalResponse,
@@ -218,6 +220,13 @@ export const detectProtocol = (projectId: string, body: ModelProtocolDetectReque
{ method: "POST", body },
);
+/** Endpoint model listing: given a base URL plus the protocol /detect reported, returns every model id the endpoint serves (the add-group import). */
+export const listEndpointModels = (projectId: string, body: EndpointModelListRequest) =>
+ apiFetch<EndpointModelListResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/models/list`,
+ { method: "POST", body },
+ );
+
/** Vision probe: sends one 1x1 image on this model's credential and reports whether it was accepted (a real, billed completion — unlike the protocol probes). */
export const detectVision = (projectId: string, body: ModelVisionDetectRequest) =>
apiFetch<ModelVisionDetectResponse>(
diff --git a/packages/web/src/features/models/group-import.ts b/packages/web/src/features/models/group-import.ts
new file mode 100644
index 00000000..68643e3c
--- /dev/null
+++ b/packages/web/src/features/models/group-import.ts
@@ -0,0 +1,102 @@
+/**
+ * Add-group bulk import: turns an endpoint's model listing (POST models/list) into new
+ * rows for the user-defined group being created. Every imported row carries the group's
+ * endpoint config inline — base URL, the detected protocol, and the typed key when there
+ * is one — matching how the config stores per-entry credentials (the bulk-key dialog
+ * writes groups the same way). The listing arrives in the endpoint's own order and is kept
+ * in it; entries that produce no row are counted for the toast (see buildImportedRows).
+ */
+import type { RowState } from "./models-page";
+
+/** Endpoint config every imported row inherits (from the add-group dialog's fields). */
+export interface GroupImportConfig {
+ baseUrl: string;
+ clientType: string;
+ apiKey: string;
+}
+
+/**
+ * Longest model id the models PUT accepts. One over-long id would 400 the whole table
+ * write, so the listing is filtered here rather than letting one entry sink the import.
+ */
+const MAX_MODEL_ID_LENGTH = 200;
+
+/** C0 controls and DEL: invisible on screen, but they would reach the config file and the upstream request path. */
+const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
+
+/**
+ * The usable model id inside one listing entry, or null when there is none. The listing is
+ * whatever the endpoint's `/models` served, so nothing in it is trusted: an entry has to
+ * survive trimming, stay within the config's id bound, and carry no control characters
+ * before it may become half of a `(provider, modelId)` key.
+ */
+function usableModelId(entry: string): string | null {
+ if (typeof entry !== "string") return null;
+ const modelId = entry.trim();
+ if (modelId === "" || modelId.length > MAX_MODEL_ID_LENGTH) return null;
+ if (CONTROL_CHARS.test(modelId)) return null;
+ return modelId;
+}
+
+/** One imported row: a custom-group model with the endpoint config inline (original: null -> added on PUT). */
+function importedRow(provider: string, modelId: string, config: GroupImportConfig): RowState {
+ return {
+ provider,
+ modelId,
+ original: null,
+ // No vision claim until it is probed or switched on by hand — the same start a model
+ // added to a user-defined group by hand gets, and the safe one: a text-only model
+ // marked vision-capable is handed images directly instead of through the vision proxy.
+ vision: false,
+ contextWindow: "",
+ maxTokens: "",
+ fastMode: false,
+ clientType: config.clientType,
+ cacheRead: "",
+ cacheWrite: "",
+ output: "",
+ baseUrl: config.baseUrl,
+ originalBaseUrl: "",
+ apiKeyInput: config.apiKey,
+ clearApiKey: false,
+ };
+}
+
+/**
+ * Builds the rows to append for an imported listing. Nothing but the id is taken from the
+ * endpoint: pricing, context window and display name stay empty, because those are
+ * hand-curated fields and a provider-reported number written into them would silently
+ * disagree with the catalog's own pricing convention.
+ *
+ * `skipped` counts the listing entries that produced no row — an unusable id (empty, over
+ * the config's length bound, or carrying control characters), or a duplicate of one
+ * already taken, whether earlier in the same listing or by a row already configured under
+ * the same `(provider, modelId)` key (the group-name check normally guarantees the group
+ * is empty; this keeps the merge correct if that ever loosens).
+ */
+export function buildImportedRows(
+ existing: RowState[],
+ groupName: string,
+ listing: readonly string[],
+ config: GroupImportConfig,
+): { rows: RowState[]; added: number; skipped: number } {
+ const key = (provider: string, modelId: string) => `${provider}\0${modelId}`;
+ const seen = new Set(existing.map((r) => key(r.provider, r.modelId)));
+ const rows: RowState[] = [];
+ let skipped = 0;
+ for (const entry of listing) {
+ const modelId = usableModelId(entry);
+ if (modelId === null) {
+ skipped += 1;
+ continue;
+ }
+ const k = key(groupName, modelId);
+ if (seen.has(k)) {
+ skipped += 1;
+ continue;
+ }
+ seen.add(k);
+ rows.push(importedRow(groupName, modelId, config));
+ }
+ return { rows, added: rows.length, skipped };
+}
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index c7cf6e8a..043f5f12 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -54,6 +54,7 @@ import { FieldError, FieldLabel } from "../../components/ui/field";
import { PasswordInput } from "../../components/ui/password-input";
import { Modal } from "../../components/ui/modal";
import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { Segmented } from "../../components/ui/segmented";
import { Select } from "../../components/ui/select";
import { Switch } from "../../components/ui/switch";
import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
@@ -97,6 +98,7 @@ import {
} from "./model-group-expansion";
import { clearDraftModelRef } from "../chat/draft-cache";
import { syncRowsWithCatalog } from "./catalog-sync";
+import { buildImportedRows } from "./group-import";
import { tpsTone, ttftTone } from "./speed-test";
import type { SpeedResult, SpeedTone } from "./speed-test";
import { toneInk, toneStrip } from "../../lib/tone";
@@ -144,6 +146,9 @@ function inputToUsd(inputStr: string, currency: Currency): string {
/** Group-header action glyphs (24x24 line paths): add, bulk key, external link, gauge for speed test. */
const PLUS_ICON = "M12 5v14M5 12h14";
+/** Trash can (same drawing as the agent cards' delete action). */
+const TRASH_ICON =
+ "M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m3 0l-1 13a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 7m4 4v6m4-6v6";
const KEY_ICON =
"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4";
const EXTERNAL_LINK_ICON =
@@ -481,10 +486,10 @@ export function ModelsPage() {
}, [projectId]);
/** Vendor group (provider id) currently having its API key configured in bulk. */
const [groupKeyFor, setGroupKeyFor] = useState<string | null>(null);
- /** "Add group" popup (user-defined group): a valid name proceeds to that group's add-model dialog. */
+ /** User-defined group (provider id) whose delete confirmation is open (built-in groups never offer this). */
+ const [deleteGroupFor, setDeleteGroupFor] = useState<string | null>(null);
+ /** "Add group" popup (user-defined group): create-only hands off to that group's add-model dialog, import mode fills the group from its endpoint (see AddGroupDialog). */
const [addGroupOpen, setAddGroupOpen] = useState(false);
- const [groupName, setGroupName] = useState("");
- const [groupNameError, setGroupNameError] = useState<string | null>(null);
/** Initial load failure: shown inline only when the whole page has no content (there's no context to pop a toast against). */
const [loadError, setLoadError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
@@ -617,24 +622,41 @@ export function ModelsPage() {
};
/**
- * "Add group" confirm: a valid name that doesn't conflict with a built-in group or an
- * existing provider proceeds directly to that group's add-model dialog — groups are
- * carried by the model entry's provider field and aren't persisted separately, so the
- * group appears once the first model saves successfully (canceling leaves nothing behind).
+ * Import-mode landing from the add-group dialog: one table PUT with the appended rows,
+ * then the new group is opened so the result is visible immediately. Returns persist's
+ * verdict so the dialog stays up (fields intact) when saving failed.
+ *
+ * A failed save is rolled back to the table as it stood: persist otherwise keeps the
+ * attempted rows on screen (right for a field edit the user is still holding), which
+ * here would show the whole group as if it existed and make the dialog's own name check
+ * report the name as taken on the retry.
*/
- const confirmAddGroup = () => {
- const name = groupName.trim();
- if (!/^[a-z0-9][a-z0-9_-]{0,31}$/.test(name)) {
- setGroupNameError(S.models.groupNameInvalid);
- return;
+ const importGroup = async (
+ nextRows: RowState[],
+ name: string,
+ added: number,
+ skipped: number,
+ ): Promise<boolean> => {
+ if (!projectId) return false;
+ const before = rows;
+ const ok = await persist(
+ nextRows,
+ defaultModel,
+ visionModel,
+ S.models.groupImported(added, skipped),
+ );
+ if (!ok) {
+ setRows(before);
+ return false;
}
- if (MODEL_PROVIDERS.some((p) => p.id === name) || rows?.some((r) => r.provider === name)) {
- setGroupNameError(S.models.groupNameExists);
- return;
+ if (!expanded.has(name)) {
+ const next = new Set(expanded);
+ next.add(name);
+ setExpanded(next);
+ saveExpandedProviders(projectId, next);
}
setAddGroupOpen(false);
- setGroupName("");
- setAddingTo(name);
+ return true;
};
const editingRow =
editing !== null ? rows?.find((r) => sameModelRef(rowRef(r), editing)) : undefined;
@@ -794,6 +816,23 @@ export function ModelsPage() {
</span>
</Button>
)}
+ {isOwner && !MODEL_PROVIDERS.some((p) => p.id === group.provider.id) && (
+ // Whole-group delete, user-defined groups only: a built-in group is
+ // catalog identity (its rows delete one by one), a user-defined group
+ // exists solely through its rows and can go as a unit.
+ <Button
+ size="sm"
+ variant="ghost"
+ className="shrink-0"
+ disabled={busy}
+ aria-label={`${S.models.deleteGroup} ${group.provider.label}`}
+ title={S.models.deleteGroup}
+ onClick={() => setDeleteGroupFor(group.provider.id)}
+ >
+ <GlyphIcon d={TRASH_ICON} size={13} />
+ <span className="hidden @3xl:inline">{S.models.deleteGroup}</span>
+ </Button>
+ )}
{group.provider.apiKeyUrl && (
// External link: its label is the last one admitted as space grows
// (@4xl); below that it collapses to the external-link glyph with a
@@ -862,11 +901,7 @@ export function ModelsPage() {
// "Add group" (user-defined group): hidden while searching (the group list itself is being filtered).
<button
type="button"
- onClick={() => {
- setGroupName("");
- setGroupNameError(null);
- setAddGroupOpen(true);
- }}
+ onClick={() => setAddGroupOpen(true)}
className="w-full rounded-md border border-dashed border-gray-300 px-3 py-2.5 text-sm text-gray-500 transition-colors hover:border-gray-400 hover:text-gray-700 dark:border-gray-700 dark:text-gray-400 dark:hover:border-gray-600 dark:hover:text-gray-200"
>
+ {S.models.addGroup}
@@ -907,6 +942,37 @@ export function ModelsPage() {
/>
)}
+ {rows && deleteGroupFor !== null && (
+ <ConfirmModal
+ open
+ title={S.models.deleteGroupTitle}
+ tone="danger"
+ onClose={() => setDeleteGroupFor(null)}
+ onConfirm={() => {
+ const target = deleteGroupFor;
+ setDeleteGroupFor(null);
+ const removed = rows.filter((r) => r.provider === target);
+ if (removed.length === 0) return;
+ // Same pointer rule as single-model delete: a default/vision reference into the
+ // deleted group is dropped, otherwise the server rejects the dangling pair.
+ void persist(
+ rows.filter((r) => r.provider !== target),
+ defaultModel?.provider === target ? undefined : defaultModel,
+ visionModel?.provider === target ? undefined : visionModel,
+ S.models.groupDeleted(removed.length),
+ );
+ }}
+ >
+ <p className="text-sm text-gray-700 dark:text-gray-300">
+ {/* Offered on user-defined groups only, whose display info is always synthesized. */}
+ {S.models.deleteGroupConfirm(
+ userProviderInfo(deleteGroupFor).label,
+ rows.filter((r) => r.provider === deleteGroupFor).length,
+ )}
+ </p>
+ </ConfirmModal>
+ )}
+
{speedFor !== null && (
<Modal open title={S.models.speedTestTitle} onClose={() => setSpeedFor(null)}>
<p className="text-sm text-gray-600 dark:text-gray-300">
@@ -927,44 +993,17 @@ export function ModelsPage() {
</div>
</Modal>
)}
- {addGroupOpen && (
- <Modal
- open
- title={S.models.addGroupTitle}
+ {rows && addGroupOpen && (
+ <AddGroupDialog
+ projectId={projectId}
+ rows={rows}
onClose={() => setAddGroupOpen(false)}
- widthClass="sm:max-w-sm"
- footer={
- <>
- <Button onClick={() => setAddGroupOpen(false)}>{S.common.cancel}</Button>
- <Button variant="primary" onClick={confirmAddGroup}>
- {S.common.confirm}
- </Button>
- </>
- }
- >
- <div className="block">
- <Input
- size="sm"
- label={S.models.groupNameLabel}
- info={S.models.addGroupDesc}
- infoLabel={S.models.groupNameLabel}
- required
- value={groupName}
- invalid={Boolean(groupNameError)}
- onChange={(e) => {
- setGroupName(e.target.value);
- setGroupNameError(null);
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") confirmAddGroup();
- }}
- placeholder={S.models.groupNameHint}
- className="font-mono"
- autoFocus
- />
- {groupNameError && <FieldError>{groupNameError}</FieldError>}
- </div>
- </Modal>
+ onManual={(name) => {
+ setAddGroupOpen(false);
+ setAddingTo(name);
+ }}
+ onImport={importGroup}
+ />
)}
{rows && (addingTo !== null || editingRow) && (
@@ -1016,6 +1055,312 @@ export function ModelsPage() {
);
}
+// ---------------------------------------------------------------------------
+// Add-group dialog
+// ---------------------------------------------------------------------------
+
+/**
+ * "Add group" in two modes, chosen under the name field:
+ *
+ * - **Create only** — the light path: a valid name hands off to that group's add-model
+ * dialog (groups are carried by model entries, so the group appears once the first
+ * model saves; canceling leaves nothing behind).
+ * - **Import models** — fills the brand-new group from its endpoint, in the add-model
+ * dialog's field rhythm: API key first, then the base URL with the detect action at its
+ * top-right and the in-field protocol picker as manual override (ProtocolSuffixMenu —
+ * the same one-to-one path menu). Only once a protocol is determined (detected or
+ * picked) does the "import all models" action appear; it lists the endpoint
+ * (POST models/list) and hands the appended rows to the page for one table PUT.
+ *
+ * Detection failure turns the suffix amber and keeps both ways out usable — pick the
+ * protocol by hand, or switch back to create-only. Errors render inside the dialog;
+ * nothing persists until a listing succeeded.
+ */
+function AddGroupDialog({
+ projectId,
+ rows,
+ onClose,
+ onManual,
+ onImport,
+}: {
+ projectId: string;
+ rows: RowState[];
+ onClose: () => void;
+ /** Create-only confirm: open the add-model dialog for the named group. */
+ onManual: (name: string) => void;
+ /** Import landing: persist the appended rows; resolves false when saving failed (the dialog stays open). */
+ onImport: (
+ nextRows: RowState[],
+ name: string,
+ added: number,
+ skipped: number,
+ ) => Promise<boolean>;
+}) {
+ const [name, setName] = useState("");
+ const [nameError, setNameError] = useState<string | null>(null);
+ const [mode, setMode] = useState<"create" | "import">("create");
+ const [apiKey, setApiKey] = useState("");
+ const [baseUrl, setBaseUrl] = useState("");
+ /** The protocol the import will speak: null until a detection lands or the user picks one. */
+ const [clientType, setClientType] = useState<ProtocolClientType | null>(null);
+ const [detecting, setDetecting] = useState(false);
+ const [detectFailed, setDetectFailed] = useState(false);
+ /** Progress line while list/save runs (null = idle); also gates every action against re-entry. */
+ const [importing, setImporting] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ /** Detection run counter: a manual pick or an edited URL supersedes an in-flight run (same convention as the model dialog). */
+ const detectSeq = useRef(0);
+
+ const validName = (): string | null => {
+ const trimmed = name.trim();
+ if (!/^[a-z0-9][a-z0-9_-]{0,31}$/.test(trimmed)) {
+ setNameError(S.models.groupNameInvalid);
+ return null;
+ }
+ if (MODEL_PROVIDERS.some((p) => p.id === trimmed) || rows.some((r) => r.provider === trimmed)) {
+ setNameError(S.models.groupNameExists);
+ return null;
+ }
+ return trimmed;
+ };
+
+ const confirmCreate = () => {
+ const n = validName();
+ if (n) onManual(n);
+ };
+
+ const detect = async () => {
+ const url = baseUrl.trim();
+ setError(null);
+ if (!detectableBaseUrl(url)) {
+ setError(S.models.groupImportNeedUrl);
+ return;
+ }
+ const seq = ++detectSeq.current;
+ setDetecting(true);
+ setDetectFailed(false);
+ try {
+ const key = apiKey.trim();
+ const res = await api.detectProtocol(projectId, {
+ baseUrl: url,
+ ...(key ? { apiKey: key } : {}),
+ });
+ if (seq !== detectSeq.current) return;
+ const detected = res.detected !== undefined ? protocolSelectorValue(res.detected) : null;
+ if (detected !== null) {
+ setClientType(detected);
+ toastSuccess(S.models.detectedProtocol(S.models.protocolNames[detected] ?? detected));
+ } else {
+ setDetectFailed(true);
+ // Same condition the model dialog reports, so it gets the same sentence.
+ setError(S.models.detectFailedBody);
+ }
+ } catch (e) {
+ if (seq !== detectSeq.current) return;
+ setDetectFailed(true);
+ setError(apiErrorText(e));
+ } finally {
+ if (seq === detectSeq.current) setDetecting(false);
+ }
+ };
+
+ const pickProtocol = (t: ProtocolClientType) => {
+ detectSeq.current++;
+ setDetecting(false);
+ setDetectFailed(false);
+ setError(null);
+ setClientType(t);
+ };
+
+ const runImport = async () => {
+ const n = validName();
+ if (!n || clientType === null) return;
+ const url = baseUrl.trim();
+ if (!detectableBaseUrl(url)) {
+ setError(S.models.groupImportNeedUrl);
+ return;
+ }
+ setError(null);
+ setImporting(S.models.groupImportListing);
+ try {
+ const key = apiKey.trim();
+ const listed = await api.listEndpointModels(projectId, {
+ baseUrl: url,
+ clientType,
+ ...(key ? { apiKey: key } : {}),
+ });
+ if (!listed.ok || !listed.models) {
+ setError(
+ listed.unsupported
+ ? S.models.groupImportUnsupported
+ : (listed.message ?? S.models.groupImportFailed),
+ );
+ return;
+ }
+ const built = buildImportedRows(rows, n, listed.models, {
+ baseUrl: url,
+ clientType,
+ apiKey: key,
+ });
+ if (built.added === 0) {
+ setError(S.models.groupImportEmpty);
+ return;
+ }
+ setImporting(S.models.groupImportSaving(built.added));
+ await onImport([...rows, ...built.rows], n, built.added, built.skipped);
+ } catch (e) {
+ setError(apiErrorText(e));
+ } finally {
+ setImporting(null);
+ }
+ };
+
+ const busy = importing !== null;
+ const suffixLabel =
+ clientType === null ? S.models.protocolUnset : protocolPathForModel(name.trim(), clientType);
+
+ return (
+ <Modal
+ open
+ title={S.models.addGroupTitle}
+ onClose={() => !busy && onClose()}
+ widthClass="sm:max-w-sm"
+ footer={
+ <>
+ <Button disabled={busy} onClick={onClose}>
+ {S.common.cancel}
+ </Button>
+ {mode === "create" ? (
+ <Button variant="primary" onClick={confirmCreate}>
+ {S.common.confirm}
+ </Button>
+ ) : (
+ // The import action exists only once the protocol is determined (detected or
+ // hand-picked): before that there is nothing meaningful to run.
+ clientType !== null && (
+ <Button variant="primary" disabled={busy} onClick={() => void runImport()}>
+ {S.models.groupImportAll}
+ </Button>
+ )
+ )}
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <div className="block">
+ <Input
+ size="sm"
+ label={S.models.groupNameLabel}
+ info={S.models.addGroupDesc}
+ infoLabel={S.models.groupNameLabel}
+ required
+ value={name}
+ invalid={Boolean(nameError)}
+ onChange={(e) => {
+ setName(e.target.value);
+ setNameError(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && mode === "create") confirmCreate();
+ }}
+ placeholder={S.models.groupNameHint}
+ className="font-mono"
+ autoFocus
+ />
+ {nameError && <FieldError>{nameError}</FieldError>}
+ </div>
+ <Segmented
+ cols={2}
+ options={[
+ { value: "create", label: S.models.groupModeCreate },
+ { value: "import", label: S.models.groupModeImport },
+ ]}
+ value={mode}
+ onChange={setMode}
+ />
+ {mode === "import" && (
+ <>
+ <PasswordInput
+ size="sm"
+ label={S.models.apiKey}
+ value={apiKey}
+ onChange={(e) => {
+ setApiKey(e.target.value);
+ setError(null);
+ }}
+ className="font-mono"
+ autoComplete="off"
+ placeholder={S.models.groupImportKeyHint}
+ />
+ {/* Base URL with the detect action at its top-right and the in-field protocol
+ picker — the add-model dialog's idiom, so the two flows read as one. */}
+ <div className="block">
+ <span className="mb-1 flex items-baseline justify-between gap-2">
+ <span className="text-xs font-semibold text-gray-600 dark:text-gray-400">
+ {S.models.baseUrl}
+ <span className="ml-0.5 text-red-500 dark:text-red-400" aria-hidden>
+ *
+ </span>
+ </span>
+ <button
+ type="button"
+ disabled={detecting || busy}
+ onClick={() => void detect()}
+ title={S.models.detectProtocolHint}
+ className="flex shrink-0 items-center gap-1 text-xs text-brand-600 underline-offset-2 hover:underline disabled:cursor-not-allowed disabled:text-gray-400 disabled:no-underline dark:text-brand-300 dark:disabled:text-gray-500"
+ >
+ {detecting && (
+ <span
+ aria-hidden
+ className="inline-block h-2.5 w-2.5 shrink-0 animate-spin rounded-full border border-current border-t-transparent"
+ />
+ )}
+ {detecting ? S.models.detecting : S.models.detectProtocol}
+ </button>
+ </span>
+ <div className="relative">
+ <Input
+ size="sm"
+ aria-label={S.models.baseUrl}
+ required
+ value={baseUrl}
+ disabled={busy}
+ onChange={(e) => {
+ // An edited URL retires the previous verdict: protocol and failure tone
+ // both described the old endpoint.
+ detectSeq.current++;
+ setDetecting(false);
+ setDetectFailed(false);
+ setError(null);
+ setBaseUrl(e.target.value);
+ }}
+ className="font-mono"
+ style={{ paddingRight: `calc(${displayWidthCh(suffixLabel)}ch + 2.25rem)` }}
+ title={S.models.baseUrlSuffixTitle}
+ placeholder="https://…"
+ />
+ <div className="absolute inset-y-0 right-1 flex items-center">
+ <ProtocolSuffixMenu
+ value={clientType}
+ path={suffixLabel}
+ detecting={detecting}
+ tone={detectFailed ? "warn" : null}
+ onPick={pickProtocol}
+ />
+ </div>
+ </div>
+ </div>
+ {importing !== null && (
+ <p className="text-xs text-gray-500 dark:text-gray-400">{importing}</p>
+ )}
+ </>
+ )}
+ {error && <FieldError>{error}</FieldError>}
+ </div>
+ </Modal>
+ );
+}
+
// ---------------------------------------------------------------------------
// Model card
// ---------------------------------------------------------------------------
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 1e381f83..10c21a69 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -549,13 +549,32 @@ export const en: Strings = {
addGroup: "Add group",
addGroupTitle: "Add group",
addGroupDesc:
- "User-defined groups share Custom semantics: the protocol is picked manually or detected from the base URL (base URL required; an empty API key reads the OPENAI_* / ANTHROPIC_* env vars per the chosen protocol). Groups live on model entries — the group appears once its first model is saved.",
+ 'User-defined groups share Custom semantics. "Import models" detects (or lets you pick) the endpoint\'s protocol, then imports every model it serves in one go; "Create only" adds models one by one after the group. Groups live on model entries — the group appears once its first model is saved.',
+ groupModeCreate: "Create only",
+ groupModeImport: "Import models",
+ groupImportAll: "Import all models",
+ groupImportNeedUrl: "Fill in a valid base URL first (http/https)",
+ groupImportKeyHint: "Leave empty to read the protocol's OPENAI_* / ANTHROPIC_* env vars",
+ groupImportListing: "Fetching model list…",
+ groupImportSaving: (n: number): string => `Importing ${n} models…`,
+ groupImportUnsupported: "This protocol cannot list models — add them manually",
+ groupImportFailed: "Fetching the model list failed",
+ groupImportEmpty: "No models to import from this endpoint",
+ groupImported: (added: number, skipped: number): string =>
+ skipped > 0
+ ? `Imported ${added} models, skipped ${skipped} entries`
+ : `Imported ${added} models`,
groupNameLabel: "Group name",
groupNameHint: "Starts with a lowercase letter / digit; may contain - and _",
groupNameInvalid:
"Group names may only use lowercase letters, digits, - and _ (starting with a letter or digit), up to 32 characters",
groupNameExists: "This name is taken by a built-in group or an existing entry",
groupEmptyHint: "No models in this group yet; use “Add model” to create one",
+ deleteGroup: "Delete group",
+ deleteGroupTitle: "Delete group",
+ deleteGroupConfirm: (label: string, n: number): string =>
+ `Delete the group “${label}”? Its ${n} models and their API key configuration will be removed.`,
+ groupDeleted: (n: number): string => `Group deleted (${n} models)`,
searchPlaceholder: "Search models: id / name / provider",
noSearchResults: "No matching models",
syncCatalog: "Sync presets",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 8c6335f9..6f80ec0f 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -515,12 +515,29 @@ export const zh = {
addGroup: "新增分组",
addGroupTitle: "新增分组",
addGroupDesc:
- "自建分组与 Custom 同语义:接口协议可手动选择,也可按 base URL 检测(base URL 必填,API key 留空按所选协议读取 OPENAI_* / ANTHROPIC_* 环境变量)。分组由模型条目承载,保存首个模型后即出现。",
+ "自建分组与 Custom 同语义。「导入模型」按端点检测或手选协议后,一键导入其全部模型;「仅新增分组」建组后逐个添加。分组由模型条目承载,保存首个模型后即出现。",
+ groupModeCreate: "仅新增分组",
+ groupModeImport: "导入模型",
+ groupImportAll: "批量导入模型",
+ groupImportNeedUrl: "请先填写有效的 base URL(http/https)",
+ groupImportKeyHint: "留空按协议读取 OPENAI_* / ANTHROPIC_* 环境变量",
+ groupImportListing: "正在获取模型列表…",
+ groupImportSaving: (n: number): string => `正在导入 ${n} 个模型…`,
+ groupImportUnsupported: "该协议不支持列出模型,请手动添加",
+ groupImportFailed: "获取模型列表失败",
+ groupImportEmpty: "该端点没有可导入的模型",
+ groupImported: (added: number, skipped: number): string =>
+ skipped > 0 ? `已导入 ${added} 个模型,跳过 ${skipped} 个条目` : `已导入 ${added} 个模型`,
groupNameLabel: "分组名",
groupNameHint: "小写字母 / 数字开头,可含 - 与 _",
groupNameInvalid: "分组名只能用小写字母、数字、- 与 _(首字符为字母或数字),长度不超过 32",
groupNameExists: "该分组名已被内置分组或既有条目占用",
groupEmptyHint: "该分组暂无模型,点「新增模型」添加",
+ deleteGroup: "删除分组",
+ deleteGroupTitle: "删除分组",
+ deleteGroupConfirm: (label: string, n: number): string =>
+ `确定删除分组「${label}」?组内 ${n} 个模型及其 API key 配置将一并移除。`,
+ groupDeleted: (n: number): string => `已删除分组(${n} 个模型)`,
searchPlaceholder: "搜索模型:id / 名称 / 厂商",
noSearchResults: "没有匹配的模型",
syncCatalog: "同步预置",
diff --git a/packages/web/test/group-import.test.ts b/packages/web/test/group-import.test.ts
new file mode 100644
index 00000000..c0ea3e31
--- /dev/null
+++ b/packages/web/test/group-import.test.ts
@@ -0,0 +1,91 @@
+/**
+ * Add-group bulk import row building: listing order preserved, entries that produce no row
+ * skipped and counted (duplicates, and ids the config could not hold), and every imported
+ * row carrying the endpoint config inline in the shape rowToEntry persists.
+ */
+import { describe, expect, it } from "vitest";
+import { buildImportedRows } from "../src/features/models/group-import";
+import { rowToEntry, toRow } from "../src/features/models/models-page";
+
+const config = { baseUrl: "https://gw.example/v1", clientType: "openai-chat", apiKey: "sk-g1" };
+
+describe("buildImportedRows", () => {
+ it("keeps the endpoint's order and carries base URL / protocol / key on every row", () => {
+ const { rows, added, skipped } = buildImportedRows([], "mygw", ["m-b", "m-a"], config);
+ expect(added).toBe(2);
+ expect(skipped).toBe(0);
+ expect(rows.map((r) => r.modelId)).toEqual(["m-b", "m-a"]);
+ for (const row of rows) {
+ expect(row.provider).toBe("mygw");
+ expect(row.original).toBeNull();
+ expect(row.clientType).toBe("openai-chat");
+ expect(row.baseUrl).toBe("https://gw.example/v1");
+ expect(row.apiKeyInput).toBe("sk-g1");
+ // The same start a hand-added model in a user-defined group gets: no vision claim.
+ expect(row.vision).toBe(false);
+ }
+ });
+
+ it("skips duplicates within the listing and against existing pairs, counting them", () => {
+ const existing = [
+ toRow({ provider: "mygw", modelId: "m-a", isDefault: false }),
+ // Same id under another group is a different (provider, modelId) pair — not a duplicate.
+ toRow({ provider: "other", modelId: "m-b", isDefault: false }),
+ ];
+ const { rows, added, skipped } = buildImportedRows(
+ existing,
+ "mygw",
+ ["m-a", "m-b", "m-b", "m-c"],
+ config,
+ );
+ expect(added).toBe(2);
+ expect(skipped).toBe(2);
+ expect(rows.map((r) => r.modelId)).toEqual(["m-b", "m-c"]);
+ });
+
+ it("drops ids the config could not hold instead of letting one entry 400 the whole PUT", () => {
+ const listing = [
+ " m-trim ",
+ "",
+ " ",
+ "x".repeat(201),
+ "m-\u0000nul",
+ "m-\nnewline",
+ "x".repeat(200),
+ ];
+ const { rows, added, skipped } = buildImportedRows([], "mygw", listing, config);
+ // Trimmed, and the 200-character id (exactly the server's bound) still lands.
+ expect(rows.map((r) => r.modelId)).toEqual(["m-trim", "x".repeat(200)]);
+ expect(added).toBe(2);
+ expect(skipped).toBe(5);
+ });
+
+ it("counts a listing entry that only duplicates another after trimming", () => {
+ const { added, skipped } = buildImportedRows([], "mygw", ["m-a", " m-a "], config);
+ expect(added).toBe(1);
+ expect(skipped).toBe(1);
+ });
+
+ it("produces rows that persist as full entries (protocol, base URL, key; vision unset)", () => {
+ const { rows } = buildImportedRows([], "mygw", ["m-x"], config);
+ expect(rowToEntry(rows[0]!)).toEqual({
+ provider: "mygw",
+ modelId: "m-x",
+ clientType: "openai-chat",
+ vision: false,
+ baseUrl: "https://gw.example/v1",
+ apiKey: "sk-g1",
+ });
+ });
+
+ it("leaves the key off entries when none was typed (environment fallback)", () => {
+ const { rows } = buildImportedRows([], "mygw", ["m-x"], { ...config, apiKey: "" });
+ expect(rowToEntry(rows[0]!)).toEqual({
+ provider: "mygw",
+ modelId: "m-x",
+ clientType: "openai-chat",
+ vision: false,
+ baseUrl: "https://gw.example/v1",
+ });
+ });
+});