From 74b2414297ad7c2f53c9c67d97ab0918107e5da6 Mon Sep 17 00:00:00 2001 From: libr Date: Sun, 9 Nov 2025 13:40:56 +0800 Subject: [PATCH] chore: fix i18n, error catching --- src/main/services/OpenAIService.ts | 18 +++++++++--------- .../src/aiCore/provider/providerConfig.ts | 9 +++++---- src/renderer/src/i18n/locales/en-us.json | 4 ++-- src/renderer/src/i18n/locales/zh-cn.json | 4 ++-- src/renderer/src/i18n/locales/zh-tw.json | 4 ++-- src/renderer/src/i18n/translate/de-de.json | 4 ++-- src/renderer/src/i18n/translate/el-gr.json | 4 ++-- src/renderer/src/i18n/translate/es-es.json | 4 ++-- src/renderer/src/i18n/translate/fr-fr.json | 4 ++-- src/renderer/src/i18n/translate/ja-jp.json | 4 ++-- src/renderer/src/i18n/translate/pt-pt.json | 4 ++-- src/renderer/src/i18n/translate/ru-ru.json | 4 ++-- 12 files changed, 34 insertions(+), 33 deletions(-) diff --git a/src/main/services/OpenAIService.ts b/src/main/services/OpenAIService.ts index 5295aed50e..1015da54ed 100644 --- a/src/main/services/OpenAIService.ts +++ b/src/main/services/OpenAIService.ts @@ -117,9 +117,6 @@ class OpenAIService { public async getValidAccessToken(): Promise { const clientId = DEFAULT_CLIENT_ID - if (!clientId || clientId.startsWith('0000')) { - logger.warn('OPENAI_OAUTH_CLIENT_ID is not set. OAuth may fail until configured.') - } const creds = await this.loadCredentials() if (!creds) return null if (creds.expires_at > Date.now() + 60000) { @@ -144,9 +141,6 @@ class OpenAIService { public async startOAuthFlow(): Promise { const clientId = DEFAULT_CLIENT_ID - if (!clientId || clientId.startsWith('0000')) { - logger.warn('OPENAI_OAUTH_CLIENT_ID is not set. Please configure it for production use.') - } // If already have valid access, short-circuit const existing = await this.getValidAccessToken() if (existing) return 'already_authenticated' @@ -194,8 +188,10 @@ class OpenAIService { try { await promises.unlink(CREDS_PATH) logger.info('OpenAI credentials cleared') - } catch (e) { - if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error + } } } @@ -249,7 +245,11 @@ class OpenAIService { const padLen = (4 - (normalized.length % 4)) % 4 const padded = normalized + '='.repeat(padLen) const json = Buffer.from(padded, 'base64').toString('utf8') - return JSON.parse(json) + try { + return JSON.parse(json) + } catch { + return null + } } } diff --git a/src/renderer/src/aiCore/provider/providerConfig.ts b/src/renderer/src/aiCore/provider/providerConfig.ts index a7689c2622..a5a52a7eaf 100644 --- a/src/renderer/src/aiCore/provider/providerConfig.ts +++ b/src/renderer/src/aiCore/provider/providerConfig.ts @@ -172,7 +172,7 @@ export function providerToAiSdkConfig( if (actualProvider.type === 'openai-response' && !isOpenAIChatCompletionOnlyModel(model)) { extraOptions.mode = 'responses' } else if (aiSdkProviderId === 'openai') { - // codex -> responses api + // OAuth authentication requires using the responses API mode instead of chat mode if (actualProvider.authType == 'oauth') { extraOptions.mode = 'responses' } else { @@ -330,7 +330,7 @@ export async function prepareSpecialProviderConfig( case 'openai': { if (provider.authType === 'oauth') { const accountId = await window.api.openai_oauth.getAccountId() - const sessionId = await window.api.openai_oauth.getSessionId?.() + const sessionId = await window.api.openai_oauth.getSessionId() const nextHeaders: Record = { ...(config.options.headers ? (config.options.headers as Record) : {}), 'chatgpt-account-id': accountId || '', @@ -338,7 +338,7 @@ export async function prepareSpecialProviderConfig( } const oauthToken = await window.api.openai_oauth.getAccessToken() - // OAuth 模式下移除 X-Api-Key,改为 Authorization + // remove some headers delete (nextHeaders as any)['X-Api-Key'] delete (nextHeaders as any)['X-Title'] config.options = { @@ -352,7 +352,8 @@ export async function prepareSpecialProviderConfig( baseURL: 'https://chatgpt.com/backend-api/codex' } config.options.fetch = async (url, options) => { - // add specified body + // Customize the request body for OpenAI's Codex API: + // Remove unsupported fields and add required parameters ('store' and 'instructions'). const originalBody = JSON.parse(options.body) const fieldsToRemove = [ 'temperature', diff --git a/src/renderer/src/i18n/locales/en-us.json b/src/renderer/src/i18n/locales/en-us.json index 8e2e9ac7bd..4bc08b17b4 100644 --- a/src/renderer/src/i18n/locales/en-us.json +++ b/src/renderer/src/i18n/locales/en-us.json @@ -4400,7 +4400,7 @@ "authenticating": "Authenticating", "cancel": "Cancel", "description": "OAuth Authentication", - "description_detail": "Click 'Start Authorization' to open the OpenAI login page in your browser. After logging in, copy the entire URL that redirects to the local address (http://127.0.0.1:1455/auth/callback?...) and paste it here to complete authentication.", + "description_detail": "Click 'Start Authorization' to open the OpenAI login page in your browser. After logging in, copy the entire URL that redirects to the local address (http://localhost:1455/auth/callback?...) and paste it here to complete authentication.", "enter_redirect_url": "Redirect URL", "logout": "Logout", "logout_failed": "Logout failed", @@ -4409,7 +4409,7 @@ "start_auth": "Start Authorization", "submit_url": "Submit URL", "url_error": "URL parsing or authentication failed, please try again", - "url_placeholder": "Paste the full URL starting with http://127.0.0.1:1455/auth/callback" + "url_placeholder": "Paste the full URL starting with http://localhost:1455/auth/callback" }, "remove_duplicate_keys": "Remove Duplicate Keys", "remove_invalid_keys": "Remove Invalid Keys", diff --git a/src/renderer/src/i18n/locales/zh-cn.json b/src/renderer/src/i18n/locales/zh-cn.json index 1e1f7f2e7d..18d653b5aa 100644 --- a/src/renderer/src/i18n/locales/zh-cn.json +++ b/src/renderer/src/i18n/locales/zh-cn.json @@ -4400,7 +4400,7 @@ "authenticating": "正在认证", "cancel": "取消", "description": "使用 OpenAI OAuth 登录", - "description_detail": "点击开始授权将在浏览器中打开 OpenAI 登录页。登录后复制跳转到本地地址的整条 URL(http://127.0.0.1:1455/auth/callback?...),粘贴回此处完成认证。", + "description_detail": "点击开始授权将在浏览器中打开 OpenAI 登录页。登录后复制跳转到本地地址的整条 URL(http://localhost:1455/auth/callback?...),粘贴回此处完成认证。", "enter_redirect_url": "重定向 URL", "logout": "登出", "logout_failed": "登出失败", @@ -4409,7 +4409,7 @@ "start_auth": "开始授权", "submit_url": "提交 URL", "url_error": "URL 解析或认证失败,请重试", - "url_placeholder": "粘贴以 http://127.0.0.1:1455/auth/callback 开头的完整 URL" + "url_placeholder": "粘贴以 http://localhost:1455/auth/callback 开头的完整 URL" }, "remove_duplicate_keys": "移除重复密钥", "remove_invalid_keys": "删除无效密钥", diff --git a/src/renderer/src/i18n/locales/zh-tw.json b/src/renderer/src/i18n/locales/zh-tw.json index e625800ab3..847e8863e3 100644 --- a/src/renderer/src/i18n/locales/zh-tw.json +++ b/src/renderer/src/i18n/locales/zh-tw.json @@ -4400,7 +4400,7 @@ "authenticating": "正在認證", "cancel": "取消", "description": "使用 OpenAI OAuth 登入", - "description_detail": "點擊開始授權後會在瀏覽器開啟 OpenAI 登入頁。登入後請複製跳轉至本機位址的完整 URL(http://127.0.0.1:1455/auth/callback?...),貼回此處完成認證。", + "description_detail": "點擊開始授權後會在瀏覽器開啟 OpenAI 登入頁。登入後請複製跳轉至本機位址的完整 URL(http://localhost:1455/auth/callback?...),貼回此處完成認證。", "enter_redirect_url": "重新導向 URL", "logout": "登出", "logout_failed": "登出失敗", @@ -4409,7 +4409,7 @@ "start_auth": "開始授權", "submit_url": "提交 URL", "url_error": "URL 解析或認證失敗,請重試", - "url_placeholder": "貼上以 http://127.0.0.1:1455/auth/callback 開頭的完整 URL" + "url_placeholder": "貼上以 http://localhost:1455/auth/callback 開頭的完整 URL" }, "remove_duplicate_keys": "移除重複金鑰", "remove_invalid_keys": "刪除無效金鑰", diff --git a/src/renderer/src/i18n/translate/de-de.json b/src/renderer/src/i18n/translate/de-de.json index 208d5ffa5f..fef53e9d3d 100644 --- a/src/renderer/src/i18n/translate/de-de.json +++ b/src/renderer/src/i18n/translate/de-de.json @@ -4400,7 +4400,7 @@ "authenticating": "Authentifizierung läuft", "cancel": "Abbrechen", "description": "OAuth-Authentifizierung", - "description_detail": "Klicken Sie auf \"Autorisierung starten\", um die OpenAI-Anmeldeseite in Ihrem Browser zu öffnen. Nach dem Anmelden kopieren Sie die vollständige URL, die zur lokalen Adresse (http://127.0.0.1:1455/auth/callback?...) weiterleitet, und fügen Sie sie hier ein, um die Authentifizierung abzuschließen.", + "description_detail": "Klicken Sie auf \"Autorisierung starten\", um die OpenAI-Anmeldeseite in Ihrem Browser zu öffnen. Nach dem Anmelden kopieren Sie die vollständige URL, die zur lokalen Adresse (http://localhost:1455/auth/callback?...) weiterleitet, und fügen Sie sie hier ein, um die Authentifizierung abzuschließen.", "enter_redirect_url": "Weiterleitungs-URL", "logout": "Abmelden", "logout_failed": "Abmelden fehlgeschlagen", @@ -4409,7 +4409,7 @@ "start_auth": "Autorisierung starten", "submit_url": "URL senden", "url_error": "URL-Analyse oder Authentifizierung fehlgeschlagen, bitte erneut versuchen", - "url_placeholder": "Fügen Sie die vollständige URL ein, die mit http://127.0.0.1:1455/auth/callback beginnt" + "url_placeholder": "Fügen Sie die vollständige URL ein, die mit http://localhost:1455/auth/callback beginnt" }, "remove_duplicate_keys": "Doppelte Schlüssel entfernen", "remove_invalid_keys": "Ungültige Schlüssel löschen", diff --git a/src/renderer/src/i18n/translate/el-gr.json b/src/renderer/src/i18n/translate/el-gr.json index abc1784123..965294d35e 100644 --- a/src/renderer/src/i18n/translate/el-gr.json +++ b/src/renderer/src/i18n/translate/el-gr.json @@ -4400,7 +4400,7 @@ "authenticating": "Γίνεται έλεγχος ταυτότητας", "cancel": "Ακύρωση", "description": "Έλεγχος ταυτότητας OAuth", - "description_detail": "Κάντε κλικ στο \"Έναρξη εξουσιοδότησης\" για να ανοίξετε τη σελίδα σύνδεσης της OpenAI στον περιηγητή σας. Αφού συνδεθείτε, αντιγράψτε ολόκληρο το URL που ανακατευθύνει στη τοπική διεύθυνση (http://127.0.0.1:1455/auth/callback?...) και επικολλήστε το εδώ για να ολοκληρώσετε τον έλεγχο ταυτότητας.", + "description_detail": "Κάντε κλικ στο \"Έναρξη εξουσιοδότησης\" για να ανοίξετε τη σελίδα σύνδεσης της OpenAI στον περιηγητή σας. Αφού συνδεθείτε, αντιγράψτε ολόκληρο το URL που ανακατευθύνει στη τοπική διεύθυνση (http://localhost:1455/auth/callback?...) και επικολλήστε το εδώ για να ολοκληρώσετε τον έλεγχο ταυτότητας.", "enter_redirect_url": "URL ανακατεύθυνσης", "logout": "Αποσύνδεση", "logout_failed": "Αποτυχία αποσύνδεσης", @@ -4409,7 +4409,7 @@ "start_auth": "Έναρξη εξουσιοδότησης", "submit_url": "Υποβολή URL", "url_error": "Αποτυχία ανάλυσης URL ή ελέγχου ταυτότητας, δοκιμάστε ξανά", - "url_placeholder": "Επικολλήστε το πλήρες URL που ξεκινά με http://127.0.0.1:1455/auth/callback" + "url_placeholder": "Επικολλήστε το πλήρες URL που ξεκινά με http://localhost:1455/auth/callback" }, "remove_duplicate_keys": "Αφαίρεση Επαναλαμβανόμενων Κλειδιών", "remove_invalid_keys": "Διαγραφή Ακυρωμένων Κλειδιών", diff --git a/src/renderer/src/i18n/translate/es-es.json b/src/renderer/src/i18n/translate/es-es.json index f86738f378..08d69fd769 100644 --- a/src/renderer/src/i18n/translate/es-es.json +++ b/src/renderer/src/i18n/translate/es-es.json @@ -4400,7 +4400,7 @@ "authenticating": "Autenticando", "cancel": "Cancelar", "description": "Autenticación OAuth", - "description_detail": "Haz clic en \"Iniciar autorización\" para abrir la página de inicio de sesión de OpenAI en tu navegador. Después de iniciar sesión, copia la URL completa que redirige a la dirección local (http://127.0.0.1:1455/auth/callback?...) y pégala aquí para completar la autenticación.", + "description_detail": "Haz clic en \"Iniciar autorización\" para abrir la página de inicio de sesión de OpenAI en tu navegador. Después de iniciar sesión, copia la URL completa que redirige a la dirección local (http://localhost:1455/auth/callback?...) y pégala aquí para completar la autenticación.", "enter_redirect_url": "URL de redirección", "logout": "Cerrar sesión", "logout_failed": "Error al cerrar sesión", @@ -4409,7 +4409,7 @@ "start_auth": "Iniciar autorización", "submit_url": "Enviar URL", "url_error": "Error al analizar la URL o al autenticar; inténtalo de nuevo", - "url_placeholder": "Pega la URL completa que empieza por http://127.0.0.1:1455/auth/callback" + "url_placeholder": "Pega la URL completa que empieza por http://localhost:1455/auth/callback" }, "remove_duplicate_keys": "Eliminar claves duplicadas", "remove_invalid_keys": "Eliminar claves inválidas", diff --git a/src/renderer/src/i18n/translate/fr-fr.json b/src/renderer/src/i18n/translate/fr-fr.json index f26be875a4..34bd7d9ff8 100644 --- a/src/renderer/src/i18n/translate/fr-fr.json +++ b/src/renderer/src/i18n/translate/fr-fr.json @@ -4400,7 +4400,7 @@ "authenticating": "Authentification en cours", "cancel": "Annuler", "description": "Authentification OAuth", - "description_detail": "Cliquez sur « Démarrer l’autorisation » pour ouvrir la page de connexion OpenAI dans votre navigateur. Après vous être connecté, copiez l’URL complète qui redirige vers l’adresse locale (http://127.0.0.1:1455/auth/callback?...) et collez-la ici pour terminer l’authentification.", + "description_detail": "Cliquez sur « Démarrer l’autorisation » pour ouvrir la page de connexion OpenAI dans votre navigateur. Après vous être connecté, copiez l’URL complète qui redirige vers l’adresse locale (http://localhost:1455/auth/callback?...) et collez-la ici pour terminer l’authentification.", "enter_redirect_url": "URL de redirection", "logout": "Se déconnecter", "logout_failed": "Échec de la déconnexion", @@ -4409,7 +4409,7 @@ "start_auth": "Démarrer l’autorisation", "submit_url": "Envoyer l’URL", "url_error": "L’analyse de l’URL ou l’authentification a échoué, veuillez réessayer", - "url_placeholder": "Collez l’URL complète commençant par http://127.0.0.1:1455/auth/callback" + "url_placeholder": "Collez l’URL complète commençant par http://localhost:1455/auth/callback" }, "remove_duplicate_keys": "Supprimer les clés en double", "remove_invalid_keys": "Supprimer les clés invalides", diff --git a/src/renderer/src/i18n/translate/ja-jp.json b/src/renderer/src/i18n/translate/ja-jp.json index 159a4a9c77..09ed5f97ba 100644 --- a/src/renderer/src/i18n/translate/ja-jp.json +++ b/src/renderer/src/i18n/translate/ja-jp.json @@ -4400,7 +4400,7 @@ "authenticating": "認証中", "cancel": "キャンセル", "description": "OAuth認証", - "description_detail": "「認可を開始」をクリックして、ブラウザで OpenAI のログインページを開きます。ログイン後、ローカルアドレス(http://127.0.0.1:1455/auth/callback?...)にリダイレクトされる完全なURLをコピーし、ここに貼り付けて認証を完了してください。", + "description_detail": "「認可を開始」をクリックして、ブラウザで OpenAI のログインページを開きます。ログイン後、ローカルアドレス(http://localhost:1455/auth/callback?...)にリダイレクトされる完全なURLをコピーし、ここに貼り付けて認証を完了してください。", "enter_redirect_url": "リダイレクトURL", "logout": "ログアウト", "logout_failed": "ログアウトに失敗しました", @@ -4409,7 +4409,7 @@ "start_auth": "認可を開始", "submit_url": "URLを送信", "url_error": "URLの解析または認証に失敗しました。もう一度お試しください", - "url_placeholder": "http://127.0.0.1:1455/auth/callback で始まる完全なURLを貼り付けてください" + "url_placeholder": "http://localhost:1455/auth/callback で始まる完全なURLを貼り付けてください" }, "remove_duplicate_keys": "重複キーを削除", "remove_invalid_keys": "無効なキーを削除", diff --git a/src/renderer/src/i18n/translate/pt-pt.json b/src/renderer/src/i18n/translate/pt-pt.json index f71c21d183..c1fb28b6f6 100644 --- a/src/renderer/src/i18n/translate/pt-pt.json +++ b/src/renderer/src/i18n/translate/pt-pt.json @@ -4400,7 +4400,7 @@ "authenticating": "A autenticar", "cancel": "Cancelar", "description": "Autenticação OAuth", - "description_detail": "Clique em \"Iniciar autorização\" para abrir a página de início de sessão da OpenAI no seu navegador. Depois de iniciar sessão, copie o URL completo que redireciona para o endereço local (http://127.0.0.1:1455/auth/callback?...) e cole-o aqui para concluir a autenticação.", + "description_detail": "Clique em \"Iniciar autorização\" para abrir a página de início de sessão da OpenAI no seu navegador. Depois de iniciar sessão, copie o URL completo que redireciona para o endereço local (http://localhost:1455/auth/callback?...) e cole-o aqui para concluir a autenticação.", "enter_redirect_url": "URL de redirecionamento", "logout": "Terminar sessão", "logout_failed": "Falha ao terminar sessão", @@ -4409,7 +4409,7 @@ "start_auth": "Iniciar autorização", "submit_url": "Enviar URL", "url_error": "Análise do URL ou autenticação falhou, tente novamente", - "url_placeholder": "Cole o URL completo começando por http://127.0.0.1:1455/auth/callback" + "url_placeholder": "Cole o URL completo começando por http://localhost:1455/auth/callback" }, "remove_duplicate_keys": "Remover chaves duplicadas", "remove_invalid_keys": "Remover chaves inválidas", diff --git a/src/renderer/src/i18n/translate/ru-ru.json b/src/renderer/src/i18n/translate/ru-ru.json index 2eb54c2623..2309907e9e 100644 --- a/src/renderer/src/i18n/translate/ru-ru.json +++ b/src/renderer/src/i18n/translate/ru-ru.json @@ -4400,7 +4400,7 @@ "authenticating": "Идёт аутентификация", "cancel": "Отмена", "description": "Аутентификация OAuth", - "description_detail": "Нажмите \"Начать авторизацию\", чтобы открыть страницу входа OpenAI в вашем браузере. После входа скопируйте полный URL, который перенаправляет на локальный адрес (http://127.0.0.1:1455/auth/callback?...), и вставьте его здесь, чтобы завершить аутентификацию.", + "description_detail": "Нажмите \"Начать авторизацию\", чтобы открыть страницу входа OpenAI в вашем браузере. После входа скопируйте полный URL, который перенаправляет на локальный адрес (http://localhost:1455/auth/callback?...), и вставьте его здесь, чтобы завершить аутентификацию.", "enter_redirect_url": "URL перенаправления", "logout": "Выйти", "logout_failed": "Не удалось выйти", @@ -4409,7 +4409,7 @@ "start_auth": "Начать авторизацию", "submit_url": "Отправить URL", "url_error": "Не удалось разобрать URL или выполнить аутентификацию. Повторите попытку", - "url_placeholder": "Вставьте полный URL, начинающийся с http://127.0.0.1:1455/auth/callback" + "url_placeholder": "Вставьте полный URL, начинающийся с http://localhost:1455/auth/callback" }, "remove_duplicate_keys": "Удалить дубликаты ключей", "remove_invalid_keys": "Удалить недействительные ключи",