diff --git a/CHANGELOG.md b/CHANGELOG.md index c9239ec..28f5a6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ ## [Unreleased] +### 修复 + +- Anthropic 渠道的模型列表检查返回 HTTP 404 / 405 时标为“跳过”,保留状态码和说明,不计入整体成功判定和通过率分母。Messages 及流式仍独立验证;鉴权、限流、服务端错误、超时和 OpenAI 渠道的列表错误仍记录为失败。无需数据库迁移。 + ## [0.4.1] - 2026-11-04 ### 修复 diff --git a/backend/app/routers/channels.py b/backend/app/routers/channels.py index 654cd89..b82fc9e 100644 --- a/backend/app/routers/channels.py +++ b/backend/app/routers/channels.py @@ -155,10 +155,13 @@ async def test_channel(channel_id: int, body: ChannelTestRequest | None = None, checks = await run_channel_checks(ch, model) except ConcurrencyExceeded: raise HTTPException(429, "Two model checks are already running", headers={"Retry-After": "10"}) - failed = next((check for check in checks if check.status != "passed"), None) + evaluated = [check for check in checks if check.status != "skipped"] + failed = next((check for check in evaluated if check.status != "passed"), None) + success = bool(evaluated) and failed is None return ChannelTestResponse( - success=failed is None, model=model, actual_model=actual, checks=checks, - status_code=failed.status_code if failed else 200, error=failed.error if failed else "", + success=success, model=model, actual_model=actual, checks=checks, + status_code=failed.status_code if failed else 200 if success else None, + error=failed.error if failed else "" if success else "No checks completed", ) diff --git a/backend/app/schemas/channel.py b/backend/app/schemas/channel.py index 8a72fc6..485536f 100644 --- a/backend/app/schemas/channel.py +++ b/backend/app/schemas/channel.py @@ -103,11 +103,12 @@ class ChannelTestRequest(StrictModel): class ChannelCheckResult(BaseModel): kind: Literal["models", "chat", "chat_stream", "responses", "responses_stream", "messages", "messages_stream"] - status: Literal["passed", "failed", "timeout"] + status: Literal["passed", "failed", "timeout", "skipped"] status_code: int | None = None latency_ms: int = 0 first_text_ms: int | None = None error: str = "" + skip_reason: Literal["models_endpoint_unavailable"] | None = None class ChannelTestResponse(BaseModel): diff --git a/backend/app/services/channel_checks.py b/backend/app/services/channel_checks.py index f1235f3..5b74d63 100644 --- a/backend/app/services/channel_checks.py +++ b/backend/app/services/channel_checks.py @@ -195,6 +195,7 @@ async def _check(provider, model: str, kind: str) -> ChannelCheckResult: first_text_ms = None status = "passed" error = "" + skip_reason = None try: async with asyncio.timeout(min(provider.channel.timeout, CHECK_TIMEOUT_SECONDS)): stream = kind.endswith("_stream") @@ -209,8 +210,14 @@ async def _check(provider, model: str, kind: str) -> ChannelCheckResult: raise CheckFailed("Expected JSON, received a non-JSON response") from None _validate_json(data, kind) except Exception as exc: - status = "timeout" if isinstance(exc, (TimeoutError, httpx.TimeoutException)) else "failed" - error = _failure(exc) + if (isinstance(exc, httpx.HTTPStatusError) + and kind == "models" and provider.channel.provider == "anthropic" + and response is not None and response.status_code in {404, 405}): + status = "skipped" + skip_reason = "models_endpoint_unavailable" + else: + status = "timeout" if isinstance(exc, (TimeoutError, httpx.TimeoutException)) else "failed" + error = _failure(exc) finally: if response is not None: with anyio.move_on_after(1, shield=True): @@ -218,6 +225,7 @@ async def _check(provider, model: str, kind: str) -> ChannelCheckResult: return ChannelCheckResult( kind=kind, status=status, status_code=response.status_code if response is not None else None, latency_ms=round((time.monotonic() - started) * 1000), first_text_ms=first_text_ms, error=error, + skip_reason=skip_reason, ) diff --git a/backend/scripts/channel_checks_ui_check.py b/backend/scripts/channel_checks_ui_check.py index 820c762..6f40ed6 100644 --- a/backend/scripts/channel_checks_ui_check.py +++ b/backend/scripts/channel_checks_ui_check.py @@ -35,13 +35,21 @@ async def api(route): if hold: await release.wait() checks = [] - for kind in ("models", "chat", "chat_stream", "responses", "responses_stream"): + kinds = ("models", "messages", "messages_stream") if channel["provider"] == "anthropic" else ( + "models", "chat", "chat_stream", "responses", "responses_stream") + for kind in kinds: + if channel["provider"] == "anthropic" and kind == "models": + checks.append({"kind": kind, "status": "skipped", "status_code": 404, + "latency_ms": 125, "first_text_ms": None, "error": "", + "skip_reason": "models_endpoint_unavailable"}) + continue passed = not kind.startswith("responses") checks.append({"kind": kind, "status": "passed" if passed else "failed", "status_code": 200 if passed else 404, "latency_ms": 125, "first_text_ms": 48 if kind == "chat_stream" else None, "error": "" if passed else "Responses endpoint is not available"}) - body = {"success": False, "model": model, "actual_model": model, "checks": checks} + body = {"success": all(check["status"] in {"passed", "skipped"} for check in checks), + "model": model, "actual_model": model, "checks": checks} else: raise AssertionError(f"Unexpected API request: {path}") await route.fulfill(status=200, content_type="application/json", body=json.dumps(body)) @@ -94,8 +102,26 @@ async def select_both(): await expect(dialog.get_by_text("已完成 5 项检测,3 项通过。", exact=False)).to_be_visible() assert requested == ["model-a"], "Stopping must not start a second model" await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="未检测")).to_have_count(5) + await dialog.get_by_role("button", name="关闭", exact=True).click() + channel["provider"] = "anthropic" + channel["name"] = "Anthropic-compatible demo" + hold = False + await page.reload() + dialog = page.get_by_role("dialog", name="接口检测 · Anthropic-compatible demo", exact=True) + await page.get_by_role("button", name="测试", exact=True).click() + await dialog.get_by_role("button", name="开始检测", exact=True).click() + await expect(dialog.get_by_text("已检测 2 项,2 项通过;另有 1 项可选检查已跳过。", exact=True)).to_be_visible() + await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="跳过")).to_have_count(1) + await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="通过")).to_have_count(2) + await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="失败")).to_have_count(0) + await expect(dialog.locator(".check-table").get_by_text("模型列表返回 HTTP 404", exact=False)).to_be_visible() + await page.wait_for_load_state("networkidle") + await page.screenshot(path=str(output / "anthropic-optional-models-desktop.png"), full_page=True, animations="disabled") + await page.set_viewport_size({"width": 390, "height": 844}) + await expect(dialog.locator(".check-cards").get_by_text("模型列表返回 HTTP 404", exact=False)).to_be_visible() + await page.screenshot(path=str(output / "anthropic-optional-models-mobile.png"), full_page=True) assert not errors, errors - print("PASS: model selection, independent endpoint results, reopening, batch stop, mobile layout, no browser errors") + print("PASS: model selection, endpoint results, batch stop, optional discovery summary, desktop/mobile, no browser errors") except Exception: if "page" in locals(): await page.screenshot(path=str(output / "channel-checks-failure.png"), full_page=True) diff --git a/backend/tests/test_channel_checks.py b/backend/tests/test_channel_checks.py index a308416..e1f7223 100644 --- a/backend/tests/test_channel_checks.py +++ b/backend/tests/test_channel_checks.py @@ -85,23 +85,85 @@ async def test_all_endpoints_pass_and_default_model_remains_supported(client, ad @respx.mock -async def test_anthropic_checks_native_messages_even_when_discovery_is_unavailable(client, admin_token): +@pytest.mark.parametrize("list_status", [404, 405]) +async def test_anthropic_checks_native_messages_even_when_discovery_is_unavailable(client, admin_token, list_status): channel = await Channel.create(name="native", provider="anthropic", base_url="https://native.test/v1", api_key="anthropic-secret", models=["alias"], model_mapping={"alias": "claude-real"}) - respx.get("https://native.test/v1/models").respond(404) + respx.get("https://native.test/v1/models").respond(list_status) messages = respx.post("https://native.test/v1/messages").mock(side_effect=lambda request: stream(MESSAGES_STREAM) if json.loads(request.content)["stream"] else httpx.Response(200, json=MESSAGES)) result = await client.post(f"/api/channels/{channel.id}/test", json={"model": "alias"}, headers=auth_header(admin_token)) checks = {item["kind"]: item for item in result.json()["checks"]} assert set(checks) == set(channel_checks.ANTHROPIC_CHECKS) - assert checks["models"]["status"] == "failed" + assert result.json()["success"] is True + assert result.json()["status_code"] == 200 and result.json()["error"] == "" + assert checks["models"]["status"] == "skipped" + assert checks["models"]["status_code"] == list_status + assert checks["models"]["skip_reason"] == "models_endpoint_unavailable" + assert checks["models"]["error"] == "" assert checks["messages"]["status"] == checks["messages_stream"]["status"] == "passed" for call in messages.calls: assert call.request.headers["x-api-key"] == "anthropic-secret" assert json.loads(call.request.content)["model"] == "claude-real" +@respx.mock +@pytest.mark.parametrize("list_status", [401, 403, 429, 500, 502]) +async def test_anthropic_discovery_operational_errors_still_fail_the_result(client, admin_token, list_status): + channel = await Channel.create(name="native-errors", provider="anthropic", base_url="https://native.test/anthropic", + api_key="secret", models=["model"]) + respx.get("https://native.test/anthropic/v1/models").respond(list_status) + respx.post("https://native.test/anthropic/v1/messages").mock(side_effect=lambda request: + stream(MESSAGES_STREAM) if json.loads(request.content)["stream"] else httpx.Response(200, json=MESSAGES)) + response = await client.post(f"/api/channels/{channel.id}/test", headers=auth_header(admin_token)) + data = response.json() + assert data["success"] is False + assert data["checks"][0]["status"] == "failed" and data["checks"][0]["skip_reason"] is None + assert data["checks"][0]["status_code"] == list_status + assert all(check["status"] == "passed" for check in data["checks"][1:]) + + +@respx.mock +@pytest.mark.parametrize("provider", ["openai", "anthropic"]) +async def test_skipped_discovery_does_not_hide_generation_failures_or_skip_openai(client, admin_token, provider): + channel = await Channel.create(name="generation-failure", provider=provider, base_url="https://checks.test", + api_key="secret", models=["model"]) + respx.get("https://checks.test/v1/models").respond(404) + respx.route(method="POST").respond(500, json={"error": {"message": "Generation is unavailable"}}) + response = await client.post(f"/api/channels/{channel.id}/test", headers=auth_header(admin_token)) + data = response.json() + assert data["success"] is False + assert data["checks"][0]["status"] == ("skipped" if provider == "anthropic" else "failed") + assert all(check["status"] == "failed" for check in data["checks"][1:]) + + +async def test_only_skipped_checks_cannot_report_success(client, admin_token, channel): + with patch("app.routers.channels.run_channel_checks", AsyncMock(return_value=[ + channel_checks.ChannelCheckResult(kind="models", status="skipped", status_code=404, + skip_reason="models_endpoint_unavailable"), + ])): + response = await client.post(f"/api/channels/{channel.id}/test", headers=auth_header(admin_token)) + assert response.json()["success"] is False + + +@pytest.mark.parametrize("case", ["timeout", "invalid_json", "error_in_200"]) +async def test_anthropic_discovery_does_not_skip_transport_or_payload_errors(case): + def upstream(_): + if case == "timeout": + raise httpx.ReadTimeout("timed out") + if case == "invalid_json": + return httpx.Response(200, text="Not a model list") + return httpx.Response(200, json={"error": {"type": "not_found_error", "message": "Unknown resource"}}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(upstream), base_url="https://checks.test") as http: + provider = SimpleNamespace(channel=SimpleNamespace(provider="anthropic", timeout=1, base_url="https://checks.test"), + client=http, _anthropic_headers=lambda: {}) + result = await channel_checks._check(provider, "model", "models") + assert result.status == ("timeout" if case == "timeout" else "failed") + assert result.skip_reason is None and result.error + + @pytest.mark.parametrize(("kind", "response", "error"), [ ("models", httpx.Response(200, text="Login required"), "non-JSON"), ("models", httpx.Response(200, json={"data": "not a list"}), "model list"), diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 8360ab5..932709f 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -55,7 +55,9 @@ | `GET /api/keys/{id}/usage` | 最近 50 条请求元数据,不含正文和凭据 | | `POST /api/channels/{id}/test` | 仅平台;传 `{"model":"渠道内模型名"}`,分别检测模型列表、原生生成和流式接口;不传请求体时检测第一个配置模型 | -渠道检测返回 `model`、`actual_model` 和 `checks`:每项含 `kind`、`status`(passed / failed / timeout)、`status_code`、`latency_ms`、`first_text_ms`、脱敏 `error`。OpenAI 渠道检测 models、chat、chat_stream、responses、responses_stream;Anthropic 渠道检测 models、messages、messages_stream。顶层 `success` 仅在所有项目通过时为 true,某一接口失败不代表其他接口不可用。 +渠道检测返回 `model`、`actual_model` 和 `checks`:每项含 `kind`、`status`(passed / failed / timeout / skipped)、`status_code`、`latency_ms`、`first_text_ms`、脱敏 `error`、可选 `skip_reason`。OpenAI 渠道检测 models、chat、chat_stream、responses、responses_stream;Anthropic 渠道检测 models、messages、messages_stream。顶层 `success` 在至少有一项非跳过检查且所有非跳过项目通过时为 true,某一接口失败不代表其他接口不可用。 + +Anthropic 兼容渠道可能只提供 Messages 接口,模型列表返回 HTTP 404 / 405 时将该项标为 `skipped`、`skip_reason=models_endpoint_unavailable`,保留原始 HTTP 状态,并从整体判定和通过率分母中排除。401 / 403、429、5xx、超时及格式错误仍为失败;OpenAI 渠道不使用此跳过规则。 检测使用渠道内一个可用上游 Key,发起少量真实文本请求,会产生上游费用;不做跨渠道重试,不计入客户账单,也不修改熔断状态。每项最多 15 秒,共享巡检的全局两个并发、管理员每分钟 6 次限制;同一渠道模型的连接检测不能重复运行(409)。暂不检测图片、音频、视频和向量模型。 diff --git a/frontend/src/api/channels.ts b/frontend/src/api/channels.ts index aac1596..53930f0 100644 --- a/frontend/src/api/channels.ts +++ b/frontend/src/api/channels.ts @@ -4,11 +4,12 @@ export type ChannelCheckKind = 'models' | 'chat' | 'chat_stream' | 'responses' | export interface ChannelCheckResult { kind: ChannelCheckKind - status: 'passed' | 'failed' | 'timeout' + status: 'passed' | 'failed' | 'timeout' | 'skipped' status_code: number | null latency_ms: number first_text_ms: number | null error: string + skip_reason?: 'models_endpoint_unavailable' | null } export interface ChannelTestResult { diff --git a/frontend/src/components/ChannelTestDialog.vue b/frontend/src/components/ChannelTestDialog.vue index 15cbae3..60097da 100644 --- a/frontend/src/components/ChannelTestDialog.vue +++ b/frontend/src/components/ChannelTestDialog.vue @@ -18,7 +18,7 @@ {{ t('channels.checkProgress', { model: runningModel, current: currentIndex, total: batchSize }) }}

- {{ t('channels.checkSummary', { passed: passedCount, total: checkedCount }) }} + {{ t(skippedCount ? 'channels.checkSummarySkipped' : 'channels.checkSummary', { passed: passedCount, total: checkedCount, skipped: skippedCount }) }}

@@ -44,6 +44,7 @@