From 8acd31c1bdb3fa8090ed38763e4b5f0c29d74050 Mon Sep 17 00:00:00 2001 From: Nikolay Seliverstov Date: Tue, 17 Nov 2026 01:07:01 +0300 Subject: [PATCH 1/3] feat: list every signed-in provider in /usage behind showAllProviders `/usage` reports the active provider only. A new `showAllProviders` setting in `subscription-usage.json` lists the other providers Pi is signed in to as well, each rendered as its usual block. The active provider stays first and is still forced, so its numbers are fresh; the others read the five-minute cache and share the failure backoff, so a list does not turn every `/usage` into a burst of requests. Providers without a Pi credential are skipped rather than reported as auth failures, which is what "signed in" means here. Claude has no endpoint to query, so it appears as `Waiting` once the bridge registers models in the session. The footer keeps tracking the active provider, and reset credits are still offered for the active OpenAI or Codex account only. `queryAdapterState` now returns undefined when Pi holds no credential, and the single-provider path turns that into the existing `No Pi runtime credential available` state, so nothing else changes. --- README.md | 12 ++- README.zh-CN.md | 12 ++- src/config-core.ts | 23 ++++- src/usage.ts | 88 ++++++++++++++--- test/config.test.ts | 28 +++++- test/usage-all.test.ts | 215 +++++++++++++++++++++++++++++++++++++++++ 6 files changed, 357 insertions(+), 21 deletions(-) create mode 100644 test/usage-all.test.ts diff --git a/README.md b/README.md index 69d6da7..9a14a35 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) @@ -139,6 +139,16 @@ Percentages show remaining quota by default. To show used quota instead, create Run `/reload` after changing the config file. `displayMode` applies to the footer status bar, `/usage` progress bars, and status events. +`/usage` reports the active provider only. To list every provider Pi is signed in to, add `showAllProviders` to the same file: + +```json +{ + "showAllProviders": true +} +``` + +The active provider stays first and is always fetched fresh; the others read the same five-minute cache 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, and reset credits are still offered for the active OpenAI or Codex account only. + ## Privacy and Safety - Credentials come only from Pi's own login (provider registry). The extension never reads browser cookies or other tools' credential files (for example, Grok never reads `~/.grok/auth.json`, and Claude usage comes from the bridge's responses, not Claude Code's keychain entry). diff --git a/README.zh-CN.md b/README.zh-CN.md index d3c5095..acfdb81 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) @@ -139,6 +139,16 @@ OpenAI 或 Codex 账号里有可用的限额重置券时,`/usage` 会提供使 修改配置文件后执行 `/reload` 生效。`displayMode` 同时作用于底部状态栏、`/usage` 进度条和状态事件。 +`/usage` 默认只显示当前提供商。如需列出 Pi 中所有已登录的提供商,在同一文件里加上 `showAllProviders`: + +```json +{ + "showAllProviders": true +} +``` + +当前提供商排在最前,并且总是重新查询;其余提供商使用同样的五分钟缓存,Pi 没有其凭据的提供商会直接略过。Claude 在 Claude Code 于本次会话中上报用量之前显示为 `Waiting`。底部状态栏仍然只跟踪当前提供商,重置券也仍然只对当前的 OpenAI 或 Codex 账号提供。 + ## 隐私与安全 - 仅从 Pi 自身的登录注册表读取凭据,不读取浏览器 Cookie 或其他工具的凭据文件(例如 Grok 不会读取 `~/.grok/auth.json`;Claude 用量来自 bridge 返回的数据,不读取 Claude Code 存在钥匙串里的凭据)。 diff --git a/src/config-core.ts b/src/config-core.ts index ace4e4b..8a5f342 100644 --- a/src/config-core.ts +++ b/src/config-core.ts @@ -5,15 +5,19 @@ import { export interface UsageConfig { displayMode: UsageDisplayMode; + /** `/usage` lists every signed-in provider instead of the active one. */ + showAllProviders: boolean; } export interface ParsedUsageConfig { displayMode?: UsageDisplayMode; + showAllProviders?: boolean; warning?: string; } export const DEFAULT_USAGE_CONFIG: UsageConfig = { displayMode: DEFAULT_USAGE_DISPLAY_MODE, + showAllProviders: false, }; export function resolveUsageConfig( @@ -25,6 +29,10 @@ export function resolveUsageConfig( projectConfig?.displayMode ?? globalConfig?.displayMode ?? DEFAULT_USAGE_CONFIG.displayMode, + showAllProviders: + projectConfig?.showAllProviders ?? + globalConfig?.showAllProviders ?? + DEFAULT_USAGE_CONFIG.showAllProviders, }; } @@ -32,12 +40,19 @@ 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; + 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" }; + } + return { + ...(displayMode === undefined ? {} : { displayMode }), + ...(showAllProviders === undefined ? {} : { showAllProviders }), + }; } diff --git a/src/usage.ts b/src/usage.ts index 044ed4d..7dfc4ea 100644 --- a/src/usage.ts +++ b/src/usage.ts @@ -48,6 +48,7 @@ import { adapterForProvider, queryProviderUsage, resolveUsageAuth, + SUPPORTED_ADAPTERS, UsageUnsupportedError, } from "./query.ts"; import type { @@ -82,6 +83,7 @@ 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 statusGeneration = 0; let statusController: AbortController | undefined; let statusTimer: ReturnType | undefined; @@ -182,12 +184,13 @@ 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 { + ): Promise { let auth: ResolvedUsageAuth | undefined; try { auth = await awaitWithDeadline( @@ -209,16 +212,7 @@ 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}.`, - }, - }; - } + if (!auth) return undefined; const cached = force ? undefined : cache.get(adapter.id, auth.fingerprint); if (cached) { return { @@ -305,7 +299,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 +581,52 @@ 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))?.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,8 +640,20 @@ 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) { @@ -644,6 +705,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { sessionActive = ctx.hasUI; const config = loadUsageConfig(ctx.cwd, ctx.isProjectTrusted()); displayMode = config.displayMode; + showAllProviders = config.showAllProviders; 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..fc270f3 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -8,6 +8,7 @@ import { test("uses remaining as the default display mode", () => { assert.equal(DEFAULT_USAGE_CONFIG.displayMode, "remaining"); + assert.equal(DEFAULT_USAGE_CONFIG.showAllProviders, false); assert.deepEqual(parseUsageConfig({}), {}); }); @@ -17,11 +18,11 @@ test("lets project configuration override global display mode", () => { parseUsageConfig({ displayMode: "used" }), parseUsageConfig({ displayMode: "remaining" }), ), - { displayMode: "remaining" }, + { displayMode: "remaining", showAllProviders: false }, ); assert.deepEqual( resolveUsageConfig(parseUsageConfig({ displayMode: "used" })), - { displayMode: "used" }, + { displayMode: "used", showAllProviders: false }, ); }); @@ -34,10 +35,33 @@ 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, + ); }); diff --git a/test/usage-all.test.ts b/test/usage-all.test.ts new file mode 100644 index 0000000..2cd83a3 --- /dev/null +++ b/test/usage-all.test.ts @@ -0,0 +1,215 @@ +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; + models?: object[]; +}) { + const agentDir = mkdtempSync(join(tmpdir(), "pi-usage-all-")); + process.env.PI_TEST_AGENT_DIR = agentDir; + if (options.showAllProviders !== undefined) { + writeFileSync( + join(agentDir, "subscription-usage.json"), + JSON.stringify({ showAllProviders: options.showAllProviders }), + ); + } + 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("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" }, + }); +} From b2aa4cd70adb8eda6c1561ee7fec47aee5ce2122 Mon Sep 17 00:00:00 2001 From: Nikolay Seliverstov Date: Tue, 17 Nov 2026 01:21:43 +0300 Subject: [PATCH 2/3] feat: add offerResetCredits to turn the /usage reset prompt off `/usage` asks whether to redeem a reset credit whenever the active OpenAI or Codex account has one. The new `offerResetCredits` setting, on by default, turns that question off for people who would rather not be asked: the account section still lists how many tickets are left, and redeeming needs the setting turned back on. The prompt is skipped before any provider or status work, so nothing else about `/usage` changes. --- README.md | 30 +++--- README.zh-CN.md | 30 +++--- src/config-core.ts | 13 +++ src/usage.ts | 3 + test/config.test.ts | 25 ++++- test/usage-reset-credits.test.ts | 172 +++++++++++++++++++++++++++++++ 6 files changed, 237 insertions(+), 36 deletions(-) create mode 100644 test/usage-reset-credits.test.ts diff --git a/README.md b/README.md index 9a14a35..ae4c3b1 100644 --- a/README.md +++ b/README.md @@ -121,33 +121,29 @@ 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. -```json -{ - "displayMode": "used" -} -``` - -| Value | Description | -| --- | --- | -| `"remaining"` | Show remaining quota percentage (default) | -| `"used"` | Show used quota percentage | - -Run `/reload` after changing the config file. `displayMode` applies to the footer status bar, `/usage` progress bars, and status events. - -`/usage` reports the active provider only. To list every provider Pi is signed in to, add `showAllProviders` to the same file: +| 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 | ```json { - "showAllProviders": true + "displayMode": "used", + "showAllProviders": true, + "offerResetCredits": false } ``` -The active provider stays first and is always fetched fresh; the others read the same five-minute cache 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, and reset credits are still offered for the active OpenAI or Codex account only. +With `showAllProviders`, the active provider stays first and is always fetched fresh; the others read the same five-minute cache 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. + +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 acfdb81..d36b1f6 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -121,33 +121,29 @@ 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` 生效。 -```json -{ - "displayMode": "used" -} -``` - -| 配置值 | 说明 | -| --- | --- | -| `"remaining"` | 显示剩余额度百分比(默认) | -| `"used"` | 显示已用额度百分比 | - -修改配置文件后执行 `/reload` 生效。`displayMode` 同时作用于底部状态栏、`/usage` 进度条和状态事件。 - -`/usage` 默认只显示当前提供商。如需列出 Pi 中所有已登录的提供商,在同一文件里加上 `showAllProviders`: +| 配置项 | 取值 | 说明 | +| --- | --- | --- | +| `displayMode` | `"remaining"`(默认)或 `"used"` | 百分比显示剩余额度还是已用额度,作用于底部状态栏、`/usage` 进度条和状态事件 | +| `showAllProviders` | `true` 或 `false`(默认) | `/usage` 列出所有已登录的提供商,而不只是当前提供商 | +| `offerResetCredits` | `true`(默认)或 `false` | 当前 OpenAI 或 Codex 账号有重置券时,`/usage` 是否询问是否使用一张 | ```json { - "showAllProviders": true + "displayMode": "used", + "showAllProviders": true, + "offerResetCredits": false } ``` -当前提供商排在最前,并且总是重新查询;其余提供商使用同样的五分钟缓存,Pi 没有其凭据的提供商会直接略过。Claude 在 Claude Code 于本次会话中上报用量之前显示为 `Waiting`。底部状态栏仍然只跟踪当前提供商,重置券也仍然只对当前的 OpenAI 或 Codex 账号提供。 +开启 `showAllProviders` 后,当前提供商排在最前并总是重新查询;其余提供商使用同样的五分钟缓存,Pi 没有其凭据的提供商会直接略过。Claude 在 Claude Code 于本次会话中上报用量之前显示为 `Waiting`。底部状态栏仍然只跟踪当前提供商。 + +`offerResetCredits` 设为 `false` 时,`/usage` 仍会显示账号上有几张重置券,但不再询问是否使用;需要使用重置券时把该配置改回 `true`。 ## 隐私与安全 diff --git a/src/config-core.ts b/src/config-core.ts index 8a5f342..940f17e 100644 --- a/src/config-core.ts +++ b/src/config-core.ts @@ -7,17 +7,21 @@ 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; } export interface ParsedUsageConfig { displayMode?: UsageDisplayMode; showAllProviders?: boolean; + offerResetCredits?: boolean; warning?: string; } export const DEFAULT_USAGE_CONFIG: UsageConfig = { displayMode: DEFAULT_USAGE_DISPLAY_MODE, showAllProviders: false, + offerResetCredits: true, }; export function resolveUsageConfig( @@ -33,6 +37,10 @@ export function resolveUsageConfig( projectConfig?.showAllProviders ?? globalConfig?.showAllProviders ?? DEFAULT_USAGE_CONFIG.showAllProviders, + offerResetCredits: + projectConfig?.offerResetCredits ?? + globalConfig?.offerResetCredits ?? + DEFAULT_USAGE_CONFIG.offerResetCredits, }; } @@ -43,6 +51,7 @@ export function parseUsageConfig(value: unknown): ParsedUsageConfig { const record = value as Record; const displayMode = record.displayMode; const showAllProviders = record.showAllProviders; + const offerResetCredits = record.offerResetCredits; if (displayMode !== undefined && displayMode !== "remaining" && displayMode !== "used") { return { warning: 'displayMode must be either "remaining" or "used"', @@ -51,8 +60,12 @@ export function parseUsageConfig(value: unknown): ParsedUsageConfig { 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" }; + } return { ...(displayMode === undefined ? {} : { displayMode }), ...(showAllProviders === undefined ? {} : { showAllProviders }), + ...(offerResetCredits === undefined ? {} : { offerResetCredits }), }; } diff --git a/src/usage.ts b/src/usage.ts index 7dfc4ea..4bf7afa 100644 --- a/src/usage.ts +++ b/src/usage.ts @@ -84,6 +84,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { let sessionActive = false; let displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE; let showAllProviders = false; + let offerResetCredits = true; let statusGeneration = 0; let statusController: AbortController | undefined; let statusTimer: ReturnType | undefined; @@ -660,6 +661,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { publishStatus(ctx, current.outcome, current.model, sessionActive); } if ( + !offerResetCredits || ![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") || current.outcome.state.status !== "ready" ) { @@ -706,6 +708,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { const config = loadUsageConfig(ctx.cwd, ctx.isProjectTrusted()); displayMode = config.displayMode; showAllProviders = config.showAllProviders; + offerResetCredits = config.offerResetCredits; 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 fc270f3..72f773a 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -9,6 +9,7 @@ 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.deepEqual(parseUsageConfig({}), {}); }); @@ -18,11 +19,11 @@ test("lets project configuration override global display mode", () => { parseUsageConfig({ displayMode: "used" }), parseUsageConfig({ displayMode: "remaining" }), ), - { displayMode: "remaining", showAllProviders: false }, + { displayMode: "remaining", showAllProviders: false, offerResetCredits: true }, ); assert.deepEqual( resolveUsageConfig(parseUsageConfig({ displayMode: "used" })), - { displayMode: "used", showAllProviders: false }, + { displayMode: "used", showAllProviders: false, offerResetCredits: true }, ); }); @@ -64,4 +65,24 @@ test("rejects invalid usage configuration", () => { parseUsageConfig({ showAllProviders: "yes" }).warning ?? "", /showAllProviders must be true or false/u, ); + assert.match( + parseUsageConfig({ offerResetCredits: "no" }).warning ?? "", + /offerResetCredits must be true or false/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, + ); }); 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" }, + }); +} From e623a3ed438116cb8efc742235a3495a078f23e8 Mon Sep 17 00:00:00 2001 From: Nikolay Seliverstov Date: Tue, 17 Nov 2026 01:31:21 +0300 Subject: [PATCH 3/3] feat: add showAllProvidersCacheMinutes to set the list cache window The providers after the active one in `/usage` reused a fixed five-minute cache. `showAllProvidersCacheMinutes` sets that window in minutes, five by default; `0` fetches every time. The footer keeps its own five-minute refresh, so the setting only changes how stale the list may be. The cache accepts a per-read window now and keeps entries as long as the longest window anyone asks for. --- README.md | 6 ++++-- README.zh-CN.md | 6 ++++-- src/config-core.ts | 23 +++++++++++++++++++++++ src/core.ts | 15 +++++++++++++-- src/usage.ts | 20 ++++++++++++++++++-- test/config.test.ts | 42 ++++++++++++++++++++++++++++++++++++++++-- test/usage-all.test.ts | 31 ++++++++++++++++++++++++++++++- 7 files changed, 132 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index ae4c3b1..af67a81 100644 --- a/README.md +++ b/README.md @@ -132,16 +132,18 @@ Create `~/.pi/agent/subscription-usage.json` (global) or `.pi/subscription-usage | `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", "showAllProviders": true, - "offerResetCredits": false + "offerResetCredits": false, + "showAllProvidersCacheMinutes": 10 } ``` -With `showAllProviders`, the active provider stays first and is always fetched fresh; the others read the same five-minute cache 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. +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. 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. diff --git a/README.zh-CN.md b/README.zh-CN.md index d36b1f6..46654d0 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -132,16 +132,18 @@ OpenAI 或 Codex 账号里有可用的限额重置券时,`/usage` 会提供使 | `displayMode` | `"remaining"`(默认)或 `"used"` | 百分比显示剩余额度还是已用额度,作用于底部状态栏、`/usage` 进度条和状态事件 | | `showAllProviders` | `true` 或 `false`(默认) | `/usage` 列出所有已登录的提供商,而不只是当前提供商 | | `offerResetCredits` | `true`(默认)或 `false` | 当前 OpenAI 或 Codex 账号有重置券时,`/usage` 是否询问是否使用一张 | +| `showAllProvidersCacheMinutes` | 默认 `5` | `/usage` 列表里其他提供商的报告复用多久;`0` 表示每次都重新查询 | ```json { "displayMode": "used", "showAllProviders": true, - "offerResetCredits": false + "offerResetCredits": false, + "showAllProvidersCacheMinutes": 10 } ``` -开启 `showAllProviders` 后,当前提供商排在最前并总是重新查询;其余提供商使用同样的五分钟缓存,Pi 没有其凭据的提供商会直接略过。Claude 在 Claude Code 于本次会话中上报用量之前显示为 `Waiting`。底部状态栏仍然只跟踪当前提供商。 +开启 `showAllProviders` 后,当前提供商排在最前并总是重新查询;其余提供商的报告按 `showAllProvidersCacheMinutes` 分钟复用,Pi 没有其凭据的提供商会直接略过。底部状态栏仍按自己的五分钟节奏刷新。Claude 在 Claude Code 于本次会话中上报用量之前显示为 `Waiting`。底部状态栏仍然只跟踪当前提供商。 `offerResetCredits` 设为 `false` 时,`/usage` 仍会显示账号上有几张重置券,但不再询问是否使用;需要使用重置券时把该配置改回 `true`。 diff --git a/src/config-core.ts b/src/config-core.ts index 940f17e..2f5ad25 100644 --- a/src/config-core.ts +++ b/src/config-core.ts @@ -9,12 +9,15 @@ export interface UsageConfig { 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; } @@ -22,6 +25,7 @@ export const DEFAULT_USAGE_CONFIG: UsageConfig = { displayMode: DEFAULT_USAGE_DISPLAY_MODE, showAllProviders: false, offerResetCredits: true, + showAllProvidersCacheMinutes: 5, }; export function resolveUsageConfig( @@ -41,6 +45,10 @@ export function resolveUsageConfig( projectConfig?.offerResetCredits ?? globalConfig?.offerResetCredits ?? DEFAULT_USAGE_CONFIG.offerResetCredits, + showAllProvidersCacheMinutes: + projectConfig?.showAllProvidersCacheMinutes ?? + globalConfig?.showAllProvidersCacheMinutes ?? + DEFAULT_USAGE_CONFIG.showAllProvidersCacheMinutes, }; } @@ -52,6 +60,7 @@ export function parseUsageConfig(value: unknown): ParsedUsageConfig { 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"', @@ -63,9 +72,23 @@ export function parseUsageConfig(value: unknown): ParsedUsageConfig { 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 4bf7afa..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, @@ -85,6 +86,8 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { 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; @@ -191,6 +194,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { adapter: UsageProviderAdapter, force: boolean, signal: AbortSignal, + maxAgeMs?: number, ): Promise { let auth: ResolvedUsageAuth | undefined; try { @@ -214,7 +218,9 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { }; } if (!auth) return undefined; - const cached = force ? undefined : cache.get(adapter.id, auth.fingerprint); + const cached = force + ? undefined + : cache.get(adapter.id, auth.fingerprint, Date.now(), maxAgeMs); if (cached) { return { state: { @@ -596,7 +602,15 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { (adapter) => adapter.id !== active.providerId, ).map(async (adapter) => { try { - return (await queryAdapterState(ctx, adapter, false, signal))?.state; + return ( + await queryAdapterState( + ctx, + adapter, + false, + signal, + showAllProvidersCacheMs, + ) + )?.state; } catch (error) { if (isAbortError(error) || !sessionActive) throw error; return { @@ -709,6 +723,8 @@ export default function subscriptionUsage(pi: ExtensionAPI): void { 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 72f773a..24d49dd 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -10,6 +10,7 @@ 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({}), {}); }); @@ -19,11 +20,21 @@ test("lets project configuration override global display mode", () => { parseUsageConfig({ displayMode: "used" }), parseUsageConfig({ displayMode: "remaining" }), ), - { displayMode: "remaining", showAllProviders: false, offerResetCredits: true }, + { + displayMode: "remaining", + showAllProviders: false, + offerResetCredits: true, + showAllProvidersCacheMinutes: 5, + }, ); assert.deepEqual( resolveUsageConfig(parseUsageConfig({ displayMode: "used" })), - { displayMode: "used", showAllProviders: false, offerResetCredits: true }, + { + displayMode: "used", + showAllProviders: false, + offerResetCredits: true, + showAllProvidersCacheMinutes: 5, + }, ); }); @@ -69,6 +80,14 @@ test("rejects invalid usage configuration", () => { 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", () => { @@ -86,3 +105,22 @@ test("offers reset credits unless offerResetCredits is off", () => { 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 index 2cd83a3..53bfb8a 100644 --- a/test/usage-all.test.ts +++ b/test/usage-all.test.ts @@ -43,14 +43,22 @@ const SECOND_USAGE = { 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({ showAllProviders: options.showAllProviders }), + JSON.stringify(config), ); } const { default: extension } = await import("../src/usage.ts"); @@ -190,6 +198,27 @@ test("/usage reuses the cache for providers other than the active one", async () } }); +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,