From c56866f48cc2171081d254c97d391afd399018dd Mon Sep 17 00:00:00 2001 From: Jason Date: Sun, 2 Nov 2025 22:44:40 +0800 Subject: [PATCH] fix(codex): auto-sync API key from auth.json to form field - Add useEffect to automatically extract and sync OPENAI_API_KEY from codexAuth to codexApiKey state - Fix issue where API key wasn't populated in form after applying configuration wizard - Optimize handleCodexApiKeyChange to trim input upfront - Move getCodexAuthApiKey function closer to usage for better code organization - Remove redundant dependency from useEffect dependency array --- .../forms/hooks/useCodexConfigState.ts | 33 ++++++++++++------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/src/components/providers/forms/hooks/useCodexConfigState.ts b/src/components/providers/forms/hooks/useCodexConfigState.ts index 9fa77ee..056ddbb 100644 --- a/src/components/providers/forms/hooks/useCodexConfigState.ts +++ b/src/components/providers/forms/hooks/useCodexConfigState.ts @@ -68,6 +68,24 @@ export function useCodexConfigState({ initialData }: UseCodexConfigStateProps) { } }, [codexConfig, codexBaseUrl]); + // 获取 API Key(从 auth JSON) + const getCodexAuthApiKey = useCallback((authString: string): string => { + try { + const auth = JSON.parse(authString || "{}"); + return typeof auth.OPENAI_API_KEY === "string" ? auth.OPENAI_API_KEY : ""; + } catch { + return ""; + } + }, []); + + // 从 codexAuth 中提取并同步 API Key + useEffect(() => { + const extractedKey = getCodexAuthApiKey(codexAuth); + if (extractedKey !== codexApiKey) { + setCodexApiKey(extractedKey); + } + }, [codexAuth, codexApiKey]); + // 验证 Codex Auth JSON const validateCodexAuth = useCallback((value: string): string => { if (!value.trim()) return ""; @@ -106,10 +124,11 @@ export function useCodexConfigState({ initialData }: UseCodexConfigStateProps) { // 处理 Codex API Key 输入并写回 auth.json const handleCodexApiKeyChange = useCallback( (key: string) => { - setCodexApiKey(key); + const trimmed = key.trim(); + setCodexApiKey(trimmed); try { const auth = JSON.parse(codexAuth || "{}"); - auth.OPENAI_API_KEY = key.trim(); + auth.OPENAI_API_KEY = trimmed; setCodexAuth(JSON.stringify(auth, null, 2)); } catch { // ignore @@ -178,16 +197,6 @@ export function useCodexConfigState({ initialData }: UseCodexConfigStateProps) { [setCodexAuth, setCodexConfig], ); - // 获取 API Key(从 auth JSON) - const getCodexAuthApiKey = useCallback((authString: string): string => { - try { - const auth = JSON.parse(authString || "{}"); - return typeof auth.OPENAI_API_KEY === "string" ? auth.OPENAI_API_KEY : ""; - } catch { - return ""; - } - }, []); - return { codexAuth, codexConfig,