From 3abc948b77cfb94988bb6b8d2b73659290a7091a Mon Sep 17 00:00:00 2001 From: libr Date: Fri, 7 Nov 2025 20:14:48 +0800 Subject: [PATCH 1/4] feat: support codex. --- packages/shared/IpcChannel.ts | 12 + src/main/ipc.ts | 15 + src/main/services/OpenAIService.ts | 266 ++++++++++++++++++ src/preload/index.ts | 13 + .../src/aiCore/provider/providerConfig.ts | 59 +++- src/renderer/src/i18n/locales/en-us.json | 20 +- src/renderer/src/i18n/locales/zh-cn.json | 20 +- src/renderer/src/i18n/locales/zh-tw.json | 20 +- .../ProviderSettings/OpenAISettings.tsx | 159 +++++++++++ .../ProviderSettings/ProviderSetting.tsx | 21 +- 10 files changed, 597 insertions(+), 8 deletions(-) create mode 100644 src/main/services/OpenAIService.ts create mode 100644 src/renderer/src/pages/settings/ProviderSettings/OpenAISettings.tsx diff --git a/packages/shared/IpcChannel.ts b/packages/shared/IpcChannel.ts index 7704bbaa13..111f9304e4 100644 --- a/packages/shared/IpcChannel.ts +++ b/packages/shared/IpcChannel.ts @@ -334,6 +334,18 @@ export enum IpcChannel { Anthropic_HasCredentials = 'anthropic:has-credentials', Anthropic_ClearCredentials = 'anthropic:clear-credentials', + // OpenAI OAuth + OpenAI_StartOAuthFlow = 'openai:start-oauth-flow', + OpenAI_CompleteOAuthWithRedirectUrl = 'openai:complete-oauth-with-redirect-url', + OpenAI_CancelOAuthFlow = 'openai:cancel-oauth-flow', + OpenAI_GetAccessToken = 'openai:get-access-token', + OpenAI_GetApiKey = 'openai:get-api-key', + OpenAI_GetIdToken = 'openai:get-id-token', + OpenAI_GetAccountId = 'openai:get-account-id', + OpenAI_GetSessionId = 'openai:get-session-id', + OpenAI_HasCredentials = 'openai:has-credentials', + OpenAI_ClearCredentials = 'openai:clear-credentials', + // CodeTools CodeTools_Run = 'code-tools:run', CodeTools_GetAvailableTerminals = 'code-tools:get-available-terminals', diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 5bf5c73051..91b6bdf20f 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -6,6 +6,7 @@ import { loggerService } from '@logger' import { isLinux, isMac, isPortable, isWin } from '@main/constant' import { generateSignature } from '@main/integration/cherryai' import anthropicService from '@main/services/AnthropicService' +import openAIService from '@main/services/OpenAIService' import { getBinaryPath, isBinaryExists, runInstallScript } from '@main/utils/process' import { handleZoomFactor } from '@main/utils/zoom' import type { SpanEntity, TokenUsage } from '@mcp-trace/trace-core' @@ -885,6 +886,20 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) { ipcMain.handle(IpcChannel.Anthropic_HasCredentials, () => anthropicService.hasCredentials()) ipcMain.handle(IpcChannel.Anthropic_ClearCredentials, () => anthropicService.clearCredentials()) + // OpenAI OAuth + ipcMain.handle(IpcChannel.OpenAI_StartOAuthFlow, () => openAIService.startOAuthFlow()) + ipcMain.handle(IpcChannel.OpenAI_CompleteOAuthWithRedirectUrl, (_, url: string) => + openAIService.completeOAuthWithRedirectUrl(url) + ) + ipcMain.handle(IpcChannel.OpenAI_CancelOAuthFlow, () => openAIService.cancelOAuthFlow()) + ipcMain.handle(IpcChannel.OpenAI_GetAccessToken, () => openAIService.getValidAccessToken()) + ipcMain.handle(IpcChannel.OpenAI_GetApiKey, () => openAIService.getApiKey()) + ipcMain.handle(IpcChannel.OpenAI_GetIdToken, () => openAIService.getIdToken()) + ipcMain.handle(IpcChannel.OpenAI_GetAccountId, () => openAIService.getAccountId()) + ipcMain.handle(IpcChannel.OpenAI_GetSessionId, () => openAIService.getSessionId()) + ipcMain.handle(IpcChannel.OpenAI_HasCredentials, () => openAIService.hasCredentials()) + ipcMain.handle(IpcChannel.OpenAI_ClearCredentials, () => openAIService.clearCredentials()) + // CodeTools ipcMain.handle(IpcChannel.CodeTools_Run, codeToolsService.run) ipcMain.handle(IpcChannel.CodeTools_GetAvailableTerminals, () => codeToolsService.getAvailableTerminalsForPlatform()) diff --git a/src/main/services/OpenAIService.ts b/src/main/services/OpenAIService.ts new file mode 100644 index 0000000000..b098ceeeb9 --- /dev/null +++ b/src/main/services/OpenAIService.ts @@ -0,0 +1,266 @@ +import path from 'node:path' + +import { loggerService } from '@logger' +import { getConfigDir } from '@main/utils/file' +import * as crypto from 'crypto' +import { net, shell } from 'electron' +import { promises } from 'fs' +import { dirname } from 'path' + +const logger = loggerService.withContext('OpenAIOAuth') + +// Client configuration +const DEFAULT_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann'; +const CREDS_PATH = path.join(getConfigDir(), 'oauth', 'openai.json') +const REDIRECT_URI = 'http://localhost:1455/auth/callback' +const ISSUER = 'https://auth.openai.com' + +interface Credentials { + access_token: string + refresh_token: string + expires_at: number + id_token?: string +} + +interface PKCEState { + verifier: string + challenge: string + state: string +} + +class OpenAIService { + private current: PKCEState | null = null + + private generatePKCEState(): PKCEState { + const verifier = crypto.randomBytes(32).toString('base64url') + const challenge = crypto.createHash('sha256').update(verifier).digest('base64url') + const state = crypto.randomBytes(16).toString('base64url') + return { verifier, challenge, state } + } + + private buildAuthorizeUrl(pkce: PKCEState, clientId: string): string { + const url = new URL(`${ISSUER}/oauth/authorize`) + url.searchParams.set('response_type', 'code') + url.searchParams.set('client_id', clientId) + url.searchParams.set('redirect_uri', REDIRECT_URI) + url.searchParams.set('scope', 'openid profile email offline_access') + url.searchParams.set('code_challenge', pkce.challenge) + url.searchParams.set('code_challenge_method', 'S256') + url.searchParams.set('state', pkce.state) + // Only required OAuth params; remove non-essential extras + logger.debug(`Built OpenAI authorize URL: ${url.toString()}`) + return url.toString() + } + + private async exchangeCodeForTokens( + code: string, + verifier: string, + clientId: string + ): Promise { + const response = await net.fetch(`${ISSUER}/oauth/token`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', + code, + redirect_uri: REDIRECT_URI, + client_id: clientId, + code_verifier: verifier + }).toString() + }) + + if (!response.ok) { + throw new Error(`OpenAI token exchange failed: ${response.status} ${response.statusText}`) + } + const data = await response.json() + return { + access_token: data.access_token, + refresh_token: data.refresh_token, + expires_at: Date.now() + data.expires_in * 1000, + id_token: data.id_token + } + } + + private async refreshAccessToken(refreshToken: string, clientId: string): Promise { + const response = await net.fetch(`${ISSUER}/oauth/token`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken, + client_id: clientId + }).toString() + }) + + if (!response.ok) { + throw new Error(`OpenAI token refresh failed: ${response.status} ${response.statusText}`) + } + const data = await response.json() + return { + access_token: data.access_token, + refresh_token: data.refresh_token ?? refreshToken, + expires_at: Date.now() + data.expires_in * 1000, + id_token: data.id_token + } + } + + private async saveCredentials(creds: Credentials) { + await promises.mkdir(dirname(CREDS_PATH), { recursive: true }) + await promises.writeFile(CREDS_PATH, JSON.stringify(creds, null, 2)) + await promises.chmod(CREDS_PATH, 0o600) + } + + private async loadCredentials(): Promise { + try { + const txt = await promises.readFile(CREDS_PATH, 'utf-8') + return JSON.parse(txt) + } catch { + return null + } + } + + 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) { + return creds.access_token + } + try { + const refreshed = await this.refreshAccessToken(creds.refresh_token, clientId) + // Preserve previous id_token if refresh did not include one + const merged: Credentials = { ...refreshed, id_token: refreshed.id_token ?? creds.id_token } + await this.saveCredentials(merged) + return merged.access_token + } catch (e) { + logger.error('OpenAI access token refresh failed', e as Error) + return null + } + } + + public async getApiKey(): Promise { + // For OAuth-based access, the access token serves as bearer token + return this.getValidAccessToken() + } + + 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' + + this.current = this.generatePKCEState() + const authUrl = this.buildAuthorizeUrl(this.current, clientId) + await shell.openExternal(authUrl) + return authUrl + } + + public async completeOAuthWithRedirectUrl(redirectUrl: string): Promise { + if (!this.current) { + throw new Error('OAuth flow not started. Please call startOAuthFlow first.') + } + const clientId = DEFAULT_CLIENT_ID + const url = new URL(redirectUrl) + const code = url.searchParams.get('code') || '' + const state = url.searchParams.get('state') || '' + if (!code) { + throw new Error('Authorization code not found in redirect URL') + } + if (!state || state !== this.current.state) { + throw new Error('State mismatch detected') + } + try { + const base = await this.exchangeCodeForTokens(code, this.current.verifier, clientId) + await this.saveCredentials(base) + this.current = null + return base.access_token + } catch (e) { + this.current = null + logger.error('OpenAI OAuth code exchange failed', e as Error) + throw e + } + } + + public cancelOAuthFlow(): void { + if (this.current) { + logger.info('Cancelling OpenAI OAuth flow') + this.current = null + } + } + + public async clearCredentials(): Promise { + try { + await promises.unlink(CREDS_PATH) + logger.info('OpenAI credentials cleared') + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e + } + } + + public async hasCredentials(): Promise { + const creds = await this.loadCredentials() + return creds !== null + } + + public async getIdToken(): Promise { + const creds = await this.loadCredentials() + return creds?.id_token ?? null + } + + public async getAccountId(): Promise { + const idToken = await this.getIdToken() + if (!idToken) return null + try { + const payload = this.decodeJwtPayload(idToken) + if (!payload) return null + // Try common fields for account/user identifiers + const candidates = [ + payload.account_id, + payload.chatgpt_user_id, + payload.aid, + payload.sub + ] + const id = candidates.find((v) => typeof v === 'string' && v.length > 0) + return id ?? null + } catch (e) { + logger.warn('Failed to parse OpenAI ID token for account id', e as Error) + return null + } + } + + public async getSessionId(): Promise { + // Derive a stable session id from ID token claims when possible + const idToken = await this.getIdToken() + if (!idToken) return null + try { + const payload = this.decodeJwtPayload(idToken) + // Prefer standard-ish fields if present + const rawCandidate = + (payload && (payload.sid || payload.session_id || payload.jti || payload.sub)) || idToken + const hash = crypto.createHash('sha256').update(String(rawCandidate)).digest('hex').slice(0, 32) + return `sess_${hash}` + } catch (e) { + logger.warn('Failed to derive OpenAI session id', e as Error) + return null + } + } + + private decodeJwtPayload(token: string): any | null { + const parts = token.split('.') + if (parts.length < 2) return null + const payload = parts[1] + const normalized = payload.replace(/-/g, '+').replace(/_/g, '/') + const padLen = (4 - (normalized.length % 4)) % 4 + const padded = normalized + '='.repeat(padLen) + const json = Buffer.from(padded, 'base64').toString('utf8') + return JSON.parse(json) + } +} + +export default new OpenAIService() diff --git a/src/preload/index.ts b/src/preload/index.ts index d60e0edfe9..861b020f18 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -481,6 +481,19 @@ const api = { hasCredentials: () => ipcRenderer.invoke(IpcChannel.Anthropic_HasCredentials), clearCredentials: () => ipcRenderer.invoke(IpcChannel.Anthropic_ClearCredentials) }, + openai_oauth: { + startOAuthFlow: () => ipcRenderer.invoke(IpcChannel.OpenAI_StartOAuthFlow), + completeOAuthWithRedirectUrl: (url: string) => + ipcRenderer.invoke(IpcChannel.OpenAI_CompleteOAuthWithRedirectUrl, url), + cancelOAuthFlow: () => ipcRenderer.invoke(IpcChannel.OpenAI_CancelOAuthFlow), + getAccessToken: () => ipcRenderer.invoke(IpcChannel.OpenAI_GetAccessToken), + getApiKey: () => ipcRenderer.invoke(IpcChannel.OpenAI_GetApiKey), + getIdToken: () => ipcRenderer.invoke(IpcChannel.OpenAI_GetIdToken), + getAccountId: () => ipcRenderer.invoke(IpcChannel.OpenAI_GetAccountId), + getSessionId: () => ipcRenderer.invoke(IpcChannel.OpenAI_GetSessionId), + hasCredentials: () => ipcRenderer.invoke(IpcChannel.OpenAI_HasCredentials), + clearCredentials: () => ipcRenderer.invoke(IpcChannel.OpenAI_ClearCredentials) + }, codeTools: { run: ( cliTool: string, diff --git a/src/renderer/src/aiCore/provider/providerConfig.ts b/src/renderer/src/aiCore/provider/providerConfig.ts index 7f279a3898..a65dffa138 100644 --- a/src/renderer/src/aiCore/provider/providerConfig.ts +++ b/src/renderer/src/aiCore/provider/providerConfig.ts @@ -172,7 +172,12 @@ export function providerToAiSdkConfig( if (actualProvider.type === 'openai-response' && !isOpenAIChatCompletionOnlyModel(model)) { extraOptions.mode = 'responses' } else if (aiSdkProviderId === 'openai') { - extraOptions.mode = 'chat' + // codex -> responses api + if(actualProvider.authType == "oauth"){ + extraOptions.mode = "responses" + } else { + extraOptions.mode = 'chat' + } } // 添加额外headers @@ -320,6 +325,58 @@ export async function prepareSpecialProviderConfig( apiKey: '' } } + break + } + case 'openai': { + if (provider.authType === 'oauth') { + const accountId = await window.api.openai_oauth.getAccountId() + const sessionId = await window.api.openai_oauth.getSessionId?.() + const nextHeaders: Record = { + ...(config.options.headers ? (config.options.headers as Record) : {}), + 'chatgpt-account-id': accountId || '', + session_id: sessionId || '' + } + const oauthToken = await window.api.openai_oauth.getAccessToken() + + // OAuth 模式下移除 X-Api-Key,改为 Authorization + delete (nextHeaders as any)['X-Api-Key'] + delete (nextHeaders as any)["X-Title"] + config.options = { + ...config.options, + mode: "responses", + headers: { + ...nextHeaders, + Authorization: `Bearer ${oauthToken}` + }, + apiKey: '', + baseURL: "https://chatgpt.com/backend-api/codex", + } + config.options.fetch = async(url, options) => { + // add specified body + console.info('Fetching OpenAI OAuth with body', options.body) + const originalBody = JSON.parse(options.body) + const fieldsToRemove = [ + 'temperature', + 'top_p', + 'max_output_tokens', + 'user', + 'text_formatting', + 'truncation', + 'text', + 'service_tier' + ] + fieldsToRemove.forEach((field) => { + delete originalBody[field] + }) + originalBody["store"] = false; + originalBody["instructions"] = 'You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.\n\nYour capabilities:\n- Receive user prompts and other context provided by the harness, such as files in the workspace.\n- Communicate with the user by streaming thinking & responses, and by making & updating plans.\n- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the "Sandbox and approvals" section.\n\nWithin this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).\n\n# How you work\n\n## Personality\n\nYour default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.\n\n## Responsiveness\n\n### Preamble messages\n\nBefore making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:\n\n- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.\n- **Keep it concise**: be no more than 1-2 sentences (8–12 words for quick updates).\n- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.\n- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.\n\n**Examples:**\n- “I’ve explored the repo; now checking the API route definitions.”\n- “Next, I’ll patch the config and update the related tests.”\n- “I’m about to scaffold the CLI commands and helper functions.”\n- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”\n- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”\n- “Finished poking at the DB gateway. I will now chase down error handling.”\n- “Alright, build pipeline order is interesting. Checking how it reports failures.”\n- “Spotted a clever caching util; now hunting where it gets used.”\n\n**Avoiding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.\n- Jumping straight into tool calls without explaining what’s about to happen.\n- Writing overly long or speculative preambles — focus on immediate, tangible next steps.\n\n## Planning\n\nYou have access to an `update_plan` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you\'ve understood the task and convey how you\'re approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go. Note that plans are not for padding out simple work with filler steps or stating the obvious. Do not repeat the full contents of the plan after an `update_plan` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step.\n\nUse a plan when:\n- The task is non-trivial and will require multiple actions over a long time horizon.\n- There are logical phases or dependencies where sequencing matters.\n- The work has ambiguity that benefits from outlining high-level goals.\n- You want intermediate checkpoints for feedback and validation.\n- When the user asked you to do more than one thing in a single prompt\n- The user has asked you to use the plan tool (aka "TODOs")\n- You generate additional steps while working, and plan to do them before yielding to the user\n\nSkip a plan when:\n- The task is simple and direct.\n- Breaking it down would only produce literal or trivial steps.\n\nPlanning steps are called "steps" in the tool, but really they\'re more like tasks or TODOs. As such they should be very concise descriptions of non-obvious work that an engineer might do like "Write the API spec", then "Update the backend", then "Implement the frontend". On the other hand, it\'s obvious that you\'ll usually have to "Explore the codebase" or "Implement the changes", so those are not worth tracking in your plan.\n\nIt may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. The content of your plan should not involve doing anything that you aren\'t capable of doing (i.e. don\'t try to test things that you can\'t test). Do not use plans for simple or single-step queries that you can just do or answer immediately.\n\n### Examples\n\n**High-quality plans**\n\nExample 1:\n\n1. Add CLI entry with file args\n2. Parse Markdown via CommonMark library\n3. Apply semantic HTML template\n4. Handle code blocks, images, links\n5. Add error handling for invalid files\n\nExample 2:\n\n1. Define CSS variables for colors\n2. Add toggle with localStorage state\n3. Refactor components to use variables\n4. Verify all views for readability\n5. Add smooth theme-change transition\n\nExample 3:\n\n1. Set up Node.js + WebSocket server\n2. Add join/leave broadcast events\n3. Implement messaging with timestamps\n4. Add usernames + mention highlighting\n5. Persist messages in lightweight DB\n6. Add typing indicators + unread count\n\n**Low-quality plans**\n\nExample 1:\n\n1. Create CLI tool\n2. Add Markdown parser\n3. Convert to HTML\n\nExample 2:\n\n1. Add dark mode toggle\n2. Save preference\n3. Make styles look good\n\nExample 3:\n\n1. Create single-file HTML game\n2. Run quick sanity check\n3. Summarize usage instructions\n\nIf you need to write a plan, only write high quality plans, not low quality ones.\n\n## Task execution\n\nYou are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.\n\nYou MUST adhere to the following criteria when solving queries:\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {"command":["apply_patch","*** Begin Patch\\\\n*** Update File: path/to/file.py\\\\n@@ def example():\\\\n- pass\\\\n+ return 123\\\\n*** End Patch"]}\n\nIf completing the user\'s task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:\n\n- Fix the problem at the root cause rather than applying surface-level patches, when possible.\n- Avoid unneeded complexity in your solution.\n- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n- Update documentation as necessary.\n- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n- Use `git log` and `git blame` to search the history of the codebase if additional context is required.\n- NEVER add copyright or license headers unless specifically requested.\n- Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn\'t work. The same goes for making folders, deleting folders, etc.\n- Do not `git commit` your changes or create new git branches unless explicitly requested.\n- Do not add inline comments within code unless explicitly requested.\n- Do not use one-letter variable names unless explicitly requested.\n- NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.\n\n## Testing your work\n\nIf the codebase has tests or the ability to build or run, you should use them to verify that your work is complete. Generally, your testing philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there\'s no test for the code you changed, and if the adjacent patterns in the codebases show that there\'s a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests, or where the patterns don\'t indicate so.\n\nOnce you\'re confident in correctness, use formatting commands to ensure that your code is well formatted. These commands can take time so you should run them on as precise a target as possible. If there are issues you can iterate up to 3 times to get formatting right, but if you still can\'t manage it\'s better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.\n\nFor all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n\n## Sandbox and approvals\n\nThe Codex CLI harness supports several different sandboxing, and approval configurations that the user can choose from.\n\nFilesystem sandboxing prevents you from editing files without user approval. The options are:\n- *read-only*: You can only read files.\n- *workspace-write*: You can read files. You can write to files in your workspace folder, but not outside it.\n- *danger-full-access*: No filesystem sandboxing.\n\nNetwork sandboxing prevents you from accessing network without approval. Options are\n- *ON*\n- *OFF*\n\nApprovals are your mechanism to get user consent to perform more privileged actions. Although they introduce friction to the user because your work is paused until the user responds, you should leverage them to accomplish your important work. Do not let these settings or the sandbox deter you from attempting to accomplish the user\'s task. Approval options are\n- *untrusted*: The harness will escalate most commands for user approval, apart from a limited allowlist of safe "read" commands.\n- *on-failure*: The harness will allow all commands to run in the sandbox (if enabled), and failures will be escalated to the user for approval to run again without the sandbox.\n- *on-request*: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. (Note that this mode is not always available. If it is, you\'ll see parameters for it in the `shell` command description.)\n- *never*: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is pared with `danger-full-access`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don\'t see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding.\n\nWhen you are running with approvals `on-request`, and sandboxing enabled, here are scenarios where you\'ll need to request approval:\n- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /tmp)\n- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files.\n- You are running sandboxed and need to run a command that requires network access (e.g. installing packages)\n- If you run a command that is important to solving the user\'s query, but it fails because of sandboxing, rerun the command with approval.\n- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for\n- (For all of these, you should weigh alternative paths that do not require approval.)\n\nNote that when sandboxing is set to read-only, you\'ll need to request approval for any command that isn\'t a read.\n\nYou will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing ON, and approval on-failure.\n\n## Ambition vs. precision\n\nFor tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.\n\nIf you\'re operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don\'t overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.\n\nYou should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user\'s needs. This means showing good judgment that you\'re capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.\n\n## Sharing progress updates\n\nFor especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you\'re going next.\n\nBefore doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you\'re about to do to ensure they know what you\'re spending time on. Don\'t start editing or writing large files before informing the user what you are doing and why.\n\nThe messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.\n\n## Presenting your work and final message\n\nYour final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you\'ve finished a large amount of work, when describing what you\'ve done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don\'t need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.\n\nYou can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.\n\nThe user is working on the same computer as you, and has access to your work. As such there\'s no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you\'ve created or modified files using `apply_patch`, there\'s no need to tell users to "save the file" or "copy the code into a file"—just reference the file path.\n\nIf there\'s something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn\'t do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.\n\nBrevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user\'s understanding.\n\n### Final answer structure and style guidelines\n\nYou are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.\n\n**Section Headers**\n- Use only when they improve clarity — they are not mandatory for every answer.\n- Choose descriptive names that fit the content\n- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`\n- Leave no blank line before the first bullet under a header.\n- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.\n\n**Bullets**\n- Use `-` followed by a space for every bullet.\n- Bold the keyword, then colon + concise description.\n- Merge related points when possible; avoid a bullet for every trivial detail.\n- Keep bullets to one line unless breaking for clarity is unavoidable.\n- Group into short lists (4–6 bullets) ordered by importance.\n- Use consistent keyword phrasing and formatting across sections.\n\n**Monospace**\n- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).\n- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.\n- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).\n\n**Structure**\n- Place related bullets together; don’t mix unrelated concepts in the same section.\n- Order sections from general → specific → supporting info.\n- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.\n- Match structure to complexity:\n - Multi-part or detailed results → use clear headers and grouped bullets.\n - Simple results → minimal headers, possibly just a short list or paragraph.\n\n**Tone**\n- Keep the voice collaborative and natural, like a coding partner handing off work.\n- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition\n- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).\n- Keep descriptions self-contained; don’t refer to “above” or “below”.\n- Use parallel structure in lists for consistency.\n\n**Don’t**\n- Don’t use literal words “bold” or “monospace” in the content.\n- Don’t nest bullets or create deep hierarchies.\n- Don’t output ANSI escape codes directly — the CLI renderer applies them.\n- Don’t cram unrelated keywords into a single bullet; split for clarity.\n- Don’t let keyword lists run long — wrap or reformat for scanability.\n\nGenerally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.\n\nFor casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.\n\n# Tools\n\n## `apply_patch`\n\nYour patch language is a stripped‑down, file‑oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high‑level envelope:\n\n**_ Begin Patch\n[ one or more file sections ]\n_** End Patch\n\nWithin that envelope, you get a sequence of file operations.\nYou MUST include a header to specify the action you are taking.\nEach operation starts with one of three headers:\n\n**_ Add File: - create a new file. Every following line is a + line (the initial contents).\n_** Delete File: - remove an existing file. Nothing follows.\n\\*\\*\\* Update File: - patch an existing file in place (optionally with a rename).\n\nMay be immediately followed by \\*\\*\\* Move to: if you want to rename the file.\nThen one or more “hunks”, each introduced by @@ (optionally followed by a hunk header).\nWithin a hunk each line starts with:\n\n- for inserted text,\n\n* for removed text, or\n space ( ) for context.\n At the end of a truncated hunk you can emit \\*\\*\\* End of File.\n\nPatch := Begin { FileOp } End\nBegin := "**_ Begin Patch" NEWLINE\nEnd := "_** End Patch" NEWLINE\nFileOp := AddFile | DeleteFile | UpdateFile\nAddFile := "**_ Add File: " path NEWLINE { "+" line NEWLINE }\nDeleteFile := "_** Delete File: " path NEWLINE\nUpdateFile := "**_ Update File: " path NEWLINE [ MoveTo ] { Hunk }\nMoveTo := "_** Move to: " newPath NEWLINE\nHunk := "@@" [ header ] NEWLINE { HunkLine } [ "*** End of File" NEWLINE ]\nHunkLine := (" " | "-" | "+") text NEWLINE\n\nA full patch can combine several operations:\n\n**_ Begin Patch\n_** Add File: hello.txt\n+Hello world\n**_ Update File: src/app.py\n_** Move to: src/main.py\n@@ def greet():\n-print("Hi")\n+print("Hello, world!")\n**_ Delete File: obsolete.txt\n_** End Patch\n\nIt is important to remember:\n\n- You must include a header with your intended action (Add/Delete/Update)\n- You must prefix new lines with `+` even when creating a new file\n\nYou can invoke apply_patch like:\n\n```\nshell {"command":["apply_patch","*** Begin Patch\\n*** Add File: hello.txt\\n+Hello, world!\\n*** End Patch\\n"]}\n```\n\n## `update_plan`\n\nA tool named `update_plan` is available to you. You can use it to keep an up‑to‑date, step‑by‑step plan for the task.\n\nTo create a new plan, call `update_plan` with a short list of 1‑sentence steps (no more than 5-7 words each) with a `status` for each step (`pending`, `in_progress`, or `completed`).\n\nWhen steps have been completed, use `update_plan` to mark each finished step as `completed` and the next step you are working on as `in_progress`. There should always be exactly one `in_progress` step until everything is done. You can mark multiple items as complete in a single `update_plan` call.\n\nIf all steps are complete, ensure you call `update_plan` to mark all steps as `completed`.\n'; + + return fetch(url, { + ...options, + body: JSON.stringify(originalBody) + }) + } + } } } return config diff --git a/src/renderer/src/i18n/locales/en-us.json b/src/renderer/src/i18n/locales/en-us.json index e851242559..804616c4cb 100644 --- a/src/renderer/src/i18n/locales/en-us.json +++ b/src/renderer/src/i18n/locales/en-us.json @@ -4391,7 +4391,25 @@ "official_website": "Official Website" }, "openai": { - "alert": "OpenAI Provider no longer support the old calling methods. If using a third-party API, please create a new service provider." + "alert": "OpenAI provider no longer supports the old calling methods. If you are using a third-party API, please create a new service provider.", + "auth_method": "Authentication Method", + "oauth": "Web OAuth", + "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.", + "start_auth": "Start Authorization", + "authenticating": "Authenticating", + "enter_redirect_url": "Redirect URL", + "submit_url": "Submit URL", + "url_placeholder": "Paste the full URL starting with http://127.0.0.1:1455/auth/callback", + "cancel": "Cancel", + "auth_success": "OpenAI OAuth authentication successful", + "auth_failed": "OpenAI OAuth authentication failed", + "url_error": "URL parsing or authentication failed, please try again", + "authenticated": "Authenticated", + "logout": "Logout", + "logout_success": "Logged out", + "logout_failed": "Logout failed", + "apikey":"API key" }, "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 4a42f6c92a..9c6448e513 100644 --- a/src/renderer/src/i18n/locales/zh-cn.json +++ b/src/renderer/src/i18n/locales/zh-cn.json @@ -4391,7 +4391,25 @@ "official_website": "官方网站" }, "openai": { - "alert": "OpenAI 服务商不再支持旧的调用方式,如果使用第三方 API 请新建服务商" + "alert": "OpenAI 服务商不再支持旧的调用方式,如果使用第三方 API 请新建服务商", + "auth_method": "认证方式", + "oauth": "网页 OAuth", + "description": "使用 OpenAI OAuth 登录", + "description_detail": "点击开始授权将在浏览器中打开 OpenAI 登录页。登录后复制跳转到本地地址的整条 URL(http://127.0.0.1:1455/auth/callback?...),粘贴回此处完成认证。", + "start_auth": "开始授权", + "authenticating": "正在认证", + "enter_redirect_url": "重定向 URL", + "submit_url": "提交 URL", + "url_placeholder": "粘贴以 http://127.0.0.1:1455/auth/callback 开头的完整 URL", + "cancel": "取消", + "auth_success": "OpenAI OAuth 认证成功", + "auth_failed": "OpenAI OAuth 认证失败", + "url_error": "URL 解析或认证失败,请重试", + "authenticated": "已认证", + "logout": "登出", + "logout_success": "已登出", + "logout_failed": "登出失败", + "apikey":"API key" }, "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 c65815ad5b..e74d2f5c90 100644 --- a/src/renderer/src/i18n/locales/zh-tw.json +++ b/src/renderer/src/i18n/locales/zh-tw.json @@ -4391,7 +4391,25 @@ "official_website": "官方網站" }, "openai": { - "alert": "OpenAI Provider 不再支援舊的呼叫方法。如果使用第三方 API,請建立新的服務供應商" + "alert": "OpenAI Provider 不再支援舊的呼叫方法。如果使用第三方 API,請建立新的服務供應商", + "auth_method": "認證方式", + "oauth": "網頁 OAuth", + "description": "使用 OpenAI OAuth 登入", + "description_detail": "點擊開始授權後會在瀏覽器開啟 OpenAI 登入頁。登入後請複製跳轉至本機位址的完整 URL(http://127.0.0.1:1455/auth/callback?...),貼回此處完成認證。", + "start_auth": "開始授權", + "authenticating": "正在認證", + "enter_redirect_url": "重新導向 URL", + "submit_url": "提交 URL", + "url_placeholder": "貼上以 http://127.0.0.1:1455/auth/callback 開頭的完整 URL", + "cancel": "取消", + "auth_success": "OpenAI OAuth 認證成功", + "auth_failed": "OpenAI OAuth 認證失敗", + "url_error": "URL 解析或認證失敗,請重試", + "authenticated": "已認證", + "logout": "登出", + "logout_success": "已登出", + "logout_failed": "登出失敗", + "apikey":"API key" }, "remove_duplicate_keys": "移除重複金鑰", "remove_invalid_keys": "刪除無效金鑰", diff --git a/src/renderer/src/pages/settings/ProviderSettings/OpenAISettings.tsx b/src/renderer/src/pages/settings/ProviderSettings/OpenAISettings.tsx new file mode 100644 index 0000000000..e7eb17928b --- /dev/null +++ b/src/renderer/src/pages/settings/ProviderSettings/OpenAISettings.tsx @@ -0,0 +1,159 @@ +import { ExclamationCircleOutlined } from '@ant-design/icons' +import { loggerService } from '@logger' +import { Alert, Button, Input, Modal } from 'antd' +import { useEffect, useState } from 'react' +import { useTranslation } from 'react-i18next' +import styled from 'styled-components' + +const logger = loggerService.withContext('OpenAISettings') + +enum AuthStatus { + NOT_STARTED, + AUTHENTICATING, + AUTHENTICATED +} + +const OpenAISettings = () => { + const { t } = useTranslation() + const [authStatus, setAuthStatus] = useState(AuthStatus.NOT_STARTED) + const [loading, setLoading] = useState(false) + const [urlModalVisible, setUrlModalVisible] = useState(false) + const [redirectUrl, setRedirectUrl] = useState('') + + useEffect(() => { + const check = async () => { + try { + const hasCredentials = await window.api.openai_oauth.hasCredentials() + if (hasCredentials) setAuthStatus(AuthStatus.AUTHENTICATED) + } catch (e) { + logger.error('Failed to check OpenAI OAuth state', e as Error) + } + } + check() + }, []) + + const handleRedirectOAuth = async () => { + try { + setLoading(true) + await window.api.openai_oauth.startOAuthFlow() + setAuthStatus(AuthStatus.AUTHENTICATING) + setUrlModalVisible(true) + } catch (e) { + logger.error('OpenAI OAuth start failed', e as Error) + window.toast.error(t('settings.provider.openai.auth_failed')) + } finally { + setLoading(false) + } + } + + const handleSubmitUrl = async () => { + logger.info('Submitting OpenAI redirect URL') + try { + setLoading(true) + await window.api.openai_oauth.completeOAuthWithRedirectUrl(redirectUrl) + setAuthStatus(AuthStatus.AUTHENTICATED) + setUrlModalVisible(false) + window.toast.success(t('settings.provider.openai.auth_success')) + } catch (e) { + logger.error('OpenAI redirect URL submit failed', e as Error) + window.toast.error(t('settings.provider.openai.url_error')) + } finally { + setLoading(false) + } + } + + const handleCancelAuth = () => { + window.api.openai_oauth.cancelOAuthFlow() + setAuthStatus(AuthStatus.NOT_STARTED) + setUrlModalVisible(false) + setRedirectUrl('') + } + + const handleLogout = async () => { + try { + await window.api.openai_oauth.clearCredentials() + setAuthStatus(AuthStatus.NOT_STARTED) + window.toast.success(t('settings.provider.openai.logout_success')) + } catch (e) { + logger.error('OpenAI logout failed', e as Error) + window.toast.error(t('settings.provider.openai.logout_failed')) + } + } + + const renderContent = () => { + switch (authStatus) { + case AuthStatus.AUTHENTICATED: + return ( + + + {t('settings.provider.openai.logout')} + + } + showIcon + icon={} + /> + + ) + case AuthStatus.AUTHENTICATING: + return ( + + } + /> + + setRedirectUrl(e.target.value)} + placeholder={t('settings.provider.openai.url_placeholder')} + /> + + + ) + default: + return ( + + + {t('settings.provider.openai.start_auth')} + + } + showIcon + icon={} + /> + + ) + } + } + + return {renderContent()} +} + +const Container = styled.div` + padding-top: 10px; +` + +const StartContainer = styled.div` + margin-bottom: 10px; +` + +export default OpenAISettings + diff --git a/src/renderer/src/pages/settings/ProviderSettings/ProviderSetting.tsx b/src/renderer/src/pages/settings/ProviderSettings/ProviderSetting.tsx index 3f8743b66e..08c335ddf9 100644 --- a/src/renderer/src/pages/settings/ProviderSettings/ProviderSetting.tsx +++ b/src/renderer/src/pages/settings/ProviderSettings/ProviderSetting.tsx @@ -1,4 +1,3 @@ -import OpenAIAlert from '@renderer/components/Alert/OpenAIAlert' import { LoadingIcon } from '@renderer/components/Icons' import { HStack } from '@renderer/components/Layout' import { ApiKeyListPopup } from '@renderer/components/Popups/ApiKeyListPopup' @@ -62,6 +61,7 @@ import DMXAPISettings from './DMXAPISettings' import GithubCopilotSettings from './GithubCopilotSettings' import GPUStackSettings from './GPUStackSettings' import LMStudioSettings from './LMStudioSettings' +import OpenAISettings from './OpenAISettings' import OVMSSettings from './OVMSSettings' import ProviderOAuth from './ProviderOAuth' import SelectProviderModelPopup from './SelectProviderModelPopup' @@ -372,7 +372,7 @@ const ProviderSetting: FC = ({ providerId }) => { : t('settings.provider.api_host_tooltip') const isAnthropicOAuth = () => provider.id === 'anthropic' && provider.authType === 'oauth' - + const isOpenAIOAuth = () => provider.id === 'openai' && provider.authType === 'oauth' return ( @@ -407,7 +407,20 @@ const ProviderSetting: FC = ({ providerId }) => { {isProviderSupportAuth(provider) && } - {provider.id === 'openai' && } + {provider.id === 'openai' && ( + <> + {t('settings.provider.openai.auth_method')} + = ({ providerId }) => { ]} /> {provider.authType === 'oauth' && } - )} + + )} {provider.id === 'ovms' && } {isDmxapi && } {provider.id === 'anthropic' && ( From 74b2414297ad7c2f53c9c67d97ab0918107e5da6 Mon Sep 17 00:00:00 2001 From: libr Date: Sun, 9 Nov 2025 13:40:56 +0800 Subject: [PATCH 3/4] 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": "Удалить недействительные ключи", From 3c51616e5b91a12f3d8896269fbc5247bc07d019 Mon Sep 17 00:00:00 2001 From: libr Date: Sat, 6 Dec 2025 15:55:05 +0800 Subject: [PATCH 4/4] fix(provider): adjust response mode handling for OpenAI and Cherryin providers --- src/renderer/src/aiCore/provider/providerConfig.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/aiCore/provider/providerConfig.ts b/src/renderer/src/aiCore/provider/providerConfig.ts index f588032608..70fdc51480 100644 --- a/src/renderer/src/aiCore/provider/providerConfig.ts +++ b/src/renderer/src/aiCore/provider/providerConfig.ts @@ -190,13 +190,15 @@ export function providerToAiSdkConfig(actualProvider: Provider, model: Model): A extraOptions.endpoint = endpoint if (actualProvider.type === 'openai-response' && !isOpenAIChatCompletionOnlyModel(model)) { extraOptions.mode = 'responses' - } else if (aiSdkProviderId === 'openai' || (aiSdkProviderId === 'cherryin' && actualProvider.type === 'openai')) { + } else if (aiSdkProviderId === 'openai' ) { // OAuth authentication requires using the responses API mode instead of chat mode if (actualProvider.authType == 'oauth') { extraOptions.mode = 'responses' } else { extraOptions.mode = 'chat' } + } else if (aiSdkProviderId === 'cherryin') { + extraOptions.mode = 'chat' } // 添加额外headers