Feat/provider icon color (#385)

* feat(ui): add color prop support to ProviderIcon component

* feat(health): add stream check core functionality

Add new stream-based health check module to replace model_test:
- Add stream_check command layer with single and batch provider checks
- Add stream_check DAO layer for config and log persistence
- Add stream_check service layer with retry mechanism and health status evaluation
- Add frontend HealthStatusIndicator component
- Add frontend useStreamCheck hook

This provides more comprehensive health checking capabilities.

* refactor(health): replace model_test with stream_check

Replace model_test module with stream_check across the codebase:
- Remove model_test command and service modules
- Update command registry in lib.rs to use stream_check commands
- Update module exports in commands/mod.rs and services/mod.rs
- Remove frontend useModelTest hook
- Update stream_check command implementation

This refactoring provides clearer naming and better separation of concerns.

* refactor(db): clean up unused database tables and optimize schema

Remove deprecated and unused database tables:
- Remove proxy_usage table (replaced by proxy_request_logs)
- Remove usage_daily_stats table (aggregation done on-the-fly)
- Rename model_test_logs to stream_check_logs with updated schema
- Remove related DAO methods for proxy_usage
- Update usage_stats service to use proxy_request_logs only
- Refactor usage_script to work with new schema

This simplifies the database schema and removes redundant data storage.

* refactor(ui): update frontend components for stream check

Update frontend components to use stream check API:
- Refactor ModelTestConfigPanel to use stream check config
- Update API layer to use stream_check commands
- Add HealthStatus type and StreamCheckResult interface
- Update ProviderList to use new health check integration
- Update AutoFailoverConfigPanel with stream check references
- Improve UI layout and configuration options

This completes the frontend migration from model_test to stream_check.

* feat(health): add configurable test models and reasoning effort support

Enhance stream check service with configurable test models:
- Add claude_model, codex_model, gemini_model to StreamCheckConfig
- Support reasoning effort syntax (model@level or model#level)
- Parse and apply reasoning_effort for OpenAI-compatible models
- Remove hardcoded model names from check functions
- Add unit tests for model parsing logic
- Remove obsolete model_test source files

This allows users to customize which models are used for health checks.
This commit is contained in:
YoVinchen
2025-12-11 17:20:44 +08:00
committed by GitHub
parent 038b74b844
commit 395783e22a
21 changed files with 883 additions and 1102 deletions
@@ -0,0 +1,45 @@
import React from "react";
import { cn } from "@/lib/utils";
import type { HealthStatus } from "@/lib/api/model-test";
interface HealthStatusIndicatorProps {
status: HealthStatus;
responseTimeMs?: number;
className?: string;
}
const statusConfig = {
operational: {
color: "bg-emerald-500",
label: "正常",
textColor: "text-emerald-600 dark:text-emerald-400",
},
degraded: {
color: "bg-yellow-500",
label: "降级",
textColor: "text-yellow-600 dark:text-yellow-400",
},
failed: {
color: "bg-red-500",
label: "失败",
textColor: "text-red-600 dark:text-red-400",
},
};
export const HealthStatusIndicator: React.FC<HealthStatusIndicatorProps> = ({
status,
responseTimeMs,
className,
}) => {
const config = statusConfig[status];
return (
<div className={cn("flex items-center gap-2", className)}>
<div className={cn("w-2 h-2 rounded-full", config.color)} />
<span className={cn("text-xs font-medium", config.textColor)}>
{config.label}
{responseTimeMs !== undefined && ` (${responseTimeMs}ms)`}
</span>
</div>
);
};
+5 -5
View File
@@ -9,7 +9,7 @@ import type { CSSProperties } from "react";
import type { Provider } from "@/types";
import type { AppId } from "@/lib/api";
import { useDragSort } from "@/hooks/useDragSort";
import { useModelTest } from "@/hooks/useModelTest";
import { useStreamCheck } from "@/hooks/useStreamCheck";
import { ProviderCard } from "@/components/providers/ProviderCard";
import { ProviderEmptyState } from "@/components/providers/ProviderEmptyState";
@@ -49,11 +49,11 @@ export function ProviderList({
appId,
);
// 模型测试
const { testProvider, isTesting } = useModelTest(appId);
// 流式健康检查
const { checkProvider, isChecking } = useStreamCheck(appId);
const handleTest = (provider: Provider) => {
testProvider(provider.id, provider.name);
checkProvider(provider.id, provider.name);
};
if (isLoading) {
@@ -100,7 +100,7 @@ export function ProviderList({
onConfigureUsage={onConfigureUsage}
onOpenWebsite={onOpenWebsite}
onTest={handleTest}
isTesting={isTesting(provider.id)}
isTesting={isChecking(provider.id)}
isProxyRunning={isProxyRunning}
isProxyTakeover={isProxyTakeover}
/>
@@ -80,11 +80,11 @@ export function AutoFailoverConfigPanel({
return (
<div className="border-0 rounded-none shadow-none bg-transparent">
{/* Header Switch moved to parent accordion logic or kept here absolutely positioned if styling permits.
Since we need it in the accordion header, and this component is inside the content, we can use a portal or
absolute positioning trick similar to ProxyPanel, OR cleaner, just duplicate the switch logic in SettingsPage
and pass it down. But for now, let's use the absolute positioning trick to "lift" it visually.
Better yet, let's just render the content directly without the wrapping Card header/collapse logic
{/* Header Switch moved to parent accordion logic or kept here absolutely positioned if styling permits.
Since we need it in the accordion header, and this component is inside the content, we can use a portal or
absolute positioning trick similar to ProxyPanel, OR cleaner, just duplicate the switch logic in SettingsPage
and pass it down. But for now, let's use the absolute positioning trick to "lift" it visually.
Better yet, let's just render the content directly without the wrapping Card header/collapse logic
since the user requested "click to expand is detailed info, no need to fold again" (implying the accordion handles folding).
*/}
+121 -89
View File
@@ -7,9 +7,9 @@ import { Alert, AlertDescription } from "@/components/ui/alert";
import { Save, Loader2 } from "lucide-react";
import { toast } from "sonner";
import {
getModelTestConfig,
saveModelTestConfig,
type ModelTestConfig,
getStreamCheckConfig,
saveStreamCheckConfig,
type StreamCheckConfig,
} from "@/lib/api/model-test";
export function ModelTestConfigPanel() {
@@ -17,12 +17,13 @@ export function ModelTestConfigPanel() {
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [config, setConfig] = useState<ModelTestConfig>({
const [config, setConfig] = useState<StreamCheckConfig>({
timeoutSecs: 45,
maxRetries: 2,
degradedThresholdMs: 6000,
claudeModel: "claude-haiku-4-5-20251001",
codexModel: "gpt-5.1-low",
geminiModel: "gemini-3-pro-low",
testPrompt: "ping",
timeoutSecs: 15,
codexModel: "gpt-5.1-codex@low",
geminiModel: "gemini-3-pro-preview",
});
useEffect(() => {
@@ -33,7 +34,7 @@ export function ModelTestConfigPanel() {
try {
setIsLoading(true);
setError(null);
const data = await getModelTestConfig();
const data = await getStreamCheckConfig();
setConfig(data);
} catch (e) {
setError(String(e));
@@ -45,11 +46,11 @@ export function ModelTestConfigPanel() {
async function handleSave() {
try {
setIsSaving(true);
await saveModelTestConfig(config);
toast.success(t("modelTest.configSaved", "模型测试配置已保存"));
await saveStreamCheckConfig(config);
toast.success(t("streamCheck.configSaved", "健康检查配置已保存"));
} catch (e) {
toast.error(
t("modelTest.configSaveFailed", "保存失败") + ": " + String(e),
t("streamCheck.configSaveFailed", "保存失败") + ": " + String(e),
);
} finally {
setIsSaving(false);
@@ -65,95 +66,126 @@ export function ModelTestConfigPanel() {
}
return (
<div className="space-y-4">
<div className="space-y-6">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="claudeModel">
{t("modelTest.claudeModel", "Claude 测试模型")}
</Label>
<Input
id="claudeModel"
value={config.claudeModel}
onChange={(e) =>
setConfig({ ...config, claudeModel: e.target.value })
}
placeholder="claude-haiku-4-5-20251001"
/>
</div>
{/* 测试模型配置 */}
<div className="space-y-4">
<h4 className="text-sm font-medium text-muted-foreground">
{t("streamCheck.testModels", "测试模型")}
</h4>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="claudeModel">
{t("streamCheck.claudeModel", "Claude 模型")}
</Label>
<Input
id="claudeModel"
value={config.claudeModel}
onChange={(e) =>
setConfig({ ...config, claudeModel: e.target.value })
}
placeholder="claude-3-5-haiku-latest"
/>
</div>
<div className="space-y-2">
<Label htmlFor="codexModel">
{t("modelTest.codexModel", "Codex 测试模型")}
</Label>
<Input
id="codexModel"
value={config.codexModel}
onChange={(e) =>
setConfig({ ...config, codexModel: e.target.value })
}
placeholder="gpt-5.1-low"
/>
</div>
<div className="space-y-2">
<Label htmlFor="codexModel">
{t("streamCheck.codexModel", "Codex 模型")}
</Label>
<Input
id="codexModel"
value={config.codexModel}
onChange={(e) =>
setConfig({ ...config, codexModel: e.target.value })
}
placeholder="gpt-4o-mini"
/>
</div>
<div className="space-y-2">
<Label htmlFor="geminiModel">
{t("modelTest.geminiModel", "Gemini 测试模型")}
</Label>
<Input
id="geminiModel"
value={config.geminiModel}
onChange={(e) =>
setConfig({ ...config, geminiModel: e.target.value })
}
placeholder="gemini-3-pro-low"
/>
<div className="space-y-2">
<Label htmlFor="geminiModel">
{t("streamCheck.geminiModel", "Gemini 模型")}
</Label>
<Input
id="geminiModel"
value={config.geminiModel}
onChange={(e) =>
setConfig({ ...config, geminiModel: e.target.value })
}
placeholder="gemini-1.5-flash"
/>
</div>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="testPrompt">
{t("modelTest.testPrompt", "测试提示词")}
</Label>
<Input
id="testPrompt"
value={config.testPrompt}
onChange={(e) =>
setConfig({ ...config, testPrompt: e.target.value })
}
placeholder="ping"
/>
<p className="text-xs text-muted-foreground">
{t(
"modelTest.testPromptHint",
"发送给模型的测试消息,建议使用简短内容以减少 token 消耗",
)}
</p>
</div>
{/* 检查参数配置 */}
<div className="space-y-4">
<h4 className="text-sm font-medium text-muted-foreground">
{t("streamCheck.checkParams", "检查参数")}
</h4>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="timeoutSecs">
{t("streamCheck.timeout", "超时时间(秒)")}
</Label>
<Input
id="timeoutSecs"
type="number"
min={10}
max={120}
value={config.timeoutSecs}
onChange={(e) =>
setConfig({
...config,
timeoutSecs: parseInt(e.target.value) || 45,
})
}
/>
</div>
<div className="space-y-2">
<Label htmlFor="timeoutSecs">
{t("modelTest.timeout", "超时时间(秒)")}
</Label>
<Input
id="timeoutSecs"
type="number"
min={5}
max={60}
value={config.timeoutSecs}
onChange={(e) =>
setConfig({
...config,
timeoutSecs: parseInt(e.target.value) || 15,
})
}
/>
<div className="space-y-2">
<Label htmlFor="maxRetries">
{t("streamCheck.maxRetries", "最大重试次数")}
</Label>
<Input
id="maxRetries"
type="number"
min={0}
max={5}
value={config.maxRetries}
onChange={(e) =>
setConfig({
...config,
maxRetries: parseInt(e.target.value) || 2,
})
}
/>
</div>
<div className="space-y-2">
<Label htmlFor="degradedThresholdMs">
{t("streamCheck.degradedThreshold", "降级阈值(毫秒)")}
</Label>
<Input
id="degradedThresholdMs"
type="number"
min={1000}
max={30000}
step={1000}
value={config.degradedThresholdMs}
onChange={(e) =>
setConfig({
...config,
degradedThresholdMs: parseInt(e.target.value) || 6000,
})
}
/>
</div>
</div>
</div>
-66
View File
@@ -1,66 +0,0 @@
import { useState, useCallback } from "react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { testProviderModel, type ModelTestResult } from "@/lib/api/model-test";
import type { AppId } from "@/lib/api";
export function useModelTest(appId: AppId) {
const { t } = useTranslation();
const [testingIds, setTestingIds] = useState<Set<string>>(new Set());
const testProvider = useCallback(
async (
providerId: string,
providerName: string,
): Promise<ModelTestResult | null> => {
setTestingIds((prev) => new Set(prev).add(providerId));
try {
const result = await testProviderModel(appId, providerId);
if (result.success) {
toast.success(
t("modelTest.success", {
name: providerName,
time: result.responseTimeMs,
defaultValue: `${providerName} 测试成功 (${result.responseTimeMs}ms)`,
}),
);
} else {
toast.error(
t("modelTest.failed", {
name: providerName,
error: result.message,
defaultValue: `${providerName} 测试失败: ${result.message}`,
}),
);
}
return result;
} catch (e) {
toast.error(
t("modelTest.error", {
name: providerName,
error: String(e),
defaultValue: `${providerName} 测试出错: ${String(e)}`,
}),
);
return null;
} finally {
setTestingIds((prev) => {
const next = new Set(prev);
next.delete(providerId);
return next;
});
}
},
[appId, t],
);
const isTesting = useCallback(
(providerId: string) => testingIds.has(providerId),
[testingIds],
);
return { testProvider, isTesting };
}
+77
View File
@@ -0,0 +1,77 @@
import { useState, useCallback } from "react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import {
streamCheckProvider,
type StreamCheckResult,
} from "@/lib/api/model-test";
import type { AppId } from "@/lib/api";
export function useStreamCheck(appId: AppId) {
const { t } = useTranslation();
const [checkingIds, setCheckingIds] = useState<Set<string>>(new Set());
const checkProvider = useCallback(
async (
providerId: string,
providerName: string,
): Promise<StreamCheckResult | null> => {
setCheckingIds((prev) => new Set(prev).add(providerId));
try {
const result = await streamCheckProvider(appId, providerId);
if (result.status === "operational") {
toast.success(
t("streamCheck.operational", {
name: providerName,
time: result.responseTimeMs,
defaultValue: `${providerName} 运行正常 (${result.responseTimeMs}ms)`,
}),
);
} else if (result.status === "degraded") {
toast.warning(
t("streamCheck.degraded", {
name: providerName,
time: result.responseTimeMs,
defaultValue: `${providerName} 响应较慢 (${result.responseTimeMs}ms)`,
}),
);
} else {
toast.error(
t("streamCheck.failed", {
name: providerName,
error: result.message,
defaultValue: `${providerName} 检查失败: ${result.message}`,
}),
);
}
return result;
} catch (e) {
toast.error(
t("streamCheck.error", {
name: providerName,
error: String(e),
defaultValue: `${providerName} 检查出错: ${String(e)}`,
}),
);
return null;
} finally {
setCheckingIds((prev) => {
const next = new Set(prev);
next.delete(providerId);
return next;
});
}
},
[appId, t],
);
const isChecking = useCallback(
(providerId: string) => checkingIds.has(providerId),
[checkingIds],
);
return { checkProvider, isChecking };
}
+27 -52
View File
@@ -1,89 +1,64 @@
import { invoke } from "@tauri-apps/api/core";
import type { AppId } from "./types";
export interface ModelTestConfig {
// ===== 流式健康检查类型 =====
export type HealthStatus = "operational" | "degraded" | "failed";
export interface StreamCheckConfig {
timeoutSecs: number;
maxRetries: number;
degradedThresholdMs: number;
claudeModel: string;
codexModel: string;
geminiModel: string;
testPrompt: string;
timeoutSecs: number;
}
export interface ModelTestResult {
export interface StreamCheckResult {
status: HealthStatus;
success: boolean;
message: string;
responseTimeMs?: number;
httpStatus?: number;
modelUsed: string;
testedAt: number;
retryCount: number;
}
export interface ModelTestLog {
id: number;
providerId: string;
providerName: string;
appType: string;
model: string;
prompt: string;
success: boolean;
message: string;
responseTimeMs?: number;
httpStatus?: number;
testedAt: number;
}
// ===== 流式健康检查 API =====
/**
* 测试单个供应商的模型可用性
* 流式健康检查(单个供应商)
*/
export async function testProviderModel(
export async function streamCheckProvider(
appType: AppId,
providerId: string,
): Promise<ModelTestResult> {
return invoke("test_provider_model", { appType, providerId });
): Promise<StreamCheckResult> {
return invoke("stream_check_provider", { appType, providerId });
}
/**
* 批量测试所有供应商
* 批量流式健康检查
*/
export async function testAllProvidersModel(
export async function streamCheckAllProviders(
appType: AppId,
proxyTargetsOnly: boolean = false,
): Promise<Array<[string, ModelTestResult]>> {
return invoke("test_all_providers_model", { appType, proxyTargetsOnly });
): Promise<Array<[string, StreamCheckResult]>> {
return invoke("stream_check_all_providers", { appType, proxyTargetsOnly });
}
/**
* 获取模型测试配置
* 获取流式检查配置
*/
export async function getModelTestConfig(): Promise<ModelTestConfig> {
return invoke("get_model_test_config");
export async function getStreamCheckConfig(): Promise<StreamCheckConfig> {
return invoke("get_stream_check_config");
}
/**
* 保存模型测试配置
* 保存流式检查配置
*/
export async function saveModelTestConfig(
config: ModelTestConfig,
export async function saveStreamCheckConfig(
config: StreamCheckConfig,
): Promise<void> {
return invoke("save_model_test_config", { config });
}
/**
* 获取模型测试日志
*/
export async function getModelTestLogs(
appType?: string,
providerId?: string,
limit?: number,
): Promise<ModelTestLog[]> {
return invoke("get_model_test_logs", { appType, providerId, limit });
}
/**
* 清理旧的测试日志
*/
export async function cleanupModelTestLogs(
keepCount?: number,
): Promise<number> {
return invoke("cleanup_model_test_logs", { keepCount });
return invoke("save_stream_check_config", { config });
}