mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
feat(quota): Command Code quota and ClinePass from the Cline sign-in (#1682)
* feat(quota): Command Code quota and ClinePass from the Cline sign-in Command Code: reads the CLI's ~/.commandcode/auth.json key and the billing credits and subscription endpoints. 5-hour and weekly windows as used of cap, remaining credits as a note, plan from planId. Live in the Mac dock from the local CLI, in codeburn quota and the Windows dock. ClinePass: without a saved or env key, falls back to the Cline CLI's providers.json session (accessToken, then apiKey, then auth.apiKey, with Cline's path overrides). Read-only; an expired session stops before the network and says to run cline. The Mac catalog adds the local CLI source so Automatic connects without a key. * fix(quota): keep retrying after an expired Cline sign-in Running cline refreshes the session file CodeBurn only reads, so an expired or rejected Cline session is now a retryable failure that keeps the last quota and shows the guidance, on the Mac and in the CLI. A rejected API key and a missing credential stay terminal. * test(quota): build expected Cline paths with path.join for Windows
This commit is contained in:
parent
6639437cd3
commit
39b9b3adcd
27 changed files with 1019 additions and 60 deletions
|
|
@ -1,12 +1,22 @@
|
|||
// Fixture-driven coverage for the ClinePass quota adapter, ported from the
|
||||
// menubar's ClinePassQuotaTests. The key is synthetic and every request goes
|
||||
// through the injected fetch.
|
||||
import { join } from 'node:path'
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { clinePassApiKey, decodeClinePassUsage, fetchClinePassQuota } from '../src/quota/clinepass.js'
|
||||
import {
|
||||
clinePassApiKey, clineProvidersPath, decodeClinePassUsage, fetchClinePassQuota, parseClineProviders,
|
||||
} from '../src/quota/clinepass.js'
|
||||
|
||||
const neverFetch = (() => { throw new Error('the test must not reach the network') }) as unknown as typeof fetch
|
||||
const SYNTHETIC_KEY = 'synthetic-clinepass-test-key'
|
||||
const noFile = async () => null
|
||||
const NOW = 1_800_000_000_000
|
||||
|
||||
function providersFile(settings: unknown): string {
|
||||
return JSON.stringify({ version: 1, providers: { cline: { settings }, anthropic: { settings: { apiKey: 'other-provider-key' } } } })
|
||||
}
|
||||
|
||||
const successBody = {
|
||||
success: true,
|
||||
|
|
@ -32,9 +42,56 @@ describe('ClinePass credential discovery', () => {
|
|||
})
|
||||
|
||||
it('reports disconnected with no key and never fetches', async () => {
|
||||
const result = await fetchClinePassQuota({ env: {}, fetch: neverFetch })
|
||||
const result = await fetchClinePassQuota({ env: {}, fetch: neverFetch, readFile: noFile })
|
||||
expect(result.quota.connection).toBe('disconnected')
|
||||
})
|
||||
|
||||
it('follows Cline\'s settings path overrides', () => {
|
||||
expect(clineProvidersPath({}, '/home/u')).toBe(join('/home/u', '.cline', 'data', 'settings', 'providers.json'))
|
||||
expect(clineProvidersPath({ CLINE_DIR: '~/c' }, '/home/u')).toBe(join('/home/u', 'c', 'data', 'settings', 'providers.json'))
|
||||
expect(clineProvidersPath({ CLINE_DIR: '/c', CLINE_DATA_DIR: '/d' }, '/home/u')).toBe(join('/d', 'settings', 'providers.json'))
|
||||
expect(clineProvidersPath({ CLINE_DATA_DIR: '/d', CLINE_PROVIDER_SETTINGS_PATH: '/f.json' }, '/home/u')).toBe('/f.json')
|
||||
})
|
||||
|
||||
it('prefers the OAuth access token, then apiKey, then auth.apiKey', () => {
|
||||
expect(parseClineProviders(providersFile({ apiKey: 'k1', auth: { accessToken: 'workos:tok', apiKey: 'k2', expiresAt: NOW } })))
|
||||
.toEqual({ token: 'workos:tok', oauth: true, expiresAt: NOW })
|
||||
expect(parseClineProviders(providersFile({ auth: { accessToken: 'bare' } }))?.token).toBe('workos:bare')
|
||||
expect(parseClineProviders(providersFile({ apiKey: 'k1', auth: { apiKey: 'k2' } }))).toEqual({ token: 'k1', oauth: false, expiresAt: null })
|
||||
expect(parseClineProviders(providersFile({ auth: { apiKey: 'k2' } }))?.token).toBe('k2')
|
||||
expect(parseClineProviders(providersFile({ provider: 'cline' }))).toBeNull()
|
||||
expect(parseClineProviders(JSON.stringify({ providers: {} }))).toBeNull()
|
||||
})
|
||||
|
||||
it('sends the Cline session token when no key is set, and a key wins over it', async () => {
|
||||
const seen: string[] = []
|
||||
const file = providersFile({ auth: { accessToken: 'workos:session-token', expiresAt: NOW + 60_000 } })
|
||||
const fetchSpy = (async (_url: string, init: RequestInit) => {
|
||||
seen.push((init.headers as Record<string, string>)['Authorization']!)
|
||||
return jsonResponse(successBody)
|
||||
}) as unknown as typeof fetch
|
||||
const viaFile = await fetchClinePassQuota({ env: {}, fetch: fetchSpy, readFile: async () => file, now: () => NOW })
|
||||
expect(viaFile.quota.connection).toBe('connected')
|
||||
await fetchClinePassQuota({ env: { CLINE_API_KEY: SYNTHETIC_KEY }, fetch: fetchSpy, readFile: async () => file, now: () => NOW })
|
||||
expect(seen).toEqual(['Bearer workos:session-token', `Bearer ${SYNTHETIC_KEY}`])
|
||||
})
|
||||
|
||||
it('stops at an expired Cline session without fetching, as a retryable failure', async () => {
|
||||
const file = providersFile({ auth: { accessToken: 'workos:old', expiresAt: NOW - 1 } })
|
||||
const result = await fetchClinePassQuota({ env: {}, fetch: neverFetch, readFile: async () => file, now: () => NOW })
|
||||
expect(result.quota.connection).toBe('transientFailure')
|
||||
expect(result.quota.footerLines).toEqual(['Cline sign-in expired. Run cline to refresh it.'])
|
||||
})
|
||||
|
||||
it('reads a rejected session token as an expired sign-in', async () => {
|
||||
const file = providersFile({ auth: { accessToken: 'workos:revoked' } })
|
||||
const result = await fetchClinePassQuota({
|
||||
env: {}, readFile: async () => file, now: () => NOW,
|
||||
fetch: (async () => jsonResponse({}, 401)) as unknown as typeof fetch,
|
||||
})
|
||||
expect(result.quota.connection).toBe('transientFailure')
|
||||
expect(result.quota.footerLines).toEqual(['Cline sign-in expired. Run cline to refresh it.'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ClinePass quota decoding', () => {
|
||||
|
|
|
|||
112
tests/quota-commandcode.test.ts
Normal file
112
tests/quota-commandcode.test.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
// Fixture-driven coverage for the Command Code quota adapter. The key is
|
||||
// synthetic and every request goes through the injected fetch.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { commandCodePlanLabel, decodeCommandCodeCredits, fetchCommandCodeQuota } from '../src/quota/commandcode.js'
|
||||
|
||||
const neverFetch = (() => { throw new Error('the test must not reach the network') }) as unknown as typeof fetch
|
||||
const AUTH = JSON.stringify({ apiKey: 'synthetic-commandcode-key', userName: 'someone' })
|
||||
const RESET_MS = 1_791_653_049_551
|
||||
|
||||
const creditsBody = {
|
||||
credits: { belowThreshold: false, creditThreshold: 0, monthlyCredits: 3.9706645399, purchasedCredits: 0, freeCredits: 0 },
|
||||
windowLimits: {
|
||||
limited: true,
|
||||
exceeded: 'weekly',
|
||||
fiveHour: { used: 0.75, cap: 3, exceeded: false, resetAt: 0 },
|
||||
weekly: { used: 6.0293354601, cap: 6, exceeded: true, resetAt: RESET_MS },
|
||||
},
|
||||
}
|
||||
const subscriptionBody = { success: true, data: { status: 'active', planId: 'individual-go-v1', currentPeriodEnd: '2026-11-01T10:38:29.000Z' } }
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
|
||||
}
|
||||
|
||||
describe('Command Code quota decoding', () => {
|
||||
it('maps the 5-hour and weekly windows as used of cap, clamped', () => {
|
||||
const quota = decodeCommandCodeCredits(creditsBody, 'individual-go-v1')
|
||||
expect(quota?.connection).toBe('connected')
|
||||
expect(quota?.details).toEqual([
|
||||
{ label: '5-hour', percent: 0.25, resetsAt: null },
|
||||
{ label: 'Weekly', percent: 1, resetsAt: new Date(RESET_MS).toISOString() },
|
||||
])
|
||||
expect(quota?.primary?.label).toBe('Weekly')
|
||||
expect(quota?.planLabel).toBe('Go')
|
||||
expect(quota?.notes).toEqual(['Credits left: $3.97 monthly'])
|
||||
})
|
||||
|
||||
it('skips an unreadable window and rejects a body with none', () => {
|
||||
const quota = decodeCommandCodeCredits({ windowLimits: { fiveHour: { used: 1, cap: 0 }, weekly: { used: 3, cap: 6, resetAt: 0 } } })
|
||||
expect(quota?.details).toEqual([{ label: 'Weekly', percent: 0.5, resetsAt: null }])
|
||||
expect(quota?.notes).toBeUndefined()
|
||||
expect(decodeCommandCodeCredits({ windowLimits: {} })).toBeNull()
|
||||
expect(decodeCommandCodeCredits({ credits: {} })).toBeNull()
|
||||
expect(decodeCommandCodeCredits(null)).toBeNull()
|
||||
})
|
||||
|
||||
it('labels plans from their id', () => {
|
||||
expect(commandCodePlanLabel('individual-pro-v1')).toBe('Pro')
|
||||
expect(commandCodePlanLabel('team-max')).toBe('Team-max')
|
||||
expect(commandCodePlanLabel('')).toBeNull()
|
||||
expect(commandCodePlanLabel(undefined)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Command Code quota fetch', () => {
|
||||
it('is disconnected without an auth file and never fetches', async () => {
|
||||
const result = await fetchCommandCodeQuota({ authPath: '/nope', readFile: async () => null, fetch: neverFetch })
|
||||
expect(result.quota.connection).toBe('disconnected')
|
||||
})
|
||||
|
||||
it('sends the key as a bearer with a User-Agent to both billing endpoints', async () => {
|
||||
const seen: { url: string; headers: Record<string, string> }[] = []
|
||||
const result = await fetchCommandCodeQuota({
|
||||
authPath: '/auth.json', readFile: async () => AUTH,
|
||||
fetch: (async (url: string, init: RequestInit) => {
|
||||
seen.push({ url, headers: init.headers as Record<string, string> })
|
||||
return jsonResponse(url.endsWith('/credits') ? creditsBody : subscriptionBody)
|
||||
}) as unknown as typeof fetch,
|
||||
})
|
||||
expect(result.quota.connection).toBe('connected')
|
||||
expect(result.quota.planLabel).toBe('Go')
|
||||
expect(seen.map(row => row.url).sort()).toEqual([
|
||||
'https://api.commandcode.ai/alpha/billing/credits',
|
||||
'https://api.commandcode.ai/alpha/billing/subscriptions',
|
||||
])
|
||||
for (const row of seen) {
|
||||
expect(row.headers['Authorization']).toBe('Bearer synthetic-commandcode-key')
|
||||
expect(row.headers['User-Agent']).toBe('CodeBurn')
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the windows when only the subscription call fails', async () => {
|
||||
const result = await fetchCommandCodeQuota({
|
||||
authPath: '/auth.json', readFile: async () => AUTH,
|
||||
fetch: (async (url: string) => url.endsWith('/credits') ? jsonResponse(creditsBody) : jsonResponse({}, 500)) as unknown as typeof fetch,
|
||||
})
|
||||
expect(result.quota.connection).toBe('connected')
|
||||
expect(result.quota.planLabel).toBeNull()
|
||||
})
|
||||
|
||||
it('maps HTTP failures', async () => {
|
||||
const respond = (status: number) => fetchCommandCodeQuota({
|
||||
authPath: '/auth.json', readFile: async () => AUTH,
|
||||
fetch: (async () => jsonResponse({}, status)) as unknown as typeof fetch,
|
||||
})
|
||||
const expired = await respond(401)
|
||||
expect(expired.quota.connection).toBe('terminalFailure')
|
||||
expect(expired.quota.footerLines).toEqual(['Command Code session expired. Sign in with the Command Code CLI again.'])
|
||||
expect((await respond(429)).quota.rateLimited).toBe(true)
|
||||
expect((await respond(503)).quota.connection).toBe('transientFailure')
|
||||
expect((await respond(200)).quota.footerLines).toEqual(['Command Code quota response was malformed.'])
|
||||
})
|
||||
|
||||
it('treats a network error as transient', async () => {
|
||||
const result = await fetchCommandCodeQuota({
|
||||
authPath: '/auth.json', readFile: async () => AUTH,
|
||||
fetch: (async () => { throw new TypeError('fetch failed') }) as unknown as typeof fetch,
|
||||
})
|
||||
expect(result.quota.connection).toBe('transientFailure')
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue