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(desktop): preserve model pricing during startup (#672)

JiangJiahao5433693fc1b9
diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.ts
index e67a83c0fc..b3d6368cd3 100644
--- a/apps/desktop/src/main/model-access/index.ts
+++ b/apps/desktop/src/main/model-access/index.ts
@@ -140,11 +140,14 @@ let modelsSyncRerunQueued = false;
let authGeneration = 0;
let lastAuthUserId: string | null = null;
-function applyGatewayModels(models: ModelAccessGatewayModel[]): void {
+function applyGatewayModels(
+ models: ModelAccessGatewayModel[],
+ authenticatedUserId?: string,
+): void {
// 同一次 /models 响应先建立 provider-scoped 价格投影,再做仅影响展示元数据的
// dev overlay。空成功响应会同时清空模型和价格;请求失败不会调用本函数,
// 因而保留上一份完整成功快照。
- const pricing = replaceGatewayModelPricing(models);
+ const pricing = replaceGatewayModelPricing(models, authenticatedUserId);
// 分母只算会产生报价的条目:免费/无价条目按设计不出报价,不该把健康目录
// 也报成覆盖不足。此时覆盖缺口只剩一种成因——币种声明与目录冲突被丢弃,
// 这在 #587 之前是全程静默的,这行日志让现场可判。
@@ -166,7 +169,10 @@ function applyGatewayModels(models: ModelAccessGatewayModel[]): void {
setXdGatewayModels(effective);
}
-async function runModelsSync(myGen: number): Promise<void> {
+async function runModelsSync(
+ myGen: number,
+ authenticatedUserId: string,
+): Promise<void> {
let payload: { models: ModelAccessGatewayModel[] };
try {
payload = await serverApiFetch<{ models: ModelAccessGatewayModel[] }>(MODELS_PATH, {
@@ -182,16 +188,24 @@ async function runModelsSync(myGen: number): Promise<void> {
const models = (payload.models ?? []).filter((m) => typeof m?.id === 'string' && m.id);
if (models.length === 0) {
log.warn('xd gateway models fetch returned empty list; clearing current list');
- applyGatewayModels([]);
+ applyGatewayModels([], authenticatedUserId);
return;
}
log.info(`xd gateway models synced: ${models.length}`);
- applyGatewayModels(models);
+ applyGatewayModels(models, authenticatedUserId);
}
/** 触发一次模型目录同步(同世代 single-flight;旧世代在途时为新账号排队补发)。 */
function scheduleModelsSync(): void {
const gen = authGeneration;
+ // localDb takeover and /models run independently during startup. Capture the
+ // authenticated owner here instead of asking localDb who owns the cache only
+ // after the network response arrives.
+ const authenticatedUserId = lastAuthUserId;
+ if (!authenticatedUserId) {
+ log.warn('xd gateway models sync skipped: authenticated user id unavailable');
+ return;
+ }
if (modelsSyncInflight) {
if (modelsSyncGen === gen) return; // 同账号在途,复用
if (!modelsSyncRerunQueued) {
@@ -205,7 +219,7 @@ function scheduleModelsSync(): void {
return;
}
modelsSyncGen = gen;
- modelsSyncInflight = runModelsSync(gen)
+ modelsSyncInflight = runModelsSync(gen, authenticatedUserId)
.catch((err) => {
log.warn('xd gateway models sync threw', {
error: err instanceof Error ? err.message : String(err),
diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
index a6b41d80c1..5a61997f5b 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
@@ -250,6 +250,31 @@ describe('pricing cache lifecycle', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
+ it('persists a startup snapshot under the authenticated user before localDb is ready', async () => {
+ mocks.getCurrentDbClientUserId.mockReturnValue(null);
+ const pricing = replaceGatewayModelPricing(
+ [
+ {
+ id: 'early-model',
+ inputCostPerToken: 0.000001,
+ outputCostPerToken: 0.000002,
+ },
+ ],
+ 'user-a',
+ );
+
+ await vi.waitFor(async () => {
+ const raw = JSON.parse(await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'));
+ expect(raw).toMatchObject({
+ scope: expectedScope('user-a'),
+ pricing,
+ });
+ });
+
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-a');
+ await expect(getModelPricing()).resolves.toEqual(pricing);
+ });
+
it('does not hydrate another account pricing snapshot', async () => {
await mkdir(userDataPath('cache'), { recursive: true });
await writeFile(
diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.ts
index 5e021d1ffe..493f1d98f2 100644
--- a/apps/desktop/src/main/usage/modelPricing.ts
+++ b/apps/desktop/src/main/usage/modelPricing.ts
@@ -66,12 +66,12 @@ function currentKeyCacheIdentity(): string {
}
}
-function currentScope(): string {
+function currentScope(userId?: string): string {
return [
'v1',
`region=${CURRENT_CINDY_REGION}`,
`base=${getClientEndpoint('modelAccessApiBaseUrl').trim()}`,
- `user=${getCurrentDbClientUserId() ?? 'anonymous'}`,
+ `user=${userId ?? getCurrentDbClientUserId() ?? 'anonymous'}`,
currentKeyCacheIdentity(),
].join('|');
}
@@ -222,8 +222,13 @@ function broadcastPricing(pricing: ModelPricingCatalog | null): void {
*/
export function replaceGatewayModelPricing(
models: readonly ModelAccessGatewayModel[],
+ authenticatedUserId?: string,
): ModelPricingCatalog {
- const scope = currentScope();
+ // /models can finish a few milliseconds before localDb takeover has exposed
+ // its user through getCurrentDbClientUserId(). The model-access caller
+ // therefore passes the authenticated user captured when the request starts,
+ // so a valid startup snapshot is never persisted under `anonymous`.
+ const scope = currentScope(authenticatedUserId);
const pricing = gatewayPricingCatalog(models);
cache = pricing;
cacheScope = scope;
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useModelPricing.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useModelPricing.test.ts
new file mode 100644
index 0000000000..031bcdb53f
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useModelPricing.test.ts
@@ -0,0 +1,71 @@
+// @vitest-environment jsdom
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ModelPricingCatalog } from '../../../shared/regionalMoney';
+
+type PricingListener = (pricing: ModelPricingCatalog | null) => void;
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((next) => {
+ resolve = next;
+ });
+ return { promise, resolve };
+}
+
+let useModelPricing: typeof import('../useModelPricing').useModelPricing;
+
+describe('useModelPricing', () => {
+ beforeEach(async () => {
+ vi.resetModules();
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+ ({ useModelPricing } = await import('../useModelPricing'));
+ });
+
+ it('does not let a stale initial IPC result overwrite a newer pricing push', async () => {
+ const initialRead = deferred<ModelPricingCatalog | null>();
+ const listeners = new Set<PricingListener>();
+ const usage = {
+ getModelPricing: vi.fn(() => initialRead.promise),
+ onModelPricingChanged: vi.fn((listener: PricingListener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ }),
+ };
+ (
+ window as unknown as {
+ electronAPI: { maker: { usage: typeof usage } };
+ }
+ ).electronAPI = { maker: { usage } };
+ const pricing: ModelPricingCatalog = {
+ xd: {
+ 'early-model': {
+ providerId: 'xd',
+ modelId: 'early-model',
+ currency: 'CNY',
+ source: 'gateway',
+ approximate: false,
+ inputPerMtok: 1,
+ outputPerMtok: 2,
+ },
+ },
+ };
+
+ const hook = renderHook(() => useModelPricing());
+ await waitFor(() => expect(listeners.size).toBe(1));
+
+ act(() => {
+ for (const listener of listeners) listener(pricing);
+ });
+ expect(hook.result.current).toEqual(pricing);
+
+ await act(async () => {
+ initialRead.resolve(null);
+ await initialRead.promise;
+ });
+
+ expect(hook.result.current).toEqual(pricing);
+ expect(usage.getModelPricing).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/useModelPricing.ts b/apps/desktop/src/renderer/hooks/useModelPricing.ts
index 1e4bc98f1f..60a432875c 100644
--- a/apps/desktop/src/renderer/hooks/useModelPricing.ts
+++ b/apps/desktop/src/renderer/hooks/useModelPricing.ts
@@ -10,6 +10,7 @@ import type {
let cache: ModelPricingCatalog | null = null;
let cacheLoaded = false;
let inflight: Promise<ModelPricingCatalog | null> | null = null;
+let cacheRevision = 0;
function isNonNegativeFinite(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value) && value >= 0;
@@ -54,14 +55,20 @@ function isValidCatalog(v: unknown): v is ModelPricingCatalog {
function load(): Promise<ModelPricingCatalog | null> {
if (cacheLoaded) return Promise.resolve(cache);
if (!inflight) {
+ const revisionAtStart = cacheRevision;
inflight = window.electronAPI.maker.usage
.getModelPricing()
.then((res) => {
+ // A push received after this read started is newer than its snapshot.
+ // Keep the pushed value instead of letting a stale startup `null`
+ // remove prices until the next application restart.
+ if (cacheRevision !== revisionAtStart) return cache;
cacheLoaded = true;
cache = isValidCatalog(res) ? res : null;
return cache;
})
.catch(() => {
+ if (cacheRevision !== revisionAtStart) return cache;
cacheLoaded = true;
cache = null;
return null;
@@ -80,6 +87,7 @@ export function useModelPricing(): ModelPricingCatalog | null {
let active = true;
const unsubscribe =
window.electronAPI.maker.usage.onModelPricingChanged((next) => {
+ cacheRevision += 1;
cacheLoaded = true;
cache = isValidCatalog(next) ? next : null;
if (active) setPricing(cache);