Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: surface heterogeneous agent usage live (#17026)

Arvin Xu4e257f033337
diff --git a/apps/server/src/services/usage/cost.test.ts b/apps/server/src/services/usage/cost.test.ts
index 892c91c9c0e..2de3e58cae4 100644
--- a/apps/server/src/services/usage/cost.test.ts
+++ b/apps/server/src/services/usage/cost.test.ts
@@ -19,6 +19,7 @@ describe('computeMessageCostSplit', () => {
expect(split.totalCost).toBe(0.42);
expect(split.inputCost).toBe(0.42);
+ expect(split.cachedInputCost).toBe(0);
expect(split.outputCost).toBe(0);
expect(split.cacheWriteCost).toBe(0);
expect(split.cacheSavings).toBe(0);
@@ -37,9 +38,12 @@ describe('computeMessageCostSplit', () => {
const split = computeMessageCostSplit(usage, priced.providerId, priced.id, 1.5);
expect(split.totalCost).toBeCloseTo(1.5, 6);
- // input (incl. cache-read) + output + cache-write must sum back to the billed total
- expect(split.inputCost + split.outputCost + split.cacheWriteCost).toBeCloseTo(1.5, 6);
+ // input + cached input + output + cache-write must sum back to the billed total
+ expect(
+ split.inputCost + split.cachedInputCost + split.outputCost + split.cacheWriteCost,
+ ).toBeCloseTo(1.5, 6);
expect(split.inputCost).toBeGreaterThan(0);
+ expect(split.cachedInputCost).toBeGreaterThan(0);
expect(split.outputCost).toBeGreaterThan(0);
});
diff --git a/apps/server/src/services/usage/cost.ts b/apps/server/src/services/usage/cost.ts
index 68b817f4e89..60d6a7c8bf4 100644
--- a/apps/server/src/services/usage/cost.ts
+++ b/apps/server/src/services/usage/cost.ts
@@ -33,6 +33,7 @@ const toUsdRate = (rate: number | undefined, currency?: string): number | undefi
rate === undefined ? undefined : currency === 'CNY' ? rate / USD_TO_CNY : rate;
export interface MessageCostSplit {
+ cachedInputCost: number;
/** Input tokens that missed the cache and were freshly processed. */
cacheMissTokens: number;
/** Cached input tokens that were read (cache hits). */
@@ -41,7 +42,7 @@ export interface MessageCostSplit {
cacheSavings: number;
cacheWriteCost: number;
cacheWriteTokens: number;
- /** Input cost incl. the cache-read portion (USD). */
+ /** Input cost for tokens that missed the cache (USD). */
inputCost: number;
inputTokens: number;
outputCost: number;
@@ -109,9 +110,10 @@ export const computeMessageCostSplit = (
cacheMissTokens,
cacheReadTokens,
cacheSavings,
+ cachedInputCost: cacheReadCost,
cacheWriteCost,
cacheWriteTokens,
- inputCost: freshInputCost + cacheReadCost,
+ inputCost: freshInputCost,
inputTokens: totalInputTokens,
outputCost,
outputTokens,
diff --git a/apps/server/src/services/usage/index.ts b/apps/server/src/services/usage/index.ts
index d609062d233..7ca9e52f40d 100644
--- a/apps/server/src/services/usage/index.ts
+++ b/apps/server/src/services/usage/index.ts
@@ -274,6 +274,8 @@ export class UsageRecordService {
const start = bucketStart(row.createdAt);
const key = start.format('YYYY-MM-DD');
const bucket = buckets.get(key) ?? {
+ cachedInputCost: 0,
+ cachedInputTokens: 0,
cacheWriteCost: 0,
cacheWriteTokens: 0,
date: start.valueOf(),
@@ -285,10 +287,12 @@ export class UsageRecordService {
totalCost: 0,
};
bucket.inputCost += split.inputCost;
+ bucket.cachedInputCost += split.cachedInputCost;
bucket.outputCost += split.outputCost;
bucket.cacheWriteCost += split.cacheWriteCost;
bucket.totalCost += split.totalCost;
- bucket.inputTokens += split.inputTokens;
+ bucket.inputTokens += split.cacheMissTokens;
+ bucket.cachedInputTokens += split.cacheReadTokens;
bucket.outputTokens += split.outputTokens;
bucket.cacheWriteTokens += split.cacheWriteTokens;
buckets.set(key, bucket);
@@ -336,6 +340,8 @@ export class UsageRecordService {
const key = cursor.format('YYYY-MM-DD');
padded.push(
buckets.get(key) ?? {
+ cachedInputCost: 0,
+ cachedInputTokens: 0,
cacheWriteCost: 0,
cacheWriteTokens: 0,
date: cursor.valueOf(),
diff --git a/locales/en-US/spend.json b/locales/en-US/spend.json
index d51e648f7a2..ec287f97751 100644
--- a/locales/en-US/spend.json
+++ b/locales/en-US/spend.json
@@ -54,6 +54,7 @@
"usageStats.cards.token": "Token",
"usageStats.cards.tokenDesc": "Input {{input}} · Output {{output}}",
"usageStats.chart.cacheWrite": "Cache write",
+ "usageStats.chart.cachedInput": "Cached input",
"usageStats.chart.input": "Input",
"usageStats.chart.output": "Output",
"usageStats.chart.spend": "Cost",
diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.json
index 189d834ad21..833aa4ce1e1 100644
--- a/locales/zh-CN/spend.json
+++ b/locales/zh-CN/spend.json
@@ -54,6 +54,7 @@
"usageStats.cards.token": "Token",
"usageStats.cards.tokenDesc": "输入 {{input}} · 输出 {{output}}",
"usageStats.chart.cacheWrite": "缓存写入",
+ "usageStats.chart.cachedInput": "缓存输入",
"usageStats.chart.input": "输入",
"usageStats.chart.output": "输出",
"usageStats.chart.spend": "费用",
diff --git a/packages/locales/src/default/spend.ts b/packages/locales/src/default/spend.ts
index 33a2e654451..d18dab65c76 100644
--- a/packages/locales/src/default/spend.ts
+++ b/packages/locales/src/default/spend.ts
@@ -54,6 +54,7 @@ export default {
'usageStats.cards.token': 'Token',
'usageStats.cards.tokenDesc': 'Input {{input}} · Output {{output}}',
'usageStats.chart.cacheWrite': 'Cache write',
+ 'usageStats.chart.cachedInput': 'Cached input',
'usageStats.chart.input': 'Input',
'usageStats.chart.output': 'Output',
'usageStats.chart.spend': 'Cost',
diff --git a/packages/types/src/usage/usageRecord.ts b/packages/types/src/usage/usageRecord.ts
index a5907b3c97c..1968cfab02a 100644
--- a/packages/types/src/usage/usageRecord.ts
+++ b/packages/types/src/usage/usageRecord.ts
@@ -59,10 +59,12 @@ export type AgentUsageGranularity = 'day' | 'week';
/**
* One bar in the agent usage trend chart. Cost components are reconciled to the
* authoritative billed cost; token components are the raw reported counts.
- * `input` cost folds the cache-read cost into it (the chart only breaks out
- * input / output / cache-write, matching the legend).
+ * Cached and uncached input are kept separate so the chart reflects their
+ * different rates.
*/
export interface AgentUsageBucket {
+ cachedInputCost: number;
+ cachedInputTokens: number;
cacheWriteCost: number;
cacheWriteTokens: number;
/** Bucket start timestamp (ms), for stable sorting. */
diff --git a/src/features/AgentUsage/UsageTrendChart.tsx b/src/features/AgentUsage/UsageTrendChart.tsx
index b8de095b60a..a5c8cc36c36 100644
--- a/src/features/AgentUsage/UsageTrendChart.tsx
+++ b/src/features/AgentUsage/UsageTrendChart.tsx
@@ -1,8 +1,9 @@
'use client';
-import { BarChart } from '@lobehub/charts';
+import { BarChart, ChartTooltipFrame, ChartTooltipRow } from '@lobehub/charts';
import { Block, Flexbox, Skeleton, Text } from '@lobehub/ui';
import { Segmented } from '@lobehub/ui/base-ui';
+import { Divider } from 'antd';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,8 +15,8 @@ enum ShowType {
Token = 'token',
}
-// 输入 (dark) / 输出 (medium) / 缓存写入 (light) — blue shades matching the design.
-const COLORS = ['#1668dc', '#4096ff', '#91caff'];
+// Uncached input (dark) / cached input / output / cache write (light).
+const COLORS = ['#1668dc', '#1677ff', '#4096ff', '#91caff'];
interface UsageTrendChartProps {
buckets?: AgentUsageBucket[];
@@ -27,19 +28,28 @@ const UsageTrendChart = memo<UsageTrendChartProps>(({ buckets, isLoading }) => {
const [type, setType] = useState<ShowType>(ShowType.Spend);
const inputKey = t('usageStats.chart.input');
+ const cachedInputKey = t('usageStats.chart.cachedInput');
const outputKey = t('usageStats.chart.output');
const cacheWriteKey = t('usageStats.chart.cacheWrite');
- const categories = [inputKey, outputKey, cacheWriteKey];
const chartData = useMemo(
() =>
(buckets ?? []).map((b) => ({
[cacheWriteKey]: type === ShowType.Spend ? b.cacheWriteCost : b.cacheWriteTokens,
+ [cachedInputKey]: type === ShowType.Spend ? b.cachedInputCost : b.cachedInputTokens,
[inputKey]: type === ShowType.Spend ? b.inputCost : b.inputTokens,
[outputKey]: type === ShowType.Spend ? b.outputCost : b.outputTokens,
label: b.label,
})),
- [buckets, type, inputKey, outputKey, cacheWriteKey],
+ [buckets, type, inputKey, cachedInputKey, outputKey, cacheWriteKey],
+ );
+
+ const series = useMemo(
+ () =>
+ [inputKey, cachedInputKey, outputKey, cacheWriteKey]
+ .map((key, index) => ({ color: COLORS[index], key }))
+ .filter(({ key }) => chartData.some((item) => Number(item[key]) > 0)),
+ [cacheWriteKey, cachedInputKey, chartData, inputKey, outputKey],
);
return (
@@ -63,11 +73,47 @@ const UsageTrendChart = memo<UsageTrendChartProps>(({ buckets, isLoading }) => {
<BarChart
showLegend
stack
- categories={categories}
- colors={COLORS}
+ categories={series.map(({ key }) => key)}
+ colors={series.map(({ color }) => color)}
data={chartData}
height={320}
index={'label'}
+ customTooltip={({ active, label, payload }) => {
+ if (!active || !payload) return null;
+
+ const visibleItems = payload.filter(
+ ({ value }) => typeof value === 'number' && value > 0,
+ );
+
+ return (
+ <ChartTooltipFrame>
+ <Flexbox paddingBlock={8} paddingInline={16}>
+ <Text as={'p'} style={{ margin: 0 }}>
+ {label}
+ </Text>
+ </Flexbox>
+ {visibleItems.length > 0 && (
+ <>
+ <Divider style={{ margin: 0 }} />
+ <Flexbox gap={4} paddingBlock={8} paddingInline={16}>
+ {visibleItems.map(({ color, name, value }) => (
+ <ChartTooltipRow
+ color={color ?? '#1668dc'}
+ key={String(name)}
+ name={String(name ?? '')}
+ value={
+ type === ShowType.Spend
+ ? `$${formatNumber(value as number, 2)}`
+ : formatTokenNumber(value as number)
+ }
+ />
+ ))}
+ </Flexbox>
+ </>
+ )}
+ </ChartTooltipFrame>
+ );
+ }}
valueFormatter={(num: number) =>
type === ShowType.Spend ? `$${formatNumber(num, 2)}` : formatTokenNumber(num)
}
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 44191030376..24ec6b81673 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -137,6 +137,7 @@ const styles = createStaticStyles(({ css }) => ({
font-weight: 500;
color: ${cssVar.colorText};
text-overflow: ellipsis;
+ text-transform: none;
white-space: nowrap;
`,
count: css`
@@ -166,17 +167,6 @@ const styles = createStaticStyles(({ css }) => ({
iconPinned: css`
color: ${cssVar.colorInfo};
`,
- fixedIndicator: css`
- display: inline-flex;
- flex: none;
- align-items: center;
- justify-content: center;
-
- width: 24px;
- height: 24px;
-
- color: ${cssVar.colorTextQuaternary};
- `,
policyButton: css`
cursor: pointer;
@@ -343,25 +333,6 @@ const styles = createStaticStyles(({ css }) => ({
width: 100%;
min-width: 0;
`,
- toolRowDisabled: css`
- opacity: 0.5;
- `,
- disabledTag: css`
- display: inline-flex;
- flex: none;
- gap: 3px;
- align-items: center;
-
- padding-block: 1px;
- padding-inline: 4px;
- border: 1px solid ${cssVar.colorErrorBorder};
- border-radius: 4px;
-
- font-size: 12px;
- color: ${cssVar.colorError};
-
- background: ${cssVar.colorErrorBg};
- `,
toolTrailing: css`
display: inline-flex;
flex: none;
@@ -430,6 +401,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
const { updateAgentChatConfig } = useUpdateAgentConfig();
const [pinnedOpen, setPinnedOpen] = useState(true);
const [autoOpen, setAutoOpen] = useState(true);
+ const [disabledOpen, setDisabledOpen] = useState(true);
const [policyOpenId, setPolicyOpenId] = useState<string | null>(null);
const [searchKeyword, setSearchKeyword] = useState('');
const [autoModeLoading, setAutoModeLoading] = useState(false);
@@ -466,9 +438,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
]);
const checkedSet = useMemo(() => new Set(checked), [checked]);
// Disabled identifiers, read from the raw (unfiltered) plugins config —
- // needed to grey out an Auto-group item and to offer the third policy-menu
- // option. Disabled items stay in the Auto group (no separate group), so
- // `allPinnedItems`/`allAutoItems` below keep splitting on `checkedSet` alone.
+ // needed to render the dedicated Disabled group and policy-menu state.
const rawPlugins = useAgentStore(
(s) => agentByIdSelectors.getAgentConfigById(agentId)(s)?.plugins,
);
@@ -531,12 +501,14 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
// connected yet (pending auth / re-authorize), where activation is
// meaningless but the user still needs a way to remove the entry.
deleteOnly = false,
+ supportedModes: SkillPolicyMode[] = ['pinned', 'auto', 'disabled'],
+ defaultMode: SkillPolicyMode = 'auto',
) => {
const mode: SkillPolicyMode = checkedSet.has(id)
? 'pinned'
: disabledIdSet.has(id)
? 'disabled'
- : 'auto';
+ : defaultMode;
const renderCheck = (value: SkillPolicyMode) =>
mode === value ? (
<span className={cx(styles.policyCheck)}>
@@ -571,6 +543,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
onContextMenu={(event) => event.stopPropagation()}
>
{!deleteOnly &&
+ supportedModes.includes('pinned') &&
renderPolicyItem(
'pinned',
<Icon
@@ -580,6 +553,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
/>,
)}
{!deleteOnly &&
+ supportedModes.includes('auto') &&
renderPolicyItem(
'auto',
<Icon
@@ -589,6 +563,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
/>,
)}
{!deleteOnly &&
+ supportedModes.includes('disabled') &&
renderPolicyItem(
'disabled',
<Icon
@@ -705,39 +680,27 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
badge?: ReactNode,
icon?: ReactNode,
extraTag?: ReactNode,
- ) => {
- // Disabled items stay in the Auto group (no separate group) — greyed out
- // + relabeled in place, per the confirmed UI plan.
- const isDisabled = disabledIdSet.has(id);
-
- return (
- <span
- className={cx(styles.toolRow, isDisabled && styles.toolRowDisabled)}
- onContextMenu={(event) => {
- event.preventDefault();
- event.stopPropagation();
- openSkillPolicyMenu(id);
- }}
- >
- <span className={cx(styles.toolLabel)}>
- {icon}
- <span className={cx(styles.toolLabelText)}>{label}</span>
- {isDisabled && (
- <span className={cx(styles.disabledTag)}>
- <Icon icon={Ban} size={11} />
- {t('tools.activation.disabled')}
- </span>
- )}
- {extraTag}
- </span>
- <span className={cx(styles.toolTrailing)}>
- {badge && <span className={cx(styles.typeTag)}>{badge}</span>}
- {action}
- </span>
+ ) => (
+ <span
+ className={cx(styles.toolRow)}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openSkillPolicyMenu(id);
+ }}
+ >
+ <span className={cx(styles.toolLabel)}>
+ {icon}
+ <span className={cx(styles.toolLabelText)}>{label}</span>
+ {extraTag}
</span>
- );
- },
- [openSkillPolicyMenu, disabledIdSet, t],
+ <span className={cx(styles.toolTrailing)}>
+ {badge && <span className={cx(styles.typeTag)}>{badge}</span>}
+ {action}
+ </span>
+ </span>
+ ),
+ [openSkillPolicyMenu],
);
const createManagedSkillItem = useCallback(
@@ -749,16 +712,20 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
icon,
id,
popoverContent,
+ defaultMode,
+ supportedModes,
searchText,
title,
}: {
badge?: ReactNode;
configureConfig?: SkillConfigureConfig;
+ defaultMode?: SkillPolicyMode;
deleteConfig?: SkillDeleteConfig;
extraTag?: ReactNode;
icon: ReactNode;
id: string;
popoverContent?: ReactNode;
+ supportedModes?: SkillPolicyMode[];
searchText?: string;
title: ReactNode;
}): SkillMenuItem =>
@@ -768,7 +735,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
label: renderToolLabel(
id,
title,
- renderPolicyMenu(id, deleteConfig, configureConfig),
+ renderPolicyMenu(id, deleteConfig, configureConfig, false, supportedModes, defaultMode),
badge,
icon,
extraTag,
@@ -1141,9 +1108,8 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
[filteredBuiltinList, t, createManagedSkillItem, uninstallBuiltinTool],
);
- // Application-fixed tool items (read-only). Always-on tools owned by the runtime
- // (lobe-agent + always-on infra), so they get a fixed indicator instead of the policy
- // menu and can't be switched to "auto" or uninstalled.
+ // Builtin runtime tools support an explicit pinned/disabled policy. They intentionally
+ // do not support "auto": when enabled, these foundational capabilities stay pinned.
const fixedItems = useMemo(
() =>
fixedDisplayList.map((item) => {
@@ -1178,33 +1144,19 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
/>
);
- return {
- closeOnClick: false,
- key: item.identifier,
- label: (
- <span className={cx(styles.toolRow)}>
- <span className={cx(styles.toolLabel)}>
- {icon}
- <span className={cx(styles.toolLabelText)}>{title}</span>
- {officialTag}
- </span>
- <span className={cx(styles.toolTrailing)}>
- <span className={cx(styles.typeTag)}>
- <Icon icon={Wrench} size={12} />
- </span>
- <Tooltip placement={'top'} title={t('tools.activation.fixed.hint')}>
- <span className={cx(styles.fixedIndicator)}>
- <Icon icon={Pin} size={15} />
- </span>
- </Tooltip>
- </span>
- </span>
- ),
+ return createManagedSkillItem({
+ badge: <Icon icon={Wrench} size={12} />,
+ defaultMode: 'pinned',
+ extraTag: officialTag,
+ icon,
+ id: item.identifier,
popoverContent,
searchText: `${title} ${item.identifier}`,
- } as SkillMenuItem;
+ supportedModes: ['pinned', 'disabled'],
+ title,
+ });
}),
- [fixedDisplayList, t],
+ [createManagedSkillItem, fixedDisplayList, t],
);
// Builtin Agent Skills list items (grouped under LobeHub)
@@ -1511,10 +1463,17 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
);
};
const allPinnedItems = allSkillItems.filter((item) => checkedSet.has(String(item.key)));
- const allAutoItems = allSkillItems.filter((item) => !checkedSet.has(String(item.key)));
- // App-fixed tools always lead the pinned section, ahead of user-pinned plugins.
- const pinnedItems = filterBySearch([...fixedItems, ...allPinnedItems]);
+ const allAutoItems = allSkillItems.filter(
+ (item) => !checkedSet.has(String(item.key)) && !disabledIdSet.has(String(item.key)),
+ );
+ const allDisabledItems = allSkillItems.filter((item) => disabledIdSet.has(String(item.key)));
+ const fixedPinnedItems = fixedItems.filter((item) => !disabledIdSet.has(String(item.key)));
+ const fixedDisabledItems = fixedItems.filter((item) => disabledIdSet.has(String(item.key)));
+ // Enabled builtin tools lead the pinned section. All disabled tools and skills live in
+ // their own section so "Auto" remains semantically accurate.
+ const pinnedItems = filterBySearch([...fixedPinnedItems, ...allPinnedItems]);
const autoItems = filterBySearch(allAutoItems);
+ const disabledItems = filterBySearch([...fixedDisabledItems, ...allDisabledItems]);
const renderActivationGroupLabel = ({
autoSwitch,
@@ -1636,7 +1595,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
children: pinnedOpen ? pinnedItems : [],
key: 'pinned',
label: renderActivationGroupLabel({
- count: allPinnedItems.length,
+ count: fixedPinnedItems.length + allPinnedItems.length,
icon: <Icon icon={Pin} size={14} />,
open: pinnedOpen,
title: t('tools.activation.pinned'),
@@ -1671,6 +1630,30 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
} as ItemType,
]
: []),
+ ...(disabledItems.length > 0 && (pinnedItems.length > 0 || autoItems.length > 0)
+ ? [
+ {
+ key: 'skill-disabled-divider',
+ type: 'divider' as const,
+ } as ItemType,
+ ]
+ : []),
+ ...(disabledItems.length > 0
+ ? [
+ {
+ children: disabledOpen ? disabledItems : [],
+ key: 'disabled',
+ label: renderActivationGroupLabel({
+ count: fixedDisabledItems.length + allDisabledItems.length,
+ icon: <Icon icon={Ban} size={14} />,
+ open: disabledOpen,
+ title: t('tools.activation.disabled'),
+ onToggle: () => setDisabledOpen((open) => !open),
+ }),
+ type: 'group' as const,
+ } as ItemType,
+ ]
+ : []),
];
// Items for the installed tab - only show installed plugins
@@ -2037,6 +2020,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
marketFooter,
marketHeader,
marketItems,
- pinnedCount: allPinnedItems.length + fixedItems.length,
+ pinnedCount: allPinnedItems.length + fixedPinnedItems.length,
};
};
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index f54ee6eeff4..b64203dbb27 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -1040,12 +1040,17 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
);
const dispatched = store.internal_dispatchMessage.mock.calls.find(
- ([payload]: any) =>
- payload.type === 'updateMessage' && payload.value?.metadata?.usage !== undefined,
+ ([payload]: any) => payload.type === 'updateMessage' && payload.value?.usage !== undefined,
);
expect(dispatched).toBeDefined();
expect(dispatched![0].value.model).toBe('claude-opus-4-6');
expect(dispatched![0].value.provider).toBe('claude-code');
+ expect(dispatched![0].value.usage).toMatchObject({
+ totalInputTokens: 100,
+ totalOutputTokens: 20,
+ totalTokens: 120,
+ });
+ expect(dispatched![0].value.metadata.usage).toBeUndefined();
});
it('should write accumulated reasoning', async () => {
@@ -1085,7 +1090,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
]);
const usageWrites = mockUpdateMessage.mock.calls.filter(
- ([, val]: any) => val.metadata?.usage?.totalTokens,
+ ([, val]: any) => val.usage?.totalTokens,
);
// One usage write per step (msg_01 → ast-initial, msg_02 → new step assistant)
expect(usageWrites.length).toBe(2);
@@ -1095,7 +1100,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
const step1 = usageWrites.find(([id]: any) => id === 'ast-initial');
expect(step1).toBeDefined();
- const u1 = step1![1].metadata.usage;
+ const u1 = step1![1].usage;
// msg_01: 100 input (miss) + 200 cached + 50 cache_create = 350; 50 output
expect(u1.totalInputTokens).toBe(350);
expect(u1.totalOutputTokens).toBe(50);
@@ -1106,7 +1111,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
const step2 = usageWrites.find(([id]: any) => id === step2Id);
expect(step2).toBeDefined();
- const u2 = step2![1].metadata.usage;
+ const u2 = step2![1].usage;
// msg_02: 300 input (miss, no cache); 80 output
expect(u2.totalInputTokens).toBe(300);
expect(u2.totalOutputTokens).toBe(80);
@@ -1140,11 +1145,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
]);
const usageWrites = mockUpdateMessage.mock.calls.filter(
- ([, val]: any) => val.metadata?.usage?.totalTokens,
+ ([, val]: any) => val.usage?.totalTokens,
);
expect(usageWrites.length).toBe(1);
- expect(usageWrites[0][1].metadata.usage.totalOutputTokens).toBe(265); // not 1
- expect(usageWrites[0][1].metadata.usage.totalInputTokens).toBe(6);
+ expect(usageWrites[0][1].usage.totalOutputTokens).toBe(265); // not 1
+ expect(usageWrites[0][1].usage.totalInputTokens).toBe(6);
});
});
@@ -2085,20 +2090,19 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
);
expect(modelWrites.length).toBeGreaterThan(0);
- const usageWrite = modelWrites.find(([, value]: any) => value.metadata?.usage);
+ const usageWrite = modelWrites.find(([, value]: any) => value.usage);
expect(usageWrite?.[1]).toMatchObject({
- metadata: {
- usage: {
- inputCachedTokens: 4,
- inputCacheMissTokens: 6,
- totalInputTokens: 10,
- totalOutputTokens: 3,
- totalTokens: 13,
- },
- },
model: 'gpt-5.5',
provider: 'codex',
+ usage: {
+ inputCachedTokens: 4,
+ inputCacheMissTokens: 6,
+ totalInputTokens: 10,
+ totalOutputTokens: 3,
+ totalTokens: 13,
+ },
});
+ expect(usageWrite?.[1].metadata.usage).toBeUndefined();
});
it('waits for late Codex terminal events when Electron complete arrives before stdout tail', async () => {
@@ -2666,7 +2670,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(contentAttempts.filter((id) => id === finalAssistantId)).toHaveLength(2);
expect(finalRow.content).toBe(finalText);
- expect(finalRow.metadata.usage).toMatchObject({
+ expect(finalRow.usage).toMatchObject({
inputCachedTokens: 4,
inputCacheMissTokens: 6,
totalInputTokens: 10,
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 71827bc3778..7225d1348f5 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -27,6 +27,7 @@ import type {
ConversationContext,
HeterogeneousProviderConfig,
MessageMapScope,
+ ModelUsage,
PageSelection,
UIChatMessage,
WorkingDirConfig,
@@ -1665,12 +1666,12 @@ export const executeHeterogeneousAgent = async (
case 'recordUsage': {
const update = {
+ // Keep usage on the promoted top-level field so the live message UI
+ // can render it immediately, before the terminal DB refresh runs.
+ usage: intent.usage as ModelUsage,
// Wholesale metadata overwrite — re-stamp the provenance the
- // createAssistant write put there, or usage would wipe it.
- metadata: {
- ...heteroProvenance(mainState.currentMainMessageId),
- usage: intent.usage as any,
- },
+ // createAssistant write put there.
+ metadata: heteroProvenance(mainState.currentMainMessageId),
...(intent.model && { model: intent.model }),
...(intent.provider && { provider: intent.provider }),
};