Repository navigation
[Feat] Add Kimi Code provider with OAuth device flow - #945
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds Kimi Code as a provider with API-key and OAuth authentication, model discovery, token refresh, extension messaging, configuration validation, and a dedicated settings UI. ChangesKimi Code provider
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
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (31)
packages/types/src/__tests__/kimi-code.test.tspackages/types/src/global-settings.tspackages/types/src/model.tspackages/types/src/provider-settings.tspackages/types/src/providers/index.tspackages/types/src/providers/kimi-code.tspackages/types/src/vscode-extension-host.tssrc/api/index.tssrc/api/providers/__tests__/kimi-code.spec.tssrc/api/providers/fetchers/__tests__/kimi-code.spec.tssrc/api/providers/fetchers/kimi-code.tssrc/api/providers/fetchers/modelCache.tssrc/api/providers/index.tssrc/api/providers/kimi-code.tssrc/core/webview/ClineProvider.tssrc/core/webview/webviewMessageHandler.tssrc/extension.tssrc/integrations/kimi-code/__tests__/oauth.spec.tssrc/integrations/kimi-code/oauth.tssrc/shared/api.tssrc/shared/checkExistApiConfig.tswebview-ui/src/components/settings/ApiOptions.tsxwebview-ui/src/components/settings/constants.tswebview-ui/src/components/settings/providers/KimiCode.tsxwebview-ui/src/components/settings/providers/__tests__/KimiCode.spec.tsxwebview-ui/src/components/settings/providers/index.tswebview-ui/src/components/settings/utils/providerModelConfig.tswebview-ui/src/components/ui/hooks/useSelectedModel.tswebview-ui/src/i18n/locales/en/settings.jsonwebview-ui/src/utils/__tests__/validate.spec.tswebview-ui/src/utils/validate.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
webview-ui/src/i18n/locales/zh-CN/settings.json (1)
462-472: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLocalize 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 winLocalize 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
📒 Files selected for processing (20)
src/api/providers/kimi-code.tssrc/core/webview/__tests__/ClineProvider.spec.tssrc/core/webview/__tests__/webviewMessageHandler.spec.tswebview-ui/src/i18n/locales/ca/settings.jsonwebview-ui/src/i18n/locales/de/settings.jsonwebview-ui/src/i18n/locales/es/settings.jsonwebview-ui/src/i18n/locales/fr/settings.jsonwebview-ui/src/i18n/locales/hi/settings.jsonwebview-ui/src/i18n/locales/id/settings.jsonwebview-ui/src/i18n/locales/it/settings.jsonwebview-ui/src/i18n/locales/ja/settings.jsonwebview-ui/src/i18n/locales/ko/settings.jsonwebview-ui/src/i18n/locales/nl/settings.jsonwebview-ui/src/i18n/locales/pl/settings.jsonwebview-ui/src/i18n/locales/pt-BR/settings.jsonwebview-ui/src/i18n/locales/ru/settings.jsonwebview-ui/src/i18n/locales/tr/settings.jsonwebview-ui/src/i18n/locales/vi/settings.jsonwebview-ui/src/i18n/locales/zh-CN/settings.jsonwebview-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
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
src/api/providers/__tests__/kimi-code.spec.tssrc/api/providers/fetchers/__tests__/kimi-code.spec.tssrc/core/webview/__tests__/webviewMessageHandler.spec.tssrc/integrations/kimi-code/__tests__/oauth.spec.tssrc/shared/__tests__/checkExistApiConfig.spec.tswebview-ui/src/utils/__tests__/validate.spec.ts
There was a problem hiding this comment.
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 winRemove the redundant outer
try-catchto prevent double-wrapping errors.The outer
try-catchblock is redundant and causes API errors to be wrapped twice. The innertry-catchblock properly intercepts API failures and throwshandleOpenAIError. That handler already prefixes the message withcompletion errorand reliably preservesstatus,errorDetails, andcodefields.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 outertry-catchaltogether allows the correctly formatted error fromhandleOpenAIErrorto 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
📒 Files selected for processing (8)
src/api/providers/__tests__/kimi-code.spec.tssrc/api/providers/__tests__/openai.spec.tssrc/api/providers/fetchers/__tests__/kimi-code.spec.tssrc/api/providers/fetchers/kimi-code.tssrc/api/providers/kimi-code.tssrc/api/providers/openai.tssrc/integrations/kimi-code/__tests__/oauth.spec.tssrc/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
|
Done — merge conflicts resolved and all 5 outstanding review threads addressed in Merge conflicts with
Review threads (all resolved):
Validation: full monorepo |
- 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
Reviewer-facing facts, verbatim from the review comment (thread
4771823159, src/integrations/kimi-code/__tests__/oauth.spec.ts line
1013): severity Minor, category Data Integrity & Integration, quick win,
and the comment carries no suggestion block. The headline reads "Test
sign-out with the host's secret operation order." and the body: "The
double lets sign-out delete the key before the earlier store finishes.
VS Code 1.100.0 queues both operations. The rollback read then queues
behind the sign-out delete, sees no value, and needs no second delete.
This assertion rejects that [redacted] outcome." plus the advice "Queue
the delete behind the parked store. Keep the assertions on the cancelled
sign-in, idle state, and absent secret." The word the stored JSON
redacts in that last sentence names the single-delete outcome the row
previously excluded by expect(deletes.length).toBe(2); the code-side
literal is quoted here rather than guessed from the redacted text.
The host fact, measured rather than asserted from the comment. VS Code
1.100.0 mainThreadSecretState.ts routes all three secret operations of
one extension through a single sequencer: _sequencer.queue(extensionId,
... ) at lines 44 (store), 56 (delete) and 67 (get) of that file, in the
order the extension issued them. The local copy of the tagged file is
kept under scratch-1552z/ outside the repository; it is not vendored
into the PR.
Measured state before this commit. The row ("a sign-out that lands while
a sign-in is storing rejects that write instead of installing it", :933)
parked the store on a gate (:952-960) but let delete run synchronously
(:961-964), and left get on the shared createContext double, which
answers every call the moment it is made (:19). So the sign-out delete
executed while the write was still parked, the write then installed
itself, the rollback read found its own pair still there, and a second
delete followed: two deletes, which is the number the row pinned. Under
the host's queue nothing runs in that order.
Fix, row-local. The diff is two hunks, @@ -948,20 +948,41 @@ and @@
-1009,8 +1030,10 @@, 33 added and 10 removed, all inside :933-1015. The
first hunk is setup only: store, delete and get are pushed onto one FIFO
chain that mirrors the host sequencer, the store task still parks on the
same gate inside its queued step, and the delete and get tasks run
through the same chain, so a delete can no longer overtake the write
ahead of it and a read queued behind a delete sees what that delete left
behind. The shared createContext helper (:12-25, upstream 78c1410 from
PR Zoo-Code-Org#945) is untouched and keeps answering immediately for every other
row. The second hunk is one assertion: the delete count moves from 2 to
1 with the reason written next to it, because the stale write's rollback
now reads through the same queue behind the sign-out delete, finds no
value, and issues no second delete. The assertions the reviewer asked to
keep are byte-identical: the rejection with "Kimi Code authorization was
cancelled", manager["credentials"] null, getState() idle, values.has(key)
false, and clearFenceCount 0.
Ownership. git blame on the row region attributes the store gate, the
delete double and the count assertion to 4e1d15f ("fix(integrations):
count sign-outs so the kimi refresh fence cannot open...") and the
surrounding rows to 27e3e8e; both are commits of this PR chain
(9f8e483..d6cce79), so this is chain-authored test code, and only
the two hunks above move.
Evidence. No production behavior changed, so the row cannot be made red
against unmodified production; the red-first equivalent is a control
inside the row. With everything else as landed and only the delete double
reverted to its synchronous form, the row fails, verbatim AssertionError:
expected 2 to be 1 // Object.is equality, over "Tests 1 failed | 52
passed (53)". The count is therefore pinned to the host order the row now
models rather than to whatever the doubles happened to produce.
Production mutants on the write path, each run against this row and
against the PR-head row: MK, the stale write accepted as owned (return
false changed to true after the ownership loss, blob 23c89d792b41):
"3 failed | 50 passed (53)" on both sides; the target row is killed with
the verbatim "promise resolved \"{ type: 'kimi-code', ... (4) }\" instead
of rejecting", and the two sibling rollback rows die with it. MH, the
rollback deleting against a secret the read found empty (blob
2ea4b9906980): "53 passed (53)" on both sides - it survives, because an
operation queued behind the ones already drained has not run when the row
asserts; that is recorded under Not closed rather than hidden. No run
reported a test timeout (0 timeout lines in every run above).
Suites, both sides from src with vitest.config.ts and the same filter on
each side: integrations/kimi-code/__tests__/oauth.spec.ts,
api/providers/__tests__/kimi-code.spec.ts and
api/providers/__tests__/kimi-code.oauth-cancellation.spec.ts. PR-head
extraction: "Tests 86 passed (86)". Landed: "Tests 87 passed (87)".
Both exit 0, 0 FAIL rows, 0 teardown or timeout lines, 14 s each, and the
pair was run twice with the same numbers. The one-test difference is the
row commit 4773886041 added to kimi-code.oauth-cancellation.spec.ts in
this worktree and absent from the extraction; this commit adds no row.
oauth.spec.ts alone: 53 passed (53), exit 0, 0 timeouts.
Gates, and two incidents. First incident: eslint rejected an intermediate
version of this file with 1795:7 error 'written' is assigned a value but
never used, which belongs to the sibling rollback row earlier in the file
(commit 4771823190) and is answered there by asserting the captured write
in the shape that row already used. Second incident: while measuring MK
the production file was left on a mutant blob for one intermediate run,
which reported "24 failed | 29 passed (53)"; the mutant was cleared with
git checkout -- src/integrations/kimi-code/oauth.ts, the file was verified
byte-equal to the committed blob 3b29cae, and MK was re-measured
from a clean pair to the 3-failed figure quoted above, so the 24-failure
run is discarded evidence. Final: prettier --check 0 problems (its first
--check flagged this file and --write touched only lines these two hunks
added - HEAD-side the same file passes prettier --check); eslint
--max-warnings=0 0 problems; eslint --prune-suppressions --max-warnings=0
leaves the parsed eslint-suppressions.json count map at 260 entries with
0 deltas for every file, and because the prune re-serializes the file
(sha256 222a8376fc64 against the HEAD serialization fa6a46a24512) that
file is restored to the HEAD serialization and verified by hash; the
judgement is the count map.
Gate calibers, with this PR's own scripts/stryker-diff.mjs helpers.
Cell-local: 43 changed lines in src/integrations/kimi-code/__tests__/
oauth.spec.ts, none of them routed - EXCLUDED_PATH_SEGMENTS
(stryker-diff.mjs:85) drops every /__tests__/ path - so this cell charges
0 changed executable lines and 0 mutants. Cumulative: unchanged from the
previous commit at base=9f8e4836680277425d36b47866b65b1b78b8b55c +
package=extension + changedExecutableLines=512 (511 at PR head, already
over the 500 cap through buildManifest's own error; the +1 is commit
4773886041's line in src/api/providers/utils/abort-signal.ts).
Not closed by this commit:
- The row proves that no second delete had run when it asserts, not that
the manager never issues one later; MH survived for exactly this reason.
- Only this row models the host queue. The createContext double (:12-25,
upstream Zoo-Code-Org#945) still answers immediately for every other row, so the
ordering is asserted for a sign-out against a parked store and nowhere
else in this file.
- The queue models one extension host. A second host sharing the same
secret sits outside it, which is the residual window the rollback
comment at oauth.ts:324-332 records and no row asserts.
[cr 4771823159]
Reviewer-facing facts, verbatim from the review comment (thread 4771823213, src/integrations/kimi-code/oauth.ts line 448, with the fix prompt quoting line 435 of an older snapshot): severity Minor, category Functional Correctness, quick win, and the comment carries no suggestion block. The headline reads "Preserve the OAuth deadline error through request preparation." and the body: "If the response body passes the new deadline, this handler returns null. The provider then reports Not authenticated with Kimi Code. Sign in from provider settings. Stored credentials remain in place. Before this change, the same body could finish because the timer stopped at headers." The advice: "Keep the deadline. Give its error a distinct type and propagate it to the provider. Keep the sign-in message for missing credentials. Check the stalled-body case through the provider as well as the direct refresh helper." Measured state before this commit. The refresh verdict handler answered null for every failure of the shared POST, and its only re-raise was the abort guard, so a deadline rejection was laundered into the same null answer as any other failure and the provider turned that null into its sign-in error. A scratch probe on the PR-head shape (stalled body, clock advanced past the 30 s deadline) recorded the caller receiving name "Error" with message "Not authenticated with Kimi Code. Sign in from provider settings.", cause unset, while the POST signal was aborted and the stored pair was still in secrets: the reviewer's description reproduced, and nothing on this path distinguished a stalled POST from a signed-out session. Ownership: git blame puts the replaced deadline line (HEAD:102-103) and the guard's neighbouring lines here at 78c1410 ([Feat] Add Kimi Code provider with OAuth device flow (Zoo-Code-Org#945), chain external) and at 8a7a4aa / 4e1d15f / 49f57b0 (chain internal); the guard block itself only gains lines, no existing line of it is rewritten. Fix. src/integrations/kimi-code/oauth.ts: a module-private KimiCodeOAuthTimeoutError (lines 81-87, not exported, so no new API surface) whose name is "TimeoutError" - the timeout name this repository already treats as a timeout rather than a cancellation (abort-signal.ts classifies a signal whose reason is named TimeoutError, and openai.ts:700 reads the same name) - and whose message is byte-identical to the string the deadline already raised, so nothing that prints it sees new text and the direct helper contract row that pins that string stays green. The deadline now aborts with that error (line 115, one line replacing one line) and the verdict handler re-raises it instead of answering null (line 460, with lines 457-459 as its reason). The provider is not changed: kimi-code.ts keeps no mapping for it, so the typed error reaches the caller raw, and the sign-in message for genuinely missing credentials is untouched (the "no token available" row at kimi-code.spec.ts:119-128 still asserts it and still passes). Tests. src/integrations/kimi-code/__tests__/oauth.spec.ts: the manager deadline row (:156-183) now expects the rejection instead of the null answer - its single assertion line was replaced one-for-one by "await rejection", and the assertion itself is attached before the clock moves (:172-178), which is what keeps the rejection handled without a swallowing catch. Its three load-bearing assertions (POST signal aborted, pair still stored, timer count zero) are byte-identical, the Zoo-Code-Org#945 createContext helper is untouched, and no other row moved. A new manager row (:186-221) pins the type by name, the exact message, that the name is not the cancellation name, that no cancellation cause is attached, that the rejection is the deadline's own object rather than a wrapper, and that the stored pair and the timer count survive it. A new provider row (kimi-code.spec.ts:130-149) pins the other half of the advice: with the manager rejecting the typed deadline, the provider hands the same object to the caller - not its sign-in error, not an AbortError - and issues no completion request and no second refresh. The direct refresh helper contract row (:223-256) is unchanged and its message pin at :252 still passes, which is what forced the message to stay byte-identical. Red-first. Against pristine PR-head production the two changed rows fail verbatim "AssertionError: promise resolved \"null\" instead of rejecting" and "Error: Expected the operation to reject", reported as "Tests 2 failed | 52 passed (54)" in that file; against this commit's production the same file is "Tests 54 passed (54)" (was 53 rows, now 54) and kimi-code.spec.ts is "Tests 33 passed (33)" (was 32), exit 0 in both, with 0 unhandled-rejection blocks and 0 PromiseRejectionHandledWarning lines. Row shape, measured before choosing, because flipping that row's promise direction initially produced an unhandled rejection (vitest reported "Errors 1 error" and exit 1 even with all 54 tests passing, and a run without any early handler reproduced that: 54 passed, exit 1, 1 error, 1 warning, 13.65 s and 13.91 s). Three shapes were measured against the same candidate production, three runs each where it mattered: - attach-first (shipped): 3 runs, all "Tests 54 passed (54)", exit 0, no Errors line, 0 warnings, 13.65 s / 13.69 s / 13.64 s. - early "void tokenPromise.catch(() => {})": 3 runs, all 54 passed, exit 0, no Errors line, 0 warnings, 13.82 s / 13.79 s / 13.61 s, but its handler swallows the rejection, which hides the real reason if the row ever fails for another cause. - no early handler: green tests, red run (above). The attach-first shape was chosen because it holds the rejection with the assertion instead of swallowing it. One honest asymmetry: in the red state attach-first reports "Errors 2 errors" where the swallowing catch reports 1, because the failing assertion's own rejection surfaces before it is awaited; in the green state attach-first reports no Errors line. No run showed a test timeout or an exit-code swing. Mutants, all on the shipped shape, oauth.ts restored byte-for-byte after each (blob fa862de verified every time, and the final disk file is byte-equal to the committed blob): - tag off (deadline aborts with a plain Error of the same text): "2 failed | 52 passed (54)", killed verbatim "promise resolved \"null\" instead of rejecting" and "Expected the operation to reject". - tagged but the guard not re-raising: "2 failed | 52 passed (54)", the same two killers verbatim. - name changed to "AbortError": "2 failed | 52 passed (54)", killed verbatim "expected AbortError: Kimi Code OAuth request timed... to match object { name: 'TimeoutError', ..." and "the deadline keeps the repository timeout name: expected 'AbortError' to be 'TimeoutError' // Object.is equality". openai.ts:700 was not exercised by these runs: this file never builds an OpenAI request. - one-char message change ("timed ou"): "3 failed | 51 passed (54)", killing the manager row, the new row and the direct helper contract row verbatim "expected 'Kimi Code OAuth request timed ou' to be 'Kimi Code OAuth request timed out' // Object.is equality": the message text is load-bearing in three rows, which is why it was not reworded. - comment-only control (one comment line added inside the guard block): "54 passed (54)", exit 0 - it survives, so the kills above track behaviour and not line count. - provider-side mapping mutant (kimi-code.ts resolving the token through ".catch(() => null)", i.e. mapping every token failure to the sign-in error): kimi-code.spec.ts "1 failed | 32 passed (33)", killed verbatim "the provider does not replace the deadline with its own error: expected Error: Not authenticated with Kimi Code. ... to be TimeoutError: Kimi Code OAuth request tim... // Object.is equality"; kimi-code.ts was then restored to its HEAD blob. Suites, both sides from src with vitest.config.ts over the 17 abort-shaped spec files (utils abort-signal, error-handler, request-timeout; providers kimi-code, kimi-code.oauth-cancellation, openai, openai.cancellation, the three base-openai-compatible-provider specs, zai, gemini, mistral, lm-studio, lite-llm, qwen-code; fetchers/kimi-code): the PR-head extraction gave "Tests 1404 passed (1404)" over 17 files and this commit's tree "Tests 1408 passed (1408)" over 17 files, exit 0 both, 0 FAIL rows, 0 unhandled blocks, 10.37 s and 9.94 s. The +1 is this commit's provider row; oauth.spec.ts is not in that set, so the manager rows are counted only in their own file above. The extraction's copies of the three touched files were verified blob-identical to PR head before and after the run, so the difference is this commit and nothing else. Gates. prettier --check over the three touched files: 0 problems (the flipped assertion is written in prettier's own wrapped form, and it is one assertion, not several). eslint --max-warnings=0 over the same three: 0 problems. eslint --prune-suppressions --max-warnings=0: the parsed eslint-suppressions.json count map has 260 entries before and after with 0 deltas; the prune re-serializes the file (sha256 222a8376fc64 against the HEAD serialization fa6a46a24512), so it is restored to the HEAD serialization and verified byte-equal to git show HEAD:... Gate calibers, measured with this PR's own scripts/stryker-diff.mjs helpers (packageForPath, parseChangedLines, executableChangedLines, toRanges) over --unified=0 diffs. Cell-local: 18 changed lines, 8 of them executable in the mutation-tested package, routed as integrations/kimi-code/oauth.ts:81-81, :83-84, :115-115, :457-460 (the last range includes the three comment lines above the re-raise; the helper counts // lines but not the JSDoc continuation lines of the class block). Both spec files are routed out (/__tests__/), so they charge nothing. Cumulative: base=9f8e4836680277425d36b47866b65b1b78b8b55c + package=extension + changedExecutableLines=520 over 9 routed files (oauth.ts 203, openai.ts 140, base-openai-compatible-provider.ts 95, kimi-code.ts 29, zai.ts 28, error-handler.ts 15, fetchers/kimi-code.ts 6, abort-signal.ts 3, request-timeout.ts 1). The same measurement over HEAD alone reproduces 512 - which is also the number the gate itself prints when it throws - so the +8 is entirely this commit's oauth.ts lines and the cap (500) was already exceeded before it. Not closed by this commit: - The reviewer's stalled-body case is covered at the manager boundary and at the provider boundary separately; no single test drives a stalled body through the real manager into the provider. - Every other refresh failure (network error, non-2xx, malformed body) still answers null and still reaches the caller as the sign-in error. Only the deadline was given a type, which is what the finding asked for; the rest is a wider design question. - The sign-in failure toast interpolates the error message, so a stalled refresh now reads as the timeout text in the UI; that surface is not covered by a test here. - The provider deliberately does not map this error onto the request-timeout.ts contract (createTimeoutError names the provider and phase), so the message keeps the OAuth wording rather than "The Kimi Code ... timed out". [cr 4771823213]
…1311 split u0) The shared abort, timeout and error helpers landed with two required checks red: compile (eslint) and knip. This commit clears both without re-inflating suppressions, and adds the test that the guard was missing. compile: ESLint 9.39.5 count-based suppressions are all-or-nothing. In suppressions-service.js:171 a file is suppressed only while violationsCount <= suppressionsCount, and :177 rewrites the remainder only when violationsCount < suppressionsCount, so a file that is over its count reports every violation rather than the excess. The previous commit lowered base-openai-compatible-provider.ts from 6 to 5 while the file still held 6 assertions, and deleted the kimi-code.spec.ts entry while that file still held 1, which turned all 7 into reported errors. The fix retypes only what costs nothing. modelInfo goes from any to ModelInfo: the type is already imported in this file and calculateApiCostOpenAI in shared/cost.ts is its only consumer, so the assertion disappears without new machinery and the file drops to exactly its remaining count of 5. The kimi mock reaches the handler's protected client by bracket access, with the seam narrowed to the one create call it replaces - the shape anthropic-vertex.spec.ts:277 and :581 already use. Bracket access alone was not enough: it produced a fresh TS2739 on the ChatCompletionMessage mock literal, so the seam type is load-bearing and not decoration. Its suppression entry stays deleted because the file now asserts nothing, so a count of zero is the honest count rather than an allowance. The other five assertions stay suppressed on purpose: they sit on lines the suite never executes. Coverage over the 18 provider and api specs reports zero hits for both thinking assignments (lines 103 and 225) and for both base_resp throws (lines 136 and 234). Retyping an unexecuted line only moves it into the mutation cell, where no existing test could kill a mutant, and the file is upstream-owned (blame 6cfa82f, #11462) rather than part of this unit, as is the mock's owner (78c1410, Zoo-Code-Org#945). Type-checking adds nothing here either way: tsc over src reports the same diagnostics before and after this change. knip: handleOpenAIRequestError has no production importer in this unit - only error-handler.spec.ts imports it, and the request sites arrive with the later splits - so knip --production reports it while dev knip does not, which is the difference between the two runs rather than a finding about the code being wrong. Marked @internal with the reason: an intentional direct-test seam, the exception docs/development-quality-checks.md sanctions and abort-signal.ts:254 already uses in this same directory. The new row is coverage-closing, not a red-first repro: the status-first guard already behaved correctly, but no row reached it because none of the abort-awareness inputs carries a numeric status, so its early return had nothing executing it. It is not free-standing either: deleting the guard fails exactly this row - "expected 'AbortError' to be 'Error'" - while the other 49 rows keep passing. Suppression debt moves down, and the baseline is the merge-base dd30249, which is what AGENTS.md states the rule against - not the PR head: 261 entries and 2844 suppressed occurrences there, 260 and 2842 here. The provider entry stays at 5 and the kimi entry stays gone, so a prune run leaves the count map unchanged and only reflows indentation. Cost against that same base, on the mutation gate's own measure: this cell reports 19 changed executable lines against a cap of 500, one more than the 18 the previous commit measured, and that one line is the retyped signature. Not closed by this commit: - the five remaining provider assertions, which are worth typing only once tests execute the thinking and base_resp paths, and only next to the splits that make them live code - production importers for handleOpenAIRequestError, which arrive with split/1311-u1-openai-family and its siblings - the whole-file typed removal for the provider, sketched during this investigation: it clears all 5 remaining assertions but raises the cell from 18 to 33 changed executable lines, so it should land after the two unexecuted paths have tests of their own
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 ofmoonshotApiKey).Key implementation details:
auth.kimi.comwith the official public client ID17e5f671-d194-4dfb-9706-5516cb48c098. OAuth credentials live only in VS Code SecretStorage (global keykimi-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.kimiCodeApiKeypath following ordinary provider-secret persistence (SECRET_STATE_KEYS) for users who prefer API-key auth.https://api.kimi.com/coding/v1with authenticated dynamic model discovery, official metadata mapping, preservation of unknown configured model IDs, and thekimi-for-codingfallback 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.low/high/max, defaultmax) matching the Kimi K3reasoning_effortAPI, rendered through the shared Model Reasoning Effort dropdown; unsupported persisted efforts (e.g.mediumfrom another provider) fall back to the model default.getStateToPostToWebview()is fault-tolerant: a failure in the dynamic import or state read returns safe defaults instead of breaking UI state synchronization.Reviewer notes: the branch was recently merged with
mainand adopted the canonicalproviderIdentifiersregistry (provider-identifiers.ts), withkimiCoderegistered there;checkExistApiConfigkeeps 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.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 forcreateMessageandcompletePrompt, 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
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
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.