Skip to content

[Feat] Add Kimi Code provider with OAuth device flow#945

Merged
navedmerchant merged 10 commits into
mainfrom
feat/kimi-code
Jul 24, 2026
Merged

[Feat] Add Kimi Code provider with OAuth device flow#945
navedmerchant merged 10 commits into
mainfrom
feat/kimi-code

Conversation

@taltas

@taltas taltas commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Opened on behalf of Toray Altas. Follow up by mentioning @zoomote, in the web UI, or in Discord.

Related GitHub Issue

No linked issue — this PR was opened on behalf of a user request to add Moonshot's Kimi Code platform as a first-class provider.

Description

Adds Kimi Code (provider ID kimi-code) as a standalone provider, entirely separate from the existing Moonshot Open Platform provider (no reuse or migration of moonshotApiKey).

Key implementation details:

  • OAuth device authorization flow against auth.kimi.com with the official public client ID 17e5f671-d194-4dfb-9706-5516cb48c098. OAuth credentials live only in VS Code SecretStorage (global key kimi-code-oauth-credentials), never in profile JSON or cloud sync. Refresh is concurrency-safe (deduplicated via a shared refresh promise and invalidated on sign-out with a credential-generation counter), and API requests resolve the token at request time with exactly one forced-refresh retry after an OAuth HTTP 401 in both streaming (createMessage) and non-streaming (completePrompt) paths.
  • Distinct kimiCodeApiKey path following ordinary provider-secret persistence (SECRET_STATE_KEYS) for users who prefer API-key auth.
  • OpenAI Chat Completions at https://api.kimi.com/coding/v1 with authenticated dynamic model discovery, official metadata mapping, preservation of unknown configured model IDs, and the kimi-for-coding fallback only when no model is selected. Discovery failures are bounded (10s timeout) and attempted at most once per handler lifecycle so a down models endpoint does not stall chat requests; OAuth token calls are bounded by a 30s request timeout.
  • Configurable reasoning effort (low / high / max, default max) matching the Kimi K3 reasoning_effort API, rendered through the shared Model Reasoning Effort dropdown; unsupported persisted efforts (e.g. medium from another provider) fall back to the model default.
  • Buffered settings UI with auth-method select, device-code UX (user code + verification link while polling), sign-in/out, localization in all supported locales, and setup-gate handling so OAuth-mode Kimi Code counts as configured without an API key.
  • OAuth state aggregation in getStateToPostToWebview() is fault-tolerant: a failure in the dynamic import or state read returns safe defaults instead of breaking UI state synchronization.
  • All existing providers are preserved, no proprietary or impersonation headers are sent, and no changeset is included.

Reviewer notes: the branch was recently merged with main and adopted the canonical providerIdentifiers registry (provider-identifiers.ts), with kimiCode registered there; checkExistApiConfig keeps both the Kimi Code OAuth special case and the Zoo Gateway session-auth check.

Test Procedure

  • pnpm test (full monorepo) passes: 423 test files, 6,912 tests.
  • Focused coverage:
    • src/integrations/kimi-code/__tests__/oauth.spec.ts — official client ID, form-encoded device requests, concurrent refresh deduplication, credential storage.
    • src/api/providers/__tests__/kimi-code.spec.ts — separate dispatch from Moonshot, unknown model preservation, fallback-only default, OAuth 401 forced-refresh retry exactly once for createMessage and completePrompt, no retry on non-401 OAuth failures or API-key auth, single model-discovery attempt after failure/empty response, reasoning-effort defaults and fallback.
    • src/api/providers/fetchers/__tests__/kimi-code.spec.ts — model discovery, schema validation, metadata mapping, request timeout.
    • src/api/transform/__tests__/reasoning.spec.ts — reasoning effort transform.
    • src/core/webview/__tests__/webviewMessageHandler.spec.ts — Kimi Code sign-in/sign-out handlers (module cache reset per test).
    • src/shared/__tests__/checkExistApiConfig.spec.ts — setup-gate behavior for OAuth vs API-key auth.
    • webview-ui/src/components/settings/providers/__tests__/KimiCode.spec.tsx — buffered API key binding and device-code polling display.
    • packages/types/src/__tests__/kimi-code.test.ts — secret-key registration and schema validation.

Pre-Submission Checklist

  • Issue Linked: This PR is linked to an approved GitHub Issue (see "Related GitHub Issue" above).
  • Scope: My changes are focused on the linked issue (one major feature/fix per PR).
  • Self-Review: I have performed a thorough self-review of my code.
  • Testing: New and/or updated tests have been added to cover my changes (if applicable).
  • Documentation Impact: I have considered if my changes require documentation updates (see "Documentation Updates" section below).
  • Contribution Guidelines: I have read and agree to the Contributor Guidelines.

Screenshots / Videos

Not captured in this environment: Zoo-Code is a VS Code extension whose settings UI runs inside the editor's webview (F5 debug host) with no browser-reachable surface in CI/sandbox. Behavior is covered by the webview component tests listed above.

Documentation Updates

  • Yes, documentation updates are required — see the related docs PR below.

Related PRs

Additional Notes

CodeRabbit review feedback has been addressed across prior commits and the latest push: forced-refresh retry contract tests (streaming and non-streaming, 401 and non-401), bounded timeouts on OAuth token and model-discovery requests, sign-out invalidation of in-flight refreshes, ownership guards for superseded authorization attempts, single-attempt model discovery, fault-tolerant OAuth state aggregation, spec module-cache isolation, and full localization of the Kimi Code settings strings.

Get in Touch

Reachable via the Discord thread linked in the provenance block above.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds Kimi Code as a provider with API-key and OAuth authentication, model discovery, token refresh, extension messaging, configuration validation, and a dedicated settings UI.

Changes

Kimi Code provider

Layer / File(s) Summary
Provider contracts and model metadata
packages/types/src/..., src/shared/api.ts
Registers Kimi Code in provider schemas, secret-state keys, model mappings, default models, extension state, and exported types.
OAuth device authorization and token management
src/integrations/kimi-code/..., src/extension.ts
Implements device authorization, polling, cancellation, secret-backed credentials, token refresh, activation, and related tests.
API handler and model discovery
src/api/...
Adds Kimi Code request handling, OAuth refresh retries, model fetching, model caching rules, default model selection, error propagation, reasoning fallback, and tests.
Extension routing and validation
src/core/webview/..., src/shared/...
Adds router-model fetching, sign-in/sign-out messages, OAuth state reporting, API configuration typing, and authentication-aware validation.
Kimi Code settings interface
webview-ui/src/components/settings/..., webview-ui/src/components/ui/..., webview-ui/src/i18n/...
Adds provider selection, OAuth/API-key controls, model selection, localization, provider configuration, and UI tests.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SettingsUI
  participant WebviewMessageHandler
  participant KimiCodeOAuthManager
  participant KimiCodeOAuthAPI
  SettingsUI->>WebviewMessageHandler: Request Kimi Code sign-in
  WebviewMessageHandler->>KimiCodeOAuthManager: Start device authorization
  KimiCodeOAuthManager->>KimiCodeOAuthAPI: Request and poll OAuth token
  KimiCodeOAuthManager-->>WebviewMessageHandler: Return OAuth state
  WebviewMessageHandler-->>SettingsUI: Update authentication state
Loading

Possibly related PRs

Suggested labels: awaiting-author, awaiting-review

Suggested reviewers: navedmerchant

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed, but it omits the required linked GitHub issue and does not provide an issue number in the template's Related GitHub Issue section. Add the approved issue number in the Related GitHub Issue section (e.g., Closes: #123) and mark the issue-linked checklist item accordingly.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately highlights the main change: adding the Kimi Code provider with OAuth device flow.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/kimi-code

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/api/providers/__tests__/kimi-code.spec.ts`:
- Around line 15-30: Extend the package-local KimiCodeHandler tests to cover
forced-refresh retry behavior for both createMessage() and completePrompt():
verify OAuth HTTP 401 failures refresh credentials and retry exactly once, while
non-401 OAuth failures and all API-key failures do not refresh. Reuse the
existing handler/authentication symbols and assert both refresh invocation
counts and the resulting request behavior.

In `@src/api/providers/kimi-code.ts`:
- Around line 59-69: Update KimiCodeProvider.prepareRequest and its
model-discovery state so a failed or empty getModels result is marked as
completed for the current provider lifecycle, preventing discovery from running
before every completion. Preserve the configured model ID and fallback metadata,
and only retry discovery through an explicit refresh or backoff mechanism if one
already exists.

In `@src/core/webview/ClineProvider.ts`:
- Around line 2537-2540: Wrap the async `kimiCodeOAuthState` aggregation block
in `getStateToPostToWebview()` with try/catch handling, covering both the
dynamic import and `kimiCodeOAuthManager.getState()` call. Match the
fallback/error-handling behavior used by the adjacent `kimiCodeIsAuthenticated`
block so a failure returns safe UI state without rejecting the overall
aggregation.

In `@src/integrations/kimi-code/oauth.ts`:
- Around line 233-258: Guard all shared-state mutations in startAuthorization
and its related finally cleanup (including the code around the pollingPromise
handling) with an ownership check that this.pollingController === controller. A
superseded authorization must not set state to "error" or clear the newer
operation’s pollingPromise; only the currently owned controller may update or
clean up shared authorization state.
- Around line 193-198: Update clearCredentials and the refresh flow around
refreshPromise/saveCredentials so sign-out invalidates any in-flight refresh
result before deleting stored credentials. Use a credential-generation counter
or abort mechanism, increment or cancel it in clearCredentials, and ensure stale
refresh completions cannot call saveCredentials or restore this.credentials;
preserve normal refresh behavior for the current generation.
- Around line 127-142: The Kimi Code authentication network calls need bounded
cancellation deadlines. In src/integrations/kimi-code/oauth.ts lines 127-142,
update refreshKimiCodeAccessToken and its postForm call to pass a bounded abort
signal so refreshPromise always settles; in
src/api/providers/fetchers/kimi-code.ts lines 27-29, add the same bounded abort
signal to the model-discovery request so chat requests can fall back promptly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4829e21f-2153-4085-9ea2-45a5b5e0eaff

📥 Commits

Reviewing files that changed from the base of the PR and between c322f3c and ff80fdf.

📒 Files selected for processing (31)
  • packages/types/src/__tests__/kimi-code.test.ts
  • packages/types/src/global-settings.ts
  • packages/types/src/model.ts
  • packages/types/src/provider-settings.ts
  • packages/types/src/providers/index.ts
  • packages/types/src/providers/kimi-code.ts
  • packages/types/src/vscode-extension-host.ts
  • src/api/index.ts
  • src/api/providers/__tests__/kimi-code.spec.ts
  • src/api/providers/fetchers/__tests__/kimi-code.spec.ts
  • src/api/providers/fetchers/kimi-code.ts
  • src/api/providers/fetchers/modelCache.ts
  • src/api/providers/index.ts
  • src/api/providers/kimi-code.ts
  • src/core/webview/ClineProvider.ts
  • src/core/webview/webviewMessageHandler.ts
  • src/extension.ts
  • src/integrations/kimi-code/__tests__/oauth.spec.ts
  • src/integrations/kimi-code/oauth.ts
  • src/shared/api.ts
  • src/shared/checkExistApiConfig.ts
  • webview-ui/src/components/settings/ApiOptions.tsx
  • webview-ui/src/components/settings/constants.ts
  • webview-ui/src/components/settings/providers/KimiCode.tsx
  • webview-ui/src/components/settings/providers/__tests__/KimiCode.spec.tsx
  • webview-ui/src/components/settings/providers/index.ts
  • webview-ui/src/components/settings/utils/providerModelConfig.ts
  • webview-ui/src/components/ui/hooks/useSelectedModel.ts
  • webview-ui/src/i18n/locales/en/settings.json
  • webview-ui/src/utils/__tests__/validate.spec.ts
  • webview-ui/src/utils/validate.ts

Comment thread src/api/providers/__tests__/kimi-code.spec.ts
Comment thread src/api/providers/kimi-code.ts
Comment thread src/core/webview/ClineProvider.ts
Comment thread src/integrations/kimi-code/oauth.ts
Comment thread src/integrations/kimi-code/oauth.ts
Comment thread src/integrations/kimi-code/oauth.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
webview-ui/src/i18n/locales/zh-CN/settings.json (1)

462-472: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Localize the Kimi Code UI strings to Simplified Chinese.

Consider translating these English fallback strings to improve the experience for Chinese users, especially since Moonshot/Kimi is primarily aimed at this audience.

🌐 Proposed translation
-		"kimiCode": {
-			"authMethod": "Authentication method",
-			"oauth": "Kimi Code subscription (OAuth)",
-			"apiKey": "Kimi Code API key",
-			"apiKeyLabel": "Kimi Code API Key",
-			"signIn": "Sign in to Kimi Code",
-			"signOut": "Sign out",
-			"authenticated": "Signed in to Kimi Code",
-			"deviceCodeHelp": "Enter this device code in the Kimi authorization page:",
-			"docs": "Kimi Code documentation"
-		},
+		"kimiCode": {
+			"authMethod": "身份验证方法",
+			"oauth": "Kimi Code 订阅 (OAuth)",
+			"apiKey": "Kimi Code API 密钥",
+			"apiKeyLabel": "Kimi Code API 密钥",
+			"signIn": "登录 Kimi Code",
+			"signOut": "登出",
+			"authenticated": "已登录 Kimi Code",
+			"deviceCodeHelp": "请在 Kimi 授权页面输入此设备代码:",
+			"docs": "Kimi Code 文档"
+		},
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@webview-ui/src/i18n/locales/zh-CN/settings.json` around lines 462 - 472,
Translate all English values in the kimiCode localization object to natural
Simplified Chinese, including authentication method, OAuth, API key,
sign-in/out, authenticated status, device-code help, and documentation labels.
Preserve the existing keys and JSON structure.
webview-ui/src/i18n/locales/zh-TW/settings.json (1)

489-499: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Localize the Kimi Code UI strings to Traditional Chinese.

Consider translating these English fallback strings to improve the experience for Traditional Chinese users.

🌐 Proposed translation
-		"kimiCode": {
-			"authMethod": "Authentication method",
-			"oauth": "Kimi Code subscription (OAuth)",
-			"apiKey": "Kimi Code API key",
-			"apiKeyLabel": "Kimi Code API Key",
-			"signIn": "Sign in to Kimi Code",
-			"signOut": "Sign out",
-			"authenticated": "Signed in to Kimi Code",
-			"deviceCodeHelp": "Enter this device code in the Kimi authorization page:",
-			"docs": "Kimi Code documentation"
-		},
+		"kimiCode": {
+			"authMethod": "驗證方式",
+			"oauth": "Kimi Code 訂閱 (OAuth)",
+			"apiKey": "Kimi Code API 金鑰",
+			"apiKeyLabel": "Kimi Code API 金鑰",
+			"signIn": "登入 Kimi Code",
+			"signOut": "登出",
+			"authenticated": "已登入 Kimi Code",
+			"deviceCodeHelp": "請在 Kimi 授權頁面輸入此裝置代碼:",
+			"docs": "Kimi Code 說明文件"
+		},
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@webview-ui/src/i18n/locales/zh-TW/settings.json` around lines 489 - 499,
Translate every English value in the kimiCode localization object to natural
Traditional Chinese, including authentication method, OAuth/API key labels,
sign-in/out states, device-code help, and documentation text; preserve all keys
and JSON structure unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@webview-ui/src/i18n/locales/de/settings.json`:
- Around line 462-472: Localize every English value in the kimiCode settings
block, including authMethod, oauth, apiKey, apiKeyLabel, signIn, signOut,
authenticated, deviceCodeHelp, and docs. Apply appropriate translations in
webview-ui/src/i18n/locales/de/settings.json#L462-L472,
es/settings.json#L462-L472, fr/settings.json#L462-L472,
hi/settings.json#L462-L472, id/settings.json#L462-L472,
it/settings.json#L462-L472, ja/settings.json#L462-L472,
ko/settings.json#L462-L472, and nl/settings.json#L462-L472, while preserving the
existing kimiCode keys and JSON structure.

---

Nitpick comments:
In `@webview-ui/src/i18n/locales/zh-CN/settings.json`:
- Around line 462-472: Translate all English values in the kimiCode localization
object to natural Simplified Chinese, including authentication method, OAuth,
API key, sign-in/out, authenticated status, device-code help, and documentation
labels. Preserve the existing keys and JSON structure.

In `@webview-ui/src/i18n/locales/zh-TW/settings.json`:
- Around line 489-499: Translate every English value in the kimiCode
localization object to natural Traditional Chinese, including authentication
method, OAuth/API key labels, sign-in/out states, device-code help, and
documentation text; preserve all keys and JSON structure unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f3268b3c-808b-465a-99fc-fb7658596249

📥 Commits

Reviewing files that changed from the base of the PR and between ff80fdf and 82c34c9.

📒 Files selected for processing (20)
  • src/api/providers/kimi-code.ts
  • src/core/webview/__tests__/ClineProvider.spec.ts
  • src/core/webview/__tests__/webviewMessageHandler.spec.ts
  • webview-ui/src/i18n/locales/ca/settings.json
  • webview-ui/src/i18n/locales/de/settings.json
  • webview-ui/src/i18n/locales/es/settings.json
  • webview-ui/src/i18n/locales/fr/settings.json
  • webview-ui/src/i18n/locales/hi/settings.json
  • webview-ui/src/i18n/locales/id/settings.json
  • webview-ui/src/i18n/locales/it/settings.json
  • webview-ui/src/i18n/locales/ja/settings.json
  • webview-ui/src/i18n/locales/ko/settings.json
  • webview-ui/src/i18n/locales/nl/settings.json
  • webview-ui/src/i18n/locales/pl/settings.json
  • webview-ui/src/i18n/locales/pt-BR/settings.json
  • webview-ui/src/i18n/locales/ru/settings.json
  • webview-ui/src/i18n/locales/tr/settings.json
  • webview-ui/src/i18n/locales/vi/settings.json
  • webview-ui/src/i18n/locales/zh-CN/settings.json
  • webview-ui/src/i18n/locales/zh-TW/settings.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/api/providers/kimi-code.ts

Comment thread webview-ui/src/i18n/locales/de/settings.json

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/api/providers/__tests__/kimi-code.spec.ts`:
- Around line 105-140: Extend the tests in the KimiCodeHandler suite to cover
completePrompt() retrying after a 401 under OAuth, including a successful second
response and verification that mockForceRefreshAccessToken is called. Also add
an OAuth createMessage() case for a non-401 failure such as 500, asserting the
request rejects and mockForceRefreshAccessToken is not called.

In `@src/core/webview/__tests__/webviewMessageHandler.spec.ts`:
- Around line 1474-1477: Add vi.resetModules() to the beforeEach blocks for both
kimiCodeSignIn and kimiCodeSignOut in
src/core/webview/__tests__/webviewMessageHandler.spec.ts at lines 1474-1477 and
1583-1586, alongside vi.clearAllMocks(), so each test dynamically imports its
newly configured OAuth mock.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ff97bda0-13eb-4852-985c-7223a525ac01

📥 Commits

Reviewing files that changed from the base of the PR and between 82c34c9 and 2a2e4f3.

📒 Files selected for processing (6)
  • src/api/providers/__tests__/kimi-code.spec.ts
  • src/api/providers/fetchers/__tests__/kimi-code.spec.ts
  • src/core/webview/__tests__/webviewMessageHandler.spec.ts
  • src/integrations/kimi-code/__tests__/oauth.spec.ts
  • src/shared/__tests__/checkExistApiConfig.spec.ts
  • webview-ui/src/utils/__tests__/validate.spec.ts

Comment thread src/api/providers/__tests__/kimi-code.spec.ts
Comment thread src/core/webview/__tests__/webviewMessageHandler.spec.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/api/providers/openai.ts (1)

299-337: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Remove the redundant outer try-catch to prevent double-wrapping errors.

The outer try-catch block is redundant and causes API errors to be wrapped twice. The inner try-catch block properly intercepts API failures and throws handleOpenAIError. That handler already prefixes the message with completion error and reliably preserves status, errorDetails, and code fields.

Because the outer block catches this newly formatted error and wraps it again, the UI will display duplicated prefixes (e.g., OpenAI completion error: OpenAI completion error: ...). Removing the outer try-catch altogether allows the correctly formatted error from handleOpenAIError to propagate cleanly.

♻️ Proposed fix to remove the outer try-catch
 	async completePrompt(prompt: string, options?: CompletePromptOptions): Promise<string> {
-		try {
-			const isAzureAiInference = this._isAzureAiInference(this.options.openAiBaseUrl)
-			const model = this.getModel()
-			const modelInfo = model.info
-
-			const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = {
-				model: model.id,
-				messages: [{ role: "user", content: prompt }],
-			}
-
-			// Add max_tokens if needed
-			this.addMaxTokensIfNeeded(requestOptions, modelInfo)
-
-			let response
-			try {
-				response = await this.client.chat.completions.create(
-					requestOptions,
-					isAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {},
-				)
-			} catch (error) {
-				throw handleOpenAIError(error, this.providerName)
-			}
-
-			return response.choices?.[0]?.message.content || ""
-		} catch (error) {
-			if (error instanceof Error) {
-				const wrapped = new Error(`${this.providerName} completion error: ${error.message}`, { cause: error })
-				const source = error as Error & { status?: number; errorDetails?: unknown; code?: unknown }
-				const target = wrapped as Error & { status?: number; errorDetails?: unknown; code?: unknown }
-				if (source.status !== undefined) target.status = source.status
-				if (source.errorDetails !== undefined) target.errorDetails = source.errorDetails
-				if (source.code !== undefined) target.code = source.code
-				throw wrapped
-			}
-
-			throw error
-		}
+		const isAzureAiInference = this._isAzureAiInference(this.options.openAiBaseUrl)
+		const model = this.getModel()
+		const modelInfo = model.info
+
+		const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = {
+			model: model.id,
+			messages: [{ role: "user", content: prompt }],
+		}
+
+		// Add max_tokens if needed
+		this.addMaxTokensIfNeeded(requestOptions, modelInfo)
+
+		let response
+		try {
+			response = await this.client.chat.completions.create(
+				requestOptions,
+				isAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {},
+			)
+		} catch (error) {
+			throw handleOpenAIError(error, this.providerName)
+		}
+
+		return response.choices?.[0]?.message.content || ""
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/api/providers/openai.ts` around lines 299 - 337, Remove the outer
try-catch and its wrapping logic from completePrompt, while retaining the inner
catch that passes API failures to handleOpenAIError. Let the formatted error
propagate directly, preserving the existing request construction, response
handling, and Azure inference behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/api/providers/openai.ts`:
- Around line 299-337: Remove the outer try-catch and its wrapping logic from
completePrompt, while retaining the inner catch that passes API failures to
handleOpenAIError. Let the formatted error propagate directly, preserving the
existing request construction, response handling, and Azure inference behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 45463726-2032-4822-91ac-6d1dd82d0835

📥 Commits

Reviewing files that changed from the base of the PR and between 2a2e4f3 and 032ac70.

📒 Files selected for processing (8)
  • src/api/providers/__tests__/kimi-code.spec.ts
  • src/api/providers/__tests__/openai.spec.ts
  • src/api/providers/fetchers/__tests__/kimi-code.spec.ts
  • src/api/providers/fetchers/kimi-code.ts
  • src/api/providers/kimi-code.ts
  • src/api/providers/openai.ts
  • src/integrations/kimi-code/__tests__/oauth.spec.ts
  • src/integrations/kimi-code/oauth.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/api/providers/fetchers/kimi-code.ts
  • src/api/providers/fetchers/tests/kimi-code.spec.ts
  • src/api/providers/tests/kimi-code.spec.ts
  • src/api/providers/kimi-code.ts
  • src/integrations/kimi-code/oauth.ts

@github-actions github-actions Bot added awaiting-review PR changes are ready and waiting for maintainer re-review has-conflicts PR has merge conflicts with the base branch and removed awaiting-review PR changes are ready and waiting for maintainer re-review has-conflicts PR has merge conflicts with the base branch labels Jul 19, 2026
@zoomote

zoomote Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Done — merge conflicts resolved and all 5 outstanding review threads addressed in ccf1597 (plus merge commit 891c04f).

Merge conflicts with main (4 files, all additive — combined both sides):

  • packages/types/src/provider-settings.ts — adopted main's canonical providerIdentifiers registry and registered kimiCode: "kimi-code" there (also added to provider-identifiers.ts and its test expectations)
  • src/shared/checkExistApiConfig.ts + spec — kept both the Kimi Code OAuth setup-gate special case and main's Zoo Gateway session-auth check
  • webview-ui/src/utils/__tests__/validate.spec.ts — kept both kimi-code and moonshot allow-list entries

Review threads (all resolved):

  • ClineProvider.ts — wrapped kimiCodeOAuthState aggregation in try/catch, matching the adjacent kimiCodeIsAuthenticated fallback
  • OAuth/model-discovery timeouts — already bounded in the current branch (30s in postForm, 10s in getKimiCodeModels); replied on the thread with the details
  • Retry-contract tests — added the missing OAuth non-401 (500) no-retry createMessage case; the completePrompt 401 retry case already existed
  • webviewMessageHandler.spec.ts — added vi.resetModules() to the kimiCodeSignIn/kimiCodeSignOut beforeEach blocks
  • Locales — translated the kimiCode settings strings in all 9 non-English locales (de, es, fr, hi, id, it, ja, ko, nl)

Validation: full monorepo pnpm test passes (423 files, 6,912 tests). Visual proof not applicable — the changes are internal error handling, tests, and extension-webview locale strings, and the VS Code extension UI has no browser-reachable surface in this environment. The PR title/body were also rebuilt from the final diff using the repo's PR template.

- Wrap kimiCodeOAuthState aggregation in try/catch in ClineProvider
- Add non-401 OAuth no-retry test for createMessage
- Add vi.resetModules() to kimiCode sign-in/out spec setup
- Localize kimiCode settings strings in 9 locales
- Merge origin/main: adopt canonical providerIdentifiers registry,
  keep both kimi-code and zoo-gateway setup-gate checks
@github-actions github-actions Bot removed the has-conflicts PR has merge conflicts with the base branch label Jul 24, 2026
@zoomote zoomote Bot changed the title feat(api): add Kimi Code provider with OAuth device flow [Feat] Add Kimi Code provider with OAuth device flow Jul 24, 2026
@github-actions github-actions Bot added the awaiting-review PR changes are ready and waiting for maintainer re-review label Jul 24, 2026
@navedmerchant
navedmerchant added this pull request to the merge queue Jul 24, 2026
Merged via the queue into main with commit 78c1410 Jul 24, 2026
15 checks passed
@navedmerchant
navedmerchant deleted the feat/kimi-code branch July 24, 2026 14:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting-review PR changes are ready and waiting for maintainer re-review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants