@@ -1459,6 +1459,24 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
14591459 } ) ;
14601460 }
14611461
1462+ {
1463+ agentCommandMock . mockClear ( ) ;
1464+ agentCommandMock . mockResolvedValueOnce ( {
1465+ payloads : [ { text : "usage last call" } ] ,
1466+ meta : {
1467+ agentMeta : {
1468+ lastCallUsage : { input : 80 , output : 20 , total : 100 } ,
1469+ } ,
1470+ } ,
1471+ } as never ) ;
1472+ const json = await postSyncUserMessage ( "usage" ) ;
1473+ expect ( json . usage ) . toEqual ( {
1474+ prompt_tokens : 80 ,
1475+ completion_tokens : 20 ,
1476+ total_tokens : 100 ,
1477+ } ) ;
1478+ }
1479+
14621480 {
14631481 agentCommandMock . mockClear ( ) ;
14641482 agentCommandMock . mockResolvedValueOnce ( {
@@ -3164,7 +3182,29 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
31643182 expect ( allContent ) . toBe ( "final answer" ) ;
31653183 } ) ;
31663184
3167- it ( "includes usage in final stream chunk when stream_options.include_usage=true" , async ( ) => {
3185+ it . each ( [
3186+ {
3187+ name : "includes aggregate usage in the final stream chunk" ,
3188+ usage : { input : 12 , output : 5 , cacheRead : 3 , cacheWrite : 0 , total : 20 } ,
3189+ lastCallUsage : undefined ,
3190+ expected : {
3191+ prompt_tokens : 15 ,
3192+ completion_tokens : 5 ,
3193+ total_tokens : 20 ,
3194+ prompt_tokens_details : { cached_tokens : 3 } ,
3195+ } ,
3196+ } ,
3197+ {
3198+ name : "uses last-call usage when the aggregate is zero" ,
3199+ usage : { input : 0 , output : 0 , total : 0 } ,
3200+ lastCallUsage : { input : 55 , output : 7 , total : 62 } ,
3201+ expected : {
3202+ prompt_tokens : 55 ,
3203+ completion_tokens : 7 ,
3204+ total_tokens : 62 ,
3205+ } ,
3206+ } ,
3207+ ] ) ( "$name" , async ( { usage, lastCallUsage, expected } ) => {
31683208 const port = enabledPort ;
31693209 agentCommandMock . mockClear ( ) ;
31703210 agentCommandMock . mockImplementationOnce ( ( async ( opts : unknown ) => {
@@ -3175,13 +3215,8 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
31753215 payloads : [ { text : "hello" } ] ,
31763216 meta : {
31773217 agentMeta : {
3178- usage : {
3179- input : 12 ,
3180- output : 5 ,
3181- cacheRead : 3 ,
3182- cacheWrite : 0 ,
3183- total : 20 ,
3184- } ,
3218+ usage,
3219+ ...( lastCallUsage ? { lastCallUsage } : { } ) ,
31853220 } ,
31863221 } ,
31873222 } ;
@@ -3203,12 +3238,7 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
32033238 . map ( ( d ) => JSON . parse ( d ) as Record < string , unknown > ) ;
32043239
32053240 const usageChunk = jsonChunks . find ( ( chunk ) => "usage" in chunk ) ;
3206- expect ( usageChunk ?. usage ) . toEqual ( {
3207- prompt_tokens : 15 ,
3208- completion_tokens : 5 ,
3209- total_tokens : 20 ,
3210- prompt_tokens_details : { cached_tokens : 3 } ,
3211- } ) ;
3241+ expect ( usageChunk ?. usage ) . toEqual ( expected ) ;
32123242 expect ( usageChunk ?. choices ) . toStrictEqual ( [ ] ) ;
32133243 } ) ;
32143244
0 commit comments