"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(loaders,i18n): add baostock/tencent A-share sources + zh-CN frontend i18n
Haozhe Wuf470947c8113
diff --git a/agent/backtest/loaders/baostock_loader.py b/agent/backtest/loaders/baostock_loader.pynew file mode 100644index 000000000..b591d95d8--- /dev/null+++ b/agent/backtest/loaders/baostock_loader.py@@ -0,0 +1,145 @@+"""BaoStock loader: free, no-auth A-share data via TCP protocol.++BaoStock (http://baostock.com) uses its own TCP protocol (not HTTP),+bypassing CDN IP blocks that affect HTTP-based data sources like+eastmoney.com. Completely free, no API token required.++Covers: A-shares (SH/SZ), does NOT cover HK/US/crypto.+"""++from __future__ import annotations++import logging+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)+++def _is_a_share(code: str) -> bool:+ return code.upper().endswith((".SZ", ".SH"))+++@register+class DataLoader:+ """BaoStock A-share OHLCV loader (free, TCP protocol, no auth)."""++ name = "baostock"+ markets = {"a_share"}+ requires_auth = False++ def is_available(self) -> bool:+ """Available if baostock is installed."""+ try:+ import baostock # noqa: F401+ return True+ except ImportError:+ return False++ def __init__(self) -> None:+ pass++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch OHLCV data via BaoStock.++ Args:+ codes: Symbol list (e.g. ["601595.SH", "000001.SZ"]).+ start_date: YYYY-MM-DD.+ end_date: YYYY-MM-DD.+ interval: Bar size (only 1D supported).+ fields: Ignored.++ Returns:+ Mapping symbol -> OHLCV DataFrame.+ """+ validate_date_range(start_date, end_date)++ import baostock as bs+ lg = bs.login()+ if lg.error_code != "0":+ logger.error("baostock login failed: %s", lg.error_msg)+ return {}++ result: Dict[str, pd.DataFrame] = {}+ try:+ for code in codes:+ try:+ df = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(bs, code, start_date, end_date),+ )+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc:+ logger.warning("baostock failed for %s: %s", code, exc)+ finally:+ bs.logout()++ return result++ def _fetch_one(+ self, bs, code: str, start_date: str, end_date: str,+ ) -> Optional[pd.DataFrame]:+ """Fetch a single A-share symbol."""+ if not _is_a_share(code):+ return None++ # BaoStock format: sh.601595 or sz.000001+ parts = code.upper().split(".")+ symbol = parts[0]+ suffix = parts[1] if len(parts) > 1 else ""+ if suffix == "SH":+ bs_code = f"sh.{symbol}"+ elif suffix == "SZ":+ bs_code = f"sz.{symbol}"+ else:+ return None++ rs = bs.query_history_k_data_plus(+ bs_code,+ "date,open,high,low,close,volume,amount",+ start_date=start_date,+ end_date=end_date,+ frequency="d",+ adjustflag="2", # 前复权+ )++ if rs.error_code != "0":+ logger.warning("baostock query failed for %s: %s", code, rs.error_msg)+ return None++ rows = []+ while rs.next():+ rows.append(rs.get_row_data())++ if not rows:+ return None++ df = pd.DataFrame(rows, columns=["date", "open", "high", "low", "close", "volume", "amount"])+ df["date"] = pd.to_datetime(df["date"])+ for col in ["open", "high", "low", "close", "volume", "amount"]:+ df[col] = pd.to_numeric(df[col], errors="coerce")++ df = df.rename(columns={"date": "trade_date"})+ df = df.set_index("trade_date").sort_index()+ df = df[["open", "high", "low", "close", "volume"]].dropna(+ subset=["open", "high", "low", "close"]+ )+ return dfdiff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex ec79707ef..5bd263f1a 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -35,6 +35,8 @@ VALID_SOURCES: set[str] = {"okx","yfinance","akshare",+ "baostock",+ "tencent","mootdx","ccxt","futu",@@ -68,6 +70,8 @@ def _ensure_registered() -> None:"backtest.loaders.okx","backtest.loaders.yfinance_loader","backtest.loaders.akshare_loader",+ "backtest.loaders.baostock_loader",+ "backtest.loaders.tencent_loader","backtest.loaders.mootdx_loader","backtest.loaders.ccxt_loader","backtest.loaders.futu",@@ -85,7 +89,7 @@ def _ensure_registered() -> None:# ---------------------------------------------------------------------------FALLBACK_CHAINS: dict[str, list[str]] = {- "a_share": ["tushare", "mootdx", "akshare"],+ "a_share": ["tushare", "mootdx", "baostock", "tencent", "akshare"],"us_equity": ["yfinance", "akshare"],"hk_equity": ["yfinance", "futu", "akshare"],"crypto": ["okx", "ccxt", "yfinance"],diff --git a/agent/backtest/loaders/tencent_loader.py b/agent/backtest/loaders/tencent_loader.pynew file mode 100644index 000000000..4b1d5acb0--- /dev/null+++ b/agent/backtest/loaders/tencent_loader.py@@ -0,0 +1,142 @@+"""Tencent Finance loader: free, no-auth A-share data via HTTP API.++Uses Tencent's ifzq.gtimg.cn API which is not blocked by eastmoney's CDN.+Covers: A-shares (SH/SZ). No API token required.++API format:+ https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=sh601595,day,2026-06-01,2026-06-13,500,qfq+"""++from __future__ import annotations++import json+import logging+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++_BASE_URL = "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get"+++def _is_a_share(code: str) -> bool:+ return code.upper().endswith((".SZ", ".SH"))+++@register+class DataLoader:+ """Tencent Finance A-share OHLCV loader (free, HTTP, no auth)."""++ name = "tencent"+ markets = {"a_share"}+ requires_auth = False++ def is_available(self) -> bool:+ """Always available — uses plain HTTP."""+ return True++ def __init__(self) -> None:+ pass++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ validate_date_range(start_date, end_date)++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ try:+ df = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(code, start_date, end_date),+ )+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc:+ logger.warning("tencent failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str,+ ) -> Optional[pd.DataFrame]:+ if not _is_a_share(code):+ return None++ parts = code.upper().split(".")+ symbol = parts[0]+ suffix = parts[1] if len(parts) > 1 else ""++ if suffix == "SH":+ tencent_code = f"sh{symbol}"+ elif suffix == "SZ":+ tencent_code = f"sz{symbol}"+ else:+ return None++ url = (+ f"{_BASE_URL}?param={tencent_code},day,"+ f"{start_date},{end_date},500,qfq"+ )++ import urllib.request+ req = urllib.request.Request(url, headers={+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",+ "Referer": "https://web.ifzq.gtimg.cn/",+ })+ with urllib.request.urlopen(req, timeout=15) as resp:+ raw = resp.read().decode("utf-8")++ data = json.loads(raw)+ # Response: {"code":0,"data":{"sh601595":{"day":[["2026-06-01","21.32",...], ...]}}}+ stock_data = data.get("data", {})+ if not stock_data:+ return None++ # Get the first (only) key+ stock_key = next(iter(stock_data), None)+ if not stock_key:+ return None++ # Try "day" first, then "qfqday" (forward-adjusted)+ klines = stock_data[stock_key].get("qfqday") or stock_data[stock_key].get("day")+ if not klines:+ return None++ # Each row: ["date", "open", "close", "high", "low", "volume"]+ rows = []+ for k in klines:+ if len(k) >= 6:+ rows.append({+ "trade_date": k[0],+ "open": float(k[1]),+ "close": float(k[2]),+ "high": float(k[3]),+ "low": float(k[4]),+ "volume": float(k[5]),+ })++ if not rows:+ return None++ df = pd.DataFrame(rows)+ df["trade_date"] = pd.to_datetime(df["trade_date"])+ df = df.set_index("trade_date").sort_index()+ df = df[["open", "high", "low", "close", "volume"]].dropna(+ subset=["open", "high", "low", "close"]+ )+ return dfdiff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex b1663a45d..ac9bbb591 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -1037,6 +1037,8 @@ def get_market_data(- "yfinance": HK/US equities (free, e.g. AAPL.US, 700.HK)- "okx": cryptocurrency (free, e.g. BTC-USDT, ETH-USDT)- "tushare": China A-shares (requires TUSHARE_TOKEN, e.g. 000001.SZ)+ - "baostock": China A-shares via TCP protocol, bypasses HTTP CDN blocks (e.g. 000001.SZ, 601595.SH)+ - "tencent": China A-shares via Tencent Finance API (e.g. 000001.SZ, 601595.SH)- "akshare": A-shares, US, HK, futures, forex (free, e.g. 000001.SZ, AAPL.US)- "ccxt": crypto from 100+ exchanges (free, e.g. BTC/USDT)- "auto": auto-detect based on symbol format (with fallback)@@ -1045,7 +1047,7 @@ def get_market_data(codes: List of symbols (e.g. ["AAPL.US", "BTC-USDT", "000001.SZ"]).start_date: Start date (YYYY-MM-DD).end_date: End date (YYYY-MM-DD).- source: Data source ("auto", "yfinance", "okx", "tushare", "akshare", "ccxt").+ source: Data source ("auto", "yfinance", "okx", "tushare", "baostock", "tencent", "akshare", "ccxt").interval: Bar size (1m/5m/15m/30m/1H/4H/1D, default "1D").max_rows: Per-symbol row cap (default 250) so the response stayswithin the MCP token budget. A symbol exceeding it returns andiff --git a/agent/skills/ashare-mootdx/references/a_mootdx_fetcher.py b/agent/skills/ashare-mootdx/references/a_mootdx_fetcher.pynew file mode 100644index 000000000..39633cf88--- /dev/null+++ b/agent/skills/ashare-mootdx/references/a_mootdx_fetcher.py@@ -0,0 +1,83 @@+"""+Mootdx A-Share Data Fetcher — Standard adapter.+Free, no API key, no IP rate limits.++Usage:+ from a_mootdx_fetcher import fetch_daily, fetch_realtime, batch_fetch_daily+"""+from mootdx.quotes import Quotes+import pandas as pd+from typing import Optional, List++FREQ_MAP = {'5min':0,'15min':1,'30min':2,'60min':3,'daily':9,'weekly':5,'monthly':6,'1min':8}++def _get_client():+ return Quotes.factory(market='std')++def _code_to_symbol(code: str) -> tuple:+ code = code.strip().upper()+ if '.' in code:+ parts = code.split('.')+ pure, suffix = parts[0], parts[1].upper()+ market = 1 if suffix in ('SH','1') else 0+ else:+ pure = code+ market = 1 if code[0] in ('6','5','9') else 0+ return market, pure++def fetch_daily(code: str, start_date=None, end_date=None, limit=250) -> pd.DataFrame:+ client = _get_client()+ _, pure = _code_to_symbol(code)+ df = client.bars(symbol=pure, frequency=9, offset=limit)+ if df is None or len(df) == 0:+ return pd.DataFrame()+ if 'datetime' in df.columns:+ df['date'] = pd.to_datetime(df['datetime'])+ df = df.rename(columns={'vol':'volume'})+ cols = [c for c in ['date','open','high','low','close','volume','amount'] if c in df.columns]+ df = df[cols].copy()+ if 'date' in df.columns:+ df = df.set_index('date').sort_index()+ if start_date: df = df[df.index >= pd.Timestamp(start_date)]+ if end_date: df = df[df.index <= pd.Timestamp(end_date)]+ return df++def fetch_realtime(codes: list) -> pd.DataFrame:+ client = _get_client()+ pure_codes = [_code_to_symbol(c)[1] for c in codes]+ df = client.quotes(symbol=pure_codes)+ if df is None or len(df) == 0:+ return pd.DataFrame()+ r = pd.DataFrame()+ r['code'] = df['code']+ r['price'] = df['price']+ r['open'] = df['open']+ r['high'] = df['high']+ r['low'] = df['low']+ r['last_close'] = df['last_close']+ r['change'] = df['price'] - df['last_close']+ r['change_pct'] = ((df['price'] - df['last_close']) / df['last_close'] * 100).round(2)+ r['volume'] = df['vol']+ r['amount'] = df['amount']+ return r++def batch_fetch_daily(codes, limit=250, sleep_sec=0.3):+ import time+ results = {}+ for i, code in enumerate(codes):+ try:+ df = fetch_daily(code, limit=limit)+ if len(df) > 0: results[code] = df+ except: results[code] = pd.DataFrame()+ if i < len(codes) - 1: time.sleep(sleep_sec)+ return results++def get_a_share_list():+ client = _get_client()+ frames = []+ for m in [0, 1]:+ df = client.stocks(market=m)+ if df is not None and len(df) > 0:+ df['market'] = m+ frames.append(df)+ return pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()diff --git a/agent/src/tools/market_data_tool.py b/agent/src/tools/market_data_tool.pyindex 27a5fe0dc..73a8a157c 100644--- a/agent/src/tools/market_data_tool.py+++ b/agent/src/tools/market_data_tool.py@@ -35,7 +35,7 @@ class MarketDataTool(BaseTool):},"source": {"type": "string",- "description": "Data source: auto, yfinance, okx, tushare, akshare, or ccxt.",+ "description": "Data source: auto, yfinance, okx, tushare, baostock, tencent, akshare, or ccxt.","default": "auto",},"interval": {diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex d896c82f5..baf34f60e 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -11,9 +11,12 @@"clsx": "^2.1.0","echarts": "^6.0.0","highlight.js": "^11.11.1",+ "i18next": "^26.3.1",+ "i18next-browser-languagedetector": "^8.2.1","lucide-react": "^0.460.0","react": "^19.0.0","react-dom": "^19.0.0",+ "react-i18next": "^17.0.8","react-markdown": "^9.0.0","react-router-dom": "^7.15.0","rehype-highlight": "^7.0.0",@@ -353,7 +356,6 @@"version": "7.29.7","resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz","integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",- "dev": true,"license": "MIT","engines": {"node": ">=6.9.0"@@ -2823,6 +2825,15 @@"dev": true,"license": "MIT"},+ "node_modules/html-parse-stringify": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",+ "integrity": "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==",+ "license": "MIT",+ "dependencies": {+ "void-elements": "3.1.0"+ }+ },"node_modules/html-url-attributes": {"version": "3.0.1","resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",@@ -2861,6 +2872,43 @@"node": ">= 14"}},+ "node_modules/i18next": {+ "version": "26.3.1",+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.1.tgz",+ "integrity": "sha512-txQqd5EULsqEh9OJqRH15aCaOuy/nLJyhw5EHCSKLKJE1aBbb3Zve2+uQIxgWhPm1QqUQoWyQBm2kfmmIrzkcQ==",+ "funding": [+ {+ "type": "individual",+ "url": "https://www.locize.com/i18next"+ },+ {+ "type": "individual",+ "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"+ },+ {+ "type": "individual",+ "url": "https://www.locize.com"+ }+ ],+ "license": "MIT",+ "peerDependencies": {+ "typescript": "^5 || ^6"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },+ "node_modules/i18next-browser-languagedetector": {+ "version": "8.2.1",+ "resolved": "https://registry.npmjs.org/i18next-browser-languagedetector/-/i18next-browser-languagedetector-8.2.1.tgz",+ "integrity": "sha512-bZg8+4bdmaOiApD7N7BPT9W8MLZG+nPTOFlLiJiT8uzKXFjhxw4v2ierCXOwB5sFDMtuA5G4kgYZ0AznZxQ/cw==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.23.2"+ }+ },"node_modules/iconv-lite": {"version": "0.6.3","resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",@@ -4582,6 +4630,33 @@"react": "^19.2.4"}},+ "node_modules/react-i18next": {+ "version": "17.0.8",+ "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.8.tgz",+ "integrity": "sha512-0ooKbGLU8JXhe1zwpQUWIeXSgLPOfwJmgheWRIUpcoA0CpyabpGhayjdG+/eA5esC1AQ8h2jWpXjJfzQzeDOCw==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.29.2",+ "html-parse-stringify": "^3.0.1",+ "use-sync-external-store": "^1.6.0"+ },+ "peerDependencies": {+ "i18next": ">= 26.2.0",+ "react": ">= 16.8.0",+ "typescript": "^5 || ^6"+ },+ "peerDependenciesMeta": {+ "react-dom": {+ "optional": true+ },+ "react-native": {+ "optional": true+ },+ "typescript": {+ "optional": true+ }+ }+ },"node_modules/react-is": {"version": "17.0.2","resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",@@ -5353,7 +5428,7 @@"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz","integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",- "dev": true,+ "devOptional": true,"license": "Apache-2.0","bin": {"tsc": "bin/tsc",@@ -5495,6 +5570,15 @@"browserslist": ">= 4.21.0"}},+ "node_modules/use-sync-external-store": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",+ "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/util-deprecate": {"version": "1.0.2","resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",@@ -5739,6 +5823,15 @@"url": "https://github.com/sponsors/jonschlinkert"}},+ "node_modules/void-elements": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-3.1.0.tgz",+ "integrity": "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/w3c-xmlserializer": {"version": "5.0.0","resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 3e5561559..f3b58d094 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -15,9 +15,12 @@"clsx": "^2.1.0","echarts": "^6.0.0","highlight.js": "^11.11.1",+ "i18next": "^26.3.1",+ "i18next-browser-languagedetector": "^8.2.1","lucide-react": "^0.460.0","react": "^19.0.0","react-dom": "^19.0.0",+ "react-i18next": "^17.0.8","react-markdown": "^9.0.0","react-router-dom": "^7.15.0","rehype-highlight": "^7.0.0",diff --git a/frontend/src/components/charts/ValidationPanel.tsx b/frontend/src/components/charts/ValidationPanel.tsxindex d99fbaa96..3148c0c94 100644--- a/frontend/src/components/charts/ValidationPanel.tsx+++ b/frontend/src/components/charts/ValidationPanel.tsx@@ -1,3 +1,4 @@+import i18n from '@/i18n';import { cn } from "@/lib/utils";import type { ValidationData } from "@/lib/api";@@ -41,7 +42,7 @@ function MonteCarloSection({ mc }: { mc: NonNullable<ValidationData["monte_carlo<div className="space-y-3"><div className="flex items-center gap-2"><h4 className="text-sm font-semibold">Monte Carlo Permutation Test</h4>- <Badge value={sig ? "Significant" : "Not Significant"} good={sig} />+ <Badge value={sig ? i18n.t("validation.significant") : i18n.t("validation.notSignificant")} good={sig} /></div><p className="text-xs text-muted-foreground">Shuffled trade order {mc.n_simulations.toLocaleString()} times to test if Sharpe is better than random.@@ -170,7 +171,7 @@ export function ValidationPanel({ data }: Props) {const hasWF = !!data.walk_forward;if (!hasMC && !hasBS && !hasWF) {- return <p className="p-8 text-sm text-muted-foreground">No validation data available.</p>;+ return <p className="p-8 text-sm text-muted-foreground">{i18n.t("validation.noData")}</p>;}return (diff --git a/frontend/src/components/chat/MandateProposalCard.tsx b/frontend/src/components/chat/MandateProposalCard.tsxindex b351a7723..3f17231ae 100644--- a/frontend/src/components/chat/MandateProposalCard.tsx+++ b/frontend/src/components/chat/MandateProposalCard.tsx@@ -1,3 +1,4 @@+import i18n from '@/i18n';import { memo, useCallback, useState } from "react";import { ShieldCheck, ShieldAlert, Wallet, OctagonX, SlidersHorizontal, Check, X, Loader2 } from "lucide-react";import { toast } from "sonner";@@ -98,23 +99,23 @@ function ProfileTile({<dl className="mt-2 grid grid-cols-2 gap-x-3 gap-y-1.5 text-[11px]"><div className="col-span-2">- <dt className="text-muted-foreground">Universe</dt>+ <dt className="text-muted-foreground">{i18n.t("mandate.universe")}</dt><dd className="font-medium text-foreground">{formatUniverse(profile.universe)}</dd></div><div>- <dt className="text-muted-foreground">Max order</dt>+ <dt className="text-muted-foreground">{i18n.t("mandate.maxOrder")}</dt><dd className="font-mono font-medium text-foreground">{formatUsd(profile.max_order_usd)}</dd></div><div>- <dt className="text-muted-foreground">Daily cap</dt>+ <dt className="text-muted-foreground">{i18n.t("mandate.dailyCap")}</dt><dd className="font-mono font-medium text-foreground">{profile.daily_trade_cap} trades/day</dd></div><div>- <dt className="text-muted-foreground">Leverage</dt>+ <dt className="text-muted-foreground">{i18n.t("mandate.leverage")}</dt><dd className="font-medium text-foreground">{formatLeverage(profile.leverage)}</dd></div><div>- <dt className="text-muted-foreground">Instruments</dt>+ <dt className="text-muted-foreground">{i18n.t("mandate.instruments")}</dt><dd className="font-medium text-foreground">{profile.instruments.join(", ") || "—"}</dd></div></dl>@@ -260,7 +261,7 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,)}<div className="min-w-0"><p className="text-sm font-semibold text-foreground">- {isReauth ? "Re-authorize connector mandate" : "Connector runtime mandate"}+ {isReauth ? i18n.t("mandate.reauthMandate") : i18n.t("mandate.runtimeMandate")}</p>{proposal.intent_normalized && (<p className="text-xs text-muted-foreground">{proposal.intent_normalized}</p>diff --git a/frontend/src/components/chat/MessageBubble.tsx b/frontend/src/components/chat/MessageBubble.tsxindex adcb1691a..f2aad15b2 100644--- a/frontend/src/components/chat/MessageBubble.tsx+++ b/frontend/src/components/chat/MessageBubble.tsx@@ -1,3 +1,4 @@+import i18n from '@/i18n';import { memo, useState, useCallback } from "react";import { User, XCircle, RefreshCw, Copy, Check } from "lucide-react";import ReactMarkdown from "react-markdown";@@ -23,7 +24,7 @@ function CopyButton({ text }: { text: string }) {<buttononClick={handleCopy}className="absolute top-2 right-2 p-1.5 rounded-md bg-muted/80 hover:bg-muted text-muted-foreground hover:text-foreground opacity-0 group-hover:opacity-100 transition-opacity"- title={copied ? "Copied" : "Copy"}+ title={copied ? i18n.t("messageBubble.copied") : i18n.t("messageBubble.copy")}>{copied ? <Check className="h-3.5 w-3.5 text-success" /> : <Copy className="h-3.5 w-3.5" />}</button>@@ -33,12 +34,12 @@ function CopyButton({ text }: { text: string }) {function getRetryHint(content: string): string {const lower = content.toLowerCase();if (lower.includes("timeout") || lower.includes("timed out")) {- return "Execution timed out. Try simplifying the strategy or reducing the number of assets.";+ return i18n.t("messageBubble.timeoutHint");}if (lower.includes("api") || lower.includes("rate limit") || lower.includes("429") || lower.includes("500") || lower.includes("502") || lower.includes("503")) {- return "API call failed. Please retry later.";+ return i18n.t("messageBubble.apiFailedHint");}- return "Execution failed. Click to retry.";+ return i18n.t("messageBubble.executionFailedHint");}interface Props {diff --git a/frontend/src/components/chat/PineScriptViewer.tsx b/frontend/src/components/chat/PineScriptViewer.tsxindex d75786973..4c977dffb 100644--- a/frontend/src/components/chat/PineScriptViewer.tsx+++ b/frontend/src/components/chat/PineScriptViewer.tsx@@ -1,3 +1,4 @@+import { useTranslation } from 'react-i18next';import { memo, useState, useCallback } from "react";import { X, Copy, Check, ExternalLink } from "lucide-react";@@ -7,6 +8,7 @@ interface Props {}export const PineScriptViewer = memo(function PineScriptViewer({ code, onClose }: Props) {+ const { t } = useTranslation();const [copied, setCopied] = useState(false);const handleCopy = useCallback(async () => {@@ -36,7 +38,7 @@ export const PineScriptViewer = memo(function PineScriptViewer({ code, onClose }{/* Header */}<div className="flex items-center justify-between px-4 py-3 border-b"><div className="flex items-center gap-2">- <span className="text-sm font-semibold">Pine Script v6</span>+ <span className="text-sm font-semibold">{t("pineViewer.pineScript")}</span><span className="text-xs text-muted-foreground">strategy.pine</span></div><div className="flex items-center gap-1.5">@@ -45,7 +47,7 @@ export const PineScriptViewer = memo(function PineScriptViewer({ code, onClose }className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-primary text-primary-foreground hover:opacity-90 transition-opacity">{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}- {copied ? "Copied" : "Copy"}+ {copied ? t("pineViewer.copied") : t("pineViewer.copy")}</button><ahref="https://www.tradingview.com/pine-script-docs/welcome/"@@ -75,7 +77,7 @@ export const PineScriptViewer = memo(function PineScriptViewer({ code, onClose }{/* Footer */}<div className="px-4 py-2.5 border-t bg-muted/30"><p className="text-xs text-muted-foreground">- TradingView Pine Editor → New blank indicator → Paste code → Add to Chart+ {t("pineViewer.footer")}</p></div></div>diff --git a/frontend/src/components/chat/RunCompleteCard.tsx b/frontend/src/components/chat/RunCompleteCard.tsxindex db99d41cc..b99508784 100644--- a/frontend/src/components/chat/RunCompleteCard.tsx+++ b/frontend/src/components/chat/RunCompleteCard.tsx@@ -1,3 +1,4 @@+import { useTranslation } from 'react-i18next';import { memo, useEffect, useState, useCallback } from "react";import { Link } from "react-router-dom";import { BarChart3, Code2, FileText, Loader2 } from "lucide-react";@@ -13,6 +14,7 @@ interface Props {}export const RunCompleteCard = memo(function RunCompleteCard({ msg }: Props) {+ const { t } = useTranslation();const [curve, setCurve] = useState(msg.equityCurve);const [pineCode, setPineCode] = useState<string | null>(null);const [pineLoading, setPineLoading] = useState(false);@@ -80,7 +82,7 @@ export const RunCompleteCard = memo(function RunCompleteCard({ msg }: Props) {className="text-sm text-primary hover:underline inline-flex items-center gap-1.5 font-medium"><BarChart3 className="h-3.5 w-3.5" />- Full Report →+ {t("runComplete.fullReport")}</Link>)}{pineExists && (diff --git a/frontend/src/components/chat/RunnerStatus.tsx b/frontend/src/components/chat/RunnerStatus.tsxindex 68ec26045..64fadc47a 100644--- a/frontend/src/components/chat/RunnerStatus.tsx+++ b/frontend/src/components/chat/RunnerStatus.tsx@@ -1,3 +1,4 @@+import i18n from '@/i18n';import { memo, useCallback, useEffect, useState } from "react";import {Activity,@@ -294,7 +295,7 @@ export const RunnerStatus = memo(function RunnerStatus({ status, unavailable, haaria-expanded={open}><Activity className="h-3 w-3 shrink-0" />- <span className="shrink-0">Connector runtime</span>+ <span className="shrink-0">{i18n.t("runnerStatus.connectorRuntime")}</span><span className="truncate text-muted-foreground">{authorizedCount > 0 ? `${authorizedCount} connected` : "no connector connected"}</span>diff --git a/frontend/src/components/chat/SwarmStatusCard.tsx b/frontend/src/components/chat/SwarmStatusCard.tsxindex 2d9d6b837..a0fdb3cd0 100644--- a/frontend/src/components/chat/SwarmStatusCard.tsx+++ b/frontend/src/components/chat/SwarmStatusCard.tsx@@ -1,3 +1,4 @@+import { useTranslation } from 'react-i18next';import { memo } from "react";import {CheckCircle2,@@ -83,6 +84,7 @@ function runTone(status: SwarmRunStatus["status"]): string {}export const SwarmStatusCard = memo(function SwarmStatusCard({ status }: Props) {+ const { t } = useTranslation();const done = status.agents.filter((agent) => ["done", "failed", "blocked", "cancelled"].includes(agent.status)).length;const total = status.agents.length;const layerTotal = Math.max(status.totalLayers, status.currentLayer + 1, 1);@@ -103,7 +105,7 @@ export const SwarmStatusCard = memo(function SwarmStatusCard({ status }: Props)</div><div className="flex items-center gap-2 text-[11px] text-muted-foreground"><Clock className="h-3 w-3" />- <span>{done}/{total || 0} agents</span>+ <span>{t('swarmStatus.agents', { done, total: total || 0 })}</span></div></div>@@ -116,19 +118,19 @@ export const SwarmStatusCard = memo(function SwarmStatusCard({ status }: Props)ariaLabel="Swarm agent progress"/><div className="text-right font-mono text-[11px] text-muted-foreground">- Layer {layerCurrent}/{layerTotal}+ {t('swarmStatus.layer', { current: layerCurrent, total: layerTotal })}</div></div><div className="mt-3 overflow-x-auto"><div className="min-w-[620px]"><div className="grid grid-cols-[10rem_7rem_9rem_5rem_4rem_minmax(0,1fr)] gap-2 border-b pb-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">- <span>Agent</span>- <span>Status</span>- <span>Tool</span>- <span className="text-right">Time</span>- <span className="text-right">Iters</span>- <span>Output</span>+ <span>{t('swarmStatus.agent')}</span>+ <span>{t('swarmStatus.status')}</span>+ <span>{t('swarmStatus.tool')}</span>+ <span className="text-right">{t('swarmStatus.time')}</span>+ <span className="text-right">{t('swarmStatus.iters')}</span>+ <span>{t('swarmStatus.output')}</span></div><div className="divide-y">{status.agents.map((agent) => (@@ -162,7 +164,7 @@ export const SwarmStatusCard = memo(function SwarmStatusCard({ status }: Props)))}{status.agents.length === 0 && (<div className="py-3 text-xs text-muted-foreground">- Waiting for agent events...+ {t('swarmStatus.waitingForEvents')}</div>)}</div>diff --git a/frontend/src/components/chat/ThinkingTimeline.tsx b/frontend/src/components/chat/ThinkingTimeline.tsxindex 182ab8ce5..60ebb992c 100644--- a/frontend/src/components/chat/ThinkingTimeline.tsx+++ b/frontend/src/components/chat/ThinkingTimeline.tsx@@ -1,3 +1,4 @@+import { useTranslation } from 'react-i18next';import { useState, useEffect, useMemo, memo } from "react";import { ChevronDown, ChevronRight, CheckCircle2, XCircle, Circle, Loader2 } from "lucide-react";import { cn } from "@/lib/utils";@@ -10,10 +11,11 @@ interface Props {}export const ThinkingTimeline = memo(function ThinkingTimeline({ messages, isLatest = false }: Props) {+ const { t } = useTranslation();const [expanded, setExpanded] = useState(isLatest);const toolLabel = (tool?: string): string => {- if (!tool) return "Processing";+ if (!tool) return t('thinking.processing');return localizeToolName(tool);};@@ -56,8 +58,8 @@ export const ThinkingTimeline = memo(function ThinkingTimeline({ messages, isLatconst stepCount = steps.length;const summaryText = isRunning- ? `Running ${toolLabel(latestTool)}...`- : `Done · ${stepCount} steps${totalMs > 0 ? ` · ${(totalMs / 1000).toFixed(1)}s` : ""}`;+ ? `${t('thinking.running')} ${toolLabel(latestTool)}...`+ : `${t('thinking.done')} · ${t('thinking.steps', { count: stepCount })}${totalMs > 0 ? ` · ${(totalMs / 1000).toFixed(1)}s` : ""}`;return (<div className="rounded-lg border border-border/40 bg-muted/5 overflow-hidden">@@ -119,7 +121,7 @@ export const ThinkingTimeline = memo(function ThinkingTimeline({ messages, isLat{/* Duration or status */}{step.status === "running" ? (- <span className="text-[10px] text-primary/60">Running</span>+ <span className="text-[10px] text-primary/60">{t('thinking.running')}</span>) : step.elapsed_ms != null ? (<span className="text-[10px] text-muted-foreground/40 tabular-nums">{(step.elapsed_ms / 1000).toFixed(1)}s</span>) : null}diff --git a/frontend/src/components/chat/WelcomeScreen.tsx b/frontend/src/components/chat/WelcomeScreen.tsxindex e67c5b004..fc5807f72 100644--- a/frontend/src/components/chat/WelcomeScreen.tsx+++ b/frontend/src/components/chat/WelcomeScreen.tsx@@ -1,3 +1,4 @@+import { useTranslation } from "react-i18next";import { Bot, TrendingUp, Globe, Sparkles, Users, UserCircle2, NotebookPen, Landmark } from "lucide-react";interface Example {@@ -173,6 +174,7 @@ interface Props {}export function WelcomeScreen({ onExample }: Props) {+ const { t } = useTranslation();return (<div className="flex flex-col items-center justify-center min-h-[60vh] space-y-8 text-center">{/* Header */}@@ -181,7 +183,7 @@ export function WelcomeScreen({ onExample }: Props) {<Bot className="h-8 w-8 text-white" /></div><div>- <h2 className="text-2xl font-bold tracking-tight">Vibe-Trading</h2>+ <h2 className="text-2xl font-bold tracking-tight">{t('welcome.title')}</h2><p className="text-xs text-muted-foreground mt-1 max-w-sm mx-auto leading-relaxed">vibe trading with your professional financial agent team</p>@@ -205,7 +207,7 @@ export function WelcomeScreen({ onExample }: Props) {{/* Example categories grid */}<div className="w-full max-w-2xl text-left space-y-4">- <p className="text-xs text-muted-foreground px-1">Try an example:</p>+ <p className="text-xs text-muted-foreground px-1">{t('welcome.tryExample')}</p><div className="grid grid-cols-1 sm:grid-cols-2 gap-3">{CATEGORIES.map((cat) => (<div key={cat.label} className="space-y-2">diff --git a/frontend/src/components/common/ErrorBoundary.tsx b/frontend/src/components/common/ErrorBoundary.tsxindex 2a14935e3..2a45cbfdc 100644--- a/frontend/src/components/common/ErrorBoundary.tsx+++ b/frontend/src/components/common/ErrorBoundary.tsx@@ -1,3 +1,4 @@+import i18n from "@/i18n";import { Component, type ReactNode } from "react";import { AlertTriangle } from "lucide-react";@@ -16,7 +17,7 @@ export class ErrorBoundary extends Component<Props, State> {return this.props.fallback ?? (<div className="flex items-center gap-2 p-4 rounded-lg border border-destructive/30 bg-destructive/5 text-sm text-destructive"><AlertTriangle className="h-4 w-4 shrink-0" />- <span>{this.state.error?.message || "Something went wrong"}</span>+ <span>{this.state.error?.message || i18n.t("errorBoundary.somethingWrong")}</span></div>);}diff --git a/frontend/src/components/layout/ConnectionBanner.tsx b/frontend/src/components/layout/ConnectionBanner.tsxindex 8248a30dd..a4e983133 100644--- a/frontend/src/components/layout/ConnectionBanner.tsx+++ b/frontend/src/components/layout/ConnectionBanner.tsx@@ -1,3 +1,4 @@+import { useTranslation } from 'react-i18next';import { WifiOff, RefreshCw } from "lucide-react";import type { SSEStatus } from "@/hooks/useSSE";@@ -7,6 +8,7 @@ interface Props {}export function ConnectionBanner({ status, retryAttempt }: Props) {+ const { t } = useTranslation();if (status === "connected" || status === "disconnected") return null;return (@@ -14,12 +16,12 @@ export function ConnectionBanner({ status, retryAttempt }: Props) {{status === "reconnecting" ? (<><RefreshCw className="h-3.5 w-3.5 animate-spin" />- <span>Connection lost, reconnecting (attempt {retryAttempt || 1})…</span>+ <span>{t('connection.reconnecting', { attempt: retryAttempt || 1 })}</span></>) : (<><WifiOff className="h-3.5 w-3.5" />- <span>Connection lost</span>+ <span>{t('connection.disconnected')}</span></>)}</div>diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex b4b0bcdf0..13c6adf37 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -1,6 +1,7 @@-import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { useEffect, useState } from "react";import { Link, Outlet, useLocation, useSearchParams } from "react-router-dom";-import { Activity, BarChart3, Bot, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2 } from "lucide-react";+import { Activity, BarChart3, Bot, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2 } from "lucide-react";import { cn } from "@/lib/utils";import { useDarkMode } from "@/hooks/useDarkMode";import { api, type SessionItem } from "@/lib/api";@@ -10,16 +11,17 @@ import { ConnectionBanner } from "@/components/layout/ConnectionBanner";// Bump on each release; one place keeps the footer in sync with package.json.const APP_VERSION = "v0.1.9";-const NAV = [- { to: "/", icon: BarChart3, label: "Home" },- { to: "/agent", icon: Bot, label: "Agent" },- { to: "/runtime", icon: Activity, label: "Runtime" },- { to: "/alpha-zoo", icon: Layers, label: "Alpha Zoo" },- { to: "/settings", icon: Settings, label: "Settings" },- { to: "/correlation", icon: BarChart3, label: "Correlation Matrix" },-];-export function Layout() {+ const { t, i18n: i18nHook } = useTranslation();++ const NAV = [+ { to: "/", icon: BarChart3, label: t('layout.home') },+ { to: "/agent", icon: Bot, label: t('layout.agent') },+ { to: "/runtime", icon: Activity, label: t('layout.runtime') },+ { to: "/alpha-zoo", icon: Layers, label: t('layout.alphaZoo') },+ { to: "/settings", icon: Settings, label: t('layout.settings') },+ { to: "/correlation", icon: BarChart3, label: t('layout.correlation') },+ ];const { pathname } = useLocation();const [searchParams] = useSearchParams();const { dark, toggle } = useDarkMode();@@ -119,7 +121,7 @@ export function Layout() {<Linkto="/agent"className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"- title="New Chat"+ title={t('layout.newChat')}><Plus className="h-3.5 w-3.5" /></Link>@@ -133,7 +135,7 @@ export function Layout() {))}</div>) : sessions.length === 0 ? (- <p className="px-3 py-2 text-xs text-muted-foreground/60">No sessions yet</p>+ <p className="px-3 py-2 text-xs text-muted-foreground/60">{t('layout.noSessions')}</p>) : null}{sessions.map((s) => {const isActive = s.session_id === activeSessionId;@@ -176,22 +178,22 @@ export function Layout() {)}{!isRenaming && isDeleting ? (<div className="absolute right-0.5 flex items-center gap-0.5">- <button onClick={() => deleteSession(s.session_id)} className="p-1 text-danger hover:bg-danger/10 rounded text-[10px] font-medium">Confirm</button>- <button onClick={() => setDeleteTarget(null)} className="p-1 text-muted-foreground hover:bg-muted rounded text-[10px]">Cancel</button>+ <button onClick={() => deleteSession(s.session_id)} className="p-1 text-danger hover:bg-danger/10 rounded text-[10px] font-medium">{t('layout.confirm')}</button>+ <button onClick={() => setDeleteTarget(null)} className="p-1 text-muted-foreground hover:bg-muted rounded text-[10px]">{t('layout.cancel')}</button></div>) : !isRenaming ? (<div className="absolute right-1 opacity-0 group-hover:opacity-100 flex items-center gap-0.5 transition-opacity"><buttononClick={(e) => { e.preventDefault(); e.stopPropagation(); setRenameTarget(s.session_id); setRenameValue(s.title || ""); }}className="p-1 text-muted-foreground hover:text-foreground rounded"- title="Rename"+ title={t('layout.rename')}><Pencil className="h-3 w-3" /></button><buttononClick={(e) => { e.preventDefault(); e.stopPropagation(); setDeleteTarget(s.session_id); }}className="p-1 text-muted-foreground hover:text-danger rounded"- title="Delete?"+ title={t('layout.delete')}><Trash2 className="h-3 w-3" /></button>@@ -211,10 +213,10 @@ export function Layout() {<div className={cn("border-t", collapsed ? "p-1 flex flex-col items-center gap-1" : "p-3 space-y-2")}>{collapsed ? (<>- <button onClick={toggle} className="p-1.5 text-muted-foreground hover:text-foreground rounded transition-colors" title={dark ? "Light" : "Dark"}>+ <button onClick={toggle} className="p-1.5 text-muted-foreground hover:text-foreground rounded transition-colors" title={dark ? t('layout.light') : t('layout.dark')}>{dark ? <Sun className="h-3.5 w-3.5" /> : <Moon className="h-3.5 w-3.5" />}</button>- <button onClick={() => setCollapsed(false)} className="p-1.5 text-muted-foreground hover:text-foreground rounded transition-colors" title="Expand">+ <button onClick={() => setCollapsed(false)} className="p-1.5 text-muted-foreground hover:text-foreground rounded transition-colors" title={t('layout.expand')}><ChevronsRight className="h-3.5 w-3.5" /></button></>@@ -232,13 +234,22 @@ export function Layout() {<buttononClick={() => setCollapsed(true)}className="p-1 text-muted-foreground hover:text-foreground rounded transition-colors"- title="Collapse"+ title={t('layout.collapse')}><ChevronsLeft className="h-3.5 w-3.5" /></button></div></div>- <p className="text-xs text-muted-foreground/60">{APP_VERSION}</p>+ <div className="flex items-center justify-between">+ <button+ onClick={() => { i18nHook.changeLanguage(i18nHook.language === "zh-CN" ? "en" : "zh-CN"); }}+ className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ <Languages className="h-3.5 w-3.5" />+ {i18nHook.language === "zh-CN" ? "English" : "中文"}+ </button>+ <p className="text-xs text-muted-foreground/60">{APP_VERSION}</p>+ </div></>)}</div>diff --git a/frontend/src/i18n/index.ts b/frontend/src/i18n/index.tsnew file mode 100644index 000000000..bd18bb974--- /dev/null+++ b/frontend/src/i18n/index.ts@@ -0,0 +1,26 @@+import i18n from "i18next";+import { initReactI18next } from "react-i18next";+import LanguageDetector from "i18next-browser-languagedetector";+import en from "./locales/en.json";+import zhCN from "./locales/zh-CN.json";++i18n+ .use(LanguageDetector)+ .use(initReactI18next)+ .init({+ resources: {+ en: { translation: en },+ "zh-CN": { translation: zhCN },+ },+ // Default to English for everyone on first visit; only an explicit toggle+ // (persisted to localStorage) switches to Chinese. We intentionally do NOT+ // read `navigator` so a zh browser is not auto-switched away from English.+ fallbackLng: "en",+ interpolation: { escapeValue: false },+ detection: {+ order: ["localStorage"],+ caches: ["localStorage"],+ },+ });++export default i18n;diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonnew file mode 100644index 000000000..ba464d826--- /dev/null+++ b/frontend/src/i18n/locales/en.json@@ -0,0 +1,520 @@+{+ "app": {+ "version": "v0.1.9"+ },+ "layout": {+ "home": "Home",+ "agent": "Agent",+ "runtime": "Runtime",+ "alphaZoo": "Alpha Zoo",+ "settings": "Settings",+ "correlation": "Correlation Matrix",+ "sessions": "Sessions",+ "newChat": "New Chat",+ "noSessions": "No sessions yet",+ "confirm": "Confirm",+ "cancel": "Cancel",+ "rename": "Rename",+ "delete": "Delete",+ "light": "Light",+ "dark": "Dark",+ "collapse": "Collapse",+ "expand": "Expand"+ },+ "runtime": {+ "monitorBadge": "Runtime Monitor",+ "title": "Live / Paper Runtime Status",+ "subtitlePre": "Read-only status from",+ "subtitlePost": ". This page does not authorize connectors, start runners, stop runners, submit orders, cancel orders, or change mandates.",+ "refresh": "Refresh",+ "unavailableTitle": "Runtime status unavailable",+ "unavailableHint": "Treat connector runtime as unavailable until the backend provides a current status snapshot.",+ "statusUnavailable": "Runtime status unavailable.",+ "globalHalt": "Global Halt",+ "halted": "Halted",+ "clear": "Clear",+ "brokers": "Brokers",+ "authorized": "Authorized",+ "runners": "Runners",+ "running": "{{count}} running",+ "noProfilesTitle": "No runtime profiles reported",+ "noProfilesBody": "The backend did not return any recognized live or paper broker profiles.",+ "authPresent": "auth present",+ "authMissing": "auth missing",+ "runnerAlive": "runner alive",+ "runnerStopped": "runner stopped",+ "haltedPill": "halted",+ "recognizedProfile": "Recognized connector profile",+ "unknownProfile": "Unknown connector profile",+ "lastTick": "Last tick",+ "authorization": "Authorization",+ "oauthToken": "OAuth token",+ "present": "present",+ "missing": "missing",+ "profileType": "Profile type",+ "recognized": "recognized",+ "unknown": "unknown",+ "mandate": "Mandate",+ "account": "Account",+ "unrecorded": "unrecorded",+ "expiry": "Expiry",+ "expired": "expired",+ "limits": "Limits",+ "noMandate": "No active mandate reported.",+ "riskStateTitle": "Runtime Risk State",+ "riskHalted": "risk halted",+ "riskHaltedDesc": "The kill switch is tripped for this profile. Treat connector runtime as stopped until status clears.",+ "riskActive": "runtime active",+ "riskActiveDesc": "Runner is alive and an unexpired mandate is present. This page is still read-only status only.",+ "riskIdle": "ready but idle",+ "riskIdleDesc": "Authorization and mandate are present, but the runner is not alive.",+ "riskDormant": "dormant",+ "riskDormantDesc": "Connector runtime is not ready for autonomous operation because authorization, mandate, or runner liveness is missing.",+ "limitsUnavailable": "limits unavailable",+ "perOrder": "/order",+ "exposure": "exposure",+ "perDay": "/day",+ "leverageSuffix": "x leverage",+ "never": "never",+ "ago": "ago"+ },+ "connection": {+ "reconnecting": "Connection lost, reconnecting (attempt {{attempt}})…",+ "disconnected": "Connection lost"+ },+ "welcome": {+ "title": "Vibe-Trading",+ "subtitle": "vibe trading with your professional financial agent team",+ "describePrompt": "Describe a trading strategy to get started.",+ "tryExample": "Try an example:",+ "categories": {+ "multiMarketBacktest": "Multi-Market Backtest",+ "researchAnalysis": "Research & Analysis",+ "swarmTeams": "Swarm Teams",+ "docWebResearch": "Document & Web Research",+ "tradeJournal": "Trade Journal",+ "tradingConnectors": "Trading Connectors",+ "shadowAccount": "Shadow Account"+ },+ "examples": {+ "crossMarketPortfolio": "Cross-Market Portfolio",+ "crossMarketPortfolioDesc": "A-shares + crypto + US equities with risk-parity optimizer",+ "btcMacd": "BTC 5-Min MACD Strategy",+ "btcMacdDesc": "Minute-level crypto backtest with real-time OKX data",+ "usTechMaxDiv": "US Tech Max Diversification",+ "usTechMaxDivDesc": "Portfolio optimizer across FAANG+ via yfinance",+ "multiFactorAlpha": "Multi-Factor Alpha Model",+ "multiFactorAlphaDesc": "IC-weighted factor synthesis across 300 stocks",+ "optionsGreeks": "Options Greeks Analysis",+ "optionsGreeksDesc": "Black-Scholes pricing with Delta/Gamma/Theta/Vega",+ "investmentCommittee": "Investment Committee Review",+ "investmentCommitteeDesc": "Multi-agent debate: long vs short, risk review, PM decision",+ "quantStrategyDesk": "Quant Strategy Desk",+ "quantStrategyDeskDesc": "Screening → factor research → backtest → risk audit pipeline",+ "earningsReport": "Analyze an Earnings Report PDF",+ "earningsReportDesc": "Upload a PDF and ask questions about the financials",+ "macroResearch": "Web Research: Macro Outlook",+ "macroResearchDesc": "Read live web sources for macro analysis",+ "analyzeBrokerExport": "Analyze My Broker Export",+ "analyzeBrokerExportDesc": "Parse 同花顺/东财/富途/generic CSV — holding days, win rate, PnL ratio, hourly distribution",+ "diagnoseBehavior": "Diagnose My Behavior Biases",+ "diagnoseBehaviorDesc": "Disposition effect, overtrading, chasing momentum, anchoring — severity + numeric evidence",+ "checkConnector": "Check Selected Connector",+ "checkConnectorDesc": "List connector profiles and verify the selected one",+ "analyzePortfolio": "Analyze Connector Portfolio",+ "analyzePortfolioDesc": "Read account summary and positions from the selected connector",+ "quoteTrend": "Quote & Trend",+ "quoteTrendDesc": "Fetch a quote plus recent daily bars through the selected connector",+ "trainShadow": "Train My Shadow from Journal",+ "trainShadowDesc": "Extract your strategy rules from a broker CSV and persist a Shadow profile",+ "shadowDelta": "How Much Am I Leaving on the Table?",+ "shadowDeltaDesc": "Backtest your shadow strategy and attribute delta vs. your actual PnL",+ "shadowReport": "Generate Shadow Report",+ "shadowReportDesc": "8-section HTML/PDF — equity curve, per-market Sharpe, attribution waterfall"+ },+ "capabilities": {+ "financeSkills": "Finance Skills Library",+ "swarmTeams": "Swarm Agent Teams",+ "autoTools": "Auto-Discovered Tools",+ "markets": "3 Markets: A-Share · Crypto · HK/US",+ "connectors": "Trading Connector Profiles",+ "timeframes": "Minute to Daily Timeframes",+ "optimizers": "4 Portfolio Optimizers",+ "riskMetrics": "15+ Risk Metrics",+ "options": "Options & Derivatives",+ "pdfWeb": "PDF & Web Research",+ "factorML": "Factor Analysis & ML",+ "journalAnalyzer": "Trade Journal Analyzer",+ "shadowBacktest": "Shadow Account Backtest",+ "memory": "Persistent Memory",+ "sessionSearch": "Session Search"+ }+ },+ "settings": {+ "title": "Settings",+ "authRequired": "Authentication Required",+ "authDesc": "Enter the API auth key to unlock settings.",+ "dataSources": "Data Sources",+ "llmBackend": "LLM Backend",+ "save": "Save",+ "saving": "Saving…",+ "saved": "Settings saved",+ "saveFailed": "Failed to save",+ "provider": "Provider",+ "refresh": "Refresh",+ "modelName": "Model Name",+ "baseUrl": "Base URL",+ "apiAuthKey": "API Auth Key",+ "loading": "Loading…",+ "temperature": "Temperature",+ "timeoutSeconds": "Timeout (seconds)",+ "maxRetries": "Max Retries",+ "reasoningEffort": "Reasoning Effort",+ "useDefaultModel": "Use default model",+ "useDefaultUrl": "Use default URL",+ "dataSourcesDesc": "Configure external data sources for the backtesting engine.",+ "tushareDesc": "China A-share historical data (requires TUSHARE_TOKEN env var).",+ "baostockDesc": "Alternative A-share data via TCP protocol (no API key needed).",+ "status": "Status",+ "installed": "Installed",+ "notInstalled": "Not installed",+ "token": "Token",+ "tokenConfigured": "Token configured",+ "tokenNotSet": "TUSHARE_TOKEN env var not set",+ "apiTimeout": "API request timeout",+ "loaderAvailable": "Loader available",+ "noProjectLoader": "No project loader",+ "pythonPackageInstalled": "Python package installed",+ "pythonPackageNotInstalled": "Python package not installed"+ },+ "agent": {+ "connectionLostReconnect": "Connection lost, reconnecting…",+ "connectionRestored": "Connection restored",+ "agentWorking": "Agent is working…",+ "reasoning": "Reasoning…",+ "running": "running",+ "newMessages": "New messages",+ "newResearchGoal": "New Research Goal",+ "goal": "Goal",+ "criteria": "Criteria",+ "evidence": "Evidence",+ "recentEvidence": "Recent Evidence",+ "continue": "Continue",+ "edit": "Edit",+ "cancel": "Cancel",+ "save": "Save",+ "cancelGoal": "Cancel goal",+ "describeGoal": "Describe the research goal to attach to this session",+ "placeholder": "e.g. Create a dual MA crossover strategy for 000001.SZ, backtest 2024",+ "exportChat": "Export chat",+ "stopGeneration": "Stop generation",+ "runSwarmTeam": "Run swarm team",+ "uploadFile": "Upload file",+ "checkConnector": "Check connector",+ "analyzePortfolio": "Analyze connector portfolio",+ "executionTimedOut": "Execution timed out, automatically stopped",+ "researchGoalAttached": "Research goal attached",+ "failedToStartGoal": "Failed to start goal.",+ "researchGoalCancelled": "Research goal cancelled",+ "failedToCancelGoal": "Failed to cancel goal.",+ "researchGoalUpdated": "Research goal updated",+ "failedToUpdateGoal": "Failed to update goal.",+ "failedToLoadGoal": "Failed to load goal.",+ "cancelRequestSent": "Cancel request sent",+ "cancelFailed": "Cancel failed",+ "connectorHalted": "Connector runtime halted",+ "failedToHaltConnector": "Failed to halt connector runtime.",+ "cancelledFromUI": "Cancelled from Web UI.",+ "executablesNotAllowed": "Executables and archives are not allowed",+ "fileSizeExceeds": "File size exceeds 50 MB limit",+ "uploaded": "Uploaded: {{filename}}",+ "uploadFailed": "Upload failed: {{error}}",+ "failedToSend": "Failed to send message, please retry.",+ "failedToContinue": "Failed to continue goal, please retry."+ },+ "runDetail": {+ "title": "Run Detail",+ "runNotFound": "Run not found",+ "runNotFoundDesc": "The run directory may have been removed, or your browser may not have API access configured. Check that the API authentication key is set in Settings if accessing remotely.",+ "goBack": "Go back",+ "chart": "Chart",+ "trades": "Trades",+ "validation": "Validation",+ "runCard": "Run Card",+ "code": "Code",+ "downloadTradesCsv": "Download Trades CSV",+ "downloadMetricsCsv": "Download Metrics CSV",+ "noChartData": "No chart data available",+ "noChartDataDesc": "The backtest engine may not have generated price data. Check the artifacts/ directory.",+ "equityDrawdown": "Equity & Drawdown",+ "noTrades": "No trades recorded.",+ "time": "Time",+ "code2": "Code",+ "side": "Side",+ "price": "Price",+ "qty": "Qty",+ "reason": "Reason",+ "schema": "Schema",+ "generated": "Generated",+ "dataSources": "Data sources",+ "warnings": "Warnings",+ "backtestSummary": "Backtest Summary",+ "reproducibility": "Reproducibility",+ "metrics": "Metrics",+ "validationPayload": "Validation",+ "artifactChecksums": "Artifact Checksums",+ "path": "Path",+ "size": "Size",+ "sha256": "SHA-256",+ "noBacktestSummary": "No backtest summary recorded.",+ "noReproducibilityHashes": "No reproducibility hashes recorded.",+ "noScalarMetrics": "No scalar metrics recorded.",+ "noValidationPayload": "No validation payload recorded.",+ "noArtifactChecksums": "No artifact checksums recorded.",+ "noCodeFiles": "No code files.",+ "fullReport": "Full Report →"+ },+ "compare": {+ "title": "Strategy Comparison",+ "baseline": "Baseline",+ "compare": "Compare",+ "select": "-- Select --",+ "equityDrawdown": "Equity & Drawdown",+ "metric": "Metric",+ "baselineCol": "Baseline",+ "compareCol": "Compare",+ "delta": "Delta",+ "selectTwoRuns": "Select two runs to compare their metrics.",+ "totalReturn": "Total Return",+ "annualizedReturn": "Annualized Return",+ "sharpeRatio": "Sharpe Ratio",+ "calmarRatio": "Calmar Ratio",+ "sortinoRatio": "Sortino Ratio",+ "maxDrawdown": "Max Drawdown",+ "volatility": "Volatility",+ "winRate": "Win Rate",+ "profitFactor": "Profit Factor",+ "avgWin": "Avg Win",+ "avgLoss": "Avg Loss",+ "trades": "Trades",+ "maxConsecLosses": "Max Consec. Losses",+ "exposureTime": "Exposure Time",+ "avgHoldingPeriod": "Avg Holding Period"+ },+ "correlation": {+ "title": "Correlation Matrix",+ "assetCodes": "Asset codes",+ "assetCodesHint": "Comma-separated ticker symbols, e.g. BTC-USDT,ETH-USDT,AAPL,SPY",+ "windowDays": "Window (days)",+ "method": "Method",+ "compute": "Compute",+ "loading": "Loading..."+ },+ "alphaZoo": {+ "title": "Alpha Zoo",+ "prebuiltAlpha": "{{count}} pre-built quant alphas across 4 zoos",+ "browseDesc": "Browse formula-driven cross-sectional signals from Qlib, the Kakushadze 101 set, GTJA 191, and the academic anomaly literature. Click any alpha to read its formula and source code, or run a bench to score the whole zoo on a universe and period.",+ "search": "Search",+ "searchPlaceholder": "Filter by id or nickname…",+ "zoo": "Zoo",+ "allZoos": "All zoos",+ "theme": "Theme",+ "allThemes": "All themes",+ "universe": "Universe",+ "allUniverses": "All universes",+ "compare": "Compare",+ "runBenchmark": "Run benchmark",+ "decayDays": "Decay (days)",+ "selectForCompare": "Select for compare",+ "loadingAlphas": "Loading alphas…",+ "noAlphasMatch": "No alphas match the current filters.",+ "showingOf": "Showing {{visible}} of {{total}}",+ "loadMore": "Load more",+ "backToAlphaZoo": "Back to Alpha Zoo",+ "couldNotLoad": "Could not load alpha",+ "unknownError": "Unknown error",+ "formula": "Formula",+ "noFormula": "(no formula provided)",+ "metadata": "Metadata",+ "themeKey": "Theme",+ "frequency": "Frequency",+ "decayHorizon": "Decay horizon",+ "minWarmupBars": "Min warm-up bars",+ "requiresSector": "Requires sector",+ "modulePath": "Module path",+ "notes": "Notes",+ "sourceCode": "Source code",+ "viewSource": "View source ({{lines}} lines)",+ "noSource": "(no source available)",+ "benchRunner": "Benchmark runner",+ "scoreZoo": "Score a zoo on a universe",+ "scoreDesc": "Computes IC / IR for every alpha in the selected zoo over the chosen universe and period, then bucketizes them as alive / reversed / dead.",+ "period": "Period",+ "top": "Top",+ "running": "Running…",+ "submitting": "Submitting…",+ "computing": "Computing: {{id}}",+ "alive": "Alive",+ "reversed": "Reversed",+ "dead": "Dead",+ "skipped": "Skipped",+ "topByIr": "Top 5 by IR",+ "mostReversed": "Most reversed",+ "byTheme": "By theme",+ "noRows": "No rows.",+ "meanIc": "Mean IC",+ "ir": "IR",+ "category": "Category",+ "headToHeadCompare": "Head-to-head compare",+ "compareAlphas": "Compare alphas side by side",+ "compareDesc": "Benches just the alphas you pick on a universe and period, then ranks them by IC / IR with the gap to the leader — far faster than benching a whole zoo when you only care about a shortlist.",+ "alphaIds": "Alpha ids",+ "selected": "{{count}} selected",+ "alphaIdsHint": "Separate ids with commas or spaces. Tip: tick alphas in the catalogue and hit \"Compare\" to prefill this.",+ "rankBy": "Rank by",+ "pickAtLeast2": "Pick at least 2 alphas.",+ "enterAtLeast2": "Enter at least 2 distinct alpha ids to compare.",+ "winner": "Winner",+ "compared": "compared",+ "rankedBy": "ranked by",+ "icMean": "IC mean",+ "icStd": "IC std",+ "icPositive": "IC>0",+ "icPositiveTitle": "Share of periods with positive IC",+ "sampleCount": "n",+ "sampleCountTitle": "IC sample count",+ "noBenchmarkMatch": "No benchmark match"+ },+ "validation": {+ "noData": "No validation data available.",+ "monteCarlo": "Monte Carlo Permutation Test",+ "significant": "Significant",+ "notSignificant": "Not Significant",+ "monteCarloDesc": "Shuffled trade order {{n}} times to test if Sharpe is better than random.",+ "actualSharpe": "Actual Sharpe",+ "pValueSharpe": "p-value (Sharpe)",+ "simulatedMean": "Simulated Mean",+ "simulatedRange": "Simulated 90% Range",+ "bootstrap": "Bootstrap Sharpe CI",+ "ciAbove0": "CI > 0",+ "ciIncludes0": "CI includes 0",+ "bootstrapDesc": "Resampled daily returns {{n}} times to estimate {{pct}} confidence interval.",+ "observedSharpe": "Observed Sharpe",+ "ci": "{{pct}} CI",+ "medianSharpe": "Median Sharpe",+ "probSharpePositive": "P(Sharpe > 0)",+ "walkForward": "Walk-Forward Analysis",+ "profitable": "{{profitable}}/{{total}} profitable",+ "walkForwardDesc": "Split into {{n}} sequential windows to check performance consistency.",+ "consistency": "Consistency",+ "avgReturn": "Avg Return",+ "avgSharpe": "Avg Sharpe",+ "windows": "Windows",+ "period2": "Period",+ "return": "Return",+ "maxDd": "Max DD",+ "winRate": "Win Rate"+ },+ "thinking": {+ "processing": "Processing",+ "running": "Running",+ "done": "Done",+ "steps": "{{count}} steps"+ },+ "runnerStatus": {+ "connectorRuntime": "Connector runtime",+ "connected": "{{count}} connected",+ "noConnector": "no connector connected",+ "running": "running",+ "halted": "halted",+ "authorized": "Authorized",+ "notConnected": "Not connected",+ "connectProfile": "Connect this profile to enable connector runtime",+ "authorizeNote": "The connector channel stays read-only until OAuth succeeds and a mandate is committed.",+ "runner": "Runner",+ "runnerRunning": "Running",+ "runnerStopped": "Stopped",+ "lastTick": "Last tick",+ "activeMandate": "Active mandate",+ "expiresIn": "expires in {{time}}",+ "expired": "expired",+ "limitsUnavailable": "limits unavailable",+ "noActiveMandate": "No active mandate. Ask the agent to propose one, then commit it before starting the connector runtime.",+ "haltedControlsDisabled": "Halted — runner controls disabled",+ "runtimeActive": "Runtime active inside mandate",+ "idle": "Idle",+ "stopRunner": "Stop runner",+ "startRunner": "Start runner",+ "never": "never",+ "unknown": "unknown",+ "justNow": "just now",+ "loadingInstructions": "Loading connector authorization instructions..."+ },+ "swarmStatus": {+ "agents": "{{done}}/{{total}} agents",+ "layer": "Layer {{current}}/{{total}}",+ "agent": "Agent",+ "status": "Status",+ "tool": "Tool",+ "time": "Time",+ "iters": "Iters",+ "output": "Output",+ "waitingForEvents": "Waiting for agent events..."+ },+ "mandate": {+ "runtimeMandate": "Connector runtime mandate",+ "reauthMandate": "Re-authorize connector mandate",+ "universe": "Universe",+ "maxOrder": "Max order",+ "dailyCap": "Daily cap",+ "leverage": "Leverage",+ "instruments": "Instruments",+ "adjust": "Adjust",+ "committing": "Committing…",+ "commit": "Commit \"{{label}}\"",+ "cancel": "Cancel",+ "sendAdjustment": "Send adjustment",+ "mandateActive": "Mandate {{id}} active",+ "fundedBy": "funded by",+ "noBroker": "Cannot commit mandate: connector broker is missing. Ask the agent to regenerate the proposal.",+ "failedToCommit": "Failed to commit mandate.",+ "noLeverage": "no leverage",+ "leverageValue": "{{value}}× leverage",+ "tradesPerDay": "{{count}} trades/day"+ },+ "messageBubble": {+ "copied": "Copied",+ "copy": "Copy",+ "timeoutHint": "Execution timed out. Try simplifying the strategy or reducing the number of assets.",+ "apiFailedHint": "API call failed. Please retry later.",+ "executionFailedHint": "Execution failed. Click to retry."+ },+ "pineViewer": {+ "pineScript": "Pine Script v6",+ "copied": "Copied",+ "copy": "Copy",+ "docs": "Docs",+ "footer": "TradingView Pine Editor → New blank indicator → Paste code → Add to Chart"+ },+ "runComplete": {+ "fullReport": "Full Report →",+ "pineScript": "Pine Script",+ "shadowReport": "Shadow Report"+ },+ "home": {+ "title": "AI-Powered Quant Strategy Research",+ "subtitle": "Describe a trading strategy in natural language. The agent generates code, runs backtests, and optimizes — all in real time.",+ "startResearch": "Start Research",+ "featureAgent": "AI Agent",+ "featureAgentDesc": "Natural language strategy generation with ReAct reasoning",+ "featureBacktest": "Built-in Backtest",+ "featureBacktestDesc": "7 data sources across A-shares, US/HK & Crypto",+ "featureStreaming": "Real-time Streaming",+ "featureStreamingDesc": "Watch the agent think, call tools, and iterate",+ "featureReplay": "Strategy Replay",+ "featureReplayDesc": "Trade journal analyzer + Shadow Account — extract your rules, backtest them, attribute PnL delta"+ },+ "errorBoundary": {+ "somethingWrong": "Something went wrong"+ }+}diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonnew file mode 100644index 000000000..1c66b8274--- /dev/null+++ b/frontend/src/i18n/locales/zh-CN.json@@ -0,0 +1,520 @@+{+ "app": {+ "version": "v0.1.9"+ },+ "layout": {+ "home": "首页",+ "agent": "智能体",+ "runtime": "运行时",+ "alphaZoo": "Alpha 动物园",+ "settings": "设置",+ "correlation": "相关性矩阵",+ "sessions": "会话",+ "newChat": "新建对话",+ "noSessions": "暂无会话",+ "confirm": "确认",+ "cancel": "取消",+ "rename": "重命名",+ "delete": "删除",+ "light": "亮色",+ "dark": "暗色",+ "collapse": "收起",+ "expand": "展开"+ },+ "runtime": {+ "monitorBadge": "运行时监控",+ "title": "实盘 / 模拟运行时状态",+ "subtitlePre": "只读状态,来自",+ "subtitlePost": "。本页面不会授权连接器、启动或停止 runner、提交或撤销订单,也不会修改 mandate。",+ "refresh": "刷新",+ "unavailableTitle": "运行时状态不可用",+ "unavailableHint": "在后端提供最新状态快照前,请将连接器运行时视为不可用。",+ "statusUnavailable": "运行时状态不可用。",+ "globalHalt": "全局熔断",+ "halted": "已熔断",+ "clear": "正常",+ "brokers": "券商",+ "authorized": "已授权",+ "runners": "Runner",+ "running": "{{count}} 个运行中",+ "noProfilesTitle": "未报告任何运行时档案",+ "noProfilesBody": "后端未返回任何已识别的实盘或模拟券商档案。",+ "authPresent": "已授权",+ "authMissing": "未授权",+ "runnerAlive": "runner 存活",+ "runnerStopped": "runner 已停止",+ "haltedPill": "已熔断",+ "recognizedProfile": "已识别的连接器档案",+ "unknownProfile": "未知连接器档案",+ "lastTick": "最后心跳",+ "authorization": "授权",+ "oauthToken": "OAuth 令牌",+ "present": "存在",+ "missing": "缺失",+ "profileType": "档案类型",+ "recognized": "已识别",+ "unknown": "未知",+ "mandate": "Mandate",+ "account": "账户",+ "unrecorded": "未记录",+ "expiry": "到期",+ "expired": "已过期",+ "limits": "限额",+ "noMandate": "未报告活跃 mandate。",+ "riskStateTitle": "运行时风险状态",+ "riskHalted": "风险熔断",+ "riskHaltedDesc": "该档案的熔断开关已触发。在状态恢复前请将连接器运行时视为已停止。",+ "riskActive": "运行时活跃",+ "riskActiveDesc": "Runner 存活且存在未过期的 mandate。本页面仍仅为只读状态。",+ "riskIdle": "就绪但空闲",+ "riskIdleDesc": "授权与 mandate 均存在,但 runner 未存活。",+ "riskDormant": "休眠",+ "riskDormantDesc": "由于缺少授权、mandate 或 runner 存活状态,连接器运行时尚未就绪以进行自主运行。",+ "limitsUnavailable": "限额不可用",+ "perOrder": "/单",+ "exposure": "敞口",+ "perDay": "/日",+ "leverageSuffix": "倍杠杆",+ "never": "从未",+ "ago": "前"+ },+ "connection": {+ "reconnecting": "连接已断开,正在重连(第 {{attempt}} 次)…",+ "disconnected": "连接已断开"+ },+ "welcome": {+ "title": "Vibe-Trading",+ "subtitle": "与你的专业金融智能体团队一起进行 vibe trading",+ "describePrompt": "描述一个交易策略即可开始。",+ "tryExample": "试试示例:",+ "categories": {+ "multiMarketBacktest": "多市场回测",+ "researchAnalysis": "研究与分析",+ "swarmTeams": "群体智能团队",+ "docWebResearch": "文档与网络研究",+ "tradeJournal": "交易日志",+ "tradingConnectors": "交易连接器",+ "shadowAccount": "影子账户"+ },+ "examples": {+ "crossMarketPortfolio": "跨市场组合",+ "crossMarketPortfolioDesc": "A股 + 加密货币 + 美股,风险平价优化器",+ "btcMacd": "BTC 5分钟 MACD 策略",+ "btcMacdDesc": "基于 OKX 实时数据的分钟级加密货币回测",+ "usTechMaxDiv": "美股科技最大分散化",+ "usTechMaxDivDesc": "通过 yfinance 对 FAANG+ 进行投资组合优化",+ "multiFactorAlpha": "多因子 Alpha 模型",+ "multiFactorAlphaDesc": "对 300 只股票进行 IC 加权因子合成",+ "optionsGreeks": "期权希腊字母分析",+ "optionsGreeksDesc": "Black-Scholes 定价,Delta/Gamma/Theta/Vega 分析",+ "investmentCommittee": "投资委员会评审",+ "investmentCommitteeDesc": "多智能体辩论:多头 vs 空头,风险审查,投资经理决策",+ "quantStrategyDesk": "量化策略工作台",+ "quantStrategyDeskDesc": "筛选 → 因子研究 → 回测 → 风险审计流水线",+ "earningsReport": "分析财报 PDF",+ "earningsReportDesc": "上传 PDF 并询问财务问题",+ "macroResearch": "网络研究:宏观经济展望",+ "macroResearchDesc": "阅读最新网络来源进行宏观分析",+ "analyzeBrokerExport": "分析券商导出数据",+ "analyzeBrokerExportDesc": "解析同花顺/东财/富途/通用 CSV —— 持仓天数、胜率、盈亏比、小时分布",+ "diagnoseBehavior": "诊断行为偏差",+ "diagnoseBehaviorDesc": "处置效应、过度交易、追涨动量、锚定效应 —— 严重程度 + 数值证据",+ "checkConnector": "检查已选连接器",+ "checkConnectorDesc": "列出连接器配置并验证当前选择",+ "analyzePortfolio": "分析连接器投资组合",+ "analyzePortfolioDesc": "从已选连接器读取账户摘要和持仓",+ "quoteTrend": "报价与趋势",+ "quoteTrendDesc": "通过已选连接器获取报价和近 30 日日线数据",+ "trainShadow": "从日志训练影子账户",+ "trainShadowDesc": "从券商 CSV 提取策略规则并持久化影子账户配置",+ "shadowDelta": "我少赚了多少?",+ "shadowDeltaDesc": "回测影子策略并与实际盈亏进行归因分析",+ "shadowReport": "生成影子报告",+ "shadowReportDesc": "8 章节 HTML/PDF —— 净值曲线、按市场夏普比率、归因瀑布图"+ },+ "capabilities": {+ "financeSkills": "金融技能库",+ "swarmTeams": "群体智能团队",+ "autoTools": "自动发现工具",+ "markets": "3 大市场:A股 · 加密货币 · 港美股",+ "connectors": "交易连接器配置",+ "timeframes": "分钟级到日线级时间框架",+ "optimizers": "4 种投资组合优化器",+ "riskMetrics": "15+ 风险指标",+ "options": "期权与衍生品",+ "pdfWeb": "PDF 与网络研究",+ "factorML": "因子分析与机器学习",+ "journalAnalyzer": "交易日志分析器",+ "shadowBacktest": "影子账户回测",+ "memory": "持久化记忆",+ "sessionSearch": "会话搜索"+ }+ },+ "settings": {+ "title": "设置",+ "authRequired": "需要认证",+ "authDesc": "请输入 API 认证密钥以解锁设置。",+ "dataSources": "数据源",+ "llmBackend": "LLM 后端",+ "save": "保存",+ "saving": "保存中…",+ "saved": "设置已保存",+ "saveFailed": "保存失败",+ "provider": "提供商",+ "refresh": "刷新",+ "modelName": "模型名称",+ "baseUrl": "基础 URL",+ "apiAuthKey": "API 认证密钥",+ "loading": "加载中…",+ "temperature": "温度",+ "timeoutSeconds": "超时(秒)",+ "maxRetries": "最大重试次数",+ "reasoningEffort": "推理强度",+ "useDefaultModel": "使用默认模型",+ "useDefaultUrl": "使用默认 URL",+ "dataSourcesDesc": "配置回测引擎的外部数据源。",+ "tushareDesc": "中国 A 股历史数据(需要设置 TUSHARE_TOKEN 环境变量)。",+ "baostockDesc": "通过 TCP 协议获取 A 股替代数据(无需 API 密钥)。",+ "status": "状态",+ "installed": "已安装",+ "notInstalled": "未安装",+ "token": "Token",+ "tokenConfigured": "Token 已配置",+ "tokenNotSet": "未设置 TUSHARE_TOKEN 环境变量",+ "apiTimeout": "API 请求超时",+ "loaderAvailable": "加载器可用",+ "noProjectLoader": "无项目加载器",+ "pythonPackageInstalled": "Python 包已安装",+ "pythonPackageNotInstalled": "Python 包未安装"+ },+ "agent": {+ "connectionLostReconnect": "连接已断开,正在重连…",+ "connectionRestored": "连接已恢复",+ "agentWorking": "智能体正在工作中…",+ "reasoning": "推理中…",+ "running": "运行中",+ "newMessages": "新消息",+ "newResearchGoal": "新建研究目标",+ "goal": "目标",+ "criteria": "达成标准",+ "evidence": "证据",+ "recentEvidence": "近期证据",+ "continue": "继续",+ "edit": "编辑",+ "cancel": "取消",+ "save": "保存",+ "cancelGoal": "取消目标",+ "describeGoal": "描述要附加到此会话的研究目标",+ "placeholder": "例如:为 000001.SZ 创建双均线交叉策略,回测 2024 年",+ "exportChat": "导出对话",+ "stopGeneration": "停止生成",+ "runSwarmTeam": "运行群体团队",+ "uploadFile": "上传文件",+ "checkConnector": "检查连接器",+ "analyzePortfolio": "分析连接器投资组合",+ "executionTimedOut": "执行超时,已自动停止",+ "researchGoalAttached": "研究目标已附加",+ "failedToStartGoal": "启动目标失败。",+ "researchGoalCancelled": "研究目标已取消",+ "failedToCancelGoal": "取消目标失败。",+ "researchGoalUpdated": "研究目标已更新",+ "failedToUpdateGoal": "更新目标失败。",+ "failedToLoadGoal": "加载目标失败。",+ "cancelRequestSent": "取消请求已发送",+ "cancelFailed": "取消失败",+ "connectorHalted": "连接器运行时已停止",+ "failedToHaltConnector": "停止连接器运行时失败。",+ "cancelledFromUI": "已从 Web UI 取消。",+ "executablesNotAllowed": "不允许上传可执行文件和压缩包",+ "fileSizeExceeds": "文件大小超过 50 MB 限制",+ "uploaded": "已上传:{{filename}}",+ "uploadFailed": "上传失败:{{error}}",+ "failedToSend": "发送消息失败,请重试。",+ "failedToContinue": "继续目标失败,请重试。"+ },+ "runDetail": {+ "title": "运行详情",+ "runNotFound": "运行记录未找到",+ "runNotFoundDesc": "运行目录可能已被删除,或者浏览器未配置 API 访问。如果远程访问,请检查设置中的 API 认证密钥是否已设置。",+ "goBack": "返回",+ "chart": "图表",+ "trades": "交易",+ "validation": "验证",+ "runCard": "运行卡片",+ "code": "代码",+ "downloadTradesCsv": "下载交易 CSV",+ "downloadMetricsCsv": "下载指标 CSV",+ "noChartData": "暂无图表数据",+ "noChartDataDesc": "回测引擎可能未生成价格数据。请检查 artifacts/ 目录。",+ "equityDrawdown": "净值与回撤",+ "noTrades": "暂无交易记录。",+ "time": "时间",+ "code2": "代码",+ "side": "方向",+ "price": "价格",+ "qty": "数量",+ "reason": "原因",+ "schema": "版本",+ "generated": "生成时间",+ "dataSources": "数据源",+ "warnings": "警告",+ "backtestSummary": "回测摘要",+ "reproducibility": "可复现性",+ "metrics": "指标",+ "validationPayload": "验证",+ "artifactChecksums": "制品校验和",+ "path": "路径",+ "size": "大小",+ "sha256": "SHA-256",+ "noBacktestSummary": "暂无回测摘要记录。",+ "noReproducibilityHashes": "暂无可复现性哈希记录。",+ "noScalarMetrics": "暂无标量指标记录。",+ "noValidationPayload": "暂无验证数据记录。",+ "noArtifactChecksums": "暂无制品校验和记录。",+ "noCodeFiles": "暂无代码文件。",+ "fullReport": "完整报告 →"+ },+ "compare": {+ "title": "策略对比",+ "baseline": "基准",+ "compare": "对比",+ "select": "-- 请选择 --",+ "equityDrawdown": "净值与回撤",+ "metric": "指标",+ "baselineCol": "基准",+ "compareCol": "对比",+ "delta": "差值",+ "selectTwoRuns": "选择两次运行以对比其指标。",+ "totalReturn": "总收益率",+ "annualizedReturn": "年化收益率",+ "sharpeRatio": "夏普比率",+ "calmarRatio": "卡尔马比率",+ "sortinoRatio": "索提诺比率",+ "maxDrawdown": "最大回撤",+ "volatility": "波动率",+ "winRate": "胜率",+ "profitFactor": "盈亏比",+ "avgWin": "平均盈利",+ "avgLoss": "平均亏损",+ "trades": "交易次数",+ "maxConsecLosses": "最大连续亏损",+ "exposureTime": "持仓时间",+ "avgHoldingPeriod": "平均持仓天数"+ },+ "correlation": {+ "title": "相关性矩阵",+ "assetCodes": "资产代码",+ "assetCodesHint": "逗号分隔的标的代码,如 BTC-USDT,ETH-USDT,AAPL,SPY",+ "windowDays": "窗口(天)",+ "method": "方法",+ "compute": "计算",+ "loading": "加载中..."+ },+ "alphaZoo": {+ "title": "Alpha 动物园",+ "prebuiltAlpha": "{{count}} 个预构建量化 Alpha,覆盖 4 个动物园",+ "browseDesc": "浏览来自 Qlib、Kakushadze 101 公式集、GTJA 191 以及学术异象文献的公式驱动截面信号。点击任意 Alpha 查看公式和源码,或运行基准测试在特定市场和时间段上评分整个动物园。",+ "search": "搜索",+ "searchPlaceholder": "按 ID 或昵称筛选…",+ "zoo": "动物园",+ "allZoos": "全部动物园",+ "theme": "主题",+ "allThemes": "全部主题",+ "universe": "标的池",+ "allUniverses": "全部标的池",+ "compare": "对比",+ "runBenchmark": "运行基准测试",+ "decayDays": "衰减天数",+ "selectForCompare": "选择用于对比",+ "loadingAlphas": "加载 Alpha 中…",+ "noAlphasMatch": "没有匹配当前筛选条件的 Alpha。",+ "showingOf": "显示 {{visible}} / {{total}}",+ "loadMore": "加载更多",+ "backToAlphaZoo": "返回 Alpha 动物园",+ "couldNotLoad": "无法加载 Alpha",+ "unknownError": "未知错误",+ "formula": "公式",+ "noFormula": "(无公式)",+ "metadata": "元数据",+ "themeKey": "主题",+ "frequency": "频率",+ "decayHorizon": "衰减周期",+ "minWarmupBars": "最小预热K线数",+ "requiresSector": "需要行业分类",+ "modulePath": "模块路径",+ "notes": "备注",+ "sourceCode": "源代码",+ "viewSource": "查看源码({{lines}} 行)",+ "noSource": "(无源码)",+ "benchRunner": "基准测试运行器",+ "scoreZoo": "在标的池上评分整个动物园",+ "scoreDesc": "对所选动物园中每个 Alpha 在指定标的池和时间段上计算 IC / IR,然后将它们分为存活 / 反转 / 失效。",+ "period": "时间段",+ "top": "Top",+ "running": "运行中…",+ "submitting": "提交中…",+ "computing": "计算中:{{id}}",+ "alive": "存活",+ "reversed": "反转",+ "dead": "失效",+ "skipped": "跳过",+ "topByIr": "IR 前 5 名",+ "mostReversed": "反转最多",+ "byTheme": "按主题",+ "noRows": "暂无数据。",+ "meanIc": "IC 均值",+ "ir": "IR",+ "category": "分类",+ "headToHeadCompare": "头对头对比",+ "compareAlphas": "并排对比 Alpha",+ "compareDesc": "仅在标的池和时间段上对您选择的 Alpha 进行基准测试,然后按 IC / IR 排名并显示与领先者的差距——当您只关心短名单时,比测试整个动物园快得多。",+ "alphaIds": "Alpha ID",+ "selected": "{{count}} 个已选",+ "alphaIdsHint": "用逗号或空格分隔 ID。提示:在目录中勾选 Alpha 并点击\"对比\"可自动填充。",+ "rankBy": "排序依据",+ "pickAtLeast2": "请至少选择 2 个 Alpha。",+ "enterAtLeast2": "请输入至少 2 个不同的 Alpha ID 进行对比。",+ "winner": "优胜者",+ "compared": "已比较",+ "rankedBy": "排名依据",+ "icMean": "IC 均值",+ "icStd": "IC 标准差",+ "icPositive": "IC>0",+ "icPositiveTitle": "IC 为正的期数占比",+ "sampleCount": "样本数",+ "sampleCountTitle": "IC 样本数量",+ "noBenchmarkMatch": "无基准匹配"+ },+ "validation": {+ "noData": "暂无验证数据。",+ "monteCarlo": "蒙特卡罗置换检验",+ "significant": "显著",+ "notSignificant": "不显著",+ "monteCarloDesc": "对交易顺序进行 {{n}} 次随机打乱,检验夏普比率是否优于随机。",+ "actualSharpe": "实际夏普比率",+ "pValueSharpe": "p 值(夏普比率)",+ "simulatedMean": "模拟均值",+ "simulatedRange": "模拟 90% 区间",+ "bootstrap": "自举夏普置信区间",+ "ciAbove0": "置信区间 > 0",+ "ciIncludes0": "置信区间包含 0",+ "bootstrapDesc": "对日收益率进行 {{n}} 次重采样以估计 {{pct}} 置信区间。",+ "observedSharpe": "观测夏普比率",+ "ci": "{{pct}} 置信区间",+ "medianSharpe": "中位数夏普比率",+ "probSharpePositive": "P(夏普比率 > 0)",+ "walkForward": "前推分析",+ "profitable": "{{profitable}}/{{total}} 盈利",+ "walkForwardDesc": "拆分为 {{n}} 个连续窗口以检验绩效一致性。",+ "consistency": "一致性",+ "avgReturn": "平均收益",+ "avgSharpe": "平均夏普比率",+ "windows": "窗口数",+ "period2": "时段",+ "return": "收益",+ "maxDd": "最大回撤",+ "winRate": "胜率"+ },+ "thinking": {+ "processing": "处理中",+ "running": "运行中",+ "done": "完成",+ "steps": "{{count}} 个步骤"+ },+ "runnerStatus": {+ "connectorRuntime": "连接器运行时",+ "connected": "{{count}} 个已连接",+ "noConnector": "无连接器已连接",+ "running": "运行中",+ "halted": "已停止",+ "authorized": "已授权",+ "notConnected": "未连接",+ "connectProfile": "连接此配置以启用连接器运行时",+ "authorizeNote": "在 OAuth 授权成功且提交 mandate 之前,连接器通道保持只读。",+ "runner": "运行器",+ "runnerRunning": "运行中",+ "runnerStopped": "已停止",+ "lastTick": "最后心跳",+ "activeMandate": "活跃 mandate",+ "expiresIn": "{{time}} 后过期",+ "expired": "已过期",+ "limitsUnavailable": "限制信息不可用",+ "noActiveMandate": "无活跃 mandate。请让智能体提议一个,然后在启动连接器运行时之前提交。",+ "haltedControlsDisabled": "已停止 — 运行器控制已禁用",+ "runtimeActive": "运行时在 mandate 内活跃",+ "idle": "空闲",+ "stopRunner": "停止运行器",+ "startRunner": "启动运行器",+ "never": "从未",+ "unknown": "未知",+ "justNow": "刚刚",+ "loadingInstructions": "正在加载连接器授权说明..."+ },+ "swarmStatus": {+ "agents": "{{done}}/{{total}} 个智能体",+ "layer": "第 {{current}}/{{total}} 层",+ "agent": "智能体",+ "status": "状态",+ "tool": "工具",+ "time": "耗时",+ "iters": "迭代",+ "output": "输出",+ "waitingForEvents": "等待智能体事件..."+ },+ "mandate": {+ "runtimeMandate": "连接器运行时 mandate",+ "reauthMandate": "重新授权连接器 mandate",+ "universe": "标的池",+ "maxOrder": "单笔最大",+ "dailyCap": "每日上限",+ "leverage": "杠杆",+ "instruments": "品种",+ "adjust": "调整",+ "committing": "提交中…",+ "commit": "提交「{{label}}」",+ "cancel": "取消",+ "sendAdjustment": "发送调整",+ "mandateActive": "Mandate {{id}} 已生效",+ "fundedBy": "资金来源",+ "noBroker": "无法提交 mandate:连接器 broker 信息缺失。请让智能体重新生成提案。",+ "failedToCommit": "提交 mandate 失败。",+ "noLeverage": "无杠杆",+ "leverageValue": "{{value}}× 杠杆",+ "tradesPerDay": "{{count}} 笔/天"+ },+ "messageBubble": {+ "copied": "已复制",+ "copy": "复制",+ "timeoutHint": "执行超时。请尝试简化策略或减少资产数量。",+ "apiFailedHint": "API 调用失败。请稍后重试。",+ "executionFailedHint": "执行失败。点击重试。"+ },+ "pineViewer": {+ "pineScript": "Pine Script v6",+ "copied": "已复制",+ "copy": "复制",+ "docs": "文档",+ "footer": "TradingView Pine 编辑器 → 新建空白指标 → 粘贴代码 → 添加到图表"+ },+ "runComplete": {+ "fullReport": "完整报告 →",+ "pineScript": "Pine Script",+ "shadowReport": "影子报告"+ },+ "home": {+ "title": "AI 驱动的量化策略研究",+ "subtitle": "用自然语言描述交易策略。智能体自动生成代码、运行回测并优化 —— 全部实时完成。",+ "startResearch": "开始研究",+ "featureAgent": "AI 智能体",+ "featureAgentDesc": "基于 ReAct 推理的自然语言策略生成",+ "featureBacktest": "内置回测引擎",+ "featureBacktestDesc": "7 大数据源,覆盖 A股、港美股与加密货币",+ "featureStreaming": "实时流式输出",+ "featureStreamingDesc": "观看智能体思考、调用工具和迭代的全过程",+ "featureReplay": "策略回放",+ "featureReplayDesc": "交易日志分析器 + 影子账户 —— 提取你的规则、回测验证、归因盈亏差异"+ },+ "errorBoundary": {+ "somethingWrong": "出了点问题"+ }+}diff --git a/frontend/src/lib/formatters.ts b/frontend/src/lib/formatters.tsindex a93968418..cac3a372e 100644--- a/frontend/src/lib/formatters.ts+++ b/frontend/src/lib/formatters.ts@@ -1,4 +1,6 @@-export const METRIC_LABELS: Record<string, string> = {+import i18n from '@/i18n';++const METRIC_LABELS_EN: Record<string, string> = {total_return: "Total Return",annual_return: "Annual",sharpe: "Sharpe",@@ -16,8 +18,32 @@ export const METRIC_LABELS: Record<string, string> = {information_ratio: "IR",};+const METRIC_LABELS_ZH: Record<string, string> = {+ total_return: "总收益率",+ annual_return: "年化",+ sharpe: "夏普比率",+ max_drawdown: "最大回撤",+ win_rate: "胜率",+ trade_count: "交易次数",+ final_value: "最终净值",+ calmar: "卡尔马",+ sortino: "索提诺",+ profit_loss_ratio: "盈亏比",+ max_consecutive_loss: "最大连续亏损",+ avg_holding_days: "平均持仓天数",+ benchmark_return: "基准收益",+ excess_return: "超额收益",+ information_ratio: "IR",+};++// Canonical metric key set (English labels). Kept exported so consumers and+// tests have a stable label map; localized lookups go through getMetricLabel.+export const METRIC_LABELS = METRIC_LABELS_EN;+export function getMetricLabel(k: string): string {- return METRIC_LABELS[k] || k;+ const lang = i18n.language;+ if (lang.startsWith('zh')) return METRIC_LABELS_ZH[k] || METRIC_LABELS_EN[k] || k;+ return METRIC_LABELS_EN[k] || k;}const PCT_KEYS = ["total_return", "annual_return", "win_rate", "max_drawdown", "benchmark_return", "excess_return"];diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex ed0b3d2a8..c4a3c8a4f 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -1,3 +1,4 @@+import './i18n';import { StrictMode } from "react";import { createRoot } from "react-dom/client";import { RouterProvider } from "react-router-dom";diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex ac075eab0..77db91bc9 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -1,3 +1,4 @@+import { useTranslation } from 'react-i18next';import { useEffect, useRef, useState, useMemo, useCallback, type FormEvent } from "react";import { useSearchParams } from "react-router-dom";import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users, Target, ChevronDown, Pencil, Check, Play, OctagonX, Activity, Ban, CheckCircle2, Landmark } from "lucide-react";@@ -45,6 +46,9 @@ function groupMessages(msgs: AgentMessage[]): MsgGroup[] {const act = () => useAgentStore.getState();+// i18n hook for Agent component — used inside the component below+// (declared at module scope for helper usage is fine since t() reads from i18n singleton)+/** Poll cadence for the shared `GET /live/status` snapshot. */const LIVE_STATUS_POLL_INTERVAL_MS = 15_000;const CONNECTOR_CHECK_PROMPT =@@ -206,6 +210,7 @@ function goalContinuePrompt(snapshot: GoalSnapshot): string {/* ---------- Component ---------- */export function Agent() {+ const { t } = useTranslation();const [input, setInput] = useState("");const [searchParams, setSearchParams] = useSearchParams();const listRef = useRef<HTMLDivElement>(null);@@ -305,8 +310,8 @@ export function Agent() {useEffect(() => {onStatusChange((s) => {act().setSseStatus(s);- if (s === "reconnecting" && prevSseStatusRef.current === "connected") toast.warning("Connection lost, reconnecting…");- else if (s === "connected" && prevSseStatusRef.current === "reconnecting") toast.success("Connection restored");+ if (s === "reconnecting" && prevSseStatusRef.current === "connected") toast.warning(t('agent.connectionLostReconnect'));+ else if (s === "connected" && prevSseStatusRef.current === "reconnecting") toast.success(t('agent.connectionRestored'));prevSseStatusRef.current = s;});}, [onStatusChange]);@@ -335,7 +340,7 @@ export function Agent() {setGoalDetailsOpen(false);setGoalEditActive(false);} else {- toast.error(error instanceof Error ? error.message : "Failed to load goal.");+ toast.error(error instanceof Error ? error.message : t('agent.failedToLoadGoal'));}}}, []);@@ -664,7 +669,7 @@ export function Agent() {// the RunnerStatus panel re-polls so its per-broker rows show "halted".setLiveHalted(halted);setLiveStatusRefresh((n) => n + 1);- toast.warning("Connector runtime halted — runner stopped, resting orders cancelled");+ toast.warning(t('agent.connectorHalted'));},"live.resumed": (d) => {@@ -674,7 +679,7 @@ export function Agent() {void d;setLiveHalted(null);setLiveStatusRefresh((n) => n + 1);- toast.success("Connector runtime resumed");+ toast.success(t('agent.connectionRestored'));},"live.action": (d) => {@@ -798,7 +803,7 @@ export function Agent() {if (lastEventRef.current && Date.now() - lastEventRef.current > sseTimeoutMsRef.current && act().status === "streaming") {setReasoningActive(false);act().setStatus("idle");- toast.warning("Execution timed out, automatically stopped");+ toast.warning(t('agent.executionTimedOut'));}}, 10_000);return () => clearInterval(timer);@@ -816,7 +821,7 @@ export function Agent() {setGoalSnapshot(snapshot);setGoalComposerActive(false);setGoalDetailsOpen(true);- toast.success("Research goal attached");+ toast.success(t('agent.researchGoalAttached'));const kickoff = goalKickoffPrompt(prompt);act().addMessage({ id: "", type: "user", content: kickoff, timestamp: Date.now() });act().setStatus("streaming");@@ -825,7 +830,7 @@ export function Agent() {await api.sendMessage(sid, kickoff);} catch (error) {act().setStatus("idle");- toast.error(error instanceof Error ? error.message : "Failed to start goal.");+ toast.error(error instanceof Error ? error.message : t('agent.failedToStartGoal'));}return;}@@ -860,7 +865,7 @@ export function Agent() {await api.sendMessage(sid, finalPrompt);} catch (error) {act().setStatus("error");- const message = isAuthRequiredError(error) ? AUTH_REQUIRED_MESSAGE : "Failed to send message, please retry.";+ const message = isAuthRequiredError(error) ? AUTH_REQUIRED_MESSAGE : t('agent.failedToSend');toast.error(message);act().addMessage({ id: "", type: "error", content: message, timestamp: Date.now() });}@@ -891,9 +896,9 @@ export function Agent() {act().setStatus("idle");act().clearStreaming();useAgentStore.setState({ toolCalls: [] });- toast.info("Cancel request sent");+ toast.info(t('agent.cancelRequestSent'));} catch {- toast.error("Cancel failed");+ toast.error(t('agent.cancelFailed'));}};@@ -911,9 +916,9 @@ export function Agent() {// optimistically and re-poll the runtime panel so the runner shows stopped.setLiveHalted((cur) => cur ?? { broker: null, by: "frontend", tripped_at: new Date().toISOString() });setLiveStatusRefresh((n) => n + 1);- toast.success("Connector runtime halted");+ toast.success(t('agent.connectorHalted'));} catch (error) {- toast.error(error instanceof Error ? error.message : "Failed to halt connector runtime.");+ toast.error(error instanceof Error ? error.message : t('agent.failedToHaltConnector'));} finally {setHalting(false);}@@ -930,9 +935,9 @@ export function Agent() {});setGoalSnapshot(null);setGoalDetailsOpen(false);- toast.success("Research goal cancelled");+ toast.success(t('agent.researchGoalCancelled'));} catch (error) {- toast.error(error instanceof Error ? error.message : "Failed to cancel goal.");+ toast.error(error instanceof Error ? error.message : t('agent.failedToCancelGoal'));}}, [goalSnapshot, sessionId]);@@ -953,9 +958,9 @@ export function Agent() {});setGoalSnapshot(response.snapshot);setGoalEditActive(false);- toast.success("Research goal updated");+ toast.success(t('agent.researchGoalUpdated'));} catch (error) {- toast.error(error instanceof Error ? error.message : "Failed to update goal.");+ toast.error(error instanceof Error ? error.message : t('agent.failedToUpdateGoal'));}}, [goalEditValue, goalSnapshot, sessionId]);@@ -971,7 +976,7 @@ export function Agent() {await api.sendMessage(sessionId, prompt);} catch (error) {act().setStatus("error");- const message = isAuthRequiredError(error) ? AUTH_REQUIRED_MESSAGE : "Failed to continue goal, please retry.";+ const message = isAuthRequiredError(error) ? AUTH_REQUIRED_MESSAGE : t('agent.failedToContinue');toast.error(message);act().addMessage({ id: "", type: "error", content: message, timestamp: Date.now() });}@@ -1033,11 +1038,11 @@ export function Agent() {];const lowered = file.name.toLowerCase();if (blockedExts.some((ext) => lowered.endsWith(ext))) {- toast.error("Executables and archives are not allowed");+ toast.error(t('agent.executablesNotAllowed'));return;}if (file.size > 50 * 1024 * 1024) {- toast.error("File size exceeds 50 MB limit");+ toast.error(t('agent.fileSizeExceeds'));return;}setUploading(true);@@ -1045,9 +1050,9 @@ export function Agent() {try {const result = await api.uploadFile(file);setAttachment({ filename: result.filename, filePath: result.file_path });- toast.success(`Uploaded: ${result.filename}`);+ toast.success(t('agent.uploaded', { filename: result.filename }));} catch (err) {- toast.error(`Upload failed: ${err instanceof Error ? err.message : "Unknown error"}`);+ toast.error(t('agent.uploadFailed', { error: err instanceof Error ? err.message : 'Unknown error' }));} finally {setUploading(false);}@@ -1169,7 +1174,7 @@ export function Agent() {<AgentAvatar /><div className="flex-1 min-w-0 flex items-center gap-2 text-xs text-muted-foreground pt-1"><Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />- <span>Agent is working…</span>+ <span>{t('agent.agentWorking')}</span></div></div>)}@@ -1182,7 +1187,7 @@ export function Agent() {{reasoningActive && !streamingText && (<div className="flex items-center gap-2 text-xs text-muted-foreground"><Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />- <span>Reasoning…</span>+ <span>{t('agent.reasoning')}</span></div>)}{streamingText && (@@ -1204,7 +1209,7 @@ export function Agent() {<div className="h-0.5 flex-1 rounded-full bg-primary/20 overflow-hidden"><div className="h-full w-1/3 bg-primary rounded-full animate-[pulse-slide_2s_ease-in-out_infinite]" /></div>- <span className="text-[10px] text-muted-foreground shrink-0 tabular-nums">running</span>+ <span className="text-[10px] text-muted-foreground shrink-0 tabular-nums">{t('agent.running')}</span></div>)}@@ -1216,7 +1221,7 @@ export function Agent() {onClick={forceScrollToBottom}className="sticky bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1 px-3 py-1.5 rounded-full bg-primary text-primary-foreground text-xs font-medium shadow-lg hover:opacity-90 transition-opacity z-10">- <ArrowDown className="h-3 w-3" /> New messages+ <ArrowDown className="h-3 w-3" /> {t('agent.newMessages')}</button>)}<ConversationTimeline messages={messages} containerRef={listRef} />@@ -1258,7 +1263,7 @@ export function Agent() {aria-expanded={goalDetailsOpen}><Target className="h-3 w-3 shrink-0" />- <span className="shrink-0">Goal</span>+ <span className="shrink-0">{t('agent.goal')}</span><span className="truncate text-muted-foreground">{goalSnapshot.goal.ui_summary || goalSnapshot.goal.objective}</span>@@ -1587,7 +1592,7 @@ export function Agent() {type="button"onClick={handleExport}className="px-3 py-2.5 rounded-xl border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"- title="Export chat"+ title={t('agent.exportChat')}><Download className="h-4 w-4" /></button>@@ -1597,7 +1602,7 @@ export function Agent() {type="button"onClick={handleCancel}className="px-4 py-2.5 rounded-xl bg-destructive text-destructive-foreground text-sm font-medium hover:opacity-90 transition-opacity"- title="Stop generation"+ title={t('agent.stopGeneration')}><Square className="h-4 w-4" /></button>diff --git a/frontend/src/pages/AlphaZoo.tsx b/frontend/src/pages/AlphaZoo.tsxindex 8555bef51..427cb01f5 100644--- a/frontend/src/pages/AlphaZoo.tsx+++ b/frontend/src/pages/AlphaZoo.tsx@@ -1,3 +1,4 @@+import i18n from '@/i18n';/*** Alpha Zoo — browse / detail / bench views.*@@ -214,7 +215,7 @@ function BrowseView() {<Layers className="h-3.5 w-3.5" aria-hidden="true" /> Alpha Zoo</div><h1 className="text-2xl md:text-3xl font-bold tracking-tight">- {total > 0 ? total : 452} pre-built quant alphas across 4 zoos+ {total > 0 ? total : 452} {i18n.t("alphaZoo.prebuiltAlpha", { count: total > 0 ? total : 452 })}</h1><p className="text-sm text-muted-foreground max-w-2xl">Browse formula-driven cross-sectional signals from Qlib, the@@ -559,7 +560,7 @@ function DetailView({ alphaId }: DetailProps) {{/* Formula */}<section className="space-y-2">- <h2 className="text-sm font-medium text-muted-foreground">Formula</h2>+ <h2 className="text-sm font-medium text-muted-foreground">{i18n.t("alphaZoo.formula")}</h2><pre className="border rounded-xl bg-muted/30 p-4 overflow-x-auto text-xs leading-relaxed"><code>{formulaLatex || "(no formula provided)"}</code></pre>@@ -567,7 +568,7 @@ function DetailView({ alphaId }: DetailProps) {{/* Metadata */}<section className="space-y-2">- <h2 className="text-sm font-medium text-muted-foreground">Metadata</h2>+ <h2 className="text-sm font-medium text-muted-foreground">{i18n.t("alphaZoo.metadata")}</h2><div className="border rounded-xl overflow-hidden"><table className="w-full text-sm"><tbody>@@ -586,7 +587,7 @@ function DetailView({ alphaId }: DetailProps) {{/* Source code */}<section className="space-y-2">- <h2 className="text-sm font-medium text-muted-foreground">Source code</h2>+ <h2 className="text-sm font-medium text-muted-foreground">{i18n.t("alphaZoo.sourceCode")}</h2><details className="border rounded-xl bg-card group"><summary className="cursor-pointer px-4 py-3 text-sm font-medium hover:bg-muted/40 select-none">View source ({(detail.source_code || "").split("\n").length} lines)@@ -806,7 +807,7 @@ function BenchView() {</select></div><div>- <label htmlFor="bench-period" className="text-xs text-muted-foreground block mb-1">Period</label>+ <label htmlFor="bench-period" className="text-xs text-muted-foreground block mb-1">{i18n.t("alphaZoo.period")}</label><inputid="bench-period"value={period}@@ -817,7 +818,7 @@ function BenchView() {/></div><div>- <label htmlFor="bench-top" className="text-xs text-muted-foreground block mb-1">Top</label>+ <label htmlFor="bench-top" className="text-xs text-muted-foreground block mb-1">{i18n.t("alphaZoo.top")}</label><inputid="bench-top"type="number"@@ -1275,7 +1276,7 @@ function CompareView() {/></div><div>- <label htmlFor="compare-sort" className="text-xs text-muted-foreground block mb-1">Rank by</label>+ <label htmlFor="compare-sort" className="text-xs text-muted-foreground block mb-1">{i18n.t("alphaZoo.rankBy")}</label><selectid="compare-sort"value={sort}@@ -1309,7 +1310,7 @@ function CompareView() {)}</button>{ids.length < 2 && (- <span className="text-xs text-muted-foreground">Pick at least 2 alphas.</span>+ <span className="text-xs text-muted-foreground">{i18n.t("alphaZoo.pickAtLeast2")}</span>)}</div>diff --git a/frontend/src/pages/Compare.tsx b/frontend/src/pages/Compare.tsxindex fb2dfe304..413d6200a 100644--- a/frontend/src/pages/Compare.tsx+++ b/frontend/src/pages/Compare.tsx@@ -1,3 +1,4 @@+import i18n from '@/i18n';import { useEffect, useRef, useState } from "react";import { GitCompare, ArrowRight } from "lucide-react";import { cn } from "@/lib/utils";@@ -51,21 +52,21 @@ function runLabel(r: RunListItem): string {}const METRICS: MetricDef[] = [- { key: "total_return", label: "Total Return", type: "pct", higherIsBetter: true },- { key: "annualized_return", label: "Annualized Return", type: "pct", higherIsBetter: true },- { key: "sharpe", label: "Sharpe Ratio", type: "num", higherIsBetter: true },- { key: "calmar_ratio", label: "Calmar Ratio", type: "num", higherIsBetter: true },- { key: "sortino_ratio", label: "Sortino Ratio", type: "num", higherIsBetter: true },- { key: "max_drawdown", label: "Max Drawdown", type: "pct", higherIsBetter: false },- { key: "volatility", label: "Volatility", type: "pct", higherIsBetter: false },- { key: "win_rate", label: "Win Rate", type: "pct", higherIsBetter: true },- { key: "profit_factor", label: "Profit Factor", type: "num", higherIsBetter: true },- { key: "avg_win", label: "Avg Win", type: "pct", higherIsBetter: true },- { key: "avg_loss", label: "Avg Loss", type: "pct", higherIsBetter: false },- { key: "trade_count", label: "Trades", type: "int", higherIsBetter: true },- { key: "max_consecutive_losses", label: "Max Consec. Losses", type: "int", higherIsBetter: false },- { key: "exposure_time", label: "Exposure Time", type: "pct", higherIsBetter: true },- { key: "avg_holding_period", label: "Avg Holding Period", type: "days", higherIsBetter: false },+ { key: "total_return", label: i18n.t("compare.totalReturn"), type: "pct", higherIsBetter: true },+ { key: "annualized_return", label: i18n.t("compare.annualizedReturn"), type: "pct", higherIsBetter: true },+ { key: "sharpe", label: i18n.t("compare.sharpeRatio"), type: "num", higherIsBetter: true },+ { key: "calmar_ratio", label: i18n.t("compare.calmarRatio"), type: "num", higherIsBetter: true },+ { key: "sortino_ratio", label: i18n.t("compare.sortinoRatio"), type: "num", higherIsBetter: true },+ { key: "max_drawdown", label: i18n.t("compare.maxDrawdown"), type: "pct", higherIsBetter: false },+ { key: "volatility", label: i18n.t("compare.volatility"), type: "pct", higherIsBetter: false },+ { key: "win_rate", label: i18n.t("compare.winRate"), type: "pct", higherIsBetter: true },+ { key: "profit_factor", label: i18n.t("compare.profitFactor"), type: "num", higherIsBetter: true },+ { key: "avg_win", label: i18n.t("compare.avgWin"), type: "pct", higherIsBetter: true },+ { key: "avg_loss", label: i18n.t("compare.avgLoss"), type: "pct", higherIsBetter: false },+ { key: "trade_count", label: i18n.t("compare.trades"), type: "int", higherIsBetter: true },+ { key: "max_consecutive_losses", label: i18n.t("compare.maxConsecLosses"), type: "int", higherIsBetter: false },+ { key: "exposure_time", label: i18n.t("compare.exposureTime"), type: "pct", higherIsBetter: true },+ { key: "avg_holding_period", label: i18n.t("compare.avgHoldingPeriod"), type: "days", higherIsBetter: false },];// Also accept backend aliases@@ -257,17 +258,17 @@ export function Compare() {{/* Selectors */}<div className="flex gap-4 items-end"><div className="flex-1">- <label className="text-xs text-muted-foreground block mb-1">Baseline</label>+ <label className="text-xs text-muted-foreground block mb-1">{i18n.t("compare.baseline")}</label><select value={leftId} onChange={(e) => setLeftId(e.target.value)} className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" title={leftRun?.prompt || leftId}>- <option value="">-- Select --</option>+ <option value="">{i18n.t("compare.select")}</option>{runs.map((r) => <option key={r.run_id} value={r.run_id}>{runLabel(r)} ({r.status})</option>)}</select></div><ArrowRight className="h-5 w-5 text-muted-foreground mb-2 shrink-0" /><div className="flex-1">- <label className="text-xs text-muted-foreground block mb-1">Compare</label>+ <label className="text-xs text-muted-foreground block mb-1">{i18n.t("compare.compare")}</label><select value={rightId} onChange={(e) => setRightId(e.target.value)} className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" title={rightRun?.prompt || rightId}>- <option value="">-- Select --</option>+ <option value="">{i18n.t("compare.select")}</option>{runs.map((r) => <option key={r.run_id} value={r.run_id}>{runLabel(r)} ({r.status})</option>)}</select></div>@@ -277,7 +278,7 @@ export function Compare() {{loading && !hasData && (<div className="space-y-6"><div className="border rounded-xl p-4">- <h2 className="text-sm font-medium text-muted-foreground mb-2">Equity & Drawdown</h2>+ <h2 className="text-sm font-medium text-muted-foreground mb-2">{i18n.t("compare.equityDrawdown")}</h2><SkeletonChart height={320} /></div><div className="border rounded-xl overflow-hidden">@@ -289,7 +290,7 @@ export function Compare() {{/* Equity curve overlay */}{(leftCurve.length > 0 || rightCurve.length > 0) && (<div className="border rounded-xl p-4">- <h2 className="text-sm font-medium text-muted-foreground mb-2">Equity & Drawdown</h2>+ <h2 className="text-sm font-medium text-muted-foreground mb-2">{i18n.t("compare.equityDrawdown")}</h2><EquityChartOverlayleftCurve={leftCurve}rightCurve={rightCurve}@@ -305,10 +306,10 @@ export function Compare() {<table className="w-full text-sm"><thead><tr className="border-b bg-muted/40">- <th className="text-left px-4 py-2.5 text-muted-foreground font-medium">Metric</th>- <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">Baseline</th>- <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">Compare</th>- <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">Delta</th>+ <th className="text-left px-4 py-2.5 text-muted-foreground font-medium">{i18n.t("compare.metric")}</th>+ <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">{i18n.t("compare.baselineCol")}</th>+ <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">{i18n.t("compare.compareCol")}</th>+ <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">{i18n.t("compare.delta")}</th></tr></thead><tbody>@@ -332,7 +333,7 @@ export function Compare() {{!hasData && !loading && (<div className="text-center py-16 text-muted-foreground"><GitCompare className="h-12 w-12 mx-auto mb-3 opacity-20" />- <p className="text-sm">Select two runs to compare their metrics.</p>+ <p className="text-sm">{i18n.t("compare.selectTwoRuns")}</p></div>)}</div>diff --git a/frontend/src/pages/Correlation.tsx b/frontend/src/pages/Correlation.tsxindex e6e7e9db1..cd43f87f1 100644--- a/frontend/src/pages/Correlation.tsx+++ b/frontend/src/pages/Correlation.tsx@@ -1,3 +1,4 @@+import i18n from '@/i18n';import { useState } from "react";import { BarChart3 } from "lucide-react";import { CorrelationMatrix } from "@/components/charts/CorrelationMatrix";@@ -35,13 +36,13 @@ export function Correlation() {{/* Header */}<div className="flex items-center gap-3"><BarChart3 className="h-6 w-6 text-primary" />- <h1 className="text-2xl font-bold">Correlation Matrix</h1>+ <h1 className="text-2xl font-bold">{i18n.t("correlation.title")}</h1></div>{/* Controls */}<div className="flex flex-col gap-4 border rounded-lg p-4"><div className="flex flex-col gap-1.5">- <label className="text-sm font-medium">Asset codes</label>+ <label className="text-sm font-medium">{i18n.t("correlation.assetCodes")}</label><inputtype="text"value={codes}@@ -56,7 +57,7 @@ export function Correlation() {<div className="flex flex-wrap gap-4"><div className="flex flex-col gap-1.5">- <label className="text-sm font-medium">Window (days)</label>+ <label className="text-sm font-medium">{i18n.t("correlation.windowDays")}</label><div className="flex gap-1.5">{WINDOWS.map((w) => (<button@@ -75,7 +76,7 @@ export function Correlation() {</div><div className="flex flex-col gap-1.5">- <label className="text-sm font-medium">Method</label>+ <label className="text-sm font-medium">{i18n.t("correlation.method")}</label><div className="flex gap-1.5">{(["pearson", "spearman"] as const).map((m) => (<button@@ -99,7 +100,7 @@ export function Correlation() {disabled={loading}className="self-start px-4 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50 transition-opacity">- {loading ? "Loading..." : "Compute"}+ {loading ? i18n.t("correlation.loading") : i18n.t("correlation.compute")}</button></div>diff --git a/frontend/src/pages/Home.tsx b/frontend/src/pages/Home.tsxindex 3e5eff164..789bfb1f1 100644--- a/frontend/src/pages/Home.tsx+++ b/frontend/src/pages/Home.tsx@@ -1,24 +1,27 @@import { Link } from "react-router-dom";import { ArrowRight, Bot, BarChart3, Zap, UserCircle2 } from "lucide-react";+import { useTranslation } from "react-i18next";export function Home() {+ const { t } = useTranslation();+const FEATURES = [- { icon: Bot, title: "AI Agent", desc: "Natural language strategy generation with ReAct reasoning" },- { icon: BarChart3, title: "Built-in Backtest", desc: "7 data sources across A-shares, US/HK & Crypto" },- { icon: Zap, title: "Real-time Streaming", desc: "Watch the agent think, call tools, and iterate" },- { icon: UserCircle2, title: "Strategy Replay", desc: "Trade journal analyzer + Shadow Account — extract your rules, backtest them, attribute PnL delta" },+ { icon: Bot, title: t("home.featureAgent"), desc: t("home.featureAgentDesc") },+ { icon: BarChart3, title: t("home.featureBacktest"), desc: t("home.featureBacktestDesc") },+ { icon: Zap, title: t("home.featureStreaming"), desc: t("home.featureStreamingDesc") },+ { icon: UserCircle2, title: t("home.featureReplay"), desc: t("home.featureReplayDesc") },];return (<div className="flex flex-col items-center justify-center min-h-screen p-8"><div className="max-w-2xl text-center space-y-6">- <h1 className="text-4xl font-bold tracking-tight">AI-Powered Quant Strategy Research</h1>- <p className="text-lg text-muted-foreground">Describe a trading strategy in natural language. The agent generates code, runs backtests, and optimizes — all in real time.</p>+ <h1 className="text-4xl font-bold tracking-tight">{t("home.title")}</h1>+ <p className="text-lg text-muted-foreground">{t("home.subtitle")}</p><Linkto="/agent"className="inline-flex items-center gap-2 px-6 py-3 rounded-lg bg-primary text-primary-foreground font-medium hover:opacity-90 transition">- Start Research <ArrowRight className="h-4 w-4" />+ {t("home.startResearch")} <ArrowRight className="h-4 w-4" /></Link></div>diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex 08e69cd89..65306d474 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -1,3 +1,4 @@+import i18n from '@/i18n';import { useEffect, useState } from "react";import type { ReactNode } from "react";import { useParams, useNavigate } from "react-router-dom";@@ -73,11 +74,11 @@ export function RunDetail() {const hasValidation = !!run?.validation;const hasRunCard = !!run?.run_card;const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [- { id: "chart", label: "Chart", icon: BarChart3 },- { id: "trades", label: "Trades", icon: List },- { id: "validation", label: "Validation", icon: ShieldCheck, hidden: !hasValidation },- { id: "runCard", label: "Run Card", icon: FileCheck2, hidden: !hasRunCard },- { id: "code", label: "Code", icon: Code2 },+ { id: "chart", label: i18n.t("runDetail.chart"), icon: BarChart3 },+ { id: "trades", label: i18n.t("runDetail.trades"), icon: List },+ { id: "validation", label: i18n.t("runDetail.validation"), icon: ShieldCheck, hidden: !hasValidation },+ { id: "runCard", label: i18n.t("runDetail.runCard"), icon: FileCheck2, hidden: !hasRunCard },+ { id: "code", label: i18n.t("runDetail.code"), icon: Code2 },];useEffect(() => {@@ -99,16 +100,16 @@ export function RunDetail() {}if (!run) return (<div className="p-8 space-y-2">- <p className="text-red-500 font-medium">Run not found</p>+ <p className="text-red-500 font-medium">{i18n.t("runDetail.runNotFound")}</p><p className="text-sm text-muted-foreground">- The run directory may have been removed, or your browser may not have API access configured.+ {i18n.t("runDetail.runNotFoundDesc")}, or your browser may not have API access configured.Check that the API authentication key is set in Settings if accessing remotely.</p><buttononClick={() => navigate(-1)}className="text-sm text-primary hover:underline inline-flex items-center gap-1.5">- <ArrowLeft className="h-3.5 w-3.5" /> Go back+ <ArrowLeft className="h-3.5 w-3.5" /> {i18n.t("runDetail.goBack")}</button></div>);@@ -123,7 +124,7 @@ export function RunDetail() {<buttononClick={() => navigate(-1)}className="p-1 rounded-md hover:bg-muted transition-colors text-muted-foreground hover:text-foreground"- title="Go back"+ title={i18n.t("runDetail.goBack")}><ArrowLeft className="h-4 w-4" /></button>@@ -153,7 +154,7 @@ export function RunDetail() {<buttononClick={() => downloadCsv(`trades_${runId}.csv`, buildTradesCsv(run.trade_log!))}className="flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs text-muted-foreground hover:bg-muted transition-colors"- title="Download Trades CSV"+ title={i18n.t("runDetail.downloadTradesCsv")}><Download className="h-3.5 w-3.5" /> Download Trades CSV</button>@@ -162,7 +163,7 @@ export function RunDetail() {<buttononClick={() => downloadCsv(`metrics_${runId}.csv`, buildMetricsCsv(run.metrics!))}className="flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs text-muted-foreground hover:bg-muted transition-colors"- title="Download Metrics CSV"+ title={i18n.t("runDetail.downloadMetricsCsv")}><Download className="h-3.5 w-3.5" /> Download Metrics CSV</button>@@ -195,10 +196,10 @@ function RunCardTab({ card }: { card: RunCard }) {return (<div className="p-4 space-y-4"><div className="grid gap-3 md:grid-cols-4">- <RunCardStat label="Schema" value={card.schema_version || "unknown"} />- <RunCardStat label="Generated" value={formatRunCardValue(card.generated_at)} />- <RunCardStat label="Data sources" value={dataSources.length ? dataSources.join(", ") : "None recorded"} />- <RunCardStat label="Warnings" value={String(warnings.length)} tone={warnings.length ? "warning" : "normal"} />+ <RunCardStat label={i18n.t("runDetail.schema")} value={card.schema_version || "unknown"} />+ <RunCardStat label={i18n.t("runDetail.generated")} value={formatRunCardValue(card.generated_at)} />+ <RunCardStat label={i18n.t("runDetail.dataSources")} value={dataSources.length ? dataSources.join(", ") : "None recorded"} />+ <RunCardStat label={i18n.t("runDetail.warnings")} value={String(warnings.length)} tone={warnings.length ? "warning" : "normal"} /></div>{warnings.length > 0 && (@@ -214,38 +215,38 @@ function RunCardTab({ card }: { card: RunCard }) {)}<div className="grid gap-4 xl:grid-cols-2">- <RunCardPanel title="Backtest Summary" icon={Database}>- <KeyValueTable data={backtest} empty="No backtest summary recorded." />+ <RunCardPanel title={i18n.t("runDetail.backtestSummary")} icon={Database}>+ <KeyValueTable data={backtest} empty={i18n.t("runDetail.noBacktestSummary")} /></RunCardPanel>- <RunCardPanel title="Reproducibility" icon={Fingerprint}>- <KeyValueTable data={reproducibility} empty="No reproducibility hashes recorded." monospaceValues />+ <RunCardPanel title={i18n.t("runDetail.reproducibility")} icon={Fingerprint}>+ <KeyValueTable data={reproducibility} empty={i18n.t("runDetail.noReproducibilityHashes")} monospaceValues /></RunCardPanel></div><div className="grid gap-4 xl:grid-cols-2">- <RunCardPanel title="Metrics" icon={BarChart3}>- <KeyValueTable data={metrics} empty="No scalar metrics recorded." />+ <RunCardPanel title={i18n.t("runDetail.metrics")} icon={BarChart3}>+ <KeyValueTable data={metrics} empty={i18n.t("runDetail.noScalarMetrics")} /></RunCardPanel>- <RunCardPanel title="Validation" icon={ShieldCheck}>+ <RunCardPanel title={i18n.t("runDetail.validationPayload")} icon={ShieldCheck}>{card.validation ? (<pre className="max-h-80 overflow-auto rounded-md bg-muted/40 p-3 text-xs leading-relaxed">{JSON.stringify(card.validation, null, 2)}</pre>) : (- <p className="text-sm text-muted-foreground">No validation payload recorded.</p>+ <p className="text-sm text-muted-foreground">{i18n.t("runDetail.noValidationPayload")}</p>)}</RunCardPanel></div>- <RunCardPanel title="Artifact Checksums" icon={FileCheck2}>+ <RunCardPanel title={i18n.t("runDetail.artifactChecksums")} icon={FileCheck2}>{artifacts.length > 0 ? (<div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr className="border-b text-left text-muted-foreground">- <th className="py-2 pr-4">Path</th>- <th className="py-2 pr-4">Size</th>- <th className="py-2">SHA-256</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.path")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.size")}</th>+ <th className="py-2">{i18n.t("runDetail.sha256")}</th></tr></thead><tbody>@@ -260,7 +261,7 @@ function RunCardTab({ card }: { card: RunCard }) {</table></div>) : (- <p className="text-sm text-muted-foreground">No artifact checksums recorded.</p>+ <p className="text-sm text-muted-foreground">{i18n.t("runDetail.noArtifactChecksums")}</p>)}</RunCardPanel></div>@@ -332,8 +333,8 @@ function ChartTab({ run }: { run: RunData }) {if (entries.length === 0 && !hasEquity) {return (<div className="p-8 text-center text-muted-foreground space-y-2">- <p className="text-sm">No chart data available</p>- <p className="text-xs">The backtest engine may not have generated price data. Check the artifacts/ directory.</p>+ <p className="text-sm">{i18n.t("runDetail.noChartData")}</p>+ <p className="text-xs">{i18n.t("runDetail.noChartDataDesc")}</p></div>);}@@ -348,7 +349,7 @@ function ChartTab({ run }: { run: RunData }) {))}{hasEquity && (<div>- <h3 className="text-sm font-medium mb-1">Equity & Drawdown</h3>+ <h3 className="text-sm font-medium mb-1">{i18n.t("runDetail.equityDrawdown")}</h3><EquityChart data={run.equity_curve!} height={280} /></div>)}@@ -358,18 +359,18 @@ function ChartTab({ run }: { run: RunData }) {function TradesTab({ run }: { run: RunData }) {const trades = run.trade_log || [];- if (trades.length === 0) return <div className="p-8 text-muted-foreground text-sm">No trades recorded.</div>;+ if (trades.length === 0) return <div className="p-8 text-muted-foreground text-sm">{i18n.t("runDetail.noTrades")}</div>;return (<div className="p-4"><table className="w-full text-sm"><thead><tr className="border-b text-left text-muted-foreground">- <th className="py-2 pr-4">Time</th>- <th className="py-2 pr-4">Code</th>- <th className="py-2 pr-4">Side</th>- <th className="py-2 pr-4">Price</th>- <th className="py-2 pr-4">Qty</th>- <th className="py-2">Reason</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.time")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.code2")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.side")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.price")}</th>+ <th className="py-2 pr-4">{i18n.t("runDetail.qty")}</th>+ <th className="py-2">{i18n.t("runDetail.reason")}</th></tr></thead><tbody>@@ -392,7 +393,7 @@ function TradesTab({ run }: { run: RunData }) {function CodeTab({ code }: { code: Record<string, string> }) {const files = Object.entries(code);const [active, setActive] = useState(files[0]?.[0] || "");- if (files.length === 0) return <div className="p-8 text-muted-foreground text-sm">No code files.</div>;+ if (files.length === 0) return <div className="p-8 text-muted-foreground text-sm">{i18n.t("runDetail.noCodeFiles")}</div>;return (<div className="flex flex-col h-full"><div className="flex gap-1 p-2 border-b">diff --git a/frontend/src/pages/Runtime.tsx b/frontend/src/pages/Runtime.tsxindex a35f746b5..f4721597e 100644--- a/frontend/src/pages/Runtime.tsx+++ b/frontend/src/pages/Runtime.tsx@@ -1,5 +1,7 @@import { useCallback, useEffect, useMemo, useState } from "react";import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import type { TFunction } from "i18next";import {Activity,AlertTriangle,@@ -19,6 +21,7 @@ import { cn } from "@/lib/utils";const RUNTIME_POLL_INTERVAL_MS = 15_000;export function Runtime() {+ const { t } = useTranslation();const [status, setStatus] = useState<LiveStatus | null>(null);const [loading, setLoading] = useState(true);const [refreshing, setRefreshing] = useState(false);@@ -33,12 +36,12 @@ export function Runtime() {setStatus(next);} catch (err) {setStatus(null);- setError(err instanceof Error ? err.message : "Runtime status unavailable.");+ setError(err instanceof Error ? err.message : t("runtime.statusUnavailable"));} finally {setLoading(false);setRefreshing(false);}- }, []);+ }, [t]);useEffect(() => {loadStatus("initial");@@ -55,13 +58,13 @@ export function Runtime() {<div className="space-y-3"><div className="inline-flex items-center gap-2 rounded-md border px-2.5 py-1 text-xs font-medium text-muted-foreground"><Activity className="h-3.5 w-3.5" />- Runtime Monitor+ {t("runtime.monitorBadge")}</div><div>- <h1 className="text-3xl font-bold tracking-tight">Live / Paper Runtime Status</h1>+ <h1 className="text-3xl font-bold tracking-tight">{t("runtime.title")}</h1><p className="mt-2 max-w-2xl text-sm text-muted-foreground">- Read-only status from <span className="font-mono">/live/status</span>. This page does not authorize connectors,- start runners, stop runners, submit orders, cancel orders, or change mandates.+ {t("runtime.subtitlePre")} <span className="font-mono">/live/status</span>+ {t("runtime.subtitlePost")}</p></div></div>@@ -72,7 +75,7 @@ export function Runtime() {className="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium transition hover:bg-muted disabled:opacity-50">{refreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}- Refresh+ {t("runtime.refresh")}</button></section>@@ -88,12 +91,10 @@ export function Runtime() {<section className="rounded-md border border-amber-500/30 bg-amber-500/5 p-5"><div className="flex items-center gap-2 font-medium text-amber-700 dark:text-amber-300"><AlertTriangle className="h-5 w-5" />- Runtime status unavailable+ {t("runtime.unavailableTitle")}</div><p className="mt-2 text-sm text-muted-foreground">{error}</p>- <p className="mt-2 text-xs text-muted-foreground">- Treat connector runtime as unavailable until the backend provides a current status snapshot.- </p>+ <p className="mt-2 text-xs text-muted-foreground">{t("runtime.unavailableHint")}</p></section>) : null}@@ -101,21 +102,21 @@ export function Runtime() {<><section className="grid gap-3 md:grid-cols-4"><SummaryTile- label="Global Halt"- value={status.global_halted ? "Halted" : "Clear"}+ label={t("runtime.globalHalt")}+ value={status.global_halted ? t("runtime.halted") : t("runtime.clear")}tone={status.global_halted ? "danger" : "success"}icon={status.global_halted ? OctagonX : CheckCircle2}/>- <SummaryTile label="Brokers" value={String(summary.brokerCount)} tone="neutral" icon={Activity} />+ <SummaryTile label={t("runtime.brokers")} value={String(summary.brokerCount)} tone="neutral" icon={Activity} /><SummaryTile- label="Authorized"+ label={t("runtime.authorized")}value={String(summary.authorizedCount)}tone={summary.authorizedCount > 0 ? "success" : "neutral"}icon={summary.authorizedCount > 0 ? Wifi : WifiOff}/><SummaryTile- label="Runners"- value={`${summary.runningCount} running`}+ label={t("runtime.runners")}+ value={t("runtime.running", { count: summary.runningCount })}tone={summary.runningCount > 0 && !status.global_halted ? "success" : "neutral"}icon={summary.runningCount > 0 ? Activity : Clock3}/>@@ -124,15 +125,13 @@ export function Runtime() {{status.brokers.length === 0 ? (<section className="rounded-md border border-dashed p-8 text-center"><ShieldOff className="mx-auto h-8 w-8 text-muted-foreground" />- <h2 className="mt-3 font-medium">No runtime profiles reported</h2>- <p className="mt-1 text-sm text-muted-foreground">- The backend did not return any recognized live or paper broker profiles.- </p>+ <h2 className="mt-3 font-medium">{t("runtime.noProfilesTitle")}</h2>+ <p className="mt-1 text-sm text-muted-foreground">{t("runtime.noProfilesBody")}</p></section>) : (<section className="grid gap-4">{status.brokers.map((broker) => (- <BrokerRuntimeCard key={broker.auth.broker} broker={broker} globalHalted={status.global_halted} />+ <BrokerRuntimeCard key={broker.auth.broker} broker={broker} globalHalted={status.global_halted} t={t} />))}</section>)}@@ -177,13 +176,13 @@ function SummaryTile({ label, value, tone, icon: Icon }: SummaryTileProps) {);}-function BrokerRuntimeCard({ broker, globalHalted }: { broker: LiveBrokerStatus; globalHalted: boolean }) {+function BrokerRuntimeCard({ broker, globalHalted, t }: { broker: LiveBrokerStatus; globalHalted: boolean; t: TFunction }) {const brokerKey = broker.auth.broker;const runnerAlive = broker.runner?.alive ?? false;const halted = globalHalted || broker.halted;const mandate = broker.mandate ?? null;- const risk = deriveRiskState(broker, globalHalted);- const mandateCountdown = formatCountdown(mandate?.expires_at);+ const risk = deriveRiskState(broker, globalHalted, t);+ const mandateCountdown = formatCountdown(mandate?.expires_at, t);return (<article className="rounded-md border p-4">@@ -192,39 +191,42 @@ function BrokerRuntimeCard({ broker, globalHalted }: { broker: LiveBrokerStatus;<div className="flex flex-wrap items-center gap-2"><h2 className="font-semibold capitalize">{brokerKey}</h2><StatusPill- label={broker.auth.oauth_token_present ? "auth present" : "auth missing"}+ label={broker.auth.oauth_token_present ? t("runtime.authPresent") : t("runtime.authMissing")}tone={broker.auth.oauth_token_present ? "success" : "neutral"}/>- <StatusPill label={runnerAlive ? "runner alive" : "runner stopped"} tone={runnerAlive ? "success" : "neutral"} />- {halted ? <StatusPill label="halted" tone="danger" /> : null}+ <StatusPill+ label={runnerAlive ? t("runtime.runnerAlive") : t("runtime.runnerStopped")}+ tone={runnerAlive ? "success" : "neutral"}+ />+ {halted ? <StatusPill label={t("runtime.haltedPill")} tone="danger" /> : null}</div><p className="mt-2 text-sm text-muted-foreground">- {broker.auth.is_live_broker ? "Recognized connector profile" : "Unknown connector profile"} · Last tick{" "}- {formatLastTick(broker.runner?.last_tick, broker.runner?.last_tick_age_seconds)}+ {broker.auth.is_live_broker ? t("runtime.recognizedProfile") : t("runtime.unknownProfile")} · {t("runtime.lastTick")}{" "}+ {formatLastTick(broker.runner?.last_tick, broker.runner?.last_tick_age_seconds, t)}</p></div><StatusPill label={risk.label} tone={risk.tone} /></div><div className="mt-4 grid gap-3 md:grid-cols-3">- <RuntimePanel title="Authorization" icon={broker.auth.oauth_token_present ? Wifi : WifiOff}>- <KeyValue label="OAuth token" value={broker.auth.oauth_token_present ? "present" : "missing"} />- <KeyValue label="Profile type" value={broker.auth.is_live_broker ? "recognized" : "unknown"} />+ <RuntimePanel title={t("runtime.authorization")} icon={broker.auth.oauth_token_present ? Wifi : WifiOff}>+ <KeyValue label={t("runtime.oauthToken")} value={broker.auth.oauth_token_present ? t("runtime.present") : t("runtime.missing")} />+ <KeyValue label={t("runtime.profileType")} value={broker.auth.is_live_broker ? t("runtime.recognized") : t("runtime.unknown")} /></RuntimePanel>- <RuntimePanel title="Mandate" icon={mandate ? ShieldCheck : ShieldOff}>+ <RuntimePanel title={t("runtime.mandate")} icon={mandate ? ShieldCheck : ShieldOff}>{mandate ? (<>- <KeyValue label="Account" value={mandate.account_ref || "unrecorded"} />- <KeyValue label="Expiry" value={mandate.expired ? "expired" : mandateCountdown} />- <KeyValue label="Limits" value={summarizeLimits(mandate.limits)} />+ <KeyValue label={t("runtime.account")} value={mandate.account_ref || t("runtime.unrecorded")} />+ <KeyValue label={t("runtime.expiry")} value={mandate.expired ? t("runtime.expired") : mandateCountdown} />+ <KeyValue label={t("runtime.limits")} value={summarizeLimits(mandate.limits, t)} /></>) : (- <p className="text-sm text-muted-foreground">No active mandate reported.</p>+ <p className="text-sm text-muted-foreground">{t("runtime.noMandate")}</p>)}</RuntimePanel>- <RuntimePanel title="Runtime Risk State" icon={risk.icon}>+ <RuntimePanel title={t("runtime.riskStateTitle")} icon={risk.icon}><p className="text-sm text-muted-foreground">{risk.description}</p></RuntimePanel></div>@@ -278,7 +280,7 @@ function summarizeRuntime(status: LiveStatus | null) {};}-function deriveRiskState(broker: LiveBrokerStatus, globalHalted: boolean): {+function deriveRiskState(broker: LiveBrokerStatus, globalHalted: boolean, t: TFunction): {label: string;tone: "success" | "danger" | "warning" | "neutral";icon: typeof Activity;@@ -286,53 +288,53 @@ function deriveRiskState(broker: LiveBrokerStatus, globalHalted: boolean): {} {if (globalHalted || broker.halted) {return {- label: "risk halted",+ label: t("runtime.riskHalted"),tone: "danger",icon: OctagonX,- description: "The kill switch is tripped for this profile. Treat connector runtime as stopped until status clears.",+ description: t("runtime.riskHaltedDesc"),};}if (broker.runner?.alive && broker.mandate && !broker.mandate.expired) {return {- label: "runtime active",+ label: t("runtime.riskActive"),tone: "success",icon: Activity,- description: "Runner is alive and an unexpired mandate is present. This page is still read-only status only.",+ description: t("runtime.riskActiveDesc"),};}if (broker.auth.oauth_token_present && broker.mandate && !broker.mandate.expired) {return {- label: "ready but idle",+ label: t("runtime.riskIdle"),tone: "warning",icon: Clock3,- description: "Authorization and mandate are present, but the runner is not alive.",+ description: t("runtime.riskIdleDesc"),};}return {- label: "dormant",+ label: t("runtime.riskDormant"),tone: "neutral",icon: ShieldOff,- description: "Connector runtime is not ready for autonomous operation because authorization, mandate, or runner liveness is missing.",+ description: t("runtime.riskDormantDesc"),};}-function summarizeLimits(limits: LiveMandateLimits | undefined): string {- if (!limits) return "limits unavailable";+function summarizeLimits(limits: LiveMandateLimits | undefined, t: TFunction): string {+ if (!limits) return t("runtime.limitsUnavailable");const parts: string[] = [];- if (typeof limits.max_order_notional_usd === "number") parts.push(`$${limits.max_order_notional_usd.toLocaleString()}/order`);- if (typeof limits.max_total_exposure_usd === "number") parts.push(`$${limits.max_total_exposure_usd.toLocaleString()} exposure`);- if (typeof limits.max_trades_per_day === "number") parts.push(`${limits.max_trades_per_day}/day`);- if (typeof limits.max_leverage === "number") parts.push(`${limits.max_leverage}x leverage`);+ if (typeof limits.max_order_notional_usd === "number") parts.push(`$${limits.max_order_notional_usd.toLocaleString()}${t("runtime.perOrder")}`);+ if (typeof limits.max_total_exposure_usd === "number") parts.push(`$${limits.max_total_exposure_usd.toLocaleString()} ${t("runtime.exposure")}`);+ if (typeof limits.max_trades_per_day === "number") parts.push(`${limits.max_trades_per_day}${t("runtime.perDay")}`);+ if (typeof limits.max_leverage === "number") parts.push(`${limits.max_leverage}${t("runtime.leverageSuffix")}`);if (limits.allowed_instruments?.length) parts.push(limits.allowed_instruments.join(", "));- return parts.join(" · ") || "limits unavailable";+ return parts.join(" · ") || t("runtime.limitsUnavailable");}-function formatCountdown(iso: string | undefined): string {- if (!iso) return "unknown";+function formatCountdown(iso: string | undefined, t: TFunction): string {+ if (!iso) return t("runtime.unknown");const target = new Date(iso).getTime();- if (!Number.isFinite(target)) return "unknown";+ if (!Number.isFinite(target)) return t("runtime.unknown");const deltaSec = Math.round((target - Date.now()) / 1000);- if (deltaSec <= 0) return "expired";+ if (deltaSec <= 0) return t("runtime.expired");const days = Math.floor(deltaSec / 86_400);const hours = Math.floor((deltaSec % 86_400) / 3600);if (days > 0) return `${days}d ${hours}h`;@@ -340,19 +342,19 @@ function formatCountdown(iso: string | undefined): string {return `${Math.max(1, Math.floor(deltaSec / 60))}m`;}-function formatLastTick(value: string | number | null | undefined, ageSeconds: number | null | undefined): string {+function formatLastTick(value: string | number | null | undefined, ageSeconds: number | null | undefined, t: TFunction): string {if (typeof ageSeconds === "number" && Number.isFinite(ageSeconds)) {- if (ageSeconds < 60) return `${Math.round(ageSeconds)}s ago`;- if (ageSeconds < 3600) return `${Math.floor(ageSeconds / 60)}m ago`;- return `${Math.floor(ageSeconds / 3600)}h ago`;+ if (ageSeconds < 60) return `${Math.round(ageSeconds)}s ${t("runtime.ago")}`;+ if (ageSeconds < 3600) return `${Math.floor(ageSeconds / 60)}m ${t("runtime.ago")}`;+ return `${Math.floor(ageSeconds / 3600)}h ${t("runtime.ago")}`;}- if (value == null || value === "") return "never";+ if (value == null || value === "") return t("runtime.never");const timestamp = typeof value === "number"? (value < 1_000_000_000_000 ? value * 1000 : value): new Date(value).getTime();- if (!Number.isFinite(timestamp)) return "unknown";+ if (!Number.isFinite(timestamp)) return t("runtime.unknown");const deltaSec = Math.round((Date.now() - timestamp) / 1000);- if (deltaSec < 60) return `${Math.max(0, deltaSec)}s ago`;- if (deltaSec < 3600) return `${Math.floor(deltaSec / 60)}m ago`;- return `${Math.floor(deltaSec / 3600)}h ago`;+ if (deltaSec < 60) return `${Math.max(0, deltaSec)}s ${t("runtime.ago")}`;+ if (deltaSec < 3600) return `${Math.floor(deltaSec / 60)}m ${t("runtime.ago")}`;+ return `${Math.floor(deltaSec / 3600)}h ${t("runtime.ago")}`;}diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsxindex fd5c83700..96e69bcd0 100644--- a/frontend/src/pages/Settings.tsx+++ b/frontend/src/pages/Settings.tsx@@ -1,3 +1,4 @@+import i18n from "@/i18n";import { useEffect, useMemo, useState, type FormEvent } from "react";import { Database, KeyRound, Loader2, RotateCcw, Save, Server, SlidersHorizontal } from "lucide-react";import { toast } from "sonner";@@ -32,6 +33,7 @@ function toForm(settings: LLMSettings): LLMFormState {}export function Settings() {+const [settings, setSettings] = useState<LLMSettings | null>(null);const [dataSettings, setDataSettings] = useState<DataSourceSettings | null>(null);const [form, setForm] = useState<LLMFormState | null>(null);@@ -173,7 +175,7 @@ export function Settings() {className="inline-flex items-center justify-center gap-2 self-end rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90"><Save className="h-4 w-4" />- {"Save local key"}+ {i18n.t("settings.save")}</button></div><p className="mt-2 text-xs text-muted-foreground">{"Stored only in this browser. Leave blank to clear it."}</p>@@ -240,7 +242,7 @@ export function Settings() {<div className="grid gap-4"><label className="grid gap-2">- <span className={labelClass}>{"Provider"}</span>+ <span className={labelClass}>{i18n.t("settings.provider")}</span><selectvalue={form.provider}onChange={(event) => onProviderChange(event.target.value)}@@ -276,7 +278,7 @@ export function Settings() {</label><label className="grid gap-2">- <span className={labelClass}>{"Base URL"}</span>+ <span className={labelClass}>{i18n.t("settings.baseUrl")}</span><inputvalue={form.base_url}onChange={(event) => setForm({ ...form, base_url: event.target.value })}@@ -331,7 +333,7 @@ export function Settings() {<div className="grid gap-4"><label className="grid gap-2">- <span className={labelClass}>{"Temperature"}</span>+ <span className={labelClass}>{i18n.t("settings.temperature")}</span><inputtype="number"min={0}@@ -344,7 +346,7 @@ export function Settings() {</label><label className="grid gap-2">- <span className={labelClass}>{"Timeout seconds"}</span>+ <span className={labelClass}>{i18n.t("settings.timeoutSeconds")}</span><inputtype="number"min={1}@@ -370,7 +372,7 @@ export function Settings() {</label><label className="grid gap-2">- <span className={labelClass}>{"Reasoning effort"}</span>+ <span className={labelClass}>{i18n.t("settings.reasoningEffort")}</span><selectvalue={form.reasoning_effort}onChange={(event) => setForm({ ...form, reasoning_effort: event.target.value })}@@ -386,7 +388,7 @@ export function Settings() {</label><div className="rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">- <span className="font-medium text-foreground">{"Saved to"}: </span>+ <span className="font-medium text-foreground">{i18n.t("settings.saved")}: </span><span className="break-all font-mono">{settings.env_path}</span></div>@@ -396,7 +398,7 @@ export function Settings() {className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-70">{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}- {saving ? "Saving..." : "Save settings"}+ {saving ? i18n.t("settings.saving") : i18n.t("settings.save")}</button></div></section>@@ -445,7 +447,7 @@ export function Settings() {</label><div className="rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">- <span className="font-medium text-foreground">{"Saved to"}: </span>+ <span className="font-medium text-foreground">{i18n.t("settings.saved")}: </span><span className="break-all font-mono">{dataSettings.env_path}</span></div>@@ -455,7 +457,7 @@ export function Settings() {className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-70">{dataSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}- {dataSaving ? "Saving..." : "Save data source settings"}+ {dataSaving ? i18n.t("settings.saving") : "Save data source settings"}</button></div>diff --git a/frontend/src/tests/setup.ts b/frontend/src/tests/setup.tsindex 2b649ad91..255fcff7b 100644--- a/frontend/src/tests/setup.ts+++ b/frontend/src/tests/setup.ts@@ -1,4 +1,8 @@import "@testing-library/jest-dom/vitest";+// Initialize i18n so `useTranslation()` resolves real strings in tests.+// With no localStorage entry under jsdom this falls back to English, keeping+// the suite's English assertions stable.+import "../i18n";// ── Global mocks for jsdom ───────────────────────────────────diff --git a/frontend/tsconfig.json b/frontend/tsconfig.jsonindex dc7a1b655..cb931e1fc 100644--- a/frontend/tsconfig.json+++ b/frontend/tsconfig.json@@ -19,5 +19,6 @@"baseUrl": ".","paths": { "@/*": ["./src/*"] }},- "include": ["src"]+ "include": ["src"],+ "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx", "src/**/__tests__"]}diff --git a/pyproject.toml b/pyproject.tomlindex bd88c1dd8..ba05b4b98 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -97,6 +97,12 @@ ibkr = [deepseek = ["langchain-deepseek>=1.0.0,<2",]+ashare = [+ # Free, no-auth A-share source over BaoStock's TCP protocol; bypasses the+ # HTTP CDN IP blocks that affect eastmoney-backed sources. The Tencent+ # A-share loader needs no extra dependency (stdlib HTTP only).+ "baostock>=0.8.8",+]dev = ["pytest>=7.0","pytest-cov>=4.0",