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): 补齐网关媒体计费与任务费用归属

liugaowei8a53a1d65bcd
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 c197402a1d..ca4b4ccb2e 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
@@ -30,9 +30,11 @@ const mocks = vi.hoisted(() => ({
videoConnection: vi.fn(),
guide: vi.fn(),
outboundFetch: vi.fn(),
+ prepareBilling: vi.fn(),
+ recordBilling: vi.fn<(response: Response) => Promise<void>>(async () => undefined),
guardedOutboundFetch: vi.fn(),
release: vi.fn(async () => undefined),
- confirm: vi.fn(async (_input: { reasons: string[] }) => true),
+ confirm: vi.fn<(input: { reasons: string[] }) => Promise<boolean>>(async () => true),
ingestMedia: vi.fn(),
readBlob: vi.fn(),
resolveBlob: vi.fn(),
@@ -92,6 +94,9 @@ vi.mock('../../maker-host/outbound-fetch.js', () => ({
outboundFetch: mocks.outboundFetch,
guardedOutboundFetch: mocks.guardedOutboundFetch,
}));
+vi.mock('../../usage/gatewayMediaBilling.js', () => ({
+ prepareGatewayMediaBilling: mocks.prepareBilling,
+}));
vi.mock('../../model-access/mediaModels.js', () => ({
listAvailableMediaModels: mocks.models,
listExecutableMediaModels: mocks.executableModels,
@@ -201,7 +206,7 @@ const callCindyMedia: typeof invokeMedia = (request, context = {
assertActive: () => undefined,
confirm: mocks.confirm,
approvals: new Set<string>(),
-}) => invokeMedia(request, context);
+}, sessionId) => invokeMedia(request, context, sessionId);
const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1]);
const MP4 = Buffer.from([
@@ -256,6 +261,8 @@ 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.failRequestLog = false;
mocks.confirm.mockReset().mockResolvedValue(true);
mocks.currentUserId = `media-user-${crypto.randomUUID()}`;
@@ -577,7 +584,7 @@ describe('Cindy Core media invocation state and security boundary', () => {
action: 'request',
invocationId,
body: { prompt: 'cat', model: 'agent-must-not-control-this' },
- });
+ }, undefined, 'host-session');
expect(result).toMatchObject({
ok: true,
@@ -600,6 +607,25 @@ describe('Cindy Core media invocation state and security boundary', () => {
});
expect(mocks.outboundFetch).toHaveBeenCalledTimes(1);
expect(mocks.ingestMedia).toHaveBeenCalledTimes(1);
+ expect(mocks.prepareBilling).toHaveBeenCalledExactlyOnceWith({
+ model: 'image-model', sessionId: 'host-session', db: mocks.db,
+ });
+ expect(mocks.recordBilling).toHaveBeenCalledOnce();
+ });
+
+ it('records a successful paid header before a malformed body is rejected', async () => {
+ mocks.guide.mockResolvedValue(resolvedGuide(operation({
+ mode: 'sync', media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],
+ })));
+ const response = new Response('not-json', { status: 200 });
+ mocks.outboundFetch.mockResolvedValueOnce(response);
+ const invocationId = await prepare();
+ await expect(callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }))
+ .resolves.toMatchObject({ ok: false });
+ expect(mocks.recordBilling).toHaveBeenCalledExactlyOnceWith(response);
+ await callCindyMedia({ action: 'request', invocationId, body: { prompt: 'retry' } });
+ expect(mocks.outboundFetch).toHaveBeenCalledOnce();
+ expect(mocks.recordBilling).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 26529b9897..3d85d4ec57 100644
--- a/apps/desktop/src/main/cindy-media/invocationService.ts
+++ b/apps/desktop/src/main/cindy-media/invocationService.ts
@@ -23,6 +23,7 @@ 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,
@@ -471,6 +472,7 @@ async function dispatchRequest(input: {
timeoutMs: number;
maxResponseBytes: number;
operation: 'submit' | 'poll';
+ recordBilling?(response: Response): Promise<void>;
}): Promise<unknown> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), input.timeoutMs);
@@ -519,6 +521,7 @@ async function dispatchRequest(input: {
signal: controller.signal,
});
responseStatus = response.status;
+ await input.recordBilling?.(response);
log.info('media request response', {
...requestLog,
status: response.status,
@@ -1373,6 +1376,7 @@ async function submitInvocation(
invocation: StoredMediaInvocation,
body: Record<string, unknown>,
context?: MediaDownloadContext,
+ sessionId?: string,
): Promise<Record<string, unknown>> {
const scope = currentAuthScope(context);
assertAuthScope(scope, invocation.owner);
@@ -1466,6 +1470,10 @@ async function submitInvocation(
}
throw error;
}
+ const recordBilling = invocation.guide.connection.providerId === 'xd'
+ ? await prepareGatewayMediaBilling({ model: invocation.modelId, sessionId, db })
+ : undefined;
+ assertAuthScope(scope, invocation.owner);
const claimed = await transitionMediaInvocation(
{
id: invocation.id,
@@ -1502,6 +1510,7 @@ async function submitInvocation(
timeoutMs: invocation.guide.request.timeoutMs,
maxResponseBytes: invocation.guide.request.maxResponseBytes,
operation: 'submit',
+ recordBilling,
});
if (invocation.guide.response.mode === 'sync') {
const responseJson = JSON.stringify(response);
@@ -1850,6 +1859,8 @@ async function pollInvocation(
export async function callCindyMedia(
request: CindyMediaToolRequest,
context?: MediaDownloadContext,
+ /** Trusted Host context; never supplied through the model's tool arguments. */
+ sessionId?: string,
): Promise<Record<string, unknown>> {
try {
if (request.action === 'resolve_local_path') {
@@ -1952,7 +1963,7 @@ export async function callCindyMedia(
activeInvocations.add(operationKey);
try {
return await (request.action === 'request'
- ? submitInvocation(invocation, request.body, context)
+ ? submitInvocation(invocation, request.body, context, sessionId)
: pollInvocation(invocation, context));
} finally {
activeInvocations.delete(operationKey);
diff --git a/apps/desktop/src/main/localDb/__tests__/mediaSpendTx.test.ts b/apps/desktop/src/main/localDb/__tests__/mediaSpendTx.test.ts
new file mode 100644
index 0000000000..5151a0b9a9
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/mediaSpendTx.test.ts
@@ -0,0 +1,152 @@
+import Database from 'better-sqlite3';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { tx } from '../worker/opHandlers/tx.js';
+
+describe('media spend transaction', () => {
+ let db: Database.Database;
+ beforeEach(() => {
+ db = new Database(':memory:');
+ db.exec(`
+ CREATE TABLE daily_spend (
+ day TEXT, cost_amount REAL DEFAULT 0, cost_currency TEXT, updated_at INTEGER,
+ PRIMARY KEY(day, cost_currency));
+ CREATE TABLE daily_model_usage (
+ day TEXT, agent_kind TEXT, model TEXT, cost_amount REAL DEFAULT 0,
+ cost_currency TEXT, updated_at INTEGER, input_tokens INTEGER DEFAULT 0,
+ output_tokens INTEGER DEFAULT 0, cache_read_tokens INTEGER DEFAULT 0,
+ cache_create_tokens INTEGER DEFAULT 0,
+ PRIMARY KEY(day, agent_kind, model, cost_currency));
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY, total_cost_usd REAL DEFAULT 0, total_cost_amount REAL DEFAULT 0,
+ total_cost_currency TEXT, total_cost_is_approximate INTEGER DEFAULT 0);
+ CREATE TABLE messages (session_id TEXT, client_id TEXT, role TEXT, agent_meta TEXT);
+ CREATE TABLE schedule_runs (id TEXT PRIMARY KEY, cost_amount REAL DEFAULT 0,
+ cost_currency TEXT, cost_attribution TEXT DEFAULT 'unavailable');
+ INSERT INTO sessions(id, total_cost_usd, total_cost_amount, total_cost_currency)
+ VALUES ('session-1', 2, 3, 'USD');
+ `);
+ });
+ afterEach(() => db.close());
+
+ const spend = (currency: 'USD' | 'CNY' = 'USD', sessionId?: string) =>
+ tx(db, {
+ name: 'usage.recordMediaSpend',
+ args: { day: '2026-10-15', model: 'image-model', amount: 0.75, currency, sessionId, now: 1 },
+ });
+
+ it('adds costs to day, model and task without changing chat tokens or historical USD', () => {
+ expect(spend('USD', 'session-1')).toEqual({
+ legacyUsd: 2,
+ amount: 3.75,
+ currency: 'USD',
+ approximate: 0,
+ });
+ spend('USD', 'session-1');
+ expect(db.prepare('SELECT cost_amount FROM daily_spend').get()).toEqual({ cost_amount: 1.5 });
+ expect(
+ db
+ .prepare(
+ 'SELECT agent_kind, cost_amount, input_tokens, output_tokens FROM daily_model_usage',
+ )
+ .get(),
+ ).toEqual({ agent_kind: 'media', cost_amount: 1.5, input_tokens: 0, output_tokens: 0 });
+ expect(db.prepare('SELECT total_cost_usd, total_cost_amount FROM sessions').get()).toEqual({
+ total_cost_usd: 2,
+ total_cost_amount: 4.5,
+ });
+ });
+
+ it('keeps separate currency rows and follows the existing task currency rollover', () => {
+ spend('USD', 'session-1');
+ expect(spend('CNY', 'session-1')).toEqual({
+ legacyUsd: 2,
+ amount: 0.75,
+ currency: 'CNY',
+ approximate: 0,
+ });
+ expect(db.prepare('SELECT COUNT(*) AS n FROM daily_spend').get()).toEqual({ n: 2 });
+ expect(db.prepare('SELECT COUNT(*) AS n FROM daily_model_usage').get()).toEqual({ n: 2 });
+ });
+
+ it('keeps unassociated media in day and model totals', () => {
+ expect(spend()).toBeNull();
+ expect(db.prepare('SELECT cost_amount FROM daily_spend').get()).toEqual({ cost_amount: 0.75 });
+ expect(db.prepare('SELECT total_cost_amount FROM sessions').get()).toEqual({
+ total_cost_amount: 3,
+ });
+ });
+
+ it.each(['unavailable', 'exact', 'direct', 'mixed'])(
+ 'persists the original user ledger and respects %s run snapshots',
+ (attribution) => {
+ const origin = { kind: 'scheduler', runId: 'run-1', scheduleId: 'schedule-1' };
+ db.prepare(`INSERT INTO messages VALUES ('session-1', 'user-1', 'user', ?)`).run(
+ JSON.stringify({ origin, model: 'keep-model' }),
+ );
+ db.prepare(
+ `INSERT INTO schedule_runs(id, cost_amount, cost_attribution) VALUES ('run-1', 1, ?)`,
+ ).run(attribution);
+ const record = () =>
+ tx(db, {
+ name: 'usage.recordMediaSpend',
+ args: {
+ day: '2026-10-15',
+ model: 'image',
+ amount: 0.75,
+ currency: 'USD',
+ sessionId: 'session-1',
+ userClientId: 'user-1',
+ now: 1,
+ },
+ });
+ record();
+ record();
+ const meta = JSON.parse(
+ (db.prepare('SELECT agent_meta FROM messages').get() as { agent_meta: string }).agent_meta,
+ );
+ expect(meta).toEqual({
+ origin,
+ model: 'keep-model',
+ mediaCosts: [{ amount: 1.5, currency: 'USD', approximate: false, kind: 'actual-cost' }],
+ });
+ expect(db.prepare('SELECT cost_amount, cost_attribution FROM schedule_runs').get()).toEqual({
+ cost_amount: attribution === 'direct' ? 1 : 2.5,
+ cost_attribution: ['direct', 'mixed'].includes(attribution) ? attribution : 'exact',
+ });
+ },
+ );
+
+ it('rolls back daily and task amounts if saving the user ledger fails', () => {
+ db.exec(`INSERT INTO messages VALUES ('session-1', 'user-1', 'user', '{}');
+ CREATE TRIGGER reject_user_cost BEFORE UPDATE ON messages
+ BEGIN SELECT RAISE(ABORT, 'message write failed'); END;`);
+ expect(() =>
+ tx(db, {
+ name: 'usage.recordMediaSpend',
+ args: {
+ day: '2026-10-15',
+ model: 'image',
+ amount: 1,
+ currency: 'USD',
+ sessionId: 'session-1',
+ userClientId: 'user-1',
+ now: 1,
+ },
+ }),
+ ).toThrow('message write failed');
+ expect(db.prepare('SELECT COUNT(*) AS n FROM daily_spend').get()).toEqual({ n: 0 });
+ expect(db.prepare('SELECT total_cost_amount FROM sessions').get()).toEqual({
+ total_cost_amount: 3,
+ });
+ });
+
+ it('rolls all aggregates back if a later write fails', () => {
+ db.exec(`CREATE TRIGGER reject_media_cost BEFORE INSERT ON daily_model_usage
+ BEGIN SELECT RAISE(ABORT, 'model write failed'); END;`);
+ expect(() => spend('USD', 'session-1')).toThrow('model write failed');
+ expect(db.prepare('SELECT COUNT(*) AS n FROM daily_spend').get()).toEqual({ n: 0 });
+ expect(db.prepare('SELECT total_cost_amount FROM sessions').get()).toEqual({
+ total_cost_amount: 3,
+ });
+ });
+});
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index 21974718dc..72c7b7448c 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -1,4 +1,5 @@
import { runTaskTagsTransaction } from '../worker/opHandlers/taskTagsTx.js';
+import { recordMediaSpend } from '../worker/opHandlers/mediaSpendTx.js';
import { createAutoReviewIntentProjection } from '@cindy/maker-shared/auto-review-intent';
import { batchAutoReviewProjection, readAutoReviewProjection } from '../autoReviewProjection.js';
import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from '../sharedTaskClosureSql.js';
@@ -25,6 +26,7 @@ const readAutoReviewProjection = ${readAutoReviewProjection.toString()};
const batchAutoReviewProjection = ${batchAutoReviewProjection.toString()};
const CLOSE_SHARED_TASKS_FOR_SESSION_SQL = ${JSON.stringify(CLOSE_SHARED_TASKS_FOR_SESSION_SQL)};
const runTaskTagsTransaction = ${runTaskTagsTransaction.toString()};
+const recordMediaSpend = ${recordMediaSpend.toString()};
// 旧版 inline worker fallback。默认运行时走 .vite/build/dbWorker.js;
// 这段只作为打包路径回滚口保留,后续验证 macOS / Windows packaged 后删除。
const { parentPort, workerData } = require('node:worker_threads');
@@ -422,6 +424,8 @@ function dispatchTransaction(readyDb, payload) {
const request = asRecord(payload, 'tx args');
const name = expectString(request.name, 'name');
switch (name) {
+ case 'usage.recordMediaSpend':
+ return recordMediaSpend(readyDb, request.args);
case 'authorization.readProjection':
return readAutoReviewProjection(readyDb, request.args, createAutoReviewIntentProjection);
case 'codex.importMessages':
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index a345d373ef..6735fe721a 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -1,6 +1,7 @@
import type { TaskTagRequest, TaskTagResult } from '@cindy/maker-shared';
export type DbTxName =
+ | 'usage.recordMediaSpend'
| 'authorization.readProjection'
| 'taskTags.execute'
| 'codex.importMessages'
@@ -1320,7 +1321,18 @@ export type SkillUsageApplyMutationArgs =
| { kind: 'deleteBefore'; analyzerVersion: string; recentSince: number }
| { kind: 'promote'; analyzerVersion: string };
+export interface MediaSpendArgs {
+ day: string;
+ model: string;
+ amount: number;
+ currency: 'USD' | 'CNY';
+ sessionId?: string;
+ userClientId?: string;
+ now: number;
+}
+
export type DbTxArgsByName = {
+ 'usage.recordMediaSpend': MediaSpendArgs;
'authorization.readProjection': { sessionId: string; leadId: string };
'codex.importMessages': CodexImportMessagesArgs;
'claude.importMessages': ClaudeImportMessagesArgs;
@@ -1406,6 +1418,12 @@ export type DbTxArgsByName = {
};
export type DbTxResultByName = {
+ 'usage.recordMediaSpend': {
+ legacyUsd: number;
+ amount: number;
+ currency: 'USD' | 'CNY';
+ approximate: number;
+ } | null;
'authorization.readProjection': import('../../autoReviewProjection.js').StoredAutoReviewProjection;
'codex.importMessages': { changed: number };
'claude.importMessages': { changed: number };
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
index 86d684372e..a13ec58f7f 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
@@ -8,6 +8,8 @@ import * as currentDb from '../../client/current';
import { runDeviceLinkInvokeContext } from '../../../device-link/invoke-context';
import { MAX_HISTORY_SCAN_ROWS } from '../historyViewReader';
import { historyViewLeaves, type HistoryViewPage, type HistoryDetailPage, type HistoryMessageSource } from '@cindy/maker-shared/message-window';
+import type { DbClient } from '../../client/DbClient';
+import { captureMediaUserTurn, refreshMediaUserTurnCost } from '../../../usage/mediaTurnCost';
const h = vi.hoisted(() => ({
db: null as ReturnType<typeof drizzle> | null,
@@ -1417,3 +1419,56 @@ describe('readPriorUserRoundCost', () => {
});
});
});
+
+describe('media user-round costs', () => {
+ const actual = (amount: number) => ({ amount, currency: 'USD', approximate: false, kind: 'actual-cost' });
+ function fixture() {
+ const sqlite = createDb();
+ sqlite.prepare('INSERT INTO sessions (id) VALUES (?)').run('s1');
+ const db = {
+ drizzle: h.db,
+ queryOne: async (query: string, params: unknown[] = []) => sqlite.prepare(query).get(...params),
+ exec: async (query: string, params: unknown[] = []) => sqlite.prepare(query).run(...params),
+ } as unknown as DbClient;
+ return { sqlite, db };
+ }
+
+ it('adds media to the visible round, keeps raw subscription valuation, and does not carry it to the next user', async () => {
+ const { sqlite, db } = fixture();
+ insertCostMessage(sqlite, { id: 'user', role: 'user', createdAt: 1, agentMeta: { mediaCosts: [actual(0.75)] } });
+ insertCostMessage(sqlite, { id: 'segment', role: 'assistant', createdAt: 2, agentMeta: { turnCost: actual(0.25) } });
+ insertCostMessage(sqlite, { id: 'resume', role: 'user', createdAt: 3, agentMeta: { autoResume: true } });
+ insertCostMessage(sqlite, { id: 'final', role: 'assistant', createdAt: 4,
+ agentMeta: { turnCostUsd: 2, turnCostIsEstimate: true, model: 'keep-model' } });
+ expect(await captureMediaUserTurn(db, 's1')).toEqual({ clientId: 'user' });
+ expect(await refreshMediaUserTurnCost(db, 's1', 'user')).toMatchObject({
+ clientId: 'final', userTurnMoney: { amount: 3, kind: 'actual-cost' }, userTurnCostIsEstimate: true,
+ });
+ const meta = JSON.parse((sqlite.prepare("SELECT agent_meta FROM messages WHERE id = 'final'").get() as { agent_meta: string }).agent_meta);
+ expect(meta).toMatchObject({ turnCostUsd: 2, turnCostIsEstimate: true, model: 'keep-model', userTurnCost: { amount: 3 } });
+ // The next real user begins a new round, including for same-millisecond rows.
+ insertCostMessage(sqlite, { id: 'next-user', role: 'user', createdAt: 4 });
+ insertCostMessage(sqlite, { id: 'next-answer', role: 'assistant', createdAt: 4 });
+ expect((await readPriorUserRoundCost('s1', 'next-answer')).money).toBeNull();
+ expect((await refreshMediaUserTurnCost(db, 's1', 'user'))?.clientId).toBe('final');
+ });
+
+ it('projects media-only responses without inventing a chat segment price and ignores clear/rewind', async () => {
+ const { sqlite, db } = fixture();
+ insertCostMessage(sqlite, { id: 'user', role: 'user', createdAt: 10, agentMeta: { mediaCosts: [actual(0.75)] } });
+ expect(await refreshMediaUserTurnCost(db, 's1', 'user')).toBeNull();
+ insertCostMessage(sqlite, { id: 'answer', role: 'assistant', createdAt: 11 });
+ expect(await refreshMediaUserTurnCost(db, 's1', 'user')).toMatchObject({
+ clientId: 'answer', userTurnMoney: actual(0.75), userTurnCostIsEstimate: false,
+ });
+ const meta = JSON.parse((sqlite.prepare("SELECT agent_meta FROM messages WHERE id = 'answer'").get() as { agent_meta: string }).agent_meta);
+ expect(meta.turnCost).toBeUndefined();
+ sqlite.prepare("UPDATE messages SET rewind_at = 12 WHERE id = 'user'").run();
+ expect(await captureMediaUserTurn(db, 's1')).toBeNull();
+ expect(await refreshMediaUserTurnCost(db, 's1', 'user')).toBeNull();
+ sqlite.prepare('UPDATE messages SET rewind_at = NULL').run();
+ sqlite.prepare('UPDATE sessions SET cleared_at = 10').run();
+ expect(await captureMediaUserTurn(db, 's1')).toBeNull();
+ expect(await refreshMediaUserTurnCost(db, 's1', 'user')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index 8e29fa4159..aee72f1cbe 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -27,6 +27,7 @@ import { historyOutlineContent, historyOutlineContentStamp, withHistoryArtifacts
import { historyViewLeaves, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
import { getDbClient, getCurrentDbClientSnapshot } from '../client/current';
+import type { DbClient } from '../client/DbClient';
import type { ContextRebuildArgs } from '../client/tx/types';
import { latestVisiblePreviewRow } from '../latestMessageText';
import { messages, sessions } from '../schema';
@@ -2045,8 +2046,9 @@ export async function broadcastMessageAgentMetaUpdate(
export async function readPriorUserRoundCost(
sessionId: string,
assistantClientId: string,
+ client: DbClient = getDbClient(),
): Promise<PriorUserRoundCost> {
- const db = getDbClient().drizzle;
+ const db = client.drizzle;
const [target] = await db
.select({ createdAt: messages.createdAt, rowid: messageRowid })
.from(messages)
@@ -2108,6 +2110,13 @@ export async function readPriorUserRoundCost(
);
const values: RegionalMoney[] = [];
+ const mediaCosts = parseAgentMetaRecord(boundary.agentMeta)?.mediaCosts;
+ if (Array.isArray(mediaCosts)) {
+ for (const value of mediaCosts) {
+ const cost = normalizeRegionalMoney(value);
+ if (cost?.kind === 'actual-cost' && cost.amount > 0) values.push(cost);
+ }
+ }
const estimatedCurrencies = new Set<RegionalMoney['currency']>();
for (const row of assistantRows) {
const meta = parseAgentMetaRecord(row.agentMeta);
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/mediaSpendTx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/mediaSpendTx.ts
new file mode 100644
index 0000000000..dd989e4c59
--- /dev/null
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/mediaSpendTx.ts
@@ -0,0 +1,107 @@
+import type Database from 'better-sqlite3';
+import type { MediaSpendArgs } from '../../client/tx/types.js';
+
+/** Self-contained: the inline worker also embeds this function. */
+export function recordMediaSpend(db: Database.Database, args: MediaSpendArgs) {
+ const { day, model, amount, currency, sessionId, userClientId, now } = args;
+ if (!Number.isFinite(amount) || amount <= 0 || (currency !== 'USD' && currency !== 'CNY')) {
+ throw new Error('Invalid media spend');
+ }
+ return db.transaction(() => {
+ db.prepare(
+ `INSERT INTO daily_spend
+ (day, cost_amount, cost_currency, updated_at) VALUES (?, ?, ?, ?)
+ ON CONFLICT(day, cost_currency) DO UPDATE SET
+ cost_amount = cost_amount + excluded.cost_amount, updated_at = excluded.updated_at`,
+ ).run(day, amount, currency, now);
+ // Media has no chat tokens and must not be attributed to a guessed harness.
+ db.prepare(
+ `INSERT INTO daily_model_usage
+ (day, agent_kind, model, cost_amount, cost_currency, updated_at)
+ VALUES (?, 'media', ?, ?, ?, ?)
+ ON CONFLICT(day, agent_kind, model, cost_currency) DO UPDATE SET
+ cost_amount = cost_amount + excluded.cost_amount, updated_at = excluded.updated_at`,
+ ).run(day, model, amount, currency, now);
+ if (!sessionId) return null;
+ // The submitting user row is the durable attribution, including tool-only
+ // runs. Never look up the latest user after the paid response has arrived.
+ if (userClientId) {
+ const row = db
+ .prepare(
+ `SELECT agent_meta FROM messages WHERE session_id = ? AND client_id = ? AND role = 'user'`,
+ )
+ .get(sessionId, userClientId) as { agent_meta: string | null } | undefined;
+ if (row) {
+ let meta: Record<string, unknown> = {};
+ try {
+ const parsed: unknown = JSON.parse(row.agent_meta ?? '{}');
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ meta = parsed as Record<string, unknown>;
+ }
+ } catch {
+ /* legacy malformed metadata */
+ }
+ const costs = (Array.isArray(meta.mediaCosts) ? meta.mediaCosts : []).filter(
+ (
+ value,
+ ): value is {
+ amount: number;
+ currency: 'USD' | 'CNY';
+ approximate: false;
+ kind: 'actual-cost';
+ } =>
+ value &&
+ Number.isFinite(value.amount) &&
+ value.amount >= 0 &&
+ (value.currency === 'USD' || value.currency === 'CNY') &&
+ value.kind === 'actual-cost',
+ );
+ const existing = costs.find((value) => value.currency === currency);
+ if (existing) existing.amount += amount;
+ else costs.push({ amount, currency, approximate: false, kind: 'actual-cost' });
+ meta.mediaCosts = costs;
+ db.prepare(`UPDATE messages SET agent_meta = ? WHERE session_id = ? AND client_id = ?`).run(
+ JSON.stringify(meta),
+ sessionId,
+ userClientId,
+ );
+ const origin = meta.origin as { kind?: string; runId?: string } | undefined;
+ if (origin?.kind === 'scheduler' && typeof origin.runId === 'string') {
+ // Same message-ledger snapshot policy as runCostLedger: a direct
+ // snapshot excludes message costs; mixed snapshots already include them.
+ db.prepare(
+ `UPDATE schedule_runs SET
+ cost_amount = CASE WHEN cost_attribution = 'direct' THEN cost_amount ELSE cost_amount + ? END,
+ cost_currency = ?,
+ cost_attribution = CASE WHEN cost_attribution IN ('direct', 'mixed') THEN cost_attribution ELSE 'exact' END
+ WHERE id = ? AND (cost_currency IS NULL OR cost_currency = ?)`,
+ ).run(amount, currency, origin.runId, currency);
+ }
+ }
+ }
+ db.prepare(
+ `UPDATE sessions SET
+ total_cost_amount = CASE WHEN total_cost_currency IS NULL OR total_cost_currency = ?
+ THEN total_cost_amount + ? ELSE ? END,
+ total_cost_is_approximate = CASE WHEN total_cost_currency IS NULL OR total_cost_currency = ?
+ THEN total_cost_is_approximate ELSE 0 END,
+ total_cost_currency = ? WHERE id = ?`,
+ ).run(currency, amount, amount, currency, currency, sessionId);
+ return (
+ (db
+ .prepare(
+ `SELECT total_cost_usd AS legacyUsd, total_cost_amount AS amount,
+ total_cost_currency AS currency, total_cost_is_approximate AS approximate
+ FROM sessions WHERE id = ?`,
+ )
+ .get(sessionId) as
+ | {
+ legacyUsd: number;
+ amount: number;
+ currency: 'USD' | 'CNY';
+ approximate: number;
+ }
+ | undefined) ?? null
+ );
+ })();
+}
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 72c165f280..ef1151a7e0 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -1,4 +1,5 @@
import { runTaskTagsTransaction } from './taskTagsTx.js';
+import { recordMediaSpend } from './mediaSpendTx.js';
import { batchAutoReviewProjection, readAutoReviewProjectionTransaction } from '../../autoReviewProjection.js';
import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from '../../sharedTaskClosureSql.js';
import { normalizeBotName } from '../../../../shared/botCreation.js';
@@ -58,6 +59,8 @@ function dispatchTransaction(db: Database.Database, args: unknown): unknown {
const txArgs = payload.args;
switch (name) {
+ case 'usage.recordMediaSpend':
+ return recordMediaSpend(db, txArgs as import('../../client/tx/types.js').MediaSpendArgs);
case 'authorization.readProjection':
return readAutoReviewProjectionTransaction(db, txArgs);
case 'codex.importMessages':
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxyMediaBilling.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxyMediaBilling.test.ts
new file mode 100644
index 0000000000..440ab09930
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxyMediaBilling.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { CindyProxyMediaServiceOptions } from '../../cindy-proxy-media/types.js';
+
+const mocks = vi.hoisted(() => ({
+ createService: vi.fn(),
+ prepareBilling: vi.fn(),
+ recordBilling: vi.fn(),
+ fetch: vi.fn(),
+}));
+vi.mock('../../model-access/effectiveEndpoint.js', () => ({
+ effectiveXdGatewayBaseUrl: () => 'https://gateway.example.invalid',
+}));
+vi.mock('../../cindy-proxy-media/service.js', () => ({
+ createCindyProxyMediaService: mocks.createService,
+}));
+vi.mock('../../cindy-media/generatedMedia.js', () => ({
+ createBlobImageStorage: () => ({}),
+ createBlobVideoStorage: () => ({}),
+}));
+vi.mock('../../imageCacheStore.js', () => ({ resolveSafe: vi.fn() }));
+vi.mock('../../secrets/providerSecretStore.js', () => ({
+ getProviderSecretStore: () => ({ get: () => 'test-key' }),
+}));
+vi.mock('../../appCapabilities.js', () => ({
+ getAppCapabilities: () => ({ canUseCindyGateway: true }),
+}));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));
+vi.mock('../../usage/gatewayMediaBilling.js', () => ({
+ prepareGatewayMediaBilling: mocks.prepareBilling,
+}));
+
+import { getCindyProxyMediaService, getCindyVideoProviderRegistry } from '../cindyProxyMedia.js';
+
+describe('legacy Gateway media billing wiring', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createService.mockReturnValue({ backend: {} });
+ mocks.prepareBilling.mockResolvedValue(mocks.recordBilling);
+ mocks.recordBilling.mockResolvedValue(undefined);
+ vi.stubGlobal('fetch', mocks.fetch);
+ });
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('wraps JSON and multipart image creation without consuming the response body', async () => {
+ getCindyProxyMediaService();
+ const opts = mocks.createService.mock.calls[0][0] as CindyProxyMediaServiceOptions;
+ const doFetch = opts.imageApi.fetchImplementation!;
+ for (const body of [JSON.stringify({ model: 'image-json' }), new FormData()]) {
+ if (body instanceof FormData) body.set('model', 'image-multipart');
+ const res = Response.json({ data: [] });
+ mocks.fetch.mockResolvedValueOnce(res);
+ expect(
+ await doFetch('https://gateway.example.invalid/v1/images/generations', {
+ method: 'POST',
+ body,
+ }),
+ ).toBe(res);
+ expect(res.bodyUsed).toBe(false);
+ }
+ expect(mocks.prepareBilling.mock.calls.map(([input]) => input.model)).toEqual([
+ 'image-json',
+ 'image-multipart',
+ ]);
+ expect(mocks.recordBilling).toHaveBeenCalledTimes(2);
+ });
+
+ 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');
+ expect(mocks.recordBilling).toHaveBeenCalledOnce();
+ const headers = { 'X-Nova-AIGateway-Billing': Buffer.from('{"cost":1}').toString('base64url') };
+ mocks.fetch.mockResolvedValueOnce(Response.json({ status: 'running' }, { headers }));
+ await provider.poll(handle);
+ mocks.fetch.mockResolvedValueOnce(new Response('video-bytes', { headers }));
+ await provider.download('https://cdn.example.invalid/video.mp4');
+ expect(mocks.prepareBilling).toHaveBeenCalledOnce();
+ expect(mocks.recordBilling).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts b/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts
index 2cf5751df3..031b31d503 100644
--- a/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts
+++ b/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts
@@ -13,6 +13,7 @@ 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');
@@ -31,6 +32,25 @@ function getGatewayBaseUrl(): string {
return effectiveXdGatewayBaseUrl();
}
+/** Only Gateway creates are billable. Polling and CDN downloads bypass accounting. */
+const gatewayMediaFetch: typeof fetch = async (input, init) => {
+ if (init?.method?.toUpperCase() !== 'POST') return fetch(input, init);
+ let model = 'unknown';
+ if (typeof init.body === 'string') {
+ try {
+ const body = JSON.parse(init.body) as { model?: unknown };
+ if (typeof body?.model === 'string') model = body.model;
+ } catch { /* The response header remains the authoritative model. */ }
+ } else if (init.body instanceof FormData) {
+ 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;
+};
+
/**
* XD Gateway 图像/视频后端单例。lizi_art MCP 工具层已退役(2026-07-12),
* 本服务不再对 agent 暴露工具,只作为 host 侧链路的后端:
@@ -56,6 +76,7 @@ export function getCindyProxyMediaService(): CindyProxyMediaService {
artService = createCindyProxyMediaService({
imageApi: {
getApiKey: readApiKey,
+ fetchImplementation: gatewayMediaFetch,
proxy: {
baseUrl: getGatewayBaseUrl(),
generatePath: '/v1/images/generations',
@@ -81,6 +102,7 @@ function createGatewayVideoProviders(baseUrl: string) {
return [
createSeedanceProvider({
baseUrl,
+ fetchImplementation: gatewayMediaFetch,
getApiKey: readApiKey,
logger: log,
}),
@@ -89,11 +111,13 @@ function createGatewayVideoProviders(baseUrl: string) {
// seedance-fast 之后,不抢出厂默认。
createSeedance25Provider({
baseUrl,
+ fetchImplementation: gatewayMediaFetch,
getApiKey: readApiKey,
logger: log,
}),
createHappyhorseProvider({
baseUrl,
+ fetchImplementation: gatewayMediaFetch,
getApiKey: readApiKey,
logger: log,
}),
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 6dc15e46d5..6549ae124f 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -1834,7 +1834,7 @@ export function getCindyGhostsMcpDeps(
: undefined;
let result: Record<string, unknown>;
try {
- result = await callCindyMedia(request, downloadContext);
+ result = await callCindyMedia(request, downloadContext, sessionId);
} finally {
downloadContext?.dispose?.();
}
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
index 77cab8bf61..e5754e92d2 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
@@ -276,6 +276,42 @@ function createStorageHarness(queries?: { query: string; params: unknown[] }[])
};
}
+it.each(['api', 'subscription', 'tool-only'])('includes media in both run history and schedule totals for %s runs', async (mode) => {
+ const harness = createStorageHarness();
+ try {
+ harness.sqlite.prepare(`INSERT INTO sessions (id, title, created_at, updated_at)
+ VALUES ('sess-media', 'media task', 1, 1)`).run();
+ await harness.storage.insert(baseSchedule({ targetSessionId: 'sess-media' }));
+ await harness.storage.insertRun({ id: 'run-media', scheduleId: 'sch-1', sessionId: 'sess-media',
+ firedAt: 10, status: 'success', costAttribution: 'exact' });
+ const origin = { kind: 'scheduler', scheduleId: 'sch-1', runId: 'run-media' };
+ const insert = harness.sqlite.prepare(`INSERT INTO messages
+ (id, client_id, session_id, role, content, agent_meta, created_at)
+ VALUES (?, ?, 'sess-media', ?, '{}', ?, ?)`);
+ insert.run('user-media', 'user-media', 'user', JSON.stringify({ origin,
+ mediaCosts: [{ amount: 0.75, currency: 'USD', approximate: false, kind: 'actual-cost' }],
+ }), 10);
+ if (mode !== 'tool-only') {
+ insert.run('answer-media', 'answer-media', 'assistant', JSON.stringify({ origin,
+ turnCostUsd: 0.25, turnCostIsEstimate: mode === 'subscription',
+ // Display totals must not be counted a second time by scheduler billing.
+ userTurnCostUsd: 1,
+ }), 11);
+ }
+ const actual = mode === 'api' ? 1 : 0.75;
+ const estimated = mode === 'subscription' ? 0.25 : 0;
+ for (let read = 0; read < 2; read++) {
+ expect(await harness.storage.listRuns('sch-1')).toMatchObject([{
+ costMoney: { amount: actual }, estimatedValueMoney: { amount: estimated }, costAttribution: 'exact',
+ }]);
+ expect(await harness.storage.listCostSummaries()).toMatchObject([{
+ scheduleId: 'sch-1', totalMoney: { amount: actual },
+ totalEstimatedValueMoney: { amount: estimated },
+ }]);
+ }
+ } finally { harness.close(); }
+});
+
function enableLegacySessionFallback(
harness: ReturnType<typeof createStorageHarness>,
scheduleId: string,
diff --git a/apps/desktop/src/main/scheduler-host/storage.ts b/apps/desktop/src/main/scheduler-host/storage.ts
index 2fad75770f..ca38d22214 100644
--- a/apps/desktop/src/main/scheduler-host/storage.ts
+++ b/apps/desktop/src/main/scheduler-host/storage.ts
@@ -289,6 +289,7 @@ function turnCostFromAgentMeta(agentMeta: string | null): {
turnCostUsd?: unknown;
turnCostIsEstimate?: unknown;
turnUsageDetails?: unknown;
+ mediaCosts?: unknown;
};
const totalTokens = normalizeTurnUsageDetails(parsed.turnUsageDetails)?.totalTokens ?? 0;
const structured = normalizeRegionalMoney(parsed.turnCost);
@@ -299,19 +300,16 @@ function turnCostFromAgentMeta(agentMeta: string | null): {
? legacyUsdMoney(parsed.turnCostUsd)
: undefined;
const money = structured ?? legacy;
- if (!money || money.amount <= 0) {
- return {
- costMoney: null,
- estimatedValueMoney: null,
- legacyProjectedActualAmount: 0,
- totalTokens,
- };
- }
- const isEstimate = parsed.turnCostIsEstimate === true || money.kind === 'value-estimate';
+ const mediaCosts = (Array.isArray(parsed.mediaCosts) ? parsed.mediaCosts : [])
+ .map(normalizeRegionalMoney)
+ .filter((value): value is RegionalMoney => Boolean(value && value.kind === 'actual-cost' && value.amount > 0));
+ const isEstimate = parsed.turnCostIsEstimate === true || money?.kind === 'value-estimate';
return {
- costMoney: isEstimate ? null : money,
- estimatedValueMoney: isEstimate ? asValueEstimateMoney(money) : null,
- legacyProjectedActualAmount: !structured && !isEstimate ? money.amount : 0,
+ costMoney: addCompatibleRegionalMoney([
+ ...mediaCosts, ...(money && money.amount > 0 && !isEstimate ? [money] : []),
+ ]),
+ estimatedValueMoney: money && money.amount > 0 && isEstimate ? asValueEstimateMoney(money) : null,
+ legacyProjectedActualAmount: !structured && !isEstimate ? (money?.amount ?? 0) : 0,
totalTokens,
};
} catch {
@@ -632,7 +630,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
// Chunking bind parameters must also bound RPC fan-out for large histories.
for (const sessionIdChunk of chunkArray([...sessionIds], SQLITE_IN_CHUNK_SIZE)) {
rows.push(...await db.select({ agentMeta: messages.agentMeta }).from(messages)
- .where(and(inArray(messages.sessionId, sessionIdChunk), eq(messages.role, 'assistant'))));
+ .where(and(inArray(messages.sessionId, sessionIdChunk), inArray(messages.role, ['user', 'assistant']))));
}
const ledger = new Map<
string,
@@ -939,9 +937,8 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
}
if (row.role === 'user') {
activeScheduleId = scheduleOriginFromAgentMeta(row.agentMeta)?.scheduleId ?? null;
- continue;
}
- if (row.role !== 'assistant') continue;
+ if (row.role !== 'assistant' && row.role !== 'user') continue;
const turnCost = turnCostFromAgentMeta(row.agentMeta);
const cost = turnCost.costMoney?.amount ?? 0;
const estimatedValue = turnCost.estimatedValueMoney?.amount ?? 0;
diff --git a/apps/desktop/src/main/sessionSpendBroadcaster.ts b/apps/desktop/src/main/sessionSpendBroadcaster.ts
index 783c4848d7..7073636e6c 100644
--- a/apps/desktop/src/main/sessionSpendBroadcaster.ts
+++ b/apps/desktop/src/main/sessionSpendBroadcaster.ts
@@ -141,7 +141,7 @@ export async function recordSessionTurnSpend(
: current
: (current ?? legacy);
if (!isOwnerScopeCurrent(ownerScope)) return;
- broadcast(
+ broadcastSessionSpend(
{
sessionId,
totalMoney,
@@ -154,7 +154,8 @@ export async function recordSessionTurnSpend(
}
}
-function broadcast(payload: SessionSpendPayload, ownerScope: OwnerScope | null = null): void {
+export function broadcastSessionSpend(payload: SessionSpendPayload, ownerScope: OwnerScope | null = null): void {
+ if (!isOwnerScopeCurrent(ownerScope)) return;
const ownerStamp = ownerScope ? ownerScope.ownerStamp : broadcastTap.getSafeDataOwnerPushStamp?.();
// device-link 旁路:控制端经 sessions topic(列表订阅常开,会话未打开也不丢)收到
// 累计 cost 镜像(本模块走裸 UPDATE、不发 sessions:patched,没有这条 tap 控制端的
diff --git a/apps/desktop/src/main/turnCostBroadcaster.ts b/apps/desktop/src/main/turnCostBroadcaster.ts
index 98f4ab958a..1a968127a9 100644
--- a/apps/desktop/src/main/turnCostBroadcaster.ts
+++ b/apps/desktop/src/main/turnCostBroadcaster.ts
@@ -91,7 +91,7 @@ function isOwnerScopeCurrent(scope: OwnerScope): boolean {
return scope === null || broadcastTap.isDataOwnerBroadcastScopeCurrent?.(scope) !== false;
}
-function broadcastTurnCostPayload(payload: MessageTurnCostPayload, ownerScope: OwnerScope): void {
+export function broadcastTurnCostPayload(payload: MessageTurnCostPayload, ownerScope: OwnerScope): void {
if (ownerScope === null) {
broadcastTap.tapWindowBroadcast(MESSAGE_TURN_COST_CHANGED, payload);
} else {
diff --git a/apps/desktop/src/main/usage/__tests__/gatewayMediaBilling.test.ts b/apps/desktop/src/main/usage/__tests__/gatewayMediaBilling.test.ts
new file mode 100644
index 0000000000..4e0961fdbc
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/gatewayMediaBilling.test.ts
@@ -0,0 +1,180 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { parseGatewayMediaBillingHeader } from '../gatewayMediaBillingHeader.js';
+
+const mocks = vi.hoisted(() => ({
+ owner: 'owner-a',
+ current: true,
+ currency: 'CNY' as 'CNY' | 'USD' | null,
+ tx: vi.fn(),
+ sessionPush: vi.fn(),
+ todayPush: vi.fn(),
+ warn: vi.fn(),
+ turnPush: vi.fn(),
+ schedulePush: vi.fn(),
+ captureTurn: vi.fn(),
+ refreshTurn: vi.fn(),
+}));
+vi.mock('../../localDb/client/current.js', () => ({
+ getDbClient: () => ({ tx: mocks.tx }),
+ getCurrentDbClientUserId: () => mocks.owner,
+}));
+vi.mock('../../localDb/dailySpend.js', () => ({ localDayKey: () => '2026-10-15' }));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({ ownerScopeKey: mocks.owner }),
+ isDataOwnerBroadcastScopeCurrent: (scope: { ownerScopeKey: string }) =>
+ mocks.current && scope.ownerScopeKey === mocks.owner,
+}));
+vi.mock('../../sessionSpendBroadcaster.js', () => ({ broadcastSessionSpend: mocks.sessionPush }));
+vi.mock('../../usageBroadcaster.js', () => ({ rebroadcastTodaySpend: mocks.todayPush }));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: mocks.warn }) }));
+vi.mock('../modelPricing.js', () => ({
+ getGatewayMediaBillingCurrency: async () => mocks.currency,
+}));
+vi.mock('../mediaTurnCost.js', () => ({
+ captureMediaUserTurn: mocks.captureTurn,
+ refreshMediaUserTurnCost: mocks.refreshTurn,
+}));
+vi.mock('../../messagePersistBroadcaster.js', () => ({
+ enqueueDurableWrite: (_label: string, fn: () => unknown) => Promise.resolve(fn()),
+}));
+vi.mock('../../turnCostBroadcaster.js', () => ({ broadcastTurnCostPayload: mocks.turnPush }));
+vi.mock('../../maker-ipc/schedule.js', () => ({ broadcastSchedulerChanged: mocks.schedulePush }));
+
+import { prepareGatewayMediaBilling } from '../gatewayMediaBilling.js';
+
+const encode = (payload: unknown) => Buffer.from(JSON.stringify(payload)).toString('base64url');
+const response = (payload: unknown, status = 200) =>
+ new Response('invalid response body', {
+ status,
+ headers: { 'X-Nova-AIGateway-Billing': encode(payload) },
+ });
+
+describe('Gateway media billing', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.owner = 'owner-a';
+ mocks.current = true;
+ mocks.currency = 'CNY';
+ mocks.tx.mockResolvedValue(null);
+ mocks.captureTurn.mockResolvedValue({ clientId: 'original-user', scheduleId: 'schedule-1' });
+ mocks.refreshTurn.mockResolvedValue({
+ sessionId: 'session-1',
+ clientId: 'answer',
+ userTurnMoney: { amount: 0.75, currency: 'CNY' },
+ });
+ });
+
+ it('accepts the Nova payload with optional provider metadata and unpadded Base64URL', () => {
+ expect(
+ parseGatewayMediaBillingHeader(
+ encode({
+ cost: 0.123,
+ model: 'seedance-2.0',
+ task_id: 'task-1',
+ custom_llm_provider: 'seedance',
+ metadata: { output_tokens: 1200 },
+ }),
+ ),
+ ).toEqual({ cost: 0.123, model: 'seedance-2.0' });
+ expect(parseGatewayMediaBillingHeader(encode({ cost: 0 }))).toEqual({ cost: 0 });
+ });
+
+ it.each([
+ null,
+ '',
+ 'not-json',
+ encode({ cost: -1 }),
+ encode({ cost: '1' }),
+ encode({ cost: true }),
+ encode({}),
+ encode([]),
+ Buffer.from('{"cost":1e400}').toString('base64url'),
+ ])('rejects invalid billing %s', (header) => {
+ expect(parseGatewayMediaBillingHeader(header)).toBeNull();
+ });
+
+ it('records the exact header cost once before body parsing, with captured currency and Host task', async () => {
+ mocks.tx.mockResolvedValue({ legacyUsd: 0, amount: 3.5, currency: 'CNY', approximate: 0 });
+ const record = await prepareGatewayMediaBilling({
+ model: 'request-model',
+ sessionId: 'session-1',
+ });
+ mocks.currency = 'USD';
+ const res = response({ cost: 0.75, model: 'billed-model' });
+ await record(res);
+ await record(res);
+ expect(res.bodyUsed).toBe(false);
+ expect(mocks.tx).toHaveBeenCalledExactlyOnceWith('usage.recordMediaSpend', {
+ day: '2026-10-15',
+ model: 'billed-model',
+ amount: 0.75,
+ currency: 'CNY',
+ sessionId: 'session-1',
+ userClientId: 'original-user',
+ now: expect.any(Number),
+ });
+ expect(mocks.sessionPush).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sessionId: 'session-1',
+ totalMoney: { amount: 3.5, currency: 'CNY', approximate: false, kind: 'actual-cost' },
+ }),
+ expect.anything(),
+ );
+ expect(mocks.todayPush).toHaveBeenCalledOnce();
+ expect(mocks.refreshTurn).toHaveBeenCalledWith(expect.anything(), 'session-1', 'original-user');
+ expect(mocks.turnPush).toHaveBeenCalledOnce();
+ expect(mocks.schedulePush).toHaveBeenCalledExactlyOnceWith('schedule-1');
+ });
+
+ it('uses the submitted model when the header omits it', async () => {
+ await (
+ await prepareGatewayMediaBilling({ model: 'request-model' })
+ )(response({ cost: 1 }));
+ expect(mocks.tx).toHaveBeenCalledWith(
+ 'usage.recordMediaSpend',
+ expect.objectContaining({ model: 'request-model' }),
+ );
+ });
+
+ it('retains the original database after an account switch without notifying the new owner', async () => {
+ const record = await prepareGatewayMediaBilling({ model: 'image' });
+ mocks.owner = 'owner-b';
+ await record(response({ cost: 1 }));
+ expect(mocks.tx).toHaveBeenCalledOnce();
+ expect(mocks.sessionPush).not.toHaveBeenCalled();
+ expect(mocks.todayPush).not.toHaveBeenCalled();
+ });
+
+ it('stops preparation if the account changes while currency is being resolved', async () => {
+ const preparing = prepareGatewayMediaBilling({ model: 'image' });
+ mocks.owner = 'owner-b';
+ await expect(preparing).rejects.toThrow('account changed before dispatch');
+ expect(mocks.tx).not.toHaveBeenCalled();
+ });
+
+ it('ignores failed responses, missing headers and zero cost', async () => {
+ for (const res of [response({ cost: 1 }, 500), new Response('{}'), response({ cost: 0 })]) {
+ await (
+ await prepareGatewayMediaBilling({ model: 'image' })
+ )(res);
+ }
+ expect(mocks.tx).not.toHaveBeenCalled();
+ });
+
+ it('does not invent a currency or fail a paid result when persistence fails', async () => {
+ mocks.currency = null;
+ await (
+ await prepareGatewayMediaBilling({ model: 'image' })
+ )(response({ cost: 1 }));
+ expect(mocks.tx).not.toHaveBeenCalled();
+ mocks.currency = 'USD';
+ mocks.tx.mockRejectedValue(new Error('database unavailable'));
+ await expect(
+ (await prepareGatewayMediaBilling({ model: 'image' }))(response({ cost: 1 })),
+ ).resolves.toBeUndefined();
+ expect(mocks.warn).toHaveBeenCalledWith(
+ 'Failed to record Gateway media billing',
+ 'database unavailable',
+ );
+ });
+});
diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
index 014578c4fa..7048f2e8c2 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
@@ -72,6 +72,7 @@ import {
clearGatewayModelPricing,
getGatewayModelPricing,
getGatewayModelPricingForModel,
+ getGatewayMediaBillingCurrency,
MODEL_PRICING_CHANGED_CHANNEL,
prewarmModelPricing,
replaceGatewayModelPricing,
@@ -83,6 +84,10 @@ import {
getCodexSubscriptionValuePrice,
getSubscriptionDirectValuePrice,
} from '../referenceModelPricing';
+import {
+ __resetAccountCurrencyStoreForTesting,
+ __flushAccountCurrencyStoreForTesting,
+} from '../accountCurrencyStore';
let tempUserDataDir: string | null = null;
// 目录整份没声明 currency 时的回落值。不再按构建区域推断 —— 服务端漏发 currency 时
@@ -114,9 +119,12 @@ beforeEach(async () => {
});
mocks.send.mockClear();
__resetModelPricingCacheForTesting();
+ __resetAccountCurrencyStoreForTesting();
+ __resetActiveLedgerCurrencyForTesting();
});
afterEach(async () => {
+ await __flushAccountCurrencyStoreForTesting();
vi.restoreAllMocks();
if (tempUserDataDir) {
await rm(tempUserDataDir, {
@@ -129,6 +137,39 @@ afterEach(async () => {
}
});
+describe('media settlement currency', () => {
+ it('keeps a confirmed account currency when a later catalog omits it', async () => {
+ replaceGatewayModelPricing([{ id: 'image', currency: 'CNY' }]);
+ replaceGatewayModelPricing([{ id: 'image' }]);
+ expect(await getGatewayMediaBillingCurrency()).toBe('CNY');
+ });
+
+ it('restores the same account currency even after credentials invalidate the quote cache', async () => {
+ replaceGatewayModelPricing([{ id: 'image', currency: 'CNY' }]);
+ await __flushAccountCurrencyStoreForTesting();
+ __resetModelPricingCacheForTesting();
+ __resetAccountCurrencyStoreForTesting();
+ __resetActiveLedgerCurrencyForTesting();
+ mocks.resolveOwnerScopedSecretStorageKey.mockReturnValue('rotated-xd');
+ expect(await getGatewayMediaBillingCurrency()).toBe('CNY');
+ });
+
+ it('does not use a default currency or the preceding account currency', async () => {
+ replaceGatewayModelPricing([{ id: 'image' }]);
+ expect(await getGatewayMediaBillingCurrency()).toBeNull();
+ replaceGatewayModelPricing([{ id: 'image', currency: 'CNY' }]);
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-b');
+ replaceGatewayModelPricing([{ id: 'image' }]);
+ expect(await getGatewayMediaBillingCurrency()).toBeNull();
+ });
+
+ it('does not hide a conflicting catalog behind the previously confirmed currency', async () => {
+ replaceGatewayModelPricing([{ id: 'image', currency: 'CNY' }]);
+ replaceGatewayModelPricing([{ id: 'image', currency: 'CNY' }, { id: 'video', currency: 'USD' }]);
+ expect(await getGatewayMediaBillingCurrency()).toBeNull();
+ });
+});
+
describe('gateway model pricing projection', () => {
it('converts model-groups per-token values to provider-scoped per-Mtok quotes', () => {
const pricing = replaceGatewayModelPricing([
diff --git a/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts b/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts
index 1bc5bb0051..88565123bf 100644
--- a/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts
@@ -104,6 +104,15 @@ function harness(over: Partial<PeerUsageSyncDeps> = {}) {
}
describe('usage device rows wire format', () => {
+ it('preserves media fees with zero tokens across devices', async () => {
+ const rows = rowsFor(['2026-10-15'], 0);
+ rows.modelRows[0].agentKind = 'media';
+ const decoded = await decodeUsageDeviceRowsResponse(await hostResponse(rows, '2026-10-15', null));
+ expect(decoded?.kind).toBe('rows');
+ if (decoded?.kind !== 'rows') throw new Error('expected rows');
+ expect(decoded.rows.modelRows[0]).toMatchObject({ agentKind: 'media', money: usd(1), inputTokens: 0 });
+ });
+
it('round-trips rows, filters by sinceDay and validates requests', async () => {
const rows = rowsFor(['2026-09-24', '2026-09-25', '2026-09-26']);
const decoded = await decodeUsageDeviceRowsResponse(
diff --git a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
index 3b301775d3..fab24fccef 100644
--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
@@ -337,6 +337,22 @@ describe('getSubscriptionValuePriceFor', () => {
});
describe('readUsageHistoryWith', () => {
+ it('keeps media fees in actual totals and model detail without inventing chat tokens', async () => {
+ const money = actual(1.25);
+ const result = await readUsageHistoryWith(makeDeps({
+ getAllSpendDays: async () => [{ day: TODAY, monies: [money] }],
+ getModelUsageSince: async () => [{
+ ...modelRow(TODAY, 'pi', 'seedance-2.0', money), agentKind: 'media',
+ }],
+ }));
+ expect(result.totals.today.amount).toBe(1.25);
+ expect(result.totals.last30DaysTokens).toBe(0);
+ expect(result.models).toEqual([expect.objectContaining({
+ agentKind: 'media', model: 'seedance-2.0', money, estimatedMoney: null,
+ })]);
+ expect(result.modelDaily[0]).toMatchObject({ agentKind: 'media', apiMoney: money, tokens: 0 });
+ });
+
it('supports an all-time request without changing the default 30-day model window', async () => {
const oldRow = modelRow('2026-04-01', 'codex', 'gpt-5.5', actual(0), {
inputTokens: 123,
diff --git a/apps/desktop/src/main/usage/gatewayMediaBilling.ts b/apps/desktop/src/main/usage/gatewayMediaBilling.ts
new file mode 100644
index 0000000000..5016ab36f8
--- /dev/null
+++ b/apps/desktop/src/main/usage/gatewayMediaBilling.ts
@@ -0,0 +1,118 @@
+import { getDbClient, getCurrentDbClientUserId } from '../localDb/client/current.js';
+import type { DbClient } from '../localDb/client/DbClient.js';
+import { localDayKey } from '../localDb/dailySpend.js';
+import { createLogger } from '../logger.js';
+import {
+ captureDataOwnerBroadcastScope,
+ isDataOwnerBroadcastScopeCurrent,
+} from '../device-link/broadcast-tap.js';
+import { broadcastSessionSpend } from '../sessionSpendBroadcaster.js';
+import { rebroadcastTodaySpend } from '../usageBroadcaster.js';
+import { getGatewayMediaBillingCurrency } from './modelPricing.js';
+import { parseGatewayMediaBillingHeader } from './gatewayMediaBillingHeader.js';
+import { captureMediaUserTurn, refreshMediaUserTurnCost } from './mediaTurnCost.js';
+import { enqueueDurableWrite } from '../messagePersistBroadcaster.js';
+import { broadcastTurnCostPayload } from '../turnCostBroadcaster.js';
+import { broadcastSchedulerChanged } from '../maker-ipc/schedule.js';
+import {
+ addRegionalMoney,
+ legacyUsdMoney,
+ type RegionalMoney,
+} from '../../shared/regionalMoney.js';
+
+const log = createLogger('gatewayMediaBilling');
+
+/** 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>> {
+ const ownerScope = captureDataOwnerBroadcastScope();
+ const dbOwnerId = getCurrentDbClientUserId();
+ const db = input.db ?? (dbOwnerId ? getDbClient() : null);
+ const currency = await getGatewayMediaBillingCurrency().catch(() => null);
+ const userTurn =
+ db && input.sessionId
+ ? await enqueueDurableWrite('media-billing-target', () =>
+ captureMediaUserTurn(db, input.sessionId!),
+ )
+ : null;
+ 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 value = response.headers.get('X-Nova-AIGateway-Billing');
+ const billing = parseGatewayMediaBillingHeader(value);
+ if (!billing) {
+ if (value) log.warn('Ignoring invalid Gateway media billing header');
+ return;
+ }
+ if (billing.cost === 0) return;
+ if (!db || !currency) {
+ log.warn('Media billing unavailable: account database or settlement currency missing');
+ return;
+ }
+ try {
+ const now = Date.now();
+ // Called only for the original submit response, before reading/downloading its body.
+ // 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', {
+ day: localDayKey(now),
+ model: billing.model ?? input.model,
+ amount: billing.cost,
+ currency,
+ sessionId: input.sessionId,
+ userClientId: userTurn?.clientId,
+ now,
+ });
+ const turnCost =
+ input.sessionId && userTurn
+ ? await refreshMediaUserTurnCost(db, input.sessionId, userTurn.clientId).catch(
+ (error) => {
+ log.warn('Failed to refresh media user-turn cost', String(error));
+ return null;
+ },
+ )
+ : null;
+ return { session, turnCost };
+ });
+ if (!isDataOwnerBroadcastScopeCurrent(ownerScope) || getCurrentDbClientUserId() !== dbOwnerId)
+ return;
+ if (turnCost) broadcastTurnCostPayload(turnCost, ownerScope);
+ if (userTurn?.scheduleId) broadcastSchedulerChanged(userTurn.scheduleId);
+ if (input.sessionId && session) {
+ const current: RegionalMoney = {
+ amount: session.amount,
+ currency: session.currency,
+ approximate: Boolean(session.approximate),
+ kind: 'actual-cost',
+ };
+ const legacy = legacyUsdMoney(session.legacyUsd);
+ const totalMoney =
+ legacy.amount > 0 && legacy.currency === current.currency
+ ? addRegionalMoney([legacy, current])
+ : current;
+ broadcastSessionSpend(
+ {
+ sessionId: input.sessionId,
+ totalMoney,
+ ...(totalMoney.currency === 'USD' ? { totalCostUsd: totalMoney.amount } : {}),
+ },
+ ownerScope,
+ );
+ }
+ await rebroadcastTodaySpend(ownerScope);
+ } catch (error) {
+ // Never retry a paid request because local accounting failed.
+ log.warn(
+ 'Failed to record Gateway media billing',
+ error instanceof Error ? error.message : String(error),
+ );
+ }
+ };
+}
diff --git a/apps/desktop/src/main/usage/gatewayMediaBillingHeader.ts b/apps/desktop/src/main/usage/gatewayMediaBillingHeader.ts
new file mode 100644
index 0000000000..9f526d2753
--- /dev/null
+++ b/apps/desktop/src/main/usage/gatewayMediaBillingHeader.ts
@@ -0,0 +1,21 @@
+/** Nova passthrough billing is Base64URL JSON, independent of the response body. */
+export interface GatewayMediaBilling {
+ cost: number;
+ model?: string;
+}
+
+export function parseGatewayMediaBillingHeader(value: string | null): GatewayMediaBilling | null {
+ if (!value || value.length > 64 * 1024 || !/^[A-Za-z0-9_-]+={0,2}$/.test(value)) return null;
+ try {
+ const payload: unknown = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;
+ const { cost, model } = payload as Record<string, unknown>;
+ if (typeof cost !== 'number' || !Number.isFinite(cost) || cost < 0) return null;
+ return {
+ cost,
+ ...(typeof model === 'string' && model.trim() ? { model: model.trim() } : {}),
+ };
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/desktop/src/main/usage/mediaTurnCost.ts b/apps/desktop/src/main/usage/mediaTurnCost.ts
new file mode 100644
index 0000000000..362e050a07
--- /dev/null
+++ b/apps/desktop/src/main/usage/mediaTurnCost.ts
@@ -0,0 +1,100 @@
+import type { DbClient } from '../localDb/client/DbClient.js';
+import { readPriorUserRoundCost } from '../localDb/ipc/messages.js';
+import {
+ addCompatibleRegionalMoney,
+ asValueEstimateMoney,
+ legacyUsdMoney,
+ normalizeRegionalMoney,
+} from '../../shared/regionalMoney.js';
+import type { MessageTurnCostPayload } from '../../shared/turnCostPayload.js';
+
+const realUser = `m.role = 'user' AND CASE WHEN json_valid(m.agent_meta)
+ THEN json_extract(m.agent_meta, '$.autoResume') END IS NOT 1`;
+
+/** Run in the message persistence FIFO before dispatch, while this turn owns the tool call. */
+export async function captureMediaUserTurn(db: DbClient, sessionId: string) {
+ const row = await db.queryOne<{ clientId: string; agentMeta: string | null }>(
+ `SELECT m.client_id AS clientId, m.agent_meta AS agentMeta FROM messages m
+ JOIN sessions s ON s.id = m.session_id
+ WHERE m.session_id = ? AND ${realUser} AND m.rewind_at IS NULL
+ AND (s.cleared_at IS NULL OR m.created_at > s.cleared_at)
+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1`,
+ [sessionId],
+ );
+ if (!row) return null;
+ let scheduleId: string | undefined;
+ try {
+ const origin = JSON.parse(row.agentMeta ?? '{}')?.origin;
+ if (origin?.kind === 'scheduler' && typeof origin.scheduleId === 'string') {
+ scheduleId = origin.scheduleId;
+ }
+ } catch {
+ /* metadata without a scheduler origin */
+ }
+ return { clientId: row.clientId, scheduleId };
+}
+
+/** Refresh an already finished response too, without moving a late fee into the next user turn. */
+export async function refreshMediaUserTurnCost(
+ db: DbClient,
+ sessionId: string,
+ userClientId: string,
+): Promise<MessageTurnCostPayload | null> {
+ const row = await db.queryOne<{ clientId: string; agentMeta: string | null }>(
+ `SELECT a.client_id AS clientId, a.agent_meta AS agentMeta FROM messages a
+ JOIN messages u ON u.session_id = a.session_id AND u.client_id = ? AND u.role = 'user'
+ JOIN sessions s ON s.id = a.session_id
+ WHERE a.session_id = ? AND a.role = 'assistant' AND a.rewind_at IS NULL
+ AND u.rewind_at IS NULL AND (s.cleared_at IS NULL OR u.created_at > s.cleared_at)
+ AND (a.created_at, a.rowid) > (u.created_at, u.rowid)
+ AND NOT EXISTS (SELECT 1 FROM messages m WHERE m.session_id = a.session_id
+ AND ${realUser} AND m.rewind_at IS NULL
+ AND (m.created_at, m.rowid) > (u.created_at, u.rowid)
+ AND (m.created_at, m.rowid) <= (a.created_at, a.rowid))
+ ORDER BY a.created_at DESC, a.rowid DESC LIMIT 1`,
+ [userClientId, sessionId],
+ );
+ if (!row) return null;
+ let meta: Record<string, unknown> = {};
+ try {
+ meta = JSON.parse(row.agentMeta ?? '{}') ?? {};
+ } catch {
+ /* legacy metadata */
+ }
+ const prior = await readPriorUserRoundCost(sessionId, row.clientId, db);
+ const raw =
+ normalizeRegionalMoney(meta.turnCost) ??
+ (typeof meta.turnCostUsd === 'number' &&
+ Number.isFinite(meta.turnCostUsd) &&
+ meta.turnCostUsd > 0
+ ? legacyUsdMoney(meta.turnCostUsd)
+ : null);
+ const current = raw && meta.turnCostIsEstimate === true ? asValueEstimateMoney(raw) : raw;
+ const money = addCompatibleRegionalMoney(
+ [...(prior.money ? [prior.money] : []), ...(current ? [current] : [])],
+ current?.currency,
+ );
+ if (!money) return null;
+ const isEstimate =
+ (prior.money?.currency === money.currency && prior.hasEstimatedValue) ||
+ (current?.currency === money.currency && current.kind === 'value-estimate');
+ const patch = {
+ userTurnCost: money,
+ userTurnCostIsEstimate: isEstimate,
+ // JSON merge patch removes a stale USD compatibility projection for CNY.
+ userTurnCostUsd: money.currency === 'USD' ? money.amount : null,
+ };
+ await db.exec(
+ `UPDATE messages SET agent_meta = json_patch(
+ CASE WHEN json_valid(agent_meta) THEN agent_meta ELSE '{}' END, ?)
+ WHERE session_id = ? AND client_id = ? AND rewind_at IS NULL`,
+ [JSON.stringify(patch), sessionId, row.clientId],
+ );
+ return {
+ sessionId,
+ clientId: row.clientId,
+ userTurnMoney: money,
+ userTurnCostIsEstimate: isEstimate,
+ ...(money.currency === 'USD' ? { userTurnCostUsd: money.amount } : {}),
+ };
+}
diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.ts
index 1dbc873df5..148d886e3e 100644
--- a/apps/desktop/src/main/usage/modelPricing.ts
+++ b/apps/desktop/src/main/usage/modelPricing.ts
@@ -26,7 +26,7 @@ import {
noteActiveAccount,
rememberAccountCurrency,
} from './accountCurrencyStore.js';
-import { currentLedgerCurrency, setActiveLedgerCurrency } from './ledgerCurrency.js';
+import { currentLedgerCurrency, isLedgerCurrencyKnown, setActiveLedgerCurrency } from './ledgerCurrency.js';
import { createLogger } from '../logger.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { resolveOwnerScopedSecretStorageKey } from '../secrets/providerSecretStore.js';
@@ -56,6 +56,7 @@ interface DiskCachePayload {
fetchedAt: number;
pricing: ModelPricingCatalog;
accountCurrency: MoneyCurrency | null;
+ currencyConflict?: boolean;
}
let cache: ModelPricingCatalog | null = null;
@@ -64,6 +65,7 @@ let cacheAt = 0;
let modelSyncInflight: Promise<unknown> | null = null;
let gatewayAccountCurrency: MoneyCurrency | null = null;
let gatewayAccountCurrencyScope: string | null = null;
+let gatewayCurrencyConflictScope: string | null = null;
/** 上一次观察到的**生效**账本币种(含回退结果),只用于把切换打进日志。 */
let activeLedgerCurrencySnapshot: MoneyCurrency | null = null;
const hydratedScopes = new Set<string>();
@@ -258,6 +260,7 @@ async function writeDiskCache(
pricing: ModelPricingCatalog,
accountCurrency: MoneyCurrency | null,
fetchedAt: number,
+ currencyConflict: boolean,
): Promise<void> {
try {
const file = diskCachePath();
@@ -268,6 +271,7 @@ async function writeDiskCache(
fetchedAt,
pricing,
accountCurrency,
+ currencyConflict,
};
await fs.writeFile(file, JSON.stringify(payload), 'utf8');
hydratedScopes.add(scope);
@@ -312,6 +316,9 @@ async function hydrateFromDisk(scope: string): Promise<ModelPricingCatalog | nul
// 用缓存报价算出的金额当异币种丢弃 —— 等于这一段时间完全不计费。
gatewayAccountCurrency = raw.accountCurrency;
gatewayAccountCurrencyScope = scope;
+ gatewayCurrencyConflictScope = raw.currencyConflict === true ||
+ new Set(Object.values(pricing.xd ?? {}).filter((quote) => !quote.currencyInferred)
+ .map((quote) => quote.currency)).size > 1 ? scope : null;
setActiveLedgerCurrency(raw.accountCurrency);
activeLedgerCurrencySnapshot = currentLedgerCurrency();
rememberAccountCurrency(getCurrentDbClientUserId(), raw.accountCurrency);
@@ -364,6 +371,8 @@ export function replaceGatewayModelPricing(
noteActiveAccount(authenticatedUserId ?? getCurrentDbClientUserId());
gatewayAccountCurrency = resolveGatewayAccountCurrency(models);
gatewayAccountCurrencyScope = scope;
+ gatewayCurrencyConflictScope = new Set(models.map((model) => model.currency)
+ .filter((currency) => currency === 'USD' || currency === 'CNY')).size > 1 ? scope : null;
// 账本写入层据此判断"这一笔是不是本账号的结算币种"。目录为空(登出 / clear)或混合
// 币种时返回 null,账本回退到「上次已知 → USD」,绝不按区域猜。
//
@@ -389,7 +398,7 @@ export function replaceGatewayModelPricing(
cacheScope = scope;
cacheAt = Date.now();
hydratedScopes.add(scope);
- void writeDiskCache(scope, pricing, gatewayAccountCurrency, cacheAt);
+ void writeDiskCache(scope, pricing, gatewayAccountCurrency, cacheAt, gatewayCurrencyConflictScope === scope);
broadcastPricing(pricing);
return pricing;
}
@@ -460,6 +469,20 @@ export async function getGatewayAccountCurrency(
return cacheScope === scope ? gatewayLedgerCurrency(cache) : null;
}
+/** Header amounts have no currency: reuse only this account's confirmed ledger currency. */
+export async function getGatewayMediaBillingCurrency(): Promise<MoneyCurrency | null> {
+ const userId = getCurrentDbClientUserId();
+ if (!userId) return null;
+ const scope = currentScope(userId);
+ noteActiveAccount(userId);
+ const declared = await getGatewayAccountCurrency(userId);
+ if (currentScope() !== scope || gatewayCurrencyConflictScope === scope) return null;
+ if (declared) return declared;
+ await hydrateAccountCurrency(userId);
+ if (currentScope() !== scope || gatewayCurrencyConflictScope === scope) return null;
+ return isLedgerCurrencyKnown() ? currentLedgerCurrency() : null;
+}
+
/** 计费热路径只等待 `/models` 写入 XD 报价,不读取 Catalog。 */
export async function getGatewayModelPricingForModel(): Promise<ModelPricingCatalog | null> {
await waitForModelPricingSync();
@@ -497,6 +520,7 @@ export function __resetModelPricingCacheForTesting(): void {
modelSyncInflight = null;
gatewayAccountCurrency = null;
gatewayAccountCurrencyScope = null;
+ gatewayCurrencyConflictScope = null;
activeLedgerCurrencySnapshot = null;
hydratedScopes.clear();
hydrateInflightByScope.clear();
diff --git a/apps/desktop/src/main/usage/usageDeviceRows.ts b/apps/desktop/src/main/usage/usageDeviceRows.ts
index 76be6f8544..773ed191e8 100644
--- a/apps/desktop/src/main/usage/usageDeviceRows.ts
+++ b/apps/desktop/src/main/usage/usageDeviceRows.ts
@@ -122,7 +122,7 @@ function finiteNonNegative(value: unknown): number {
}
function isAgentKind(value: unknown): value is DailyModelUsageRow['agentKind'] {
- return value === 'claude-code' || value === 'codex' || value === 'pi';
+ return value === 'claude-code' || value === 'codex' || value === 'pi' || value === 'media';
}
/** 控制端和缓存共用的逐行校验:远端 / 磁盘数据一律当不可信输入。 */
diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.ts
index 6d158ceaea..00d09731bc 100644
--- a/apps/desktop/src/main/usage/usageHistory.ts
+++ b/apps/desktop/src/main/usage/usageHistory.ts
@@ -90,8 +90,12 @@ export interface UsageHistoryDay {
tokens: number;
}
+function usageAgentKind(value: string): UsageHistoryModel['agentKind'] {
+ return value === 'codex' || value === 'pi' || value === 'media' ? value : 'claude-code';
+}
+
export interface UsageHistoryModel {
- agentKind: 'claude-code' | 'codex' | 'pi';
+ agentKind: 'claude-code' | 'codex' | 'pi' | 'media';
model: string;
/** SDK 实报美元 (Claude); Codex 恒 0。 */
money: RegionalMoney;
@@ -106,7 +110,7 @@ export interface UsageHistoryModel {
/** 每日 × 模型的一行明细 — 右栏堆叠柱状图的分段数据。 */
export interface UsageHistoryModelDay {
day: string;
- agentKind: 'claude-code' | 'codex' | 'pi';
+ agentKind: 'claude-code' | 'codex' | 'pi' | 'media';
model: string;
/** 可比金额: Claude 实报 $; Codex 为价格表估算 (无价格 → 0, 只出现在图例 token 行)。 */
money: RegionalMoney;
@@ -523,12 +527,13 @@ export function piSubscriptionUsageModelKey(model: string): string {
* 各级都 miss → undefined(该行只显示 token,不臆造金额)。
*/
export function getSubscriptionValuePriceFor(
- agentKind: 'claude-code' | 'codex' | 'pi',
+ agentKind: 'claude-code' | 'codex' | 'pi' | 'media',
model: string,
pricing: ModelPricingMap | null,
at?: string | Date,
overrides?: ModelPriceOverridesSnapshot,
): ModelPriceQuote | undefined {
+ if (agentKind === 'media') return undefined;
if (agentKind === 'codex') {
return (
getSubscriptionDirectValuePrice(model, 'codex', pricing, at, overrides) ??
@@ -808,7 +813,7 @@ export async function readUsageHistoryWith(
if (row.day === todayKey) todayTokens += rowTokens;
}
for (const row of modelRows) {
- const agentKind = row.agentKind === 'codex' ? 'codex' : row.agentKind === 'pi' ? 'pi' : 'claude-code';
+ const agentKind = usageAgentKind(row.agentKind);
// claude 订阅行同样带 #billing= 后缀, 展示名统一剥后缀; key 保留原始 model
// (api / subscription 两个计费维度分行聚合)。
const model = displayModelName(row.model);
@@ -868,11 +873,7 @@ export async function readUsageHistoryWith(
// 每日 × 模型明细 (30 天窗口) — 堆叠柱状图分段。金额口径与 models 一致:
// Claude 实报 $, Codex 行按价格表折算 (无价格 → 0, 该模型只出现在图例 token 行)。
const modelDaily: UsageHistoryModelDay[] = modelRows.map((row) => {
- const agentKind = row.agentKind === 'codex'
- ? ('codex' as const)
- : row.agentKind === 'pi'
- ? ('pi' as const)
- : ('claude-code' as const);
+ const agentKind = usageAgentKind(row.agentKind);
const model = displayModelName(row.model);
const apiMoney = row.money.kind === 'actual-cost' ? row.money : zeroActual();
const subscriptionEstimateMoney = isSubscriptionUsageModel(row.model)
diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.ts
index d36252bfab..700d4680c4 100644
--- a/apps/desktop/src/main/usageBroadcaster.ts
+++ b/apps/desktop/src/main/usageBroadcaster.ts
@@ -45,6 +45,7 @@ import {
import { createLogger } from './logger';
import { tapWindowBroadcast } from './device-link/broadcast-tap.js';
+import { isDataOwnerBroadcastScopeCurrent, type DataOwnerBroadcastScope } from './device-link/broadcast-tap.js';
import type { RegionalMoney } from '../shared/regionalMoney.js';
const log = createLogger('usageBroadcaster');
@@ -161,9 +162,11 @@ export async function readTodaySpend(): Promise<TodaySpendPayload> {
* (cost=0, 不走 recordTurnSpend), renderer 的 useUsageHistory 以 spend/tokens push
* 为仪表盘刷新信号, 用它通知"按模型数据有更新"(对齐 rebroadcastCodexTodayUsage)。
*/
-export async function rebroadcastTodaySpend(): Promise<void> {
+export async function rebroadcastTodaySpend(ownerScope?: DataOwnerBroadcastScope): Promise<void> {
try {
- broadcastTodaySpend(await readTodaySpend());
+ const payload = await readTodaySpend();
+ if (ownerScope && !isDataOwnerBroadcastScopeCurrent(ownerScope)) return;
+ broadcastTodaySpend(payload);
} catch (err) {
log.warn(
'rebroadcastTodaySpend failed:',
diff --git a/apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts b/apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts
index 18af16f834..05c0b9278e 100644
--- a/apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts
+++ b/apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts
@@ -30,6 +30,7 @@ export function usageHistoryAgentColor(agentKind: UsageAgentKind): string {
'claude-code': 'var(--engine-badge-cc)',
codex: 'var(--engine-badge-codex)',
pi: MODEL_COLORS[0],
+ media: 'var(--text-secondary)',
};
return colors[agentKind];
}
diff --git a/apps/desktop/src/renderer/hooks/useUsageHistory.ts b/apps/desktop/src/renderer/hooks/useUsageHistory.ts
index 0419d34d02..9e0a4b0973 100644
--- a/apps/desktop/src/renderer/hooks/useUsageHistory.ts
+++ b/apps/desktop/src/renderer/hooks/useUsageHistory.ts
@@ -34,7 +34,7 @@ import type { Session } from '@/lib/ccAgent.types';
import { onPatch as onSessionPatch } from '@/lib/sessionsBus';
export interface UsageHistoryModel {
- agentKind: 'claude-code' | 'codex' | 'pi';
+ agentKind: 'claude-code' | 'codex' | 'pi' | 'media';
model: string;
money: RegionalMoney;
estimatedMoney: RegionalMoney | null;
@@ -47,7 +47,7 @@ export interface UsageHistoryModel {
/** 每日 × 模型明细 — 右栏堆叠柱状图分段。 */
export interface UsageHistoryModelDay {
day: string;
- agentKind: 'claude-code' | 'codex' | 'pi';
+ agentKind: 'claude-code' | 'codex' | 'pi' | 'media';
model: string;
money: RegionalMoney;
apiMoney: RegionalMoney;
@@ -202,7 +202,7 @@ function finiteNumber(value: unknown, fallback = 0): number {
}
function isAgentKind(value: unknown): value is UsageHistoryModel['agentKind'] {
- return value === 'claude-code' || value === 'codex' || value === 'pi';
+ return value === 'claude-code' || value === 'codex' || value === 'pi' || value === 'media';
}
function parseDevices(value: unknown): UsageHistoryDevice[] | undefined {
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index b907340176..eeea50f94b 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -22,6 +22,29 @@ Gateway 边界对整块报价校验,非法或无有效币种即整体省略,
模型快照投影,成功刷新缺字段会移除旧展示;没有新权限、数据库迁移或独立价格缓存。
两端可独立升级,完整展示需两端支持。字段只用于报价展示,不参与账单或调用授权。
+## Gateway 媒体请求计费
+
+此契约仅适用于 Cindy AI provider(内部 `providerId='xd'`),按实际供应商身份判断,
+与模型名称无关;自定义及第三方 provider 不走此计费头读取和落账链路。
+个人版与企业账号的返回结构一致,共用同一解析器,不按账号类型分支。
+
+成功创建媒体请求的 `X-Nova-AIGateway-Billing` 是 Base64URL 编码的 JSON,`cost` 为有限的
+非负数,`model` 可选;其它供应商字段忽略。费用直接采用此头,不从 token 或展示价目推算。
+头本身没有币种,客户端在提交前捕获同账号 Gateway 的结算币种与数据库归属;币种未知、
+头缺失或非法时不猜测金额。旧网关没有头时继续提供媒体结果,不补算历史费用。
+仅原始创建响应记账,视频轮询、下载、已保存结果恢复不重复记账;响应正文或下载失败不撤回
+已经收到的有效计费。每日总额、模型费用和 Host 可关联的任务费用原子更新。
+
+目录暂缺币种时复用同账号已确认的结算币种;从未确认或目录币种冲突时仍不猜测。
+任务内媒体费在提交前绑定真实用户消息,`agent_meta.mediaCosts` 按币种保存实际费用,
+与日账及任务总额同一事务落库。响应下方沿用 `userTurnMoney` 累计,晚到费用刷新原轮,
+不修改聊天分段 `turnCost` 或订阅估值。定时运行与累计费用同时读取用户消息媒体账本,
+保留纯工具运行的费用,避免与助手消息费用重复累计。
+
+用量模型行的 `agentKind` 追加 `media`,token 数为 0,不虚构聊天引擎或 token 用量。
+同账号设备同步沿用 `usage-device-rows-v1`;新版保留此行,旧版可能忽略新类别的模型明细,
+每日费用仍通过既有日账同步,无新增 channel、权限或数据库 migration。
+
## 手机直连群的设置管理
现有 `bot-group-chat` 数据可选追加 `supportsSettingsManagement`。仅服务器群的新版 Host