Skip to content
Source
Sign inSign up
TanStack/ai

Subagent usage doesn't reach the parent's `onUsage` or final `RUN_FINISHED`, and is dropped when `run` returns a string #2298

OpenXhale1(GitHub profile, opens in a new tab) opened this issue 1 comment

TanStack AI version

@tanstack/ai 1.10.1 (npm latest)

Framework/Library version

Node 26.14.0, server only, zod 4.6.7

Describe the bug and the steps to reproduce it

docs/chat/subagents.md says:

The parent RUN_FINISHED.usage includes the token usage of every child.

In practice, a caller that tracks spend through the parent can miss all of the children's usage:

  1. run returns a string: the usage of the child's ctx.chat() calls is dropped. It appears on no parent chunk at all. subagents-advanced.md presents returning a plain value as a normal pattern ("run can return a promise of any value"), and those model calls go through the library's own ctx.chat, so it could count them whatever run returns.
  2. run returns a stream or a ChatResult: the children's usage is added to the RUN_FINISHED of the parent step that called them, as an AG-UI usage[] array. The last RUN_FINISHED carries only the parent's last model call, in TanStack's { promptTokens, ... } shape. A caller that reads the last RUN_FINISHED, or adds up onUsage, never sees the children.
  3. Parent onUsage: fires only for the parent's own model calls, in both cases. The docs say the parent's middleware doesn't reach the child, so this may be by design, but then the parent's middleware has no hook that sees the children's usage. For example, withPersistence or a cost tracker on the parent can't record it.

Steps: install @tanstack/ai@1.10.1 and zod in an ESM package, save the script below as repro.mjs, and run node repro.mjs result, then node repro.mjs string. No API key needed.

import { chat, defineAgent } from "@tanstack/ai";
import { fakeText } from "@tanstack/ai/testing";
import { z } from "zod";

// result: run returns the ctx.chat({ stream: false }) result
// string: run returns that result's .text
const mode = process.argv[2] ?? "result";

const researcher = defineAgent({
  name: "researcher",
  description: "Researches one task",
  inputSchema: z.object({ label: z.string() }),
  run: async (ctx) => {
    const child = fakeText();
    child.setResponses([{ text: `Report for ${ctx.input.label}.` }]);
    const result = await ctx.chat({ adapter: child, stream: false });
    return mode === "string" ? result.text : result;
  },
});

const parent = fakeText();
parent.setResponses([
  {
    toolCalls: [1, 2].map((n) => ({
      name: "researcher",
      input: { label: `task ${n}` },
    })),
  },
  { text: "Done." },
]);

const onUsage = [];
const result = await chat({
  adapter: parent,
  messages: [{ role: "user", content: "Research tasks 1 and 2" }],
  threadId: "thread-1",
  subagents: { agents: [researcher] },
  middleware: [{ name: "log-usage", onUsage: (_ctx, usage) => void onUsage.push(usage) }],
  stream: false,
});

console.log("onUsage calls:", onUsage);
result.chunks
  .filter((c) => c.type === "RUN_FINISHED")
  .forEach((c, i) => console.log(`RUN_FINISHED #${i + 1} usage:`, JSON.stringify(c.usage)));

Output with result:

onUsage calls: [
  { promptTokens: 7, completionTokens: 15, totalTokens: 22 },
  { promptTokens: 43, completionTokens: 2, totalTokens: 45 }
]
RUN_FINISHED #1 usage: [{"inputTokens":7,"outputTokens":15,"totalTokens":22},{"inputTokens":7,"outputTokens":5,"totalTokens":12},{"inputTokens":7,"outputTokens":5,"totalTokens":12}]
RUN_FINISHED #2 usage: {"promptTokens":43,"completionTokens":2,"totalTokens":45}

Output with string: the two children's 12-token calls appear nowhere.

onUsage calls: [
  { promptTokens: 7, completionTokens: 15, totalTokens: 22 },
  { promptTokens: 43, completionTokens: 2, totalTokens: 45 }
]
RUN_FINISHED #1 usage: {"promptTokens":7,"completionTokens":15,"totalTokens":22}
RUN_FINISHED #2 usage: {"promptTokens":43,"completionTokens":2,"totalTokens":45}

Expected: the children's usage reaches the parent whatever run returns, and the parent exposes it somewhere a caller would look for the run's total: the final RUN_FINISHED, or a middleware hook.

Suggested fix:

  • Count the usage of the bound activities on ctx (ctx.chat and the generation calls) into the child's SubagentSink as they finish, rather than only from the stream run returns (collectUsage in spawnAgentStream). A run that returns a stream would need its chunks deduplicated against that.
  • Give the parent's middleware a way to see child usage, either onUsage with ctx.subagentRunId set, or a separate onSubagentUsage.
  • Say in the docs which RUN_FINISHED carries the roll-up, and that its usage is then an array in AG-UI's shape, not a TokenUsage object.

Workaround: pass a usage middleware to every child ctx.chat() call and add it to the parent's total yourself.

Related: #2261 (usage not persisted for router-owned subagent runs).

  1. tanstack-source added labelsbug

  2. tanstack-sourcecommented

    Reproduced on main (0ac51d8). All three claims in the issue hold. The child token usage is lost, or sits on the wrong chunk, or never reaches onUsage.

    What I measured

    The parent makes two model calls (22 and 45 tokens). The two children make one 12-token call each. The run total is 91 tokens.

    run returnsparent onUsage totalsum of all parent RUN_FINISHEDlast RUN_FINISHED
    a ChatResult679145
    a stream679145
    a string676745
    1. run returns a string: both 12-token child calls appear on no chunk at all. valueResultChunks in spawn.ts turns the value into text chunks only, so collectUsage never runs for those calls.
    2. run returns a ChatResult or a stream: the children land on the first RUN_FINISHED as an AG-UI usage[] array. The last RUN_FINISHED carries only the parent's own 45 tokens, in the { promptTokens, ... } shape. A caller that reads the last chunk sees 45 of 91.
    3. Parent onUsage: fires twice, for 22 and 45 tokens, in every mode. It never sees a child call. The parent middleware has no hook that reports child usage, so a cost tracker on the parent under-counts by 24 tokens here.

    The docs at docs/chat/subagents.md:130 still say "The parent RUN_FINISHED.usage includes the token usage of every child." That sentence holds only for the first RUN_FINISHED and only when run returns a stream or a ChatResult.

    Suspected files

    • packages/ai/src/activities/chat/agents/spawn.ts: spawnAgentStream (line 752) calls collectUsage only on chunks of the stream that run returns (line 825). valueResultChunks (line 674) drops the usage of the bound ctx.chat calls. collectUsage (line 599) and withChildUsage (line 621) are the roll-up.
    • packages/ai/src/activities/chat/index.ts: streamWithChildUsage (line 7005) adds child usage to the first RUN_FINISHED it sees, not the final one.
    • packages/ai/src/activities/chat/middleware/types.ts: onUsage (line 1003) has no subagent form, and no onSubagentUsage exists.
    • docs/chat/subagents.md line 130 and docs/chat/subagents-advanced.md line 248: the docs do not say which RUN_FINISHED carries the roll-up, nor that its usage is an array.

    How I ran it

    The sandbox has no node_modules, and pnpm install fails here with a SQLite disk I/O error. I installed the runtime dependencies with npm in /tmp/repro and symlinked them to node_modules. The repro is a vitest file, so it runs in the repository's own test setup.

    Repro

    Path: repro/issue-2298.test.ts Command: node_modules/.bin/vitest run repro/issue-2298.test.ts --root .

    import { describe, expect, it } from 'vitest'
    import { z } from 'zod'
    import { chat, defineAgent } from '../packages/ai/src/index'
    import { fakeText } from '../packages/ai/src/testing'
    
    type Mode = 'result' | 'string' | 'stream'
    
    /** Token total of one RUN_FINISHED usage value: AG-UI array or TanStack object. */
    function totalOf(usage: unknown): number {
      if (Array.isArray(usage)) {
        return usage.reduce(
          (sum, entry) => sum + Number(entry?.totalTokens ?? 0),
          0,
        )
      }
      if (usage && typeof usage === 'object' && 'totalTokens' in usage) {
        return Number((usage as { totalTokens?: number }).totalTokens ?? 0)
      }
      return 0
    }
    
    async function scenario(mode: Mode) {
      const researcher = defineAgent({
        name: 'researcher',
        description: 'Researches one task',
        inputSchema: z.object({ label: z.string() }),
        run: async (ctx) => {
          const child = fakeText()
          child.setResponses([{ text: `Report for ${ctx.input.label}.` }])
          if (mode === 'stream') {
            return ctx.chat({ adapter: child }) as never
          }
          const result = await ctx.chat({ adapter: child, stream: false })
          return mode === 'string' ? result.text : result
        },
      })
    
      const parent = fakeText()
      parent.setResponses([
        {
          toolCalls: [1, 2].map((n) => ({
            name: 'researcher',
            input: { label: `task ${n}` },
          })),
        },
        { text: 'Done.' },
      ])
    
      const onUsage: Array<unknown> = []
      const result = await chat({
        adapter: parent,
        messages: [{ role: 'user', content: 'Research tasks 1 and 2' }],
        threadId: 'thread-1',
        subagents: { agents: [researcher] },
        middleware: [
          {
            name: 'log-usage',
            onUsage: (_ctx: unknown, usage: unknown) => void onUsage.push(usage),
          },
        ],
        stream: false,
      })
    
      const usages = result.chunks
        .filter((chunk) => chunk.type === 'RUN_FINISHED')
        .map((chunk) => (chunk as { usage?: unknown }).usage)
    
      const totals = {
        onUsage: onUsage.reduce((sum, usage) => sum + totalOf(usage), 0),
        allFinished: usages.reduce((sum, usage) => sum + totalOf(usage), 0),
        lastFinished: totalOf(usages.at(-1)),
      }
      console.log(`[${mode}] onUsage:`, JSON.stringify(onUsage))
      console.log(`[${mode}] RUN_FINISHED usage:`, JSON.stringify(usages))
      console.log(`[${mode}] totals:`, JSON.stringify(totals))
      return totals
    }
    
    // Parent model calls: 22 + 45 tokens. The two children: 12 + 12 tokens.
    const RUN_TOTAL = 91
    
    describe('issue 2298: child usage reaches the parent run', () => {
      it('run returns a string: the children are in the parent RUN_FINISHED', async () => {
        const totals = await scenario('string')
        expect(totals.allFinished).toBe(RUN_TOTAL)
      })
    
      it('run returns a ChatResult: the final RUN_FINISHED holds the roll-up', async () => {
        const totals = await scenario('result')
        expect(totals.lastFinished).toBe(RUN_TOTAL)
      })
    
      it('run returns a ChatResult: the parent onUsage sees the children', async () => {
        const totals = await scenario('result')
        expect(totals.onUsage).toBe(RUN_TOTAL)
      })
    
      it('run returns a stream: the parent onUsage sees the children', async () => {
        const totals = await scenario('stream')
        expect(totals.onUsage).toBe(RUN_TOTAL)
      })
    })

    Output (end):

    [string] totals: {"onUsage":67,"allFinished":67,"lastFinished":45}
    [result] totals: {"onUsage":67,"allFinished":91,"lastFinished":45}
    [stream] totals: {"onUsage":67,"allFinished":91,"lastFinished":45}
    
     FAIL  repro/issue-2298.test.ts > issue 2298: child usage reaches the parent run > run returns a string: the children are in the parent RUN_FINISHED
    AssertionError: expected 67 to be 91 // Object.is equality
     FAIL  repro/issue-2298.test.ts > issue 2298: child usage reaches the parent run > run returns a ChatResult: the final RUN_FINISHED holds the roll-up
    AssertionError: expected 45 to be 91 // Object.is equality
     FAIL  repro/issue-2298.test.ts > issue 2298: child usage reaches the parent run > run returns a ChatResult: the parent onUsage sees the children
    AssertionError: expected 67 to be 91 // Object.is equality
     FAIL  repro/issue-2298.test.ts > issue 2298: child usage reaches the parent run > run returns a stream: the parent onUsage sees the children
    AssertionError: expected 67 to be 91 // Object.is equality
    
     Test Files  1 failed (1)
          Tests  4 failed (4)

    TanStack Source bot, investigate agent

  3. github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author

Sign in to join this conversation.