From 6e5d5b5d859819393b3b80f4b1e3f110ea0f5bd3 Mon Sep 17 00:00:00 2001 From: Weiming Liao Date: Mon, 23 Nov 2026 14:33:17 +0800 Subject: [PATCH 1/2] [bugfix] providers: fetch the live text model list Signed-off-by: Weiming Liao --- apps/api/src/opendirector_api/localization.py | 7 + docs/development/validation.md | 2 +- .../integrations/model_capabilities.py | 8 +- scripts/run-browser-suite.mjs | 1 + src/canvas/ModelPicker.tsx | 42 +++-- src/canvas/ModelServiceForm.tsx | 37 +++-- src/i18n/messages/en-US/generation.ts | 10 ++ src/i18n/messages/zh-CN/generation.ts | 4 + tests/browser/manifest.json | 5 +- tests/browser/moss_provider.mjs | 23 ++- tests/browser/provider_settings.mjs | 20 ++- tests/browser/zhipu_provider.mjs | 153 ++++++++++++++++-- tests/test_model_configs.py | 21 ++- 13 files changed, 268 insertions(+), 65 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 5018e4146..ca5ae3605 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -4,6 +4,8 @@ chooses an English message from the stable error code when the caller asks for English, so a missing translation never leaks Chinese into an English UI. """ +import re + from fastapi import Request @@ -98,6 +100,7 @@ "role_restricted": "This item does not allow that operation.", "storage_unavailable": "A stored file is missing or has changed. Restore the file and try again.", "capability_unsupported": "This capability is not supported yet.", + "model_list_http_error": "Could not load the model list from the service.", "operation_rejected": "The operation was rejected. Reload the item and try again.", "storage_busy": "Project storage is busy. Try again shortly.", "project_open_elsewhere": "This project is open in another window. Close it there and try again.", @@ -150,6 +153,10 @@ def localized_error_for_language( return chinese if code == 'tool_model_missing': return missing_tool_model_message(required_capability, english=True) + if code == 'model_list_http_error': + upstream_status = re.search(r'HTTP ([0-9]{3})', chinese) + if upstream_status: + return f'Could not load the model list (HTTP {upstream_status[1]}).' if code.startswith(('capability_', 'image_input_', 'tool_source_')): translated = english_capability_message(chinese) if translated: diff --git a/docs/development/validation.md b/docs/development/validation.md index 134744d1b..c204af04a 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -612,7 +612,7 @@ CREATION_API_URL=http://127.0.0.1:8019 CREATION_WEB_URL=http://127.0.0.1:5179 no The Python cases check how the shared thinking levels map to GLM reasoning_effort. GLM accepts only low, high and max for reasoning_effort. The auto level omits the parameter so the provider default applies, and an unknown level falls back to high as in the DeepSeek branch. Other hosts and the DeepSeek behavior stay unchanged. -The browser case checks both display languages for the provider list and names, canonical URL prefill, GLM model preselection without remote discovery, manual addition of other model IDs, the saved connection reuse hint, save and reopen, key privacy in public model responses, and the assistant agent picker listing and keeping the selected Zhipu model. The browser never contacts open.bigmodel.cn and the API key is always a fixture value. Real streaming conversations, tool call execution and thinking level effects additionally require valid Zhipu credentials. Keep the conversation transcript, tool receipts and screenshots as evidence. +The PR browser gate checks both display languages. Choosing the Zhipu text preset preselects suggested models. Fetching text models sends an authenticated `GET /models` through the discovery API and makes a new model ID selectable. An upstream HTTP failure is visible and manual entry remains available. Loading the Zhipu audio preset lists only `glm-tts` and sends no discovery request. The case also checks save and reopen, key privacy, and the assistant model picker. It uses an isolated HTTP fixture with a synthetic API key. Real streaming conversations, tool calls, and thinking levels require a separate run with valid Zhipu credentials. 智谱 BigModel GLM-TTS 接入使用以下检查: diff --git a/packages/core/src/opendirector/integrations/model_capabilities.py b/packages/core/src/opendirector/integrations/model_capabilities.py index bd5072550..2305b9048 100644 --- a/packages/core/src/opendirector/integrations/model_capabilities.py +++ b/packages/core/src/opendirector/integrations/model_capabilities.py @@ -1,4 +1,4 @@ -"""Read an optional, explicit videoCapabilities extension on GET /models.""" +"""Read service model lists and resolve video capabilities.""" import json import logging @@ -23,18 +23,20 @@ async def read_service_models(config, transport=None): return [{'id': name, 'videoCapabilities': kling_capabilities(name)} for name in KLING_MODELS] if config.get('protocol') == 'minimax_video_v2': return [{'id': name} for name in MINIMAX_MODELS] + is_text_model = config.get('kind') == 'agent' try: async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=transport, trust_env=trust_environment(config['url'], config=config), timeout=15, follow_redirects=False) as client: async with client.stream('GET', endpoint(config['url'], '/models'), headers=auth_headers(config)) as response: if response.status_code != 200: - raise ProjectError(f'读取模型声明失败(HTTP {response.status_code}),未修改配置。') + raise ProjectError(f'读取模型声明失败(HTTP {response.status_code}),未修改配置。', + code='model_list_http_error' if is_text_model else None) data = bytearray() async for chunk in response.aiter_bytes(): data.extend(chunk) if len(data) > 1024 * 1024: raise ProjectError('模型声明超过 1 MB,未修改配置。') - models = json.loads(data).get('data', []) + models = json.loads(data).get('data', None if is_text_model else []) if not isinstance(models, list) or any(not isinstance(item, dict) or not isinstance(item.get('id'), str) or not item['id'].strip() or len(item['id']) > 200 for item in models): raise ProjectError('服务返回的模型列表格式无效。') diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index 48291194c..c4044ab74 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -32,6 +32,7 @@ const workflows = [ }, { name: "minimax h3", script: "tests/browser/minimax_h3.mjs" }, { name: "provider settings", script: "tests/browser/provider_settings.mjs" }, + { name: "provider model discovery", script: "tests/browser/zhipu_provider.mjs" }, { name: "capability discovery", script: "tests/browser/capability_discovery.mjs" }, { name: "created node focus", script: "tests/browser/created_node_focus.mjs" }, { name: "cross canvas paste", script: "tests/browser/cross_canvas_paste.mjs" }, diff --git a/src/canvas/ModelPicker.tsx b/src/canvas/ModelPicker.tsx index 364285f5b..eb5ded86e 100644 --- a/src/canvas/ModelPicker.tsx +++ b/src/canvas/ModelPicker.tsx @@ -14,6 +14,7 @@ export function ModelPicker({ selected, loaded, loading, + loadsPreset, error, disabled, canFetch, @@ -22,13 +23,13 @@ export function ModelPicker({ onTest, results, renderDetails, - fetchLabel, }: { modelPlaceholder: string; available: string[]; selected: string[]; loaded: boolean; loading: boolean; + loadsPreset: boolean; error: string; disabled: boolean; canFetch: boolean; @@ -37,7 +38,6 @@ export function ModelPicker({ onTest?: (id: string) => void; results: Record; renderDetails?: (id: string) => ReactNode; - fetchLabel?: string; }) { const t = useT(); const manualFieldId = useId(); @@ -55,6 +55,17 @@ export function ModelPicker({ ); const allSelected = visible.length > 0 && visible.every((id) => selected.includes(id)); + const fetchLabel = loadsPreset + ? "models.service.loadSupportedModels" + : loaded ? "generation.picker.refresh" : "generation.picker.fetch"; + let status = ""; + if (loading) { + status = t("generation.picker.fetching"); + } else if (loaded && !error) { + status = available.length + ? t(loadsPreset ? "generation.picker.loadedPreset" : "generation.picker.fetched", { count: available.length }) + : t("generation.picker.noReturned"); + } const addManual = () => { const id = manualId.trim(); if (!id || id.length > 200 || /[\x00-\x1f]/.test(id)) { @@ -101,18 +112,21 @@ export function ModelPicker({ +
+ {status &&

{status}

} +
+ {error && ( +

+ {error} +

+ )} {manualOpen && (
)} - {error && ( -

- {t("generation.picker.retry", { error })} -

- )} {ids.length > 4 && ( <>
@@ -209,15 +218,14 @@ export function ModelPicker({ )}
{loading && !ids.length ? ( -
+
- {t("generation.picker.fetching")}

{t("generation.picker.connecting")}

) : !ids.length ? (
- {loaded ? t("generation.picker.noReturned") : t("generation.picker.noneAdded")} + {!loaded && {t("generation.picker.noneAdded")}}

{loaded ? t("generation.picker.manualHint") diff --git a/src/canvas/ModelServiceForm.tsx b/src/canvas/ModelServiceForm.tsx index 05eff8044..3d23f206a 100644 --- a/src/canvas/ModelServiceForm.tsx +++ b/src/canvas/ModelServiceForm.tsx @@ -145,15 +145,19 @@ export function ModelServiceForm({ const segmentation = value.protocol === "vllm_omni_segmentation"; const depth = value.protocol === "vllm_omni_depth"; const score = value.protocol === "vllm_omni_score"; + const preset = PROVIDER_PRESETS.find((item) => item.id === presetId); + const mediaPresetModels = kind === "agent" ? undefined : preset?.modelsByKind?.[kind]; const hasSavedKey = Boolean( connection && connection.authMode === "bearer" && connection.url === value.url.trim(), ); - const canFetch = Boolean( - value.url.trim() && - (value.authMode === "none" || value.apiKey.trim() || hasSavedKey), - ); + const fetchPrerequisite = !value.url.trim() + ? "generation.picker.addressRequired" + : value.authMode === "bearer" && !value.apiKey.trim() && !hasSavedKey + ? "generation.picker.keyRequired" + : null; + const canFetch = fetchPrerequisite === null; const canSave = canFetch && selectedModels.length > 0 && selectedModels.length <= 200 && !selectedTestFailed && !selectedModels.some((id) => modelErrors[id]); const update = (patch: Partial) => { @@ -174,7 +178,7 @@ export function ModelServiceForm({ patch.protocol !== undefined || patch.connectionType !== undefined || patch.authMode !== undefined; - if (connectionChanged) { + if (connectionChanged || patch.proxyMode !== undefined) { setModelIds(selectedModels); setLoaded(false); setDiscoveryError(""); @@ -198,20 +202,23 @@ export function ModelServiceForm({ setError(""); }; const loadModels = async () => { + if (fetchPrerequisite) { + setDiscoveryError(t(fetchPrerequisite)); + if (fetchPrerequisite === "generation.picker.addressRequired") setConnectionOpen(true); + return; + } setDiscovering(true); setDiscoveryError(""); try { - const preset = PROVIDER_PRESETS.find((item) => item.id === presetId); - const presetModels = preset?.modelsByKind?.[kind]; - const models = presetModels - ? [...presetModels] + const models = mediaPresetModels + ? [...mediaPresetModels] : (await discoverModels(value, connection?.id)).models; setModelIds(models); - if (presetModels && !connection) setSelectedModels(models); + if (mediaPresetModels && !connection) setSelectedModels(models); setLoaded(true); setConnectionOpen(false); } catch (failure) { - setDiscoveryError(errorMessage(failure)); + setDiscoveryError(t("generation.picker.retry", { error: errorMessage(failure) })); } finally { setDiscovering(false); } @@ -320,6 +327,8 @@ export function ModelServiceForm({ ); setSelectedModels(peers.map((item) => item.modelId)); setModelIds(peers.map((item) => item.modelId)); + setLoaded(false); + setDiscoveryError(""); setModelOptions({}); setModelErrors({}); setResults({}); @@ -524,6 +533,7 @@ export function ModelServiceForm({ selected={selectedModels} loaded={loaded} loading={discovering} + loadsPreset={Boolean(mediaPresetModels)} error={discoveryError} disabled={locked} canFetch={canFetch} @@ -534,11 +544,6 @@ export function ModelServiceForm({ }} onTest={kind === "agent" ? (id) => void test(id) : undefined} results={results} - fetchLabel={ - PROVIDER_PRESETS.find((item) => item.id === presetId)?.modelsByKind?.[kind] - ? t("models.service.loadSupportedModels") - : undefined - } renderDetails={(id) => ( <> diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index 542afa478..018b79425 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -216,6 +216,8 @@ export const generation = { "generation.picker.modelId": "Model ID (the service's served-model-name)", "generation.picker.add": "Add", "generation.picker.cancel": "Cancel", + "generation.picker.addressRequired": "Enter the service address first.", + "generation.picker.keyRequired": "Enter an API Key first.", "generation.picker.retry": "{error} You can retry or add a model manually.", "generation.picker.search": "Search models", "generation.picker.searchPlaceholder": "Search model names…", @@ -227,6 +229,14 @@ export const generation = { "generation.picker.selectAll": "Select all current results", "generation.picker.deselectAll": "Deselect all", "generation.picker.fetching": "Fetching the model list", + "generation.picker.fetched": { + one: "{count} model fetched", + other: "{count} models fetched", + }, + "generation.picker.loadedPreset": { + one: "{count} preset model loaded", + other: "{count} preset models loaded", + }, "generation.picker.connecting": "Connecting to the service…", "generation.picker.noReturned": "The service returned no models", "generation.picker.noneAdded": "No models added yet", diff --git a/src/i18n/messages/zh-CN/generation.ts b/src/i18n/messages/zh-CN/generation.ts index 4e6184e66..5a6697af9 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -201,6 +201,8 @@ export const generation = { "generation.picker.modelId": "Model ID(服务的 served-model-name)", "generation.picker.add": "添加", "generation.picker.cancel": "取消", + "generation.picker.addressRequired": "请先填写服务地址。", + "generation.picker.keyRequired": "请先填写 API Key。", "generation.picker.retry": "{error} 可重试或手动添加模型。", "generation.picker.search": "搜索模型", "generation.picker.searchPlaceholder": "搜索模型名称…", @@ -209,6 +211,8 @@ export const generation = { "generation.picker.selectAll": "全选当前结果", "generation.picker.deselectAll": "取消当前全选", "generation.picker.fetching": "正在获取模型列表", + "generation.picker.fetched": "已获取 {count} 个模型", + "generation.picker.loadedPreset": "已载入 {count} 个预设模型", "generation.picker.connecting": "正在连接服务,请稍候…", "generation.picker.noReturned": "服务未返回模型", "generation.picker.noneAdded": "尚未添加模型", diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index 48ce10d17..a5bcdac38 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -556,8 +556,9 @@ "file": "zhipu_provider.mjs", "previewSafe": true, "lanes": [ - "extended" - ] + "gate" + ], + "note": "Bilingual model discovery through the API and a loopback GET /models service, including upstream failure and retry." }, { "file": "kimi_real.mjs", diff --git a/tests/browser/moss_provider.mjs b/tests/browser/moss_provider.mjs index b3cab056e..32d999336 100644 --- a/tests/browser/moss_provider.mjs +++ b/tests/browser/moss_provider.mjs @@ -15,6 +15,7 @@ const speechModelIds = ["moss-tts-1.5-flash", "moss-tts-1.0-pro", "moss-tts-1.5-flash-2026-06-26", "moss-tts-1.0-pro-2026-02-07"]; const canonicalURL = "https://api.mosi.cn/v1"; const fixtureKey = "moss-browser-fixture-only-no-real-service"; +const discoveryPath = "/api/model-configs/discover"; const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; async function call(path, { method = "GET", body } = {}) { const response = await fetch(api + path, { @@ -50,14 +51,16 @@ const copy = { "zh-CN": { settings: "设置", models: "模型接入", imageOverview: "图片模型", image: "图片", audio: "音频", add: "添加服务", provider: "提供商", moss: "MOSS 开放平台", url: "服务地址(Base URL)", - reload: "载入支持的模型", save: "保存服务", cancel: "取消", manage: "管理", close: "关闭设置", + reload: "载入支持的模型", presetLoaded: count => `已载入 ${count} 个预设模型`, + save: "保存服务", cancel: "取消", manage: "管理", close: "关闭设置", general: "通用", language: "语言", defaultImage: "vLLM-Omni 图片接口", defaultAudio: "vLLM-Omni 语音合成接口", custom: "OpenAI 兼容", fetch: "获取模型", discoveryError: "服务返回 HTTP 401,请检查 API Key。", }, "en-US": { settings: "Settings", models: "Model connections", imageOverview: "Image model", image: "Image", audio: "Audio", add: "Add service", provider: "Provider", moss: "MOSS Open Platform", url: "Service URL (Base URL)", - reload: "Load supported models", save: "Save service", cancel: "Cancel", manage: "Manage", close: "Close settings", + reload: "Load supported models", presetLoaded: count => `${count} preset models loaded`, + save: "Save service", cancel: "Cancel", manage: "Manage", close: "Close settings", general: "General", language: "Language", defaultImage: "vLLM-Omni image API", defaultAudio: "vLLM-Omni speech synthesis API", custom: "OpenAI compatible", fetch: "Fetch models", discoveryError: "Service returned HTTP 401. Check the API Key.", }, @@ -108,10 +111,18 @@ async function provePreset(labels, locale, kind = "image") { await officialLogo(page.locator(".cw-model-option").filter({ has: page.getByRole("checkbox", { name: modelId, exact: true }) }).locator("img.cw-model-logo")); } await page.getByLabel("API Key", { exact: true }).fill(fixtureKey); - await page.getByRole("button", { name: labels.reload, exact: true }).click(); + const endpoint = `**${discoveryPath}`; + await page.route(endpoint, route => route.fulfill({ json: { models: ["fixture-text-only"] } })); + try { + await page.getByRole("button", { name: labels.reload, exact: true }).click(); + await page.getByRole("status").getByText(labels.presetLoaded(expectedModels.length), { exact: true }).waitFor(); + assert.ok(!requests.slice(start).some(url => url.endsWith(discoveryPath)), "Selecting or loading a media preset must not discover remote models"); + assert.equal(await page.locator(".cw-model-option").count(), expectedModels.length); + } finally { + await page.unroute(endpoint); + } for (const modelId of expectedModels) assert.equal(await page.getByRole("checkbox", { name: modelId, exact: true }).isChecked(), true); - assert.ok(!requests.slice(start).some(url => url.includes("/model-configs/discover")), "Preset selection/reload must not discover remote models"); await shot(`${locale}-mock-moss-${kind}-provider.png`); } async function proveReopen(labels, locale, kind = "image") { @@ -152,7 +163,7 @@ async function proveDiscoveryError(labels) { await page.getByRole("option", { name: labels.custom, exact: true }).click(); await page.getByLabel(labels.url, { exact: true }).fill("http://127.0.0.1:12345/v1"); await page.getByLabel("API Key", { exact: true }).fill(fixtureKey); - const endpoint = "**/api/model-configs/discover"; + const endpoint = `**${discoveryPath}`; await page.route(endpoint, route => route.fulfill({ status: 401, contentType: "application/json", body: JSON.stringify({ detail: labels.discoveryError }), @@ -208,7 +219,7 @@ try { console.log(JSON.stringify({ passed: true, fixture: true, generation: "not submitted", base, api, projectURL: `${base}/ai-tool/ai-canvas/${projectId}?creation=unified`, screenshotDirectory: output, modelConfigIds: saved.map(config => config.id), checks: ["Chinese and English", "official local SVG with original colors", - "canonical URL", "SFT and Base preselected without discovery", "speech model only in audio", "save and reopen image and audio", "public models have no key", "discovery failure cause in both languages"] })); + "canonical URL", "image and audio presets load only their own models without discovery", "preset load feedback in both languages", "save and reopen image and audio", "public models have no key", "custom discovery failure cause in both languages"] })); } catch (error) { await shot("mock-moss-provider-failure.png").catch(() => {}); throw error; diff --git a/tests/browser/provider_settings.mjs b/tests/browser/provider_settings.mjs index 5cd8f904c..99b119186 100644 --- a/tests/browser/provider_settings.mjs +++ b/tests/browser/provider_settings.mjs @@ -89,10 +89,21 @@ try { assert.equal(await page.getByRole("checkbox", { name, exact: true }).isChecked(), true); } await page.getByLabel("API Key", { exact: true }).fill("fixture-only"); - await page - .getByRole("button", { name: "Load supported models", exact: true }) - .click(); - await page.getByRole("checkbox", { name: "MiniMax-H3", exact: true }).check(); + const discoveryPath = "/api/model-configs/discover"; + const discoveryEndpoint = `**${discoveryPath}`; + await page.route(discoveryEndpoint, route => route.fulfill({ + json: { models: ["fixture-text-only"] }, + })); + const discoveryStart = calls.length; + try { + await page.getByRole("button", { name: "Load supported models", exact: true }).click(); + await page.getByRole("status").getByText("4 preset models loaded", { exact: true }).waitFor(); + assert.ok(!calls.slice(discoveryStart).some(url => url.endsWith(discoveryPath)), "Loading a native video preset must not discover remote models"); + assert.equal(await page.locator(".cw-model-option").count(), 4); + assert.equal(await page.getByRole("checkbox", { name: "MiniMax-H3", exact: true }).isChecked(), true); + } finally { + await page.unroute(discoveryEndpoint); + } await page .getByText("Text-to-video / first-last frame / multimodal references", { exact: true }).first() .waitFor(); @@ -199,6 +210,7 @@ try { passed: true, checks: [ "provider presets", + "native video preset load feedback without discovery", "official capability card", "independent model modalities", "save without inference", diff --git a/tests/browser/zhipu_provider.mjs b/tests/browser/zhipu_provider.mjs index ca43876bd..eb3c62130 100644 --- a/tests/browser/zhipu_provider.mjs +++ b/tests/browser/zhipu_provider.mjs @@ -1,16 +1,19 @@ -/** Isolated Zhipu BigModel provider UI proof. Saves a fixture key and never calls a model service. +/** Isolated Zhipu BigModel provider UI proof. Discovers models through a loopback service. * Start creation_server.py on 8029 and Vite on 5189 with its API proxy on 8029. * CREATION_WEB_URL, CREATION_API_URL and ZHIPU_SCREENSHOT_DIR override defaults. */ import assert from "node:assert/strict"; import { mkdir } from "node:fs/promises"; +import { createServer } from "node:http"; import { join } from "node:path"; import { launchBrowser } from "./engine.mjs"; const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5189"; const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8029"; const output = process.env.ZHIPU_SCREENSHOT_DIR ?? "/tmp/opendirector-zhipu-evidence"; -const modelIds = ["glm-5.3", "glm-5.3-flash", "glm-5.2"]; +const suggestedIds = ["glm-5.3", "glm-5.3-flash", "glm-5.2"]; +const newModel = "glm-5.4"; +const modelIds = [...suggestedIds, newModel]; const canonicalURL = "https://open.bigmodel.cn/api/paas/v4"; const fixtureKey = "zhipu-browser-fixture-only-no-real-service"; const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; @@ -55,15 +58,23 @@ await call(`/api/creation/projects/${projectId}/commands`, { const copy = { "zh-CN": { - settings: "设置", models: "模型接入", agentOverview: "文本模型", chat: "对话", + settings: "设置", models: "模型接入", agentOverview: "文本模型", chat: "对话", audio: "音频", add: "添加服务", provider: "提供商", zhipu: "智谱 BigModel", url: "服务地址(Base URL)", - reload: "载入支持的模型", save: "保存服务", cancel: "取消", manage: "管理", close: "关闭设置", + fetch: "获取模型", refresh: "刷新列表", retry: "可重试或手动添加模型。", + missingKey: "请先填写 API Key。", pending: "正在获取模型列表", fetched: "已获取 4 个模型", empty: "服务未返回模型", + loadAudioPreset: "载入支持的模型", audioPresetLoaded: "已载入 1 个预设模型", + providerError: "读取模型声明失败(HTTP 503)", + save: "保存服务", cancel: "取消", manage: "管理", close: "关闭设置", chatEntry: "与 AI 对话", manual: "手动添加", manualAdd: "添加", manualId: "Model ID(服务的 served-model-name)", }, "en-US": { - settings: "Settings", models: "Model connections", agentOverview: "Text model", chat: "Chat", + settings: "Settings", models: "Model connections", agentOverview: "Text model", chat: "Chat", audio: "Audio", add: "Add service", provider: "Provider", zhipu: "Zhipu BigModel", url: "Service URL (Base URL)", - reload: "Load supported models", save: "Save service", cancel: "Cancel", manage: "Manage", close: "Close settings", + fetch: "Fetch models", refresh: "Refresh list", retry: "You can retry or add a model manually.", + missingKey: "Enter an API Key first.", pending: "Fetching the model list", fetched: "4 models fetched", empty: "The service returned no models", + loadAudioPreset: "Load supported models", audioPresetLoaded: "1 preset model loaded", + providerError: "Could not load the model list (HTTP 503).", + save: "Save service", cancel: "Cancel", manage: "Manage", close: "Close settings", chatEntry: "Chat with AI", manual: "Add manually", manualAdd: "Add", manualId: "Model ID (the service's served-model-name)", }, }; @@ -77,6 +88,28 @@ await page.addInitScript(() => { }); const requests = []; const errors = []; +const modelRequests = []; +let catalogStatus = 200; +let catalogModelIds = modelIds; +let catalogResponseReady = Promise.resolve(); +const catalogPath = new URL(canonicalURL).pathname; +const catalog = createServer(async (request, response) => { + const expectedRequest = { + method: request.method, + path: request.url, + authorized: request.headers.authorization === `Bearer ${fixtureKey}`, + }; + modelRequests.push(expectedRequest); + if (request.method !== "GET" || request.url !== `${catalogPath}/models` || !expectedRequest.authorized) { + response.writeHead(400).end(); + return; + } + const status = catalogStatus; + const ids = catalogModelIds; + await catalogResponseReady; + response.writeHead(status, { "Content-Type": "application/json" }); + response.end(JSON.stringify(status === 200 ? { data: ids.map(id => ({ id })) } : {})); +}); page.on("request", request => requests.push(request.url())); page.on("pageerror", error => errors.push(error.message)); const shot = name => page.screenshot({ path: join(output, name), fullPage: true }); @@ -96,26 +129,77 @@ async function openAgentCategory(labels) { .filter({ has: page.locator("strong", { hasText: new RegExp(`^${labels.agentOverview}$`) }) }) .getByRole("button").click(); } +async function discoverWithFeedback(button, labels, resultText = labels.fetched) { + const picker = page.locator(".cw-model-picker"); + const pending = picker.getByText(labels.pending, { exact: true }); + const fetched = picker.getByText(labels.fetched, { exact: true }); + const { promise, resolve } = Promise.withResolvers(); + catalogResponseReady = promise; + try { + await button.click(); + await pending.waitFor({ timeout: 5000 }); + await fetched.waitFor({ state: "hidden", timeout: 5000 }); + } finally { + resolve(); + } + await picker.getByText(resultText, { exact: true }).waitFor(); + await pending.waitFor({ state: "hidden" }); +} async function provePreset(labels, locale) { await page.getByRole("button", { name: labels.add, exact: true }).click(); - const start = requests.length; + const start = modelRequests.length; await provider(labels).click(); const option = page.getByRole("option", { name: labels.zhipu, exact: true }); await brandLogo(option.locator("img.cw-model-logo")); await option.click(); assert.equal(await provider(labels).innerText(), labels.zhipu); assert.equal(await page.getByLabel(labels.url, { exact: true }).inputValue(), canonicalURL); - assert.equal(await page.locator(".cw-model-option").count(), modelIds.length); + assert.equal(await page.locator(".cw-model-option").count(), suggestedIds.length); await brandLogo(provider(labels).locator("img.cw-model-logo")); - for (const modelId of modelIds) { + for (const modelId of suggestedIds) { assert.equal(await page.getByRole("checkbox", { name: modelId, exact: true }).isChecked(), true); await brandLogo(optionRow(modelId).locator("img.cw-model-logo")); } + assert.equal(modelRequests.length, start, "Selecting a preset must not query the provider"); + const fetchModels = page.getByRole("button", { name: labels.fetch, exact: true }); + const refresh = page.getByRole("button", { name: labels.refresh, exact: true }); + const discovered = page.getByRole("checkbox", { name: newModel, exact: true }); + const startBrowserRequests = requests.length; + assert.equal(await fetchModels.isEnabled(), true, "Users must be able to ask why discovery cannot start"); + await fetchModels.click(); + const missingKey = page.getByRole("alert").filter({ hasText: labels.missingKey }); + await missingKey.waitFor(); + assert.equal(modelRequests.length, start, "Missing credentials must not reach the provider"); + assert.ok(!requests.slice(startBrowserRequests).some(url => url.includes("/model-configs/discover")), + "Missing credentials must not start discovery"); + await page.getByLabel("API Key", { exact: true }).fill(fixtureKey); - await page.getByRole("button", { name: labels.reload, exact: true }).click(); - for (const modelId of modelIds) + catalogStatus = 503; + await fetchModels.click(); + const failure = page.getByRole("alert").filter({ hasText: labels.retry }); + await failure.waitFor(); + assert.ok((await failure.innerText()).includes(labels.providerError)); + assert.equal(await fetchModels.isEnabled(), true, "A failed query remains available for retry"); + assert.equal(await refresh.count(), 0, "An error must not mark model discovery successful"); + assert.equal(await discovered.count(), 0, "An error must not introduce a discovered model"); + assert.equal(await page.getByRole("button", { name: labels.manual, exact: true }).isEnabled(), true); + catalogStatus = 200; + await discoverWithFeedback(fetchModels, labels); + await refresh.waitFor(); + await failure.waitFor({ state: "hidden" }); + assert.equal(await discovered.isChecked(), false, "Remote IDs require an explicit selection"); + await discovered.check(); + await discoverWithFeedback(refresh, labels); + assert.equal(await discovered.isChecked(), true, "Refreshing must preserve the selected model"); + catalogModelIds = []; + await discoverWithFeedback(refresh, labels, labels.empty); + catalogModelIds = modelIds; + assert.equal(await discovered.isChecked(), true, "An empty result must preserve the selected model"); + for (const modelId of suggestedIds) assert.equal(await page.getByRole("checkbox", { name: modelId, exact: true }).isChecked(), true); - assert.ok(!requests.slice(start).some(url => url.includes("/model-configs/discover")), "Preset selection or reload must not discover remote models"); + assert.deepEqual(modelRequests.slice(start), Array.from({ length: 4 }, () => ({ + method: "GET", path: `${catalogPath}/models`, authorized: true, + })), "Initial load, retry and refresh must query the service catalog with authentication"); await shot(`${locale}-mock-zhipu-provider.png`); } async function proveReopen(labels, locale) { @@ -142,13 +226,30 @@ async function proveManualAdd(labels, locale) { await page.getByRole("button", { name: labels.manual, exact: true }).click(); await page.getByLabel(labels.manualId, { exact: true }).fill("glm-4.7"); await page.locator(".cw-model-manual").getByRole("button", { name: labels.manualAdd, exact: true }).click(); - assert.equal(await page.locator(".cw-model-option").count(), modelIds.length + 1); + assert.equal(await page.locator(".cw-model-option").count(), suggestedIds.length + 1); assert.equal(await page.getByRole("checkbox", { name: "glm-4.7", exact: true }).isChecked(), true); assert.ok(!requests.slice(start).some(url => url.includes("/model-configs/discover")), "Manual add must not discover remote models"); await shot(`${locale}-mock-zhipu-manual-add.png`); await page.getByRole("button", { name: labels.cancel, exact: true }).click(); await page.getByRole("button", { name: labels.add, exact: true }).waitFor(); } +async function proveAudioPreset(labels) { + const startBrowserRequests = requests.length; + const startModelRequests = modelRequests.length; + await page.getByRole("button", { name: labels.audio, exact: true }).click(); + await page.getByRole("button", { name: labels.add, exact: true }).click(); + await provider(labels).click(); + await page.getByRole("option", { name: labels.zhipu, exact: true }).click(); + await page.getByLabel("API Key", { exact: true }).fill(fixtureKey); + await page.getByRole("button", { name: labels.loadAudioPreset, exact: true }).click(); + await page.getByText(labels.audioPresetLoaded, { exact: true }).waitFor(); + assert.equal(await page.locator(".cw-model-option").count(), 1); + assert.equal(await page.getByRole("checkbox", { name: "glm-tts", exact: true }).isChecked(), true); + assert.ok(!requests.slice(startBrowserRequests).some(url => url.endsWith("/api/model-configs/discover")), + "The audio preset must not use the text model catalog"); + assert.equal(modelRequests.length, startModelRequests); + await page.getByRole("button", { name: labels.cancel, exact: true }).click(); +} async function proveAgentPicker(labels, locale) { // Each locale gets a fresh page. The browser context still shares the saved // model configuration. A separate project avoids competing for the current @@ -174,7 +275,7 @@ async function proveAgentPicker(labels, locale) { })); await pickerPage.goto(base + "/ai-tool/ai-canvas/" + pickerProjectId + "?creation=unified"); await pickerPage.locator('.cw-workspace[aria-busy="false"]').waitFor(); - const pickerRow = pickerPage.getByRole("menuitemradio", { name: "glm-5.3", exact: true }); + const pickerRow = pickerPage.getByRole("menuitemradio", { name: newModel, exact: true }); const chatButton = pickerPage.getByRole("button", { name: labels.chatEntry, exact: true }); if (await chatButton.getAttribute("aria-expanded") !== "true") await chatButton.click(); @@ -200,6 +301,24 @@ async function proveAgentPicker(labels, locale) { } try { + await new Promise((resolve, reject) => { + catalog.once("error", reject); + catalog.listen(0, "127.0.0.1", resolve); + }); + const fixtureURL = `http://127.0.0.1:${catalog.address().port}${catalogPath}`; + await page.route(`${new URL(canonicalURL).origin}/**`, route => route.abort()); + await page.route("**/api/model-configs/discover", async route => { + const request = route.request(); + const body = request.postDataJSON(); + assert.equal(request.method(), "POST"); + assert.equal(body.url, canonicalURL, "Use the selected preset's Base URL"); + assert.equal(body.kind, "agent"); + assert.equal(body.protocol, "openai"); + assert.equal(body.apiKey === fixtureKey, true, "Send the entered API Key to the local backend"); + // Preserve the browser's request except for the destination of the backend's GET /models. + const response = await route.fetch({ postData: { ...body, url: fixtureURL } }); + await route.fulfill({ response }); + }); await page.goto(`${base}/ai-tool/ai-canvas/${projectId}?creation=unified`); const zh = copy["zh-CN"]; await page.getByRole("button", { name: zh.settings, exact: true }).click(); @@ -218,6 +337,7 @@ try { } await proveReopen(zh, "zh-CN"); await proveManualAdd(zh, "zh-CN"); + await proveAudioPreset(zh); await page.getByRole("button", { name: zh.close, exact: true }).click(); await proveAgentPicker(zh, "zh-CN"); @@ -232,6 +352,7 @@ try { await page.getByRole("button", { name: en.cancel, exact: true }).click(); await proveReopen(en, "en-US"); await proveManualAdd(en, "en-US"); + await proveAudioPreset(en); await page.getByRole("button", { name: en.close, exact: true }).click(); await proveAgentPicker(en, "en-US"); assert.ok(!requests.some(url => new URL(url).hostname === "open.bigmodel.cn"), "Browser must not contact the model provider"); @@ -239,11 +360,13 @@ try { console.log(JSON.stringify({ passed: true, fixture: true, generation: "not submitted", base, api, projectURL: `${base}/ai-tool/ai-canvas/${projectId}?creation=unified`, screenshotDirectory: output, modelConfigIds: saved.map(config => config.id), checks: ["Chinese and English", "Z.ai brand logo", - "canonical URL", "GLM models preselected without discovery", "save and reopen", "public models have no key", + "canonical URL", "authenticated GET /models with upstream retry", "missing key warning, load and refresh progress, and empty results", + "save discovered model and reopen", "audio preset excludes text model catalog", "public models have no key", "manual model IDs stay available", "assistant picker lists and keeps the Zhipu model", "no provider request from the browser"] })); } catch (error) { await shot("mock-zhipu-provider-failure.png").catch(() => {}); throw error; } finally { await browser.close(); + catalog.close(); } diff --git a/tests/test_model_configs.py b/tests/test_model_configs.py index 6d3242903..3ab9a0beb 100644 --- a/tests/test_model_configs.py +++ b/tests/test_model_configs.py @@ -317,17 +317,36 @@ def test_read_service_models_protocol(): import httpx from opendirector.integrations.model_capabilities import read_service_models - config = payload(authMode='bearer') + config = payload(protocol='openai', authMode='bearer') def respond(request): + assert request.method == 'GET' assert request.url.path == '/v1/models' assert request.headers['Authorization'] == 'Bearer test-secret' return httpx.Response(200, json={'data': [{'id': 'model-a'}]}) assert asyncio.run(read_service_models(config, httpx.MockTransport(respond))) == [{'id': 'model-a'}] + with pytest.raises(ProjectError, match='HTTP 503') as failure: + asyncio.run(read_service_models(config, httpx.MockTransport( + lambda request: httpx.Response(503)))) + assert failure.value.code == 'model_list_http_error' with pytest.raises(ProjectError): asyncio.run(read_service_models(config, httpx.MockTransport( lambda request: httpx.Response(200, json={'data': [{'id': 123}]})))) + with pytest.raises(ProjectError): + asyncio.run(read_service_models(config, httpx.MockTransport( + lambda request: httpx.Response(200, json={'error': {'message': 'Upstream rejected the request'}})))) + + +def test_minimax_video_model_list_does_not_contact_provider(): + import asyncio + import httpx + from opendirector.integrations.model_capabilities import read_service_models + + config = payload('video', protocol='minimax_video_v2', authMode='bearer') + transport = httpx.MockTransport(lambda _: pytest.fail('No catalog request expected')) + models = asyncio.run(read_service_models(config, transport)) + assert [item['id'] for item in models] == ['MiniMax-H3', 'MiniMax-H3-Highspeed', 'MiniMax-H3-Lite', 'MiniMax-H3-Max'] def test_shared_service_batch_persists_one_credential_and_stable_models(api): From eb2ff30e9a18ec1b4528039ad8f79991499c4054 Mon Sep 17 00:00:00 2001 From: Weiming Liao Date: Mon, 23 Nov 2026 14:39:44 +0800 Subject: [PATCH 2/2] [test] providers: split new model discovery gate Signed-off-by: Weiming Liao --- docs/development/validation.md | 3 +- scripts/run-browser-suite.mjs | 3 +- tests/browser/manifest.json | 15 +++- tests/browser/new_model_discovery.mjs | 113 ++++++++++++++++++++++++ tests/browser/zhipu_catalog_fixture.mjs | 49 ++++++++++ tests/browser/zhipu_provider.mjs | 95 +++++++------------- 6 files changed, 210 insertions(+), 68 deletions(-) create mode 100644 tests/browser/new_model_discovery.mjs create mode 100644 tests/browser/zhipu_catalog_fixture.mjs diff --git a/docs/development/validation.md b/docs/development/validation.md index c204af04a..13fce12fc 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -607,12 +607,13 @@ Zhipu BigModel chat access uses the following checks. Browser commands connect t ```sh .venv/bin/python -m pytest tests/test_zhipu.py tests/test_model_configs.py -q node --test tests/providerPresets.test.ts +CREATION_API_URL=http://127.0.0.1:8019 CREATION_WEB_URL=http://127.0.0.1:5179 node tests/browser/new_model_discovery.mjs CREATION_API_URL=http://127.0.0.1:8019 CREATION_WEB_URL=http://127.0.0.1:5179 node tests/browser/zhipu_provider.mjs ``` The Python cases check how the shared thinking levels map to GLM reasoning_effort. GLM accepts only low, high and max for reasoning_effort. The auto level omits the parameter so the provider default applies, and an unknown level falls back to high as in the DeepSeek branch. Other hosts and the DeepSeek behavior stay unchanged. -The PR browser gate checks both display languages. Choosing the Zhipu text preset preselects suggested models. Fetching text models sends an authenticated `GET /models` through the discovery API and makes a new model ID selectable. An upstream HTTP failure is visible and manual entry remains available. Loading the Zhipu audio preset lists only `glm-tts` and sends no discovery request. The case also checks save and reopen, key privacy, and the assistant model picker. It uses an isolated HTTP fixture with a synthetic API key. Real streaming conversations, tool calls, and thinking levels require a separate run with valid Zhipu credentials. +The **New model discovery** case runs on its own with the isolated API and Vite. It verifies that a model absent from the preset appears after an authenticated `GET /models`, can be selected and saved, and remains selectable in the assistant. The **Zhipu model settings feedback** case checks both display languages for missing credentials, request progress, upstream failure, retry, empty responses, manual entry, and audio preset isolation. Both cases use local HTTP fixtures and synthetic keys. Real streaming conversations, tool calls, and thinking levels require a separate run with valid Zhipu credentials. 智谱 BigModel GLM-TTS 接入使用以下检查: diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index c4044ab74..7f1c43be0 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -32,7 +32,8 @@ const workflows = [ }, { name: "minimax h3", script: "tests/browser/minimax_h3.mjs" }, { name: "provider settings", script: "tests/browser/provider_settings.mjs" }, - { name: "provider model discovery", script: "tests/browser/zhipu_provider.mjs" }, + { name: "new model discovery", script: "tests/browser/new_model_discovery.mjs" }, + { name: "Zhipu model settings feedback", script: "tests/browser/zhipu_provider.mjs" }, { name: "capability discovery", script: "tests/browser/capability_discovery.mjs" }, { name: "created node focus", script: "tests/browser/created_node_focus.mjs" }, { name: "cross canvas paste", script: "tests/browser/cross_canvas_paste.mjs" }, diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index a5bcdac38..654bc6934 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -552,13 +552,26 @@ ], "note": "Runs with voice_library_server.py in the Release checks voice library phase." }, + { + "file": "new_model_discovery.mjs", + "previewSafe": true, + "lanes": [ + "gate" + ], + "note": "Discovers a new text model from a loopback GET /models service, saves it, and selects it in the assistant." + }, + { + "file": "zhipu_catalog_fixture.mjs", + "helper": true, + "note": "Shared loopback catalog fixture for the new-model and Zhipu feedback tests." + }, { "file": "zhipu_provider.mjs", "previewSafe": true, "lanes": [ "gate" ], - "note": "Bilingual model discovery through the API and a loopback GET /models service, including upstream failure and retry." + "note": "Bilingual catalog feedback, retry and empty responses, and Zhipu audio preset isolation." }, { "file": "kimi_real.mjs", diff --git a/tests/browser/new_model_discovery.mjs b/tests/browser/new_model_discovery.mjs new file mode 100644 index 000000000..e087e2546 --- /dev/null +++ b/tests/browser/new_model_discovery.mjs @@ -0,0 +1,113 @@ +/** Run with creation_server.py on 8019 and its Vite proxy on 5179. + * Override the URLs with CREATION_API_URL and CREATION_WEB_URL. + */ +import assert from "node:assert/strict"; +import { launchBrowser } from "./engine.mjs"; +import { startZhipuCatalog, zhipuBaseURL, zhipuFixtureKey, zhipuModelsPath } from "./zhipu_catalog_fixture.mjs"; + +const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; +const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8019"; +const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; +const modelId = `glm-discovery-fixture-${crypto.randomUUID()}`; +const projectId = crypto.randomUUID(); +const projectURL = `${base}/ai-tool/ai-canvas/${projectId}?creation=unified`; + +async function call(path, { method = "GET", body } = {}) { + const response = await fetch(api + path, { method, headers, ...(body ? { body: JSON.stringify(body) } : {}) }); + assert.ok(response.ok, `Fixture API ${method} ${path}: ${response.status}`); + return response.status === 204 ? null : response.json(); +} + +const health = await call("/api/creation-test-health"); +assert.equal(health.isolated, true, "Run only against creation_server.py"); +assert.equal(health.provider, "fixture"); +const webHealth = await fetch(`${base}/api/creation-test-health`, { headers }); +assert.ok(webHealth.ok); +assert.equal((await webHealth.json()).root, health.root, "Web proxy must use the same isolated API"); +await call(`/api/creation/projects/${projectId}/commands`, { + method: "POST", + body: { commandId: crypto.randomUUID(), projectId, type: "project.create", + payload: { name: `New model discovery ${projectId.slice(0, 8)}` } }, +}); + +const browser = await launchBrowser(); +let catalog; +try { + const page = await browser.newPage({ locale: "en-US", viewport: { width: 1500, height: 1000 } }); + page.setDefaultTimeout(15000); + await page.addInitScript(() => { + localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); + localStorage.setItem("opendirector.locale.v1", "en-US"); + }); + catalog = await startZhipuCatalog(page, () => ({ status: 200, ids: [modelId] })); + // Runtime availability is fixed for the test. Model choices come from saved settings. + await page.route(/\/assistant\/runtimes$/, route => route.fulfill({ + json: [{ + id: "default", label: "Default", group: "default", modelSource: "settings", + available: true, status: "ready", modelOverride: false, + }], + })); + + const button = name => page.getByRole("button", { name, exact: true }); + const picker = page.locator(".cw-model-picker"); + const discovered = picker.getByRole("checkbox", { name: modelId, exact: true }); + async function openTextModels() { + await page.locator('.cw-workspace[aria-busy="false"]').waitFor(); + await button("Settings").click(); + await button("Model connections").click(); + await page.locator(".cw-model-setup-row") + .filter({ has: page.getByText("Text model", { exact: true }) }) + .getByRole("button").click(); + } + + await page.goto(projectURL); + await openTextModels(); + await button("Add service").click(); + await page.getByRole("combobox", { name: "Provider", exact: true }).click(); + await page.getByRole("option", { name: "Zhipu BigModel", exact: true }).click(); + assert.equal(await discovered.count(), 0, "The new model must be absent before discovery"); + assert.deepEqual(catalog.requests, [], "Selecting a preset must not query the provider"); + await page.getByLabel("API Key", { exact: true }).fill(zhipuFixtureKey); + for (const option of await picker.locator(".cw-model-option > label > input[type=checkbox]").all()) { + await option.uncheck(); + } + + await button("Fetch models").click(); + await discovered.waitFor(); + assert.deepEqual(catalog.requests, [{ method: "GET", path: zhipuModelsPath, authorized: true }]); + assert.equal(await discovered.isChecked(), false, "The discovered model needs an explicit selection"); + await discovered.check(); + await button("Save service").click(); + await button("Add service").waitFor(); + + const configs = await call("/api/model-configs"); + const saved = configs.find(config => config.modelId === modelId); + assert.ok(saved?.providerId, "Save must persist the selected model in a model service"); + assert.equal(saved.kind, "agent"); + assert.equal(saved.url, zhipuBaseURL); + assert.deepEqual(configs.filter(config => config.providerId === saved.providerId).map(config => config.modelId), [modelId]); + + await page.reload(); + await openTextModels(); + await page.locator(".cw-model-service").filter({ hasText: modelId }) + .getByRole("button", { name: "Manage", exact: true }).click(); + assert.equal(await discovered.isChecked(), true, "The saved model stays selected after reload"); + await button("Cancel").click(); + await button("Close settings").click(); + + const chat = button("Chat with AI"); + if (await chat.getAttribute("aria-expanded") !== "true") await chat.click(); + const agent = page.getByRole("button", { name: /^Agent:/ }); + const assistantModel = page.getByRole("menuitemradio", { name: modelId, exact: true }); + await agent.click(); + await assistantModel.click(); + await agent.click(); + assert.equal(await assistantModel.getAttribute("aria-checked"), "true", "The assistant uses the new saved model"); + console.log(JSON.stringify({ passed: true, modelId, checks: ["GET /models", "explicit selection", "saved model after reload", "assistant selection"] })); +} finally { + await browser.close(); + catalog?.close(); + const configs = await call("/api/model-configs"); + const saved = configs.find(config => config.kind === "agent" && config.url === zhipuBaseURL && config.modelId === modelId); + if (saved) await call(`/api/model-services/${saved.id}`, { method: "DELETE" }); +} diff --git a/tests/browser/zhipu_catalog_fixture.mjs b/tests/browser/zhipu_catalog_fixture.mjs new file mode 100644 index 000000000..a1d2c04b6 --- /dev/null +++ b/tests/browser/zhipu_catalog_fixture.mjs @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import { once } from "node:events"; +import { createServer } from "node:http"; + +export const zhipuBaseURL = "https://open.bigmodel.cn/api/paas/v4"; +export const zhipuFixtureKey = "zhipu-browser-fixture-only-no-real-service"; +export const zhipuModelsPath = `${new URL(zhipuBaseURL).pathname}/models`; + +export async function startZhipuCatalog(page, readCatalog) { + const requests = []; + const server = createServer(async (request, response) => { + const received = { + method: request.method, + path: request.url, + authorized: request.headers.authorization === `Bearer ${zhipuFixtureKey}`, + }; + requests.push(received); + if (received.method !== "GET" || received.path !== zhipuModelsPath || !received.authorized) { + response.writeHead(400).end(); + return; + } + const { status, ids, ready } = readCatalog(); + await ready; + response.writeHead(status, { "Content-Type": "application/json" }); + response.end(JSON.stringify(status === 200 ? { data: ids.map(id => ({ id })) } : {})); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const fixtureURL = `http://127.0.0.1:${server.address().port}${new URL(zhipuBaseURL).pathname}`; + try { + await page.route(`${new URL(zhipuBaseURL).origin}/**`, route => route.abort()); + await page.route("**/api/model-configs/discover", async route => { + const request = route.request(); + const body = request.postDataJSON(); + assert.equal(request.method(), "POST"); + assert.equal(body.url, zhipuBaseURL, "Use the selected preset's Base URL"); + assert.equal(body.kind, "agent"); + assert.equal(body.protocol, "openai"); + assert.ok(body.apiKey === zhipuFixtureKey, "Send the fixture API Key to the local backend"); + // Rewrite just the destination for the backend's real GET /models request. + const response = await route.fetch({ postData: { ...body, url: fixtureURL } }); + await route.fulfill({ response }); + }); + } catch (error) { + server.close(); + throw error; + } + return { requests, close: () => server.close() }; +} diff --git a/tests/browser/zhipu_provider.mjs b/tests/browser/zhipu_provider.mjs index eb3c62130..7020ab64c 100644 --- a/tests/browser/zhipu_provider.mjs +++ b/tests/browser/zhipu_provider.mjs @@ -4,18 +4,19 @@ */ import assert from "node:assert/strict"; import { mkdir } from "node:fs/promises"; -import { createServer } from "node:http"; import { join } from "node:path"; import { launchBrowser } from "./engine.mjs"; +import { + startZhipuCatalog, + zhipuBaseURL as canonicalURL, + zhipuFixtureKey as fixtureKey, + zhipuModelsPath, +} from "./zhipu_catalog_fixture.mjs"; const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5189"; const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8029"; const output = process.env.ZHIPU_SCREENSHOT_DIR ?? "/tmp/opendirector-zhipu-evidence"; -const suggestedIds = ["glm-5.3", "glm-5.3-flash", "glm-5.2"]; -const newModel = "glm-5.4"; -const modelIds = [...suggestedIds, newModel]; -const canonicalURL = "https://open.bigmodel.cn/api/paas/v4"; -const fixtureKey = "zhipu-browser-fixture-only-no-real-service"; +const modelIds = ["glm-5.3", "glm-5.3-flash", "glm-5.2"]; const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; async function call(path, { method = "GET", body } = {}) { const response = await fetch(api + path, { @@ -61,7 +62,7 @@ const copy = { settings: "设置", models: "模型接入", agentOverview: "文本模型", chat: "对话", audio: "音频", add: "添加服务", provider: "提供商", zhipu: "智谱 BigModel", url: "服务地址(Base URL)", fetch: "获取模型", refresh: "刷新列表", retry: "可重试或手动添加模型。", - missingKey: "请先填写 API Key。", pending: "正在获取模型列表", fetched: "已获取 4 个模型", empty: "服务未返回模型", + missingKey: "请先填写 API Key。", pending: "正在获取模型列表", fetched: "已获取 3 个模型", empty: "服务未返回模型", loadAudioPreset: "载入支持的模型", audioPresetLoaded: "已载入 1 个预设模型", providerError: "读取模型声明失败(HTTP 503)", save: "保存服务", cancel: "取消", manage: "管理", close: "关闭设置", @@ -71,7 +72,7 @@ const copy = { settings: "Settings", models: "Model connections", agentOverview: "Text model", chat: "Chat", audio: "Audio", add: "Add service", provider: "Provider", zhipu: "Zhipu BigModel", url: "Service URL (Base URL)", fetch: "Fetch models", refresh: "Refresh list", retry: "You can retry or add a model manually.", - missingKey: "Enter an API Key first.", pending: "Fetching the model list", fetched: "4 models fetched", empty: "The service returned no models", + missingKey: "Enter an API Key first.", pending: "Fetching the model list", fetched: "3 models fetched", empty: "The service returned no models", loadAudioPreset: "Load supported models", audioPresetLoaded: "1 preset model loaded", providerError: "Could not load the model list (HTTP 503).", save: "Save service", cancel: "Cancel", manage: "Manage", close: "Close settings", @@ -88,28 +89,10 @@ await page.addInitScript(() => { }); const requests = []; const errors = []; -const modelRequests = []; +let catalog; let catalogStatus = 200; let catalogModelIds = modelIds; let catalogResponseReady = Promise.resolve(); -const catalogPath = new URL(canonicalURL).pathname; -const catalog = createServer(async (request, response) => { - const expectedRequest = { - method: request.method, - path: request.url, - authorized: request.headers.authorization === `Bearer ${fixtureKey}`, - }; - modelRequests.push(expectedRequest); - if (request.method !== "GET" || request.url !== `${catalogPath}/models` || !expectedRequest.authorized) { - response.writeHead(400).end(); - return; - } - const status = catalogStatus; - const ids = catalogModelIds; - await catalogResponseReady; - response.writeHead(status, { "Content-Type": "application/json" }); - response.end(JSON.stringify(status === 200 ? { data: ids.map(id => ({ id })) } : {})); -}); page.on("request", request => requests.push(request.url())); page.on("pageerror", error => errors.push(error.message)); const shot = name => page.screenshot({ path: join(output, name), fullPage: true }); @@ -147,29 +130,28 @@ async function discoverWithFeedback(button, labels, resultText = labels.fetched) } async function provePreset(labels, locale) { await page.getByRole("button", { name: labels.add, exact: true }).click(); - const start = modelRequests.length; + const start = catalog.requests.length; await provider(labels).click(); const option = page.getByRole("option", { name: labels.zhipu, exact: true }); await brandLogo(option.locator("img.cw-model-logo")); await option.click(); assert.equal(await provider(labels).innerText(), labels.zhipu); assert.equal(await page.getByLabel(labels.url, { exact: true }).inputValue(), canonicalURL); - assert.equal(await page.locator(".cw-model-option").count(), suggestedIds.length); + assert.equal(await page.locator(".cw-model-option").count(), modelIds.length); await brandLogo(provider(labels).locator("img.cw-model-logo")); - for (const modelId of suggestedIds) { + for (const modelId of modelIds) { assert.equal(await page.getByRole("checkbox", { name: modelId, exact: true }).isChecked(), true); await brandLogo(optionRow(modelId).locator("img.cw-model-logo")); } - assert.equal(modelRequests.length, start, "Selecting a preset must not query the provider"); + assert.equal(catalog.requests.length, start, "Selecting a preset must not query the provider"); const fetchModels = page.getByRole("button", { name: labels.fetch, exact: true }); const refresh = page.getByRole("button", { name: labels.refresh, exact: true }); - const discovered = page.getByRole("checkbox", { name: newModel, exact: true }); const startBrowserRequests = requests.length; assert.equal(await fetchModels.isEnabled(), true, "Users must be able to ask why discovery cannot start"); await fetchModels.click(); const missingKey = page.getByRole("alert").filter({ hasText: labels.missingKey }); await missingKey.waitFor(); - assert.equal(modelRequests.length, start, "Missing credentials must not reach the provider"); + assert.equal(catalog.requests.length, start, "Missing credentials must not reach the provider"); assert.ok(!requests.slice(startBrowserRequests).some(url => url.includes("/model-configs/discover")), "Missing credentials must not start discovery"); @@ -181,24 +163,22 @@ async function provePreset(labels, locale) { assert.ok((await failure.innerText()).includes(labels.providerError)); assert.equal(await fetchModels.isEnabled(), true, "A failed query remains available for retry"); assert.equal(await refresh.count(), 0, "An error must not mark model discovery successful"); - assert.equal(await discovered.count(), 0, "An error must not introduce a discovered model"); + assert.equal(await page.locator(".cw-model-option").count(), modelIds.length, "An error must keep the preset list"); assert.equal(await page.getByRole("button", { name: labels.manual, exact: true }).isEnabled(), true); catalogStatus = 200; await discoverWithFeedback(fetchModels, labels); await refresh.waitFor(); await failure.waitFor({ state: "hidden" }); - assert.equal(await discovered.isChecked(), false, "Remote IDs require an explicit selection"); - await discovered.check(); await discoverWithFeedback(refresh, labels); - assert.equal(await discovered.isChecked(), true, "Refreshing must preserve the selected model"); + for (const modelId of modelIds) + assert.equal(await page.getByRole("checkbox", { name: modelId, exact: true }).isChecked(), true, "Refreshing must preserve the selected models"); catalogModelIds = []; await discoverWithFeedback(refresh, labels, labels.empty); catalogModelIds = modelIds; - assert.equal(await discovered.isChecked(), true, "An empty result must preserve the selected model"); - for (const modelId of suggestedIds) + for (const modelId of modelIds) assert.equal(await page.getByRole("checkbox", { name: modelId, exact: true }).isChecked(), true); - assert.deepEqual(modelRequests.slice(start), Array.from({ length: 4 }, () => ({ - method: "GET", path: `${catalogPath}/models`, authorized: true, + assert.deepEqual(catalog.requests.slice(start), Array.from({ length: 4 }, () => ({ + method: "GET", path: zhipuModelsPath, authorized: true, })), "Initial load, retry and refresh must query the service catalog with authentication"); await shot(`${locale}-mock-zhipu-provider.png`); } @@ -226,7 +206,7 @@ async function proveManualAdd(labels, locale) { await page.getByRole("button", { name: labels.manual, exact: true }).click(); await page.getByLabel(labels.manualId, { exact: true }).fill("glm-4.7"); await page.locator(".cw-model-manual").getByRole("button", { name: labels.manualAdd, exact: true }).click(); - assert.equal(await page.locator(".cw-model-option").count(), suggestedIds.length + 1); + assert.equal(await page.locator(".cw-model-option").count(), modelIds.length + 1); assert.equal(await page.getByRole("checkbox", { name: "glm-4.7", exact: true }).isChecked(), true); assert.ok(!requests.slice(start).some(url => url.includes("/model-configs/discover")), "Manual add must not discover remote models"); await shot(`${locale}-mock-zhipu-manual-add.png`); @@ -235,7 +215,7 @@ async function proveManualAdd(labels, locale) { } async function proveAudioPreset(labels) { const startBrowserRequests = requests.length; - const startModelRequests = modelRequests.length; + const startModelRequests = catalog.requests.length; await page.getByRole("button", { name: labels.audio, exact: true }).click(); await page.getByRole("button", { name: labels.add, exact: true }).click(); await provider(labels).click(); @@ -247,7 +227,7 @@ async function proveAudioPreset(labels) { assert.equal(await page.getByRole("checkbox", { name: "glm-tts", exact: true }).isChecked(), true); assert.ok(!requests.slice(startBrowserRequests).some(url => url.endsWith("/api/model-configs/discover")), "The audio preset must not use the text model catalog"); - assert.equal(modelRequests.length, startModelRequests); + assert.equal(catalog.requests.length, startModelRequests); await page.getByRole("button", { name: labels.cancel, exact: true }).click(); } async function proveAgentPicker(labels, locale) { @@ -275,7 +255,7 @@ async function proveAgentPicker(labels, locale) { })); await pickerPage.goto(base + "/ai-tool/ai-canvas/" + pickerProjectId + "?creation=unified"); await pickerPage.locator('.cw-workspace[aria-busy="false"]').waitFor(); - const pickerRow = pickerPage.getByRole("menuitemradio", { name: newModel, exact: true }); + const pickerRow = pickerPage.getByRole("menuitemradio", { name: modelIds[0], exact: true }); const chatButton = pickerPage.getByRole("button", { name: labels.chatEntry, exact: true }); if (await chatButton.getAttribute("aria-expanded") !== "true") await chatButton.click(); @@ -301,24 +281,9 @@ async function proveAgentPicker(labels, locale) { } try { - await new Promise((resolve, reject) => { - catalog.once("error", reject); - catalog.listen(0, "127.0.0.1", resolve); - }); - const fixtureURL = `http://127.0.0.1:${catalog.address().port}${catalogPath}`; - await page.route(`${new URL(canonicalURL).origin}/**`, route => route.abort()); - await page.route("**/api/model-configs/discover", async route => { - const request = route.request(); - const body = request.postDataJSON(); - assert.equal(request.method(), "POST"); - assert.equal(body.url, canonicalURL, "Use the selected preset's Base URL"); - assert.equal(body.kind, "agent"); - assert.equal(body.protocol, "openai"); - assert.equal(body.apiKey === fixtureKey, true, "Send the entered API Key to the local backend"); - // Preserve the browser's request except for the destination of the backend's GET /models. - const response = await route.fetch({ postData: { ...body, url: fixtureURL } }); - await route.fulfill({ response }); - }); + catalog = await startZhipuCatalog(page, () => ({ + status: catalogStatus, ids: catalogModelIds, ready: catalogResponseReady, + })); await page.goto(`${base}/ai-tool/ai-canvas/${projectId}?creation=unified`); const zh = copy["zh-CN"]; await page.getByRole("button", { name: zh.settings, exact: true }).click(); @@ -361,12 +326,12 @@ try { projectURL: `${base}/ai-tool/ai-canvas/${projectId}?creation=unified`, screenshotDirectory: output, modelConfigIds: saved.map(config => config.id), checks: ["Chinese and English", "Z.ai brand logo", "canonical URL", "authenticated GET /models with upstream retry", "missing key warning, load and refresh progress, and empty results", - "save discovered model and reopen", "audio preset excludes text model catalog", "public models have no key", + "save preset models and reopen", "audio preset excludes text model catalog", "public models have no key", "manual model IDs stay available", "assistant picker lists and keeps the Zhipu model", "no provider request from the browser"] })); } catch (error) { await shot("mock-zhipu-provider-failure.png").catch(() => {}); throw error; } finally { await browser.close(); - catalog.close(); + catalog?.close(); }