Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(model-hub): pick a vendor in the add-key dialog (#1851)

Max7bbdfd4a8df3
diff --git a/Dockerfile b/Dockerfile
index 09f265bed..aac14d93f 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -6,11 +6,14 @@ FROM node:20-slim AS ui-builder
WORKDIR /app/ui
COPY ui/package.json ui/package-lock.json ./
RUN npm ci --ignore-scripts
-# ``ui/src/lib/messageTypes.ts`` imports the repo-root message-type policy catalog so
-# the Web UI and the Python readers share one declaration. This stage copies only
-# ``ui/``, so the catalog has to be placed at the repository-relative path the import
+# Two repo-root catalogs are imported from ``ui/src`` so the Web UI and the Python
+# readers share one declaration: the message-type policy catalog
+# (``ui/src/lib/messageTypes.ts``) and the API-key vendor catalog
+# (``ui/src/components/settings/models/apiKeyVendors.ts``). This stage copies only
+# ``ui/``, so each has to be placed at the repository-relative path its import
# expects, or ``npm run build`` fails to resolve it.
COPY vibe/message_types.json /app/vibe/message_types.json
+COPY vibe/data/api_key_vendors.json /app/vibe/data/api_key_vendors.json
COPY ui/ .
RUN npm run build
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index 282de1b8d..351915e46 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -3383,11 +3383,44 @@ The dialog is now a single add flow:
written over exits: whether a state happens to expose an editable field today
decides only whether it fires, never whether it applies.
+**2026-09-04 owner ruling — no text in this dialog inherits the document's default
+type scale** `[derived]`. Manual verification found the idle/ready row's
+active-interface statement rendering at 16px, larger than the 15px dialog title,
+because the element carrying that statement declared only layout. Its scale is
+12 / 600 — `--model-hub-add-key-strip-title-size`, already the detecting row's and
+the identified strip's scale — while the 自动探测 hint beside it keeps the 10.5
+field-hint scale. Stated as the property rather than as that one row: **every text
+node in this dialog declares its own size.** The element that owns a statement is
+the element that sizes it, which is why the two-scale idle row sizes each child
+instead of the row, and why a row added later is measured by the rule rather than by
+whether it appears in the Metrics list below.
+
+**2026-09-04 owner ruling — wherever this dialog states the interface, it states why
+it is settled** `[derived]`. ① Default above registers 「内置目录」
+(`addKey.protocol.catalogPinned`) as the badge on a catalog pin. Two keys extend that
+rule to the cases ① does not cover, and neither introduces a new state:
+
+- `addKey.protocol.declared` — 「手动指定」, the same badge shape on the other answer
+ that is not "the response proved it": a concrete interface chosen from the 自定义
+ disclosure. It rides the ready row and both result strips, exactly where
+ `catalogPinned` does. 自动探测 carries no badge, because there the response shape
+ IS the evidence and the identified strip already names what it found.
+- `addKey.protocol.catalogPinned.hint` — what 检测 still establishes under a pin
+ (authenticate the key, fetch the model list), replacing `addKey.protocol.idleHint`
+ on the ready row. The two cannot share one string: `idleHint` promises the
+ interface will be identified automatically, which under a pin is neither true nor
+ still in question.
+
+Stated as the property rather than as three call sites: **an interface this dialog did
+not detect says where it came from, and the row that says it also says what detection
+is still for.**
+
**Element inventory**
| Element | Displays | Data source | Interactive | On activate |
| --- | --- | --- | --- | --- |
| head sub-line | that Add detects the connection and interface first, then confirms | static | no | — |
+| 服务商 + hint | 自定义 · 兼容端点 first, then one option per shipped catalog row in file order, by its label; the hint says a catalog pick prefills the official address and pins the interface | `vibe/data/api_key_vendors.json`, read by this dialog and the server from the one tracked file | yes | Select a catalog vendor → Base URL becomes its `official_base_url` (still editable), 接口类型 locks to its protocol and the disclosure is gone, any observation is retired. Select 自定义 → Base URL clears and the disclosure returns |
| `f7Ao1U` 名称(可选) | free text | user | yes | — |
| `cXsiv` Base URL + hint | free text; the hint names an API root, and says a bare host uses the standard `/v1` path | user | yes | — |
| `mZBBw` API Key | masked value, reveal icon | user | yes | Toggle reveal |
diff --git a/ui/e2e/b-add-api-key.spec.ts b/ui/e2e/b-add-api-key.spec.ts
index 4cd173505..168915a1d 100644
--- a/ui/e2e/b-add-api-key.spec.ts
+++ b/ui/e2e/b-add-api-key.spec.ts
@@ -22,6 +22,10 @@ import { expect, test } from './support/gateway';
import { fillApiKeyForm } from './support/hub';
import { anthropicInventory } from './support/mock';
import { captureAgentChain, restoreAgentChain } from './support/restore';
+// The shipped vendor catalog, read from the same tracked file the dialog and the
+// server read. A spec that named an id and its pinned interface by hand would
+// keep passing after the catalog moved underneath it.
+import { CATALOG_VENDORS } from './support/vendors';
/**
* Runs the routed dry run until the source has settled on a verdict about its
@@ -112,9 +116,50 @@ test.describe('B · add an API-key source', () => {
const created = (await api.sources()).find((source) => source.display_name === name);
expect(created?.protocol).toBe(protocol.id);
+ expect(created?.vendor).toBe('custom');
});
}
+ // B1 · the other rung of the same scenario. A vendor picked from the shipped
+ // catalog is not asked to prove its interface by shape — the catalog row is the
+ // proof, so detection only has to authenticate and fetch. The address is then
+ // pointed at the mock, which is both the only way this suite can reach a real
+ // upstream AND the state a user behind a gateway is actually in: it proves the
+ // pin belongs to the VENDOR and not to the URL it proposed.
+ test('B1 · a catalog vendor is added under its own id, with its interface pinned', async ({ hub, mock, api }) => {
+ const preset = CATALOG_VENDORS[0];
+ await mock.configure({ auth: 'ok', protocol: preset.protocol, models_endpoint: 'ok' });
+ const name = `${E2E_SOURCE_PREFIX}catalog-${preset.id}`;
+
+ await hub.goto();
+ await hub.addApiKeyButton.click();
+ await expect(hub.addKeyDialog).toBeVisible();
+ await fillApiKeyForm(hub.addKeyDialog, {
+ vendor: preset.id,
+ name,
+ baseUrl: mockBaseUrl(),
+ apiKey: 'e2e-add',
+ });
+
+ // The interface is stated, not asked: the pinned name is on screen with the
+ // badge that says where it came from, and the control that would offer a
+ // different one is gone rather than merely disabled.
+ await expect(hub.addKeyDialog).toContainText(copy('addKey.protocol.catalogPinned'));
+ await expect(
+ hub.addKeyDialog.getByRole('button', { name: copy('addKey.protocol.manual'), exact: true }),
+ ).toHaveCount(0);
+
+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.detect'), exact: true }).click();
+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.confirm'), exact: true }).click({ timeout: 30_000 });
+
+ await expect(hub.addKeyDialog).toHaveCount(0, { timeout: 30_000 });
+ await expect(hub.sourceDetailDialog).toBeVisible();
+
+ const created = (await api.sources()).find((source) => source.display_name === name);
+ expect(created?.vendor).toBe(preset.id);
+ expect(created?.protocol).toBe(preset.protocol);
+ });
+
test('B1 · a rejected credential is named as a credential problem', async ({ hub, mock }) => {
await mock.configure({ auth: '401', protocol: 'anthropic', models_endpoint: 'ok' });
diff --git a/ui/e2e/support/api.ts b/ui/e2e/support/api.ts
index 32a0f17c4..a400e9a04 100644
--- a/ui/e2e/support/api.ts
+++ b/ui/e2e/support/api.ts
@@ -22,6 +22,9 @@ export type Source = {
id: string;
display_name: string;
kind: string;
+ /** The catalog id a preset was added under, or `custom` for a compatible
+ * endpoint. It is what the vendor dropdown selected, not a UI label. */
+ vendor: string;
protocol: string;
supply_channel: string;
base_url?: string | null;
diff --git a/ui/e2e/support/hub.ts b/ui/e2e/support/hub.ts
index 22c509e7f..d90da47a7 100644
--- a/ui/e2e/support/hub.ts
+++ b/ui/e2e/support/hub.ts
@@ -369,11 +369,20 @@ export const labelledButton = (scope: Locator, name: string): Locator =>
* Fills the add-API-key form. `name` is optional in the product and optional
* here for the same reason: a spec that does not care about the label should
* not have to invent one.
+ *
+ * `vendor` is a catalog id and goes FIRST, because choosing one rewrites the
+ * Base URL and retires whatever interface was selected — filling those before it
+ * would fill them into a form the next click resets. It also removes the manual
+ * disclosure, so `vendor` and `protocol` are alternatives, not a pair: the pin IS
+ * the interface, and there is no control left for `protocol` to press.
*/
export const fillApiKeyForm = async (
dialog: Locator,
- values: { name?: string; baseUrl: string; apiKey: string; protocol?: string },
+ values: { vendor?: string; name?: string; baseUrl: string; apiKey: string; protocol?: string },
): Promise<void> => {
+ if (values.vendor) {
+ await dialog.getByLabel(hub('addKey.field.vendor'), { exact: true }).selectOption(values.vendor);
+ }
if (values.name !== undefined) {
await dialog.getByLabel(hub('addKey.field.name'), { exact: true }).fill(values.name);
}
diff --git a/ui/e2e/support/mock.ts b/ui/e2e/support/mock.ts
index b523ed684..21ac8eb24 100644
--- a/ui/e2e/support/mock.ts
+++ b/ui/e2e/support/mock.ts
@@ -9,7 +9,10 @@ import type { APIRequestContext } from '@playwright/test';
import { MOCK_UPSTREAM_URL } from './env';
export type MockAuthMode = 'ok' | '401' | '403_banned' | '402' | '429' | 'quota_message' | '5xx';
-export type MockProtocol = 'anthropic' | 'openai_responses' | 'openai_chat';
+/** Declared as values, not only as a union, so a caller can ask at runtime
+ * whether some protocol it read from elsewhere is one this mock can serve. */
+export const MOCK_PROTOCOLS = ['anthropic', 'openai_responses', 'openai_chat'] as const;
+export type MockProtocol = (typeof MOCK_PROTOCOLS)[number];
export type MockModelsEndpoint = 'ok' | 'http_404' | 'http_500' | 'timeout' | 'malformed_json';
export type MockConfig = {
diff --git a/ui/e2e/support/vendors.ts b/ui/e2e/support/vendors.ts
new file mode 100644
index 000000000..bb492fa86
--- /dev/null
+++ b/ui/e2e/support/vendors.ts
@@ -0,0 +1,44 @@
+// The shipped API-key vendor catalog, as this suite sees it.
+//
+// The dialog offers one option per row of `vibe/data/api_key_vendors.json`, and
+// the server pins the created source's interface from the same file. A spec that
+// typed a vendor id and its interface by hand would agree with neither after the
+// catalog moved: it would keep passing while testing a vendor that no longer
+// ships, or pin an interface the row no longer declares. So the file is read
+// here, the way `copy.ts` reads the i18n bundles — from disk, in Node, with no
+// bundler in the path.
+//
+// Only rows the mock upstream can actually speak are offered. The mock is how
+// this suite reaches an upstream at all, so a row whose interface it cannot
+// serve is not drivable from here — that is a gap in the mock, not a vendor to
+// assert against. The list is asserted non-empty at import, because silently
+// having nothing to pick would read as coverage.
+import { readFileSync } from 'node:fs';
+
+import { MOCK_PROTOCOLS, type MockProtocol } from './mock';
+
+/** One catalog row, narrowed to what a spec needs to drive it. */
+export type CatalogVendor = {
+ /** The id the dialog sends and the created source is stored under. */
+ id: string;
+ label: string;
+ official_base_url: string;
+ /** The interface the catalog pins for this vendor — never detected. */
+ protocol: MockProtocol;
+};
+
+const rows = JSON.parse(
+ readFileSync(new URL('../../../vibe/data/api_key_vendors.json', import.meta.url), 'utf8'),
+) as CatalogVendor[];
+
+/** Every shipped vendor whose pinned interface the mock upstream can serve. */
+export const CATALOG_VENDORS: readonly CatalogVendor[] = rows.filter(
+ (row) => (MOCK_PROTOCOLS as readonly string[]).includes(row.protocol),
+);
+
+if (CATALOG_VENDORS.length === 0) {
+ throw new Error(
+ 'vibe/data/api_key_vendors.json has no row whose protocol the mock upstream can serve, '
+ + `so no vendor can be driven from this suite. Mock protocols: ${MOCK_PROTOCOLS.join(', ')}.`,
+ );
+}
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
index 5f9c14f0e..74d79720e 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import { AddApiKeyDialog } from './AddApiKeyDialog';
+import { API_KEY_VENDOR_PRESETS } from './apiKeyVendors';
import { createSourceCollectionReadAuthority } from './collectionReadAuthority';
import { ApiCallError, modelsApi } from './modelsApi';
import type {
@@ -144,6 +145,23 @@ const fillCredentials = async () => {
return user;
};
+const vendorSelect = () => screen.getByRole('combobox', { name: /^Vendor$|^服务商$/ }) as HTMLSelectElement;
+const baseUrlInput = () => screen.getByRole('textbox', { name: /^Base URL$/i }) as HTMLInputElement;
+const disclosure = () => screen.queryByRole('button', { name: /Manually specify interface type|手动指定接口类型/i });
+
+/** A catalog row read from the shipped file, so the case does not restate an id,
+ * a URL, or a pin that the backend owns. Chosen by protocol rather than by name:
+ * the assertions are about a pin being carried, not about which vendor it is. */
+const preset = (protocol: string) => {
+ const entry = API_KEY_VENDOR_PRESETS.find((row) => row.protocol === protocol);
+ if (!entry) throw new Error(`the shipped catalog has no ${protocol} row to exercise the pin with`);
+ return entry;
+};
+
+const selectVendor = async (user: ReturnType<typeof userEvent.setup>, id: string) => {
+ await user.selectOptions(vendorSelect(), id);
+};
+
const openManualProtocol = async (user: ReturnType<typeof userEvent.setup>) => {
await user.click(screen.getByRole('button', { name: /Manually specify interface type|手动指定接口类型/i }));
};
@@ -990,3 +1008,132 @@ describe('AddApiKeyDialog', () => {
},
);
});
+
+// The vendor dropdown is the ladder's rung selector. A catalog row makes the
+// interface a fact this dialog READS — from the same shipped file the server
+// pins by — so detection only has to authenticate; 自定义 leaves the two rungs
+// that still ask, the response's shape or the user's word.
+describe('AddApiKeyDialog · vendor', () => {
+ it('sends custom with nothing pinned when the vendor is left on 自定义', async () => {
+ const observe = vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed());
+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValueOnce({
+ source,
+ added_to: [],
+ adopted_by: [],
+ });
+ renderDialog();
+ const user = await fillCredentials();
+
+ await clickDetect(user);
+ await clickConfirm(user);
+
+ await waitFor(() => expect(create).toHaveBeenCalledOnce());
+ expect(observe.mock.calls[0][0].vendor).toBe('custom');
+ expect(observe.mock.calls[0][0].protocol).toBeUndefined();
+ expect(create.mock.calls[0][0].vendor).toBe('custom');
+ });
+
+ it('prefills the official address and sends the catalog id with its pinned interface', async () => {
+ const entry = preset('openai_chat');
+ const observe = vi.spyOn(modelsApi, 'observeApiKeySource')
+ .mockResolvedValueOnce(observed({ protocol: entry.protocol }));
+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValueOnce({
+ source,
+ added_to: [],
+ adopted_by: [],
+ });
+ renderDialog();
+ const user = userEvent.setup();
+
+ await selectVendor(user, entry.id);
+ expect(baseUrlInput().value).toBe(entry.official_base_url);
+ await user.type(screen.getByLabelText(/^API key$/i), 'secret-key');
+ await clickDetect(user);
+ await clickConfirm(user);
+
+ await waitFor(() => expect(create).toHaveBeenCalledOnce());
+ expect(observe.mock.calls[0][0]).toMatchObject({ vendor: entry.id, protocol: entry.protocol });
+ expect(create.mock.calls[0][0]).toMatchObject({ vendor: entry.id, protocol: entry.protocol });
+ });
+
+ it('states the pinned interface as a fact and offers no way to choose another', async () => {
+ const entry = preset('anthropic');
+ renderDialog();
+ const user = userEvent.setup();
+
+ await selectVendor(user, entry.id);
+
+ const row = document.querySelector('.model-hub-add-key-protocol-idle-row');
+ expect(row?.textContent).toMatch(/Anthropic Messages/);
+ expect(row?.querySelector('.model-hub-add-key-protocol-glyph')).toBeTruthy();
+ expect(row?.textContent).toMatch(/Built-in catalog/);
+ expect(disclosure()).toBeNull();
+ expect(screen.queryByRole('button', { name: 'OpenAI Responses' })).toBeNull();
+ });
+
+ it('retires an observation taken under the previous vendor', async () => {
+ const entry = preset('openai_chat');
+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed());
+ renderDialog();
+ const user = await fillCredentials();
+
+ await clickDetect(user);
+ expect(await screen.findByRole('button', { name: CONFIRM })).toBeTruthy();
+
+ await selectVendor(user, entry.id);
+
+ expect(screen.queryByRole('button', { name: CONFIRM })).toBeNull();
+ expect(screen.getByRole('button', { name: DETECT })).toBeTruthy();
+ expect(baseUrlInput().value).toBe(entry.official_base_url);
+ });
+
+ it('keeps the pin when a preset is pointed at another address', async () => {
+ const entry = preset('openai_chat');
+ const observe = vi.spyOn(modelsApi, 'observeApiKeySource')
+ .mockResolvedValueOnce(observed({ protocol: entry.protocol }));
+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValueOnce({
+ source,
+ added_to: [],
+ adopted_by: [],
+ });
+ renderDialog();
+ const user = userEvent.setup();
+
+ await selectVendor(user, entry.id);
+ await user.clear(baseUrlInput());
+ await user.type(baseUrlInput(), 'https://relay.example/v1');
+ await user.type(screen.getByLabelText(/^API key$/i), 'secret-key');
+
+ // A gateway in front of a catalog vendor is still that vendor: the address
+ // is the one thing the preset only proposes.
+ expect(document.querySelector('.model-hub-add-key-protocol-idle-row')?.textContent)
+ .toMatch(/Built-in catalog/);
+ expect(disclosure()).toBeNull();
+
+ await clickDetect(user);
+ await clickConfirm(user);
+
+ await waitFor(() => expect(create).toHaveBeenCalledOnce());
+ expect(observe.mock.calls[0][0]).toMatchObject({
+ vendor: entry.id,
+ base_url: 'https://relay.example/v1',
+ protocol: entry.protocol,
+ });
+ expect(create.mock.calls[0][0]).toMatchObject({
+ vendor: entry.id,
+ base_url: 'https://relay.example/v1',
+ });
+ });
+
+ it('gives the address and the interface choice back on the way to 自定义', async () => {
+ const entry = preset('openai_chat');
+ renderDialog();
+ const user = userEvent.setup();
+
+ await selectVendor(user, entry.id);
+ await selectVendor(user, 'custom');
+
+ expect(baseUrlInput().value).toBe('');
+ expect(disclosure()).not.toBeNull();
+ });
+});
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
index 8e7bdd0ab..23b0d4ebe 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -15,7 +15,9 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
+import { Select } from '@/components/ui/select';
import { cn } from '@/lib/utils';
+import { API_KEY_VENDOR_PRESETS, apiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';
import { classifyModelHubFailure, type ModelHubFailureClass } from './asyncLifetime';
import { Field } from './dialogFields';
import {
@@ -253,6 +255,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
const addOnAdded = replaceMode ? null : props.onAdded;
const replaceSourceId = replaceMode ? props.source.id : null;
const { t } = useTranslation();
+ const [vendor, setVendor] = React.useState<string>(CUSTOM_VENDOR);
const [displayName, setDisplayName] = React.useState('');
const [baseUrl, setBaseUrl] = React.useState('');
const [apiKey, setApiKey] = React.useState('');
@@ -280,6 +283,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
}
if (open) {
clientNonce.current = sourceClientNonce();
+ setVendor(CUSTOM_VENDOR);
setDisplayName('');
setBaseUrl('');
setApiKey('');
@@ -328,14 +332,17 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
acceptUnavailableInventory = false,
): ApiKeySourceCreate => ({
kind: 'api_key',
- vendor: 'custom',
+ vendor,
+ // The name is left out when empty rather than filled in here: the server
+ // already names a catalog source after its catalog label, and a second
+ // owner of that default is a second thing to keep in step with the catalog.
...(displayName.trim() ? { display_name: displayName.trim() } : {}),
base_url: baseUrl.trim(),
key: apiKey.trim(),
client_nonce: clientNonce.current,
...(protocol ? { protocol } : {}),
...(acceptUnavailableInventory ? { accept_unavailable_inventory: true } : {}),
- }), [apiKey, baseUrl, displayName]);
+ }), [apiKey, baseUrl, displayName, vendor]);
const persist = React.useCallback(async (
seq: ContinuationTicket,
@@ -388,7 +395,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
setPhase({ kind: 'working', origin, stage: 'observe' });
try {
const observation = await modelsApi.observeApiKeySource({
- vendor: 'custom',
+ vendor,
base_url: baseUrl.trim(),
key: apiKey.trim(),
...(protocol ? { protocol } : {}),
@@ -417,7 +424,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
});
});
}
- }, [apiKey, baseUrl, continuation]);
+ }, [apiKey, baseUrl, continuation, vendor]);
const submitReplacement = React.useCallback(async (force: boolean) => {
if (props.mode !== 'replace' || !apiKey.trim() || replacePhase.kind === 'submitting') return;
@@ -518,10 +525,20 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
createdDelivery.close();
}, [continuation, createdDelivery, onClose, phase, replaceMode, replacePhase.kind]);
+ // What the next observation will be made under. A catalog vendor pins the
+ // interface (ladder rung 1: the catalog row is the proof, so the response only
+ // has to authenticate); 自定义 leaves it to the disclosure — a concrete choice
+ // is a declaration (rung 3), and Auto sends nothing so the shape must prove it
+ // (rung 2). Read by the handlers below and by the render, because "what 检测
+ // will send" and "what the row says 检测 will send" must be one value.
+ const vendorPreset = apiKeyVendorPreset(vendor);
+ const selectedProtocol = protocolSelection === 'auto' ? undefined : protocolSelection;
+ const constrainedProtocol = vendorPreset?.protocol ?? selectedProtocol;
+
const retry = async () => {
if (phase.kind === 'undetermined') {
- if (protocolSelection === 'auto') return;
- await observe(phase.origin, protocolSelection);
+ if (!constrainedProtocol) return;
+ await observe(phase.origin, constrainedProtocol);
return;
}
if (phase.kind === 'inventory') {
@@ -559,10 +576,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
return;
}
if (phase.kind === 'failure') {
- await observe(
- phase.origin,
- protocolSelection === 'auto' ? undefined : protocolSelection,
- );
+ await observe(phase.origin, constrainedProtocol);
}
};
@@ -601,6 +615,19 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
setProtocolSelection(value);
retireProvedEvidence();
};
+ // A vendor is not one more field of the same request. It changes the endpoint
+ // AND the interface the request is made under, so anything observed before the
+ // switch was observed against a different pair — including a report that
+ // `retireProvedEvidence` would have kept, and an ④/failure the new vendor may
+ // simply not have. §1.5: switching resets the URL to the new vendor's official
+ // one, drops the interface selection, and retires the observation outright.
+ const editVendor = (value: string) => {
+ setVendor(value);
+ setBaseUrl(apiKeyVendorPreset(value)?.official_base_url ?? '');
+ setProtocolSelection('auto');
+ setManualOpen(false);
+ setPhase(INITIAL_PHASE);
+ };
const isWorking = phase.kind === 'working';
const formLocked = isWorking || phase.kind === 'save_unconfirmed';
@@ -610,15 +637,25 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
const displayNameValid = optionalTrimmedTextWithin(displayName, SOURCE_DISPLAY_NAME_MAX_LENGTH);
const canObserve = Boolean(baseUrl.trim() && apiKey.trim()) && !formLocked;
const canSubmit = canObserve && displayNameValid;
- const selectedProtocol = protocolSelection === 'auto' ? undefined : protocolSelection;
const protocolIdle = !baseUrl.trim() || !apiKey.trim();
const detecting = isWorking && phase.kind === 'working' && phase.stage === 'observe';
const identified = phase.kind === 'form' && phase.report !== null && Boolean(phase.report.protocol);
const identifiedProtocol = identified && phase.kind === 'form' ? phase.report?.protocol ?? null : null;
// The segments and the summary row are two renderings of one selection, so
// only one of them is on screen at a time: expanded, the pressed segment IS
- // the statement; collapsed, the row carries it.
- const segmentsOpen = phase.kind === 'undetermined' || (manualOpen && !isWorking);
+ // the statement; collapsed, the row carries it. Under a catalog pin neither
+ // the disclosure nor ④'s forced selector may open one: the interface is not
+ // this dialog's to choose, so offering the choice would be offering a control
+ // whose value the request then ignores.
+ const segmentsOpen = !vendorPreset && (phase.kind === 'undetermined' || (manualOpen && !isWorking));
+ // Why the interface is what it is, on every strip that states it. A catalog
+ // pin and a user declaration are the two answers that are not "the response
+ // proved it" — and Auto, which is that third answer, carries no badge.
+ const protocolBadge = vendorPreset
+ ? <span className="model-hub-add-key-protocol-badge">{t('settings.models.addKey.protocol.catalogPinned')}</span>
+ : selectedProtocol
+ ? <span className="model-hub-add-key-protocol-badge">{t('settings.models.addKey.protocol.declared')}</span>
+ : null;
const showForm = phase.kind !== 'inventory';
const replaceTerminalFailure = replacePhase.kind === 'failure'
&& replacePhase.failureClass === 'authoritative-terminal';
@@ -722,6 +759,32 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
{!replaceMode && showForm && (
<div className="model-hub-add-key-body flex flex-col">
+ {/* First, because it is the field the rest are conditioned on: it
+ decides what the Base URL starts as and whether the interface is
+ still a question. Options are the shipped catalog in file order,
+ after the one entry that is not a vendor at all. */}
+ <Field
+ className="model-hub-add-key-field"
+ labelClassName="model-hub-add-key-label"
+ hintClassName="model-hub-add-key-hint"
+ label={t('settings.models.addKey.field.vendor')}
+ hint={t('settings.models.addKey.field.vendor.hint')}
+ >
+ {(id) => (
+ <Select
+ id={id}
+ value={vendor}
+ disabled={formLocked}
+ onChange={(event) => editVendor(event.target.value)}
+ className="model-hub-add-key-input"
+ >
+ <option value={CUSTOM_VENDOR}>{t('settings.models.addKey.field.vendor.custom')}</option>
+ {API_KEY_VENDOR_PRESETS.map((preset) => (
+ <option key={preset.id} value={preset.id}>{preset.label}</option>
+ ))}
+ </Select>
+ )}
+ </Field>
<Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={t('settings.models.addKey.field.name')}>
{(id) => <Input id={id} value={displayName} disabled={formLocked} aria-invalid={!displayNameValid} onChange={(event) => editDisplayName(event.target.value)} className="model-hub-add-key-input" />}
</Field>
@@ -749,6 +812,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
<span className="model-hub-add-key-strip-title model-hub-ink-gold">{t('settings.models.addKey.undetermined.title')}</span>
<span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.undetermined.detail')}</span>
</div>
+ {protocolBadge}
</div>
)}
{detecting && (
@@ -770,22 +834,31 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
count: phase.kind === 'form' && phase.report ? phase.report.models.length : 0,
})}
</span>
+ {protocolBadge}
</div>
)}
{phase.kind === 'form' && !phase.report && !segmentsOpen && (
<div className="model-hub-add-key-protocol-idle-row">
- {/* Whatever 检测 is about to send, and nothing else: a concrete
- choice is the active constraint even while the disclosure
- that made it is closed. */}
+ {/* Whatever 检测 is about to send, and nothing else: a catalog
+ pin and a concrete choice are each the active constraint
+ even while the disclosure that could have made one is shut
+ — or, under a pin, is not offered at all. */}
<span className="model-hub-add-key-protocol-active">
- {selectedProtocol && <ProtocolGlyph protocol={selectedProtocol} />}
- {t(selectedProtocol
- ? PROTOCOL_COPY_KEYS[selectedProtocol]
+ {constrainedProtocol && <ProtocolGlyph protocol={constrainedProtocol} />}
+ {t(constrainedProtocol
+ ? PROTOCOL_COPY_KEYS[constrainedProtocol]
: 'settings.models.addKey.protocol.auto')}
</span>
- {/* The hint promises automatic identification, which is only
- what Auto does. A named interface has already answered it. */}
- {!selectedProtocol && (
+ {/* The pin is the reason this row has no control beside it, so
+ it says so here rather than only on the strip 检测 returns. */}
+ {vendorPreset && protocolBadge}
+ {/* The idle hint promises automatic identification, which is
+ only what Auto does. A named interface has already answered
+ it; a pin answers a different question — what 检测 still has
+ to establish once the interface is no longer in doubt. */}
+ {vendorPreset ? (
+ <span className="model-hub-add-key-hint">{t('settings.models.addKey.protocol.catalogPinned.hint')}</span>
+ ) : !selectedProtocol && (
<span className="model-hub-add-key-hint">{t('settings.models.addKey.protocol.idleHint')}</span>
)}
</div>
@@ -800,7 +873,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
<p className="model-hub-add-key-hint">{t('settings.models.addKey.field.protocol.hint')}</p>
</div>
)}
- {!isWorking && phase.kind !== 'undetermined' && (
+ {!vendorPreset && !isWorking && phase.kind !== 'undetermined' && (
<button
type="button"
className="model-hub-add-key-protocol-disclosure"
@@ -916,7 +989,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
variant="brand"
className="model-hub-add-key-action"
disabled={!canSubmit}
- onClick={() => void observe('add', selectedProtocol)}
+ onClick={() => void observe('add', constrainedProtocol)}
>
{t('settings.models.addKey.detect')}
</Button>
@@ -946,10 +1019,10 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
variant="brand"
className={cn(
'model-hub-add-key-action',
- (phase.kind === 'inventory' || phase.kind === 'save_unconfirmed' || (phase.kind === 'undetermined' && protocolSelection === 'auto'))
+ (phase.kind === 'inventory' || phase.kind === 'save_unconfirmed' || (phase.kind === 'undetermined' && !constrainedProtocol))
&& 'model-hub-add-key-action--dim',
)}
- disabled={phase.kind === 'undetermined' && protocolSelection === 'auto'}
+ disabled={phase.kind === 'undetermined' && !constrainedProtocol}
onClick={() => void retry()}
>
{t('settings.models.addKey.retry')}
diff --git a/ui/src/components/settings/models/apiKeyVendors.test.ts b/ui/src/components/settings/models/apiKeyVendors.test.ts
new file mode 100644
index 000000000..95c29c353
--- /dev/null
+++ b/ui/src/components/settings/models/apiKeyVendors.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+
+import { API_KEY_VENDOR_PRESETS, apiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';
+import { SOURCE_PROTOCOLS } from './types';
+
+// The dialog casts the shipped JSON to its preset type on the strength of the
+// Python loader's validation. These hold the file to the same properties from
+// this side, so a row that would render a broken dropdown — an unpinnable
+// protocol, a blank label, a second `custom` — fails here instead of at the
+// moment a user picks it. Stated as properties over every row, never as a list
+// of the vendors that happen to ship today.
+describe('the shipped API-key vendor catalog', () => {
+ it('offers something to pick', () => {
+ expect(API_KEY_VENDOR_PRESETS.length).toBeGreaterThan(0);
+ });
+
+ it('pins every row to an interface this UI can name', () => {
+ for (const preset of API_KEY_VENDOR_PRESETS) {
+ expect(SOURCE_PROTOCOLS).toContain(preset.protocol);
+ }
+ });
+
+ it('gives every row an id, a label, and an absolute official address', () => {
+ for (const preset of API_KEY_VENDOR_PRESETS) {
+ expect(preset.id.trim()).not.toBe('');
+ expect(preset.label.trim()).not.toBe('');
+ expect(preset.official_base_url).toMatch(/^https?:\/\/\S+$/);
+ }
+ });
+
+ // The Python reader normalizes as it loads — `normalize_model_hub_vendor_id`
+ // lowercases and trims the id, `label.strip()` the label. This reader does
+ // not: it hands the raw JSON to the dropdown and sends the raw id. That is
+ // only equivalent while the shipped file is ALREADY in normal form, so the
+ // equivalence is asserted here rather than assumed. A row that needed
+ // normalizing would otherwise put a differently-spelled id on the wire than
+ // the one the server stores.
+ it('ships every row already in the form the Python reader would normalize it to', () => {
+ for (const preset of API_KEY_VENDOR_PRESETS) {
+ expect(preset.id).toBe(preset.id.trim().toLowerCase());
+ // The persisted vendor-id grammar, from `normalize_model_hub_vendor_id`.
+ expect(preset.id).toMatch(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/);
+ expect(preset.label).toBe(preset.label.trim());
+ expect(preset.official_base_url).toBe(preset.official_base_url.trim());
+ }
+ });
+
+ it('names each vendor once, and never names the one option that is not a vendor', () => {
+ const ids = API_KEY_VENDOR_PRESETS.map((preset) => preset.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(ids).not.toContain(CUSTOM_VENDOR);
+ });
+
+ it('resolves a row by its id, and anything else to no preset at all', () => {
+ for (const preset of API_KEY_VENDOR_PRESETS) {
+ expect(apiKeyVendorPreset(preset.id)).toBe(preset);
+ }
+ // Both the custom option and an id a later catalog dropped land here: with no
+ // preset there is no pin, which is the rung that asks rather than the rung
+ // that would assert an interface nothing defines.
+ expect(apiKeyVendorPreset(CUSTOM_VENDOR)).toBeNull();
+ expect(apiKeyVendorPreset('a-vendor-this-catalog-does-not-carry')).toBeNull();
+ });
+});
diff --git a/ui/src/components/settings/models/apiKeyVendors.ts b/ui/src/components/settings/models/apiKeyVendors.ts
new file mode 100644
index 000000000..b288c5b2a
--- /dev/null
+++ b/ui/src/components/settings/models/apiKeyVendors.ts
@@ -0,0 +1,39 @@
+// The Web UI half of the shipped API-key vendor catalog. This reads the SAME
+// tracked file as ``vibe/model_hub_runtime/api_key_vendors.py`` — there is
+// deliberately no TypeScript copy of the ids, labels, official base URLs or
+// pinned protocols. A second copy is exactly how a preset's URL drifts from the
+// one the server pins its protocol by, and the drift would surface as a
+// `discovery_failed` the user cannot explain. Vite inlines the JSON at build
+// time, so the browser bundle carries the values with no runtime coupling to the
+// Python package — the same arrangement as ``src/lib/messageTypes.ts`` and
+// ``vibe/message_types.json``.
+//
+// The Python loader is the validating authority: it refuses a catalog carrying a
+// `custom` id, a duplicate id, a blank label, or an unsupported protocol, and
+// the service does not start until the file is valid. The assertion below trusts
+// that check rather than restating it in a second place; `apiKeyVendors.test.ts`
+// holds the shipped file to it from this side too, so a bad row fails a test
+// instead of rendering a dropdown that pins a protocol nothing defines.
+import catalog from '../../../../../vibe/data/api_key_vendors.json';
+import type { SourceProtocol } from './types';
+
+export type ApiKeyVendorPreset = {
+ id: string;
+ label: string;
+ official_base_url: string;
+ protocol: SourceProtocol;
+};
+
+/** The dropdown's default, and the ladder's rungs 2 and 3: no preset, no pin.
+ * It is the one vendor id the catalog may never contain. */
+export const CUSTOM_VENDOR = 'custom';
+
+/** Catalog order is file order. The backend ships the list already ranked, and
+ * re-sorting it here would put the ranking in a second place. */
+export const API_KEY_VENDOR_PRESETS = catalog as readonly ApiKeyVendorPreset[];
+
+/** The preset a vendor id names, or `null` for 自定义 — which is also what an id
+ * the shipped catalog no longer carries resolves to, so a row dropped upstream
+ * degrades to the custom path rather than pinning a protocol nothing defines. */
+export const apiKeyVendorPreset = (vendor: string): ApiKeyVendorPreset | null =>
+ API_KEY_VENDOR_PRESETS.find((preset) => preset.id === vendor) ?? null;
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index b6a5b7130..12fffc660 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -562,6 +562,7 @@
--model-hub-add-key-strip-gap: 10px;
--model-hub-add-key-strip-radius: 9px;
--model-hub-add-key-inventory-height: 59px;
+ --model-hub-add-key-badge-size: 10px;
--model-hub-add-key-strip-title-size: 12px;
--model-hub-add-key-strip-detail-size: 10.5px;
--model-hub-add-key-strip-detail-line: 16px;
@@ -621,6 +622,13 @@
padding-inline: var(--model-hub-add-key-input-padding);
font-size: var(--model-hub-add-key-input-size);
}
+/* Same field surface, one exception: `Select` lays its chevron over the trailing
+ edge, so the shared inline padding has to leave that side room. Qualified by
+ element rather than by a second class, which would make every future select
+ here a call site that can forget it. */
+.model-hub-add-key-input:is(select) {
+ padding-inline-end: calc(var(--model-hub-add-key-input-padding) + 20px);
+}
.model-hub-add-key-secret { width: 100%; }
.model-hub-add-key-hint {
color: var(--model-hub-muted-b3);
@@ -646,10 +654,37 @@
align-items: baseline;
gap: 8px;
}
+/* The element that carries the statement is the element that sizes it. The idle
+ row holds two deliberately different scales -- this 12px statement and the
+ 10.5px hint beside it -- so the scale sits on each child rather than on the row
+ the way the single-child detecting row does. Color stays inherited so the
+ row's `.is-idle` dimming keeps applying to it. */
.model-hub-add-key-protocol-active {
display: inline-flex;
align-items: center;
gap: 6px;
+ font-size: var(--model-hub-add-key-strip-title-size);
+ font-weight: 600;
+}
+/* Why the interface beside it is settled, on the idle row and on both result
+ strips. It declares its own size for the same reason the statement does, and
+ takes both border and ink from `currentColor` so it annotates whatever it sits
+ in -- mint inside ①″ -- rather than introducing an ink of its own. On a strip
+ it goes to the trailing edge, out of the way of text that wraps; on the idle
+ row it stays in the reading order, between the statement and its hint. */
+.model-hub-add-key-protocol-badge {
+ flex-shrink: 0;
+ align-self: center;
+ border: 1px solid currentColor;
+ border-radius: 999px;
+ padding: 1px 7px;
+ opacity: 0.75;
+ font-size: var(--model-hub-add-key-badge-size);
+ font-weight: 600;
+ white-space: nowrap;
+}
+.model-hub-add-key-strip .model-hub-add-key-protocol-badge {
+ margin-inline-start: auto;
}
.model-hub-add-key-protocol-manual {
flex-direction: column;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b23923022..92859ebdc 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1368,6 +1368,9 @@
"title": "Add API key",
"subtitle": "Detect the connection and interface first, then confirm to add",
"field": {
+ "vendor": "Vendor",
+ "vendor.custom": "Custom · compatible endpoint",
+ "vendor.hint": "Pick DeepSeek, Qwen, Kimi and the like to prefill the official address and pin the interface",
"name": "Name (optional)",
"protocol": "Interface type",
"protocol.hint": "Use Auto detect when unsure; choose a type to declare that interface. If authentication succeeds it can be added, a wrong choice can fail at runtime, and the saved type cannot be changed",
@@ -1412,7 +1415,10 @@
"openaiChatCompletions": "OpenAI Chat Completions",
"idleHint": "Identified automatically once Base URL and API key are filled",
"detecting": "Identifying the interface…",
- "manual": "Manually specify interface type"
+ "manual": "Manually specify interface type",
+ "catalogPinned": "Built-in catalog",
+ "catalogPinned.hint": "Detection authenticates the key and fetches models; it no longer has to prove the interface by its response shape",
+ "declared": "Manually specified"
},
"inventory": {
"title": "The interface is identified — but its model list did not come back this time"
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 0caa0bf20..6e11dcd43 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1368,6 +1368,9 @@
"title": "添加 API Key",
"subtitle": "先检测连接与接口,确认后添加",
"field": {
+ "vendor": "服务商",
+ "vendor.custom": "自定义 · 兼容端点",
+ "vendor.hint": "选 DeepSeek / Qwen / Kimi 等时,预填官方地址并钉死接口",
"name": "名称(可选)",
"protocol": "接口类型",
"protocol.hint": "不确定时用自动探测;已知类型时可直接声明所选接口。该路径鉴权成功即可添加;选错了运行时可能失败,而且保存后不可更改",
@@ -1412,7 +1415,10 @@
"openaiChatCompletions": "OpenAI Chat Completions",
"idleHint": "填好 Base URL 和 API Key 后自动识别",
"detecting": "识别接口中…",
- "manual": "手动指定接口类型"
+ "manual": "手动指定接口类型",
+ "catalogPinned": "内置目录",
+ "catalogPinned.hint": "检测会验证密钥并拉取模型;不再需要靠返回结构证明接口",
+ "declared": "手动指定"
},
"inventory": {
"title": "接口已经识别,但这次没有拿到模型清单"
diff --git a/ui/vite.config.ts b/ui/vite.config.ts
index 8c9f2616b..d9324e396 100644
--- a/ui/vite.config.ts
+++ b/ui/vite.config.ts
@@ -45,16 +45,20 @@ export default defineConfig({
},
server: {
fs: {
- // ``src/lib/messageTypes.ts`` imports the repo-root ``vibe/message_types.json``
- // policy catalog so the Web UI and the Python readers share one declaration.
+ // Two shipped catalogs are read by both the Web UI and a Python module, from
+ // one tracked file each rather than from a copy per reader:
+ // ``src/lib/messageTypes.ts`` imports ``vibe/message_types.json``, and
+ // ``src/components/settings/models/apiKeyVendors.ts`` imports
+ // ``vibe/data/api_key_vendors.json``.
// ``ui/package-lock.json`` makes Vite infer ``ui/`` as the workspace root, which
- // would put that file outside the dev server's default allow list; production
- // builds inline the JSON and are unaffected. Allow the UI root plus that one
- // file — not their common ancestor, which would serve the rest of the checkout
+ // would put both files outside the dev server's default allow list; production
+ // builds inline the JSON and are unaffected. Allow the UI root plus those exact
+ // files — not their common ancestor, which would serve the rest of the checkout
// over ``/@fs/`` to anything that can reach the dev server.
allow: [
fileURLToPath(new URL('.', import.meta.url)),
fileURLToPath(new URL('../vibe/message_types.json', import.meta.url)),
+ fileURLToPath(new URL('../vibe/data/api_key_vendors.json', import.meta.url)),
],
},
proxy: {