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(codex): 修正子代理卡 token 统计 (#2256)

Chris Zhang4dbf86dc8f72
diff --git a/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts b/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts
index 5489dc5a64..527f1f5151 100644
--- a/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts
+++ b/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts
@@ -98,6 +98,195 @@ describe('createSubagentLiveCardTracker', () => {
expect(afterUsage?.toolUses).toBe(1);
});
+ it('subtracts forked parent history from the token count shown on a subagent card', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+
+ // app-server attaches the forked child by replaying its restored usage before the
+ // first child turn. That absolute total belongs to the parent history, not this card.
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'restored-parent-turn',
+ tokenUsage: {
+ total: { totalTokens: 10_000 },
+ last: { totalTokens: 900 },
+ },
+ }),
+ ).toBeNull();
+ expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'))).toBeNull();
+
+ tracker.handleDescendantNotification('t-child', 'turn/started', {
+ turn: { id: 'child-turn-1' },
+ });
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-1',
+ tokenUsage: {
+ total: { totalTokens: 10_120 },
+ last: { totalTokens: 120 },
+ },
+ })?.totalTokens,
+ ).toBe(120);
+
+ // Later absolute snapshots remain relative to the same spawn baseline.
+ tracker.handleDescendantNotification('t-child', 'turn/started', {
+ turn: { id: 'child-turn-2' },
+ });
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-2',
+ tokenUsage: {
+ total: { totalTokens: 10_310 },
+ last: { totalTokens: 190 },
+ },
+ })?.totalTokens,
+ ).toBe(310);
+ });
+
+ it('infers the spawn baseline from last-turn usage when no restored snapshot arrives', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));
+ // item 通知也能证明这是 live turn;即使 turn/started 丢失也不能误判成恢复帧。
+ tracker.handleDescendantNotification('t-child', 'item/started', {
+ turnId: 'child-turn-1',
+ item: { id: 'message-1', type: 'agentMessage' },
+ });
+
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-1',
+ tokenUsage: {
+ total: { totalTokens: 8_250 },
+ last: { totalTokens: 250 },
+ },
+ })?.totalTokens,
+ ).toBe(250);
+ });
+
+ it('counts delayed first usage from an earlier observed live turn without a restored snapshot', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));
+ tracker.handleDescendantNotification('t-child', 'turn/started', {
+ turn: { id: 'child-turn-1' },
+ });
+ tracker.handleDescendantNotification('t-child', 'turn/started', {
+ turn: { id: 'child-turn-2' },
+ });
+
+ // turn 1 的首帧 usage 可以晚于 turn 2 started;它仍是已观测的 live turn,必须用
+ // last 反推 spawn 基线,而不能把整帧误认成 fork / resume 的恢复快照。
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-1',
+ tokenUsage: {
+ total: { totalTokens: 8_250 },
+ last: { totalTokens: 250 },
+ },
+ })?.totalTokens,
+ ).toBe(250);
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-2',
+ tokenUsage: {
+ total: { totalTokens: 8_400 },
+ last: { totalTokens: 150 },
+ },
+ })?.totalTokens,
+ ).toBe(400);
+ });
+
+ it('keeps legacy total-only token payloads as absolute snapshots', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));
+ tracker.handleDescendantNotification('t-child', 'item/started', {
+ turnId: 'child-turn-1',
+ item: { id: 'child-tool-1', type: 'commandExecution' },
+ });
+
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-1',
+ tokenUsage: { total: { totalTokens: 4_242 } },
+ })?.totalTokens,
+ ).toBe(4_242);
+ });
+
+ it('keeps the original spawn baseline when restored snapshots are duplicated out of order', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));
+
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'restored-parent-turn',
+ tokenUsage: { total: { totalTokens: 1_000 }, last: { totalTokens: 100 } },
+ });
+ tracker.handleDescendantNotification('t-child', 'turn/started', {
+ turn: { id: 'child-turn-1' },
+ });
+ // A zero-growth live snapshot leaves the visible counter at zero.
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-1',
+ tokenUsage: { total: { totalTokens: 1_000 }, last: { totalTokens: 0 } },
+ }),
+ ).toBeNull();
+
+ // A stale replay must not replace the already-established 1,000-token baseline.
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'older-parent-turn',
+ tokenUsage: { total: { totalTokens: 900 }, last: { totalTokens: 90 } },
+ }),
+ ).toBeNull();
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-1',
+ tokenUsage: { total: { totalTokens: 1_100 }, last: { totalTokens: 100 } },
+ })?.totalTokens,
+ ).toBe(100);
+ });
+
+ it('keeps cumulative usage monotonic when a prior live turn reports late', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'restored-parent-turn',
+ tokenUsage: { total: { totalTokens: 1_000 }, last: { totalTokens: 100 } },
+ });
+ tracker.handleDescendantNotification('t-child', 'turn/started', {
+ turn: { id: 'child-turn-1' },
+ });
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-1',
+ tokenUsage: { total: { totalTokens: 1_100 }, last: { totalTokens: 100 } },
+ })?.totalTokens,
+ ).toBe(100);
+
+ tracker.handleDescendantNotification('t-child', 'turn/started', {
+ turn: { id: 'child-turn-2' },
+ });
+ // The previous turn can finish flushing after the next turn starts; its newer
+ // cumulative snapshot still belongs to this child and must not be discarded.
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-1',
+ tokenUsage: { total: { totalTokens: 1_150 }, last: { totalTokens: 50 } },
+ })?.totalTokens,
+ ).toBe(150);
+ // An older duplicate must not make the displayed count fall back to 100.
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-1',
+ tokenUsage: { total: { totalTokens: 1_100 }, last: { totalTokens: 100 } },
+ }),
+ ).toBeNull();
+ expect(
+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {
+ turnId: 'child-turn-2',
+ tokenUsage: { total: { totalTokens: 1_300 }, last: { totalTokens: 150 } },
+ })?.totalTokens,
+ ).toBe(300);
+ });
+
it('uses Cindy configured model only until the child thread reports its actual model', () => {
const tracker = createSubagentLiveCardTracker({ now: () => 0, subagentModelFallback: 'gpt-5.6-terra' });
expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'))).toMatchObject({
@@ -230,20 +419,35 @@ describe('createSubagentLiveCardTracker', () => {
toolUses: 2,
});
- // token 是各线程累计快照之和;同线程再报只覆盖自己那份,不重复相加。
+ // 每个 receiver 都先收到 fork 恢复帧;卡片只累计各线程从自身基线之后的增长。
+ tracker.handleDescendantNotification('t-a', 'thread/tokenUsage/updated', {
+ turnId: 'restored-a',
+ tokenUsage: { total: { totalTokens: 1_000 }, last: { totalTokens: 80 } },
+ });
+ tracker.handleDescendantNotification('t-b', 'thread/tokenUsage/updated', {
+ turnId: 'restored-b',
+ tokenUsage: { total: { totalTokens: 2_000 }, last: { totalTokens: 90 } },
+ });
+ tracker.handleDescendantNotification('t-a', 'turn/started', { turn: { id: 'live-a' } });
+ tracker.handleDescendantNotification('t-b', 'turn/started', { turn: { id: 'live-b' } });
+
+ // token 是各线程 spawn 后累计快照之和;同线程再报只覆盖自己那份,不重复相加。
expect(
tracker.handleDescendantNotification('t-a', 'thread/tokenUsage/updated', {
- tokenUsage: { total: { totalTokens: 100 } },
+ turnId: 'live-a',
+ tokenUsage: { total: { totalTokens: 1_100 }, last: { totalTokens: 100 } },
})?.totalTokens,
).toBe(100);
expect(
tracker.handleDescendantNotification('t-b', 'thread/tokenUsage/updated', {
- tokenUsage: { total: { totalTokens: 40 } },
+ turnId: 'live-b',
+ tokenUsage: { total: { totalTokens: 2_040 }, last: { totalTokens: 40 } },
})?.totalTokens,
).toBe(140);
expect(
tracker.handleDescendantNotification('t-a', 'thread/tokenUsage/updated', {
- tokenUsage: { total: { totalTokens: 130 } },
+ turnId: 'live-a',
+ tokenUsage: { total: { totalTokens: 1_130 }, last: { totalTokens: 30 } },
})?.totalTokens,
).toBe(170);
});
@@ -492,6 +696,34 @@ describe('createSubagentLiveCardTracker', () => {
).toBeNull();
});
+ it('counts delayed usage from a failed nested child turn without an item notification', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));
+ // nested spawn 先失败,receiver 随后才补发 turn/started;失败状态必须锁住,但 turn id
+ // 仍要记下,否则后续现代 usage 会被当成恢复帧,烧掉的 token 永久漏计。
+ expect(tracker.noteDescendantThread('t-grand', 't-child', undefined, true)).toBeNull();
+ expect(
+ tracker.handleDescendantNotification('t-grand', 'turn/started', {
+ turn: { id: 'failed-child-turn' },
+ }),
+ ).toBeNull();
+
+ expect(
+ tracker.handleDescendantNotification('t-grand', 'thread/tokenUsage/updated', {
+ turnId: 'failed-child-turn',
+ tokenUsage: {
+ total: { totalTokens: 1_250 },
+ last: { totalTokens: 250 },
+ },
+ }),
+ ).toMatchObject({ status: 'running', totalTokens: 250 });
+ expect(
+ tracker.handleDescendantNotification('t-child', 'turn/completed', {
+ turn: { status: 'completed' },
+ }),
+ ).toMatchObject({ status: 'failed', totalTokens: 250 });
+ });
+
it('ignores lineage for threads unrelated to any subagent card', () => {
const tracker = createSubagentLiveCardTracker({ now: () => 0 });
// 父线程不属于任何卡(例如主线程的后代未经 spawn 登记)→ 无副作用。
diff --git a/packages/maker-core/src/agents/codex/subagent-live-cards.ts b/packages/maker-core/src/agents/codex/subagent-live-cards.ts
index 4fb641d794..67cb11be90 100644
--- a/packages/maker-core/src/agents/codex/subagent-live-cards.ts
+++ b/packages/maker-core/src/agents/codex/subagent-live-cards.ts
@@ -41,7 +41,7 @@ export interface SubagentLiveCardUpdate {
agentPath?: string;
/** Observed child-thread model, or Cindy's explicit display fallback. `null` clears a stale badge. */
model?: string | null;
- /** 本卡全部子线程的累计 token 之和;未知为 0。 */
+ /** 本卡全部子线程 token 快照之和;现代载荷按 spawn 增量,旧 total-only 载荷保留绝对值。 */
totalTokens: number;
/** 本卡全部子线程内的工具类 item 数;未知为 0。 */
toolUses: number;
@@ -152,11 +152,20 @@ const MAX_PENDING_THREAD_MODELS = MAX_PENDING_LINEAGE_PARENTS * MAX_PENDING_LINE
* 后台 item/completed,提前清会让迟到的 completed 重复计数),所以只能按条数封顶。
*/
const MAX_COUNTED_ITEM_IDS = 4096;
+/** 基线建立前保留的 live turn id 上限,用于识别跨 turn 延迟到达的首帧 usage。 */
+const MAX_OBSERVED_LIVE_TURN_IDS = 64;
interface ThreadState {
status: SubagentLiveCardStatus;
- /** 该子线程最新的**累计** token(tokenUsage.total 是快照,按线程覆盖而非相加)。 */
+ /** 现代载荷为本次 spawn 后增量;旧 total-only 载荷保留宿主提供的绝对快照。 */
totalTokens: number;
+ /**
+ * app-server 在 fork / resume 连接建立时会先重放一帧恢复后的 tokenUsage;其中 total
+ * 含父线程继承历史,不能直接展示。保存该绝对水位,后续 live 快照只显示相对增量。
+ */
+ tokenUsageBaseline?: number;
+ /** 基线建立前已确认的 live turn id;usage 可能晚于下一轮 turn/started 才到。 */
+ observedLiveTurnIds: Set<string>;
/** Model observed from thread metadata or a spawn item. */
model?: string;
/** A failed nested spawn remains terminal despite late lifecycle events. */
@@ -362,6 +371,15 @@ export function createSubagentLiveCardTracker(opts: {
children.add(childThreadId);
};
+ const noteObservedLiveTurn = (thread: ThreadState, turnId: string | undefined): void => {
+ if (!turnId || thread.tokenUsageBaseline !== undefined || thread.observedLiveTurnIds.has(turnId)) return;
+ if (thread.observedLiveTurnIds.size >= MAX_OBSERVED_LIVE_TURN_IDS) {
+ const oldest = thread.observedLiveTurnIds.values().next();
+ if (!oldest.done) thread.observedLiveTurnIds.delete(oldest.value);
+ }
+ thread.observedLiveTurnIds.add(turnId);
+ };
+
/** 应用一条通知到卡上;返回是否产生了变化(无变化不必发帧)。 */
const applyNotification = (
card: TrackedCard,
@@ -373,7 +391,15 @@ export function createSubagentLiveCardTracker(opts: {
case 'item/started':
case 'item/updated':
case 'item/completed': {
- const item = (params as { item?: { type?: unknown; id?: unknown } } | null)?.item;
+ const itemParams = params as {
+ turnId?: unknown;
+ item?: { type?: unknown; id?: unknown };
+ } | null;
+ const itemTurnId = typeof itemParams?.turnId === 'string' ? itemParams.turnId : undefined;
+ // app-server 不会把历史 item 重放成 live 通知;即使 turn/started 丢失,item 也能
+ // 证明这个 turn 已经真实开跑,避免把随后到来的 live usage 误判成恢复帧。
+ noteObservedLiveTurn(thread, itemTurnId);
+ const item = itemParams?.item;
const itemType = typeof item?.type === 'string' ? item.type : '';
const itemId = typeof item?.id === 'string' ? item.id : '';
if (!itemId || !TOOL_ITEM_TYPES.has(itemType)) return false;
@@ -389,17 +415,71 @@ export function createSubagentLiveCardTracker(opts: {
return true;
}
case 'thread/tokenUsage/updated': {
- const total = (params as { tokenUsage?: { total?: { totalTokens?: unknown } } } | null)
- ?.tokenUsage?.total?.totalTokens;
- if (typeof total !== 'number' || !Number.isFinite(total)) return false;
- // total 是该线程的累计快照 → 覆盖本线程分量,卡片总量由各线程求和。
- thread.totalTokens = total;
+ const usageParams = params as {
+ turnId?: unknown;
+ tokenUsage?: {
+ total?: { totalTokens?: unknown };
+ last?: { totalTokens?: unknown };
+ };
+ } | null;
+ const total = usageParams?.tokenUsage?.total?.totalTokens;
+ if (typeof total !== 'number' || !Number.isFinite(total) || total < 0) return false;
+ const usageTurnId = typeof usageParams?.turnId === 'string' ? usageParams.turnId : undefined;
+ const last = usageParams?.tokenUsage?.last?.totalTokens;
+
+ // 旧宿主只给 total(即使附带 turnId),没有 last 就无法从第一帧反推出 spawn 水位。
+ // 这种载荷保持既有绝对快照语义;当前 app-server 的恢复帧与 live 帧都会带 last。
+ if (thread.tokenUsageBaseline === undefined && last === undefined) {
+ if (thread.totalTokens === total) return false;
+ thread.totalTokens = total;
+ return true;
+ }
+
+ // fork / resume 会在子线程第一个 live turn 之前重放恢复后的 usage。它的 total 是
+ // 父线程历史 + 子线程增量的绝对累计值;若直接展示,就会把整段父会话历史算到卡上。
+ // live 用量通知带当前 turnId,恢复帧没有对应的 live turn / item(或 id 不同),
+ // 所以只把它记成基线而不产可见帧。无 turnId 的旧宿主载荷沿用原来的绝对快照口径。
+ if (
+ usageTurnId
+ && !thread.observedLiveTurnIds.has(usageTurnId)
+ && thread.tokenUsageBaseline === undefined
+ ) {
+ thread.tokenUsageBaseline = total;
+ thread.observedLiveTurnIds.clear();
+ return false;
+ }
+ if (!usageTurnId && thread.observedLiveTurnIds.size === 0) {
+ if (thread.totalTokens === total) return false;
+ thread.totalTokens = total;
+ return true;
+ }
+
+ if (thread.tokenUsageBaseline === undefined) {
+ // 若宿主或 fork 配置没先发恢复帧,用本次 live 增量反推出 spawn 前水位。协议缺
+ // last 时宁可从当前 total 起算(本帧显示 0),也不要再次把继承历史误报成用量。
+ thread.tokenUsageBaseline = typeof last === 'number'
+ && Number.isFinite(last)
+ && last >= 0
+ && last <= total
+ ? total - last
+ : total;
+ thread.observedLiveTurnIds.clear();
+ }
+ const relativeTotal = Math.max(0, total - thread.tokenUsageBaseline);
+ // total 是累计快照,乱序旧帧或重复恢复帧都不能让卡片数字回退。
+ if (relativeTotal <= thread.totalTokens) return false;
+ thread.totalTokens = relativeTotal;
return true;
}
- case 'turn/started':
+ case 'turn/started': {
+ const turnId = (params as { turn?: { id?: unknown } } | null)?.turn?.id;
+ noteObservedLiveTurn(thread, typeof turnId === 'string' ? turnId : undefined);
+ // nested spawn 的失败闩可能早于迟到的 turn/started;状态仍须保持 failed,但 live
+ // turn 身份必须先留下,后续 usage 才不会被误判成 fork / resume 的恢复快照。
if (thread.spawnFailed) return false;
thread.status = 'running';
return true;
+ }
case 'turn/completed': {
if (thread.spawnFailed) return false;
const turnStatus = (params as { turn?: { status?: unknown } } | null)?.turn?.status;
@@ -449,6 +529,7 @@ export function createSubagentLiveCardTracker(opts: {
card.threads.set(childThreadId, {
status: card.spawnFailed || latchSpawnFailure ? 'failed' : 'running',
totalTokens: 0,
+ observedLiveTurnIds: new Set<string>(),
...(initialModel ? { model: initialModel } : {}),
spawnFailed: latchSpawnFailure,
});
@@ -637,7 +718,12 @@ export function createSubagentLiveCardTracker(opts: {
if (card.threads.size === 0) {
// 一个线程都还没登记上的卡(spawn 刚认出、子线程尚未 started):补一个占位线程,
// 否则 aggregateStatus 对空集合返回 running,这张卡还是会留在转圈状态。
- card.threads.set('__shutdown__', { status: 'stopped', totalTokens: 0, spawnFailed: false });
+ card.threads.set('__shutdown__', {
+ status: 'stopped',
+ totalTokens: 0,
+ observedLiveTurnIds: new Set<string>(),
+ spawnFailed: false,
+ });
}
out.push(snapshot(card));
}