Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(usage): 让 Pi SuperGrok 订阅轮显示 token 价值估算 (#3061)

Dash99d67e111494
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 782d1e7584..7d81b97376 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -917,6 +917,19 @@ describe('maker:event hot path ordering', () => {
expect(claudeDoneSource).toContain('const rawDelta = Math.max(0, cumulative - prevReportedCost);');
});
+ it('pi subscription turns estimate value from the shared reference-price helper', () => {
+ const wireSessionSource = extractWireSessionSource();
+ const piDoneIndex = wireSessionSource.indexOf("event.type === 'done' && event.source === 'pi'");
+ expect(piDoneIndex).toBeGreaterThanOrEqual(0);
+ const piDoneSource = wireSessionSource.slice(piDoneIndex);
+ expect(piDoneSource).toContain('const pricing = isCustomProviderRoute');
+ expect(piDoneSource).toContain('? getReferenceModelPricing()');
+ expect(piDoneSource).toContain("getSubscriptionValuePriceFor('pi', pricingModel, pricing)");
+ expect(piDoneSource).not.toMatch(/getModelPriceQuote\(\s*null\s*,\s*effectiveProvider/);
+ expect(piDoneSource).toContain('if (!isSubscriptionValue)');
+ expect(piDoneSource).toContain('await recordSchedulerTurnCost({');
+ });
+
it('refreshes Claude credential cache before dropping mismatched header snapshots', () => {
const listenerSource = usageSource.match(
/setClaudeRateLimitHeadersListener\(\(snapshot, requestBearerToken\) => \{[\s\S]*?\n {2}\}\);/,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 57ef93e70c..1ba15182de 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -492,6 +492,7 @@ import {
claudeSubscriptionUsageModelKey,
codexApiUsageModelKey,
codexSubscriptionUsageModelKey,
+ getSubscriptionValuePriceFor,
piSubscriptionUsageModelKey,
} from '../usage/usageHistory.js';
import {
@@ -5094,20 +5095,19 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 自定义(source:'user')provider——本地 Ollama / 用户自付费兼容端点——即便
// 模型 id 与 XD 目录重名,也不能套用 XD 网关定价当作 Cindy 消费入账;只记 token
// (上方已入库),不写 money(codex review)。仅 xd / 默认网关与订阅路由计费。
- const pricing =
- isSubscriptionValue || isCustomProviderRoute
- ? null
+ // 订阅估值必须走参考价目录 + getSubscriptionValuePriceFor,与仪表盘同口径:
+ // 裸 grok-4.6 会先映射到 xai/grok-4.6。旧实现把 catalog 置 null 再
+ // getModelPriceQuote(null, 'xai', 'grok-4.6'),报价永远 miss,消息上就只剩用量。
+ const pricing = isCustomProviderRoute
+ ? null
+ : isSubscriptionValue
+ ? getReferenceModelPricing()
: await getGatewayModelPricingForModel();
- const price =
- isCustomProviderRoute
- ? null
- : effectiveProvider === 'openai' ||
- effectiveProvider === 'anthropic' ||
- effectiveProvider === 'xai'
- ? getModelPriceQuote(null, effectiveProvider, pricingModel)
- : isSubscriptionDirectRoute(pricingModel)
- ? getSubscriptionDirectValuePrice(pricingModel)
- : getModelPriceQuote(pricing, 'xd', pricingModel);
+ const price = isCustomProviderRoute
+ ? null
+ : isSubscriptionValue
+ ? getSubscriptionValuePriceFor('pi', pricingModel, pricing)
+ : getModelPriceQuote(pricing, 'xd', pricingModel);
const money = computePriceQuoteTurnMoney(
tokens,
price ?? undefined,
@@ -5116,7 +5116,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
if (money && money.amount > 0) {
if (!isSubscriptionValue) {
// token 已在上方入库;这里只补真实 API/gateway 费用,
- // 避免重复累加 token。订阅价值则由 #billing=subscription 读时估算。
+ // 避免重复累加 token。订阅价值挂到消息(value-estimate),不进 daily_spend。
await recordModelTurnUsage({
agentKind: 'pi',
model: modelUsageKey,
diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
index 9a3eff629b..d243b915f1 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
@@ -54,7 +54,7 @@ vi.mock('../../secrets/providerSecretStore', () => ({
}));
import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
-import { providerReferencePriceQuote } from '../../../shared/modelPriceQuote';
+import { modelPricingKey, providerReferencePriceQuote } from '../../../shared/modelPriceQuote';
import { getActiveCatalog } from '../../maker-host/active-catalog';
import {
applyModelPriceOverrides,
@@ -575,6 +575,62 @@ describe('reference pricing helpers', () => {
modelId: 'chatgpt/gpt-5.5',
source: 'subscription-reference',
});
+ // Pi SuperGrok 目录 id 是裸 grok-*,报价户口是 xai/grok-*。两条都要能取到参考价,
+ // 否则消息 tooltip 会落到「本轮费用暂不可用」。
+ expect(getSubscriptionDirectValuePrice('grok-4.6')).toMatchObject({
+ providerId: 'xai',
+ modelId: 'grok-4.6',
+ source: 'subscription-reference',
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.5,
+ });
+ expect(getSubscriptionDirectValuePrice('xai/grok-4.6')).toMatchObject({
+ providerId: 'xai',
+ modelId: 'xai/grok-4.6',
+ source: 'subscription-reference',
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.5,
+ });
+ expect(
+ getSubscriptionDirectValuePrice('grok-4.6', 'pi', {
+ xai: {
+ [modelPricingKey('grok-4.6', 'pi')]: {
+ providerId: 'xai',
+ modelId: 'grok-4.6',
+ currency: 'USD',
+ source: 'user-override',
+ approximate: true,
+ inputPerMtok: 9,
+ outputPerMtok: 27,
+ },
+ },
+ }),
+ ).toMatchObject({
+ modelId: 'grok-4.6',
+ source: 'user-override',
+ inputPerMtok: 9,
+ outputPerMtok: 27,
+ });
+ expect(
+ getSubscriptionDirectValuePrice('grok-4.6', undefined, {
+ xai: {
+ [modelPricingKey('grok-4.6', 'pi')]: {
+ providerId: 'xai',
+ modelId: 'grok-4.6',
+ currency: 'USD',
+ source: 'user-override',
+ approximate: true,
+ inputPerMtok: 9,
+ outputPerMtok: 27,
+ },
+ },
+ }),
+ ).toMatchObject({
+ source: 'subscription-reference',
+ inputPerMtok: 2,
+ });
expect(
getSubscriptionDirectValuePrice('chatgpt/gpt-5.5', 'claude-code', {
openai: {
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
index 87d1215bab..49c464ebeb 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
@@ -263,6 +263,33 @@ describe('computePriceQuoteTurnMoney', () => {
).toEqual(['reference-price']);
}
});
+
+ it('estimates SuperGrok token value from xAI reference prices including cache reads',
+ () => {
+ const money = computePriceQuoteTurnMoney(
+ {
+ inputTokens: 179_300,
+ outputTokens: 9_300,
+ cacheReadTokens: 1_600_000,
+ cacheCreateTokens: 0,
+ },
+ quote('grok-4.6', 2, 6, {
+ providerId: 'xai',
+ source: 'subscription-reference',
+ approximate: true,
+ cacheReadPerMtok: 0.5,
+ }),
+ 'USD',
+ );
+ // 179.3k * $2 + 9.3k * $6 + 1.6M * $0.50 = $0.3586 + $0.0558 + $0.80
+ expect(money).toMatchObject({
+ amount: 1.2144,
+ currency: 'USD',
+ approximate: true,
+ kind: 'value-estimate',
+ });
+ expect(money?.estimateReasons).toEqual(['subscription-value', 'reference-price']);
+ });
});
describe('resolveTurnCost', () => {
diff --git a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
index 9d4919f32a..e1846e64ac 100644
--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
@@ -74,16 +74,17 @@ vi.mock('../referenceModelPricing', () => ({
outputPerMtok: 10,
}
: undefined,
- getSubscriptionDirectValuePrice: (model: string) =>
- model === 'xai/grok-4.3'
+ getSubscriptionDirectValuePrice: (model: string, agent?: string) =>
+ model === 'xai/grok-4.3' || (model === 'grok-4.6' && agent === 'pi')
? {
providerId: 'xai',
modelId: model,
currency: 'USD',
source: 'subscription-reference',
approximate: true,
- inputPerMtok: 3,
- outputPerMtok: 15,
+ inputPerMtok: model === 'grok-4.6' ? 2 : 3,
+ outputPerMtok: model === 'grok-4.6' ? 6 : 15,
+ cacheReadPerMtok: model === 'grok-4.6' ? 0.5 : undefined,
}
: undefined,
}));
@@ -109,6 +110,7 @@ import {
computeAnomaly,
computeStreaks,
emptyUsageHistoryPayload,
+ getSubscriptionValuePriceFor,
piSubscriptionUsageModelKey,
prevDayKey,
readUsageHistory,
@@ -297,6 +299,18 @@ describe('billing model keys', () => {
});
});
+describe('getSubscriptionValuePriceFor', () => {
+ it('routes Pi exclusive Grok ids through the subscription-direct quote', () => {
+ expect(getSubscriptionValuePriceFor('pi', 'grok-4.6', null)).toMatchObject({
+ providerId: 'xai',
+ modelId: 'grok-4.6',
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0.5,
+ });
+ });
+});
+
describe('readUsageHistoryWith', () => {
it('aggregates actual money and subscription value without double counting', async () => {
const estimateAmount = regionalUsdAmount(2);
@@ -565,6 +579,29 @@ describe('readUsageHistoryWith', () => {
expect(result.totals.todayTokens).toBe(1_002_000);
});
+ it('estimates Pi SuperGrok subscription value for exclusive grok ids', async () => {
+ const result = await readUsageHistoryWith(makeDeps({
+ getModelUsageSince: async () => [
+ modelRow(
+ TODAY,
+ 'pi',
+ piSubscriptionUsageModelKey('grok-4.6'),
+ actual(0),
+ { inputTokens: 179_300, outputTokens: 9_300, cacheReadTokens: 1_600_000 },
+ ),
+ ],
+ }));
+
+ expect(result.models[0]).toMatchObject({
+ agentKind: 'pi',
+ model: 'grok-4.6',
+ inputTokens: 179_300,
+ cacheReadTokens: 1_600_000,
+ });
+ // 179.3k * $2 + 9.3k * $6 + 1.6M * $0.50 = $1.2144
+ expect(result.models[0].estimatedMoney?.amount).toBeCloseTo(1.2144, 6);
+ });
+
it('marks estimates pending only when a subscription price is missing during refresh', async () => {
const row = modelRow(
TODAY,
diff --git a/apps/desktop/src/main/usage/referenceModelPricing.ts b/apps/desktop/src/main/usage/referenceModelPricing.ts
index fc6afe4c98..6877e624e7 100644
--- a/apps/desktop/src/main/usage/referenceModelPricing.ts
+++ b/apps/desktop/src/main/usage/referenceModelPricing.ts
@@ -6,6 +6,7 @@
*/
import { BrowserWindow } from 'electron';
+import type { AgentKind } from '@cindy/model-providers';
import {
getModelPriceQuote,
@@ -117,7 +118,7 @@ export function getClaudeSubscriptionValuePrice(
export function getSubscriptionDirectValuePrice(
modelId: string,
- agent?: 'claude-code' | 'codex',
+ agent?: AgentKind,
pricing?: ModelPricingCatalog | null,
at?: string | Date,
overrides?: ModelPriceOverridesSnapshot,
diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.ts
index f0b3cbf255..d273bc2fea 100644
--- a/apps/desktop/src/main/usage/usageHistory.ts
+++ b/apps/desktop/src/main/usage/usageHistory.ts
@@ -363,12 +363,13 @@ export function piSubscriptionUsageModelKey(model: string): string {
* - codex → 订阅直连(chatgpt/ / xai/)registry 参考价 → OpenAI registry 参考价
* → Anthropic registry 参考价(Codex 显式选内置 anthropic 的 Claude.ai 订阅轮;
* 模型 id 只会命中各自 provider 的路由,依次尝试不会串价)
- * - pi → 先按订阅直连估价,再依次回退 Codex(OpenAI)与 Anthropic registry 参考价
+ * - pi → 先按订阅直连估价(agent=pi,才能命中设置里的 Pi 价格覆盖),
+ * 再依次回退 Codex(OpenAI)与 Anthropic registry 参考价
* (Pi 可跨三类 provider,按模型 id 路由,依次尝试不会串价)
* - claude-code → Anthropic registry 参考价
* 各级都 miss → undefined(该行只显示 token,不臆造金额)。
*/
-function getSubscriptionValuePriceFor(
+export function getSubscriptionValuePriceFor(
agentKind: 'claude-code' | 'codex' | 'pi',
model: string,
pricing: ModelPricingMap | null,
@@ -384,7 +385,7 @@ function getSubscriptionValuePriceFor(
}
if (agentKind === 'pi') {
return (
- getSubscriptionDirectValuePrice(model, undefined, pricing, at, overrides) ??
+ getSubscriptionDirectValuePrice(model, 'pi', pricing, at, overrides) ??
getCodexSubscriptionValuePrice(model, pricing, at, overrides) ??
getClaudeSubscriptionValuePrice(model, pricing, at, overrides)
);