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: reliably report automation run costs (#271)

DavidShenXD3198fe07b50b
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index ddceba9456..f29df9e9bb 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -302,11 +302,12 @@ describe('maker:event hot path ordering', () => {
);
const costRecordIndex = codexDoneSource.indexOf('void recordTurnSpend(cost);');
const modelCostRecordIndex = codexDoneSource.indexOf('costUsdDelta: cost,');
- const messageCostGuardIndex = codexDoneSource.indexOf('if (turnAssistantPersistId)');
+ const schedulerCostRecordIndex = codexDoneSource.indexOf('await recordSchedulerTurnCost({');
expect(costRecordIndex).toBeGreaterThanOrEqual(0);
expect(modelCostRecordIndex).toBeGreaterThanOrEqual(0);
expect(modelCostRecordIndex).toBeGreaterThan(codexDoneSource.indexOf('const pricing = isSubscriptionValue && !isCodexXaiProviderRoute'));
- expect(messageCostGuardIndex).toBeGreaterThan(costRecordIndex);
+ expect(schedulerCostRecordIndex).toBeGreaterThan(costRecordIndex);
+ expect(codexDoneSource).toContain('clientId: turnAssistantPersistId');
expect(codexDoneSource).toContain('isEstimate: isSubscriptionValue');
expect(codexDoneSource).toContain('if (!isRemoteCodexSession &&');
expect(codexDoneSource).toContain("!model.startsWith(XAI_MODEL_PREFIX) &&");
diff --git a/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts b/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts
index 5454d401c3..f5e631973d 100644
--- a/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts
@@ -28,6 +28,7 @@ vi.mock('../localDb/ipc/messages.js', () => ({
}));
vi.mock('../scheduler-host/runCostLedger.js', () => ({
applyScheduleRunCostMetaChange: vi.fn(async () => undefined),
+ recordScheduleRunCostDirect: vi.fn(async () => null),
}));
vi.mock('../messagePersistBroadcaster.js', () => ({
enqueueDurableWrite: vi.fn((_label: string, fn: () => unknown) => Promise.resolve(fn())),
@@ -35,6 +36,7 @@ vi.mock('../messagePersistBroadcaster.js', () => ({
import {
recordTurnCostOnMessage,
+ recordSchedulerTurnCost,
codexUsageToTokens,
type TurnCostDeps,
type MessageTurnCostPayload,
@@ -97,7 +99,7 @@ beforeEach(() => {
describe('recordTurnCostOnMessage', () => {
it('patch 成功 → 写入原始分段与本用户轮累计,并广播同值', async () => {
const { deps, broadcasts, patchCalls } = makeDeps(true);
- await recordTurnCostOnMessage(ARGS, deps);
+ await expect(recordTurnCostOnMessage(ARGS, deps)).resolves.toBe(true);
expect(patchCalls).toEqual([
{
sessionId: 's1',
@@ -205,7 +207,7 @@ describe('recordTurnCostOnMessage', () => {
it('patch 返回 false(行不存在,典型 rewind 已删)→ 不广播', async () => {
const { deps, broadcasts, patchCalls } = makeDeps(false);
- await recordTurnCostOnMessage(ARGS, deps);
+ await expect(recordTurnCostOnMessage(ARGS, deps)).resolves.toBe(false);
expect(patchCalls).toHaveLength(1);
expect(broadcasts).toHaveLength(0);
});
@@ -228,18 +230,120 @@ describe('recordTurnCostOnMessage', () => {
it('patch 抛错 → 吞掉不传播、不广播', async () => {
const { deps, broadcasts } = makeDeps(new Error('db locked'));
- await expect(recordTurnCostOnMessage(ARGS, deps)).resolves.toBeUndefined();
+ await expect(recordTurnCostOnMessage(ARGS, deps)).resolves.toBe(false);
expect(broadcasts).toHaveLength(0);
});
it('读取累计失败 → 不写入错误的单段展示值,也不广播', async () => {
const { deps, broadcasts, patchCalls } = makeDeps(true, new Error('db locked'));
- await expect(recordTurnCostOnMessage(ARGS, deps)).resolves.toBeUndefined();
+ await expect(recordTurnCostOnMessage(ARGS, deps)).resolves.toBe(false);
expect(patchCalls).toHaveLength(0);
expect(broadcasts).toHaveLength(0);
});
});
+describe('recordSchedulerTurnCost', () => {
+ const schedulerOrigin = {
+ kind: 'scheduler',
+ scheduleId: 'schedule-1',
+ runId: 'run-1',
+ } as const;
+
+ it('有 assistant message 且写入成功时保持消息账本为唯一来源', async () => {
+ const recordOnMessage = vi.fn(async () => true);
+ const recordDirect = vi.fn(async () => 'schedule-1');
+
+ await expect(recordSchedulerTurnCost(
+ {
+ ...ARGS,
+ turnOrigin: schedulerOrigin,
+ },
+ { recordOnMessage, recordDirect },
+ )).resolves.toBeNull();
+
+ expect(recordOnMessage).toHaveBeenCalledOnce();
+ expect(recordDirect).not.toHaveBeenCalled();
+ });
+
+ it('纯 tool turn 没有 assistant message 时按 runId 直接归因并刷新自动化', async () => {
+ const recordOnMessage = vi.fn(async () => true);
+ const recordDirect = vi.fn(async () => 'schedule-1');
+
+ await expect(recordSchedulerTurnCost(
+ {
+ sessionId: 's1',
+ costUsd: 0.42,
+ isEstimate: false,
+ turnOrigin: schedulerOrigin,
+ },
+ { recordOnMessage, recordDirect },
+ )).resolves.toBe('schedule-1');
+
+ expect(recordOnMessage).not.toHaveBeenCalled();
+ expect(recordDirect).toHaveBeenCalledWith({
+ runId: 'run-1',
+ costUsd: 0.42,
+ isEstimate: false,
+ });
+ });
+
+ it('assistant message 已被删除时回退到 runId 归因', async () => {
+ const recordOnMessage = vi.fn(async () => false);
+ const recordDirect = vi.fn(async () => 'schedule-1');
+
+ await expect(recordSchedulerTurnCost(
+ {
+ ...ARGS,
+ turnOrigin: schedulerOrigin,
+ },
+ { recordOnMessage, recordDirect },
+ )).resolves.toBe('schedule-1');
+
+ expect(recordDirect).toHaveBeenCalledOnce();
+ });
+
+ it('broadcast failure after message persistence does not trigger scheduler fallback', async () => {
+ const { deps } = makeDeps(true);
+ deps.broadcast = () => {
+ throw new Error('window closed');
+ };
+ const recordOnMessage: typeof recordTurnCostOnMessage = (args) =>
+ recordTurnCostOnMessage(args, deps);
+ const recordDirect = vi.fn(async () => 'schedule-1');
+
+ await expect(recordSchedulerTurnCost(
+ {
+ ...ARGS,
+ turnOrigin: schedulerOrigin,
+ },
+ { recordOnMessage, recordDirect },
+ )).resolves.toBeNull();
+
+ expect(recordDirect).not.toHaveBeenCalled();
+ });
+
+ it('可靠计价结果为零时仍用 runId 标记为已确认费用', async () => {
+ const recordOnMessage = vi.fn(async () => false);
+ const recordDirect = vi.fn(async () => 'schedule-1');
+
+ await expect(recordSchedulerTurnCost(
+ {
+ sessionId: 's1',
+ costUsd: 0,
+ isEstimate: false,
+ turnOrigin: schedulerOrigin,
+ },
+ { recordOnMessage, recordDirect },
+ )).resolves.toBe('schedule-1');
+
+ expect(recordDirect).toHaveBeenCalledWith({
+ runId: 'run-1',
+ costUsd: 0,
+ isEstimate: false,
+ });
+ });
+});
+
describe('codexUsageToTokens', () => {
it('completion 已含 reasoning,不重复相加;cached 计入 cacheRead', () => {
expect(
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index ba4b523669..d56289c114 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -764,8 +764,13 @@ export const scheduleRuns = sqliteTable(
costUsd: real('cost_usd').notNull().default(0),
/** 单次 run 的订阅 token 估算价值,不计入真实账单。 */
estimatedValueUsd: real('estimated_value_usd').notNull().default(0),
- /** legacy 表示迁移前数据缺少 runId,不能精确拆分到单次执行。 */
- costAttribution: text('cost_attribution', { enum: ['exact', 'legacy'] })
+ /**
+ * zero 表示已确认零费用;unavailable 表示 agent run 尚无可靠计价;legacy
+ * 表示迁移前数据缺少 runId,不能精确拆分。SQLite 无 CHECK,无需 migration。
+ */
+ costAttribution: text('cost_attribution', {
+ enum: ['exact', 'direct', 'mixed', 'zero', 'unavailable', 'legacy'],
+ })
.notNull()
.default('legacy'),
/**
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 0f8539f86c..f07655367c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -216,7 +216,11 @@ import {
recordSessionTurnSpend,
recordSessionTurnTokens,
} from '../sessionSpendBroadcaster.js';
-import { codexUsageToTokens, recordTurnCostOnMessage } from '../turnCostBroadcaster.js';
+import {
+ codexUsageToTokens,
+ recordSchedulerTurnCost,
+ recordTurnCostOnMessage,
+} from '../turnCostBroadcaster.js';
import { recordModelMismatchOnMessage } from '../modelMismatchBroadcaster.js';
import { detectClaudeModelMismatch } from '../../shared/modelMismatch.js';
import { triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';
@@ -257,6 +261,7 @@ import type {
import { runAcceptedCallback } from './acceptedCallbackRunner.js';
import { createElectronIpcHandlerRegistry } from './electronIpcRegistry.js';
import { refreshCodexMcpEnvironment } from './codexMcpRefresh.js';
+import { broadcastSchedulerChanged } from './schedule.js';
import { validateExtraDirs } from './extraDirsValidator.js';
import { prepareHandoffWorktree, shouldRecycleHandoffWorktreeOnFailure } from './handoffWorktree.js';
import { registerProjectPluginPolicyHandlers } from './projectPluginPolicyHandlers.js';
@@ -2836,16 +2841,17 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
void recordTurnSpend(cost);
void recordSessionTurnSpend(session.id, cost);
}
- if (turnAssistantPersistId) {
- await recordTurnCostOnMessage({
- sessionId: session.id,
- clientId: turnAssistantPersistId,
- costUsd: cost,
- isEstimate: isSubscriptionValue,
- turnUsageDetails,
- turnOrigin: event.turnOrigin,
- });
- }
+ }
+ if (cost != null) {
+ const changedScheduleId = await recordSchedulerTurnCost({
+ sessionId: session.id,
+ clientId: turnAssistantPersistId,
+ costUsd: cost,
+ isEstimate: isSubscriptionValue,
+ turnUsageDetails,
+ turnOrigin: event.turnOrigin,
+ });
+ if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);
}
} catch {
// token row 已在价格请求前落库;价格失败只影响 API cost / message cost。
diff --git a/apps/desktop/src/main/maker-ipc/schedule.ts b/apps/desktop/src/main/maker-ipc/schedule.ts
index 757db0339d..46000e2d84 100644
--- a/apps/desktop/src/main/maker-ipc/schedule.ts
+++ b/apps/desktop/src/main/maker-ipc/schedule.ts
@@ -101,6 +101,12 @@ function broadcastSchedulerEvent(event: SchedulerEvent): void {
}
}
+/** 非 Scheduler 引擎写入 run 衍生数据后,通知各端重新读取该任务。 */
+export function broadcastSchedulerChanged(scheduleId: string): void {
+ if (!scheduleId) return;
+ broadcastSchedulerEvent({ type: 'changed', scheduleId });
+}
+
/**
* 把 scheduler 抛的业务 Error 翻成带 code 的 IPC error。
* Scheduler 当前抛的 message 形态固定为 'schedule {id} not found' 等明文(见
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts
index fb4c82db8b..6a8821e215 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
-import { computeScheduleRunCostDeltas } from '../runCostLedger.js';
+import type { DbClient } from '../../localDb/client/DbClient';
+import { clearCurrentDbClient, setCurrentDbClient } from '../../localDb/client/current';
+import { computeScheduleRunCostDeltas, recordScheduleRunCostDirect } from '../runCostLedger.js';
function meta(runId: string, costUsd: number, isEstimate = false): Record<string, unknown> {
return {
@@ -39,3 +41,54 @@ describe('computeScheduleRunCostDeltas', () => {
]);
});
});
+
+describe('recordScheduleRunCostDirect', () => {
+ it('忽略低于消息账本阈值的正费用', async () => {
+ await expect(recordScheduleRunCostDirect({
+ runId: 'run-near-zero',
+ costUsd: 1e-12,
+ isEstimate: false,
+ })).resolves.toBeNull();
+ });
+
+ it('更新竞态下 run 已消失时返回 null', async () => {
+ const selectChain = {
+ from() {
+ return this;
+ },
+ where() {
+ return this;
+ },
+ async limit() {
+ return [{ scheduleId: 'schedule-1' }];
+ },
+ };
+ const updateChain = {
+ set() {
+ return this;
+ },
+ where() {
+ return this;
+ },
+ async run() {
+ return { changes: 0 };
+ },
+ };
+ const dbClient = {
+ drizzle: {
+ select: () => selectChain,
+ update: () => updateChain,
+ },
+ } as unknown as DbClient;
+ setCurrentDbClient(dbClient, 'test-user');
+ try {
+ await expect(recordScheduleRunCostDirect({
+ runId: 'run-raced-delete',
+ costUsd: 0.42,
+ isEstimate: false,
+ })).resolves.toBeNull();
+ } finally {
+ clearCurrentDbClient(dbClient);
+ }
+ });
+});
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 07b9f876be..90544bbd40 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
@@ -12,6 +12,9 @@ import { drizzle } from 'drizzle-orm/better-sqlite3';
import { describe, expect, it } from 'vitest';
import * as schema from '../../localDb/schema';
import { createDbClient } from '../../localDb/client/DbClient';
+import type { DbClient } from '../../localDb/client/DbClient';
+import { clearCurrentDbClient, setCurrentDbClient } from '../../localDb/client/current';
+import { recordScheduleRunCostDirect } from '../runCostLedger';
import { DrizzleScheduleStorage, type SchedulerDrizzleDb } from '../storage';
function baseSchedule(overrides: Partial<Schedule> = {}): Schedule {
@@ -747,6 +750,271 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
}
});
+ it('includes direct run ledger costs when no assistant message can carry origin', async () => {
+ const harness = createStorageHarness();
+ const schedule = baseSchedule({ id: 'sch-direct', targetSessionId: 'sess-direct' });
+ try {
+ harness.db.run(sql`
+ INSERT INTO sessions (id, title, source, workspace_kind, created_at, updated_at, total_cost_usd)
+ VALUES ('sess-direct', 'Direct cost session', 'desktop', 'dialogue', 1, 1, 0.42)
+ `);
+ await harness.storage.insert(schedule);
+ await harness.storage.insertRun({
+ id: 'run-direct',
+ scheduleId: schedule.id,
+ sessionId: 'sess-direct',
+ firedAt: 10,
+ finishedAt: 20,
+ status: 'success',
+ costUsd: 0.42,
+ costAttribution: 'exact',
+ });
+
+ await expect(harness.storage.listCostSummaries()).resolves.toEqual([
+ {
+ scheduleId: schedule.id,
+ totalCostUsd: 0.42,
+ totalEstimatedValueUsd: 0,
+ sessionCount: 1,
+ sessions: [
+ {
+ sessionId: 'sess-direct',
+ totalCostUsd: 0.42,
+ totalEstimatedValueUsd: 0,
+ },
+ ],
+ },
+ ]);
+ } finally {
+ harness.close();
+ }
+ });
+
+ it('accumulates multiple direct run ledger segments', async () => {
+ const harness = createStorageHarness();
+ const schedule = baseSchedule({ id: 'sch-direct-segments' });
+ const dbClient = { drizzle: harness.db } as unknown as DbClient;
+ try {
+ await harness.storage.insert(schedule);
+ await harness.storage.insertRun({
+ id: 'run-direct-segments',
+ scheduleId: schedule.id,
+ firedAt: 10,
+ finishedAt: 20,
+ status: 'success',
+ costAttribution: 'unavailable',
+ });
+ setCurrentDbClient(dbClient, 'test-user');
+
+ await recordScheduleRunCostDirect({
+ runId: 'run-direct-segments',
+ costUsd: 0.42,
+ isEstimate: false,
+ });
+ await recordScheduleRunCostDirect({
+ runId: 'run-direct-segments',
+ costUsd: 0.18,
+ isEstimate: false,
+ });
+ await recordScheduleRunCostDirect({
+ runId: 'run-direct-segments',
+ costUsd: 0,
+ isEstimate: false,
+ });
+
+ await expect(harness.storage.listRuns(schedule.id)).resolves.toEqual([
+ expect.objectContaining({
+ id: 'run-direct-segments',
+ costUsd: 0.6,
+ estimatedValueUsd: 0,
+ costAttribution: 'exact',
+ }),
+ ]);
+ } finally {
+ clearCurrentDbClient(dbClient);
+ harness.close();
+ }
+ });
+
+ it('keeps direct ledger remainder when a run also has message costs', async () => {
+ const harness = createStorageHarness();
+ const schedule = baseSchedule({ id: 'sch-mixed-ledger', targetSessionId: 'sess-mixed-ledger' });
+ try {
+ harness.db.run(sql`
+ INSERT INTO sessions (id, title, source, workspace_kind, created_at, updated_at, total_cost_usd)
+ VALUES ('sess-mixed-ledger', 'Mixed ledger session', 'desktop', 'dialogue', 1, 1, 0)
+ `);
+ await harness.storage.insert(schedule);
+ await harness.storage.insertRun({
+ id: 'run-mixed-ledger',
+ scheduleId: schedule.id,
+ sessionId: 'sess-mixed-ledger',
+ firedAt: 10,
+ finishedAt: 20,
+ status: 'success',
+ costUsd: 0.6,
+ costAttribution: 'mixed',
+ });
+ harness.db.run(sql`
+ INSERT INTO messages (id, client_id, session_id, role, content, agent_meta, created_at)
+ VALUES
+ ('mixed-user', 'mixed-user', 'sess-mixed-ledger', 'user', '{}',
+ '{"origin":{"kind":"scheduler","scheduleId":"sch-mixed-ledger","runId":"run-mixed-ledger"}}', 10),
+ ('mixed-assistant', 'mixed-assistant', 'sess-mixed-ledger', 'assistant', '{}',
+ '{"origin":{"kind":"scheduler","scheduleId":"sch-mixed-ledger","runId":"run-mixed-ledger"},"turnCostUsd":0.42}', 11)
+ `);
+
+ await expect(harness.storage.listCostSummaries()).resolves.toEqual([
+ {
+ scheduleId: schedule.id,
+ totalCostUsd: 0.6,
+ totalEstimatedValueUsd: 0,
+ sessionCount: 1,
+ sessions: [
+ {
+ sessionId: 'sess-mixed-ledger',
+ totalCostUsd: 0.6,
+ totalEstimatedValueUsd: 0,
+ },
+ ],
+ },
+ ]);
+ } finally {
+ harness.close();
+ }
+ });
+
+ it('merges direct-only snapshot with a later message ledger update', async () => {
+ const harness = createStorageHarness();
+ const schedule = baseSchedule({ id: 'sch-direct-only-snapshot', targetSessionId: 'sess-direct-only' });
+ const dbClient = { drizzle: harness.db } as unknown as DbClient;
+ try {
+ harness.db.run(sql`
+ INSERT INTO sessions (id, title, source, workspace_kind, created_at, updated_at, total_cost_usd)
+ VALUES ('sess-direct-only', 'Direct-only snapshot session', 'desktop', 'dialogue', 1, 1, 0)
+ `);
+ await harness.storage.insert(schedule);
+ await harness.storage.insertRun({
+ id: 'run-direct-only-snapshot',
+ scheduleId: schedule.id,
+ sessionId: 'sess-direct-only',
+ firedAt: 10,
+ finishedAt: 20,
+ status: 'success',
+ costAttribution: 'unavailable',
+ });
+ setCurrentDbClient(dbClient, 'test-user');
+ await recordScheduleRunCostDirect({
+ runId: 'run-direct-only-snapshot',
+ costUsd: 0.6,
+ isEstimate: false,
+ });
+ harness.db.run(sql`
+ INSERT INTO messages (id, client_id, session_id, role, content, agent_meta, created_at)
+ VALUES
+ ('direct-only-user', 'direct-only-user', 'sess-direct-only', 'user', '{}',
+ '{"origin":{"kind":"scheduler","scheduleId":"sch-direct-only-snapshot","runId":"run-direct-only-snapshot"}}', 10),
+ ('direct-only-assistant', 'direct-only-assistant', 'sess-direct-only', 'assistant', '{}',
+ '{"origin":{"kind":"scheduler","scheduleId":"sch-direct-only-snapshot","runId":"run-direct-only-snapshot"},"turnCostUsd":0.4}', 11)
+ `);
+
+ await expect(harness.storage.listRuns(schedule.id)).resolves.toEqual([
+ expect.objectContaining({
+ id: 'run-direct-only-snapshot',
+ costUsd: 1,
+ estimatedValueUsd: 0,
+ costAttribution: 'exact',
+ }),
+ ]);
+ await expect(harness.storage.listCostSummaries()).resolves.toEqual([
+ {
+ scheduleId: schedule.id,
+ totalCostUsd: 1,
+ totalEstimatedValueUsd: 0,
+ sessionCount: 1,
+ sessions: [
+ {
+ sessionId: 'sess-direct-only',
+ totalCostUsd: 1,
+ totalEstimatedValueUsd: 0,
+ },
+ ],
+ },
+ ]);
+ } finally {
+ clearCurrentDbClient(dbClient);
+ harness.close();
+ }
+ });
+
+ it('marks runs with no reliable pricing as unavailable instead of zero', async () => {
+ const harness = createStorageHarness();
+ const schedule = baseSchedule({ id: 'sch-unavailable', targetSessionId: 'sess-unavailable' });
+ try {
+ harness.db.run(sql`
+ INSERT INTO sessions (id, title, source, workspace_kind, created_at, updated_at, total_cost_usd)
+ VALUES ('sess-unavailable', 'Unavailable cost session', 'desktop', 'dialogue', 1, 1, 0)
+ `);
+ await harness.storage.insert(schedule);
+ await harness.storage.insertRun({
+ id: 'run-unavailable',
+ scheduleId: schedule.id,
+ sessionId: 'sess-unavailable',
+ firedAt: 10,
+ finishedAt: 20,
+ status: 'success',
+ costAttribution: 'unavailable',
+ });
+
+ await expect(harness.storage.listCostSummaries()).resolves.toEqual([
+ {
+ scheduleId: schedule.id,
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ hasUnavailableCost: true,
+ sessionCount: 1,
+ sessions: [
+ {
+ sessionId: 'sess-unavailable',
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ },
+ ],
+ },
+ ]);
+ } finally {
+ harness.close();
+ }
+ });
+
+ it('keeps a confirmed zero-cost run distinct from unavailable pricing', async () => {
+ const harness = createStorageHarness();
+ const schedule = baseSchedule({ id: 'sch-zero', executionMode: 'script' });
+ try {
+ await harness.storage.insert(schedule);
+ await harness.storage.insertRun({
+ id: 'run-zero',
+ scheduleId: schedule.id,
+ firedAt: 10,
+ finishedAt: 20,
+ status: 'success',
+ costAttribution: 'zero',
+ });
+
+ await expect(harness.storage.listCostSummaries()).resolves.toEqual([
+ {
+ scheduleId: schedule.id,
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ sessionCount: 0,
+ sessions: [],
+ },
+ ]);
+ } finally {
+ harness.close();
+ }
+ });
+
it('preserves legacy baseline when a scheduler session later gains turn costs', async () => {
const harness = createStorageHarness();
const schedule = baseSchedule({
diff --git a/apps/desktop/src/main/scheduler-host/runCostLedger.ts b/apps/desktop/src/main/scheduler-host/runCostLedger.ts
index b9545484d3..ea59a289ba 100644
--- a/apps/desktop/src/main/scheduler-host/runCostLedger.ts
+++ b/apps/desktop/src/main/scheduler-host/runCostLedger.ts
@@ -16,6 +16,8 @@ interface RunCostEntry {
estimatedValueUsd: number;
}
+const MIN_RECORDED_COST_USD = 1e-10;
+
export interface ScheduleRunCostDelta {
runId: string;
costUsdDelta: number;
@@ -23,7 +25,9 @@ export interface ScheduleRunCostDelta {
}
function finitePositive(value: unknown): number {
- return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
+ return typeof value === 'number' && Number.isFinite(value) && value >= MIN_RECORDED_COST_USD
+ ? value
+ : 0;
}
function runCostEntry(meta: Record<string, unknown>): RunCostEntry | null {
@@ -60,7 +64,9 @@ export function computeScheduleRunCostDeltas(
apply(runCostEntry(previous), -1);
apply(runCostEntry(next), 1);
return [...changes.values()].filter(
- (change) => Math.abs(change.costUsdDelta) >= 1e-10 || Math.abs(change.estimatedValueUsdDelta) >= 1e-10,
+ (change) =>
+ Math.abs(change.costUsdDelta) >= MIN_RECORDED_COST_USD ||
+ Math.abs(change.estimatedValueUsdDelta) >= MIN_RECORDED_COST_USD,
);
}
@@ -76,10 +82,83 @@ export async function applyScheduleRunCostMetaChange(
await db
.update(scheduleRuns)
.set({
- costUsd: sql<number>`MAX(0, ${scheduleRuns.costUsd} + ${change.costUsdDelta})`,
- estimatedValueUsd: sql<number>`MAX(0, ${scheduleRuns.estimatedValueUsd} + ${change.estimatedValueUsdDelta})`,
- costAttribution: 'exact',
+ // A direct-only snapshot is an independent ledger. Once it exists,
+ // keep the message ledger in agent_meta and let read paths add it;
+ // otherwise a successful message update would make a later read
+ // unable to tell whether the snapshot already contains that segment.
+ costUsd: sql<number>`CASE
+ WHEN ${scheduleRuns.costAttribution} = 'direct'
+ THEN ${scheduleRuns.costUsd}
+ ELSE MAX(0, ${scheduleRuns.costUsd} + ${change.costUsdDelta})
+ END`,
+ estimatedValueUsd: sql<number>`CASE
+ WHEN ${scheduleRuns.costAttribution} = 'direct'
+ THEN ${scheduleRuns.estimatedValueUsd}
+ ELSE MAX(0, ${scheduleRuns.estimatedValueUsd} + ${change.estimatedValueUsdDelta})
+ END`,
+ costAttribution: sql<string>`CASE
+ WHEN ${scheduleRuns.costAttribution} IN ('direct', 'mixed')
+ THEN ${scheduleRuns.costAttribution}
+ ELSE 'exact'
+ END`,
})
.where(eq(scheduleRuns.id, change.runId));
}
}
+
+/**
+ * 没有可挂费用的 assistant message 时,按 scheduler runId 直接写聚合快照。
+ *
+ * 这是 Codex 纯 tool turn 等场景的兜底;正常有消息时仍以 agent_meta 账本为主。
+ * 直接路径将每个无法挂载消息的 turn 分段累加到 run 快照。
+ * 返回 scheduleId 供调用方广播 changed,run 已被删除时返回 null。
+ */
+export async function recordScheduleRunCostDirect(args: {
+ runId: string;
+ costUsd: number;
+ isEstimate: boolean;
+}): Promise<string | null> {
+ const { runId, costUsd, isEstimate } = args;
+ if (!runId || typeof costUsd !== 'number' || !Number.isFinite(costUsd) || costUsd < 0) {
+ return null;
+ }
+ const amount = finitePositive(costUsd);
+ // Match the message ledger's delta threshold; a tiny positive residue must
+ // not create a direct-only run segment or a misleading changed broadcast.
+ if (costUsd > 0 && amount === 0) return null;
+
+ const db = getDbClient().drizzle;
+ const [run] = await db
+ .select({ scheduleId: scheduleRuns.scheduleId })
+ .from(scheduleRuns)
+ .where(eq(scheduleRuns.id, runId))
+ .limit(1);
+ if (!run) return null;
+
+ const result = await db
+ .update(scheduleRuns)
+ .set({
+ costUsd: sql<number>`MAX(0, ${scheduleRuns.costUsd} + ${isEstimate ? 0 : amount})`,
+ estimatedValueUsd: sql<number>`MAX(0, ${scheduleRuns.estimatedValueUsd} + ${isEstimate ? amount : 0})`,
+ // A confirmed zero-cost segment must not downgrade a run that already
+ // contains an exact segment; otherwise later summary reads lose the
+ // accumulated direct cost.
+ costAttribution:
+ isEstimate || amount > 0
+ ? sql<string>`CASE
+ WHEN ${scheduleRuns.costAttribution} = 'mixed' THEN 'mixed'
+ WHEN ${scheduleRuns.costAttribution} = 'exact' THEN 'mixed'
+ ELSE 'direct'
+ END`
+ : sql<string>`CASE
+ WHEN ${scheduleRuns.costAttribution} IN ('exact', 'direct', 'mixed')
+ THEN ${scheduleRuns.costAttribution}
+ ELSE 'zero'
+ END`,
+ })
+ .where(eq(scheduleRuns.id, runId))
+ .run();
+ const changes = (result as unknown as { changes?: number }).changes;
+ if (typeof changes !== 'number' || changes === 0) return null;
+ return run.scheduleId;
+}
diff --git a/apps/desktop/src/main/scheduler-host/storage.ts b/apps/desktop/src/main/scheduler-host/storage.ts
index 23b8344e65..6bee2ae506 100644
--- a/apps/desktop/src/main/scheduler-host/storage.ts
+++ b/apps/desktop/src/main/scheduler-host/storage.ts
@@ -51,6 +51,8 @@ export interface ScheduleCostSummary {
scheduleId: string;
totalCostUsd: number;
totalEstimatedValueUsd: number;
+ /** 至少一轮 agent run 无法得到可靠费用。 */
+ hasUnavailableCost?: boolean;
sessionCount: number;
sessions: ScheduleSessionCostSummary[];
}
@@ -64,6 +66,7 @@ export interface ScheduleSessionCostSummary {
interface ScheduleTurnCostState {
totalCostUsd: number;
totalEstimatedValueUsd: number;
+ hasUnavailableCost: boolean;
sessionIds: Set<string>;
sessionCosts: Map<string, { totalCostUsd: number; totalEstimatedValueUsd: number }>;
}
@@ -179,6 +182,10 @@ function turnCostFromAgentMeta(agentMeta: string | null): {
}
}
+function finitePositiveNumber(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
+}
+
function chunkArray<T>(items: readonly T[], size: number): T[][] {
const chunks: T[][] = [];
for (let i = 0; i < items.length; i += size) {
@@ -388,16 +395,22 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
db: SchedulerDrizzleDb,
runs: ScheduleRun[],
): Promise<ScheduleRun[]> {
- const exactRunIds = new Set(
- runs.filter((run) => run.costAttribution === 'exact').map((run) => run.id),
+ const normalizeAttribution = (run: ScheduleRun): ScheduleRun =>
+ run.costAttribution === 'direct' || run.costAttribution === 'mixed'
+ ? { ...run, costAttribution: 'exact' }
+ : run;
+ const attributableRunIds = new Set(
+ runs.filter((run) => run.costAttribution !== 'legacy').map((run) => run.id),
);
const sessionIds = new Set(
runs
- .filter((run) => exactRunIds.has(run.id))
+ .filter((run) => attributableRunIds.has(run.id))
.map((run) => run.sessionId)
.filter((id): id is string => Boolean(id)),
);
- if (exactRunIds.size === 0 || sessionIds.size === 0) return runs;
+ if (attributableRunIds.size === 0 || sessionIds.size === 0) {
+ return runs.map(normalizeAttribution);
+ }
const rows = (
await Promise.all(
@@ -417,8 +430,9 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
const ledger = new Map<string, { costUsd: number; estimatedValueUsd: number }>();
for (const row of rows) {
const origin = scheduleOriginFromAgentMeta(row.agentMeta);
- if (!origin?.runId || !exactRunIds.has(origin.runId)) continue;
+ if (!origin?.runId || !attributableRunIds.has(origin.runId)) continue;
const cost = turnCostFromAgentMeta(row.agentMeta);
+ if (cost.costUsd <= 0 && cost.estimatedValueUsd <= 0) continue;
const current = ledger.get(origin.runId) ?? { costUsd: 0, estimatedValueUsd: 0 };
current.costUsd += cost.costUsd;
current.estimatedValueUsd += cost.estimatedValueUsd;
@@ -427,7 +441,24 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
return runs.map((run) => {
const persisted = ledger.get(run.id);
- return persisted ? { ...run, ...persisted } : run;
+ if (!persisted) return normalizeAttribution(run);
+ if (run.costAttribution === 'direct') {
+ return {
+ ...run,
+ costUsd: finitePositiveNumber(run.costUsd) + persisted.costUsd,
+ estimatedValueUsd:
+ finitePositiveNumber(run.estimatedValueUsd) + persisted.estimatedValueUsd,
+ costAttribution: 'exact',
+ };
+ }
+ if (run.costAttribution === 'mixed') {
+ return { ...run, costAttribution: 'exact' };
+ }
+ return {
+ ...run,
+ ...persisted,
+ costAttribution: 'exact',
+ };
});
}
@@ -534,21 +565,24 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
*/
async listCostSummaries(): Promise<ScheduleCostSummary[]> {
const db = this.getDb();
- const linkedRows = await db
+ const runCostRows = await db
.select({
+ runId: scheduleRuns.id,
scheduleId: scheduleRuns.scheduleId,
sessionId: scheduleRuns.sessionId,
+ status: scheduleRuns.status,
+ costUsd: scheduleRuns.costUsd,
+ estimatedValueUsd: scheduleRuns.estimatedValueUsd,
+ costAttribution: scheduleRuns.costAttribution,
})
- .from(scheduleRuns)
- .where(isNotNull(scheduleRuns.sessionId));
+ .from(scheduleRuns);
const bySchedule = new Map<string, ScheduleTurnCostState>();
const linkedSessionIds = new Set<string>();
const linkedScheduleIds = new Set<string>();
- for (const row of linkedRows) {
- if (!row.sessionId) continue;
- linkedSessionIds.add(row.sessionId);
+ for (const row of runCostRows) {
linkedScheduleIds.add(row.scheduleId);
+ if (row.sessionId) linkedSessionIds.add(row.sessionId);
}
const scheduleByLegacyKey = await this.listSchedulesByLegacyKey(db);
@@ -618,6 +652,11 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
let activeSessionId: string | null = null;
let activeScheduleId: string | null = null;
const billableMessageCostBySessionId = new Map<string, number>();
+ const messageCostRunIds = new Set<string>();
+ const messageCostByRunId = new Map<
+ string,
+ { costUsd: number; estimatedValueUsd: number }
+ >();
for (const row of messageRows) {
if (row.sessionId !== activeSessionId) {
activeSessionId = row.sessionId;
@@ -637,7 +676,9 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
(billableMessageCostBySessionId.get(row.sessionId) ?? 0) + cost,
);
}
- const assistantScheduleId = scheduleOriginFromAgentMeta(row.agentMeta)?.scheduleId;
+ const assistantOrigin = scheduleOriginFromAgentMeta(row.agentMeta);
+ const assistantScheduleId = assistantOrigin?.scheduleId;
+ const assistantRunId = assistantOrigin?.runId;
const attributedScheduleId = assistantScheduleId ?? activeScheduleId;
if (!attributedScheduleId || !linkedScheduleIds.has(attributedScheduleId)) {
continue;
@@ -645,9 +686,20 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
const entry = bySchedule.get(attributedScheduleId) ?? {
totalCostUsd: 0,
totalEstimatedValueUsd: 0,
+ hasUnavailableCost: false,
sessionIds: new Set<string>(),
sessionCosts: new Map(),
};
+ if (assistantRunId) {
+ messageCostRunIds.add(assistantRunId);
+ const runCost = messageCostByRunId.get(assistantRunId) ?? {
+ costUsd: 0,
+ estimatedValueUsd: 0,
+ };
+ runCost.costUsd += cost;
+ runCost.estimatedValueUsd += turnCost.estimatedValueUsd;
+ messageCostByRunId.set(assistantRunId, runCost);
+ }
entry.sessionIds.add(row.sessionId);
entry.totalCostUsd += cost;
entry.totalEstimatedValueUsd += turnCost.estimatedValueUsd;
@@ -661,6 +713,138 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
bySchedule.set(attributedScheduleId, entry);
}
+ // 纯 tool turn 没有 assistant message 可挂账,费用会直接写在 schedule_runs。
+ // 正常消息费用已经进入 message ledger;混合 run 则只补 schedule_runs 快照中
+ // 尚未被消息账本覆盖的余量,避免漏记 direct segment 或双计。
+ for (const run of runCostRows) {
+ if (run.costAttribution === 'unavailable' && run.status !== 'running') {
+ // 消息账本已经给出该 run 的费用时,以账本为准;schedule_runs 快照可由
+ // listRuns 的 hydrate 路径自愈,不应把任务误标成“部分费用不可用”。
+ if (messageCostRunIds.has(run.runId)) continue;
+ const entry = bySchedule.get(run.scheduleId) ?? {
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ hasUnavailableCost: false,
+ sessionIds: new Set<string>(),
+ sessionCosts: new Map(),
+ };
+ entry.hasUnavailableCost = true;
+ if (run.sessionId) {
+ entry.sessionIds.add(run.sessionId);
+ if (!entry.sessionCosts.has(run.sessionId)) {
+ entry.sessionCosts.set(run.sessionId, {
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ });
+ }
+ }
+ bySchedule.set(run.scheduleId, entry);
+ continue;
+ }
+ if (
+ run.costAttribution === 'zero' &&
+ run.status !== 'running' &&
+ !messageCostRunIds.has(run.runId)
+ ) {
+ const entry = bySchedule.get(run.scheduleId) ?? {
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ hasUnavailableCost: false,
+ sessionIds: new Set<string>(),
+ sessionCosts: new Map(),
+ };
+ if (run.sessionId) {
+ entry.sessionIds.add(run.sessionId);
+ if (!entry.sessionCosts.has(run.sessionId)) {
+ entry.sessionCosts.set(run.sessionId, {
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ });
+ }
+ }
+ bySchedule.set(run.scheduleId, entry);
+ continue;
+ }
+ if (run.costAttribution === 'direct' || run.costAttribution === 'mixed') {
+ const messageCost = messageCostByRunId.get(run.runId);
+ const costUsd =
+ run.costAttribution === 'direct'
+ ? finitePositiveNumber(run.costUsd)
+ : Math.max(
+ 0,
+ finitePositiveNumber(run.costUsd) - (messageCost?.costUsd ?? 0),
+ );
+ const estimatedValueUsd =
+ run.costAttribution === 'direct'
+ ? finitePositiveNumber(run.estimatedValueUsd)
+ : Math.max(
+ 0,
+ finitePositiveNumber(run.estimatedValueUsd) -
+ (messageCost?.estimatedValueUsd ?? 0),
+ );
+ if (costUsd === 0 && estimatedValueUsd === 0) continue;
+ const entry = bySchedule.get(run.scheduleId) ?? {
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ hasUnavailableCost: false,
+ sessionIds: new Set<string>(),
+ sessionCosts: new Map(),
+ };
+ entry.totalCostUsd += costUsd;
+ entry.totalEstimatedValueUsd += estimatedValueUsd;
+ if (run.sessionId) {
+ entry.sessionIds.add(run.sessionId);
+ const sessionCost = entry.sessionCosts.get(run.sessionId) ?? {
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ };
+ sessionCost.totalCostUsd += costUsd;
+ sessionCost.totalEstimatedValueUsd += estimatedValueUsd;
+ entry.sessionCosts.set(run.sessionId, sessionCost);
+ if (costUsd > 0) {
+ billableMessageCostBySessionId.set(
+ run.sessionId,
+ (billableMessageCostBySessionId.get(run.sessionId) ?? 0) + costUsd,
+ );
+ }
+ }
+ bySchedule.set(run.scheduleId, entry);
+ continue;
+ }
+ if (run.costAttribution !== 'exact') continue;
+ const messageCost = messageCostByRunId.get(run.runId);
+ if (messageCost) continue;
+ const costUsd = finitePositiveNumber(run.costUsd);
+ const estimatedValueUsd = finitePositiveNumber(run.estimatedValueUsd);
+ if (costUsd === 0 && estimatedValueUsd === 0) continue;
+ const entry = bySchedule.get(run.scheduleId) ?? {
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ hasUnavailableCost: false,
+ sessionIds: new Set<string>(),
+ sessionCosts: new Map(),
+ };
+ entry.totalCostUsd += costUsd;
+ entry.totalEstimatedValueUsd += estimatedValueUsd;
+ if (run.sessionId) {
+ entry.sessionIds.add(run.sessionId);
+ const sessionCost = entry.sessionCosts.get(run.sessionId) ?? {
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
+ };
+ sessionCost.totalCostUsd += costUsd;
+ sessionCost.totalEstimatedValueUsd += estimatedValueUsd;
+ entry.sessionCosts.set(run.sessionId, sessionCost);
+ if (costUsd > 0) {
+ billableMessageCostBySessionId.set(
+ run.sessionId,
+ (billableMessageCostBySessionId.get(run.sessionId) ?? 0) + costUsd,
+ );
+ }
+ }
+ bySchedule.set(run.scheduleId, entry);
+ }
+
for (const session of legacySessions) {
const scheduleId = legacySessionScheduleIds.get(session.id);
if (!scheduleId) continue;
@@ -668,6 +852,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
const entry = bySchedule.get(scheduleId) ?? {
totalCostUsd: 0,
totalEstimatedValueUsd: 0,
+ hasUnavailableCost: false,
sessionIds: new Set<string>(),
sessionCosts: new Map(),
};
@@ -691,6 +876,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
scheduleId,
totalCostUsd: summary.totalCostUsd,
totalEstimatedValueUsd: summary.totalEstimatedValueUsd,
+ ...(summary.hasUnavailableCost ? { hasUnavailableCost: true } : {}),
sessionCount: summary.sessionIds.size,
sessions: [...summary.sessionCosts.entries()].map(([sessionId, costs]) => ({
sessionId,
diff --git a/apps/desktop/src/main/turnCostBroadcaster.ts b/apps/desktop/src/main/turnCostBroadcaster.ts
index a70a366262..01d14c2005 100644
--- a/apps/desktop/src/main/turnCostBroadcaster.ts
+++ b/apps/desktop/src/main/turnCostBroadcaster.ts
@@ -25,7 +25,10 @@ import {
import { enqueueDurableWrite } from './messagePersistBroadcaster.js';
import { createLogger } from './logger.js';
import { tapWindowBroadcast } from './device-link/broadcast-tap.js';
-import { applyScheduleRunCostMetaChange } from './scheduler-host/runCostLedger.js';
+import {
+ applyScheduleRunCostMetaChange,
+ recordScheduleRunCostDirect,
+} from './scheduler-host/runCostLedger.js';
const log = createLogger('turnCostBroadcaster');
@@ -98,10 +101,10 @@ export async function recordTurnCostOnMessage(
turnOrigin?: SendOrigin;
},
deps: TurnCostDeps = defaultDeps,
-): Promise<void> {
+): Promise<boolean> {
const { sessionId, clientId, costUsd, isEstimate, turnUsageDetails, turnOrigin } = args;
- if (!sessionId || !clientId) return;
- if (!Number.isFinite(costUsd) || costUsd < 1e-10) return;
+ if (!sessionId || !clientId) return false;
+ if (!Number.isFinite(costUsd) || costUsd < 1e-10) return false;
try {
let userTurnCostUsd = costUsd;
let userTurnCostIsEstimate = isEstimate;
@@ -134,18 +137,78 @@ export async function recordTurnCostOnMessage(
}
return result;
});
- if (!patched) return;
- deps.broadcast({
- sessionId,
+ if (!patched) return false;
+ try {
+ deps.broadcast({
+ sessionId,
+ clientId,
+ turnCostUsd: costUsd,
+ turnCostIsEstimate: isEstimate,
+ userTurnCostUsd,
+ userTurnCostIsEstimate,
+ ...(turnUsageDetails ? { turnUsageDetails } : {}),
+ });
+ } catch (err) {
+ // The message cost is already durable; a broadcast failure must not
+ // make scheduler fallback record the same segment a second time.
+ log.warn('recordTurnCostOnMessage broadcast failed:', err instanceof Error ? err.message : String(err));
+ }
+ return true;
+ } catch (err) {
+ log.warn('recordTurnCostOnMessage failed:', err instanceof Error ? err.message : String(err));
+ return false;
+ }
+}
+
+export interface SchedulerTurnCostFallbackDeps {
+ recordOnMessage: typeof recordTurnCostOnMessage;
+ recordDirect: typeof recordScheduleRunCostDirect;
+}
+
+const defaultSchedulerTurnCostFallbackDeps: SchedulerTurnCostFallbackDeps = {
+ recordOnMessage: recordTurnCostOnMessage,
+ recordDirect: recordScheduleRunCostDirect,
+};
+
+/**
+ * 记录一笔 scheduler turn 费用:优先写 assistant message;消息路径无法写入时按 runId
+ * 直接归因,保证会话费用与自动化费用不会因纯 tool turn 分叉。
+ */
+export async function recordSchedulerTurnCost(
+ args: {
+ sessionId: string;
+ clientId?: string;
+ costUsd: number;
+ isEstimate: boolean;
+ turnUsageDetails?: TurnUsageDetails | null;
+ turnOrigin?: SendOrigin;
+ },
+ deps: SchedulerTurnCostFallbackDeps = defaultSchedulerTurnCostFallbackDeps,
+): Promise<string | null> {
+ const { clientId, turnOrigin } = args;
+ if (clientId) {
+ const recorded = await deps.recordOnMessage({
+ ...args,
clientId,
- turnCostUsd: costUsd,
- turnCostIsEstimate: isEstimate,
- userTurnCostUsd,
- userTurnCostIsEstimate,
- ...(turnUsageDetails ? { turnUsageDetails } : {}),
+ });
+ if (recorded) return null;
+ }
+ if (
+ turnOrigin?.kind !== 'scheduler' ||
+ typeof turnOrigin.runId !== 'string' ||
+ !turnOrigin.runId
+ ) {
+ return null;
+ }
+ try {
+ return await deps.recordDirect({
+ runId: turnOrigin.runId,
+ costUsd: args.costUsd,
+ isEstimate: args.isEstimate,
});
} catch (err) {
- log.warn('recordTurnCostOnMessage failed:', err instanceof Error ? err.message : String(err));
+ log.warn('recordSchedulerTurnCost fallback failed:', err instanceof Error ? err.message : String(err));
+ return null;
}
}
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index 7d6517a3e7..39414b064f 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -946,7 +946,7 @@ describe('automation-generated sessions', () => {
expect(schedulePageSource).toContain('useScheduleCostSummaries(sorted)');
expect(taskListPaneSource).toContain('costSummariesLoaded');
expect(taskListCellSource).toContain('scheduler.cell.totalCost');
- expect(taskListCellSource).toContain('formatUsd(totalCostUsd)');
+ expect(taskListCellSource).toContain('formatUsd(totalCostUsd ?? 0)');
expect(runHistoryPaneSource).toContain('groupRunsForHistory');
expect(runHistoryPaneSource).toContain('PERSISTENT_SESSION_PREVIEW_LIMIT = 3');
expect(runHistoryPaneSource).toContain('expandRemainingRuns');
diff --git a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx
index ae3d9044c5..c12a67f7c8 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx
@@ -152,20 +152,27 @@ export function RunHistoryCard({
run.status === 'running'
? formatStartedAgo(run.firedAt)
: t('scheduler.runs.took', { duration: formatDuration(run.firedAt, run.finishedAt) });
- const costText = run.costAttribution === 'legacy'
- ? t('scheduler.runs.legacyCostUnavailable')
- : run.costAttribution === 'exact'
- ? [
- (run.costUsd ?? 0) > 0
- ? t('scheduler.runs.runCost', { cost: formatUsd(run.costUsd ?? 0) })
- : null,
- (run.estimatedValueUsd ?? 0) > 0
- ? t('scheduler.runs.runValue', { value: formatUsd(run.estimatedValueUsd ?? 0) })
- : null,
- ]
- .filter(Boolean)
- .join(' · ') || t('scheduler.runs.runCost', { cost: formatUsd(0) })
- : null;
+ const costText = run.status === 'running'
+ ? null
+ : run.costAttribution === 'legacy'
+ ? t('scheduler.runs.legacyCostUnavailable')
+ : run.costAttribution === 'unavailable'
+ ? t('scheduler.runs.costUnavailable')
+ : run.costAttribution === 'exact' ||
+ run.costAttribution === 'direct' ||
+ run.costAttribution === 'mixed' ||
+ run.costAttribution === 'zero'
+ ? [
+ (run.costUsd ?? 0) > 0
+ ? t('scheduler.runs.runCost', { cost: formatUsd(run.costUsd ?? 0) })
+ : null,
+ (run.estimatedValueUsd ?? 0) > 0
+ ? t('scheduler.runs.runValue', { value: formatUsd(run.estimatedValueUsd ?? 0) })
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' · ') || t('scheduler.runs.runCost', { cost: formatUsd(0) })
+ : null;
// 终态且未读 → 在 agent 图标右上角点一个状态点(全端统一色表:失败结局红 / 成功绿)。
// running 不算未读(结果还没出来,没什么"漏看")。
diff --git a/apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx b/apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx
index 113530ff09..fc40e4a48a 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx
@@ -45,6 +45,7 @@ interface Props {
unreadCount?: number;
totalCostUsd?: number;
totalEstimatedValueUsd?: number;
+ hasUnavailableCost?: boolean;
onSelect: (s: Schedule) => void;
/** 右键菜单的 Pause/Resume 动作;与 RunHistoryPane ⋯ 菜单同行为。 */
onTogglePause?: (s: Schedule) => void | Promise<void>;
@@ -81,6 +82,7 @@ export function TaskListCell({
unreadCount = 0,
totalCostUsd,
totalEstimatedValueUsd = 0,
+ hasUnavailableCost = false,
onSelect,
onTogglePause,
onDelete,
@@ -164,15 +166,16 @@ export function TaskListCell({
subtitle = lastText ?? nextText;
}
const costText =
- totalCostUsd == null
+ totalCostUsd == null && !hasUnavailableCost
? null
: [
- totalCostUsd > 0
- ? t('scheduler.cell.totalCost', { cost: formatUsd(totalCostUsd) })
+ (totalCostUsd ?? 0) > 0
+ ? t('scheduler.cell.totalCost', { cost: formatUsd(totalCostUsd ?? 0) })
: null,
totalEstimatedValueUsd > 0
? t('scheduler.cell.totalValue', { value: formatUsd(totalEstimatedValueUsd) })
: null,
+ hasUnavailableCost ? t('scheduler.cell.costUnavailable') : null,
]
.filter(Boolean)
.join(' · ') || t('scheduler.cell.totalCost', { cost: formatUsd(0) });
diff --git a/apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx b/apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx
index 884d9dac0b..002ff1933e 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx
@@ -227,12 +227,17 @@ export function TaskListPane({
unreadCount={unreadRunCounts.get(s.id) ?? 0}
totalCostUsd={
costSummariesLoaded
- ? (costSummaries.get(s.id)?.totalCostUsd ?? 0)
+ ? costSummaries.get(s.id)?.totalCostUsd
: undefined
}
totalEstimatedValueUsd={
costSummariesLoaded
- ? (costSummaries.get(s.id)?.totalEstimatedValueUsd ?? 0)
+ ? costSummaries.get(s.id)?.totalEstimatedValueUsd
+ : undefined
+ }
+ hasUnavailableCost={
+ costSummariesLoaded
+ ? costSummaries.get(s.id)?.hasUnavailableCost
: undefined
}
onSelect={onSelect}
diff --git a/apps/desktop/src/renderer/features/scheduler/components/__tests__/RunHistoryCard.test.tsx b/apps/desktop/src/renderer/features/scheduler/components/__tests__/RunHistoryCard.test.tsx
index 65cc5518ee..0dbbd57c4c 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/__tests__/RunHistoryCard.test.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/__tests__/RunHistoryCard.test.tsx
@@ -106,3 +106,34 @@ describe('RunHistoryCard 前置检查结果', () => {
expect(screen.getByText(/scheduler\.runs\.preRun\.truncated/)).toBeTruthy();
});
});
+
+describe('RunHistoryCard 费用展示', () => {
+ it('不可可靠计价时不显示假 $0.00', () => {
+ renderRun({
+ id: 'run-unavailable-cost',
+ scheduleId: 'schedule-1',
+ firedAt: 1,
+ finishedAt: 11,
+ status: 'success',
+ costAttribution: 'unavailable',
+ });
+
+ expect(screen.getByText('scheduler.runs.costUnavailable')).toBeTruthy();
+ expect(screen.queryByText(/scheduler\.runs\.runCost/)).toBeNull();
+ });
+
+ it('已确认真实零费用时显示 $0.00', () => {
+ renderRun({
+ id: 'run-zero-cost',
+ scheduleId: 'schedule-1',
+ firedAt: 1,
+ finishedAt: 11,
+ status: 'success',
+ costAttribution: 'zero',
+ costUsd: 0,
+ estimatedValueUsd: 0,
+ });
+
+ expect(screen.getByText('scheduler.runs.runCost')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/scheduler/components/__tests__/TaskListCell.test.tsx b/apps/desktop/src/renderer/features/scheduler/components/__tests__/TaskListCell.test.tsx
index 15eaf8193a..30cd5ec3da 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/__tests__/TaskListCell.test.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/__tests__/TaskListCell.test.tsx
@@ -92,3 +92,46 @@ describe('TaskListCell 并发等待提示', () => {
expect(screen.queryByText(/Next less than 1 min/)).toBeNull();
});
});
+
+describe('TaskListCell 费用展示', () => {
+ it('无汇总时不伪造 $0.00', () => {
+ render(
+ createElement(TaskListCell, {
+ schedule,
+ selected: false,
+ onSelect: vi.fn(),
+ }),
+ );
+
+ expect(screen.queryByText('scheduler.cell.totalCost')).toBeNull();
+ });
+
+ it('不可可靠计价时显示费用不可用', () => {
+ render(
+ createElement(TaskListCell, {
+ schedule,
+ selected: false,
+ onSelect: vi.fn(),
+ totalCostUsd: 0,
+ hasUnavailableCost: true,
+ }),
+ );
+
+ expect(screen.getByText('scheduler.cell.costUnavailable')).toBeTruthy();
+ expect(screen.queryByText('scheduler.cell.totalCost')).toBeNull();
+ });
+
+ it('已确认真实零费用时仍显示 $0.00', () => {
+ render(
+ createElement(TaskListCell, {
+ schedule,
+ selected: false,
+ onSelect: vi.fn(),
+ totalCostUsd: 0,
+ hasUnavailableCost: false,
+ }),
+ );
+
+ expect(screen.getByText('scheduler.cell.totalCost')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useRuns.test.tsx b/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useRuns.test.tsx
new file mode 100644
index 0000000000..eff2fb2227
--- /dev/null
+++ b/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useRuns.test.tsx
@@ -0,0 +1,124 @@
+// @vitest-environment jsdom
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useRuns } from '../useRuns';
+
+type Listener = (payload: unknown) => void;
+
+let scheduleListeners: Listener[] = [];
+let turnCostListeners: Listener[] = [];
+let listRuns: ReturnType<typeof vi.fn>;
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+beforeEach(() => {
+ scheduleListeners = [];
+ turnCostListeners = [];
+ listRuns = vi.fn(async () => []);
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ maker: {
+ schedule: {
+ listRuns,
+ onEvent: (listener: Listener) => {
+ scheduleListeners.push(listener);
+ return () => {
+ scheduleListeners = scheduleListeners.filter((item) => item !== listener);
+ };
+ },
+ },
+ },
+ onUsageMessageTurnCost: (listener: Listener) => {
+ turnCostListeners.push(listener);
+ return () => {
+ turnCostListeners = turnCostListeners.filter((item) => item !== listener);
+ };
+ },
+ };
+});
+
+afterEach(() => {
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+ vi.restoreAllMocks();
+});
+
+describe('useRuns 异步费用刷新', () => {
+ it('费用广播晚于 completed 时重新读取运行历史', async () => {
+ const { unmount } = renderHook(() => useRuns('schedule-1'));
+ await waitFor(() => expect(listRuns).toHaveBeenCalledTimes(1));
+
+ act(() => {
+ turnCostListeners.forEach((listener) =>
+ listener({ sessionId: 'session-1', clientId: 'assistant-1', turnCostUsd: 0.42 }),
+ );
+ });
+
+ await waitFor(() => expect(listRuns).toHaveBeenCalledTimes(2));
+ unmount();
+ expect(turnCostListeners).toHaveLength(0);
+ });
+
+ it('同一 schedule 的旧刷新响应不能覆盖较新的费用快照', async () => {
+ const firstRefresh = deferred<unknown[]>();
+ const secondRefresh = deferred<unknown[]>();
+ listRuns
+ .mockResolvedValueOnce([])
+ .mockImplementationOnce(() => firstRefresh.promise)
+ .mockImplementationOnce(() => secondRefresh.promise);
+
+ const { result } = renderHook(() => useRuns('schedule-1'));
+ await waitFor(() => expect(listRuns).toHaveBeenCalledTimes(1));
+
+ act(() => {
+ turnCostListeners.forEach((listener) => listener({}));
+ turnCostListeners.forEach((listener) => listener({}));
+ });
+ await waitFor(() => expect(listRuns).toHaveBeenCalledTimes(3));
+
+ const latestRuns = [{ id: 'latest-run' }];
+ const staleRuns = [{ id: 'stale-run' }];
+ await act(async () => {
+ secondRefresh.resolve(latestRuns);
+ await secondRefresh.promise;
+ });
+ await waitFor(() => expect(result.current.runs).toEqual(latestRuns));
+
+ await act(async () => {
+ firstRefresh.resolve(staleRuns);
+ await firstRefresh.promise;
+ });
+ expect(result.current.runs).toEqual(latestRuns);
+ });
+
+ it('清空 scheduleId 时结束旧请求留下的 loading 状态', async () => {
+ const pendingRefresh = deferred<unknown[]>();
+ listRuns.mockImplementationOnce(() => pendingRefresh.promise);
+
+ const { result, rerender } = renderHook(
+ ({ scheduleId }: { scheduleId: string | null }) => useRuns(scheduleId),
+ { initialProps: { scheduleId: 'schedule-1' as string | null } },
+ );
+ await waitFor(() => expect(result.current.loading).toBe(true));
+
+ rerender({ scheduleId: null });
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.runs).toEqual([]);
+ expect(result.current.hasLoaded).toBe(false);
+
+ await act(async () => {
+ pendingRefresh.resolve([{ id: 'stale-run' }]);
+ await pendingRefresh.promise;
+ });
+ expect(result.current.loading).toBe(false);
+ expect(result.current.runs).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts
index 9c634b5cda..e724b68064 100644
--- a/apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts
+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts
@@ -36,36 +36,37 @@ export function useRuns(scheduleId: string | null, limit = 50): UseRunsResult {
const [hasLoaded, setHasLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
- // 防止 race:用户飞快切 A→B→A 时,A 的请求晚于 B 的请求返回会把 B 的数据冲掉。
- // 用 ref 记录最近发起的 fetch 的 scheduleId,回调里只接受跟它匹配的结果。
- const latestFetchIdRef = useRef<string | null>(null);
+ // 防止 race:同一 schedule 的连续刷新可能并发返回,旧快照不能覆盖新费用。
+ // 用递增序号记录最近发起的 fetch,回调里只接受最新请求的结果。
+ const latestFetchIdRef = useRef(0);
const refresh = useCallback(async () => {
+ const fetchId = latestFetchIdRef.current + 1;
+ latestFetchIdRef.current = fetchId;
if (!scheduleId) {
// 完全没有选中:清空展示。其他场景(切任务)保留旧数据等新数据替换。
- latestFetchIdRef.current = null;
setRuns([]);
setRunsScheduleId(null);
+ setLoading(false);
setError(null);
setHasLoaded(false);
return;
}
- latestFetchIdRef.current = scheduleId;
setLoading(true);
try {
const list = (await window.electronAPI.maker.schedule.listRuns(scheduleId, limit)) as ScheduleRun[];
// 过期请求直接丢弃,不写 state
- if (latestFetchIdRef.current !== scheduleId) return;
+ if (latestFetchIdRef.current !== fetchId) return;
setRuns(list);
setRunsScheduleId(scheduleId);
setError(null);
} catch (e) {
- if (latestFetchIdRef.current !== scheduleId) return;
+ if (latestFetchIdRef.current !== fetchId) return;
setError(e instanceof Error ? e.message : String(e));
// 失败也算"这条 scheduleId 有结论",让 caller 走 error 分支
setRunsScheduleId(scheduleId);
} finally {
- if (latestFetchIdRef.current === scheduleId) {
+ if (latestFetchIdRef.current === fetchId) {
setLoading(false);
setHasLoaded(true);
}
@@ -102,9 +103,15 @@ export function useRuns(scheduleId: string | null, limit = 50): UseRunsResult {
// 广播,跨实例过期的未读快照等不到上面的事件,必须靠这条本地通道自愈
// (见 scheduleRunReadSync 模块注释)。
const offReadSync = subscribeScheduleRunReadSync(() => void refresh());
+ // Codex 费用在 done 后异步查价并落 message/run 账本,可能晚于 completed 事件。
+ // 监听费用广播,避免历史卡永久保留 completed 时读到的旧快照。
+ const offTurnCost = window.electronAPI.onUsageMessageTurnCost?.(() => {
+ void refresh();
+ });
return () => {
off();
offReadSync();
+ offTurnCost?.();
};
}, [scheduleId, refresh]);
diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts
index 3b3f0862bd..0d572388bb 100644
--- a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts
+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts
@@ -10,7 +10,9 @@ export interface ScheduleCostSummary {
scheduleId: string;
totalCostUsd: number;
totalEstimatedValueUsd: number;
- /** 产生过自动化 turn cost 的去重 session 数;legacy 会话兜底同样计入。 */
+ /** 至少一轮自动化无法取得可靠费用。 */
+ hasUnavailableCost?: boolean;
+ /** 产生过自动化 run 的去重 session 数;费用不可用或确认为零的 run 也会计入。 */
sessionCount: number;
sessions?: readonly ScheduleSessionCostSummary[];
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b564f7eb6e..ca209319c9 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5348,6 +5348,7 @@
"tagManual": "Manual",
"totalCost": "Cost {{cost}}",
"totalValue": "Value {{value}}",
+ "costUnavailable": "Cost unavailable",
"menu": {
"rename": "Rename",
"resume": "Resume",
@@ -5387,6 +5388,7 @@
"sessionValue": "Session value {{value}}",
"runCost": "Run cost {{cost}}",
"runValue": "Estimated run value {{value}}",
+ "costUnavailable": "Cost unavailable",
"legacyCostUnavailable": "Historical cost unavailable",
"persistentSessionGroup": "Persistent session {{session}} · {{count}} runs",
"expandRemainingRuns": "Show {{count}} more",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 210734577e..3eab9e69ae 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5338,6 +5338,7 @@
"tagManual": "手動",
"totalCost": "コスト {{cost}}",
"totalValue": "価値 {{value}}",
+ "costUnavailable": "コストを取得できません",
"menu": {
"rename": "名前を変更",
"resume": "再開",
@@ -5377,6 +5378,7 @@
"sessionValue": "セッション価値 {{value}}",
"runCost": "実行コスト {{cost}}",
"runValue": "実行の推定価値 {{value}}",
+ "costUnavailable": "コストを取得できません",
"legacyCostUnavailable": "過去のコストは実行別に分割できません",
"persistentSessionGroup": "継続セッション {{session}} · {{count}} 回の実行",
"expandRemainingRuns": "残り {{count}} 回を表示",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 36413e4345..db463017a5 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5338,6 +5338,7 @@
"tagManual": "수동",
"totalCost": "비용 {{cost}}",
"totalValue": "가치 {{value}}",
+ "costUnavailable": "비용을 확인할 수 없음",
"menu": {
"rename": "이름 변경",
"resume": "재개",
@@ -5377,6 +5378,7 @@
"sessionValue": "세션 가치 {{value}}",
"runCost": "실행 비용 {{cost}}",
"runValue": "실행 추정 가치 {{value}}",
+ "costUnavailable": "비용을 확인할 수 없음",
"legacyCostUnavailable": "이전 비용은 실행별로 구분할 수 없습니다",
"persistentSessionGroup": "지속 세션 {{session}} · {{count}}회 실행",
"expandRemainingRuns": "나머지 {{count}}회 보기",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 2145db306f..6d443ff603 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5338,6 +5338,7 @@
"tagManual": "手动",
"totalCost": "开销 {{cost}}",
"totalValue": "价值 {{value}}",
+ "costUnavailable": "费用不可用",
"menu": {
"rename": "重命名",
"resume": "恢复",
@@ -5377,6 +5378,7 @@
"sessionValue": "会话价值 {{value}}",
"runCost": "本次开销 {{cost}}",
"runValue": "本次估算价值 {{value}}",
+ "costUnavailable": "费用不可用",
"legacyCostUnavailable": "历史费用无法拆分",
"persistentSessionGroup": "持续会话 {{session}} · {{count}} 次运行",
"expandRemainingRuns": "展开另外 {{count}} 次",
diff --git a/packages/maker-scheduler/src/__tests__/scheduler.test.ts b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
index a49e4497bf..3d7e8e1a72 100644
--- a/packages/maker-scheduler/src/__tests__/scheduler.test.ts
+++ b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
@@ -213,6 +213,23 @@ describe('Scheduler', () => {
expect(list).toHaveLength(1);
});
+ it('marks skipped child runs as zero-cost', async () => {
+ const childHarness = makeHarness({
+ runnerImpl: async (_schedule, ctx) => {
+ await ctx.createChildRun?.({ status: 'skipped' });
+ return { sessionId: '' };
+ },
+ });
+ const sch = await childHarness.scheduler.create({ ...baseInput });
+
+ await childHarness.scheduler.runNow(sch.id);
+
+ const skippedRun = (await childHarness.scheduler.listRuns(sch.id)).find(
+ (run) => run.status === 'skipped',
+ );
+ expect(skippedRun?.costAttribution).toBe('zero');
+ });
+
it('create() preserves dialogue workspace target', async () => {
const sch = await h.scheduler.create({ ...baseInput, workspaceKind: 'dialogue' });
expect(sch.workspaceKind).toBe('dialogue');
diff --git a/packages/maker-scheduler/src/engine/scheduler.ts b/packages/maker-scheduler/src/engine/scheduler.ts
index bebb5362e2..bb360f864f 100644
--- a/packages/maker-scheduler/src/engine/scheduler.ts
+++ b/packages/maker-scheduler/src/engine/scheduler.ts
@@ -500,6 +500,8 @@ export class Scheduler extends EventEmitter {
scheduleId: schedule.id,
firedAt,
status: 'running',
+ // Script 不产生 agent token,零费用是确定值;agent 费用在 turn done 后异步归因。
+ costAttribution: schedule.executionMode === 'script' ? 'zero' : 'unavailable',
heartbeatAt: firedAt,
};
try {
@@ -609,6 +611,7 @@ export class Scheduler extends EventEmitter {
status: 'skipped',
sessionId: sessionId || undefined,
finishedAt,
+ costAttribution: 'zero',
resultText,
readAt: finishedAt,
});
@@ -725,6 +728,7 @@ export class Scheduler extends EventEmitter {
scheduleId: schedule.id,
firedAt,
status: 'running',
+ costAttribution: schedule.executionMode === 'script' ? 'zero' : 'unavailable',
heartbeatAt: firedAt,
};
await this.storage.insertRun(initialRun);
@@ -829,6 +833,7 @@ export class Scheduler extends EventEmitter {
status: 'skipped',
sessionId: runSessionId || undefined,
finishedAt,
+ costAttribution: 'zero',
resultText: runResultText,
readAt: finishedAt,
});
@@ -1617,6 +1622,7 @@ export class Scheduler extends EventEmitter {
firedAt,
finishedAt: this.clock.now(),
status: input.status,
+ costAttribution: input.status === 'skipped' ? 'zero' : 'unavailable',
resultText: input.resultText,
errorMsg: input.errorMsg,
};
diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.ts
index c9d2d68bb5..7e03efea7b 100644
--- a/packages/maker-scheduler/src/types.ts
+++ b/packages/maker-scheduler/src/types.ts
@@ -241,8 +241,12 @@ export interface ScheduleRun {
costUsd?: number;
/** 本次 run 的订阅 token 估算价值,不计入真实账单。 */
estimatedValueUsd?: number;
- /** exact = 有持久化 runId 归因;legacy = 历史数据无法精确拆到单次 run。 */
- costAttribution?: 'exact' | 'legacy';
+ /**
+ * exact = 已确认费用(可能是实际账单,也可能是 estimate-only);direct = 费用仅来自
+ * 无法挂载消息的直接账本;mixed = 快照同时包含直接账本和消息账本;zero = 已确认零费用;
+ * unavailable = agent run 尚无可靠计价;legacy = 历史数据无法精确拆到单次 run。
+ */
+ costAttribution?: 'exact' | 'direct' | 'mixed' | 'zero' | 'unavailable' | 'legacy';
/**
* Agent 这一轮 turn 的最终文本(与飞书正常对话气泡显示内容同源 — 按 isFinal
* 替换、否则追加 delta,done 时定格)。仅 prompt 类 run 在 success 时填,
diff --git a/packages/maker-shared/src/scheduleTypes.ts b/packages/maker-shared/src/scheduleTypes.ts
index 5263ad40e1..8617a09b6f 100644
--- a/packages/maker-shared/src/scheduleTypes.ts
+++ b/packages/maker-shared/src/scheduleTypes.ts
@@ -119,7 +119,7 @@ export interface RemoteScheduleRun {
resultText?: string;
costUsd?: number;
estimatedValueUsd?: number;
- costAttribution?: 'exact' | 'legacy';
+ costAttribution?: 'exact' | 'direct' | 'mixed' | 'zero' | 'unavailable' | 'legacy';
readAt?: RemoteTimestamp;
}