diff --git a/README.md b/README.md index 69d6da7..af67a81 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ pi install /path/to/pi-subscription-usage Sign in through `/login` as described above, then select a model from that provider. From then on: - The footer status bar shows the active quota windows and refreshes after each turn and every 5 minutes (using a 5-minute cache). -- Running `/usage` always fetches fresh data for the active provider and shows progress bars, reset times (`MM/DD HH:mm`), and account details. +- Running `/usage` always fetches fresh data for the active provider and shows progress bars, reset times (`MM/DD HH:mm`), and account details. With [`showAllProviders`](#configuration) it also lists the other signed-in providers. - Claude is the exception: its quota is never fetched, only read from Claude Code's responses (see [Claude (Claude Code)](#claude-claude-code)). ### Reset Credits (OpenAI and Codex) @@ -121,23 +121,31 @@ When your OpenAI or Codex account has redeemable rate-limit reset tickets, `/usa - Before redeeming, the extension checks that the active model and account have not changed and that the runtime token matches Pi's stored OAuth login. - In OpenAI mode, a ticket resets server-defined account windows rather than specifically clearing the current app's limits. - Redeeming a reset ticket is the only write operation in this extension. +- Set [`offerResetCredits`](#configuration) to `false` to skip the offer; the account still lists how many tickets it has. ## Configuration -Percentages show remaining quota by default. To show used quota instead, create `~/.pi/agent/subscription-usage.json` (global) or `.pi/subscription-usage.json` (trusted project override): +Create `~/.pi/agent/subscription-usage.json` (global) or `.pi/subscription-usage.json` (trusted project override). Run `/reload` after changing it. + +| Key | Value | Description | +| --- | --- | --- | +| `displayMode` | `"remaining"` (default) or `"used"` | Whether percentages show remaining or used quota, in the footer, `/usage` progress bars and status events | +| `showAllProviders` | `true` or `false` (default) | `/usage` lists every signed-in provider instead of the active one | +| `offerResetCredits` | `true` (default) or `false` | Whether `/usage` offers to redeem a reset credit when the active OpenAI or Codex account has one | +| `showAllProvidersCacheMinutes` | `5` (default) | How long `/usage` reuses a provider's report in the all-providers list; `0` fetches every time | ```json { - "displayMode": "used" + "displayMode": "used", + "showAllProviders": true, + "offerResetCredits": false, + "showAllProvidersCacheMinutes": 10 } ``` -| Value | Description | -| --- | --- | -| `"remaining"` | Show remaining quota percentage (default) | -| `"used"` | Show used quota percentage | +With `showAllProviders`, the active provider stays first and is always fetched fresh; the others reuse a report for `showAllProvidersCacheMinutes` minutes and are left out when Pi holds no credential for them. Claude appears as `Waiting` until Claude Code reports usage in the session. The footer keeps tracking the active provider on its own five-minute refresh. -Run `/reload` after changing the config file. `displayMode` applies to the footer status bar, `/usage` progress bars, and status events. +With `offerResetCredits` set to `false`, `/usage` still shows how many reset credits the account has, but never asks whether to redeem one; redeeming then needs the setting turned back on. ## Privacy and Safety diff --git a/README.zh-CN.md b/README.zh-CN.md index d3c5095..46654d0 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -110,7 +110,7 @@ pi install /path/to/pi-subscription-usage 按上面的方法登录,再选一个该提供商的模型,之后: - 底部状态栏会自动显示当前额度窗口,在每轮对话结束后及每 5 分钟刷新一次(带 5 分钟缓存)。 -- 执行 `/usage` 会跳过缓存直接拉取最新数据,显示进度条、重置时间(`MM/DD HH:mm`)及账号信息。 +- 执行 `/usage` 会跳过缓存直接拉取最新数据,显示进度条、重置时间(`MM/DD HH:mm`)及账号信息。开启 [`showAllProviders`](#配置) 后,还会一并列出其他已登录的提供商。 - Claude 例外:不会主动查询额度,只读取 Claude Code 回复中附带的数据(见 [Claude (Claude Code)](#claude-claude-code))。 ### 使用重置券(OpenAI 与 Codex) @@ -121,23 +121,31 @@ OpenAI 或 Codex 账号里有可用的限额重置券时,`/usage` 会提供使 - 提交兑换前,扩展会检查当前模型和账号是否发生变动,并核对运行时令牌是否与 Pi 保存的 OAuth 登录信息一致。 - 在 OpenAI 模式下,重置券作用于服务端定义的账户级窗口,不一定单独清空当前应用的限额。 - 兑换重置券是本扩展唯一的写操作。 +- 把 [`offerResetCredits`](#配置) 设为 `false` 可以关掉这个询问;账号上的重置券数量仍会显示。 ## 配置 -百分比默认显示剩余额度。如需改为显示已用额度,可在 `~/.pi/agent/subscription-usage.json`(全局)或 `.pi/subscription-usage.json`(受信任项目的局部覆盖)中配置: +配置文件为 `~/.pi/agent/subscription-usage.json`(全局)或 `.pi/subscription-usage.json`(受信任项目的局部覆盖),修改后执行 `/reload` 生效。 + +| 配置项 | 取值 | 说明 | +| --- | --- | --- | +| `displayMode` | `"remaining"`(默认)或 `"used"` | 百分比显示剩余额度还是已用额度,作用于底部状态栏、`/usage` 进度条和状态事件 | +| `showAllProviders` | `true` 或 `false`(默认) | `/usage` 列出所有已登录的提供商,而不只是当前提供商 | +| `offerResetCredits` | `true`(默认)或 `false` | 当前 OpenAI 或 Codex 账号有重置券时,`/usage` 是否询问是否使用一张 | +| `showAllProvidersCacheMinutes` | 默认 `5` | `/usage` 列表里其他提供商的报告复用多久;`0` 表示每次都重新查询 | ```json { - "displayMode": "used" + "displayMode": "used", + "showAllProviders": true, + "offerResetCredits": false, + "showAllProvidersCacheMinutes": 10 } ``` -| 配置值 | 说明 | -| --- | --- | -| `"remaining"` | 显示剩余额度百分比(默认) | -| `"used"` | 显示已用额度百分比 | +开启 `showAllProviders` 后,当前提供商排在最前并总是重新查询;其余提供商的报告按 `showAllProvidersCacheMinutes` 分钟复用,Pi 没有其凭据的提供商会直接略过。底部状态栏仍按自己的五分钟节奏刷新。Claude 在 Claude Code 于本次会话中上报用量之前显示为 `Waiting`。底部状态栏仍然只跟踪当前提供商。 -修改配置文件后执行 `/reload` 生效。`displayMode` 同时作用于底部状态栏、`/usage` 进度条和状态事件。 +`offerResetCredits` 设为 `false` 时,`/usage` 仍会显示账号上有几张重置券,但不再询问是否使用;需要使用重置券时把该配置改回 `true`。 ## 隐私与安全 diff --git a/src/config-core.ts b/src/config-core.ts index ace4e4b..2f5ad25 100644 --- a/src/config-core.ts +++ b/src/config-core.ts @@ -5,15 +5,27 @@ import { export interface UsageConfig { displayMode: UsageDisplayMode; + /** `/usage` lists every signed-in provider instead of the active one. */ + showAllProviders: boolean; + /** `/usage` offers to redeem a reset credit when the account has one. */ + offerResetCredits: boolean; + /** Minutes a report is reused for the providers after the active one; 0 fetches each time. */ + showAllProvidersCacheMinutes: number; } export interface ParsedUsageConfig { displayMode?: UsageDisplayMode; + showAllProviders?: boolean; + offerResetCredits?: boolean; + showAllProvidersCacheMinutes?: number; warning?: string; } export const DEFAULT_USAGE_CONFIG: UsageConfig = { displayMode: DEFAULT_USAGE_DISPLAY_MODE, + showAllProviders: false, + offerResetCredits: true, + showAllProvidersCacheMinutes: 5, }; export function resolveUsageConfig( @@ -25,6 +37,18 @@ export function resolveUsageConfig( projectConfig?.displayMode ?? globalConfig?.displayMode ?? DEFAULT_USAGE_CONFIG.displayMode, + showAllProviders: + projectConfig?.showAllProviders ?? + globalConfig?.showAllProviders ?? + DEFAULT_USAGE_CONFIG.showAllProviders, + offerResetCredits: + projectConfig?.offerResetCredits ?? + globalConfig?.offerResetCredits ?? + DEFAULT_USAGE_CONFIG.offerResetCredits, + showAllProvidersCacheMinutes: + projectConfig?.showAllProvidersCacheMinutes ?? + globalConfig?.showAllProvidersCacheMinutes ?? + DEFAULT_USAGE_CONFIG.showAllProvidersCacheMinutes, }; } @@ -32,12 +56,39 @@ export function parseUsageConfig(value: unknown): ParsedUsageConfig { if (!value || typeof value !== "object" || Array.isArray(value)) { return { warning: "configuration must be a JSON object" }; } - const displayMode = (value as Record).displayMode; - if (displayMode === undefined) return {}; - if (displayMode !== "remaining" && displayMode !== "used") { + const record = value as Record; + const displayMode = record.displayMode; + const showAllProviders = record.showAllProviders; + const offerResetCredits = record.offerResetCredits; + const showAllProvidersCacheMinutes = record.showAllProvidersCacheMinutes; + if (displayMode !== undefined && displayMode !== "remaining" && displayMode !== "used") { return { warning: 'displayMode must be either "remaining" or "used"', }; } - return { displayMode }; + if (showAllProviders !== undefined && typeof showAllProviders !== "boolean") { + return { warning: "showAllProviders must be true or false" }; + } + if (offerResetCredits !== undefined && typeof offerResetCredits !== "boolean") { + return { warning: "offerResetCredits must be true or false" }; + } + if ( + showAllProvidersCacheMinutes !== undefined && + (typeof showAllProvidersCacheMinutes !== "number" || + !Number.isFinite(showAllProvidersCacheMinutes) || + showAllProvidersCacheMinutes < 0) + ) { + return { + warning: + "showAllProvidersCacheMinutes must be 0 or more", + }; + } + return { + ...(displayMode === undefined ? {} : { displayMode }), + ...(showAllProviders === undefined ? {} : { showAllProviders }), + ...(offerResetCredits === undefined ? {} : { offerResetCredits }), + ...(showAllProvidersCacheMinutes === undefined + ? {} + : { showAllProvidersCacheMinutes }), + }; } diff --git a/src/core.ts b/src/core.ts index d6ac299..21bfbf0 100644 --- a/src/core.ts +++ b/src/core.ts @@ -7,7 +7,7 @@ export class UsageCache { string, { createdAt: number; report: UsageReport } >(); - private readonly ttlMs: number; + private ttlMs: number; private readonly maxEntries: number; constructor(ttlMs: number, maxEntries = 32) { @@ -21,13 +21,24 @@ export class UsageCache { this.maxEntries = maxEntries; } + /** `maxAgeMs` lets one caller accept a staler report than the default window. */ get( providerId: string, fingerprint: string, now = Date.now(), + maxAgeMs = this.ttlMs, ): UsageReport | undefined { this.sweepExpired(now); - return this.entries.get(cacheKey(providerId, fingerprint))?.report; + // A zero window means "fetch every time", not "accept a same-millisecond hit". + if (maxAgeMs <= 0) return undefined; + const entry = this.entries.get(cacheKey(providerId, fingerprint)); + if (!entry) return undefined; + return now - entry.createdAt <= maxAgeMs ? entry.report : undefined; + } + + /** A caller that accepts staler reports keeps entries that long before sweeping. */ + raiseTtl(ttlMs: number): void { + if (Number.isFinite(ttlMs) && ttlMs > this.ttlMs) this.ttlMs = ttlMs; } set( diff --git a/src/usage.ts b/src/usage.ts index 044ed4d..846b8ac 100644 --- a/src/usage.ts +++ b/src/usage.ts @@ -5,6 +5,7 @@ import type { ExtensionContext, } from "@earendil-works/pi-coding-agent"; import { loadUsageConfig } from "./config.ts"; +import { DEFAULT_USAGE_CONFIG } from "./config-core.ts"; import { awaitWithDeadline, errorMessage, @@ -48,6 +49,7 @@ import { adapterForProvider, queryProviderUsage, resolveUsageAuth, + SUPPORTED_ADAPTERS, UsageUnsupportedError, } from "./query.ts"; import type { @@ -82,6 +84,10 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { const activeControllers = new Set(); let sessionActive = false; let displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE; + let showAllProviders = false; + let offerResetCredits = true; + let showAllProvidersCacheMs = + DEFAULT_USAGE_CONFIG.showAllProvidersCacheMinutes * 60_000; let statusGeneration = 0; let statusController: AbortController | undefined; let statusTimer: ReturnType | undefined; @@ -182,12 +188,14 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { if (schedule && sessionActive) scheduleStatusRefresh(ctx, model); } + /** Undefined means Pi holds no credential for the provider, so it is not signed in. */ async function queryAdapterState( ctx: ExtensionContext, adapter: UsageProviderAdapter, force: boolean, signal: AbortSignal, - ): Promise { + maxAgeMs?: number, + ): Promise { let auth: ResolvedUsageAuth | undefined; try { auth = await awaitWithDeadline( @@ -209,17 +217,10 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { }, }; } - if (!auth) { - return { - state: { - providerId: adapter.id, - providerName: adapter.displayName, - status: "auth-unavailable", - message: `No Pi runtime credential available for ${adapter.displayName}.`, - }, - }; - } - const cached = force ? undefined : cache.get(adapter.id, auth.fingerprint); + if (!auth) return undefined; + const cached = force + ? undefined + : cache.get(adapter.id, auth.fingerprint, Date.now(), maxAgeMs); if (cached) { return { state: { @@ -305,7 +306,16 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { }, }; } - return queryAdapterState(ctx, adapter, force, signal); + return ( + (await queryAdapterState(ctx, adapter, force, signal)) ?? { + state: { + providerId: adapter.id, + providerName: adapter.displayName, + status: "auth-unavailable", + message: `No Pi runtime credential available for ${adapter.displayName}.`, + }, + } + ); } /** Claude has no query to force; /usage and refreshes reread the last observation. */ @@ -578,6 +588,60 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { return undefined; } + /** + * The other signed-in providers for `/usage`. Only the active provider is + * forced; these read the five-minute cache so a list costs few requests. + */ + async function collectOtherProviders( + ctx: ExtensionContext, + active: ProviderUsageState, + signal: AbortSignal, + ): Promise { + const states = await Promise.all( + SUPPORTED_ADAPTERS.filter( + (adapter) => adapter.id !== active.providerId, + ).map(async (adapter) => { + try { + return ( + await queryAdapterState( + ctx, + adapter, + false, + signal, + showAllProvidersCacheMs, + ) + )?.state; + } catch (error) { + if (isAbortError(error) || !sessionActive) throw error; + return { + providerId: adapter.id, + providerName: adapter.displayName, + status: "query-failed", + message: errorMessage(error), + } satisfies ProviderUsageState; + } + }), + ); + const others = states.filter( + (state): state is ProviderUsageState => state !== undefined, + ); + if ( + active.providerId !== CLAUDE_BRIDGE_PROVIDER_ID && + hasClaudeBridgeModels(ctx) + ) { + others.push(observedClaudeOutcome().state); + } + return others; + } + + /** Claude has no endpoint to query, so it appears only when the bridge is installed. */ + function hasClaudeBridgeModels(ctx: ExtensionContext): boolean { + return [ + ...ctx.modelRegistry.getAvailable(), + ...ctx.modelRegistry.getAll(), + ].some((model) => model.provider === CLAUDE_BRIDGE_PROVIDER_ID); + } + async function showUsage(ctx: ExtensionCommandContext): Promise { if (!ctx.hasUI) throw new Error("/usage requires TUI or RPC mode."); const controller = new AbortController(); @@ -591,14 +655,27 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { ); return; } + const states = [current.outcome.state]; + if (showAllProviders) { + states.push( + ...(await collectOtherProviders( + ctx, + current.outcome.state, + controller.signal, + )), + ); + } ctx.ui.notify( - formatProviderState(current.outcome.state, displayMode), + states + .map((state) => formatProviderState(state, displayMode)) + .join("\n\n"), "info", ); if (current.model) { publishStatus(ctx, current.outcome, current.model, sessionActive); } if ( + !offerResetCredits || ![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") || current.outcome.state.status !== "ready" ) { @@ -644,6 +721,10 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { sessionActive = ctx.hasUI; const config = loadUsageConfig(ctx.cwd, ctx.isProjectTrusted()); displayMode = config.displayMode; + showAllProviders = config.showAllProviders; + offerResetCredits = config.offerResetCredits; + showAllProvidersCacheMs = config.showAllProvidersCacheMinutes * 60_000; + cache.raiseTtl(showAllProvidersCacheMs); for (const warning of config.warnings) { ctx.ui.notify(`Usage config ignored: ${warning}`, "warning"); } diff --git a/test/config.test.ts b/test/config.test.ts index 45a7852..24d49dd 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -8,6 +8,9 @@ import { test("uses remaining as the default display mode", () => { assert.equal(DEFAULT_USAGE_CONFIG.displayMode, "remaining"); + assert.equal(DEFAULT_USAGE_CONFIG.showAllProviders, false); + assert.equal(DEFAULT_USAGE_CONFIG.offerResetCredits, true); + assert.equal(DEFAULT_USAGE_CONFIG.showAllProvidersCacheMinutes, 5); assert.deepEqual(parseUsageConfig({}), {}); }); @@ -17,11 +20,21 @@ test("lets project configuration override global display mode", () => { parseUsageConfig({ displayMode: "used" }), parseUsageConfig({ displayMode: "remaining" }), ), - { displayMode: "remaining" }, + { + displayMode: "remaining", + showAllProviders: false, + offerResetCredits: true, + showAllProvidersCacheMinutes: 5, + }, ); assert.deepEqual( resolveUsageConfig(parseUsageConfig({ displayMode: "used" })), - { displayMode: "used" }, + { + displayMode: "used", + showAllProviders: false, + offerResetCredits: true, + showAllProvidersCacheMinutes: 5, + }, ); }); @@ -34,10 +47,80 @@ test("accepts remaining and used display modes", () => { }); }); +test("shows only the active provider unless showAllProviders is on", () => { + assert.equal(resolveUsageConfig().showAllProviders, false); + assert.equal( + resolveUsageConfig(parseUsageConfig({ showAllProviders: true })) + .showAllProviders, + true, + ); + assert.equal( + resolveUsageConfig( + parseUsageConfig({ showAllProviders: true }), + parseUsageConfig({ showAllProviders: false }), + ).showAllProviders, + false, + ); + assert.deepEqual(parseUsageConfig({ showAllProviders: true }), { + showAllProviders: true, + }); +}); + test("rejects invalid usage configuration", () => { assert.match(parseUsageConfig([]).warning ?? "", /JSON object/u); assert.match( parseUsageConfig({ displayMode: "total" }).warning ?? "", /displayMode/u, ); + assert.match( + parseUsageConfig({ showAllProviders: "yes" }).warning ?? "", + /showAllProviders must be true or false/u, + ); + assert.match( + parseUsageConfig({ offerResetCredits: "no" }).warning ?? "", + /offerResetCredits must be true or false/u, + ); + assert.match( + parseUsageConfig({ showAllProvidersCacheMinutes: "5" }).warning ?? "", + /showAllProvidersCacheMinutes must be 0 or more/u, + ); + assert.match( + parseUsageConfig({ showAllProvidersCacheMinutes: -1 }).warning ?? "", + /showAllProvidersCacheMinutes must be 0 or more/u, + ); +}); + +test("offers reset credits unless offerResetCredits is off", () => { + assert.equal(resolveUsageConfig().offerResetCredits, true); + assert.equal( + resolveUsageConfig(parseUsageConfig({ offerResetCredits: false })) + .offerResetCredits, + false, + ); + assert.equal( + resolveUsageConfig( + parseUsageConfig({ offerResetCredits: false }), + parseUsageConfig({ offerResetCredits: true }), + ).offerResetCredits, + true, + ); +}); + +test("accepts a cache window for the other providers", () => { + assert.equal(resolveUsageConfig().showAllProvidersCacheMinutes, 5); + assert.equal( + resolveUsageConfig(parseUsageConfig({ showAllProvidersCacheMinutes: 0 })) + .showAllProvidersCacheMinutes, + 0, + ); + assert.equal( + resolveUsageConfig( + parseUsageConfig({ showAllProvidersCacheMinutes: 30 }), + parseUsageConfig({ showAllProvidersCacheMinutes: 1 }), + ).showAllProvidersCacheMinutes, + 1, + ); + assert.deepEqual(parseUsageConfig({ showAllProvidersCacheMinutes: 2.5 }), { + showAllProvidersCacheMinutes: 2.5, + }); }); diff --git a/test/usage-all.test.ts b/test/usage-all.test.ts new file mode 100644 index 0000000..53bfb8a --- /dev/null +++ b/test/usage-all.test.ts @@ -0,0 +1,244 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { registerHooks } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +// Keep the extension offline and independent of a globally installed Pi. +const sdkUrl = "data:text/javascript," + encodeURIComponent(` +export const CONFIG_DIR_NAME = '.pi'; +export const readStoredCredential = () => undefined; +export const getAgentDir = () => process.env.PI_TEST_AGENT_DIR ?? '/nonexistent/pi-usage-all-test'; +`); +registerHooks({ + resolve(specifier, context, next) { + return specifier === "@earendil-works/pi-coding-agent" + ? { url: sdkUrl, shortCircuit: true } + : next(specifier, context); + }, +}); + +const ACTIVE_MODEL = { + provider: "kimi-coding", + id: "kimi-for-coding", + baseUrl: "https://api.kimi.com", +}; +const SECOND_MODEL = { + provider: "opencode-go", + id: "grok-code", + baseUrl: "https://opencode.ai", +}; +const CLAUDE_MODEL = { provider: "claude-bridge", id: "claude-haiku-4-5" }; + +const ACTIVE_USAGE = { + usage: { limit: 100, used: 25, resetTime: "2026-12-01T00:00:00Z" }, +}; +const SECOND_USAGE = { + usage: { + rolling: { status: "ok", percent: 12, resetsAt: "2026-12-01T00:00:00Z" }, + weekly: { status: "rate-limited", percent: 100 }, + }, +}; + +async function startExtension(options: { + showAllProviders?: boolean; + showAllProvidersCacheMinutes?: number; + models?: object[]; +}) { + const agentDir = mkdtempSync(join(tmpdir(), "pi-usage-all-")); + process.env.PI_TEST_AGENT_DIR = agentDir; + const config: Record = {}; + if (options.showAllProviders !== undefined) { + config.showAllProviders = options.showAllProviders; + } + if (options.showAllProvidersCacheMinutes !== undefined) { + config.showAllProvidersCacheMinutes = options.showAllProvidersCacheMinutes; + } + if (Object.keys(config).length > 0) { + writeFileSync( + join(agentDir, "subscription-usage.json"), + JSON.stringify(config), + ); + } + const { default: extension } = await import("../src/usage.ts"); + const handlers = new Map(); + const commands = new Map(); + extension({ + on: (name: string, handler: Function) => { + handlers.set(name, handler); + }, + registerCommand: (name: string, command: { handler: Function }) => { + commands.set(name, command); + }, + events: { emit: () => {} }, + } as never); + const models = options.models ?? [ACTIVE_MODEL]; + const statuses: (string | undefined)[] = []; + const notices: string[] = []; + const ctx = { + model: ACTIVE_MODEL, + hasUI: true, + cwd: agentDir, + isProjectTrusted: () => false, + modelRegistry: { + getAll: () => models, + getAvailable: () => models, + isUsingOAuth: () => false, + getProviderAuth: async (provider: string) => ({ + auth: { apiKey: `key-${provider}` }, + }), + }, + ui: { + setStatus: (_key: string, value: string | undefined) => { + statuses.push(value); + }, + notify: (text: string) => { + notices.push(text); + }, + }, + }; + const settle = () => new Promise((resolve) => setImmediate(resolve)); + const emit = async (name: string, event: object = {}) => { + await handlers.get(name)!(event, ctx); + await settle(); + }; + const usage = async () => { + await commands.get("usage")!.handler("", ctx); + return notices.at(-1) ?? ""; + }; + return { + ctx, + statuses, + notices, + emit, + usage, + cleanup: async () => { + await handlers.get("session_shutdown")?.({}, ctx); + rmSync(agentDir, { recursive: true, force: true }); + }, + }; +} + +function installFetch() { + const original = globalThis.fetch; + const calls: string[] = []; + globalThis.fetch = async (input) => { + const url = String(input); + calls.push(url); + if (url.includes("api.kimi.com")) return jsonResponse(ACTIVE_USAGE); + if (url.includes("opencode.ai")) return jsonResponse(SECOND_USAGE); + return jsonResponse({ error: "unexpected" }, 500); + }; + return { + calls, + restore: () => { + globalThis.fetch = original; + }, + }; +} + +test("/usage lists only the active provider by default", async () => { + const harness = await startExtension({ + models: [ACTIVE_MODEL, SECOND_MODEL], + }); + const fetchStub = installFetch(); + try { + await harness.emit("session_start"); + const text = await harness.usage(); + assert.match(text, /^Kimi Coding\n/u); + assert.doesNotMatch(text, /OpenCode Go/u); + } finally { + fetchStub.restore(); + await harness.cleanup(); + } +}); + +test("/usage lists every signed-in provider when showAllProviders is on", async () => { + const harness = await startExtension({ + showAllProviders: true, + models: [ACTIVE_MODEL, SECOND_MODEL, CLAUDE_MODEL], + }); + const fetchStub = installFetch(); + try { + await harness.emit("session_start"); + const text = await harness.usage(); + const blocks = text.split("\n\n"); + assert.match(blocks[0] ?? "", /^Kimi Coding\n/u); + assert.match(text, /OpenCode Go\n 5h Window/u); + assert.match(text, /Claude \(Claude Code\)\n Waiting: /u); + // The footer keeps the active provider only. + assert.match(harness.statuses.at(-1) ?? "", /^1w 75% /u); + } finally { + fetchStub.restore(); + await harness.cleanup(); + } +}); + +test("/usage reuses the cache for providers other than the active one", async () => { + const harness = await startExtension({ + showAllProviders: true, + models: [ACTIVE_MODEL, SECOND_MODEL], + }); + const fetchStub = installFetch(); + try { + await harness.emit("session_start"); + const calls = (host: string) => + fetchStub.calls.filter((url) => url.includes(host)).length; + await harness.usage(); + assert.equal(calls("opencode.ai"), 1); + const activeCalls = calls("api.kimi.com"); + await harness.usage(); + assert.equal(calls("opencode.ai"), 1); + // The active provider is always fresh. + assert.equal(calls("api.kimi.com") - activeCalls, 1); + } finally { + fetchStub.restore(); + await harness.cleanup(); + } +}); + +test("showAllProvidersCacheMinutes 0 refetches the other providers every time", async () => { + const harness = await startExtension({ + showAllProviders: true, + showAllProvidersCacheMinutes: 0, + models: [ACTIVE_MODEL, SECOND_MODEL], + }); + const fetchStub = installFetch(); + try { + await harness.emit("session_start"); + const calls = (host: string) => + fetchStub.calls.filter((url) => url.includes(host)).length; + await harness.usage(); + assert.equal(calls("opencode.ai"), 1); + await harness.usage(); + assert.equal(calls("opencode.ai"), 2); + } finally { + fetchStub.restore(); + await harness.cleanup(); + } +}); + +test("skips providers Pi holds no credential for", async () => { + const harness = await startExtension({ + showAllProviders: true, + models: [ACTIVE_MODEL], + }); + const fetchStub = installFetch(); + try { + await harness.emit("session_start"); + const text = await harness.usage(); + assert.doesNotMatch(text, /OpenCode Go|Grok|Antigravity|Claude/u); + assert.doesNotMatch(text, /No Pi runtime credential/u); + } finally { + fetchStub.restore(); + await harness.cleanup(); + } +}); + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +} diff --git a/test/usage-reset-credits.test.ts b/test/usage-reset-credits.test.ts new file mode 100644 index 0000000..4e8e14e --- /dev/null +++ b/test/usage-reset-credits.test.ts @@ -0,0 +1,172 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { registerHooks } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +// Keep the extension offline and independent of a globally installed Pi. +const sdkUrl = "data:text/javascript," + encodeURIComponent(` +export const CONFIG_DIR_NAME = '.pi'; +export const readStoredCredential = () => undefined; +export const getAgentDir = () => process.env.PI_TEST_AGENT_DIR ?? '/nonexistent/pi-reset-test'; +`); +registerHooks({ + resolve(specifier, context, next) { + return specifier === "@earendil-works/pi-coding-agent" + ? { url: sdkUrl, shortCircuit: true } + : next(specifier, context); + }, +}); + +const CODEX_MODEL = { + provider: "openai-codex", + id: "gpt-5-codex", + baseUrl: "https://chatgpt.com", +}; + +function codexToken(accountId: string): string { + const claims = { + "https://api.openai.com/auth": { chatgpt_account_id: accountId }, + }; + return `e30.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.sig`; +} + +const ACCESS = codexToken("account-fixture"); + +async function startExtension(config?: object) { + const agentDir = mkdtempSync(join(tmpdir(), "pi-reset-test-")); + process.env.PI_TEST_AGENT_DIR = agentDir; + if (config) { + writeFileSync( + join(agentDir, "subscription-usage.json"), + JSON.stringify(config), + ); + } + const { default: extension } = await import("../src/usage.ts"); + const handlers = new Map(); + const commands = new Map(); + extension({ + on: (name: string, handler: Function) => { + handlers.set(name, handler); + }, + registerCommand: (name: string, command: { handler: Function }) => { + commands.set(name, command); + }, + events: { emit: () => {} }, + } as never); + const models = [CODEX_MODEL]; + const notices: string[] = []; + const prompts: string[] = []; + const ctx = { + model: CODEX_MODEL, + hasUI: true, + cwd: agentDir, + isProjectTrusted: () => false, + modelRegistry: { + getAll: () => models, + getAvailable: () => models, + isUsingOAuth: () => true, + getProviderAuth: async () => ({ auth: { apiKey: ACCESS } }), + }, + ui: { + setStatus: () => {}, + notify: (text: string) => { + notices.push(text); + }, + select: async (title: string) => { + prompts.push(title); + return undefined; + }, + }, + }; + const settle = () => new Promise((resolve) => setImmediate(resolve)); + const emit = async (name: string, event: object = {}) => { + await handlers.get(name)!(event, ctx); + await settle(); + }; + const usage = async () => { + await commands.get("usage")!.handler("", ctx); + return notices.at(-1) ?? ""; + }; + return { + notices, + prompts, + emit, + usage, + cleanup: async () => { + await handlers.get("session_shutdown")?.({}, ctx); + rmSync(agentDir, { recursive: true, force: true }); + }, + }; +} + +function installFetch() { + const original = globalThis.fetch; + globalThis.fetch = async (input) => { + const url = String(input); + if (url.endsWith("/wham/usage")) { + return jsonResponse({ + rate_limit: { + primary_window: { used_percent: 10, limit_window_seconds: 18_000 }, + }, + rate_limit_reset_credits: { available_count: 1 }, + }); + } + if (url.endsWith("/wham/rate-limit-reset-credits")) { + return jsonResponse({ + available_count: 1, + credits: [ + { + id: "ticket", + status: "available", + reset_type: "codex_rate_limits", + is_supported_by_plan: true, + }, + ], + }); + } + return jsonResponse({ error: "unexpected" }, 500); + }; + return { + restore: () => { + globalThis.fetch = original; + }, + }; +} + +test("/usage offers a reset credit by default", async () => { + const harness = await startExtension(); + const fetchStub = installFetch(); + try { + await harness.emit("session_start"); + const text = await harness.usage(); + assert.match(text, /Resets Left +1/u); + assert.deepEqual(harness.prompts, ["Reset Credits: 1 Available"]); + } finally { + fetchStub.restore(); + await harness.cleanup(); + } +}); + +test("offerResetCredits turns the reset prompt off", async () => { + const harness = await startExtension({ offerResetCredits: false }); + const fetchStub = installFetch(); + try { + await harness.emit("session_start"); + const text = await harness.usage(); + // The count still shows; only the prompt is gone. + assert.match(text, /Resets Left +1/u); + assert.deepEqual(harness.prompts, []); + } finally { + fetchStub.restore(); + await harness.cleanup(); + } +}); + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +}