From ae6d16ccaeaee4f42b67044c42ec9ba4c3e5fe41 Mon Sep 17 00:00:00 2001 From: Jason Date: Thu, 23 Oct 2025 12:09:59 +0800 Subject: [PATCH] refactor: prevent apiKey field creation for official providers Improved useApiKeyState hook to explicitly handle category parameter: - Only create apiKey field for non-official providers in add mode - Explicitly check category !== undefined to avoid unintended behavior - Added comprehensive comments explaining the logic - Updated dependency array to include category parameter This ensures official provider configs remain clean without empty apiKey fields. --- src/components/providers/forms/ProviderForm.tsx | 1 + .../providers/forms/hooks/useApiKeyState.ts | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/components/providers/forms/ProviderForm.tsx b/src/components/providers/forms/ProviderForm.tsx index aff1fd6..e620275 100644 --- a/src/components/providers/forms/ProviderForm.tsx +++ b/src/components/providers/forms/ProviderForm.tsx @@ -121,6 +121,7 @@ export function ProviderForm({ initialConfig: form.watch("settingsConfig"), onConfigChange: (config) => form.setValue("settingsConfig", config), selectedPresetId, + category, }); // 使用 Base URL hook (仅 Claude 模式) diff --git a/src/components/providers/forms/hooks/useApiKeyState.ts b/src/components/providers/forms/hooks/useApiKeyState.ts index f0670f2..13624cb 100644 --- a/src/components/providers/forms/hooks/useApiKeyState.ts +++ b/src/components/providers/forms/hooks/useApiKeyState.ts @@ -1,4 +1,5 @@ import { useState, useCallback } from "react"; +import type { ProviderCategory } from "@/types"; import { getApiKeyFromConfig, setApiKeyInConfig, @@ -9,6 +10,7 @@ interface UseApiKeyStateProps { initialConfig?: string; onConfigChange: (config: string) => void; selectedPresetId: string | null; + category?: ProviderCategory; } /** @@ -19,6 +21,7 @@ export function useApiKeyState({ initialConfig, onConfigChange, selectedPresetId, + category, }: UseApiKeyStateProps) { const [apiKey, setApiKey] = useState(() => { if (initialConfig) { @@ -35,14 +38,21 @@ export function useApiKeyState({ initialConfig || "{}", key.trim(), { + // 最佳实践:仅在"新增模式"且"非官方类别"时补齐缺失字段 + // - 新增模式:selectedPresetId !== null + // - 非官方类别:category !== undefined && category !== "official" + // - 官方类别:不创建字段(UI 也会禁用输入框) + // - 未传入 category:不创建字段(避免意外行为) createIfMissing: - selectedPresetId !== null && selectedPresetId !== "custom", + selectedPresetId !== null && + category !== undefined && + category !== "official", }, ); onConfigChange(configString); }, - [initialConfig, selectedPresetId, onConfigChange], + [initialConfig, selectedPresetId, category, onConfigChange], ); const showApiKey = useCallback(