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(media): 修复媒体计费响应与账号生命周期

liugaowei1f29cdca7484
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 75a66859a1..4d2a2c13e1 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -567,6 +567,7 @@ import { createXaiImageChannel } from './xaiImageClient.js';
import {
getCindyProxyMediaService,
getCindyVideoProviderRegistry,
+ withCindyMediaBillingSession,
} from '../mcp-integrations/cindyProxyMedia.js';
import { getCindyProxySearchService } from '../mcp-integrations/cindyProxySearch.js';
import { normalizeImageParameters } from '../cindy-media/imageParameters.js';
@@ -8416,7 +8417,11 @@ export function registerGhostIpc(): void {
}
// cindy-request = 请 Cindy 本体代办;旧名 model-request 静默兼容(更名前的老包)。
if (type === 'cindy-request' || type === 'model-request') {
- return getGhostCindySlot().handleModelRequest(id, payload);
+ const callId = (payload as { callId?: unknown } | null)?.callId;
+ const sessionId = getPluginTaskSourceSessionId(id, typeof callId === 'string' ? callId : undefined);
+ return withCindyMediaBillingSession(sessionId, () =>
+ getGhostCindySlot().handleModelRequest(id, payload),
+ );
}
// fetch-request = network 槽代理 HTTP(invoke 返回值即响应,机制同上)。
if (type === 'download-request') return pluginDownloads.handle(id, payload, () => !event.sender.isDestroyed() && ghostIdForLogicWebContents(event.sender.id) === id);
diff --git a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
index ca4b4ccb2e..34b6cf68c5 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
@@ -32,6 +32,7 @@ const mocks = vi.hoisted(() => ({
outboundFetch: vi.fn(),
prepareBilling: vi.fn(),
recordBilling: vi.fn<(response: Response) => Promise<void>>(async () => undefined),
+ finishBilling: vi.fn(),
guardedOutboundFetch: vi.fn(),
release: vi.fn(async () => undefined),
confirm: vi.fn<(input: { reasons: string[] }) => Promise<boolean>>(async () => true),
@@ -261,8 +262,11 @@ async function prepare(capability: MediaCapability = 'image.generate'): Promise<
describe('Cindy Core media invocation state and security boundary', () => {
beforeEach(() => {
- mocks.recordBilling.mockClear();
- mocks.prepareBilling.mockReset().mockResolvedValue(mocks.recordBilling);
+ mocks.recordBilling.mockReset().mockResolvedValue(undefined);
+ mocks.finishBilling.mockReset();
+ mocks.prepareBilling.mockReset().mockResolvedValue(
+ Object.assign(mocks.recordBilling, { finish: mocks.finishBilling }),
+ );
mocks.failRequestLog = false;
mocks.confirm.mockReset().mockResolvedValue(true);
mocks.currentUserId = `media-user-${crypto.randomUUID()}`;
@@ -626,6 +630,43 @@ describe('Cindy Core media invocation state and security boundary', () => {
await callCindyMedia({ action: 'request', invocationId, body: { prompt: 'retry' } });
expect(mocks.outboundFetch).toHaveBeenCalledOnce();
expect(mocks.recordBilling).toHaveBeenCalledOnce();
+ expect(mocks.finishBilling).toHaveBeenCalledOnce();
+ });
+
+ it('reads the paid response and ends its network deadline while accounting is still pending', async () => {
+ mocks.guide.mockResolvedValue(resolvedGuide(operation({
+ mode: 'sync', media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],
+ })));
+ const invocationId = await prepare();
+ let finishBilling!: () => void;
+ mocks.recordBilling.mockImplementationOnce(() => new Promise<void>(resolve => { finishBilling = resolve; }));
+ const response = Response.json({ data: PNG.toString('base64') });
+ mocks.outboundFetch.mockResolvedValueOnce(response);
+ vi.useFakeTimers();
+ try {
+ const result = callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } });
+ await vi.waitFor(() => expect(response.bodyUsed).toBe(true));
+ await vi.advanceTimersByTimeAsync(5_001);
+ expect(mocks.outboundFetch.mock.calls[0][1].signal.aborted).toBe(false);
+ finishBilling();
+ await expect(result).resolves.toMatchObject({ ok: true, status: 'complete' });
+ expect(mocks.finishBilling).toHaveBeenCalledOnce();
+ } finally {
+ finishBilling?.();
+ vi.useRealTimers();
+ }
+ });
+
+ it('releases the accounting database when dispatch fails before any response', async () => {
+ mocks.guide.mockResolvedValue(resolvedGuide(operation({
+ mode: 'sync', media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],
+ })));
+ const invocationId = await prepare();
+ mocks.outboundFetch.mockRejectedValueOnce(new Error('connection reset'));
+ await expect(callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }))
+ .resolves.toMatchObject({ ok: false });
+ expect(mocks.recordBilling).not.toHaveBeenCalled();
+ expect(mocks.finishBilling).toHaveBeenCalledOnce();
});
it.each([0, 1, 2])('materializes large base64 images with %i trailing padding characters', async (padding) => {
diff --git a/apps/desktop/src/main/cindy-media/invocationService.ts b/apps/desktop/src/main/cindy-media/invocationService.ts
index 3d85d4ec57..ed0f4c94f5 100644
--- a/apps/desktop/src/main/cindy-media/invocationService.ts
+++ b/apps/desktop/src/main/cindy-media/invocationService.ts
@@ -23,7 +23,6 @@ import { getCurrentDbClientUserId, getDbClient } from '../localDb/client/current
import type { DbClient } from '../localDb/client/DbClient.js';
import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
-import { prepareGatewayMediaBilling } from '../usage/gatewayMediaBilling.js';
import {
fetchMediaInvocationGuide,
listAvailableMediaModels,
@@ -521,13 +520,20 @@ async function dispatchRequest(input: {
signal: controller.signal,
});
responseStatus = response.status;
- await input.recordBilling?.(response);
log.info('media request response', {
...requestLog,
status: response.status,
durationMs: Date.now() - startedAt,
});
- const buffer = await readBoundedResponse(response, input.maxResponseBytes);
+ const [body, billing] = await Promise.allSettled([
+ readBoundedResponse(response, input.maxResponseBytes).finally(() => clearTimeout(timeout)),
+ input.recordBilling?.(response),
+ ]);
+ if (body.status === 'rejected') throw body.reason;
+ if (billing.status === 'rejected') {
+ log.warn('media billing failed', { error: mediaErrorForLog(billing.reason) });
+ }
+ const buffer = body.value;
// A successful paid response belongs to the original invocation even if
// its connection changed in flight. Save it before guarding later reads.
if (input.operation === 'poll') input.connection.assertCurrent?.();
@@ -1471,49 +1477,112 @@ async function submitInvocation(
throw error;
}
const recordBilling = invocation.guide.connection.providerId === 'xd'
- ? await prepareGatewayMediaBilling({ model: invocation.modelId, sessionId, db })
+ ? await import('../usage/gatewayMediaBilling.js').then(({ prepareGatewayMediaBilling }) =>
+ prepareGatewayMediaBilling({ model: invocation.modelId, sessionId, db }),
+ )
: undefined;
- assertAuthScope(scope, invocation.owner);
- const claimed = await transitionMediaInvocation(
- {
- id: invocation.id,
- owner: invocation.owner,
- from: 'prepared',
- to: 'submitting',
- },
- db,
- );
- if (!claimed) {
- const current = await getMediaInvocation(invocation.id, invocation.owner, db);
+ try {
assertAuthScope(scope, invocation.owner);
- return failure(
- 'INVOCATION_ALREADY_USED',
- `该 invocation 当前状态为 ${current?.state ?? 'unknown'};付费提交不可重复执行`,
+ const claimed = await transitionMediaInvocation(
+ {
+ id: invocation.id,
+ owner: invocation.owner,
+ from: 'prepared',
+ to: 'submitting',
+ },
+ db,
);
- }
- // claim 之后再过一次认证代次闸;通过后到 outboundFetch 发起之间没有异步让出点,
- // 因而不会拿切换后账号的 endpoint / key 提交旧账号的付费请求。
- assertAuthScope(scope, invocation.owner);
- try {
- const response = await dispatchRequest({
- invocationId: invocation.id,
- providerId: invocation.guide.connection.providerId,
- modelId: invocation.modelId,
- capability: invocation.capability,
- connection,
- method: invocation.guide.request.method,
- path: invocation.guide.request.path,
- headers: invocation.guide.request.headers,
- body: requestBody,
- bodyEncoding: invocation.guide.request.bodyEncoding,
- multipartFiles: invocation.guide.request.multipartFiles,
- timeoutMs: invocation.guide.request.timeoutMs,
- maxResponseBytes: invocation.guide.request.maxResponseBytes,
- operation: 'submit',
- recordBilling,
- });
- if (invocation.guide.response.mode === 'sync') {
- const responseJson = JSON.stringify(response);
+ if (!claimed) {
+ const current = await getMediaInvocation(invocation.id, invocation.owner, db);
+ assertAuthScope(scope, invocation.owner);
+ return failure(
+ 'INVOCATION_ALREADY_USED',
+ `该 invocation 当前状态为 ${current?.state ?? 'unknown'};付费提交不可重复执行`,
+ );
+ }
+ // claim 之后再过一次认证代次闸;通过后到 outboundFetch 发起之间没有异步让出点,
+ // 因而不会拿切换后账号的 endpoint / key 提交旧账号的付费请求。
+ assertAuthScope(scope, invocation.owner);
+ try {
+ const response = await dispatchRequest({
+ invocationId: invocation.id,
+ providerId: invocation.guide.connection.providerId,
+ modelId: invocation.modelId,
+ capability: invocation.capability,
+ connection,
+ method: invocation.guide.request.method,
+ path: invocation.guide.request.path,
+ headers: invocation.guide.request.headers,
+ body: requestBody,
+ bodyEncoding: invocation.guide.request.bodyEncoding,
+ multipartFiles: invocation.guide.request.multipartFiles,
+ timeoutMs: invocation.guide.request.timeoutMs,
+ maxResponseBytes: invocation.guide.request.maxResponseBytes,
+ operation: 'submit',
+ recordBilling,
+ });
+ if (invocation.guide.response.mode === 'sync') {
+ const responseJson = JSON.stringify(response);
+ let persisted = false;
+ try {
+ persisted = await transitionMediaInvocation(
+ {
+ id: invocation.id,
+ owner: invocation.owner,
+ from: 'submitting',
+ to: 'pending',
+ responseJson,
+ },
+ db,
+ );
+ } catch (error) {
+ log.warn('persist sync media response failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ await transitionMediaInvocation(
+ {
+ id: invocation.id,
+ owner: invocation.owner,
+ from: 'submitting',
+ to: 'unknown',
+ },
+ db,
+ ).catch(() => false);
+ return submissionOutcomeUnknown(
+ '上游结果已生成,但本地未能保存结果;不要自动重提',
+ );
+ }
+ if (!persisted) {
+ return submissionOutcomeUnknown(
+ '上游结果已生成,但本地未能保存结果;不要自动重提',
+ );
+ }
+ connection.assertCurrent?.();
+ assertAuthScope(scope, invocation.owner);
+ return materializeSyncInvocation(
+ { ...invocation, state: 'pending', responseJson },
+ response,
+ scope,
+ db,
+ );
+ }
+ const taskId = valuesAtPath(response, invocation.guide.response.taskIdPath).find(
+ (value): value is string => typeof value === 'string' && value.length > 0,
+ );
+ if (!taskId) {
+ await transitionMediaInvocation(
+ {
+ id: invocation.id,
+ owner: invocation.owner,
+ from: 'submitting',
+ to: 'unknown',
+ },
+ db,
+ );
+ return submissionOutcomeUnknown(
+ '上游响应没有任务 id,无法确认任务状态;不要自动重提',
+ );
+ }
let persisted = false;
try {
persisted = await transitionMediaInvocation(
@@ -1522,12 +1591,12 @@ async function submitInvocation(
owner: invocation.owner,
from: 'submitting',
to: 'pending',
- responseJson,
+ taskId,
},
db,
);
} catch (error) {
- log.warn('persist sync media response failed', {
+ log.warn('persist async media task id failed', {
error: error instanceof Error ? error.message : String(error),
});
await transitionMediaInvocation(
@@ -1540,110 +1609,53 @@ async function submitInvocation(
db,
).catch(() => false);
return submissionOutcomeUnknown(
- '上游结果已生成,但本地未能保存结果;不要自动重提',
+ '上游任务已创建,但本地未能保存任务 id;不要自动重提',
);
}
if (!persisted) {
return submissionOutcomeUnknown(
- '上游结果已生成,但本地未能保存结果;不要自动重提',
+ '上游任务已创建,但本地未能保存任务 id;不要自动重提',
);
}
connection.assertCurrent?.();
assertAuthScope(scope, invocation.owner);
- return materializeSyncInvocation(
- { ...invocation, state: 'pending', responseJson },
- response,
- scope,
- db,
- );
- }
- const taskId = valuesAtPath(response, invocation.guide.response.taskIdPath).find(
- (value): value is string => typeof value === 'string' && value.length > 0,
- );
- if (!taskId) {
- await transitionMediaInvocation(
- {
- id: invocation.id,
- owner: invocation.owner,
- from: 'submitting',
- to: 'unknown',
- },
- db,
- );
- return submissionOutcomeUnknown(
- '上游响应没有任务 id,无法确认任务状态;不要自动重提',
- );
- }
- let persisted = false;
- try {
- persisted = await transitionMediaInvocation(
- {
- id: invocation.id,
- owner: invocation.owner,
- from: 'submitting',
- to: 'pending',
- taskId,
- },
- db,
- );
+ return {
+ ok: true,
+ status: 'pending',
+ invocation_id: invocation.id,
+ recommended_poll_after_ms: invocation.guide.response.poll.recommendedIntervalMs,
+ };
} catch (error) {
- log.warn('persist async media task id failed', {
- error: error instanceof Error ? error.message : String(error),
- });
- await transitionMediaInvocation(
+ const expected = error instanceof MediaInvocationError ? error : null;
+ // 本地组装失败、提交前模型停用或连接变化:请求从未出站、无费用,把 invocation 放回 prepared,
+ // 让同一 invocation_id 可以直接再次 request;其余失败仍进入 failed / unknown。
+ // 已保存结果为 pending 时,submitting 条件更新不匹配,不回退已付费任务。
+ const notSubmitted = expected?.code === 'REQUEST_BUILD_FAILED' || expected?.code === 'MODEL_NOT_AVAILABLE' || expected?.code === 'CONNECTION_CHANGED';
+ const restored = await transitionMediaInvocation(
{
id: invocation.id,
owner: invocation.owner,
from: 'submitting',
- to: 'unknown',
+ to: notSubmitted ? 'prepared' : expected?.outcomeUnknown ? 'unknown' : 'failed',
},
db,
).catch(() => false);
- return submissionOutcomeUnknown(
- '上游任务已创建,但本地未能保存任务 id;不要自动重提',
- );
- }
- if (!persisted) {
- return submissionOutcomeUnknown(
- '上游任务已创建,但本地未能保存任务 id;不要自动重提',
- );
- }
- connection.assertCurrent?.();
- assertAuthScope(scope, invocation.owner);
- return {
- ok: true,
- status: 'pending',
- invocation_id: invocation.id,
- recommended_poll_after_ms: invocation.guide.response.poll.recommendedIntervalMs,
- };
- } catch (error) {
- const expected = error instanceof MediaInvocationError ? error : null;
- // 本地组装失败、提交前模型停用或连接变化:请求从未出站、无费用,把 invocation 放回 prepared,
- // 让同一 invocation_id 可以直接再次 request;其余失败仍进入 failed / unknown。
- // 已保存结果为 pending 时,submitting 条件更新不匹配,不回退已付费任务。
- const notSubmitted = expected?.code === 'REQUEST_BUILD_FAILED' || expected?.code === 'MODEL_NOT_AVAILABLE' || expected?.code === 'CONNECTION_CHANGED';
- const restored = await transitionMediaInvocation(
- {
- id: invocation.id,
- owner: invocation.owner,
- from: 'submitting',
- to: notSubmitted ? 'prepared' : expected?.outcomeUnknown ? 'unknown' : 'failed',
- },
- db,
- ).catch(() => false);
- if (expected) {
- if (expected.outcomeUnknown) return submissionOutcomeUnknown(expected.message);
- if (notSubmitted && restored) {
- return failure(expected.code, `${expected.message};同一 invocation_id 可直接再次 request`, true, {
- outcomeKnown: true,
- });
+ if (expected) {
+ if (expected.outcomeUnknown) return submissionOutcomeUnknown(expected.message);
+ if (notSubmitted && restored) {
+ return failure(expected.code, `${expected.message};同一 invocation_id 可直接再次 request`, true, {
+ outcomeKnown: true,
+ });
+ }
+ return failure(expected.code, expected.message, false, { outcomeKnown: true });
}
- return failure(expected.code, expected.message, false, { outcomeKnown: true });
+ log.warn('media submission failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return failure('INTERNAL', '媒体任务提交失败');
}
- log.warn('media submission failed', {
- error: error instanceof Error ? error.message : String(error),
- });
- return failure('INTERNAL', '媒体任务提交失败');
+ } finally {
+ recordBilling?.finish();
}
}
diff --git a/apps/desktop/src/main/localDb/client/__tests__/lifecycleDbClient.test.ts b/apps/desktop/src/main/localDb/client/__tests__/lifecycleDbClient.test.ts
index da9811de21..b653ce9824 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/lifecycleDbClient.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/lifecycleDbClient.test.ts
@@ -1,12 +1,43 @@
import { describe, expect, it, vi } from 'vitest';
import type { DbClient } from '../DbClient.js';
+import { retainDbClient } from '../pendingOperations.js';
import {
createLifecycleDbClientManager,
type LifecycleDbClientLog,
} from '../lifecycleDbClient.js';
describe('lifecycle DbClient manager', () => {
+ it.each(['worker', 'inproc-fallback'])('keeps the outgoing %s database open until all paid operations settle', async mode => {
+ const worker = makeClient('worker');
+ const fallback = makeClient('fallback');
+ if (mode === 'inproc-fallback') worker.query.mockRejectedValueOnce(new Error('worker unavailable'));
+ const clearCurrent = vi.fn();
+ const manager = createLifecycleDbClientManager({
+ getCurrentDbPath: () => '/tmp/owner-a.db',
+ createWorkerClient: vi.fn(async () => worker),
+ createInprocClient: vi.fn(async () => fallback),
+ setCurrentDbClient: vi.fn(),
+ clearCurrentDbClient: clearCurrent,
+ log: makeLog(),
+ });
+ await manager.ensure('owner-a', {});
+ const client = mode === 'worker' ? worker : fallback;
+ const first = retainDbClient(client);
+ const second = retainDbClient(client);
+ const disposing = manager.dispose('user-switch');
+ expect(clearCurrent).toHaveBeenCalledWith(client);
+ await Promise.resolve();
+ expect(client.dispose).not.toHaveBeenCalled();
+ first();
+ first();
+ await Promise.resolve();
+ expect(client.dispose).not.toHaveBeenCalled();
+ second();
+ await disposing;
+ expect(client.dispose).toHaveBeenCalledOnce();
+ });
+
it('keeps main db active and installs inproc fallback when worker smoke fails', async () => {
const worker = makeClient('worker');
const fallback = makeClient('fallback');
diff --git a/apps/desktop/src/main/localDb/client/lifecycleDbClient.ts b/apps/desktop/src/main/localDb/client/lifecycleDbClient.ts
index 03707b81c2..b9baa2c0ee 100644
--- a/apps/desktop/src/main/localDb/client/lifecycleDbClient.ts
+++ b/apps/desktop/src/main/localDb/client/lifecycleDbClient.ts
@@ -1,4 +1,5 @@
import type { CreateDbClientOptions, DbClient } from './DbClient.js';
+import { waitForRetainedDbClient } from './pendingOperations.js';
export type LifecycleDbClientMode =
| 'worker'
@@ -53,6 +54,7 @@ export function createLifecycleDbClientManager(
lifecycleDbClientMode = null;
deps.clearCurrentDbClient(client);
try {
+ await waitForRetainedDbClient(client);
await client.dispose();
deps.log.info('[DbClient] disposed', { reason });
} catch (err) {
diff --git a/apps/desktop/src/main/localDb/client/pendingOperations.ts b/apps/desktop/src/main/localDb/client/pendingOperations.ts
new file mode 100644
index 0000000000..abddbea3bd
--- /dev/null
+++ b/apps/desktop/src/main/localDb/client/pendingOperations.ts
@@ -0,0 +1,20 @@
+import type { DbClient } from './DbClient.js';
+
+const pending = new WeakMap<DbClient, Set<Promise<void>>>();
+
+/** Keep the outgoing account database alive until an already-paid request is accounted for. */
+export function retainDbClient(client: DbClient): () => void {
+ const operations = pending.get(client) ?? new Set<Promise<void>>();
+ pending.set(client, operations);
+ let resolve!: () => void;
+ const done = new Promise<void>((complete) => { resolve = complete; });
+ operations.add(done);
+ return () => {
+ operations.delete(done);
+ resolve();
+ };
+}
+
+export async function waitForRetainedDbClient(client: DbClient): Promise<void> {
+ while (pending.get(client)?.size) await Promise.all(pending.get(client)!);
+}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxyMediaBilling.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxyMediaBilling.test.ts
index 440ab09930..a2c2d7154b 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxyMediaBilling.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxyMediaBilling.test.ts
@@ -5,7 +5,9 @@ const mocks = vi.hoisted(() => ({
createService: vi.fn(),
prepareBilling: vi.fn(),
recordBilling: vi.fn(),
+ finishBilling: vi.fn(),
fetch: vi.fn(),
+ serviceOptions: null as CindyProxyMediaServiceOptions | null,
}));
vi.mock('../../model-access/effectiveEndpoint.js', () => ({
effectiveXdGatewayBaseUrl: () => 'https://gateway.example.invalid',
@@ -29,13 +31,16 @@ vi.mock('../../usage/gatewayMediaBilling.js', () => ({
prepareGatewayMediaBilling: mocks.prepareBilling,
}));
-import { getCindyProxyMediaService, getCindyVideoProviderRegistry } from '../cindyProxyMedia.js';
+import { getCindyProxyMediaService, getCindyVideoProviderRegistry, withCindyMediaBillingSession } from '../cindyProxyMedia.js';
describe('legacy Gateway media billing wiring', () => {
beforeEach(() => {
vi.clearAllMocks();
- mocks.createService.mockReturnValue({ backend: {} });
- mocks.prepareBilling.mockResolvedValue(mocks.recordBilling);
+ mocks.createService.mockImplementation((options: CindyProxyMediaServiceOptions) => {
+ mocks.serviceOptions = options;
+ return { backend: {} };
+ });
+ mocks.prepareBilling.mockResolvedValue(Object.assign(mocks.recordBilling, { finish: mocks.finishBilling }));
mocks.recordBilling.mockResolvedValue(undefined);
vi.stubGlobal('fetch', mocks.fetch);
});
@@ -67,7 +72,8 @@ describe('legacy Gateway media billing wiring', () => {
it('records video create but skips polls and downloads even if they contain billing headers', async () => {
const { provider } = getCindyVideoProviderRegistry().resolveByAlias('seedance-fast');
mocks.fetch.mockResolvedValueOnce(Response.json({ id: 'paid-task' }));
- const handle = await provider.submit({ prompt: 'cat' }, 'seedance-fast');
+ const handle = await withCindyMediaBillingSession('video-task', () => provider.submit({ prompt: 'cat' }, 'seedance-fast'));
+ expect(mocks.prepareBilling).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'video-task' }));
expect(mocks.recordBilling).toHaveBeenCalledOnce();
const headers = { 'X-Nova-AIGateway-Billing': Buffer.from('{"cost":1}').toString('base64url') };
mocks.fetch.mockResolvedValueOnce(Response.json({ status: 'running' }, { headers }));
@@ -77,4 +83,37 @@ describe('legacy Gateway media billing wiring', () => {
expect(mocks.prepareBilling).toHaveBeenCalledOnce();
expect(mocks.recordBilling).toHaveBeenCalledOnce();
});
+
+ it('isolates concurrent Host task contexts and leaves background requests unassociated', async () => {
+ getCindyProxyMediaService();
+ // The service is a singleton; reuse its installed fetch adapter.
+ const doFetch = mocks.serviceOptions!.imageApi.fetchImplementation!;
+ mocks.fetch.mockImplementation(async () => Response.json({ data: [] }));
+ const create = () => doFetch('https://gateway.example.invalid/v1/images/generations', {
+ method: 'POST', body: JSON.stringify({ model: 'image' }),
+ });
+ const releases: Array<() => void> = [];
+ mocks.recordBilling.mockImplementation(() => new Promise<void>(resolve => { releases.push(resolve); }));
+ // Vitest shares mock import callstacks. Settle each import before the next starts,
+ // while keeping all three accounting operations in flight together.
+ const first = withCindyMediaBillingSession('task-a', async () => { await Promise.resolve(); return create(); });
+ await vi.waitFor(() => expect(releases).toHaveLength(1));
+ const second = withCindyMediaBillingSession('task-b', create);
+ await vi.waitFor(() => expect(releases).toHaveLength(2));
+ const background = create();
+ await vi.waitFor(() => expect(releases).toHaveLength(3));
+ releases.forEach(release => release());
+ await Promise.all([first, second, background]);
+ expect(mocks.prepareBilling.mock.calls.map(([input]) => input.sessionId).sort()).toEqual([
+ 'task-a', 'task-b', undefined,
+ ]);
+ });
+
+ it('releases its accounting database when fetch fails', async () => {
+ const { provider } = getCindyVideoProviderRegistry().resolveByAlias('seedance-fast');
+ mocks.fetch.mockRejectedValueOnce(new Error('connection reset'));
+ await expect(provider.submit({ prompt: 'cat' }, 'seedance-fast')).rejects.toThrow('connection reset');
+ expect(mocks.recordBilling).not.toHaveBeenCalled();
+ expect(mocks.finishBilling).toHaveBeenCalledOnce();
+ });
});
diff --git a/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts b/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts
index 031b31d503..59215b0d45 100644
--- a/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts
+++ b/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts
@@ -1,3 +1,4 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
import { createCindyProxyMediaService } from '../cindy-proxy-media/service.js';
import type { CindyProxyMediaService } from '../cindy-proxy-media/types.js';
import {
@@ -13,9 +14,14 @@ import { mediaErrorForLog } from '../cindy-media/mediaRequestLog.js';
import { getProviderSecretStore } from '../secrets/providerSecretStore.js';
import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';
import { getAppCapabilities } from '../appCapabilities.js';
-import { prepareGatewayMediaBilling } from '../usage/gatewayMediaBilling.js';
const log = createLogger('art');
+const billingSession = new AsyncLocalStorage<string | undefined>();
+
+/** The session comes from the Host's active same-plugin call, never plugin arguments. */
+export function withCindyMediaBillingSession<T>(sessionId: string | undefined, run: () => T): T {
+ return billingSession.run(sessionId, run);
+}
let artService: CindyProxyMediaService | null = null;
/** 构建单例时捕获的 baseUrl;model-access 下发切换 endpoint 后据此重建。 */
@@ -45,10 +51,15 @@ const gatewayMediaFetch: typeof fetch = async (input, init) => {
const value = init.body.get('model');
if (typeof value === 'string') model = value;
}
- const recordBilling = await prepareGatewayMediaBilling({ model });
- const response = await fetch(input, init);
- await recordBilling(response);
- return response;
+ const { prepareGatewayMediaBilling } = await import('../usage/gatewayMediaBilling.js');
+ const recordBilling = await prepareGatewayMediaBilling({ model, sessionId: billingSession.getStore() });
+ try {
+ const response = await fetch(input, init);
+ await recordBilling(response);
+ return response;
+ } finally {
+ recordBilling.finish();
+ }
};
/**
diff --git a/apps/desktop/src/main/usage/__tests__/gatewayMediaBilling.test.ts b/apps/desktop/src/main/usage/__tests__/gatewayMediaBilling.test.ts
index 4e0961fdbc..5b3c2fa1a3 100644
--- a/apps/desktop/src/main/usage/__tests__/gatewayMediaBilling.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/gatewayMediaBilling.test.ts
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { parseGatewayMediaBillingHeader } from '../gatewayMediaBillingHeader.js';
+import type { DbClient } from '../../localDb/client/DbClient.js';
+import { waitForRetainedDbClient } from '../../localDb/client/pendingOperations.js';
const mocks = vi.hoisted(() => ({
owner: 'owner-a',
@@ -137,9 +139,16 @@ describe('Gateway media billing', () => {
});
it('retains the original database after an account switch without notifying the new owner', async () => {
- const record = await prepareGatewayMediaBilling({ model: 'image' });
+ const db = { tx: mocks.tx } as unknown as DbClient;
+ const record = await prepareGatewayMediaBilling({ model: 'image', db });
+ let drained = false;
+ const draining = waitForRetainedDbClient(db).then(() => { drained = true; });
mocks.owner = 'owner-b';
+ await Promise.resolve();
+ expect(drained).toBe(false);
await record(response({ cost: 1 }));
+ await draining;
+ expect(drained).toBe(true);
expect(mocks.tx).toHaveBeenCalledOnce();
expect(mocks.sessionPush).not.toHaveBeenCalled();
expect(mocks.todayPush).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
index 7048f2e8c2..fa64f179ab 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
@@ -168,6 +168,24 @@ describe('media settlement currency', () => {
replaceGatewayModelPricing([{ id: 'image', currency: 'CNY' }, { id: 'video', currency: 'USD' }]);
expect(await getGatewayMediaBillingCurrency()).toBeNull();
});
+
+ it('does not relabel header charges using a remembered currency when a legacy v9 cache is ambiguous', async () => {
+ replaceGatewayModelPricing([{ id: 'image', currency: 'CNY' }]);
+ await __flushAccountCurrencyStoreForTesting();
+ await vi.waitFor(async () => {
+ expect(JSON.parse(await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8')).accountCurrency).toBe('CNY');
+ });
+ await writeFile(userDataPath('cache', 'model-pricing.json'), JSON.stringify({
+ version: 9, scope: expectedScope(), fetchedAt: Date.now(), accountCurrency: null, pricing: {},
+ }));
+ __resetModelPricingCacheForTesting();
+ __resetAccountCurrencyStoreForTesting();
+ __resetActiveLedgerCurrencyForTesting();
+ expect(await getGatewayMediaBillingCurrency()).toBeNull();
+ // A newly written no-currency snapshot explicitly rules out a conflict.
+ replaceGatewayModelPricing([{ id: 'image' }]);
+ expect(await getGatewayMediaBillingCurrency()).toBe('CNY');
+ });
});
describe('gateway model pricing projection', () => {
diff --git a/apps/desktop/src/main/usage/gatewayMediaBilling.ts b/apps/desktop/src/main/usage/gatewayMediaBilling.ts
index 5016ab36f8..233e1b22f7 100644
--- a/apps/desktop/src/main/usage/gatewayMediaBilling.ts
+++ b/apps/desktop/src/main/usage/gatewayMediaBilling.ts
@@ -1,5 +1,6 @@
import { getDbClient, getCurrentDbClientUserId } from '../localDb/client/current.js';
import type { DbClient } from '../localDb/client/DbClient.js';
+import { retainDbClient } from '../localDb/client/pendingOperations.js';
import { localDayKey } from '../localDb/dailySpend.js';
import { createLogger } from '../logger.js';
import {
@@ -22,12 +23,16 @@ import {
const log = createLogger('gatewayMediaBilling');
+export type GatewayMediaBillingRecorder = ((response: Response) => Promise<void>) & {
+ finish(): void;
+};
+
/** Capture the account, database and settlement currency before the paid dispatch. */
export async function prepareGatewayMediaBilling(input: {
model: string;
sessionId?: string;
db?: DbClient;
-}): Promise<(response: Response) => Promise<void>> {
+}): Promise<GatewayMediaBillingRecorder> {
const ownerScope = captureDataOwnerBroadcastScope();
const dbOwnerId = getCurrentDbClientUserId();
const db = input.db ?? (dbOwnerId ? getDbClient() : null);
@@ -41,10 +46,9 @@ export async function prepareGatewayMediaBilling(input: {
if (!isDataOwnerBroadcastScopeCurrent(ownerScope) || getCurrentDbClientUserId() !== dbOwnerId) {
throw new Error('Media billing account changed before dispatch');
}
- let handled = false;
- return async (response) => {
- if (handled || !response.ok) return;
- handled = true;
+ const finish = db ? retainDbClient(db) : () => undefined;
+ const record = async (response: Response): Promise<void> => {
+ if (!response.ok) return;
const value = response.headers.get('X-Nova-AIGateway-Billing');
const billing = parseGatewayMediaBillingHeader(value);
if (!billing) {
@@ -58,7 +62,7 @@ export async function prepareGatewayMediaBilling(input: {
}
try {
const now = Date.now();
- // Called only for the original submit response, before reading/downloading its body.
+ // Called only for the original submit response; body reading may proceed in parallel.
// Polling and recovery of persisted results never reapply this delta.
const { session, turnCost } = await enqueueDurableWrite('media-billing', async () => {
const session = await db.tx('usage.recordMediaSpend', {
@@ -115,4 +119,9 @@ export async function prepareGatewayMediaBilling(input: {
);
}
};
+ let recording: Promise<void> | undefined;
+ return Object.assign(
+ (response: Response) => recording ??= record(response).finally(finish),
+ { finish },
+ );
}
diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.ts
index 148d886e3e..9eb9c51aaa 100644
--- a/apps/desktop/src/main/usage/modelPricing.ts
+++ b/apps/desktop/src/main/usage/modelPricing.ts
@@ -317,6 +317,8 @@ async function hydrateFromDisk(scope: string): Promise<ModelPricingCatalog | nul
gatewayAccountCurrency = raw.accountCurrency;
gatewayAccountCurrencyScope = scope;
gatewayCurrencyConflictScope = raw.currencyConflict === true ||
+ // Legacy v9 snapshots cannot distinguish an omitted currency from a mixed catalog.
+ (raw.currencyConflict === undefined && raw.accountCurrency === null) ||
new Set(Object.values(pricing.xd ?? {}).filter((quote) => !quote.currencyInferred)
.map((quote) => quote.currency)).size > 1 ? scope : null;
setActiveLedgerCurrency(raw.accountCurrency);
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index eeea50f94b..9ea4e6d2f3 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -34,8 +34,14 @@ Gateway 边界对整块报价校验,非法或无有效币种即整体省略,
头缺失或非法时不猜测金额。旧网关没有头时继续提供媒体结果,不补算历史费用。
仅原始创建响应记账,视频轮询、下载、已保存结果恢复不重复记账;响应正文或下载失败不撤回
已经收到的有效计费。每日总额、模型费用和 Host 可关联的任务费用原子更新。
+正文读取与记账并行,读取完成即结束网络超时计时;本地记账等待不占用正文读取时间。
+账号数据库关闭前等待已发出媒体请求的记账结束,成功、拒绝、网络失败及提交前退出均释放
+对应等待。旧插件代办通过 Host 的同插件在途调用恢复任务上下文;没有此上下文的后台生成
+只记日账与模型费用,不借用当前聚焦任务。
目录暂缺币种时复用同账号已确认的结算币种;从未确认或目录币种冲突时仍不猜测。
+旧版 v9 缓存未保存冲突标记且账号币种为空时,不能区分缺省与混合币种;在新的目录声明前
+不复用历史币种给媒体计费头标注币种。
任务内媒体费在提交前绑定真实用户消息,`agent_meta.mediaCosts` 按币种保存实际费用,
与日账及任务总额同一事务落库。响应下方沿用 `userTurnMoney` 累计,晚到费用刷新原轮,
不修改聊天分段 `turnCost` 或订阅估值。定时运行与累计费用同时读取用户消息媒体账本,