Feat/provider individual config (#663)

* refactor(ui): simplify UpdateBadge to minimal dot indicator

* feat(provider): add individual test and proxy config for providers

Add support for provider-specific model test and proxy configurations:

- Add ProviderTestConfig and ProviderProxyConfig types in Rust and TypeScript
- Create ProviderAdvancedConfig component with collapsible panels
- Update stream_check service to merge provider config with global config
- Proxy config UI follows global proxy style (single URL input)

Provider-level configs stored in meta field, no database schema changes needed.

* feat(ui): add failover toggle and improve proxy controls

- Add FailoverToggle component with slide animation
- Simplify ProxyToggle style to match FailoverToggle
- Add usage statistics button when proxy is active
- Fix i18n parameter passing for failover messages
- Add missing failover translation keys (inQueue, addQueue, priority)
- Replace AboutSection icon with app logo

* fix(proxy): support system proxy fallback and provider-level proxy config

- Remove no_proxy() calls in http_client.rs to allow system proxy fallback
- Add get_for_provider() to build HTTP client with provider-specific proxy
- Update forwarder.rs and stream_check.rs to use provider proxy config
- Fix EditProviderDialog.tsx to include provider.meta in useMemo deps
- Add useEffect in ProviderAdvancedConfig.tsx to sync expand state

Fixes #636
Fixes #583

* fix(ui): sync toast theme with app setting

* feat(settings): add log config management

Fixes #612
Fixes #514

* fix(proxy): increase request body size limit to 200MB

Fixes #666

* docs(proxy): update timeout config descriptions and defaults

Fixes #612

* fix(proxy): filter x-goog-api-key header to prevent duplication

* fix(proxy): prevent proxy recursion when system proxy points to localhost

Detect if HTTP_PROXY, HTTPS_PROXY, or ALL_PROXY environment variables
point to loopback addresses (localhost, 127.0.0.1), and bypass system
proxy in such cases to avoid infinite request loops.

* fix(i18n): add providerAdvanced i18n keys and fix failover toast parameter

- Add providerAdvanced.* i18n keys to en.json, zh.json, and ja.json
- Fix failover toggleFailed toast to pass detail parameter
- Remove Chinese fallback text from UI for English/Japanese users

* fix(tray): restore tray-provider events and enable Auto failover properly

- Emit provider-switched event on tray provider click (backward compatibility)
- Auto button now: starts proxy, takes over live config, enables failover

* fix(log): enable dynamic log level and single file mode

- Initialize log at Trace level for dynamic adjustment
- Change rotation strategy to KeepSome(1) for single file
- Set max file size to 1GB
- Delete old log file on startup for clean start

* fix(tray): fix clippy uninlined format args warning

Use inline format arguments: {app_type_str} instead of {}

* fix(provider): allow typing :// in endpoint URL inputs

Change input type from "url" to "text" to prevent browser
URL validation from blocking :// input.

Closes #681

* fix(stream-check): use Gemini native streaming API format

- Change endpoint from OpenAI-compatible to native streamGenerateContent
- Add alt=sse parameter for SSE format response
- Use x-goog-api-key header instead of Bearer token
- Convert request body to Gemini contents/parts format

* feat(proxy): add request logging for debugging

Add debug logs for outgoing requests including URL and body content
with byte size, matching the existing response logging format.

* fix(log): prevent usize underflow in KeepSome rotation strategy

KeepSome(n) internally computes n-2, so n=1 causes underflow.
Use KeepSome(2) as the minimum safe value.
This commit is contained in:
Dex Miller
2026-01-20 21:02:44 +08:00
committed by GitHub
parent 7bb458eecb
commit e7badb1a24
46 changed files with 2008 additions and 331 deletions
+25 -42
View File
@@ -1,6 +1,6 @@
import { X, Download } from "lucide-react";
import { useUpdate } from "@/contexts/UpdateContext";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
interface UpdateBadgeProps {
className?: string;
@@ -8,56 +8,39 @@ interface UpdateBadgeProps {
}
export function UpdateBadge({ className = "", onClick }: UpdateBadgeProps) {
const { hasUpdate, updateInfo, isDismissed, dismissUpdate } = useUpdate();
const { hasUpdate, updateInfo } = useUpdate();
const { t } = useTranslation();
const isActive = hasUpdate && updateInfo;
const title = isActive
? t("settings.updateAvailable", {
version: updateInfo?.availableVersion ?? "",
})
: t("settings.checkForUpdates");
// 如果没有更新或已关闭,不显示
if (!hasUpdate || isDismissed || !updateInfo) {
if (!isActive) {
return null;
}
return (
<div
<Button
type="button"
variant="ghost"
size="icon"
title={title}
aria-label={title}
onClick={onClick}
className={`
flex items-center gap-1.5 px-2.5 py-1
bg-white dark:bg-gray-800
border border-border-default
rounded-lg text-xs
shadow-sm
transition-all duration-200
${onClick ? "cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-750" : ""}
relative h-6 w-6 rounded-full
${isActive ? "text-blue-600 dark:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-500/10" : "text-muted-foreground hover:bg-muted/60"}
${className}
`}
role={onClick ? "button" : undefined}
tabIndex={onClick ? 0 : -1}
onClick={onClick}
onKeyDown={(e) => {
if (!onClick) return;
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onClick();
}
}}
>
<Download className="w-3 h-3 text-blue-500 dark:text-blue-400" />
<span className="text-gray-700 dark:text-gray-300 font-medium">
{t("settings.updateBadge")}
</span>
<button
onClick={(e) => {
e.stopPropagation();
dismissUpdate();
}}
className="
ml-1 -mr-0.5 p-0.5 rounded
hover:bg-gray-100 dark:hover:bg-gray-700
transition-colors
focus:outline-none focus:ring-2 focus:ring-blue-500/20
"
aria-label={t("common.close")}
>
<X className="w-3 h-3 text-muted-foreground" />
</button>
</div>
<span
className={`
absolute inset-0 m-auto h-2 w-2 rounded-full ring-1 ring-background
${isActive ? "bg-blue-500 dark:bg-blue-400" : "bg-blue-300/70 dark:bg-blue-300/60"}
`}
/>
</Button>
);
}
+1 -3
View File
@@ -128,9 +128,7 @@ export const FullScreenPanel: React.FC<FullScreenPanelProps> = ({
{/* Content */}
<div className="flex-1 overflow-y-auto scroll-overlay">
<div className="px-6 py-6 space-y-6 w-full">
{children}
</div>
<div className="px-6 py-6 space-y-6 w-full">{children}</div>
</div>
{/* Footer */}
@@ -24,7 +24,9 @@ interface AddProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
appId: AppId;
onSubmit: (provider: Omit<Provider, "id"> & { providerKey?: string }) => Promise<void> | void;
onSubmit: (
provider: Omit<Provider, "id"> & { providerKey?: string },
) => Promise<void> | void;
}
export function AddProviderDialog({
@@ -186,7 +188,9 @@ export function AddProviderDialog({
}
} else if (appId === "opencode") {
// OpenCode uses options.baseURL
const options = parsedConfig.options as Record<string, any> | undefined;
const options = parsedConfig.options as
| Record<string, any>
| undefined;
if (options?.baseURL) {
addUrl(options.baseURL);
}
@@ -130,8 +130,8 @@ export function EditProviderDialog({
}, [
open, // 修复:编辑保存后再次打开显示旧数据,依赖 open 确保每次打开时重新读取最新 provider 数据
provider?.id, // 只依赖 ID,provider 对象更新不会触发重新计算
provider?.meta, // 需要依赖 meta 以便正确初始化 testConfig 和 proxyConfig
initialSettingsConfig,
// 注意:不依赖 provider 的其他字段,防止表单重置
]);
const handleSubmit = useCallback(
+2 -1
View File
@@ -64,7 +64,8 @@ export function ProviderActions({
const isOpenCodeMode = appId === "opencode";
// 故障转移模式下的按钮逻辑(OpenCode 不支持故障转移)
const isFailoverMode = !isOpenCodeMode && isAutoFailoverEnabled && onToggleFailover;
const isFailoverMode =
!isOpenCodeMode && isAutoFailoverEnabled && onToggleFailover;
// 处理主按钮点击
const handleMainButtonClick = () => {
@@ -29,7 +29,10 @@ interface BasicFormFieldsProps {
beforeNameSlot?: ReactNode;
}
export function BasicFormFields({ form, beforeNameSlot }: BasicFormFieldsProps) {
export function BasicFormFields({
form,
beforeNameSlot,
}: BasicFormFieldsProps) {
const { t } = useTranslation();
const [iconDialogOpen, setIconDialogOpen] = useState(false);
@@ -525,7 +525,7 @@ const EndpointSpeedTest: React.FC<EndpointSpeedTestProps> = ({
<div className="space-y-1.5">
<div className="flex gap-2">
<Input
type="url"
type="text"
value={customUrl}
placeholder={t("endpointTest.addEndpointPlaceholder")}
onChange={(event) => setCustomUrl(event.target.value)}
@@ -265,7 +265,7 @@ export function OpenCodeFormFields({
const handleModelOptionKeyChange = (
modelKey: string,
oldKey: string,
newKey: string
newKey: string,
) => {
if (!newKey.trim() || oldKey === newKey) return;
const model = models[modelKey];
@@ -283,7 +283,7 @@ export function OpenCodeFormFields({
const handleModelOptionValueChange = (
modelKey: string,
optionKey: string,
value: string
value: string,
) => {
const model = models[modelKey];
let parsedValue: unknown;
@@ -443,7 +443,9 @@ export function OpenCodeFormFields({
/>
<Input
value={value}
onChange={(e) => handleExtraOptionValueChange(key, e.target.value)}
onChange={(e) =>
handleExtraOptionValueChange(key, e.target.value)
}
placeholder={t("opencode.extraOptionValuePlaceholder", {
defaultValue: "600000",
})}
@@ -521,7 +523,7 @@ export function OpenCodeFormFields({
<ChevronRight
className={cn(
"h-4 w-4 transition-transform",
expandedModels.has(key) && "rotate-90"
expandedModels.has(key) && "rotate-90",
)}
/>
</Button>
@@ -575,17 +577,24 @@ export function OpenCodeFormFields({
<>
{Object.entries(model.options || {}).map(
([optKey, optValue]) => (
<div key={optKey} className="flex items-center gap-2">
<div
key={optKey}
className="flex items-center gap-2"
>
<ModelOptionKeyInput
optionKey={optKey}
onChange={(newKey) =>
handleModelOptionKeyChange(key, optKey, newKey)
handleModelOptionKeyChange(
key,
optKey,
newKey,
)
}
placeholder={t(
"opencode.modelOptionKeyPlaceholder",
{
defaultValue: "provider",
}
},
)}
/>
<Input
@@ -598,14 +607,14 @@ export function OpenCodeFormFields({
handleModelOptionValueChange(
key,
optKey,
e.target.value
e.target.value,
)
}
placeholder={t(
"opencode.modelOptionValuePlaceholder",
{
defaultValue: '{"order": ["baseten"]}',
}
},
)}
className="flex-1"
/>
@@ -621,7 +630,7 @@ export function OpenCodeFormFields({
<Trash2 className="h-4 w-4" />
</Button>
</div>
)
),
)}
<div className="flex items-center justify-end">
<Button
@@ -0,0 +1,455 @@
import { useTranslation } from "react-i18next";
import { useState, useEffect } from "react";
import {
ChevronDown,
ChevronRight,
FlaskConical,
Globe,
Eye,
EyeOff,
X,
} from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { ProviderTestConfig, ProviderProxyConfig } from "@/types";
interface ProviderAdvancedConfigProps {
testConfig: ProviderTestConfig;
proxyConfig: ProviderProxyConfig;
onTestConfigChange: (config: ProviderTestConfig) => void;
onProxyConfigChange: (config: ProviderProxyConfig) => void;
}
/** 从 ProviderProxyConfig 构建完整 URL */
function buildProxyUrl(config: ProviderProxyConfig): string {
if (!config.proxyHost) return "";
const protocol = config.proxyType || "http";
const host = config.proxyHost;
const port = config.proxyPort || (protocol === "socks5" ? 1080 : 7890);
return `${protocol}://${host}:${port}`;
}
/** 从完整 URL 解析为 ProviderProxyConfig */
function parseProxyUrl(url: string): Partial<ProviderProxyConfig> {
if (!url.trim()) {
return { proxyHost: undefined, proxyPort: undefined, proxyType: undefined };
}
try {
const parsed = new URL(url);
const protocol = parsed.protocol.replace(":", "") as
| "http"
| "https"
| "socks5";
const host = parsed.hostname;
const port = parsed.port ? parseInt(parsed.port, 10) : undefined;
return {
proxyType: protocol,
proxyHost: host || undefined,
proxyPort: port,
};
} catch {
// 尝试简单解析(不是标准 URL 格式)
const match = url.match(/^(?:(\w+):\/\/)?([^:]+)(?::(\d+))?$/);
if (match) {
return {
proxyType: (match[1] as "http" | "https" | "socks5") || "http",
proxyHost: match[2] || undefined,
proxyPort: match[3] ? parseInt(match[3], 10) : undefined,
};
}
return {};
}
}
export function ProviderAdvancedConfig({
testConfig,
proxyConfig,
onTestConfigChange,
onProxyConfigChange,
}: ProviderAdvancedConfigProps) {
const { t } = useTranslation();
const [isTestConfigOpen, setIsTestConfigOpen] = useState(testConfig.enabled);
const [isProxyConfigOpen, setIsProxyConfigOpen] = useState(
proxyConfig.enabled,
);
const [showPassword, setShowPassword] = useState(false);
// 代理 URL 输入状态(仅在初始化时从 proxyConfig 构建)
const [proxyUrl, setProxyUrl] = useState(() => buildProxyUrl(proxyConfig));
// 标记是否为用户主动输入(用于区分外部更新和用户输入)
const [isUserTyping, setIsUserTyping] = useState(false);
// 同步外部 testConfig.enabled 变化到展开状态
useEffect(() => {
setIsTestConfigOpen(testConfig.enabled);
}, [testConfig.enabled]);
// 同步外部 proxyConfig.enabled 变化到展开状态
useEffect(() => {
setIsProxyConfigOpen(proxyConfig.enabled);
}, [proxyConfig.enabled]);
// 仅在外部 proxyConfig 变化且非用户输入时同步(如:重置表单、加载数据)
useEffect(() => {
if (!isUserTyping) {
const newUrl = buildProxyUrl(proxyConfig);
if (newUrl !== proxyUrl) {
setProxyUrl(newUrl);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [proxyConfig.proxyType, proxyConfig.proxyHost, proxyConfig.proxyPort]);
// 处理代理 URL 变化(用户输入时不触发 URL 重建)
const handleProxyUrlChange = (value: string) => {
setIsUserTyping(true);
setProxyUrl(value);
const parsed = parseProxyUrl(value);
onProxyConfigChange({
...proxyConfig,
...parsed,
});
};
// 输入框失焦时结束用户输入状态
const handleProxyUrlBlur = () => {
setIsUserTyping(false);
};
// 清除代理配置
const handleClearProxy = () => {
setProxyUrl("");
onProxyConfigChange({
...proxyConfig,
proxyType: undefined,
proxyHost: undefined,
proxyPort: undefined,
proxyUsername: undefined,
proxyPassword: undefined,
});
};
return (
<div className="space-y-4">
{/* 模型测试配置 */}
<div className="rounded-lg border border-border/50 bg-muted/20">
<button
type="button"
className="flex w-full items-center justify-between p-4 hover:bg-muted/30 transition-colors"
onClick={() => setIsTestConfigOpen(!isTestConfigOpen)}
>
<div className="flex items-center gap-3">
<FlaskConical className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">
{t("providerAdvanced.testConfig", {
defaultValue: "模型测试配置",
})}
</span>
</div>
<div className="flex items-center gap-3">
<div
className="flex items-center gap-2"
onClick={(e) => e.stopPropagation()}
>
<Label
htmlFor="test-config-enabled"
className="text-sm text-muted-foreground"
>
{t("providerAdvanced.useCustomConfig", {
defaultValue: "使用单独配置",
})}
</Label>
<Switch
id="test-config-enabled"
checked={testConfig.enabled}
onCheckedChange={(checked) => {
onTestConfigChange({ ...testConfig, enabled: checked });
if (checked) setIsTestConfigOpen(true);
}}
/>
</div>
{isTestConfigOpen ? (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronRight className="h-4 w-4 text-muted-foreground" />
)}
</div>
</button>
<div
className={cn(
"overflow-hidden transition-all duration-200",
isTestConfigOpen
? "max-h-[500px] opacity-100"
: "max-h-0 opacity-0",
)}
>
<div className="border-t border-border/50 p-4 space-y-4">
<p className="text-sm text-muted-foreground">
{t("providerAdvanced.testConfigDesc", {
defaultValue:
"为此供应商配置单独的模型测试参数,不启用时使用全局配置。",
})}
</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="test-model">
{t("providerAdvanced.testModel", {
defaultValue: "测试模型",
})}
</Label>
<Input
id="test-model"
value={testConfig.testModel || ""}
onChange={(e) =>
onTestConfigChange({
...testConfig,
testModel: e.target.value || undefined,
})
}
placeholder={t("providerAdvanced.testModelPlaceholder", {
defaultValue: "留空使用全局配置",
})}
disabled={!testConfig.enabled}
/>
</div>
<div className="space-y-2">
<Label htmlFor="test-timeout">
{t("providerAdvanced.timeoutSecs", {
defaultValue: "超时时间(秒)",
})}
</Label>
<Input
id="test-timeout"
type="number"
min={1}
max={300}
value={testConfig.timeoutSecs || ""}
onChange={(e) =>
onTestConfigChange({
...testConfig,
timeoutSecs: e.target.value
? parseInt(e.target.value, 10)
: undefined,
})
}
placeholder="45"
disabled={!testConfig.enabled}
/>
</div>
<div className="space-y-2">
<Label htmlFor="test-prompt">
{t("providerAdvanced.testPrompt", {
defaultValue: "测试提示词",
})}
</Label>
<Input
id="test-prompt"
value={testConfig.testPrompt || ""}
onChange={(e) =>
onTestConfigChange({
...testConfig,
testPrompt: e.target.value || undefined,
})
}
placeholder="Who are you?"
disabled={!testConfig.enabled}
/>
</div>
<div className="space-y-2">
<Label htmlFor="degraded-threshold">
{t("providerAdvanced.degradedThreshold", {
defaultValue: "降级阈值(毫秒)",
})}
</Label>
<Input
id="degraded-threshold"
type="number"
min={100}
max={60000}
value={testConfig.degradedThresholdMs || ""}
onChange={(e) =>
onTestConfigChange({
...testConfig,
degradedThresholdMs: e.target.value
? parseInt(e.target.value, 10)
: undefined,
})
}
placeholder="6000"
disabled={!testConfig.enabled}
/>
</div>
<div className="space-y-2">
<Label htmlFor="max-retries">
{t("providerAdvanced.maxRetries", {
defaultValue: "最大重试次数",
})}
</Label>
<Input
id="max-retries"
type="number"
min={0}
max={10}
value={testConfig.maxRetries ?? ""}
onChange={(e) =>
onTestConfigChange({
...testConfig,
maxRetries: e.target.value
? parseInt(e.target.value, 10)
: undefined,
})
}
placeholder="2"
disabled={!testConfig.enabled}
/>
</div>
</div>
</div>
</div>
</div>
{/* 代理配置 */}
<div className="rounded-lg border border-border/50 bg-muted/20">
<button
type="button"
className="flex w-full items-center justify-between p-4 hover:bg-muted/30 transition-colors"
onClick={() => setIsProxyConfigOpen(!isProxyConfigOpen)}
>
<div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">
{t("providerAdvanced.proxyConfig", {
defaultValue: "代理配置",
})}
</span>
</div>
<div className="flex items-center gap-3">
<div
className="flex items-center gap-2"
onClick={(e) => e.stopPropagation()}
>
<Label
htmlFor="proxy-config-enabled"
className="text-sm text-muted-foreground"
>
{t("providerAdvanced.useCustomProxy", {
defaultValue: "使用单独代理",
})}
</Label>
<Switch
id="proxy-config-enabled"
checked={proxyConfig.enabled}
onCheckedChange={(checked) => {
onProxyConfigChange({ ...proxyConfig, enabled: checked });
if (checked) setIsProxyConfigOpen(true);
}}
/>
</div>
{isProxyConfigOpen ? (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronRight className="h-4 w-4 text-muted-foreground" />
)}
</div>
</button>
<div
className={cn(
"overflow-hidden transition-all duration-200",
isProxyConfigOpen
? "max-h-[500px] opacity-100"
: "max-h-0 opacity-0",
)}
>
<div className="border-t border-border/50 p-4 space-y-3">
<p className="text-sm text-muted-foreground">
{t("providerAdvanced.proxyConfigDesc", {
defaultValue:
"为此供应商配置单独的网络代理,不启用时使用系统代理或全局设置。",
})}
</p>
{/* 代理地址输入框(仿照全局代理样式) */}
<div className="flex gap-2">
<Input
placeholder="http://127.0.0.1:7890 / socks5://127.0.0.1:1080"
value={proxyUrl}
onChange={(e) => handleProxyUrlChange(e.target.value)}
onBlur={handleProxyUrlBlur}
className="font-mono text-sm flex-1"
disabled={!proxyConfig.enabled}
/>
<Button
type="button"
variant="outline"
size="icon"
disabled={!proxyConfig.enabled || !proxyUrl}
onClick={handleClearProxy}
title={t("common.clear", { defaultValue: "清除" })}
>
<X className="h-4 w-4" />
</Button>
</div>
{/* 认证信息:用户名 + 密码(可选) */}
<div className="flex gap-2">
<Input
placeholder={t("providerAdvanced.proxyUsername", {
defaultValue: "用户名(可选)",
})}
value={proxyConfig.proxyUsername || ""}
onChange={(e) =>
onProxyConfigChange({
...proxyConfig,
proxyUsername: e.target.value || undefined,
})
}
className="font-mono text-sm flex-1"
disabled={!proxyConfig.enabled}
/>
<div className="relative flex-1">
<Input
type={showPassword ? "text" : "password"}
placeholder={t("providerAdvanced.proxyPassword", {
defaultValue: "密码(可选)",
})}
value={proxyConfig.proxyPassword || ""}
onChange={(e) =>
onProxyConfigChange({
...proxyConfig,
proxyPassword: e.target.value || undefined,
})
}
className="font-mono text-sm pr-10"
disabled={!proxyConfig.enabled}
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
onClick={() => setShowPassword(!showPassword)}
tabIndex={-1}
disabled={!proxyConfig.enabled}
>
{showPassword ? (
<EyeOff className="h-4 w-4 text-muted-foreground" />
) : (
<Eye className="h-4 w-4 text-muted-foreground" />
)}
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
+111 -34
View File
@@ -8,7 +8,12 @@ import { Form, FormField, FormItem, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { providerSchema, type ProviderFormData } from "@/lib/schemas/provider";
import type { AppId } from "@/lib/api";
import type { ProviderCategory, ProviderMeta } from "@/types";
import type {
ProviderCategory,
ProviderMeta,
ProviderTestConfig,
ProviderProxyConfig,
} from "@/types";
import {
providerPresets,
type ProviderPreset,
@@ -41,6 +46,7 @@ import { BasicFormFields } from "./BasicFormFields";
import { ClaudeFormFields } from "./ClaudeFormFields";
import { CodexFormFields } from "./CodexFormFields";
import { GeminiFormFields } from "./GeminiFormFields";
import { ProviderAdvancedConfig } from "./ProviderAdvancedConfig";
import {
useProviderCategory,
useApiKeyState,
@@ -87,7 +93,11 @@ const OPENCODE_DEFAULT_CONFIG = JSON.stringify(
type PresetEntry = {
id: string;
preset: ProviderPreset | CodexProviderPreset | GeminiProviderPreset | OpenCodeProviderPreset;
preset:
| ProviderPreset
| CodexProviderPreset
| GeminiProviderPreset
| OpenCodeProviderPreset;
};
interface ProviderFormProps {
@@ -151,6 +161,14 @@ export function ProviderForm({
() => initialData?.meta?.endpointAutoSelect ?? true,
);
// 高级配置:模型测试和代理配置
const [testConfig, setTestConfig] = useState<ProviderTestConfig>(
() => initialData?.meta?.testConfig ?? { enabled: false },
);
const [proxyConfig, setProxyConfig] = useState<ProviderProxyConfig>(
() => initialData?.meta?.proxyConfig ?? { enabled: false },
);
// 使用 category hook
const { category } = useProviderCategory({
appId,
@@ -168,6 +186,8 @@ export function ProviderForm({
setDraftCustomEndpoints([]);
}
setEndpointAutoSelect(initialData?.meta?.endpointAutoSelect ?? true);
setTestConfig(initialData?.meta?.testConfig ?? { enabled: false });
setProxyConfig(initialData?.meta?.proxyConfig ?? { enabled: false });
}, [appId, initialData]);
const defaultValues: ProviderFormData = useMemo(
@@ -506,7 +526,7 @@ export function ProviderForm({
if (!opencodeProvidersData?.providers) return [];
// Exclude current provider ID when in edit mode
return Object.keys(opencodeProvidersData.providers).filter(
(k) => k !== providerId
(k) => k !== providerId,
);
}, [opencodeProvidersData?.providers, providerId]);
@@ -521,7 +541,11 @@ export function ProviderForm({
const [opencodeNpm, setOpencodeNpm] = useState<string>(() => {
if (appId !== "opencode") return "@ai-sdk/openai-compatible";
try {
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
initialData?.settingsConfig
? JSON.stringify(initialData.settingsConfig)
: OPENCODE_DEFAULT_CONFIG,
);
return config.npm || "@ai-sdk/openai-compatible";
} catch {
return "@ai-sdk/openai-compatible";
@@ -531,7 +555,11 @@ export function ProviderForm({
const [opencodeApiKey, setOpencodeApiKey] = useState<string>(() => {
if (appId !== "opencode") return "";
try {
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
initialData?.settingsConfig
? JSON.stringify(initialData.settingsConfig)
: OPENCODE_DEFAULT_CONFIG,
);
return config.options?.apiKey || "";
} catch {
return "";
@@ -541,17 +569,27 @@ export function ProviderForm({
const [opencodeBaseUrl, setOpencodeBaseUrl] = useState<string>(() => {
if (appId !== "opencode") return "";
try {
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
initialData?.settingsConfig
? JSON.stringify(initialData.settingsConfig)
: OPENCODE_DEFAULT_CONFIG,
);
return config.options?.baseURL || "";
} catch {
return "";
}
});
const [opencodeModels, setOpencodeModels] = useState<Record<string, OpenCodeModel>>(() => {
const [opencodeModels, setOpencodeModels] = useState<
Record<string, OpenCodeModel>
>(() => {
if (appId !== "opencode") return {};
try {
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
initialData?.settingsConfig
? JSON.stringify(initialData.settingsConfig)
: OPENCODE_DEFAULT_CONFIG,
);
return config.models || {};
} catch {
return {};
@@ -559,10 +597,16 @@ export function ProviderForm({
});
// OpenCode extra options state (e.g., timeout, setCacheKey)
const [opencodeExtraOptions, setOpencodeExtraOptions] = useState<Record<string, string>>(() => {
const [opencodeExtraOptions, setOpencodeExtraOptions] = useState<
Record<string, string>
>(() => {
if (appId !== "opencode") return {};
try {
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
initialData?.settingsConfig
? JSON.stringify(initialData.settingsConfig)
: OPENCODE_DEFAULT_CONFIG,
);
const options = config.options || {};
const extra: Record<string, string> = {};
const knownKeys = ["baseURL", "apiKey", "headers"];
@@ -583,7 +627,9 @@ export function ProviderForm({
(npm: string) => {
setOpencodeNpm(npm);
try {
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
);
config.npm = npm;
form.setValue("settingsConfig", JSON.stringify(config, null, 2));
} catch {
@@ -597,7 +643,9 @@ export function ProviderForm({
(apiKey: string) => {
setOpencodeApiKey(apiKey);
try {
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
);
if (!config.options) config.options = {};
config.options.apiKey = apiKey;
form.setValue("settingsConfig", JSON.stringify(config, null, 2));
@@ -612,7 +660,9 @@ export function ProviderForm({
(baseUrl: string) => {
setOpencodeBaseUrl(baseUrl);
try {
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
);
if (!config.options) config.options = {};
config.options.baseURL = baseUrl.trim().replace(/\/+$/, "");
form.setValue("settingsConfig", JSON.stringify(config, null, 2));
@@ -627,7 +677,9 @@ export function ProviderForm({
(models: Record<string, OpenCodeModel>) => {
setOpencodeModels(models);
try {
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
);
config.models = models;
form.setValue("settingsConfig", JSON.stringify(config, null, 2));
} catch {
@@ -641,7 +693,9 @@ export function ProviderForm({
(options: Record<string, string>) => {
setOpencodeExtraOptions(options);
try {
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
const config = JSON.parse(
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
);
if (!config.options) config.options = {};
// Remove old extra options (keep only known keys)
@@ -883,6 +937,9 @@ export function ProviderForm({
payload.meta = {
...(baseMeta ?? {}),
endpointAutoSelect,
// 添加高级配置
testConfig: testConfig.enabled ? testConfig : undefined,
proxyConfig: proxyConfig.enabled ? proxyConfig : undefined,
};
onSubmit(payload);
@@ -1122,32 +1179,44 @@ export function ProviderForm({
<Input
id="opencode-key"
value={opencodeProviderKey}
onChange={(e) => setOpencodeProviderKey(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""))}
onChange={(e) =>
setOpencodeProviderKey(
e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""),
)
}
placeholder={t("opencode.providerKeyPlaceholder")}
disabled={isEditMode}
className={
(existingOpencodeKeys.includes(opencodeProviderKey) && !isEditMode) ||
(opencodeProviderKey.trim() !== "" && !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey))
(existingOpencodeKeys.includes(opencodeProviderKey) &&
!isEditMode) ||
(opencodeProviderKey.trim() !== "" &&
!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey))
? "border-destructive"
: ""
}
/>
{existingOpencodeKeys.includes(opencodeProviderKey) && !isEditMode && (
<p className="text-xs text-destructive">
{t("opencode.providerKeyDuplicate")}
</p>
)}
{opencodeProviderKey.trim() !== "" && !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey) && (
<p className="text-xs text-destructive">
{t("opencode.providerKeyInvalid")}
</p>
)}
{!(existingOpencodeKeys.includes(opencodeProviderKey) && !isEditMode) &&
(opencodeProviderKey.trim() === "" || /^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey)) && (
<p className="text-xs text-muted-foreground">
{t("opencode.providerKeyHint")}
</p>
)}
{existingOpencodeKeys.includes(opencodeProviderKey) &&
!isEditMode && (
<p className="text-xs text-destructive">
{t("opencode.providerKeyDuplicate")}
</p>
)}
{opencodeProviderKey.trim() !== "" &&
!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey) && (
<p className="text-xs text-destructive">
{t("opencode.providerKeyInvalid")}
</p>
)}
{!(
existingOpencodeKeys.includes(opencodeProviderKey) &&
!isEditMode
) &&
(opencodeProviderKey.trim() === "" ||
/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey)) && (
<p className="text-xs text-muted-foreground">
{t("opencode.providerKeyHint")}
</p>
)}
</div>
) : undefined
}
@@ -1391,6 +1460,14 @@ export function ProviderForm({
</>
)}
{/* 高级配置:模型测试和代理配置 */}
<ProviderAdvancedConfig
testConfig={testConfig}
proxyConfig={proxyConfig}
onTestConfigChange={setTestConfig}
onProxyConfigChange={setProxyConfig}
/>
{showButtons && (
<div className="flex justify-end gap-2">
<Button variant="outline" type="button" onClick={onCancel}>
@@ -49,7 +49,7 @@ export function EndpointField({
</div>
<Input
id={id}
type="url"
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
@@ -25,9 +25,9 @@ export function AutoFailoverConfigPanel({
const [formData, setFormData] = useState({
autoFailoverEnabled: false,
maxRetries: "3",
streamingFirstByteTimeout: "30",
streamingIdleTimeout: "60",
nonStreamingTimeout: "300",
streamingFirstByteTimeout: "60",
streamingIdleTimeout: "120",
nonStreamingTimeout: "600",
circuitFailureThreshold: "5",
circuitSuccessThreshold: "2",
circuitTimeoutSeconds: "60",
@@ -67,9 +67,9 @@ export function AutoFailoverConfigPanel({
// 定义各字段的有效范围
const ranges = {
maxRetries: { min: 0, max: 10 },
streamingFirstByteTimeout: { min: 0, max: 180 },
streamingFirstByteTimeout: { min: 1, max: 120 },
streamingIdleTimeout: { min: 0, max: 600 },
nonStreamingTimeout: { min: 0, max: 1800 },
nonStreamingTimeout: { min: 60, max: 1200 },
circuitFailureThreshold: { min: 1, max: 20 },
circuitSuccessThreshold: { min: 1, max: 10 },
circuitTimeoutSeconds: { min: 0, max: 300 },
@@ -307,8 +307,8 @@ export function AutoFailoverConfigPanel({
<Input
id={`streamingFirstByte-${appType}`}
type="number"
min="0"
max="180"
min="1"
max="120"
value={formData.streamingFirstByteTimeout}
onChange={(e) =>
setFormData({
@@ -321,7 +321,7 @@ export function AutoFailoverConfigPanel({
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.streamingFirstByteHint",
"等待首个数据块的最大时间",
"等待首个数据块的最大时间,范围 1-120 秒,默认 60 秒",
)}
</p>
</div>
@@ -347,7 +347,7 @@ export function AutoFailoverConfigPanel({
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.streamingIdleHint",
"数据块之间的最大间隔",
"数据块之间的最大间隔,范围 60-600 秒,填 0 禁用(防止中途卡住)",
)}
</p>
</div>
@@ -359,8 +359,8 @@ export function AutoFailoverConfigPanel({
<Input
id={`nonStreaming-${appType}`}
type="number"
min="0"
max="1800"
min="60"
max="1200"
value={formData.nonStreamingTimeout}
onChange={(e) =>
setFormData({
@@ -373,7 +373,7 @@ export function AutoFailoverConfigPanel({
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.nonStreamingHint",
"非流式请求的总超时时间",
"非流式请求的总超时时间,范围 60-1200 秒,默认 600 秒(10 分钟)",
)}
</p>
</div>
+76
View File
@@ -0,0 +1,76 @@
/**
* 故障转移切换开关组件
*
* 放置在主界面头部,用于一键启用/关闭自动故障转移
*/
import { Shuffle, Loader2 } from "lucide-react";
import { Switch } from "@/components/ui/switch";
import {
useAutoFailoverEnabled,
useSetAutoFailoverEnabled,
} from "@/lib/query/failover";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";
import type { AppId } from "@/lib/api";
interface FailoverToggleProps {
className?: string;
activeApp: AppId;
}
export function FailoverToggle({ className, activeApp }: FailoverToggleProps) {
const { t } = useTranslation();
const { data: isEnabled = false, isLoading } =
useAutoFailoverEnabled(activeApp);
const setEnabled = useSetAutoFailoverEnabled();
const handleToggle = (checked: boolean) => {
setEnabled.mutate({ appType: activeApp, enabled: checked });
};
const appLabel =
activeApp === "claude"
? "Claude"
: activeApp === "codex"
? "Codex"
: "Gemini";
const tooltipText = isEnabled
? t("failover.tooltip.enabled", {
app: appLabel,
defaultValue: `${appLabel} 故障转移已启用\n自动切换到下一个可用供应商`,
})
: t("failover.tooltip.disabled", {
app: appLabel,
defaultValue: `启用 ${appLabel} 故障转移\n当当前供应商失败时自动切换`,
});
return (
<div
className={cn(
"flex items-center gap-1 px-1.5 h-8 rounded-lg bg-muted/50 transition-all",
className,
)}
title={tooltipText}
>
{setEnabled.isPending || isLoading ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : (
<Shuffle
className={cn(
"h-4 w-4 transition-colors",
isEnabled
? "text-emerald-500 animate-pulse"
: "text-muted-foreground",
)}
/>
)}
<Switch
checked={isEnabled}
onCheckedChange={handleToggle}
disabled={setEnabled.isPending || isLoading}
/>
</div>
);
}
+16 -26
View File
@@ -55,39 +55,29 @@ export function ProxyToggle({ className, activeApp }: ProxyToggleProps) {
return (
<div
className={cn("p-1 rounded-xl transition-all", className)}
className={cn(
"flex items-center gap-1 px-1.5 h-8 rounded-lg bg-muted/50 transition-all",
className,
)}
title={tooltipText}
>
<div className="flex items-center gap-2 px-2 h-8 rounded-md cursor-default">
{isPending ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : (
<Radio
className={cn(
"h-4 w-4 transition-colors",
takeoverEnabled
? "text-emerald-500 animate-pulse"
: "text-muted-foreground",
)}
/>
)}
<span
{isPending ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : (
<Radio
className={cn(
"text-sm font-medium transition-colors select-none",
"h-4 w-4 transition-colors",
takeoverEnabled
? "text-emerald-600 dark:text-emerald-400"
? "text-emerald-500 animate-pulse"
: "text-muted-foreground",
)}
>
Proxy
</span>
<Switch
checked={takeoverEnabled}
onCheckedChange={handleToggle}
disabled={isPending}
className="ml-1"
/>
</div>
)}
<Switch
checked={takeoverEnabled}
onCheckedChange={handleToggle}
disabled={isPending}
/>
</div>
);
}
+2 -2
View File
@@ -9,7 +9,6 @@ import {
Terminal,
CheckCircle2,
AlertCircle,
Sparkles,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { useTranslation } from "react-i18next";
@@ -20,6 +19,7 @@ import { useUpdate } from "@/contexts/UpdateContext";
import { relaunchApp } from "@/lib/updater";
import { Badge } from "@/components/ui/badge";
import { motion } from "framer-motion";
import appIcon from "@/assets/icons/app-icon.png";
interface AboutSectionProps {
isPortable: boolean;
@@ -204,7 +204,7 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="space-y-2">
<div className="flex items-center gap-2">
<Sparkles className="h-5 w-5 text-primary" />
<img src={appIcon} alt="CC Switch" className="h-5 w-5" />
<h4 className="text-lg font-semibold text-foreground">
CC Switch
</h4>
+119
View File
@@ -0,0 +1,119 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { settingsApi, type LogConfig } from "@/lib/api/settings";
const LOG_LEVELS = ["error", "warn", "info", "debug", "trace"] as const;
export function LogConfigPanel() {
const { t } = useTranslation();
const [config, setConfig] = useState<LogConfig>({
enabled: true,
level: "info",
});
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
settingsApi
.getLogConfig()
.then(setConfig)
.catch((e) => console.error("Failed to load log config:", e))
.finally(() => setIsLoading(false));
}, []);
const handleChange = async (updates: Partial<LogConfig>) => {
const newConfig = { ...config, ...updates };
setConfig(newConfig);
try {
await settingsApi.setLogConfig(newConfig);
} catch (e) {
console.error("Failed to save log config:", e);
toast.error(String(e));
setConfig(config);
}
};
if (isLoading) return null;
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>{t("settings.advanced.logConfig.enabled")}</Label>
<p className="text-xs text-muted-foreground">
{t("settings.advanced.logConfig.enabledDescription")}
</p>
</div>
<Switch
checked={config.enabled}
onCheckedChange={(checked) => handleChange({ enabled: checked })}
/>
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>{t("settings.advanced.logConfig.level")}</Label>
<p className="text-xs text-muted-foreground">
{t("settings.advanced.logConfig.levelDescription")}
</p>
</div>
<Select
value={config.level}
disabled={!config.enabled}
onValueChange={(value) =>
handleChange({ level: value as LogConfig["level"] })
}
>
<SelectTrigger className="w-[120px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{LOG_LEVELS.map((level) => (
<SelectItem key={level} value={level}>
{t(`settings.advanced.logConfig.levels.${level}`)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 日志级别说明 */}
<div className="rounded-lg bg-muted/50 p-4 text-xs space-y-1.5">
<p className="font-medium text-muted-foreground mb-2">
{t("settings.advanced.logConfig.levelHint")}
</p>
<div className="grid gap-1 text-muted-foreground">
<p>
<span className="font-mono text-red-500">error</span> -{" "}
{t("settings.advanced.logConfig.levelDesc.error")}
</p>
<p>
<span className="font-mono text-orange-500">warn</span> -{" "}
{t("settings.advanced.logConfig.levelDesc.warn")}
</p>
<p>
<span className="font-mono text-blue-500">info</span> -{" "}
{t("settings.advanced.logConfig.levelDesc.info")}
</p>
<p>
<span className="font-mono text-green-500">debug</span> -{" "}
{t("settings.advanced.logConfig.levelDesc.debug")}
</p>
<p>
<span className="font-mono text-gray-500">trace</span> -{" "}
{t("settings.advanced.logConfig.levelDesc.trace")}
</p>
</div>
</div>
</div>
);
}
+24
View File
@@ -11,6 +11,7 @@ import {
ChevronDown,
Zap,
Globe,
ScrollText,
} from "lucide-react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { toast } from "sonner";
@@ -44,6 +45,7 @@ import { AutoFailoverConfigPanel } from "@/components/proxy/AutoFailoverConfigPa
import { FailoverQueueManager } from "@/components/proxy/FailoverQueueManager";
import { UsageDashboard } from "@/components/usage/UsageDashboard";
import { RectifierConfigPanel } from "@/components/settings/RectifierConfigPanel";
import { LogConfigPanel } from "@/components/settings/LogConfigPanel";
import { useSettings } from "@/hooks/useSettings";
import { useImportExport } from "@/hooks/useImportExport";
import { useTranslation } from "react-i18next";
@@ -574,6 +576,28 @@ export function SettingsPage({
<RectifierConfigPanel />
</AccordionContent>
</AccordionItem>
<AccordionItem
value="logConfig"
className="rounded-xl glass-card overflow-hidden"
>
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
<div className="flex items-center gap-3">
<ScrollText className="h-5 w-5 text-cyan-500" />
<div className="text-left">
<h3 className="text-base font-semibold">
{t("settings.advanced.logConfig.title")}
</h3>
<p className="text-sm text-muted-foreground font-normal">
{t("settings.advanced.logConfig.description")}
</p>
</div>
</div>
</AccordionTrigger>
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
<LogConfigPanel />
</AccordionContent>
</AccordionItem>
</Accordion>
<div className="pt-4">
+8 -1
View File
@@ -1,11 +1,18 @@
import { Toaster as SonnerToaster } from "sonner";
import { useTheme } from "@/components/theme-provider";
export function Toaster() {
const { theme } = useTheme();
// 将应用主题映射到 Sonner 的主题
// 如果是 "system"Sonner 会自己处理
const sonnerTheme = theme === "system" ? "system" : theme;
return (
<SonnerToaster
position="top-center"
richColors
theme="system"
theme={sonnerTheme}
toastOptions={{
duration: 2000,
classNames: {