Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: live tool feedback + graceful CLI cancel

Haozhe Wua1e83aded725
diff --git a/README.md b/README.md
index 9fae8d4a8..3722cae14 100644
--- a/README.md
+++ b/README.md
@@ -46,13 +46,13 @@
## 📰 News
+- **2026-05-19** ✨ **Live tool feedback + graceful cancel**: Long-running tools (backtests, large PDFs, swarm workers) no longer look frozen. Each tool call now emits a 3-second heartbeat plus structured per-stage progress — `run_backtest` shows phase markers (`validate` / `simulate` / `finalize`), `read_document` ticks per page on PDF or per sheet on Excel, `read_url` marks `fetch` / `parse`. The CLI Rich Live dashboard renders a Unicode spinner, ASCII progress bar, ETA, and stacks up to 3 parallel tools keyed by name; the frontend chat ships a new `ToolProgressIndicator` with rAF-coalesced renders, ARIA `role="status"` + hidden native `<progress>` for screen readers, and a determinate `ProgressRing` SVG when total is known. First `Ctrl+C` during a CLI run now calls `agent.cancel()` for graceful exit (current step finishes, trace closes cleanly); a second within 2s force-quits. Reusable primitives extracted along the way: `ProgressBar.tsx` and `lib/tools.ts` (shared tool-name i18n).
- **2026-05-18** 🧹 **Cleanup pass + three latent bug fixes**: `CompositeEngine` no longer misroutes bare Chinese-futures codes like `RB2410` to `GlobalFuturesEngine` — `_is_china_futures` moved into a shared `_market_hooks` module with a case-normalized product table and a non-CN exchange guard, plus 9 new regression cases. Session FTS5 indexes now persist timestamps so cross-session search can sort by date; the same path also fixed a re-upsert that was wall-clocking every session's `started_at`. The Vite dev-mode proxy gained the missing `/alpha` entry so the AlphaZoo page resolves on `npm run dev`. `tests/test_e2e_harness_v2.py` (real-LLM e2e suite) is now gated behind `VIBE_TRADING_RUN_LIVE_E2E=1` so CI no longer changes shape based on env-key presence. Ruff `per-file-ignores` added for the factor zoo (3783 → 0 F401 noise), frontend tsconfig enables `noUnusedLocals` / `noUnusedParameters` as regression guards, and 76 unused `vw = vwap(...)` boilerplate lines were dropped from `gtja191` alphas. Net **-918 LOC**.
- **2026-05-17** 🧬 **Alpha Zoo v1 (0.1.8)**: 452 pre-built quant alphas across 4 zoos — `qlib158` (Microsoft Qlib, Apache-2 attribution), `alpha101` (Kakushadze 101 Formulaic Alphas, paper rewrite from arXiv:1601.00991), `gtja191` (Guotai Junan 2014 short-horizon factor report), and `academic` (Fama-French 5 + Carhart price-based proxies). One-line CLI to bench any zoo on your universe: `vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`. Ships with AST purity gate, lookahead-guard test, `pytest-socket` network kill-switch, per-zoo LICENSE.md, and a Developer Certificate of Origin (DCO) workflow for community PRs. Auto-rendered Alpha Library at [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/) + research-lab post [Which of the 191 GTJA alphas still work in 2026?](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html).
-- **2026-05-16** 🧪 **Research spine update**: Added a backend Hypothesis Registry with `create_hypothesis`, `update_hypothesis`, `link_backtest`, and `search_hypotheses`; external-content readers now attach warning-only `security_warnings`; and Shadow Account scanning now uses deterministic OHLCV feature evaluation instead of the old calendar-phase stub.
-
<details>
<summary>Earlier news</summary>
+- **2026-05-16** 🧪 **Research spine update**: Added a backend Hypothesis Registry with `create_hypothesis`, `update_hypothesis`, `link_backtest`, and `search_hypotheses`; external-content readers now attach warning-only `security_warnings`; and Shadow Account scanning now uses deterministic OHLCV feature evaluation instead of the old calendar-phase stub.
- **2026-05-15** 🪪 The run detail page now surfaces the Trust Layer run card alongside metrics and artifacts, completing the UI side of the `run_card.json` work landed on 2026-05-12. `PersistentMemory.add()` was also hardened on length, empty/whitespace-only names, and C0/C1 control bytes from the #108/#109/#110 triage ([#112](https://github.com/HKUDS/Vibe-Trading/pull/112), thanks @Teerapat-Vatpitak).
- **2026-05-14** 🌐 the public wiki is now live at [vibetrading.wiki](https://vibetrading.wiki/) with docs, tutorials, Research Lab, and Alpha Library sections deployed through Cloudflare Pages. Persistent memory is also inspectable from the CLI via `vibe-trading memory list/show/search/forget` ([#102](https://github.com/HKUDS/Vibe-Trading/pull/102), thanks @Teerapat-Vatpitak), and memory tokenization/slugs now support Thai, Arabic, Hebrew, and Cyrillic text ([#104](https://github.com/HKUDS/Vibe-Trading/pull/104)).
- **2026-05-13** 🧭 Swarm runs now ground workers with fetched market data and cleaner persisted reports ([#93](https://github.com/HKUDS/Vibe-Trading/pull/93), [#84](https://github.com/HKUDS/Vibe-Trading/pull/84)).
diff --git a/README_ar.md b/README_ar.md
index 73cf134d1..493ebd67c 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -46,13 +46,13 @@
## 📰 الأخبار
+- **2026-05-19** ✨ **تغذية راجعة حيّة للأدوات + إلغاء سلس**: لم تعد الأدوات الطويلة (backtests، PDF كبيرة، عمّال swarm) تبدو متجمدة. كل استدعاء أداة يُصدر الآن نبضة قلب كل 3 ثوانٍ، بالإضافة إلى تقدّم مرحلي مهيكل — يُظهر `run_backtest` علامات الأطوار (`validate` / `simulate` / `finalize`)، ويُحدّث `read_document` عدّاد كل صفحة على PDF أو كل ورقة على Excel، ويُعلِم `read_url` بمرحلتي `fetch` / `parse`. تعرض لوحة Rich Live في CLI دوّاراً Unicode وشريط تقدّم ASCII وETA، وتُكدّس حتى 3 أدوات متوازية مفهرسة بالاسم. تضيف الواجهة الأمامية مكوّن `ToolProgressIndicator` جديد مع تجميع rAF، وARIA `role="status"` + `<progress>` أصلي مخفي لقارئات الشاشة، وSVG `ProgressRing` حتمي عندما يكون المجموع معروفاً. أول `Ctrl+C` أثناء تشغيل CLI يستدعي الآن `agent.cancel()` للخروج السلس (تكتمل الخطوة الحالية وتُغلق التتبعات بنظافة)، والثاني خلال ثانيتين يفرض الإنهاء. تم استخراج عناصر أساسية قابلة لإعادة الاستخدام: `ProgressBar.tsx` و`lib/tools.ts` (تعيين i18n لأسماء الأدوات المشترك).
- **2026-05-18** 🧹 **تنظيف + إصلاح 3 أخطاء كامنة**: لم يعد `CompositeEngine` يوجّه رموز العقود الآجلة الصينية بدون لاحقة (مثل `RB2410`) إلى `GlobalFuturesEngine` بشكل خاطئ — انتقل `_is_china_futures` إلى وحدة `_market_hooks` المشتركة مع تطبيع حالة جدول المنتجات + حارس لبورصة غير صينية، وأُضيفت 9 حالات اختبار انحدار. تحفظ فهارس FTS5 للجلسات الآن الطوابع الزمنية، فيمكن لبحث الجلسات الفرز بالتاريخ، ونفس التغيير أصلح مسار إعادة الإدراج الذي كان يستبدل `started_at` بساعة الحائط في كل مرة. أُضيف `/alpha` المفقود إلى بروكسي تطوير Vite، فتُحلّ صفحة AlphaZoo الآن على `npm run dev`. تم تقييد `tests/test_e2e_harness_v2.py` (مجموعة e2e بـ LLM حقيقي) خلف `VIBE_TRADING_RUN_LIVE_E2E=1` كي لا تغيّر CI شكلها بناءً على وجود مفتاح البيئة. أُضيفت إلى ruff قاعدة `per-file-ignores` لمكتبة المعاملات (الضوضاء F401 من 3783 إلى 0)، وفُعِّلت `noUnusedLocals` / `noUnusedParameters` في tsconfig الواجهة كحواجز انحدار، وحُذف 76 سطراً من نموذج `vw = vwap(...)` غير المستخدم في ملفات `gtja191`. الصافي **-918 سطراً**.
- **2026-05-17** 🧬 **Alpha Zoo v1 (0.1.8)**: 452 ألفا كمّي جاهز عبر 4 zoos — `qlib158` (ميزات Alpha158 من Microsoft Qlib، إسناد Apache-2.0)، `alpha101` (إعادة تنفيذ "101 Formulaic Alphas" من Kakushadze بناءً على ورقة arXiv:1601.00991)، `gtja191` (تقرير بحث Guotai Junan 2014 لعوامل تداول قصيرة الأجل)، `academic` (Fama-French 5 + Carhart momentum كـ proxy قائم على الأسعار). سطر أوامر واحد للـ bench على أي universe: `vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`. تتضمن بوابة AST للنقاء، اختبار حماية lookahead، عزل الشبكة عبر `pytest-socket`، LICENSE.md لكل zoo، وسير عمل توقيع DCO لمساهمات المجتمع. تقديم Alpha Library تلقائياً على [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/)، مع منشور Research Lab [Which of the 191 GTJA alphas still work in 2026?](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html).
-- **2026-05-16** 🧪 **تحديث عمود البحث**: أضيف backend Hypothesis Registry مع `create_hypothesis` و`update_hypothesis` و`link_backtest` و`search_hypotheses`. تضيف قارئات المحتوى الخارجي الآن `security_warnings` تحذيرية فقط، وانتقل ماسح Shadow Account من calendar-phase stub القديم إلى تقييم حتمي لميزات OHLCV.
-
<details>
<summary>أخبار سابقة</summary>
+- **2026-05-16** 🧪 **تحديث عمود البحث**: أضيف backend Hypothesis Registry مع `create_hypothesis` و`update_hypothesis` و`link_backtest` و`search_hypotheses`. تضيف قارئات المحتوى الخارجي الآن `security_warnings` تحذيرية فقط، وانتقل ماسح Shadow Account من calendar-phase stub القديم إلى تقييم حتمي لميزات OHLCV.
- **2026-05-15** 🪪 تعرض صفحة تفاصيل الـ run الآن بطاقة Trust Layer run card إلى جانب المقاييس والمخرجات، لتكمل الجانب الواجهي من عمل `run_card.json` الذي هبط في 2026-05-12. كما تم تعزيز `PersistentMemory.add()` على مسارات الطول والأسماء الفارغة أو التي تحتوي على فراغات فقط وبايتات التحكم C0/C1 ضمن فرز #108/#109/#110 ([#112](https://github.com/HKUDS/Vibe-Trading/pull/112)، شكراً @Teerapat-Vatpitak).
- **2026-05-14** 🌐 أصبح الويكي العام متاحاً على [vibetrading.wiki](https://vibetrading.wiki/) مع أقسام docs وtutorials وResearch Lab وAlpha Library، ويُنشر عبر Cloudflare Pages. أصبحت الذاكرة الدائمة أيضاً قابلة للفحص من سطر الأوامر عبر `vibe-trading memory list/show/search/forget` ([#102](https://github.com/HKUDS/Vibe-Trading/pull/102)، شكراً @Teerapat-Vatpitak)، كما يدعم توليد الرموز وslugs للذاكرة الآن التايلاندية والعربية والعبرية والنص السيريلي ([#104](https://github.com/HKUDS/Vibe-Trading/pull/104)).
diff --git a/README_ja.md b/README_ja.md
index 03b400542..ed02b6d6b 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -46,13 +46,13 @@
## 📰 ニュース
+- **2026-05-19** ✨ **ツールのライブフィードバック + グレースフルキャンセル**: 長時間実行されるツール(バックテスト、大きい PDF、swarm worker)が固まったように見えなくなりました。各ツール呼び出しは 3 秒ごとのハートビートに加え、構造化された段階進捗を発行します — `run_backtest` はフェーズマーカー(`validate` / `simulate` / `finalize`)、`read_document` は PDF ではページ単位、Excel ではシート単位、`read_url` は `fetch` / `parse` をマーク。CLI の Rich Live ダッシュボードは Unicode スピナー、ASCII プログレスバー、ETA を描画し、ツール名でキー付けして最大 3 つの並列ツールをスタック表示します。フロントエンドのチャットには新規 `ToolProgressIndicator` を追加し、rAF コアレッシング、ARIA `role="status"` + スクリーンリーダー向けの非表示 `<progress>`、合計が既知の場合は determinate な `ProgressRing` SVG を備えます。CLI 実行中の最初の `Ctrl+C` は `agent.cancel()` を呼んでグレースフル終了(現在のステップが完了し、trace がクリーンに閉じる)し、2 秒以内に 2 度目を押すと強制終了します。再利用可能なプリミティブ `ProgressBar.tsx` と `lib/tools.ts`(共有ツール名 i18n マッピング)も抽出。
- **2026-05-18** 🧹 **クリーンアップ + 3 つの潜在バグ修正**: `CompositeEngine` が取引所サフィックスのない中国先物コード(`RB2410` 等)を `GlobalFuturesEngine` に誤ルーティングしていた問題を修正。`_is_china_futures` を共有の `_market_hooks` モジュールに移し、製品コード表を大小文字正規化 + 非中国取引所のガードを追加、回帰ケース 9 件を新設しました。session FTS5 インデックスがタイムスタンプを永続化するようになり、クロスセッション検索を日付ソートできるようになりました。同じ修正で、re-upsert 経路が `started_at` を wall-clock で上書きしていた副次バグも解消しました。Vite 開発プロキシに `/alpha` を追加し、AlphaZoo ページが `npm run dev` で解決されるようになりました。`tests/test_e2e_harness_v2.py`(実 LLM の e2e スイート)は `VIBE_TRADING_RUN_LIVE_E2E=1` でゲート化し、CI が環境変数の有無で形を変えないようにしました。ruff に factor zoo 用の `per-file-ignores` を追加(F401 ノイズ 3783 → 0)、フロントエンド tsconfig は `noUnusedLocals` / `noUnusedParameters` を有効化して回帰ガードとし、`gtja191` alpha の未使用 `vw = vwap(...)` 雛形 76 件も削除しました。正味 **-918 行**。
- **2026-05-17** 🧬 **Alpha Zoo v1(0.1.8)**: 4 つの zoo にまたがる 452 個の事前構築 quant alpha を同梱しました — `qlib158`(Microsoft Qlib の Alpha158 特徴量、Apache-2.0 出処明示)、`alpha101`(Kakushadze の "101 Formulaic Alphas" を arXiv:1601.00991 から論文ベースで書き直し)、`gtja191`(国泰君安 2014 年の短期取引型 alpha レポート)、`academic`(Fama-French 5 + Carhart 動量の価格ベース proxy 実装)。任意の universe で 1 行 CLI: `vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`。AST 純関数ゲート、look-ahead ガードテスト、`pytest-socket` ネットワーク遮断、各 zoo ごとの LICENSE.md、コミュニティ PR 用の DCO 署名フローも同梱。Alpha Library 自動レンダリングは [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/)、Research Lab には [Which of the 191 GTJA alphas still work in 2026?](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html) を公開。
-- **2026-05-16** 🧪 **リサーチ基盤アップデート**: backend Hypothesis Registry を追加し、`create_hypothesis`、`update_hypothesis`、`link_backtest`、`search_hypotheses` を提供します。外部コンテンツ reader は warning-only の `security_warnings` を付与し、Shadow Account scanner は旧 calendar-phase stub から決定的な OHLCV feature evaluation に移行しました。
-
<details>
<summary>過去のニュース</summary>
+- **2026-05-16** 🧪 **リサーチ基盤アップデート**: backend Hypothesis Registry を追加し、`create_hypothesis`、`update_hypothesis`、`link_backtest`、`search_hypotheses` を提供します。外部コンテンツ reader は warning-only の `security_warnings` を付与し、Shadow Account scanner は旧 calendar-phase stub から決定的な OHLCV feature evaluation に移行しました。
- **2026-05-15** 🪪 Run 詳細ページが metrics と artifacts の隣に Trust Layer の run card を描画するようになり、2026-05-12 に入った `run_card.json` 側の UI 半分が揃いました。`PersistentMemory.add()` も #108/#109/#110 の triage を受け、長さ、空・空白だけの name、C0/C1 制御バイトの各経路で強化されました([#112](https://github.com/HKUDS/Vibe-Trading/pull/112)、@Teerapat-Vatpitak に感謝)。
- **2026-05-14** 🌐 公開 Wiki が [vibetrading.wiki](https://vibetrading.wiki/) で公開され、docs、tutorials、Research Lab、Alpha Library セクションを Cloudflare Pages から配信します。永続メモリも CLI から `vibe-trading memory list/show/search/forget` で確認できるようになり([#102](https://github.com/HKUDS/Vibe-Trading/pull/102)、@Teerapat-Vatpitak に感謝)、メモリの tokenization/slug はタイ語、アラビア語、ヘブライ語、キリル文字にも対応しました([#104](https://github.com/HKUDS/Vibe-Trading/pull/104))。
diff --git a/README_ko.md b/README_ko.md
index 5429895b0..8d49d6d8b 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -46,13 +46,13 @@
## 📰 뉴스
+- **2026-05-19** ✨ **도구 라이브 피드백 + 우아한 취소**: 오래 걸리는 도구(백테스트, 큰 PDF, swarm worker)가 멈춘 것처럼 보이지 않게 되었습니다. 모든 도구 호출은 이제 3초 간격의 하트비트와 구조화된 단계별 진행 상황을 발행합니다 — `run_backtest`는 단계 마커(`validate` / `simulate` / `finalize`), `read_document`는 PDF에서는 페이지 단위, Excel에서는 시트 단위, `read_url`은 `fetch` / `parse`를 표시합니다. CLI의 Rich Live 대시보드는 유니코드 스피너, ASCII 진행 표시줄, ETA를 렌더링하고 도구 이름으로 키된 최대 3개의 병렬 도구를 스택 표시합니다. 프런트엔드 채팅에는 새로운 `ToolProgressIndicator`를 추가했으며, rAF 코얼레싱, ARIA `role="status"` + 스크린 리더용 숨겨진 네이티브 `<progress>`, 총량을 알 때 결정적 `ProgressRing` SVG로 전환합니다. CLI 실행 중 첫 번째 `Ctrl+C`는 이제 `agent.cancel()`을 호출해 우아하게 종료(현재 단계가 끝나고 trace가 깨끗하게 닫힘)하고, 2초 이내 두 번째는 강제 종료합니다. 재사용 가능한 기본 요소도 추출했습니다: `ProgressBar.tsx`와 `lib/tools.ts`(공유 도구 이름 i18n).
- **2026-05-18** 🧹 **정리 + 3개의 잠재 버그 수정**: `CompositeEngine`이 거래소 접미사가 없는 중국 선물 코드(`RB2410` 등)를 `GlobalFuturesEngine`으로 잘못 라우팅하던 문제를 수정했습니다. `_is_china_futures`를 공유 `_market_hooks` 모듈로 옮기고, 상품 코드 테이블에 대소문자 정규화 + 비중국 거래소 가드를 추가했으며, 회귀 케이스 9개를 새로 작성했습니다. session FTS5 인덱스가 타임스탬프를 영구 저장하게 되어 크로스 세션 검색에서 날짜 정렬이 가능해졌으며, 동일 변경으로 re-upsert 경로가 `started_at`을 wall-clock으로 덮어쓰던 부수 버그도 해결했습니다. Vite 개발 프록시에 누락되었던 `/alpha`를 추가하여 AlphaZoo 페이지가 `npm run dev`에서 정상 해석됩니다. `tests/test_e2e_harness_v2.py`(실 LLM e2e 스위트)는 `VIBE_TRADING_RUN_LIVE_E2E=1`로 게이트하여 CI가 환경변수 유무에 따라 형태를 바꾸지 않도록 했습니다. ruff에 factor zoo용 `per-file-ignores`를 추가(F401 잡음 3783 → 0)하고, 프런트엔드 tsconfig에 `noUnusedLocals` / `noUnusedParameters`를 활성화해 회귀 가드로 두었으며, `gtja191` alpha 파일들의 사용되지 않는 `vw = vwap(...)` 보일러플레이트 76개도 삭제했습니다. 순 **-918줄**.
- **2026-05-17** 🧬 **Alpha Zoo v1 (0.1.8)**: 4개 zoo에 걸친 452개의 사전 빌드된 quant alpha를 번들로 제공 — `qlib158`(Microsoft Qlib의 Alpha158 특성, Apache-2.0 출처 표기), `alpha101`(Kakushadze의 "101 Formulaic Alphas"를 arXiv:1601.00991 논문 부록에서 재구현), `gtja191`(국태군안 2014 단기 거래형 alpha 리서치 보고서), `academic`(Fama-French 5 + Carhart 모멘텀의 가격 기반 proxy 구현). 한 줄 CLI로 임의 universe에서 벤치: `vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`. AST 순수 함수 게이트, look-ahead 가드 테스트, `pytest-socket` 네트워크 차단, zoo별 LICENSE.md, 커뮤니티 PR용 DCO 서명 워크플로우 포함. Alpha Library 자동 렌더링: [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/), Research Lab 글: [Which of the 191 GTJA alphas still work in 2026?](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html).
-- **2026-05-16** 🧪 **리서치 기반 업데이트**: backend Hypothesis Registry를 추가해 `create_hypothesis`, `update_hypothesis`, `link_backtest`, `search_hypotheses`를 제공합니다. 외부 콘텐츠 reader는 warning-only `security_warnings`를 붙이고, Shadow Account scanner는 기존 calendar-phase stub 대신 deterministic OHLCV feature evaluation을 사용합니다.
-
<details>
<summary>이전 뉴스</summary>
+- **2026-05-16** 🧪 **리서치 기반 업데이트**: backend Hypothesis Registry를 추가해 `create_hypothesis`, `update_hypothesis`, `link_backtest`, `search_hypotheses`를 제공합니다. 외부 콘텐츠 reader는 warning-only `security_warnings`를 붙이고, Shadow Account scanner는 기존 calendar-phase stub 대신 deterministic OHLCV feature evaluation을 사용합니다.
- **2026-05-15** 🪪 Run 상세 페이지에서 metrics와 artifacts 옆에 Trust Layer run card를 렌더링해, 2026-05-12에 들어간 `run_card.json` 작업의 UI 측을 마무리합니다. `PersistentMemory.add()`도 #108/#109/#110 triage에 따라 길이, 빈 문자열 또는 공백만으로 이루어진 name, C0/C1 제어 바이트 경로에서 강화되었습니다([#112](https://github.com/HKUDS/Vibe-Trading/pull/112), @Teerapat-Vatpitak 감사합니다).
- **2026-05-14** 🌐 공개 Wiki가 [vibetrading.wiki](https://vibetrading.wiki/)에 열렸고, docs, tutorials, Research Lab, Alpha Library 섹션을 Cloudflare Pages로 배포합니다. 영구 메모리도 이제 `vibe-trading memory list/show/search/forget`으로 CLI에서 확인할 수 있으며([#102](https://github.com/HKUDS/Vibe-Trading/pull/102), @Teerapat-Vatpitak 감사합니다), memory tokenization/slug는 태국어, 아랍어, 히브리어, 키릴 문자도 지원합니다([#104](https://github.com/HKUDS/Vibe-Trading/pull/104)).
diff --git a/README_zh.md b/README_zh.md
index 071587aab..d6eac1cd3 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -46,13 +46,13 @@
## 📰 News
+- **2026-05-19** ✨ **工具实时反馈 + 优雅取消**:长时间运行的工具(回测、大 PDF、swarm worker)不再看起来卡死。每个工具调用现在会发出 3 秒一次的心跳,以及结构化的阶段进度 —— `run_backtest` 输出阶段标记(`validate` / `simulate` / `finalize`),`read_document` 在 PDF 上按页打点 / Excel 上按工作表打点,`read_url` 标记 `fetch` / `parse`。CLI 的 Rich Live 面板渲染 Unicode 转轮、ASCII 进度条、ETA,按工具名最多堆叠 3 个并行工具;前端 chat 新增 `ToolProgressIndicator`,rAF 合并刷新、ARIA `role="status"` + 隐藏的原生 `<progress>` 供屏幕阅读器使用,已知总数时切换为 determinate 的 `ProgressRing` SVG。CLI 中第一次 `Ctrl+C` 现在会调 `agent.cancel()` 优雅退出(当前步骤跑完、trace 干净关闭);2 秒内第二次 `Ctrl+C` 强制退出。顺手抽出可复用基础件:`ProgressBar.tsx` 和 `lib/tools.ts`(共享工具名 i18n 映射)。
- **2026-05-18** 🧹 **清理一次 + 3 个潜伏 bug 修复**:`CompositeEngine` 不再把无交易所后缀的中国期货代码(如 `RB2410`)错误路由到 `GlobalFuturesEngine` —— `_is_china_futures` 移到共享的 `_market_hooks` 模块,产品代码表做了大小写归一并加入非中国交易所守卫,新增 9 条回归用例。session FTS5 索引现在会持久化时间戳,跨 session 搜索可按日期排序;同一改动也修复了 re-upsert 路径每次都用 wall-clock 覆盖 `started_at` 的副作用 bug。前端 Vite dev proxy 补上漏配的 `/alpha`,AlphaZoo 页在 `npm run dev` 下不再 404。`tests/test_e2e_harness_v2.py`(真 LLM 的 e2e 套件)现在用 `VIBE_TRADING_RUN_LIVE_E2E=1` 做环境门控,CI 不再因为有无 LLM key 而静默切状态。Ruff 为 factor zoo 添加 `per-file-ignores`(3783 → 0 F401 噪音),前端 tsconfig 打开 `noUnusedLocals` / `noUnusedParameters` 做回归护栏,并删掉了 76 个 `gtja191` alpha 文件里没用上的 `vw = vwap(...)` 残留。净 **-918 行**。
- **2026-05-17** 🧬 **Alpha Zoo v1(0.1.8)**:内置 452 个量化 alpha,覆盖 4 个 zoo —— `qlib158`(Microsoft Qlib 的 Alpha158 特征,Apache-2.0 出处声明)、`alpha101`(Kakushadze 的 "101 Formulaic Alphas",从 arXiv:1601.00991 论文公式重写)、`gtja191`(国君证券 2014 短周期交易型因子研报)、`academic`(Fama-French 5 因子 + Carhart 动量的价格代理实现)。一行 CLI 就能在自己的 universe 上跑横评:`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`。配套设施包括 AST 纯函数门禁、lookahead 防护测试、`pytest-socket` 网络隔离、每个 zoo 一份 LICENSE.md、社区贡献用的 DCO 签名流程;Alpha Library 自动渲染上线 [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/);Research Lab 同步发布 [《191 个 GTJA alpha 哪些在 2026 还能用》](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html)。
-- **2026-05-16** 🧪 **研究主干更新**:新增后端 Hypothesis Registry,提供 `create_hypothesis`、`update_hypothesis`、`link_backtest`、`search_hypotheses`;外部内容读取工具现在会附加 warning-only 的 `security_warnings`;Shadow Account 扫描也从旧的日历 phase stub 升级为确定性的 OHLCV 特征评估。
-
<details>
<summary>更早的更新</summary>
+- **2026-05-16** 🧪 **研究主干更新**:新增后端 Hypothesis Registry,提供 `create_hypothesis`、`update_hypothesis`、`link_backtest`、`search_hypotheses`;外部内容读取工具现在会附加 warning-only 的 `security_warnings`;Shadow Account 扫描也从旧的日历 phase stub 升级为确定性的 OHLCV 特征评估。
- **2026-05-15** 🪪 Run 详情页现在会在 metrics 和 artifacts 旁边渲染 Trust Layer 的 run card,把 2026-05-12 已落地的 `run_card.json` 工作补齐到 UI 一侧。`PersistentMemory.add()` 也根据 #108/#109/#110 的 triage,在长度限制、空 / 纯空白 name、以及 C0/C1 控制字节三条路径上做了加固([#112](https://github.com/HKUDS/Vibe-Trading/pull/112),感谢 @Teerapat-Vatpitak)。
- **2026-05-14** 🌐 公开 Wiki 已上线 [vibetrading.wiki](https://vibetrading.wiki/),包含 docs、tutorials、Research Lab 和 Alpha Library,并通过 Cloudflare Pages 部署。持久记忆也可以通过 CLI 使用 `vibe-trading memory list/show/search/forget` 检查([#102](https://github.com/HKUDS/Vibe-Trading/pull/102),感谢 @Teerapat-Vatpitak);记忆 tokenizer/slug 现在支持泰语、阿拉伯语、希伯来语和西里尔文字([#104](https://github.com/HKUDS/Vibe-Trading/pull/104))。
- **2026-05-13** 🧭 Swarm 运行现在会用已获取的市场数据为 worker 提供依据,并生成更清晰的持久化报告([#93](https://github.com/HKUDS/Vibe-Trading/pull/93),[#84](https://github.com/HKUDS/Vibe-Trading/pull/84))。
diff --git a/agent/cli.py b/agent/cli.py
index e82a59d3d..b78457db6 100644
--- a/agent/cli.py
+++ b/agent/cli.py
@@ -453,6 +453,9 @@ def _metric_value_style(key: str, value: str) -> str:
return "white"
+_SPINNER_GLYPHS = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
+
+
class _RunDashboard:
"""Render a compact live view for a single agent run."""
@@ -467,12 +470,37 @@ class _RunDashboard:
self.timeline: list[tuple[str, str, str, float, str]] = []
self.status = "running"
self.live: Optional[Live] = None
+ # Per-tool live feedback keyed by tool name. Supports parallel
+ # readonly batches (loop._execute_parallel runs up to 8 tools in
+ # ThreadPoolExecutor and each gets its own HeartbeatTimer). Each
+ # entry: {start_ts, elapsed_s, stage, current, total, message,
+ # prev_stage, stage_started_at}.
+ self.tool_active: dict[str, dict[str, Any]] = {}
+ self._spinner_idx = 0
+ self._last_progress_render: float = 0.0
def refresh(self) -> None:
"""Refresh the live display when attached to a Rich Live context."""
if self.live is not None:
self.live.update(self.render())
+ def _ensure_entry(self, tool: str) -> dict[str, Any]:
+ """Return the active per-tool entry, creating it on first use."""
+ entry = self.tool_active.get(tool)
+ if entry is None:
+ entry = {
+ "start_ts": time.monotonic(),
+ "elapsed_s": 0.0,
+ "stage": "",
+ "current": None,
+ "total": None,
+ "message": "",
+ "prev_stage": None,
+ "stage_started_at": time.monotonic(),
+ }
+ self.tool_active[tool] = entry
+ return entry
+
def handle_event(self, event_type: str, data: Dict[str, Any]) -> None:
"""Update the dashboard from AgentLoop UI events."""
if event_type == "text_delta":
@@ -494,24 +522,91 @@ class _RunDashboard:
self.iterations += 1
self.current_tool = tool or "tool"
self.current_args = _strip_rich_tags(_format_tool_call_args(tool, args)).strip()
+ # If the prior timeline row is still "running" with no active
+ # entry in self.tool_active (i.e. its HeartbeatTimer is gone but
+ # no tool_result arrived), downgrade it to a warning (H2). Skip
+ # this when a parallel batch is still in flight — sibling tools
+ # legitimately remain "running" while a new call lands.
+ if self.timeline and self.timeline[-1][0] == "running":
+ prev_status, prev_tool, prev_args, _prev_el, _prev_pre = self.timeline[-1]
+ if prev_tool not in self.tool_active:
+ self.timeline[-1] = (
+ "warning",
+ prev_tool,
+ prev_args,
+ 0.0,
+ "no result event",
+ )
+ # Reset per-tool state on each call (handles repeat invocations).
+ now = time.monotonic()
+ self.tool_active[self.current_tool] = {
+ "start_ts": now,
+ "elapsed_s": 0.0,
+ "stage": "",
+ "current": None,
+ "total": None,
+ "message": "",
+ "prev_stage": None,
+ "stage_started_at": now,
+ }
self.timeline.append(("running", self.current_tool, self.current_args, 0.0, ""))
self.timeline = self.timeline[-8:]
self.refresh()
return
+ if event_type == "tool_heartbeat":
+ # Keepalive while a long tool runs. Updates elapsed in-place.
+ tool = data.get("tool") or self.current_tool
+ entry = self._ensure_entry(tool)
+ entry["elapsed_s"] = float(data.get("elapsed_s", 0) or 0)
+ self.refresh()
+ return
+
+ if event_type == "tool_progress":
+ # Structured stage/current/total emitted from the tool.
+ tool = data.get("tool") or self.current_tool
+ entry = self._ensure_entry(tool)
+ stage = str(data.get("stage", "") or "")
+ if stage and stage != entry.get("stage"):
+ entry["prev_stage"] = entry.get("stage") or None
+ entry["stage_started_at"] = time.monotonic()
+ entry["stage"] = stage
+ entry["current"] = data.get("current")
+ entry["total"] = data.get("total")
+ entry["message"] = str(data.get("message", "") or "")
+ elapsed = data.get("elapsed_s")
+ if elapsed is not None:
+ entry["elapsed_s"] = float(elapsed)
+ # Throttle redraws so a chatty tool can't peg the renderer (M1).
+ now = time.monotonic()
+ if now - self._last_progress_render >= 0.25:
+ self._last_progress_render = now
+ self.refresh()
+ return
+
if event_type == "tool_result":
tool = data.get("tool", self.current_tool)
status = data.get("status", "ok")
elapsed_s = float(data.get("elapsed_ms", 0) or 0) / 1000
preview = _strip_rich_tags(_format_tool_result_preview(tool, status, data.get("preview", "")))
row_status = "success" if status == "ok" else "failed"
- if self.timeline and self.timeline[-1][0] == "running":
- self.timeline[-1] = (row_status, tool, self.timeline[-1][2], elapsed_s, preview)
- else:
+ # Find the matching running row for this tool (may not be the last
+ # row when tools run in parallel).
+ matched = False
+ for idx in range(len(self.timeline) - 1, -1, -1):
+ row = self.timeline[idx]
+ if row[0] == "running" and row[1] == tool:
+ self.timeline[idx] = (row_status, tool, row[2], elapsed_s, preview)
+ matched = True
+ break
+ if not matched:
self.timeline.append((row_status, tool, "", elapsed_s, preview))
self.timeline = self.timeline[-8:]
- self.current_tool = "thinking"
- self.current_args = ""
+ # Drop the per-tool entry so it disappears from the active list.
+ self.tool_active.pop(tool, None)
+ if not self.tool_active:
+ self.current_tool = "thinking"
+ self.current_args = ""
self.refresh()
return
@@ -521,6 +616,82 @@ class _RunDashboard:
self.timeline = self.timeline[-8:]
self.refresh()
+ def _render_progress_row(
+ self,
+ tool: str,
+ entry: Dict[str, Any],
+ spinner: str,
+ bar_width: int,
+ compact: bool,
+ detail_width: int,
+ ) -> str:
+ """Render a single active-tool progress row for the Current grid."""
+ stage = str(entry.get("stage") or "")
+ current_val = entry.get("current")
+ total_val = entry.get("total")
+ message = str(entry.get("message") or "")
+ elapsed_s = float(entry.get("elapsed_s") or 0.0)
+ has_count = (
+ isinstance(current_val, int)
+ and isinstance(total_val, int)
+ and total_val > 0
+ )
+ has_structured = bool(stage or has_count or message)
+ if not has_structured and elapsed_s <= 0:
+ return ""
+ if not has_structured:
+ # Heartbeat-only fallback. No bar, no decimal precision (L4).
+ plain = f"{spinner} {tool} · still running… {elapsed_s:.0f}s elapsed"
+ return f"[dim]{_clip_inline(plain, detail_width)}[/dim]"
+ # Build a plain prefix + dim suffix so markup survives clipping.
+ prefix_plain_parts: list[str] = [spinner]
+ prefix_styled_parts: list[str] = [f"[cyan]{spinner}[/cyan]"]
+ if stage:
+ prefix_plain_parts.append(stage)
+ prefix_styled_parts.append(f"[bold cyan]{stage}[/bold cyan]")
+ if has_count:
+ filled = max(0, min(bar_width, int(bar_width * current_val / total_val)))
+ bar = "#" * filled + "-" * (bar_width - filled)
+ prefix_plain_parts.append(f"[{bar}]")
+ prefix_styled_parts.append(f"[cyan]\\[{bar}][/cyan]")
+ count_str = f"{current_val}/{total_val}"
+ prefix_plain_parts.append(count_str)
+ prefix_styled_parts.append(f"[cyan]{count_str}[/cyan]")
+ else:
+ prefix_plain_parts.append(f"{elapsed_s:.1f}s")
+ prefix_styled_parts.append(f"[cyan]{elapsed_s:.1f}s[/cyan]")
+ prefix_plain = " ".join(prefix_plain_parts)
+ prefix_styled = " ".join(prefix_styled_parts)
+ suffix_plain_parts: list[str] = []
+ if message:
+ suffix_plain_parts.append(f"· {message}")
+ # ETA: only when count is known, we're past ~10% and at least 3 units,
+ # and the stage hasn't just changed (L1). Suppressed in compact mode.
+ if has_count and not compact and current_val >= 3 and current_val >= total_val * 0.1:
+ stage_started_at = entry.get("stage_started_at")
+ prev_stage = entry.get("prev_stage")
+ stable_stage = (
+ prev_stage is None
+ or (
+ stage_started_at is not None
+ and (time.monotonic() - float(stage_started_at)) >= 1.0
+ )
+ )
+ if stable_stage and elapsed_s > 0:
+ try:
+ eta = (elapsed_s / current_val) * (total_val - current_val)
+ except ZeroDivisionError:
+ eta = 0.0
+ if eta > 0 and eta == eta: # NaN check
+ suffix_plain_parts.append(f"· ~{eta:.0f}s left")
+ suffix_plain = " ".join(suffix_plain_parts)
+ # Clip the dim suffix to whatever space is left after the prefix.
+ remaining = max(0, detail_width - len(prefix_plain) - 1)
+ if suffix_plain and remaining > 4:
+ clipped_suffix = _clip_inline(suffix_plain, remaining)
+ return f"{prefix_styled} [dim]{clipped_suffix}[/dim]"
+ return prefix_styled
+
def render(self) -> Panel:
"""Build the Rich renderable shown while the run is active."""
term_width = _terminal_width()
@@ -552,6 +723,27 @@ class _RunDashboard:
if self.current_args:
tool_label = f"{tool_label} [dim]{_clip_inline(self.current_args, max(20, content_width - 18))}[/dim]"
current.add_row("Current", f"[cyan]{tool_label}[/cyan]")
+ # One row per active tool (caps at 3 to keep dashboard height bounded).
+ # Snapshot via list(...) first: Rich's refresh thread calls render()
+ # concurrently with heartbeat/worker threads mutating self.tool_active,
+ # so a bare ``.items()`` would race and may raise "dictionary changed
+ # size during iteration". list() materialization is GIL-atomic.
+ active_entries = sorted(
+ list(self.tool_active.items()), key=lambda kv: kv[1].get("start_ts", 0.0)
+ )
+ if len(active_entries) > 3:
+ active_entries = active_entries[:3]
+ # Advance the spinner once per render so all active rows step together.
+ self._spinner_idx = (self._spinner_idx + 1) % len(_SPINNER_GLYPHS)
+ spinner = _SPINNER_GLYPHS[self._spinner_idx]
+ bar_width = 6 if compact else 8
+ detail_width = max(20, content_width - 18)
+ for tool, entry in active_entries:
+ row_text = self._render_progress_row(
+ tool, entry, spinner, bar_width, compact, detail_width
+ )
+ if row_text:
+ current.add_row("Progress", row_text)
timeline = Table(
box=box.SIMPLE,
@@ -660,6 +852,14 @@ def _run_agent(
from src.providers.chat import ChatLLM
from src.agent.loop import AgentLoop
+ # Closure-level state for the no-rich path so dots and progress lines
+ # don't shoulder-bump each other (M3) and progress prints are throttled
+ # to ≤1/0.5s per tool (M1).
+ no_rich_state: dict[str, Any] = {
+ "dot_pending": False,
+ "last_progress_ts": {}, # type: ignore[var-annotated]
+ }
+
def on_event(event_type: str, data: Dict[str, Any]) -> None:
if not stream_output:
return
@@ -674,6 +874,7 @@ def _run_agent(
args = data.get("arguments", {})
args_preview = _format_tool_call_args(tool, args)
print(f" - {tool}{_strip_rich_tags(args_preview)}", end="")
+ no_rich_state["dot_pending"] = False
return
if no_rich and event_type == "tool_result":
tool = data.get("tool", "")
@@ -683,12 +884,49 @@ def _run_agent(
preview = _format_tool_result_preview(tool, status, data.get("preview", ""))
suffix = f" {preview}" if preview else ""
mark = "OK" if status == "ok" else "FAIL"
+ # If a heartbeat dot is open on the line, break it cleanly.
+ if no_rich_state["dot_pending"]:
+ no_rich_state["dot_pending"] = False
print(f" {mark} {elapsed_s:.1f}s{_strip_rich_tags(suffix)}")
+ no_rich_state["last_progress_ts"].pop(tool, None)
return
if no_rich and event_type == "compact":
tokens = data.get("tokens_before", "?")
+ if no_rich_state["dot_pending"]:
+ no_rich_state["dot_pending"] = False
+ print()
print(f"\n context compressed ({tokens} tokens -> summary)\n")
return
+ if no_rich and event_type == "tool_heartbeat":
+ # Print a dot per tick so the user sees the tool is alive.
+ print(".", end="", flush=True)
+ no_rich_state["dot_pending"] = True
+ return
+ if no_rich and event_type == "tool_progress":
+ tool = data.get("tool", "") or ""
+ now = time.monotonic()
+ last_ts = no_rich_state["last_progress_ts"].get(tool, 0.0)
+ if now - last_ts < 0.5:
+ # Throttle: max one progress line per 0.5s per tool (M1).
+ return
+ no_rich_state["last_progress_ts"][tool] = now
+ stage = data.get("stage", "")
+ current_idx = data.get("current")
+ total = data.get("total")
+ message = data.get("message", "")
+ bits = [stage]
+ if isinstance(current_idx, int) and isinstance(total, int) and total > 0:
+ bits.append(f"{current_idx}/{total}")
+ if message:
+ bits.append(message)
+ label = " · ".join(b for b in bits if b)
+ if label:
+ # Break a pending dot line before printing the progress detail.
+ if no_rich_state["dot_pending"]:
+ no_rich_state["dot_pending"] = False
+ print()
+ print(f" {label}", flush=True)
+ return
if event_type == "text_delta":
if no_rich:
print(data.get("delta", ""), end="")
@@ -743,7 +981,71 @@ def _run_agent(
if run_dir_override:
agent.memory.run_dir = run_dir_override
- return agent.run(user_message=prompt, history=history)
+ return _run_with_graceful_cancel(agent, prompt, history, no_rich=no_rich)
+
+
+def _run_with_graceful_cancel(
+ agent: "AgentLoop",
+ prompt: str,
+ history: Optional[List[Dict]],
+ *,
+ no_rich: bool,
+) -> dict:
+ """Run an agent loop with first-Ctrl+C = graceful cancel.
+
+ First SIGINT during the run sets ``agent._cancelled`` so the loop exits
+ cleanly after the current LLM/tool step finishes. A second SIGINT within
+ two seconds restores the default handler and re-raises ``KeyboardInterrupt``
+ for hard quit. Outside of a run the parent CLI's normal SIGINT handling
+ (exit on input prompt) is unaffected — the handler is restored in
+ ``finally``.
+
+ Args:
+ agent: AgentLoop instance ready to ``run()``.
+ prompt: User prompt.
+ history: Recent message history.
+ no_rich: Whether the parent caller is rendering with Rich Live.
+
+ Returns:
+ AgentLoop result dict.
+ """
+ import signal as _signal
+
+ state = {"requested": False, "last_ts": 0.0}
+ try:
+ original = _signal.getsignal(_signal.SIGINT)
+ except (ValueError, AttributeError):
+ # Not on a thread that can receive signals — skip the handler swap.
+ return agent.run(user_message=prompt, history=history)
+
+ def _on_sigint(_signum, _frame) -> None:
+ now = time.time()
+ if state["requested"] and (now - state["last_ts"]) < 2.0:
+ # Second Ctrl+C within 2s — hand control back to the default handler.
+ _signal.signal(_signal.SIGINT, original)
+ raise KeyboardInterrupt
+ state["requested"] = True
+ state["last_ts"] = now
+ agent.cancel()
+ notice = "Cancelling… current step will finish, then exit. Ctrl+C again to force quit."
+ if no_rich:
+ print(f"\n[{notice}]", flush=True)
+ else:
+ console.print(f"\n[yellow]{notice}[/yellow]")
+
+ try:
+ _signal.signal(_signal.SIGINT, _on_sigint)
+ except (ValueError, OSError):
+ # signal.signal only works on the main thread of the main interpreter.
+ return agent.run(user_message=prompt, history=history)
+
+ try:
+ return agent.run(user_message=prompt, history=history)
+ finally:
+ try:
+ _signal.signal(_signal.SIGINT, original)
+ except (ValueError, OSError):
+ pass
def _build_benchmark_table(m: dict) -> Optional[Table]:
@@ -1216,6 +1518,7 @@ def _print_help() -> None:
("/swarm cancel <run_id>", "Cancel a team run"),
("/sessions", "List chat sessions"),
("/settings", "Show provider, model, timeout, and credentials"),
+ ("/stop", "How to gracefully cancel a running agent"),
("/clear", "Clear the terminal"),
("/quit", "Exit"),
("", ""),
@@ -1328,6 +1631,12 @@ def _handle_slash_command(input_str: str, *, max_iter: int) -> None:
cmd_sessions()
elif cmd == "/settings":
_show_settings()
+ elif cmd == "/stop":
+ console.print(
+ "[dim]No agent is running. Press [bold]Ctrl+C[/bold] during a run "
+ "to gracefully cancel — the current step finishes, then the loop "
+ "exits cleanly. Press Ctrl+C twice within 2 seconds to force quit.[/dim]"
+ )
elif cmd == "/clear":
console.clear()
_print_welcome()
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index b4a9b3dab..e1191eb88 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -23,6 +23,7 @@ from typing import Any, Callable, Dict, List, Optional
from src.agent.context import ContextBuilder
from src.agent.memory import WorkspaceMemory
+from src.agent.progress import HeartbeatTimer, ProgressEvent, _set_emitter
from src.agent.tools import ToolRegistry
from src.agent.trace import TraceWriter
from src.core.state import RunStateStore
@@ -33,6 +34,7 @@ RUNS_DIR = Path(__file__).resolve().parents[2] / "runs"
TOKEN_THRESHOLD = int(os.getenv("TOKEN_THRESHOLD", "40000"))
KEEP_RECENT = 3
TOOL_RESULT_LIMIT = 10_000
+HEARTBEAT_INTERVAL_S = float(os.getenv("VT_HEARTBEAT_INTERVAL_S", "3.0"))
# Layer 2: Context collapse thresholds
COLLAPSE_THRESHOLD = int(TOKEN_THRESHOLD * 0.7)
@@ -608,12 +610,10 @@ class AgentLoop:
trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "args": {k: str(v)[:200] for k, v in args.items()}})
runnable.append((tc, args))
- # Execute in parallel
+ # Execute in parallel — each worker gets its own heartbeat + progress emitter.
def _run(tc_args: tuple) -> tuple:
tc, args = tc_args
- t0 = _time.perf_counter()
- result = self.registry.execute(tc.name, args)
- elapsed_ms = int((_time.perf_counter() - t0) * 1000)
+ result, elapsed_ms = self._invoke_tool(tc.name, args)
return tc, result, elapsed_ms
with concurrent.futures.ThreadPoolExecutor(max_workers=min(len(runnable), 8)) as pool:
@@ -655,12 +655,49 @@ class AgentLoop:
trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "args": {k: str(v)[:200] for k, v in args.items()}})
logger.info(f"Tool call: {tc.name}({list(args.keys())})")
- t0 = _time.perf_counter()
- result = self.registry.execute(tc.name, args)
- elapsed_ms = int((_time.perf_counter() - t0) * 1000)
+ result, elapsed_ms = self._invoke_tool(tc.name, args)
self._finalize_tool_result(tc, result, elapsed_ms, context, messages, trace, react_trace, iteration)
+ def _invoke_tool(self, tool_name: str, args: Dict[str, Any]) -> tuple[str, int]:
+ """Execute a tool with heartbeat + structured progress emission.
+
+ Installs a thread-local progress emitter so the tool may call
+ ``emit_progress()`` without taking a callback parameter, and runs a
+ background heartbeat timer that ticks every ``HEARTBEAT_INTERVAL_S``
+ seconds. Both event streams are forwarded through ``self._emit`` and
+ therefore land in the same SSE bus and CLI dashboard as normal
+ tool events.
+
+ Args:
+ tool_name: Tool name to execute.
+ args: Tool arguments dict.
+
+ Returns:
+ Tuple of (result_str, elapsed_ms).
+ """
+ def _on_progress(event: ProgressEvent) -> None:
+ payload = event.to_dict()
+ payload["tool"] = tool_name
+ self._emit("tool_progress", payload)
+
+ def _on_heartbeat(payload: Dict[str, Any]) -> None:
+ self._emit("tool_heartbeat", payload)
+
+ _set_emitter(_on_progress)
+ t0 = _time.perf_counter()
+ try:
+ with HeartbeatTimer(
+ tool_name=tool_name,
+ interval=HEARTBEAT_INTERVAL_S,
+ emit=_on_heartbeat,
+ ):
+ result = self.registry.execute(tool_name, args)
+ finally:
+ _set_emitter(None)
+ elapsed_ms = int((_time.perf_counter() - t0) * 1000)
+ return result, elapsed_ms
+
def _finalize_tool_result(
self,
tc: Any,
diff --git a/agent/src/agent/progress.py b/agent/src/agent/progress.py
new file mode 100644
index 000000000..447ed524e
--- /dev/null
+++ b/agent/src/agent/progress.py
@@ -0,0 +1,184 @@
+"""Progress emission channel for long-running tools.
+
+Two mechanisms:
+ * Tool-level heartbeat: a background timer fires keepalive events every N
+ seconds while a tool runs, so the UI never looks frozen. Driven by the
+ agent loop, opaque to the tool.
+ * Structured progress: tools can opt in via ``emit_progress()`` to publish
+ quantified state (stage, current/total, message). Routed back to the
+ agent loop's event channel via a thread-local emitter set before the
+ tool executes.
+
+Thread model: tools run synchronously inside ``ToolRegistry.execute`` from
+worker threads (read batches) or the main loop thread (writes). A
+``threading.local`` slot holds the per-thread emitter so structured
+progress flows back to the correct AgentLoop instance even when multiple
+read-only tools run in parallel.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+from dataclasses import dataclass, field
+from typing import Any, Callable, Dict, Optional
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class ProgressEvent:
+ """Structured progress event emitted by a tool mid-execution.
+
+ Attributes:
+ tool: Tool name (filled by the loop, tools don't supply this).
+ stage: Short stage label, e.g. ``loading_data`` or ``simulating``.
+ current: Current unit count (e.g. page 23 of 100). Optional.
+ total: Total unit count. Optional.
+ message: Free-form human-readable detail.
+ elapsed_s: Seconds since the tool started.
+ ts: Wall-clock timestamp.
+ """
+
+ tool: str = ""
+ stage: str = ""
+ current: Optional[int] = None
+ total: Optional[int] = None
+ message: str = ""
+ elapsed_s: float = 0.0
+ ts: float = field(default_factory=time.time)
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return a JSON-serializable dict for SSE payloads."""
+ return {
+ "tool": self.tool,
+ "stage": self.stage,
+ "current": self.current,
+ "total": self.total,
+ "message": self.message,
+ "elapsed_s": round(self.elapsed_s, 2),
+ "ts": self.ts,
+ }
+
+
+# Thread-local emitter slot. The agent loop sets ``_local.emit`` to a callable
+# before invoking the tool and clears it after, so tools running on the same
+# thread can publish structured progress without a circular import.
+_local = threading.local()
+
+
+def _set_emitter(emit: Optional[Callable[[ProgressEvent], None]]) -> None:
+ """Install the active progress emitter for the current thread.
+
+ Args:
+ emit: Callable that consumes a ``ProgressEvent``. Pass ``None`` to clear.
+ """
+ if emit is None:
+ if hasattr(_local, "emit"):
+ del _local.emit
+ return
+ _local.emit = emit
+
+
+def _get_emitter() -> Optional[Callable[[ProgressEvent], None]]:
+ """Return the active emitter on the current thread, if any."""
+ return getattr(_local, "emit", None)
+
+
+def emit_progress(
+ stage: str = "",
+ *,
+ current: Optional[int] = None,
+ total: Optional[int] = None,
+ message: str = "",
+) -> None:
+ """Publish a structured progress event from a tool.
+
+ Silently no-ops when called outside an active tool context (e.g. during
+ unit tests that invoke tools directly). Never raises.
+
+ Args:
+ stage: Short stage label.
+ current: Current unit count.
+ total: Total unit count.
+ message: Free-form human-readable detail.
+ """
+ emit = _get_emitter()
+ if emit is None:
+ return
+ try:
+ event = ProgressEvent(
+ stage=stage,
+ current=current,
+ total=total,
+ message=message,
+ )
+ emit(event)
+ except Exception:
+ # Progress emission must never break a tool.
+ pass
+
+
+class HeartbeatTimer:
+ """Background thread that emits keepalive ticks while a tool runs.
+
+ Use as a context manager around a single tool invocation:
+
+ with HeartbeatTimer(tool_name="run_backtest", interval=3.0, emit=fn):
+ result = registry.execute(...)
+
+ The timer wakes every ``interval`` seconds and calls ``emit`` with a
+ dict containing ``tool`` and ``elapsed_s``. Stops cleanly on context
+ exit; ``join`` is bounded so a hung emitter can't deadlock the loop.
+ """
+
+ def __init__(
+ self,
+ tool_name: str,
+ interval: float,
+ emit: Callable[[Dict[str, Any]], None],
+ ) -> None:
+ """Initialize the heartbeat timer (not started until ``__enter__``).
+
+ Args:
+ tool_name: Tool name surfaced in each tick payload.
+ interval: Seconds between ticks. Values <0.5 are clamped.
+ emit: Callback invoked with each tick payload.
+ """
+ self._tool_name = tool_name
+ requested_interval = float(interval)
+ self._interval = max(0.5, requested_interval)
+ if requested_interval < 0.5:
+ logger.warning(
+ "HeartbeatTimer interval %s clamped to 0.5s", interval
+ )
+ self._emit = emit
+ self._stop_event = threading.Event()
+ self._thread: Optional[threading.Thread] = None
+ self._t0 = 0.0
+
+ def __enter__(self) -> "HeartbeatTimer":
+ self._t0 = time.perf_counter()
+ self._thread = threading.Thread(
+ target=self._run,
+ name=f"heartbeat-{self._tool_name}",
+ daemon=True,
+ )
+ self._thread.start()
+ return self
+
+ def __exit__(self, exc_type, exc, tb) -> None:
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join(timeout=1.0)
+
+ def _run(self) -> None:
+ """Tick loop: wait + emit until the stop event fires."""
+ while not self._stop_event.wait(self._interval):
+ elapsed = time.perf_counter() - self._t0
+ try:
+ self._emit({"tool": self._tool_name, "elapsed_s": round(elapsed, 2)})
+ except Exception:
+ # A failing callback must not crash the heartbeat thread.
+ pass
diff --git a/agent/src/tools/backtest_tool.py b/agent/src/tools/backtest_tool.py
index 6b99c2f1b..30ed764c9 100644
--- a/agent/src/tools/backtest_tool.py
+++ b/agent/src/tools/backtest_tool.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from pathlib import Path
+from src.agent.progress import emit_progress
from src.agent.tools import BaseTool
from src.core.runner import Runner
from src.tools.path_utils import safe_run_dir
@@ -19,6 +20,7 @@ def run_backtest(run_dir: str) -> str:
Returns:
JSON-formatted execution result.
"""
+ emit_progress("validate", message="validating run_dir and config")
try:
run_path = safe_run_dir(run_dir)
except ValueError as exc:
@@ -47,6 +49,11 @@ def run_backtest(run_dir: str) -> str:
agent_root = Path(__file__).resolve().parents[2]
entry_script = agent_root / "backtest" / "runner.py"
+ source = config.get("source", "?")
+ emit_progress(
+ "simulate",
+ message=f"running backtest engine (source={source})",
+ )
runner = Runner(timeout=300)
result = runner.execute(
entry_script,
@@ -55,6 +62,7 @@ def run_backtest(run_dir: str) -> str:
cli_args=[str(run_path)],
)
+ emit_progress("finalize", message="collecting artifacts")
artifacts_found = {name: str(path) for name, path in result.artifacts.items()}
return json.dumps({
"status": "ok" if result.success else "error",
diff --git a/agent/src/tools/doc_reader_tool.py b/agent/src/tools/doc_reader_tool.py
index 07a4a365b..14b566536 100644
--- a/agent/src/tools/doc_reader_tool.py
+++ b/agent/src/tools/doc_reader_tool.py
@@ -19,6 +19,7 @@ import json
from pathlib import Path
from typing import Any, Callable
+from src.agent.progress import emit_progress
from src.agent.tools import BaseTool
from src.security.scanner import with_security_warnings
from src.tools.path_utils import safe_document_path
@@ -126,15 +127,22 @@ def _read_pdf(path: Path, pages: str) -> str:
try:
total_pages = len(doc)
targets = _parse_pages(pages, total_pages) if pages.strip() else list(range(total_pages))
+ total_targets = len(targets)
chunks: list[str] = []
ocr_pages = 0
- for i in targets:
+ for idx, i in enumerate(targets, start=1):
if not 0 <= i < total_pages:
continue
page = doc[i]
text = page.get_textpage().get_text_range().strip()
if len(text) >= _MIN_TEXT_PER_PAGE:
chunks.append(f"--- Page {i + 1} ---\n{text}")
+ emit_progress(
+ "reading_pdf",
+ current=idx,
+ total=total_targets,
+ message=f"page {i + 1}/{total_pages}",
+ )
continue
# OCR fallback for image pages
bitmap = page.render(scale=300 / 72)
@@ -145,6 +153,12 @@ def _read_pdf(path: Path, pages: str) -> str:
ocr_pages += 1
elif text:
chunks.append(f"--- Page {i + 1} ---\n{text}")
+ emit_progress(
+ "reading_pdf",
+ current=idx,
+ total=total_targets,
+ message=f"page {i + 1}/{total_pages} (OCR)" if ocr_text.strip() else f"page {i + 1}/{total_pages}",
+ )
full = "\n\n".join(chunks)
return _envelope(
path, "pdf", full,
@@ -185,7 +199,14 @@ def _read_excel(path: Path) -> str:
xls = pd.ExcelFile(path)
parts: list[str] = []
sheet_info: list[dict[str, Any]] = []
- for name in xls.sheet_names:
+ total_sheets = len(xls.sheet_names)
+ for idx, name in enumerate(xls.sheet_names, start=1):
+ emit_progress(
+ "reading_excel",
+ current=idx,
+ total=total_sheets,
+ message=f"sheet {name}",
+ )
df = xls.parse(name, dtype=str)
preview = df.head(100).to_string(index=False)
parts.append(f"--- Sheet: {name} ({len(df)} rows × {len(df.columns)} cols) ---\n{preview}")
diff --git a/agent/src/tools/web_reader_tool.py b/agent/src/tools/web_reader_tool.py
index 4fdf53434..481fca220 100644
--- a/agent/src/tools/web_reader_tool.py
+++ b/agent/src/tools/web_reader_tool.py
@@ -9,6 +9,7 @@ from urllib.parse import urlsplit
import requests
+from src.agent.progress import emit_progress
from src.agent.tools import BaseTool
from src.security.scanner import with_security_warnings
@@ -81,11 +82,16 @@ def read_url(url: str, no_cache: bool = False) -> str:
headers = {"Accept": "text/markdown"}
if no_cache:
headers["x-no-cache"] = "true"
+ emit_progress(
+ "fetching",
+ message=f"GET {target_url[:60]}{'…' if len(target_url) > 60 else ''}",
+ )
resp = requests.get(
f"{_JINA_PREFIX}{target_url}",
headers=headers,
timeout=_TIMEOUT,
)
+ emit_progress("parsing", message="extracting markdown")
if resp.status_code != 200:
logger.warning("read_url upstream HTTP %s: %s", resp.status_code, resp.text[:500])
return json.dumps({
diff --git a/agent/tests/test_fundamental_filter_example.py b/agent/tests/test_fundamental_filter_example.py
index cde6dbca9..94661d80f 100644
--- a/agent/tests/test_fundamental_filter_example.py
+++ b/agent/tests/test_fundamental_filter_example.py
@@ -6,8 +6,11 @@ from pathlib import Path
import pandas as pd
+_AGENT_ROOT = Path(__file__).resolve().parents[1]
+
+
def _load_example_module():
- path = Path("agent/src/skills/fundamental-filter/example_signal_engine.py")
+ path = _AGENT_ROOT / "src" / "skills" / "fundamental-filter" / "example_signal_engine.py"
spec = importlib.util.spec_from_file_location("fundamental_filter_example", path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
diff --git a/agent/tests/test_openai_codex.py b/agent/tests/test_openai_codex.py
index b3748fba7..5be9bacf5 100644
--- a/agent/tests/test_openai_codex.py
+++ b/agent/tests/test_openai_codex.py
@@ -76,7 +76,10 @@ def test_codex_body_strips_provider_prefix_and_converts_tools() -> None:
def test_missing_codex_token_raises_login_hint(monkeypatch: pytest.MonkeyPatch) -> None:
- import oauth_cli_kit
+ oauth_cli_kit = pytest.importorskip(
+ "oauth_cli_kit",
+ reason="oauth-cli-kit is declared in requirements.txt but optional at runtime",
+ )
def _missing_token() -> None:
raise RuntimeError("missing")
diff --git a/agent/tests/test_progress.py b/agent/tests/test_progress.py
new file mode 100644
index 000000000..21431d2f2
--- /dev/null
+++ b/agent/tests/test_progress.py
@@ -0,0 +1,186 @@
+"""Tests for agent.progress (heartbeat + structured progress emission)."""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+
+import pytest
+
+from src.agent.progress import (
+ HeartbeatTimer,
+ ProgressEvent,
+ _get_emitter,
+ _set_emitter,
+ emit_progress,
+)
+
+
+# ---------- ProgressEvent ---------------------------------------------------
+
+
+def test_progress_event_to_dict_round_trip() -> None:
+ """to_dict returns every public field with rounded elapsed_s."""
+ e = ProgressEvent(
+ tool="run_backtest",
+ stage="loading",
+ current=3,
+ total=10,
+ message="page 3",
+ elapsed_s=1.23456,
+ )
+ d = e.to_dict()
+ assert d["tool"] == "run_backtest"
+ assert d["stage"] == "loading"
+ assert d["current"] == 3
+ assert d["total"] == 10
+ assert d["message"] == "page 3"
+ assert d["elapsed_s"] == 1.23
+ assert "ts" in d
+
+
+def test_progress_event_is_immutable() -> None:
+ """frozen dataclass forbids field reassignment."""
+ e = ProgressEvent(stage="x")
+ with pytest.raises(Exception):
+ e.stage = "y" # type: ignore[misc]
+
+
+# ---------- emit_progress ---------------------------------------------------
+
+
+def test_emit_progress_noop_without_emitter() -> None:
+ """emit_progress must silently no-op when nothing is listening."""
+ # Ensure no leftover emitter from another test.
+ _set_emitter(None)
+ assert _get_emitter() is None
+ emit_progress("nope", message="should not raise")
+ # Still no emitter installed.
+ assert _get_emitter() is None
+
+
+def test_emit_progress_routes_to_active_emitter() -> None:
+ """Installed emitter receives a ProgressEvent with the supplied fields."""
+ captured: list[ProgressEvent] = []
+ _set_emitter(captured.append)
+ try:
+ emit_progress("loading", current=2, total=5, message="halfway")
+ finally:
+ _set_emitter(None)
+
+ assert len(captured) == 1
+ assert captured[0].stage == "loading"
+ assert captured[0].current == 2
+ assert captured[0].total == 5
+ assert captured[0].message == "halfway"
+ # Tool name is filled by the agent loop, not the tool itself.
+ assert captured[0].tool == ""
+
+
+def test_emit_progress_swallows_emitter_errors() -> None:
+ """A failing emitter must not propagate out of a tool."""
+ def _boom(_ev: ProgressEvent) -> None:
+ raise RuntimeError("emitter is angry")
+
+ _set_emitter(_boom)
+ try:
+ # Should not raise.
+ emit_progress("danger")
+ finally:
+ _set_emitter(None)
+
+
+def test_set_emitter_is_thread_local() -> None:
+ """Each thread gets its own emitter slot."""
+ other_captured: list[ProgressEvent] = []
+
+ def _other_thread() -> None:
+ # No emitter installed on this thread.
+ emit_progress("from_other") # no-op
+ assert _get_emitter() is None
+ # Install a thread-local emitter.
+ _set_emitter(other_captured.append)
+ emit_progress("other_active")
+ _set_emitter(None)
+
+ main_captured: list[ProgressEvent] = []
+ _set_emitter(main_captured.append)
+ try:
+ t = threading.Thread(target=_other_thread)
+ t.start()
+ t.join()
+ emit_progress("main_still_here")
+ finally:
+ _set_emitter(None)
+
+ # Main thread's emitter must not have received the other thread's event.
+ assert [e.stage for e in main_captured] == ["main_still_here"]
+ assert [e.stage for e in other_captured] == ["other_active"]
+
+
+# ---------- HeartbeatTimer --------------------------------------------------
+
+
+def test_heartbeat_timer_emits_ticks_until_exit() -> None:
+ """Timer ticks ~every interval seconds and stops on context exit."""
+ ticks: list[dict] = []
+ # interval is clamped to 0.5 minimum, so sleep ~1.4s to fit two ticks.
+ with HeartbeatTimer("dummy_tool", interval=0.5, emit=ticks.append):
+ time.sleep(1.4)
+ assert len(ticks) >= 2
+ assert all(t["tool"] == "dummy_tool" for t in ticks)
+ assert all(isinstance(t["elapsed_s"], (int, float)) for t in ticks)
+ # Elapsed must be monotonic non-decreasing.
+ elapsed = [t["elapsed_s"] for t in ticks]
+ assert elapsed == sorted(elapsed)
+
+
+def test_heartbeat_timer_clamps_short_interval() -> None:
+ """Intervals below 0.5s are clamped to avoid CPU thrash."""
+ timer = HeartbeatTimer("x", interval=0.01, emit=lambda d: None)
+ assert timer._interval >= 0.5 # implementation detail but worth pinning
+
+
+def test_heartbeat_timer_logs_warning_when_clamped(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Clamping a sub-0.5s interval emits exactly one warning record."""
+ with caplog.at_level(logging.WARNING, logger="src.agent.progress"):
+ HeartbeatTimer("x", interval=0.01, emit=lambda d: None)
+ clamp_records = [
+ r for r in caplog.records if "clamped" in r.getMessage()
+ ]
+ assert len(clamp_records) == 1
+ assert clamp_records[0].levelno == logging.WARNING
+
+
+def test_heartbeat_timer_no_warning_when_interval_ok(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """A valid interval (>= 0.5s) must not log the clamp warning."""
+ with caplog.at_level(logging.WARNING, logger="src.agent.progress"):
+ HeartbeatTimer("x", interval=1.5, emit=lambda d: None)
+ assert not any("clamped" in r.getMessage() for r in caplog.records)
+
+
+def test_heartbeat_timer_swallows_emit_errors() -> None:
+ """A failing emit callback must not crash the heartbeat thread."""
+ raised = threading.Event()
+
+ def _boom(_d: dict) -> None:
+ raised.set()
+ raise RuntimeError("nope")
+
+ with HeartbeatTimer("x", interval=0.3, emit=_boom):
+ time.sleep(0.7)
+ # The callback was invoked at least once and didn't bring the thread down.
+ assert raised.is_set()
+
+
+def test_heartbeat_timer_no_ticks_when_exits_before_interval() -> None:
+ """Quick tool calls don't emit any heartbeat tick."""
+ ticks: list[dict] = []
+ with HeartbeatTimer("fast", interval=2.0, emit=ticks.append):
+ time.sleep(0.05)
+ assert ticks == []
diff --git a/frontend/src/components/chat/ProgressBar.tsx b/frontend/src/components/chat/ProgressBar.tsx
new file mode 100644
index 000000000..3fa71dc3f
--- /dev/null
+++ b/frontend/src/components/chat/ProgressBar.tsx
@@ -0,0 +1,73 @@
+import type { ReactElement } from "react";
+import { cn } from "@/lib/utils";
+
+interface ProgressBarProps {
+ /** Current progress value; clamped to [0, total] internally. */
+ current: number;
+ /** Total value; must be > 0 or the component renders nothing. */
+ total: number;
+ /** Bar height: "xs" => h-1, "sm" => h-2. Defaults to "xs". */
+ height?: "xs" | "sm";
+ /** When true, appends "{current}/{total}" text after the bar. */
+ showCount?: boolean;
+ /** Visible-context label (e.g. "PDF page progress"). */
+ ariaLabel?: string;
+ /** Extra Tailwind classes for the outer wrapper. */
+ className?: string;
+}
+
+/**
+ * Thin horizontal progress bar primitive.
+ *
+ * Visual pattern mirrors AlphaZoo's progress bar
+ * (`frontend/src/pages/AlphaZoo.tsx:854-859`):
+ * `bg-muted rounded-full overflow-hidden` track + `bg-primary
+ * transition-all duration-300` fill.
+ *
+ * Accessibility: a native `<progress>` element carries the semantics
+ * for assistive technologies; the visual fill div is purely decorative.
+ */
+export function ProgressBar({
+ current,
+ total,
+ height = "xs",
+ showCount = false,
+ ariaLabel,
+ className,
+}: ProgressBarProps): ReactElement | null {
+ if (total <= 0) return null;
+
+ const clamped = Math.min(total, Math.max(0, current));
+ const pct = Math.min(100, Math.max(0, (clamped / total) * 100));
+ const heightClass = height === "sm" ? "h-2" : "h-1";
+
+ return (
+ <div
+ className={cn("flex items-center gap-2 min-w-0", className)}
+ aria-label={ariaLabel}
+ >
+ <progress
+ value={clamped}
+ max={total}
+ className="sr-only"
+ aria-label={ariaLabel}
+ />
+ <div
+ className={cn(
+ "bg-muted rounded-full overflow-hidden flex-1",
+ heightClass,
+ )}
+ >
+ <div
+ className="h-full bg-primary transition-all duration-300"
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ {showCount && (
+ <span className="text-[10px] text-muted-foreground tabular-nums shrink-0">
+ {clamped}/{total}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/components/chat/ThinkingTimeline.tsx b/frontend/src/components/chat/ThinkingTimeline.tsx
index ddbae03b9..b6539017d 100644
--- a/frontend/src/components/chat/ThinkingTimeline.tsx
+++ b/frontend/src/components/chat/ThinkingTimeline.tsx
@@ -2,24 +2,9 @@ import { useState, useEffect, useMemo, memo } from "react";
import { ChevronDown, ChevronRight, CheckCircle2, XCircle, Circle, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { useI18n } from "@/lib/i18n";
+import { localizeToolName } from "@/lib/tools";
import type { AgentMessage } from "@/types/agent";
-/* ---------- Tool display name keys (mapped to i18n) ---------- */
-const TOOL_I18N_KEY: Record<string, string> = {
- load_skill: "toolLoadSkill",
- write_file: "toolWriteFile",
- edit_file: "toolEditFile",
- read_file: "toolReadFile",
- run_backtest: "toolRunBacktest",
- bash: "toolBash",
- read_url: "toolReadUrl",
- read_document: "toolReadDocument",
- compact: "toolCompact",
- create_task: "toolCreateTask",
- update_task: "toolUpdateTask",
- spawn_subagent: "toolSpawnSubagent",
-};
-
interface Props {
messages: AgentMessage[];
isLatest?: boolean;
@@ -31,8 +16,11 @@ export const ThinkingTimeline = memo(function ThinkingTimeline({ messages, isLat
const toolLabel = (tool?: string): string => {
if (!tool) return t.toolProcessing;
- const key = TOOL_I18N_KEY[tool];
- return key ? (t as Record<string, string>)[key] || tool : tool;
+ const key = localizeToolName(tool);
+ // If the lookup returned a mapped i18n key, resolve it against the
+ // active i18n table; otherwise fall back to the raw tool name.
+ if (key === tool) return tool;
+ return (t as Record<string, string>)[key] || tool;
};
useEffect(() => {
diff --git a/frontend/src/components/chat/ToolProgressIndicator.tsx b/frontend/src/components/chat/ToolProgressIndicator.tsx
new file mode 100644
index 000000000..c329f9c42
--- /dev/null
+++ b/frontend/src/components/chat/ToolProgressIndicator.tsx
@@ -0,0 +1,271 @@
+import { useRef, type JSX } from "react";
+import { Loader2, CheckCircle2, XCircle } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { useI18n } from "@/lib/i18n";
+import { ProgressBar } from "@/components/chat/ProgressBar";
+import { localizeToolName } from "@/lib/tools";
+import type { ToolCallEntry } from "@/types/agent";
+
+/**
+ * Resolve a tool name to its user-facing label via the active i18n bundle.
+ * Mirrors the pattern in ThinkingTimeline.tsx (`toolLabel`): localizeToolName
+ * returns an i18n key when one is mapped, otherwise the raw tool name.
+ */
+function useLocalizedToolName(): (tool: string) => string {
+ const { t } = useI18n();
+ return (tool: string) => {
+ const key = localizeToolName(tool);
+ if (key === tool) return tool;
+ return (t as Record<string, string>)[key] || tool;
+ };
+}
+
+/* ---------- ETA tracking (per-tool) ---------- */
+interface EtaSample {
+ stage: string;
+ current: number;
+ suppressed: boolean;
+}
+
+/* ---------- Determinate progress ring ---------- */
+interface RingProps {
+ current: number;
+ total: number;
+}
+
+function ProgressRing({ current, total }: RingProps): JSX.Element {
+ // h-3 w-3 = 12px; viewBox 24, r=10, circumference = 2*PI*10 ≈ 62.83
+ const pct = Math.min(1, Math.max(0, current / total));
+ const c = 2 * Math.PI * 10;
+ const dash = c * pct;
+ return (
+ <svg
+ viewBox="0 0 24 24"
+ className="h-3 w-3 text-primary shrink-0"
+ aria-hidden="true"
+ >
+ <circle
+ cx="12"
+ cy="12"
+ r="10"
+ fill="none"
+ stroke="currentColor"
+ strokeOpacity="0.2"
+ strokeWidth="3"
+ />
+ <circle
+ cx="12"
+ cy="12"
+ r="10"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="3"
+ strokeLinecap="round"
+ strokeDasharray={`${dash} ${c - dash}`}
+ transform="rotate(-90 12 12)"
+ style={{ transition: "stroke-dasharray 200ms ease" }}
+ />
+ </svg>
+ );
+}
+
+/* ---------- Single tool row ---------- */
+interface RowProps {
+ entry: ToolCallEntry;
+ stepIndex: number;
+ totalSteps: number;
+ isHeader?: boolean;
+ connector?: "branch" | "end" | "none";
+ eta: number | null;
+}
+
+function ToolRow({ entry, stepIndex, totalSteps, isHeader, connector = "none", eta }: RowProps): JSX.Element {
+ const localizeName = useLocalizedToolName();
+ const progress = entry.progress;
+ const hasDeterminate = !!(progress && typeof progress.current === "number" && typeof progress.total === "number" && progress.total > 0);
+ const stage = progress?.stage || "";
+ const message = progress?.message || "";
+
+ const icon = entry.status === "error"
+ ? <XCircle className="h-3 w-3 text-danger shrink-0" />
+ : entry.status === "ok"
+ ? <CheckCircle2 className="h-3 w-3 text-success shrink-0" />
+ : hasDeterminate
+ ? <ProgressRing current={progress!.current!} total={progress!.total!} />
+ : <Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />;
+
+ const localized = localizeName(entry.tool);
+ const stepLabel = isHeader
+ ? `${totalSteps} tools running`
+ : `Step ${stepIndex} · ${localized}`;
+
+ return (
+ <div className="flex flex-col sm:flex-row sm:items-center gap-x-2 gap-y-0.5 text-xs min-w-0">
+ {/* Primary row */}
+ <div className="flex items-center gap-2 min-w-0 sm:flex-none">
+ {connector !== "none" && (
+ <span className="text-border/60 shrink-0 w-3 text-center" aria-hidden="true">
+ {connector === "branch" ? "├" : "└"}
+ </span>
+ )}
+ {icon}
+ <span className="text-foreground truncate">{stepLabel}</span>
+ {entry.elapsed_s != null && (
+ <span className="ml-auto sm:ml-0 tabular-nums text-[10px] text-muted-foreground/70 shrink-0">
+ {entry.elapsed_s.toFixed(0)}s
+ </span>
+ )}
+ </div>
+ {/* Secondary row: stage + progress bar (+ ETA) */}
+ {(progress && (hasDeterminate || stage)) && (
+ <div className="flex items-center gap-2 min-w-0 sm:flex-1">
+ {stage && (
+ <span className="text-foreground text-xs shrink-0 truncate max-w-[40%]">{stage}</span>
+ )}
+ {hasDeterminate && (
+ <ProgressBar
+ current={progress!.current!}
+ total={progress!.total!}
+ height="xs"
+ showCount
+ ariaLabel={stage || localized}
+ className="text-muted-foreground"
+ />
+ )}
+ {eta != null && (
+ <span className="text-[10px] text-muted-foreground/70 tabular-nums shrink-0">
+ ~{eta}s left
+ </span>
+ )}
+ </div>
+ )}
+ {/* Tertiary row: message */}
+ {message && (
+ <div className="text-[10px] text-muted-foreground/60 truncate min-w-0 sm:basis-full">
+ {message}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* ---------- Public component ---------- */
+interface Props {
+ /** Full toolCalls slice from the store. The component filters running ones internally. */
+ toolCalls: ToolCallEntry[];
+}
+
+const MAX_VISIBLE = 3;
+
+export function ToolProgressIndicator({ toolCalls }: Props): JSX.Element | null {
+ // Per-tool ETA samples (mutable across renders, not state to avoid re-renders).
+ const etaSamplesRef = useRef<Map<string, EtaSample>>(new Map());
+
+ const running = toolCalls.filter((tc) => tc.status === "running");
+ if (running.length === 0) return null;
+
+ const totalSoFar = toolCalls.length;
+
+ /* ---------- compute ETA for each running tool ---------- */
+ const computeEta = (tc: ToolCallEntry): number | null => {
+ const p = tc.progress;
+ if (!p || typeof p.current !== "number" || typeof p.total !== "number") return null;
+ if (p.total <= 0) return null;
+ const stage = p.stage || "";
+ const samples = etaSamplesRef.current;
+ const prev = samples.get(tc.tool);
+
+ // Out-of-order: current decreased → suppress for the rest of the run.
+ if (prev && p.current < prev.current) {
+ samples.set(tc.tool, { stage, current: p.current, suppressed: true });
+ return null;
+ }
+ if (prev?.suppressed && prev.stage === stage) {
+ // Update tracking but keep suppressed.
+ samples.set(tc.tool, { stage, current: p.current, suppressed: true });
+ return null;
+ }
+ samples.set(tc.tool, { stage, current: p.current, suppressed: false });
+
+ // Need a stable stage and enough samples to extrapolate.
+ if (!prev || prev.stage !== stage) return null;
+ if (p.current < 3) return null;
+ if (p.current < p.total * 0.1) return null;
+ if (tc.elapsed_s == null || tc.elapsed_s <= 0) return null;
+
+ const eta = (tc.elapsed_s / p.current) * (p.total - p.current);
+ if (!isFinite(eta) || eta < 0) return null;
+ return Math.round(eta);
+ };
+
+ /* ---------- aggregate icon state for the header row ---------- */
+ // (Used when 2+ tools are running — header shows multi-tool aggregate.)
+ // Note: filtered list is `running` so all are still running by construction.
+ // We still inspect entire toolCalls so an earlier error in this turn shows
+ // through the aggregate.
+ const anyError = toolCalls.some((tc) => tc.status === "error");
+ const aggregateIcon = anyError
+ ? <XCircle className="h-3 w-3 text-danger shrink-0" />
+ : <Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />;
+
+ // Display rule: ≤3 running → show all; >3 → first 2 + "… +N more".
+ const showAll = running.length <= MAX_VISIBLE;
+ const rows = showAll ? running : running.slice(0, 2);
+ const overflow = showAll ? 0 : running.length - rows.length;
+
+ /* ---------- render ---------- */
+ if (running.length === 1) {
+ const only = running[0];
+ const eta = computeEta(only);
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
+ className="min-w-0"
+ >
+ <ToolRow
+ entry={only}
+ stepIndex={totalSoFar}
+ totalSteps={running.length}
+ eta={eta}
+ />
+ </div>
+ );
+ }
+
+ // 2+ running — header + indented rows.
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
+ className={cn("min-w-0 space-y-1")}
+ >
+ {/* Header row */}
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ {aggregateIcon}
+ <span className="text-foreground">{running.length} tools running</span>
+ </div>
+ {/* Indented rows */}
+ <div className="pl-4 space-y-1">
+ {rows.map((tc, i) => (
+ <ToolRow
+ key={tc.id}
+ entry={tc}
+ stepIndex={toolCalls.indexOf(tc) + 1}
+ totalSteps={running.length}
+ connector={i === rows.length - 1 && overflow === 0 ? "end" : "branch"}
+ eta={computeEta(tc)}
+ />
+ ))}
+ {overflow > 0 && (
+ <div className="flex items-center gap-2 text-[10px] text-muted-foreground/60">
+ <span className="text-border/60 shrink-0 w-3 text-center" aria-hidden="true">└</span>
+ <span>… +{overflow} more</span>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/lib/tools.ts b/frontend/src/lib/tools.ts
new file mode 100644
index 000000000..c65d14e7d
--- /dev/null
+++ b/frontend/src/lib/tools.ts
@@ -0,0 +1,44 @@
+/**
+ * Single source of truth for tool name → i18n key.
+ *
+ * Values are i18n keys (looked up in `useI18n().t`), not final labels.
+ * The map name "TOOL_I18N_KEY" reflects this: it maps a raw tool identifier
+ * to the i18n bundle key whose value is the user-facing label.
+ *
+ * Consumers that need a final localized string should:
+ * 1. Call `localizeToolName(tool)` to get the i18n key (or fallback).
+ * 2. Resolve that key against the active i18n table.
+ */
+export const TOOL_I18N_KEY: Record<string, string> = {
+ load_skill: "toolLoadSkill",
+ write_file: "toolWriteFile",
+ edit_file: "toolEditFile",
+ read_file: "toolReadFile",
+ run_backtest: "toolRunBacktest",
+ bash: "toolBash",
+ read_url: "toolReadUrl",
+ read_document: "toolReadDocument",
+ compact: "toolCompact",
+ create_task: "toolCreateTask",
+ update_task: "toolUpdateTask",
+ spawn_subagent: "toolSpawnSubagent",
+};
+
+/**
+ * Returns the i18n key (or fallback) for a tool name.
+ *
+ * - If `tool` is mapped in `TOOL_I18N_KEY`, returns the mapped key.
+ * - Else if `fallback` is provided, returns `fallback`.
+ * - Else returns `tool` unchanged.
+ *
+ * Centralizes the previously-duplicated lookup pattern.
+ */
+export function localizeToolName(tool: string, fallback?: string): string {
+ if (tool in TOOL_I18N_KEY) {
+ return TOOL_I18N_KEY[tool];
+ }
+ if (fallback !== undefined) {
+ return fallback;
+ }
+ return tool;
+}
diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsx
index 77d772870..eca730570 100644
--- a/frontend/src/pages/Agent.tsx
+++ b/frontend/src/pages/Agent.tsx
@@ -1,17 +1,18 @@
import { useEffect, useRef, useState, useMemo, useCallback, type FormEvent } from "react";
import { useSearchParams } from "react-router-dom";
-import { Send, Loader2, ArrowDown, CheckCircle2, Square, Download, Plus, Paperclip, X, Users } from "lucide-react";
+import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users } from "lucide-react";
import { toast } from "sonner";
import { useAgentStore } from "@/stores/agent";
import { useSSE } from "@/hooks/useSSE";
import { useI18n } from "@/lib/i18n";
import { api } from "@/lib/api";
-import type { AgentMessage } from "@/types/agent";
+import type { AgentMessage, ToolCallEntry } from "@/types/agent";
import { AgentAvatar } from "@/components/chat/AgentAvatar";
import { WelcomeScreen } from "@/components/chat/WelcomeScreen";
import { MessageBubble } from "@/components/chat/MessageBubble";
import { ThinkingTimeline } from "@/components/chat/ThinkingTimeline";
import { ConversationTimeline } from "@/components/chat/ConversationTimeline";
+import { ToolProgressIndicator } from "@/components/chat/ToolProgressIndicator";
/* ---------- Message grouping ---------- */
type MsgGroup =
@@ -48,6 +49,10 @@ export function Agent() {
const [showScrollBtn, setShowScrollBtn] = useState(false);
const lastEventRef = useRef(0);
+ /* tool_progress coalescing — keep latest payload per-tool, flush once per rAF. */
+ const pendingProgressRef = useRef<Map<string, NonNullable<ToolCallEntry["progress"]>>>(new Map());
+ const progressRafRef = useRef(0);
+
const [attachment, setAttachment] = useState<{ filename: string; filePath: string } | null>(null);
const [uploading, setUploading] = useState(false);
const [showUploadMenu, setShowUploadMenu] = useState(false);
@@ -175,11 +180,49 @@ export function Agent() {
tool_result: (d) => {
touch();
+ const toolName = String(d.tool || "");
+ // Drop any in-flight coalesced progress for this tool.
+ pendingProgressRef.current.delete(toolName);
// Only update tracker (no message creation during streaming)
- act().updateToolCall(String(d.tool || ""), {
+ act().updateToolCall(toolName, {
status: d.status === "ok" ? "ok" : "error",
preview: String(d.preview || ""),
elapsed_ms: Number(d.elapsed_ms || 0),
+ elapsed_s: undefined,
+ progress: undefined,
+ });
+ },
+
+ tool_heartbeat: (d) => {
+ touch();
+ const toolName = String(d.tool || "");
+ if (!toolName) return;
+ act().updateToolCall(toolName, {
+ elapsed_s: Number(d.elapsed_s || 0),
+ });
+ },
+
+ tool_progress: (d) => {
+ touch();
+ const toolName = String(d.tool || "");
+ if (!toolName) return;
+ const payload: NonNullable<ToolCallEntry["progress"]> = {};
+ if (typeof d.stage === "string" && d.stage) payload.stage = d.stage;
+ if (typeof d.message === "string" && d.message) payload.message = d.message;
+ if (typeof d.current === "number") payload.current = d.current;
+ if (typeof d.total === "number") payload.total = d.total;
+ // Coalesce: keep latest payload per tool, flush once per animation frame.
+ pendingProgressRef.current.set(toolName, payload);
+ if (progressRafRef.current) return;
+ progressRafRef.current = requestAnimationFrame(() => {
+ progressRafRef.current = 0;
+ const pending = pendingProgressRef.current;
+ if (pending.size === 0) return;
+ const store = act();
+ for (const [tool, progress] of pending) {
+ store.updateToolCall(tool, { progress });
+ }
+ pending.clear();
});
},
@@ -245,6 +288,9 @@ export function Agent() {
act().clearStreaming();
act().addMessage({ id: "", type: "error", content: String(d.error || "Execution failed"), timestamp: Date.now() });
act().setStatus("idle");
+ // Clear stale toolCalls so the next turn's running indicator doesn't
+ // briefly show the previous turn's progress before fresh events land.
+ useAgentStore.setState({ toolCalls: [] });
scrollToBottom();
},
@@ -494,18 +540,9 @@ export function Agent() {
<span className="inline-block w-0.5 h-4 bg-primary ml-0.5 animate-pulse align-middle" />
</div>
)}
- {status === "streaming" && toolCalls.length > 0 && (() => {
- const latest = toolCalls[toolCalls.length - 1];
- const running = latest.status === "running";
- return (
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- {running
- ? <Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />
- : <CheckCircle2 className="h-3 w-3 text-success/60 shrink-0" />}
- <span>Step {toolCalls.length} · {latest.tool}</span>
- </div>
- );
- })()}
+ {status === "streaming" && toolCalls.length > 0 && (
+ <ToolProgressIndicator toolCalls={toolCalls} />
+ )}
</div>
</div>
)}
diff --git a/frontend/src/types/agent.ts b/frontend/src/types/agent.ts
index 111a17b87..a2ff44076 100644
--- a/frontend/src/types/agent.ts
+++ b/frontend/src/types/agent.ts
@@ -29,5 +29,17 @@ export interface ToolCallEntry {
status: "running" | "ok" | "error";
preview?: string;
elapsed_ms?: number;
+ /** Live elapsed seconds while the tool is running (heartbeat). */
+ elapsed_s?: number;
+ /**
+ * Structured progress emitted from the tool. All fields optional —
+ * presence of `current`/`total > 0` indicates a determinate progress signal.
+ */
+ progress?: {
+ stage?: string;
+ current?: number;
+ total?: number;
+ message?: string;
+ };
timestamp: number;
}