🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(chat): show real context size instead of per-step usage sum (#17058)
YuTengjing17e50146311b
diff --git a/locales/ar/chat.json b/locales/ar/chat.jsonindex ac1b7a9ea0b..444f27909ee 100644--- a/locales/ar/chat.json+++ b/locales/ar/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "مخرج نصي","messages.tokenDetails.outputTitle": "تفاصيل المخرج","messages.tokenDetails.reasoning": "تفكير عميق",+ "messages.tokenDetails.runCumulative": "الإجمالي التراكمي (جميع الخطوات)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "الرموز في الثانية (TPS). يشير إلى متوسط سرعة المحتوى الذي يولده الذكاء الاصطناعي (رموز/ثانية)، محسوبًا من لحظة استلام أول رمز.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "تفاصيل السياق","tokenDetails.tools": "إعدادات المهارة","tokenDetails.total": "الإجمالي المتاح",+ "tokenDetails.untracked": "غير متتبع (استدعاءات الأدوات، إلخ.)","tokenDetails.used": "الإجمالي المستخدم","tokenTag.overload": "تجاوز الحد","tokenTag.remained": "المتبقي",diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.jsonindex 4e83041a5ae..327c38738b4 100644--- a/locales/bg-BG/chat.json+++ b/locales/bg-BG/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Текстов изход","messages.tokenDetails.outputTitle": "Детайли за изхода","messages.tokenDetails.reasoning": "Дълбоко мислене",+ "messages.tokenDetails.runCumulative": "Общо изпълнение (всички стъпки)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Токени в секунда (TPS). Показва средната скорост на генерирано съдържание (токени/секунда), изчислена от момента на получаване на първия токен.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Детайли за контекста","tokenDetails.tools": "Настройки на уменията","tokenDetails.total": "Общо налични",+ "tokenDetails.untracked": "Непроследено (обаждания към инструменти и др.)","tokenDetails.used": "Общо използвани","tokenTag.overload": "Превишен лимит","tokenTag.remained": "Оставащи",diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.jsonindex 4a0016a844f..551a1e70f0e 100644--- a/locales/de-DE/chat.json+++ b/locales/de-DE/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Text-Output","messages.tokenDetails.outputTitle": "Output-Details","messages.tokenDetails.reasoning": "Tiefes Denken",+ "messages.tokenDetails.runCumulative": "Gesamtlaufzeit (alle Schritte)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens pro Sekunde (TPS). Zeigt die durchschnittliche Geschwindigkeit der KI-generierten Inhalte an (Tokens/Sekunde), berechnet ab dem Empfang des ersten Tokens.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Kontextdetails","tokenDetails.tools": "Skill-Einstellungen","tokenDetails.total": "Gesamt verfügbar",+ "tokenDetails.untracked": "Nicht verfolgt (Tool-Aufrufe, etc.)","tokenDetails.used": "Insgesamt verwendet","tokenTag.overload": "Limit überschritten","tokenTag.remained": "Verbleibend",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex d7c7107381e..9140b6c40d0 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -518,6 +518,7 @@"messages.tokenDetails.outputText": "Text Output","messages.tokenDetails.outputTitle": "Output Details","messages.tokenDetails.reasoning": "Deep Thinking",+ "messages.tokenDetails.runCumulative": "Run Total (all steps)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens Per Second (TPS). This indicates the average speed of AI-generated content (Tokens/second), calculated from the moment the first Token is received.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1050,6 +1051,7 @@"tokenDetails.title": "Context Details","tokenDetails.tools": "Skill Settings","tokenDetails.total": "Total Available",+ "tokenDetails.untracked": "Untracked (tool calls, etc.)","tokenDetails.used": "Total Used","tokenTag.overload": "Exceeded Limit","tokenTag.remained": "Remaining",diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.jsonindex f365be3f3c0..5f4d5ac1393 100644--- a/locales/es-ES/chat.json+++ b/locales/es-ES/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Salida de texto","messages.tokenDetails.outputTitle": "Detalles de salida","messages.tokenDetails.reasoning": "Razonamiento profundo",+ "messages.tokenDetails.runCumulative": "Total acumulado (todos los pasos)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens por segundo (TPS). Indica la velocidad promedio del contenido generado por IA (tokens/segundo), calculado desde la recepción del primer token.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Detalles del contexto","tokenDetails.tools": "Configuración de habilidades","tokenDetails.total": "Total disponible",+ "tokenDetails.untracked": "No rastreado (llamadas a herramientas, etc.)","tokenDetails.used": "Total usado","tokenTag.overload": "Límite excedido","tokenTag.remained": "Restante",diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.jsonindex bfc296f7c47..53167807372 100644--- a/locales/fa-IR/chat.json+++ b/locales/fa-IR/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "خروجی متنی","messages.tokenDetails.outputTitle": "جزئیات خروجی","messages.tokenDetails.reasoning": "تفکر عمیق",+ "messages.tokenDetails.runCumulative": "مجموع اجرا (همه مراحل)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "توکن در ثانیه (TPS). این مقدار سرعت متوسط تولید محتوا توسط هوش مصنوعی را نشان میدهد.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "جزئیات زمینه","tokenDetails.tools": "تنظیمات مهارت","tokenDetails.total": "کل موجودی",+ "tokenDetails.untracked": "ردیابی نشده (تماسهای ابزار و غیره)","tokenDetails.used": "کل مصرفشده","tokenTag.overload": "فراتر از حد مجاز","tokenTag.remained": "باقیمانده",diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.jsonindex 18016866689..8009f5995c7 100644--- a/locales/fr-FR/chat.json+++ b/locales/fr-FR/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Texte de sortie","messages.tokenDetails.outputTitle": "Détails de la sortie","messages.tokenDetails.reasoning": "Raisonnement approfondi",+ "messages.tokenDetails.runCumulative": "Total cumulé (toutes les étapes)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens par seconde (TPS). Indique la vitesse moyenne de génération de contenu par l'IA (tokens/seconde), calculée à partir de la réception du premier token.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Détails du contexte","tokenDetails.tools": "Paramètres de compétence","tokenDetails.total": "Total disponible",+ "tokenDetails.untracked": "Non suivi (appels d'outils, etc.)","tokenDetails.used": "Total utilisé","tokenTag.overload": "Limite dépassée","tokenTag.remained": "Restant",diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.jsonindex 6781104ce60..c5156e5e430 100644--- a/locales/it-IT/chat.json+++ b/locales/it-IT/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Output testuale","messages.tokenDetails.outputTitle": "Dettagli output","messages.tokenDetails.reasoning": "Riflessione profonda",+ "messages.tokenDetails.runCumulative": "Totale Esecuzioni (tutti i passaggi)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Token al secondo (TPS). Indica la velocità media di generazione dei contenuti da parte dell'IA (Token/secondo), calcolata dal momento in cui viene ricevuto il primo token.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Dettagli contesto","tokenDetails.tools": "Impostazioni Skill","tokenDetails.total": "Totale disponibile",+ "tokenDetails.untracked": "Non tracciato (chiamate agli strumenti, ecc.)","tokenDetails.used": "Totale utilizzato","tokenTag.overload": "Limite superato","tokenTag.remained": "Rimanenti",diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.jsonindex 37895c2deda..b00b003e7b5 100644--- a/locales/ja-JP/chat.json+++ b/locales/ja-JP/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "テキスト出力","messages.tokenDetails.outputTitle": "出力詳細","messages.tokenDetails.reasoning": "深い思考",+ "messages.tokenDetails.runCumulative": "実行合計(すべてのステップ)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens Per Second(TPS):生成コンテンツの平均速度(トークン/秒)。最初のトークンを受信した後から計算を開始します","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "コンテキスト詳細","tokenDetails.tools": "スキル設定","tokenDetails.total": "総利用可能",+ "tokenDetails.untracked": "未追跡(ツール呼び出しなど)","tokenDetails.used": "使用済み","tokenTag.overload": "制限超過","tokenTag.remained": "残り",diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.jsonindex 3639ece42c8..c73aa50e840 100644--- a/locales/ko-KR/chat.json+++ b/locales/ko-KR/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "텍스트 출력","messages.tokenDetails.outputTitle": "출력 상세","messages.tokenDetails.reasoning": "심층 사고",+ "messages.tokenDetails.runCumulative": "실행 총계 (모든 단계)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens Per Second(TPS): AI가 생성한 콘텐츠의 평균 속도(토큰/초). 첫 번째 토큰을 수신한 후부터 계산을 시작합니다","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "컨텍스트 상세","tokenDetails.tools": "기능 설정","tokenDetails.total": "총 사용량",+ "tokenDetails.untracked": "추적되지 않음 (도구 호출 등)","tokenDetails.used": "사용됨","tokenTag.overload": "한도 초과","tokenTag.remained": "남음",diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.jsonindex f56687bc0e7..1d9a8343677 100644--- a/locales/nl-NL/chat.json+++ b/locales/nl-NL/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Tekstuitvoer","messages.tokenDetails.outputTitle": "Uitvoerdetails","messages.tokenDetails.reasoning": "Diep nadenken",+ "messages.tokenDetails.runCumulative": "Totaal aantal uitvoeringen (alle stappen)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens per seconde (TPS). Dit geeft de gemiddelde snelheid van AI-gegenereerde inhoud aan (tokens/seconde), berekend vanaf het moment dat het eerste token wordt ontvangen.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Contextdetails","tokenDetails.tools": "Skill-instellingen","tokenDetails.total": "Totaal beschikbaar",+ "tokenDetails.untracked": "Niet gevolgd (tooloproepen, enz.)","tokenDetails.used": "Totaal gebruikt","tokenTag.overload": "Limiet overschreden","tokenTag.remained": "Resterend",diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.jsonindex c12b07e648c..c368b61d485 100644--- a/locales/pl-PL/chat.json+++ b/locales/pl-PL/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Tekst wyjściowy","messages.tokenDetails.outputTitle": "Szczegóły wyjścia","messages.tokenDetails.reasoning": "Głębokie rozumowanie",+ "messages.tokenDetails.runCumulative": "Łączny wynik (wszystkie kroki)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokeny na sekundę (TPS). Wskazuje średnią prędkość generowania treści przez AI (tokeny/sekundę), liczoną od momentu otrzymania pierwszego tokena.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Szczegóły kontekstu","tokenDetails.tools": "Ustawienia umiejętności","tokenDetails.total": "Dostępne łącznie",+ "tokenDetails.untracked": "Nieśledzone (wywołania narzędzi itp.)","tokenDetails.used": "Łącznie użyte","tokenTag.overload": "Przekroczono limit","tokenTag.remained": "Pozostało",diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.jsonindex 4866c7f74dd..558ba6bda7b 100644--- a/locales/pt-BR/chat.json+++ b/locales/pt-BR/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Saída de Texto","messages.tokenDetails.outputTitle": "Detalhes da Saída","messages.tokenDetails.reasoning": "Raciocínio Profundo",+ "messages.tokenDetails.runCumulative": "Total de Execuções (todos os passos)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens por Segundo (TPS). Indica a velocidade média de geração de conteúdo pela IA (tokens/segundo), calculada a partir do recebimento do primeiro token.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Detalhes do Contexto","tokenDetails.tools": "Configurações de Habilidade","tokenDetails.total": "Total Disponível",+ "tokenDetails.untracked": "Não rastreado (chamadas de ferramentas, etc.)","tokenDetails.used": "Total Utilizado","tokenTag.overload": "Limite Excedido","tokenTag.remained": "Restante",diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.jsonindex a33f3502af6..f04a9a02442 100644--- a/locales/ru-RU/chat.json+++ b/locales/ru-RU/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Текстовый вывод","messages.tokenDetails.outputTitle": "Детали вывода","messages.tokenDetails.reasoning": "Глубокое мышление",+ "messages.tokenDetails.runCumulative": "Общий итог (все шаги)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Токенов в секунду (TPS). Показывает среднюю скорость генерации (токенов/секунда) с момента получения первого токена.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Детали контекста","tokenDetails.tools": "Настройки навыков","tokenDetails.total": "Всего доступно",+ "tokenDetails.untracked": "Не отслеживается (вызовы инструментов и т.д.)","tokenDetails.used": "Всего использовано","tokenTag.overload": "Превышен лимит","tokenTag.remained": "Осталось",diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.jsonindex c0ad239a973..e4581751250 100644--- a/locales/tr-TR/chat.json+++ b/locales/tr-TR/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Metin Çıkışı","messages.tokenDetails.outputTitle": "Çıkış Detayları","messages.tokenDetails.reasoning": "Derin Düşünme",+ "messages.tokenDetails.runCumulative": "Toplam Çalıştırma (tüm adımlar)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Saniye Başına Token (TPS). Bu, ilk token alındıktan sonra AI tarafından içerik üretim hızını gösterir.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Bağlam Detayları","tokenDetails.tools": "Yetenek Ayarları","tokenDetails.total": "Toplam Mevcut",+ "tokenDetails.untracked": "Takip edilmedi (araç çağrıları, vb.)","tokenDetails.used": "Toplam Kullanılan","tokenTag.overload": "Limit Aşıldı","tokenTag.remained": "Kalan",diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.jsonindex 44c96912b73..74f24a3e004 100644--- a/locales/vi-VN/chat.json+++ b/locales/vi-VN/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "Đầu ra văn bản","messages.tokenDetails.outputTitle": "Chi tiết đầu ra","messages.tokenDetails.reasoning": "Suy luận sâu",+ "messages.tokenDetails.runCumulative": "Tổng chạy (tất cả các bước)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens mỗi giây (TPS). Chỉ số này thể hiện tốc độ trung bình của nội dung do AI tạo ra (Tokens/giây), tính từ thời điểm nhận được token đầu tiên.","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "Chi tiết ngữ cảnh","tokenDetails.tools": "Cài đặt kỹ năng","tokenDetails.total": "Tổng khả dụng",+ "tokenDetails.untracked": "Không được theo dõi (gọi công cụ, v.v.)","tokenDetails.used": "Tổng đã dùng","tokenTag.overload": "Vượt giới hạn","tokenTag.remained": "Còn lại",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 0a2bc4e3015..dec13623a96 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -518,6 +518,7 @@"messages.tokenDetails.outputText": "文本输出","messages.tokenDetails.outputTitle": "输出明细","messages.tokenDetails.reasoning": "深度思考",+ "messages.tokenDetails.runCumulative": "本轮累计消耗","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "Tokens Per Second(TPS):生成内容的平均速度(Token/秒),从接收到首个 Token 后开始计算。","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1050,6 +1051,7 @@"tokenDetails.title": "上下文明细","tokenDetails.tools": "技能设定","tokenDetails.total": "总可用",+ "tokenDetails.untracked": "未统计(工具调用等)","tokenDetails.used": "已使用","tokenTag.overload": "超出限制","tokenTag.remained": "剩余",diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.jsonindex 32db2fe8113..715e75e9fee 100644--- a/locales/zh-TW/chat.json+++ b/locales/zh-TW/chat.json@@ -511,6 +511,7 @@"messages.tokenDetails.outputText": "文本輸出","messages.tokenDetails.outputTitle": "輸出明細","messages.tokenDetails.reasoning": "深度思考",+ "messages.tokenDetails.runCumulative": "運行總計(所有步驟)","messages.tokenDetails.speed.tps.title": "TPS","messages.tokenDetails.speed.tps.tooltip": "每秒令牌數,TPS。指AI生成內容的平均速度(Token/秒),在接收到首個令牌後開始計算。","messages.tokenDetails.speed.ttft.title": "TTFT",@@ -1040,6 +1041,7 @@"tokenDetails.title": "上下文詳細資訊","tokenDetails.tools": "外掛程式設定","tokenDetails.total": "總共可用",+ "tokenDetails.untracked": "未追蹤(工具調用等)","tokenDetails.used": "總計使用","tokenTag.overload": "超過限制","tokenTag.remained": "剩餘",diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/assistantGroup/assistant-with-tools.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/assistantGroup/assistant-with-tools.jsonindex b515ae001df..d689bfc7049 100644--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/assistantGroup/assistant-with-tools.json+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/assistantGroup/assistant-with-tools.json@@ -169,9 +169,9 @@"tps": 50.166666666666664},"usage": {- "totalInputTokens": 429,- "totalOutputTokens": 199,- "totalTokens": 628,+ "totalInputTokens": 245,+ "totalOutputTokens": 112,+ "totalTokens": 357,"cost": 0.0018839999999999998},"metadata": {diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/multi-assistant-group.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/multi-assistant-group.jsonindex b03c7e7d756..e4294ff26cb 100644--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/multi-assistant-group.json+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/multi-assistant-group.json@@ -136,9 +136,9 @@}],"usage": {- "totalInputTokens": 11045,- "totalOutputTokens": 770,- "totalTokens": 11815+ "totalInputTokens": 7604,+ "totalOutputTokens": 584,+ "totalTokens": 8188}}],diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/compare/with-tools.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/compare/with-tools.jsonindex fa862872b69..b2b39c3483b 100644--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/compare/with-tools.json+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/compare/with-tools.json@@ -195,9 +195,9 @@"tps": 50},"usage": {- "totalInputTokens": 180,- "totalOutputTokens": 172,- "totalTokens": 352,+ "totalInputTokens": 156,+ "totalOutputTokens": 134,+ "totalTokens": 290,"cost": 0.001056}}diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/single-task-with-tool-chain.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/single-task-with-tool-chain.jsonindex 27ebacf636f..159e154a43a 100644--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/single-task-with-tool-chain.json+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/tasks/single-task-with-tool-chain.json@@ -218,9 +218,9 @@"tps": 51.254999999999995},"usage": {- "totalInputTokens": 26063,- "totalOutputTokens": 648,- "totalTokens": 26711,+ "totalInputTokens": 13059,+ "totalOutputTokens": 74,+ "totalTokens": 13133,"cost": 0.035531}}diff --git a/packages/conversation-flow/src/__tests__/parse.test.ts b/packages/conversation-flow/src/__tests__/parse.test.tsindex 757be89e369..b15c1209eb2 100644--- a/packages/conversation-flow/src/__tests__/parse.test.ts+++ b/packages/conversation-flow/src/__tests__/parse.test.ts@@ -1100,12 +1100,12 @@ describe('parse', () => {expect(result.flatList[0]?.usage).toEqual(topLevelUsage);});- it('should aggregate per-step nested metadata.usage across an assistantGroup chain', () => {+ it('should surface the last step usage across an assistantGroup chain', () => {// Hetero-agent (Claude Code) writes per-turn usage to `metadata.usage` on- // each step assistant message. The assistantGroup virtual message must- // sum them — without this, the UI shows only one step's tokens (typically- // the last step, which gets surfaced via the lone metadata.usage that- // survived Object.assign collapse).+ // each step assistant message. The assistantGroup virtual message keeps+ // the LAST step's token snapshot (the run's context watermark) — summing+ // would count the resent context once per step (LOBE-11585). Costs are+ // still summed since billing is per-request.const step1Usage = {inputCachedTokens: 100,totalInputTokens: 200,@@ -1154,12 +1154,7 @@ describe('parse', () => {const result = parse(input as any[]);const group = result.flatList.find((m) => m.role === 'assistantGroup');- expect(group?.usage).toEqual({- inputCachedTokens: 400,- totalInputTokens: 600,- totalOutputTokens: 130,- totalTokens: 730,- });+ expect(group?.usage).toEqual(step2Usage);});});diff --git a/packages/conversation-flow/src/transformation/MessageTransformer.ts b/packages/conversation-flow/src/transformation/MessageTransformer.tsindex 12cb456e700..8ce3ac1a836 100644--- a/packages/conversation-flow/src/transformation/MessageTransformer.ts+++ b/packages/conversation-flow/src/transformation/MessageTransformer.ts@@ -97,7 +97,12 @@ export class MessageTransformer {/*** Aggregate metadata from multiple children- * - Sums token counts and costs+ * - Token fields: taken from the LAST child that reports usage. In a+ * multi-step agent run every step resends the full context, so summing+ * input-side tokens counts the same context once per step (e.g. 15 steps+ * × ~55K read as "827K" while the real context was ~75K — see LOBE-11585).+ * The final step's usage IS the context watermark of the whole run.+ * - Sums costs (billing is per-request, so the sum is the real spend)* - Takes first ttft* - Averages tps* - Sums duration and latency@@ -106,45 +111,27 @@ export class MessageTransformer {performance?: ModelPerformance;usage?: ModelUsage;} {- const usage: ModelUsage = {};+ let usage: ModelUsage = {};const performance: ModelPerformance = {};let hasUsageData = false;let hasPerformanceData = false;let tpsSum = 0;let tpsCount = 0;+ let costSum = 0;+ let hasCost = false;children.forEach((child) => {if (child.usage) {- const tokenFields = [- 'acceptedPredictionTokens',- 'inputAudioTokens',- 'inputCacheMissTokens',- 'inputCachedTokens',- 'inputCitationTokens',- 'inputImageTokens',- 'inputTextTokens',- 'inputVideoTokens',- 'inputToolTokens',- 'inputWriteCacheTokens',- 'outputAudioTokens',- 'outputImageTokens',- 'outputReasoningTokens',- 'outputTextTokens',- 'rejectedPredictionTokens',- 'totalInputTokens',- 'totalOutputTokens',- 'totalTokens',- ] as const;-- tokenFields.forEach((field) => {- if (typeof child.usage![field] === 'number') {- (usage as any)[field] = ((usage as any)[field] || 0) + child.usage![field]!;- hasUsageData = true;- }- });-- if (typeof child.usage.cost === 'number') {- usage.cost = (usage.cost || 0) + child.usage.cost;+ const { cost, ...tokens } = child.usage;++ if (Object.keys(tokens).length > 0) {+ usage = { ...tokens };+ hasUsageData = true;+ }++ if (typeof cost === 'number') {+ costSum += cost;+ hasCost = true;hasUsageData = true;}}@@ -182,6 +169,8 @@ export class MessageTransformer {performance.tps = tpsSum / tpsCount;}+ if (hasCost) usage.cost = costSum;+return {performance: hasPerformanceData ? performance : undefined,usage: hasUsageData ? usage : undefined,diff --git a/packages/conversation-flow/src/transformation/__tests__/MessageTransformer.test.ts b/packages/conversation-flow/src/transformation/__tests__/MessageTransformer.test.tsindex db2ec03e0c4..5c46bc9ddce 100644--- a/packages/conversation-flow/src/transformation/__tests__/MessageTransformer.test.ts+++ b/packages/conversation-flow/src/transformation/__tests__/MessageTransformer.test.ts@@ -125,7 +125,7 @@ describe('MessageTransformer', () => {});describe('aggregateMetadata', () => {- it('should aggregate usage and performance from multiple children', () => {+ it('should take token fields from the last child and sum costs', () => {const children: AssistantContentBlock[] = [{content: 'First',@@ -162,11 +162,13 @@ describe('MessageTransformer', () => {const result = transformer.aggregateMetadata(children);+ // Token fields come from the LAST step: each step of an agent run+ // resends the full context, so summing would count it once per step.expect(result.usage).toEqual({cost: 0.003,- totalInputTokens: 25,- totalOutputTokens: 45,- totalTokens: 70,+ totalInputTokens: 15,+ totalOutputTokens: 25,+ totalTokens: 40,});expect(result.performance).toEqual({@@ -234,7 +236,7 @@ describe('MessageTransformer', () => {expect(result.usage).toEqual({cost: 0.003,- totalTokens: 70,+ totalTokens: 40,});});diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex f6c44c12213..a82f46bad23 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -441,6 +441,7 @@ export default {'messages.tokenDetails.outputText': 'Text Output','messages.tokenDetails.outputTitle': 'Output Details','messages.tokenDetails.reasoning': 'Deep Thinking',+ 'messages.tokenDetails.runCumulative': 'Run Total (all steps)','messages.tokenDetails.speed.tps.title': 'TPS','messages.tokenDetails.speed.tps.tooltip':'Tokens Per Second (TPS). This indicates the average speed of AI-generated content (Tokens/second), calculated from the moment the first Token is received.',@@ -1157,6 +1158,7 @@ export default {'tokenDetails.title': 'Context Details','tokenDetails.tools': 'Skill Settings','tokenDetails.total': 'Total Available',+ 'tokenDetails.untracked': 'Untracked (tool calls, etc.)','tokenDetails.used': 'Total Used','tokenTag.overload': 'Exceeded Limit','tokenTag.remained': 'Remaining',diff --git a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx b/src/features/ChatInput/ActionBar/Token/TokenTag.tsxindex 09caa234ee2..d090340ad69 100644--- a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx+++ b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx@@ -150,8 +150,19 @@ const Token = memo(() => {const systemRoleToken = useTokenCount(systemRole);const historySummaryToken = useTokenCount(historySummary);- // Total token- const totalToken = systemRoleToken + historySummaryToken + toolsToken + chatsToken;+ // Local estimate — only sees plain-text content, so tool-call args/results+ // (often the bulk of an agent run) are invisible to it.+ const estimatedToken = systemRoleToken + historySummaryToken + toolsToken + chatsToken;++ // Calibrate with the real API-metered usage when available: the last+ // assistant message's totalTokens already covers system role, tools and the+ // whole history as the provider actually counted them (LOBE-11585).+ const lastMeteredTokens = contextWindowMessages?.findLast((m) => !!m.totalTokens)?.totalTokens;+ const totalToken = lastMeteredTokens ? lastMeteredTokens + inputTokenCount : estimatedToken;++ // The calibration gap, surfaced in the dev breakdown so the stacked items+ // still sum up to the displayed total.+ const untrackedToken = Math.max(0, totalToken - estimatedToken);const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);@@ -211,6 +222,12 @@ const Token = memo(() => {title: t('tokenDetails.chats'),value: chatsToken,},+ {+ color: cssVar.colorFillSecondary,+ id: 'untracked',+ title: t('tokenDetails.untracked'),+ value: untrackedToken,+ },]}/>)}diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.tsindex bc23643c7b4..1427c90be94 100644--- a/src/features/ChatInput/store/initialState.ts+++ b/src/features/ChatInput/store/initialState.ts@@ -30,6 +30,13 @@ export type SlashPlacement = 'top' | 'bottom';export interface ContextWindowMessage {content: string;+ /**+ * Real API-metered totalTokens of the request that produced this message+ * (assistant messages only). Used by TokenTag to calibrate the context-size+ * estimate — the local tokenizer only sees plain-text content, so tool-call+ * args/results are invisible to it and the estimate can be far too low (LOBE-11585).+ */+ totalTokens?: number;}export interface ChatInputFeature {diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.tsindex fc388015c34..1d3a9c7f17a 100644--- a/src/features/Conversation/ChatInput/utils.test.ts+++ b/src/features/Conversation/ChatInput/utils.test.ts@@ -83,6 +83,20 @@ describe('getContextWindowMessages', () => {}),).toEqual([]);});++ it('carries the real metered totalTokens on assistant messages only', () => {+ const messagesWithUsage = [+ { content: 'user', id: 'msg-1', role: 'user', usage: { totalTokens: 999 } },+ { content: 'assistant', id: 'msg-2', role: 'assistant', usage: { totalTokens: 46_175 } },+ { content: 'tool', id: 'msg-3', role: 'tool' },+ ] as any[];++ expect(+ getContextWindowMessages(messagesWithUsage, { enableHistoryCount: false }).map(+ (message) => message.totalTokens,+ ),+ ).toEqual([undefined, 46_175, undefined]);+ });});describe('getConversationChatInputUiState', () => {diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.tsindex 04b3677efbc..50f2997e180 100644--- a/src/features/Conversation/ChatInput/utils.ts+++ b/src/features/Conversation/ChatInput/utils.ts@@ -1,6 +1,7 @@import type { OpenAIChatMessage, UIChatMessage } from '@lobechat/types';import type { PlaceholderVariant } from '@/features/ChatInput/InputEditor/Placeholder';+import type { ContextWindowMessage } from '@/features/ChatInput/store/initialState';import { chatHelpers } from '@/store/chat/helpers';type SupportedChatInputRole = Extract<OpenAIChatMessage['role'], 'assistant' | 'tool' | 'user'>;@@ -27,7 +28,14 @@ export const getContextWindowMessages = (enableHistoryCount?: boolean;historyCount?: number;},-) => toChatInputMessages(chatHelpers.getSlicedMessages(messages, options));+): ContextWindowMessage[] =>+ chatHelpers+ .getSlicedMessages(messages, options)+ .filter(isSupportedChatInputMessage)+ .map((m) => ({+ content: typeof m.content === 'string' ? m.content : '',+ totalTokens: m.role === 'assistant' ? m.usage?.totalTokens : undefined,+ }));export interface ConversationChatInputUiState {placeholderVariant: PlaceholderVariant;diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsxindex b6ae7c45d26..8e8f71b996d 100644--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx@@ -102,6 +102,18 @@ const GroupMessage = memo<GroupMessageProps>(return children.flatMap((child: AssistantContentBlock) => child.fileList || []);}, [children]);+ // Run-level cumulative consumption: `usage` on the group carries the final+ // step's snapshot (context watermark), so the billing-side total must be+ // re-summed from the per-step blocks (LOBE-11585).+ const cumulativeTokens = useMemo(+ () =>+ children?.reduce(+ (sum: number, child: AssistantContentBlock) => sum + (child.usage?.totalTokens || 0),+ 0,+ ),+ [children],+ );+const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);const openChatSettings = useOpenChatSettings();@@ -258,7 +270,13 @@ const GroupMessage = memo<GroupMessageProps>()}{interrupted && <InterruptedHint />}{isDevMode && model && (- <Usage model={model} performance={performance} provider={provider!} usage={usage} />+ <Usage+ cumulativeTokens={cumulativeTokens}+ model={model}+ performance={performance}+ provider={provider!}+ usage={usage}+ />)}{footerRender}{reactions.length > 0 && (diff --git a/src/features/Conversation/Messages/Tasks/shared/TaskMessages.tsx b/src/features/Conversation/Messages/Tasks/shared/TaskMessages.tsxindex bd43ed5992b..4d1e6d6fa97 100644--- a/src/features/Conversation/Messages/Tasks/shared/TaskMessages.tsx+++ b/src/features/Conversation/Messages/Tasks/shared/TaskMessages.tsx@@ -17,7 +17,7 @@ import ContentBlocksScroll from '../../AssistantGroup/components/ContentBlocksScimport { resolveAssistantGroupFromMessages } from '../../AssistantGroup/utils/resolveAssistantGroupFromMessages';import Usage from '../../components/Extras/Usage';import AnimatedNumber from '../../components/Extras/Usage/UsageDetail/AnimatedNumber';-import { accumulateUsage, formatDuration, formatElapsedTime } from './utils';+import { formatDuration, formatElapsedTime, resolveRunUsage } from './utils';const styles = createStaticStyles(({ css }) => ({instructionContent: css`@@ -125,13 +125,13 @@ interface TaskMessagesProps {* Processing state - shows all blocks with loading indicator*/const ProcessingView = memo<{- accumulatedUsage: { cost?: number; totalTokens?: number };messages: UIChatMessage[];model?: string;provider?: string;+ runUsage: ReturnType<typeof resolveRunUsage>;startTime?: number;totalToolCalls: number;-}>(({ messages, startTime, model, provider, totalToolCalls, accumulatedUsage }) => {+}>(({ messages, startTime, model, provider, totalToolCalls, runUsage }) => {const { t } = useTranslation('chat');const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);const [elapsedTime, setElapsedTime] = useState(0);@@ -202,7 +202,12 @@ const ProcessingView = memo<{{/* Usage display */}{isDevMode && model && provider && (- <Usage model={model} provider={provider} usage={accumulatedUsage} />+ <Usage+ cumulativeTokens={runUsage.cumulativeTokens}+ model={model}+ provider={provider}+ usage={runUsage.usage}+ />)}</Flexbox>);@@ -219,10 +224,10 @@ const CompletedView = memo<{duration?: number;model?: string;provider?: string;+ runUsage: ReturnType<typeof resolveRunUsage>;totalCost?: number;- totalTokens?: number;totalToolCalls: number;-}>(({ blocks, assistantId, duration, totalToolCalls, model, provider, totalTokens, totalCost }) => {+}>(({ blocks, assistantId, duration, totalToolCalls, model, provider, runUsage, totalCost }) => {const { t } = useTranslation('chat');const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);@@ -291,7 +296,12 @@ const CompletedView = memo<{{/* Usage display */}{isDevMode && model && provider && (- <Usage model={model} provider={provider} usage={{ cost: totalCost, totalTokens }} />+ <Usage+ cumulativeTokens={runUsage.cumulativeTokens}+ model={model}+ provider={provider}+ usage={{ ...runUsage.usage, cost: totalCost ?? runUsage.usage?.cost }}+ />)}</Flexbox>);@@ -320,8 +330,8 @@ const TaskMessages = memo<TaskMessagesProps>([blocks],);- // Accumulate usage from all blocks- const accumulatedUsage = useMemo(() => accumulateUsage(blocks), [blocks]);+ // Resolve run usage from all blocks (last-step tokens + summed cost)+ const runUsage = useMemo(() => resolveRunUsage(blocks), [blocks]);return (<Flexbox gap={4}>@@ -333,10 +343,10 @@ const TaskMessages = memo<TaskMessagesProps>({/* Processing or Completed view */}{isProcessing ? (<ProcessingView- accumulatedUsage={accumulatedUsage}messages={messages}model={model}provider={provider}+ runUsage={runUsage}startTime={startTime}totalToolCalls={totalToolCalls}/>@@ -347,8 +357,8 @@ const TaskMessages = memo<TaskMessagesProps>(duration={duration}model={model}provider={provider}+ runUsage={runUsage}totalCost={totalCost}- totalTokens={accumulatedUsage.totalTokens}totalToolCalls={totalToolCalls}/>)}diff --git a/src/features/Conversation/Messages/Tasks/shared/utils.ts b/src/features/Conversation/Messages/Tasks/shared/utils.tsindex d629fd28f84..a3980c03d4c 100644--- a/src/features/Conversation/Messages/Tasks/shared/utils.ts+++ b/src/features/Conversation/Messages/Tasks/shared/utils.ts@@ -75,17 +75,25 @@ export const isProcessingStatus = (status?: ThreadStatus): boolean => {};/**- * Accumulate usage from all blocks+ * Resolve display usage for a multi-step run.+ *+ * Token fields come from the LAST block that reports usage — every step+ * resends the full context, so summing them counts the same context once per+ * step and massively overstates the context size (LOBE-11585). Cost and+ * `cumulativeTokens` ARE summed: billing is per-request, so those totals are real.*/-export const accumulateUsage = (blocks: AssistantContentBlock[]): ModelUsage => {- return blocks.reduce((acc, block) => {- const usage = block.usage;- if (!usage) return acc;- return {- cost: (acc.cost || 0) + (usage.cost || 0),- totalInputTokens: (acc.totalInputTokens || 0) + (usage.totalInputTokens || 0),- totalOutputTokens: (acc.totalOutputTokens || 0) + (usage.totalOutputTokens || 0),- totalTokens: (acc.totalTokens || 0) + (usage.totalTokens || 0),- };- }, {} as ModelUsage);+export const resolveRunUsage = (+ blocks: AssistantContentBlock[],+): { cumulativeTokens?: number; usage?: ModelUsage } => {+ const usages = blocks.map((block) => block.usage).filter(Boolean) as ModelUsage[];+ if (usages.length === 0) return {};++ const cost = usages.reduce((sum, usage) => sum + (usage.cost || 0), 0);+ const cumulativeTokens = usages.reduce((sum, usage) => sum + (usage.totalTokens || 0), 0);+ const last = usages.at(-1)!;++ return {+ cumulativeTokens,+ usage: cost ? { ...last, cost } : { ...last },+ };};diff --git a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsxindex d0ff9358edd..16c916fdef5 100644--- a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx+++ b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx@@ -20,250 +20,271 @@ import TokenProgress from './TokenProgress';import { getDetailsToken } from './tokens';interface TokenDetailProps {+ /**+ * Run-level cumulative token consumption (sum of every step's usage).+ * Only meaningful for multi-step runs — shown as an extra popover row so the+ * main figure can stay the context watermark (final step's totalTokens).+ */+ cumulativeTokens?: number;model: string;performance?: ModelPerformance;provider: string;usage: ModelUsage;}-const TokenDetail = memo<TokenDetailProps>(({ usage, performance, model, provider }) => {- const { t } = useTranslation('chat');+const TokenDetail = memo<TokenDetailProps>(+ ({ cumulativeTokens, usage, performance, model, provider }) => {+ const { t } = useTranslation('chat');- // Use systemStatus to manage short-format display state- const isShortFormat = useGlobalStore(systemStatusSelectors.tokenDisplayFormatShort);- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);+ // Use systemStatus to manage short-format display state+ const isShortFormat = useGlobalStore(systemStatusSelectors.tokenDisplayFormatShort);+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);- const modelCard = useAiInfraStore(aiModelSelectors.getModelCard(model, provider));- const isShowCredit = useGlobalStore(systemStatusSelectors.isShowCredit) && !!modelCard?.pricing;+ const modelCard = useAiInfraStore(aiModelSelectors.getModelCard(model, provider));+ const isShowCredit = useGlobalStore(systemStatusSelectors.isShowCredit) && !!modelCard?.pricing;- const detailTokens = getDetailsToken(usage, modelCard);- const inputDetails = [- !!detailTokens.inputAudio && {- color: cssVar.cyan9,- id: 'reasoning',- title: t('messages.tokenDetails.inputAudio'),- value: isShowCredit ? detailTokens.inputAudio.credit : detailTokens.inputAudio.token,- },- !!detailTokens.inputCitation && {- color: cssVar.orange,- id: 'inputText',- title: t('messages.tokenDetails.inputCitation'),- value: isShowCredit ? detailTokens.inputCitation.credit : detailTokens.inputCitation.token,- },- !!detailTokens.inputText && {- color: cssVar.green,- id: 'inputText',- title: t('messages.tokenDetails.inputText'),- value: isShowCredit ? detailTokens.inputText.credit : detailTokens.inputText.token,- },- ].filter(Boolean) as TokenProgressItem[];+ const detailTokens = getDetailsToken(usage, modelCard);+ const inputDetails = [+ !!detailTokens.inputAudio && {+ color: cssVar.cyan9,+ id: 'reasoning',+ title: t('messages.tokenDetails.inputAudio'),+ value: isShowCredit ? detailTokens.inputAudio.credit : detailTokens.inputAudio.token,+ },+ !!detailTokens.inputCitation && {+ color: cssVar.orange,+ id: 'inputText',+ title: t('messages.tokenDetails.inputCitation'),+ value: isShowCredit ? detailTokens.inputCitation.credit : detailTokens.inputCitation.token,+ },+ !!detailTokens.inputText && {+ color: cssVar.green,+ id: 'inputText',+ title: t('messages.tokenDetails.inputText'),+ value: isShowCredit ? detailTokens.inputText.credit : detailTokens.inputText.token,+ },+ ].filter(Boolean) as TokenProgressItem[];- const outputDetails = [- !!detailTokens.outputReasoning && {- color: cssVar.pink,- id: 'reasoning',- title: t('messages.tokenDetails.reasoning'),- value: isShowCredit- ? detailTokens.outputReasoning.credit- : detailTokens.outputReasoning.token,- },- !!detailTokens.outputImage && {- color: cssVar.purple,- id: 'outputImage',- title: t('messages.tokenDetails.outputImage'),- value: isShowCredit ? detailTokens.outputImage.credit : detailTokens.outputImage.token,- },- !!detailTokens.outputAudio && {- color: cssVar.cyan9,- id: 'outputAudio',- title: t('messages.tokenDetails.outputAudio'),- value: isShowCredit ? detailTokens.outputAudio.credit : detailTokens.outputAudio.token,- },- !!detailTokens.outputText && {- color: cssVar.green,- id: 'outputText',- title: t('messages.tokenDetails.outputText'),- value: isShowCredit ? detailTokens.outputText.credit : detailTokens.outputText.token,- },- ].filter(Boolean) as TokenProgressItem[];+ const outputDetails = [+ !!detailTokens.outputReasoning && {+ color: cssVar.pink,+ id: 'reasoning',+ title: t('messages.tokenDetails.reasoning'),+ value: isShowCredit+ ? detailTokens.outputReasoning.credit+ : detailTokens.outputReasoning.token,+ },+ !!detailTokens.outputImage && {+ color: cssVar.purple,+ id: 'outputImage',+ title: t('messages.tokenDetails.outputImage'),+ value: isShowCredit ? detailTokens.outputImage.credit : detailTokens.outputImage.token,+ },+ !!detailTokens.outputAudio && {+ color: cssVar.cyan9,+ id: 'outputAudio',+ title: t('messages.tokenDetails.outputAudio'),+ value: isShowCredit ? detailTokens.outputAudio.credit : detailTokens.outputAudio.token,+ },+ !!detailTokens.outputText && {+ color: cssVar.green,+ id: 'outputText',+ title: t('messages.tokenDetails.outputText'),+ value: isShowCredit ? detailTokens.outputText.credit : detailTokens.outputText.token,+ },+ ].filter(Boolean) as TokenProgressItem[];- const totalDetail = [- !!detailTokens.inputCacheMiss && {- color: cssVar.colorFill,+ const totalDetail = [+ !!detailTokens.inputCacheMiss && {+ color: cssVar.colorFill,- id: 'uncachedInput',- title: t('messages.tokenDetails.inputUncached'),- value: isShowCredit ? detailTokens.inputCacheMiss.credit : detailTokens.inputCacheMiss.token,- },- !!detailTokens.inputCached && {- color: cssVar.orange,- id: 'inputCached',- title: t('messages.tokenDetails.inputCached'),- value: isShowCredit ? detailTokens.inputCached.credit : detailTokens.inputCached.token,- },- !!detailTokens.inputCachedWrite && {- color: cssVar.yellow,- id: 'cachedWriteInput',- title: t('messages.tokenDetails.inputWriteCached'),- value: isShowCredit- ? detailTokens.inputCachedWrite.credit- : detailTokens.inputCachedWrite.token,- },- !!detailTokens.inputTool && {- color: cssVar.geekblue,- id: 'inputTool',- title: t('messages.tokenDetails.inputTool'),- value: isShowCredit ? detailTokens.inputTool.credit : detailTokens.inputTool.token,- },- !!detailTokens.totalOutput && {- color: cssVar.colorSuccess,- id: 'output',- title: t('messages.tokenDetails.output'),- value: isShowCredit ? detailTokens.totalOutput.credit : detailTokens.totalOutput.token,- },- ].filter(Boolean) as TokenProgressItem[];+ id: 'uncachedInput',+ title: t('messages.tokenDetails.inputUncached'),+ value: isShowCredit+ ? detailTokens.inputCacheMiss.credit+ : detailTokens.inputCacheMiss.token,+ },+ !!detailTokens.inputCached && {+ color: cssVar.orange,+ id: 'inputCached',+ title: t('messages.tokenDetails.inputCached'),+ value: isShowCredit ? detailTokens.inputCached.credit : detailTokens.inputCached.token,+ },+ !!detailTokens.inputCachedWrite && {+ color: cssVar.yellow,+ id: 'cachedWriteInput',+ title: t('messages.tokenDetails.inputWriteCached'),+ value: isShowCredit+ ? detailTokens.inputCachedWrite.credit+ : detailTokens.inputCachedWrite.token,+ },+ !!detailTokens.inputTool && {+ color: cssVar.geekblue,+ id: 'inputTool',+ title: t('messages.tokenDetails.inputTool'),+ value: isShowCredit ? detailTokens.inputTool.credit : detailTokens.inputTool.token,+ },+ !!detailTokens.totalOutput && {+ color: cssVar.colorSuccess,+ id: 'output',+ title: t('messages.tokenDetails.output'),+ value: isShowCredit ? detailTokens.totalOutput.credit : detailTokens.totalOutput.token,+ },+ ].filter(Boolean) as TokenProgressItem[];- const totalCount =- isShowCredit && !!detailTokens.totalTokens- ? detailTokens.totalTokens.credit- : detailTokens.totalTokens!.token;+ const totalCount =+ isShowCredit && !!detailTokens.totalTokens+ ? detailTokens.totalTokens.credit+ : detailTokens.totalTokens!.token;- const detailTotal = formatUsageValue(totalCount);- const cacheRate =- typeof detailTokens.inputCacheRate === 'number'- ? `${formatNumber(detailTokens.inputCacheRate * 100, 1)}%`- : undefined;+ const detailTotal = formatUsageValue(totalCount);+ const cacheRate =+ typeof detailTokens.inputCacheRate === 'number'+ ? `${formatNumber(detailTokens.inputCacheRate * 100, 1)}%`+ : undefined;- const averagePricing = formatNumber(- detailTokens.totalTokens!.credit / detailTokens.totalTokens!.token,- 2,- );+ const averagePricing = formatNumber(+ detailTokens.totalTokens!.credit / detailTokens.totalTokens!.token,+ 2,+ );- const tps = performance?.tps ? formatNumber(performance.tps, 2) : undefined;- const ttft = performance?.ttft ? formatNumber(performance.ttft / 1000, 2) : undefined;+ const tps = performance?.tps ? formatNumber(performance.tps, 2) : undefined;+ const ttft = performance?.ttft ? formatNumber(performance.ttft / 1000, 2) : undefined;- return (- <Popover- placement={'top'}- trigger="hover"- content={- <Flexbox gap={8} style={{ minWidth: 200 }}>- {modelCard && <ModelCard {...modelCard} provider={provider} />}+ return (+ <Popover+ placement={'top'}+ trigger="hover"+ content={+ <Flexbox gap={8} style={{ minWidth: 200 }}>+ {modelCard && <ModelCard {...modelCard} provider={provider} />}- <Flexbox gap={20}>- {inputDetails.length > 1 && (- <Flexbox gap={4}>- <Flexbox- horizontal- align={'center'}- gap={4}- justify={'space-between'}- width={'100%'}- >- <div style={{ color: cssVar.colorTextDescription, fontSize: 12 }}>- {t('messages.tokenDetails.inputTitle')}- </div>- </Flexbox>- <TokenProgress showIcon data={inputDetails} />- </Flexbox>- )}- {outputDetails.length > 1 && (- <Flexbox gap={4}>- <Flexbox- horizontal- align={'center'}- gap={4}- justify={'space-between'}- width={'100%'}- >- <div style={{ color: cssVar.colorTextDescription, fontSize: 12 }}>- {t('messages.tokenDetails.outputTitle')}- </div>+ <Flexbox gap={20}>+ {inputDetails.length > 1 && (+ <Flexbox gap={4}>+ <Flexbox+ horizontal+ align={'center'}+ gap={4}+ justify={'space-between'}+ width={'100%'}+ >+ <div style={{ color: cssVar.colorTextDescription, fontSize: 12 }}>+ {t('messages.tokenDetails.inputTitle')}+ </div>+ </Flexbox>+ <TokenProgress showIcon data={inputDetails} /></Flexbox>- <TokenProgress showIcon data={outputDetails} />- </Flexbox>- )}- <Flexbox>- <TokenProgress showIcon data={totalDetail} />- <Divider style={{ marginBlock: 8 }} />- {cacheRate && (- <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>- <div style={{ color: cssVar.colorTextSecondary }}>- {t('messages.tokenDetails.cacheRate')}- </div>- <div style={{ fontWeight: 500 }}>{cacheRate}</div>+ )}+ {outputDetails.length > 1 && (+ <Flexbox gap={4}>+ <Flexbox+ horizontal+ align={'center'}+ gap={4}+ justify={'space-between'}+ width={'100%'}+ >+ <div style={{ color: cssVar.colorTextDescription, fontSize: 12 }}>+ {t('messages.tokenDetails.outputTitle')}+ </div>+ </Flexbox>+ <TokenProgress showIcon data={outputDetails} /></Flexbox>)}- <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>- <div style={{ color: cssVar.colorTextSecondary }}>- {t('messages.tokenDetails.total')}- </div>- <div style={{ fontWeight: 500 }}>{detailTotal}</div>- </Flexbox>- {isShowCredit && (+ <Flexbox>+ <TokenProgress showIcon data={totalDetail} />+ <Divider style={{ marginBlock: 8 }} />+ {cacheRate && (+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>+ <div style={{ color: cssVar.colorTextSecondary }}>+ {t('messages.tokenDetails.cacheRate')}+ </div>+ <div style={{ fontWeight: 500 }}>{cacheRate}</div>+ </Flexbox>+ )}<Flexbox horizontal align={'center'} gap={4} justify={'space-between'}><div style={{ color: cssVar.colorTextSecondary }}>- {t('messages.tokenDetails.average')}+ {t('messages.tokenDetails.total')}</div>- <div style={{ fontWeight: 500 }}>{averagePricing}</div>+ <div style={{ fontWeight: 500 }}>{detailTotal}</div></Flexbox>- )}- {tps && (- <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>- <Flexbox horizontal gap={8}>+ {/* Multi-step runs resend the context every step, so the cumulative+ figure can be far larger than the context watermark shown above —+ surface it separately to avoid reading it as context size (LOBE-11585) */}+ {!!cumulativeTokens && cumulativeTokens > (usage.totalTokens || 0) && (+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}><div style={{ color: cssVar.colorTextSecondary }}>- {t('messages.tokenDetails.speed.tps.title')}+ {t('messages.tokenDetails.runCumulative')}</div>- <InfoTooltip title={t('messages.tokenDetails.speed.tps.tooltip')} />+ <div style={{ fontWeight: 500 }}>{formatUsageValue(cumulativeTokens)}</div></Flexbox>- <div style={{ fontWeight: 500 }}>{tps}</div>- </Flexbox>- )}- {ttft && (- <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>- <Flexbox horizontal gap={8}>+ )}+ {isShowCredit && (+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}><div style={{ color: cssVar.colorTextSecondary }}>- {t('messages.tokenDetails.speed.ttft.title')}+ {t('messages.tokenDetails.average')}</div>- <InfoTooltip title={t('messages.tokenDetails.speed.ttft.tooltip')} />+ <div style={{ fontWeight: 500 }}>{averagePricing}</div></Flexbox>- <div style={{ fontWeight: 500 }}>{ttft}s</div>- </Flexbox>- )}+ )}+ {tps && (+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>+ <Flexbox horizontal gap={8}>+ <div style={{ color: cssVar.colorTextSecondary }}>+ {t('messages.tokenDetails.speed.tps.title')}+ </div>+ <InfoTooltip title={t('messages.tokenDetails.speed.tps.tooltip')} />+ </Flexbox>+ <div style={{ fontWeight: 500 }}>{tps}</div>+ </Flexbox>+ )}+ {ttft && (+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>+ <Flexbox horizontal gap={8}>+ <div style={{ color: cssVar.colorTextSecondary }}>+ {t('messages.tokenDetails.speed.ttft.title')}+ </div>+ <InfoTooltip title={t('messages.tokenDetails.speed.ttft.tooltip')} />+ </Flexbox>+ <div style={{ fontWeight: 500 }}>{ttft}s</div>+ </Flexbox>+ )}+ </Flexbox></Flexbox></Flexbox>- </Flexbox>- }- >- <Center- horizontal- gap={2}- style={{ cursor: 'pointer' }}- onClick={(e) => {- // Prevent Popover from closing and toggle the format- e.preventDefault();- e.stopPropagation();- updateSystemStatus({ tokenDisplayFormatShort: !isShortFormat });- }}+ }>- <Icon icon={isShowCredit ? BadgeCent : CoinsIcon} />- <AnimatedNumber- duration={1500}- // Force remount when switching between token/credit to prevent unwanted animation- // See: https://github.com/lobehub/lobe-chat/pull/10098- key={isShowCredit ? 'credit' : 'token'}- value={totalCount}- formatter={(value) => {- const roundedValue = Math.round(value);- if (isShortFormat) {- return (formatShortenNumber(roundedValue) as string).toLowerCase?.();- }- return new Intl.NumberFormat('en-US').format(roundedValue);+ <Center+ horizontal+ gap={2}+ style={{ cursor: 'pointer' }}+ onClick={(e) => {+ // Prevent Popover from closing and toggle the format+ e.preventDefault();+ e.stopPropagation();+ updateSystemStatus({ tokenDisplayFormatShort: !isShortFormat });}}- />- </Center>- </Popover>- );-});+ >+ <Icon icon={isShowCredit ? BadgeCent : CoinsIcon} />+ <AnimatedNumber+ duration={1500}+ // Force remount when switching between token/credit to prevent unwanted animation+ // See: https://github.com/lobehub/lobe-chat/pull/10098+ key={isShowCredit ? 'credit' : 'token'}+ value={totalCount}+ formatter={(value) => {+ const roundedValue = Math.round(value);+ if (isShortFormat) {+ return (formatShortenNumber(roundedValue) as string).toLowerCase?.();+ }+ return new Intl.NumberFormat('en-US').format(roundedValue);+ }}+ />+ </Center>+ </Popover>+ );+ },+);export default TokenDetail;diff --git a/src/features/Conversation/Messages/components/Extras/Usage/index.tsx b/src/features/Conversation/Messages/components/Extras/Usage/index.tsxindex f6ef4f1748c..8014c33a4c5 100644--- a/src/features/Conversation/Messages/components/Extras/Usage/index.tsx+++ b/src/features/Conversation/Messages/components/Extras/Usage/index.tsx@@ -34,13 +34,19 @@ const MIN_DISPLAY_COST = 0.2;const formatCost = (cost: number) => cost.toFixed(2);interface UsageProps {+ /**+ * Total tokens consumed across ALL steps of the run (each step resends the+ * full context, so this is a billing-side figure — NOT the context size).+ * `usage` itself carries the final step's snapshot, i.e. the context watermark.+ */+ cumulativeTokens?: number;model: string;performance?: ModelPerformance;provider: string;usage?: ModelUsage;}-const Usage = memo<UsageProps>(({ model, usage, performance, provider }) => {+const Usage = memo<UsageProps>(({ cumulativeTokens, model, usage, performance, provider }) => {const onboardingAgentId = useAgentStore(builtinAgentSelectors.webOnboardingAgentId);const conversationAgentId = useConversationStore(contextSelectors.agentId);// Credit mode already expresses cost in credits — showing USD alongside would conflict.@@ -78,6 +84,7 @@ const Usage = memo<UsageProps>(({ model, usage, performance, provider }) => {<Center horizontal gap={8}>{!!usage?.totalTokens && (<TokenDetail+ cumulativeTokens={cumulativeTokens}model={model as string}performance={performance}provider={provider}