diff --git a/packages/vscode/src/quotaProviders.ts b/packages/vscode/src/quotaProviders.ts index 807d8ace..d3de2e8d 100644 --- a/packages/vscode/src/quotaProviders.ts +++ b/packages/vscode/src/quotaProviders.ts @@ -1137,6 +1137,24 @@ const fetchCopilotAddonQuota = async (): Promise => { } }; +// Kimi's weekly `usage` block reports `used`; its rate-limit `limits[].detail` +// blocks report `remaining` instead. Neither field is guaranteed present, so +// derive usedPercent from whichever one the API actually returned. +const computeKimiUsedPercent = ( + total: number | null, + used: number | null, + remaining: number | null, +): number | null => { + if (!total) return null; + if (used !== null) { + return Math.max(0, Math.min(100, (used / total) * 100)); + } + if (remaining !== null) { + return Math.max(0, Math.min(100, 100 - (remaining / total) * 100)); + } + return null; +}; + const fetchKimiQuota = async (): Promise => { const auth = readAuthFile(); const entry = normalizeAuthEntry(getAuthEntry(auth, ['kimi-for-coding', 'kimi'])) as Record | null; @@ -1176,10 +1194,9 @@ const fetchKimiQuota = async (): Promise => { const usage = payload.usage as Record | undefined; if (usage) { const limit = toNumber(usage.limit); + const used = toNumber(usage.used); const remaining = toNumber(usage.remaining); - const usedPercent = limit && remaining !== null - ? Math.max(0, Math.min(100, 100 - (remaining / limit) * 100)) - : null; + const usedPercent = computeKimiUsedPercent(limit, used, remaining); windows.weekly = toUsageWindow({ usedPercent, windowSeconds: null, @@ -1195,10 +1212,9 @@ const fetchKimiQuota = async (): Promise => { const windowSeconds = durationToSeconds(window?.duration as number | undefined, window?.timeUnit as string | undefined); const label = windowSeconds === 5 * 60 * 60 ? `Rate Limit (${rawLabel})` : rawLabel; const total = toNumber(detail?.limit); + const used = toNumber(detail?.used); const remaining = toNumber(detail?.remaining); - const usedPercent = total && remaining !== null - ? Math.max(0, Math.min(100, 100 - (remaining / total) * 100)) - : null; + const usedPercent = computeKimiUsedPercent(total, used, remaining); windows[label] = toUsageWindow({ usedPercent, windowSeconds, diff --git a/packages/web/server/lib/quota/DOCUMENTATION.md b/packages/web/server/lib/quota/DOCUMENTATION.md index 475ff2cf..40643b06 100644 --- a/packages/web/server/lib/quota/DOCUMENTATION.md +++ b/packages/web/server/lib/quota/DOCUMENTATION.md @@ -70,6 +70,14 @@ In 2025/2026 MiniMax rebranded "Coding Plan" to "Token Plan" alongside the M3 mo - **model_remains array**: Now contains entries for multiple model categories (chat, speech, video, image). The provider selects the chat-model entry by matching `MiniMax-M*`, then `general`/`chat`/`text` by name, then any entry with a remaining percent. - **Window status**: The `current_interval_status` and `current_weekly_status` fields indicate whether a window is active. Status `3` means the window is not applicable for the current plan tier (e.g. legacy plans without weekly limits). The provider omits inactive windows. +## Kimi for Coding field semantics + +`GET https://api.kimi.com/coding/v1/usages` is inconsistent about which field carries consumption: +- The weekly `usage` block returns `used` (consumed) with no `remaining` field. +- Each `limits[].detail` rate-limit block returns `remaining` (available) with no `used` field. + +The provider computes `usedPercent` from whichever of `used`/`remaining` is present (`used` takes precedence when both exist) rather than assuming one field name. Both `packages/web/server/lib/quota/providers/kimi.js` and `packages/vscode/src/quotaProviders.ts` (`fetchKimiQuota`) must stay in sync — the VS Code extension duplicates this parsing logic rather than importing it. + ## Notes for contributors - Keep provider IDs stable; clients use them directly. - Avoid adding alias-based dispatch in `fetchQuotaForProvider`; dispatch currently expects exact provider IDs. diff --git a/packages/web/server/lib/quota/providers/kimi.js b/packages/web/server/lib/quota/providers/kimi.js index a9d6c893..2ebd34a6 100644 --- a/packages/web/server/lib/quota/providers/kimi.js +++ b/packages/web/server/lib/quota/providers/kimi.js @@ -14,6 +14,20 @@ export const providerId = 'kimi-for-coding'; export const providerName = 'Kimi for Coding'; const aliases = ['kimi-for-coding', 'kimi']; +// Kimi's weekly `usage` block reports `used`; its rate-limit `limits[].detail` +// blocks report `remaining` instead. Neither field is guaranteed present, so +// derive usedPercent from whichever one the API actually returned. +const computeUsedPercent = (total, used, remaining) => { + if (!total) return null; + if (used !== null) { + return Math.max(0, Math.min(100, (used / total) * 100)); + } + if (remaining !== null) { + return Math.max(0, Math.min(100, 100 - (remaining / total) * 100)); + } + return null; +}; + export const isConfigured = () => { const auth = readAuthFile(); const entry = normalizeAuthEntry(getAuthEntry(auth, aliases)); @@ -59,10 +73,9 @@ export const fetchQuota = async () => { const usage = payload?.usage ?? null; if (usage) { const limit = toNumber(usage.limit); + const used = toNumber(usage.used); const remaining = toNumber(usage.remaining); - const usedPercent = limit && remaining !== null - ? Math.max(0, Math.min(100, 100 - (remaining / limit) * 100)) - : null; + const usedPercent = computeUsedPercent(limit, used, remaining); windows.weekly = toUsageWindow({ usedPercent, windowSeconds: null, @@ -78,10 +91,9 @@ export const fetchQuota = async () => { const windowSeconds = durationToSeconds(window?.duration, window?.timeUnit); const label = windowSeconds === 5 * 60 * 60 ? `Rate Limit (${rawLabel})` : rawLabel; const total = toNumber(detail?.limit); + const used = toNumber(detail?.used); const remaining = toNumber(detail?.remaining); - const usedPercent = total && remaining !== null - ? Math.max(0, Math.min(100, 100 - (remaining / total) * 100)) - : null; + const usedPercent = computeUsedPercent(total, used, remaining); windows[label] = toUsageWindow({ usedPercent, windowSeconds, diff --git a/packages/web/server/lib/quota/providers/kimi.test.js b/packages/web/server/lib/quota/providers/kimi.test.js new file mode 100644 index 00000000..c2eb3b00 --- /dev/null +++ b/packages/web/server/lib/quota/providers/kimi.test.js @@ -0,0 +1,108 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../opencode/auth.js', () => ({ + readAuthFile: () => ({ 'kimi-for-coding': { key: 'test-token' } }), +})); + +import { fetchQuota } from './kimi.js'; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +const mockResponse = (body, init = {}) => ({ + ok: true, + status: 200, + json: async () => body, + ...init, +}); + +describe('Kimi for Coding quota provider', () => { + it('computes weekly usedPercent from the used field (live API shape, no remaining field)', async () => { + // Captured from GET https://api.kimi.com/coding/v1/usages — the weekly + // `usage` block only ever includes `used`, never `remaining`. + vi.stubGlobal('fetch', vi.fn().mockResolvedValue( + mockResponse({ + usage: { limit: '100', used: '100', resetTime: '2026-08-04T06:21:48.514003Z' }, + limits: [{ + window: { duration: 300, timeUnit: 'TIME_UNIT_MINUTE' }, + detail: { limit: '100', remaining: '100', resetTime: '2026-08-03T07:21:48.514003Z' }, + }], + }), + )); + + const result = await fetchQuota(); + + expect(result.ok).toBe(true); + expect(result.usage.windows.weekly.usedPercent).toBe(100); + expect(result.usage.windows['Rate Limit (300m)'].usedPercent).toBe(0); + }); + + it('falls back to computing usedPercent from remaining when used is absent', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue( + mockResponse({ + usage: { limit: '2048', remaining: '512', resetTime: '2026-08-04T06:21:48.514003Z' }, + limits: [], + }), + )); + + const result = await fetchQuota(); + + expect(result.usage.windows.weekly.usedPercent).toBe(75); + }); + + it('prefers used over remaining when both fields are present', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue( + mockResponse({ + usage: { limit: '100', used: '30', remaining: '999', resetTime: null }, + limits: [], + }), + )); + + const result = await fetchQuota(); + + expect(result.usage.windows.weekly.usedPercent).toBe(30); + }); + + it('reports null usedPercent when neither used nor remaining is present', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue( + mockResponse({ + usage: { limit: '100', resetTime: null }, + limits: [], + }), + )); + + const result = await fetchQuota(); + + expect(result.usage.windows.weekly.usedPercent).toBeNull(); + }); + + it('reports not configured when no credentials are stored', async () => { + vi.doMock('../../opencode/auth.js', () => ({ readAuthFile: () => ({}) })); + vi.resetModules(); + const { fetchQuota: fetchQuotaFresh } = await import('./kimi.js'); + + const result = await fetchQuotaFresh(); + + expect(result.ok).toBe(false); + expect(result.configured).toBe(false); + expect(result.error).toBe('Not configured'); + + vi.doUnmock('../../opencode/auth.js'); + vi.resetModules(); + }); + + it('surfaces API errors with status', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ + ok: false, + status: 401, + json: async () => ({}), + })); + + const result = await fetchQuota(); + + expect(result.ok).toBe(false); + expect(result.configured).toBe(true); + expect(result.error).toBe('API error: 401'); + }); +});