"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: FW-2 wave 1 — end-to-end tool call_id, tool-trail persistence, 84-tool i18n, copy polish, a11y/robustness sweep
Haozhe Wu4b69f49809f5
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 8be770c19..b6bd01a5b 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -1202,14 +1202,22 @@ class AgentLoop:args = _normalize_tool_run_dir(tc.arguments, self.memory.run_dir)redacted_args = redact_payload(args)event_args = {k: str(v)[:200] for k, v in redacted_args.items()}- self._emit("tool_call", {"tool": tc.name, "arguments": event_args, "iter": iteration})+ self._emit(+ "tool_call",+ {+ "tool": tc.name,+ "arguments": event_args,+ "iter": iteration,+ "call_id": tc.id,+ },+ )trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "call_id": tc.id, "args": redacted_args})runnable.append((tc, args))# Execute in parallel — each worker gets its own heartbeat + progress emitter.def _run(tc_args: tuple) -> tuple:tc, args = tc_args- result, elapsed_ms = self._invoke_tool(tc.name, args)+ result, elapsed_ms = self._invoke_tool(tc.name, args, call_id=tc.id)return tc, result, elapsed_mswith concurrent.futures.ThreadPoolExecutor(max_workers=min(len(runnable), 8)) as pool:@@ -1249,15 +1257,29 @@ class AgentLoop:redacted_args = redact_payload(args)event_args = {k: str(v)[:200] for k, v in redacted_args.items()}- self._emit("tool_call", {"tool": tc.name, "arguments": event_args, "iter": iteration})+ self._emit(+ "tool_call",+ {+ "tool": tc.name,+ "arguments": event_args,+ "iter": iteration,+ "call_id": tc.id,+ },+ )trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "call_id": tc.id, "args": redacted_args})logger.info(f"Tool call: {tc.name}({list(args.keys())})")- result, elapsed_ms = self._invoke_tool(tc.name, args)+ result, elapsed_ms = self._invoke_tool(tc.name, args, call_id=tc.id)self._finalize_tool_result(tc, result, elapsed_ms, context, messages, trace, react_trace, iteration)- def _invoke_tool(self, tool_name: str, args: Dict[str, Any]) -> tuple[str, int]:+ def _invoke_tool(+ self,+ tool_name: str,+ args: Dict[str, Any],+ *,+ call_id: str,+ ) -> tuple[str, int]:"""Execute a tool with heartbeat + structured progress emission.Installs a thread-local progress emitter so the tool may call@@ -1270,6 +1292,7 @@ class AgentLoop:Args:tool_name: Tool name to execute.args: Tool arguments dict.+ call_id: Stable identity of this tool invocation.Returns:Tuple of (result_str, elapsed_ms).@@ -1282,11 +1305,13 @@ class AgentLoop:returnpayload = event.to_dict()payload["tool"] = tool_name+ payload["call_id"] = call_idself._emit("tool_progress", payload)def _on_heartbeat(payload: Dict[str, Any]) -> None:if timed_out.is_set():return+ payload["call_id"] = call_idself._emit("tool_heartbeat", payload)t0 = _time.perf_counter()@@ -1328,6 +1353,7 @@ class AgentLoop:elapsed_ms = _elapsed_ms()payload: Dict[str, Any] = {"tool": tool_name,+ "call_id": call_id,"stage": stage,"message": message,"elapsed_s": round(elapsed_ms / 1000, 2),@@ -1468,7 +1494,16 @@ class AgentLoop:)preview = trace_result[:200]react_trace.append({"type": "tool_call", "tool": tc.name, "result_preview": preview})- self._emit("tool_result", {"tool": tc.name, "status": status, "elapsed_ms": elapsed_ms, "preview": preview})+ self._emit(+ "tool_result",+ {+ "tool": tc.name,+ "status": status,+ "elapsed_ms": elapsed_ms,+ "preview": preview,+ "call_id": tc.id,+ },+ )# -- Context compression ---------------------------------------------------diff --git a/agent/src/api/sessions_routes.py b/agent/src/api/sessions_routes.pyindex dbf9bb780..c1e6388da 100644--- a/agent/src/api/sessions_routes.py+++ b/agent/src/api/sessions_routes.py@@ -52,6 +52,7 @@ class MessageResponse(BaseModel):created_at: strlinked_attempt_id: Optional[str] = Nonemetadata: Optional[Dict[str, Any]] = None+ tool_trail: List[Dict[str, Any]] = Field(default_factory=list)class CreateGoalRequest(BaseModel):@@ -660,6 +661,7 @@ def register_sessions_routes(app: FastAPI) -> None:created_at=m.created_at,linked_attempt_id=m.linked_attempt_id,metadata=m.metadata if m.metadata else None,+ tool_trail=m.tool_trail,)for m in messages]diff --git a/agent/src/session/models.py b/agent/src/session/models.pyindex ef7fab89c..a6327c4a5 100644--- a/agent/src/session/models.py+++ b/agent/src/session/models.py@@ -92,6 +92,7 @@ class Message:created_at: Creation time in ISO format.linked_attempt_id: Related Attempt ID, if any.metadata: Additional metadata.+ tool_trail: Compact completed tool-call records for history hydration."""message_id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])@@ -101,6 +102,7 @@ class Message:created_at: str = field(default_factory=_utc_now_iso)linked_attempt_id: Optional[str] = Nonemetadata: Dict[str, Any] = field(default_factory=dict)+ tool_trail: List[Dict[str, Any]] = field(default_factory=list)def to_dict(self) -> Dict[str, Any]:"""Serialize the message to a dictionary.diff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex 99e4c2b24..abe6087db 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport asyncioimport concurrent.futures+import timefrom datetime import datetimefrom pathlib import Pathfrom typing import Any, Dict, Optional@@ -176,6 +177,11 @@ class SessionService:content=self._format_result_message(attempt),linked_attempt_id=attempt.attempt_id,metadata=reply_metadata,+ tool_trail=(+ result.get("tool_trail", [])+ if attempt.status == AttemptStatus.COMPLETED+ else []+ ),)self.store.append_message(reply)self._search_index.index_message(session.session_id, "assistant", reply.content)@@ -225,12 +231,15 @@ class SessionService:session_id = attempt.session_idattempt_id = attempt.attempt_idloop = asyncio.get_running_loop()+ tool_trail: list[Dict[str, Any]] = []safe_overrides = sanitize_session_overrides(session_config) if session_config else session_configagent_config = load_runtime_agent_config(overrides=safe_overrides)def event_callback(event_type: str, data: Dict[str, Any]) -> None:"""Forward AgentLoop events to the SSE event bus."""+ if event_type in {"tool_call", "tool_result"}:+ self._record_tool_trail_event(tool_trail, event_type, data)data["attempt_id"] = attempt_idself.event_bus.emit(session_id, event_type, data)@@ -274,6 +283,8 @@ class SessionService:finally:self._active_loops.pop(session_id, None)+ result["tool_trail"] = tool_trail+# Load metrics from the run output when available.if result.get("run_dir"):metrics = self._load_metrics(Path(result["run_dir"]))@@ -282,6 +293,79 @@ class SessionService:return result+ @staticmethod+ def _record_tool_trail_event(+ tool_trail: list[Dict[str, Any]],+ event_type: str,+ data: Dict[str, Any],+ ) -> None:+ """Consolidate live tool events into a compact history record.++ Args:+ tool_trail: Mutable per-attempt trail.+ event_type: Agent event type (`tool_call` or `tool_result`).+ data: Already-redacted live event payload.+ """+ tool = str(data.get("tool") or "")+ if not tool:+ return++ call_id_value = data.get("call_id")+ call_id = call_id_value if isinstance(call_id_value, str) and call_id_value else None++ if event_type == "tool_call":+ entry: Dict[str, Any] = {+ "tool": tool,+ "status": "running",+ "arguments": (+ dict(data["arguments"])+ if isinstance(data.get("arguments"), dict)+ else {}+ ),+ "timestamp": int(time.time() * 1000),+ }+ if call_id:+ entry["call_id"] = call_id+ tool_trail.append(entry)+ return++ match = None+ if call_id:+ match = next(+ (+ entry+ for entry in tool_trail+ if entry.get("call_id") == call_id+ and entry.get("status") == "running"+ ),+ None,+ )+ if match is None:+ match = next(+ (+ entry+ for entry in tool_trail+ if entry.get("tool") == tool+ and entry.get("status") == "running"+ ),+ None,+ )+ if match is None:+ match = {+ "tool": tool,+ "arguments": {},+ "timestamp": int(time.time() * 1000),+ }+ tool_trail.append(match)++ match["status"] = "ok" if data.get("status") == "ok" else "error"+ elapsed_ms = data.get("elapsed_ms")+ if isinstance(elapsed_ms, (int, float)) and not isinstance(elapsed_ms, bool):+ match["elapsed_ms"] = max(0, int(elapsed_ms))+ match["preview"] = str(data.get("preview") or "")+ if call_id:+ match["call_id"] = call_id+@staticmethoddef _convert_messages_to_history(messages: list) -> list[Dict[str, Any]]:"""Convert Session messages into OpenAI-format history.diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex bd17bcb47..a7b5bbd31 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -665,6 +665,7 @@ def run_worker(_emit(event_callback, "tool_call", agent_id, task_id,{"tool": tc.name, "iteration": iteration,+ "call_id": tc.id,"arguments": _preview_tool_arguments(tc.arguments),**mcp_meta},)@@ -701,6 +702,7 @@ def run_worker(task_id,{"tool": tc.name,+ "call_id": tc.id,"elapsed_ms": int(tc_elapsed * 1000),"status": "error" if result_is_error else "ok","iteration": iteration,diff --git a/agent/tests/test_agent_loop_dsml_tool_calls.py b/agent/tests/test_agent_loop_dsml_tool_calls.pyindex 06a16f80e..5307eaae7 100644--- a/agent/tests/test_agent_loop_dsml_tool_calls.py+++ b/agent/tests/test_agent_loop_dsml_tool_calls.py@@ -7,6 +7,7 @@ from pathlib import Pathfrom typing import Anyfrom src.agent.loop import AgentLoop+from src.agent.progress import emit_progressfrom src.agent.tools import BaseTool, ToolRegistryfrom src.memory.persistent import PersistentMemoryfrom src.providers.chat import ChatLLM@@ -53,6 +54,7 @@ class _EchoProbeTool(BaseTool):is_readonly = Falsedef execute(self, **kwargs: Any) -> str:+ emit_progress("echoing", current=1, total=1)return json.dumps({"status": "ok", "marker": kwargs.get("marker")})@@ -63,8 +65,27 @@ def _chat_llm(fake_llm: _ScriptedStreamingLLM) -> ChatLLM:return client-def test_agent_loop_executes_dsml_textual_tool_call(tmp_path: Path) -> None:+def test_agent_loop_executes_dsml_textual_tool_call(+ tmp_path: Path,+ monkeypatch,+) -> None:"""A pure DSML response must execute as a tool call instead of final text."""+ class _ImmediateHeartbeatTimer:+ def __init__(self, tool_name: str, interval: float, emit) -> None:+ del interval+ self._tool_name = tool_name+ self._emit = emit++ def __enter__(self):+ self._emit({"tool": self._tool_name, "elapsed_s": 0.01})+ return self++ def __exit__(self, exc_type, exc, tb) -> None:+ return None++ monkeypatch.setattr(+ "src.agent.loop.HeartbeatTimer", _ImmediateHeartbeatTimer+ )dsml = ('<||DSML||tool_calls>''<||DSML||invoke name="echo_probe">'@@ -89,11 +110,21 @@ def test_agent_loop_executes_dsml_textual_tool_call(tmp_path: Path) -> None:assert result["status"] == "success"assert result["content"] == "final answer"- assert any(- event_type == "tool_call" and payload["tool"] == "echo_probe"+ tool_events = {+ event_type: payloadfor event_type, payload in events- )- assert any(- event_type == "tool_result" and payload["tool"] == "echo_probe"- for event_type, payload in events- )+ if event_type+ in {"tool_call", "tool_progress", "tool_heartbeat", "tool_result"}+ }+ assert set(tool_events) == {+ "tool_call",+ "tool_progress",+ "tool_heartbeat",+ "tool_result",+ }+ assert {+ payload["call_id"] for payload in tool_events.values()+ } == {"dsml_call_1"}+ assert {+ payload["tool"] for payload in tool_events.values()+ } == {"echo_probe"}diff --git a/agent/tests/test_session_tool_trail.py b/agent/tests/test_session_tool_trail.pynew file mode 100644index 000000000..e85d7bfa4--- /dev/null+++ b/agent/tests/test_session_tool_trail.py@@ -0,0 +1,202 @@+"""Session history regressions for completed-attempt tool trails."""++from __future__ import annotations++import asyncio+from pathlib import Path++from fastapi.testclient import TestClient++import api_server+from src.session.events import EventBus+from src.session.models import Attempt, Message, Session+from src.session.service import SessionService+from src.session.store import SessionStore+++class _DummyIndex:+ def index_session(self, session_id: str, title: str) -> None:+ del session_id, title++ def index_message(self, session_id: str, role: str, content: str) -> None:+ del session_id, role, content+++def _service(tmp_path: Path, monkeypatch) -> SessionService:+ monkeypatch.setattr("src.session.service.get_shared_index", lambda: _DummyIndex())+ return SessionService(+ store=SessionStore(tmp_path / "sessions"),+ event_bus=EventBus(),+ runs_dir=tmp_path / "runs",+ )+++def test_completed_attempt_tool_trail_round_trips_through_history_endpoint(+ tmp_path: Path,+ monkeypatch,+) -> None:+ service = _service(tmp_path, monkeypatch)+ session = Session(session_id="abcdef012345", title="tool trail")+ service.store.create_session(session)+ attempt = Attempt(+ attempt_id="attempt00001",+ session_id=session.session_id,+ prompt="Inspect AAPL",+ )+ service.store.create_attempt(attempt)+ expected_trail = [+ {+ "tool": "get_market_data",+ "status": "ok",+ "arguments": {"symbol": "AAPL"},+ "elapsed_ms": 125,+ "preview": "AAPL 195.00",+ "call_id": "call-market-1",+ "timestamp": 1_785_342_400_000,+ }+ ]++ async def _run_with_agent(*args, **kwargs):+ del args, kwargs+ return {+ "status": "success",+ "content": "AAPL is trading near 195.",+ "tool_trail": expected_trail,+ }++ monkeypatch.setattr(service, "_run_with_agent", _run_with_agent)+ asyncio.run(service._run_attempt(session, attempt))++ monkeypatch.setattr(api_server, "_get_session_service", lambda: service)+ client = TestClient(api_server.app, client=("127.0.0.1", 50000))+ response = client.get(f"/sessions/{session.session_id}/messages")++ assert response.status_code == 200+ assert response.json() == [+ {+ "message_id": service.store.get_messages(session.session_id)[0].message_id,+ "session_id": session.session_id,+ "role": "assistant",+ "content": "AAPL is trading near 195.",+ "created_at": service.store.get_messages(session.session_id)[0].created_at,+ "linked_attempt_id": attempt.attempt_id,+ "metadata": {"status": "completed"},+ "tool_trail": expected_trail,+ }+ ]++ stored = service.store.get_messages(session.session_id)[0]+ assert isinstance(stored, Message)+ assert stored.tool_trail == expected_trail+++def test_run_with_agent_consolidates_tool_events_by_call_id(+ tmp_path: Path,+ monkeypatch,+) -> None:+ class _DummyAgentLoop:+ def __init__(+ self,+ *,+ registry,+ llm,+ event_callback,+ max_iterations,+ persistent_memory,+ ) -> None:+ del registry, llm, max_iterations, persistent_memory+ self._event_callback = event_callback++ def run(self, *, user_message: str, history, session_id: str):+ del user_message, history, session_id+ self._event_callback(+ "tool_call",+ {+ "tool": "get_market_data",+ "call_id": "call-1",+ "arguments": {"symbol": "AAPL"},+ },+ )+ self._event_callback(+ "tool_call",+ {+ "tool": "get_market_data",+ "call_id": "call-2",+ "arguments": {"symbol": "MSFT"},+ },+ )+ self._event_callback(+ "tool_result",+ {+ "tool": "get_market_data",+ "call_id": "call-2",+ "status": "ok",+ "elapsed_ms": 20,+ "preview": "MSFT",+ },+ )+ self._event_callback(+ "tool_result",+ {+ "tool": "get_market_data",+ "call_id": "call-1",+ "status": "error",+ "elapsed_ms": 10,+ "preview": "AAPL unavailable",+ },+ )+ return {"status": "success", "content": "done"}++ def cancel(self) -> None:+ pass++ monkeypatch.setattr("src.tools.build_registry", lambda **kwargs: object())+ monkeypatch.setattr("src.providers.chat.ChatLLM", lambda: object())+ monkeypatch.setattr("src.memory.persistent.PersistentMemory", lambda: object())+ monkeypatch.setattr("src.agent.loop.AgentLoop", _DummyAgentLoop)+ monkeypatch.setattr(+ "src.config.loader.load_runtime_agent_config",+ lambda overrides=None: object(),+ )+ monkeypatch.setattr(+ "src.config.loader.sanitize_session_overrides",+ lambda overrides: dict(overrides),+ )+ service = _service(tmp_path, monkeypatch)+ attempt = Attempt(session_id="abcdef012345", prompt="compare")++ result = asyncio.run(+ service._run_with_agent(attempt, messages=[], session_config={})+ )++ assert [+ {+ key: entry[key]+ for key in (+ "tool",+ "call_id",+ "arguments",+ "status",+ "elapsed_ms",+ "preview",+ )+ }+ for entry in result["tool_trail"]+ ] == [+ {+ "tool": "get_market_data",+ "call_id": "call-1",+ "arguments": {"symbol": "AAPL"},+ "status": "error",+ "elapsed_ms": 10,+ "preview": "AAPL unavailable",+ },+ {+ "tool": "get_market_data",+ "call_id": "call-2",+ "arguments": {"symbol": "MSFT"},+ "status": "ok",+ "elapsed_ms": 20,+ "preview": "MSFT",+ },+ ]diff --git a/agent/tests/test_swarm_m4_e2e.py b/agent/tests/test_swarm_m4_e2e.pyindex 023138b72..b703e9a02 100644--- a/agent/tests/test_swarm_m4_e2e.py+++ b/agent/tests/test_swarm_m4_e2e.py@@ -480,6 +480,8 @@ def test_tool_call_events_carry_mcp_metadata_and_redact_sensitive_arguments(assert call_data["remote_tool"] == "search"assert result_data["server"] == "kb"assert result_data["remote_tool"] == "search"+ assert call_data["call_id"] == "tc-1"+ assert result_data["call_id"] == "tc-1"assert result_data["status"] == "ok"# R-10: redaction is applied to known sensitive keys.diff --git a/agent/tests/test_tool_timeout.py b/agent/tests/test_tool_timeout.pyindex aec4ec4ec..9bf60f74e 100644--- a/agent/tests/test_tool_timeout.py+++ b/agent/tests/test_tool_timeout.py@@ -51,7 +51,9 @@ def test_tool_timeout_returns_error_and_stops_heartbeats(monkeypatch) -> None:max_iterations=1,)- result, elapsed_ms = agent._invoke_tool("slow_tool", {})+ result, elapsed_ms = agent._invoke_tool(+ "slow_tool", {}, call_id="slow-call"+ )event_count_at_return = len(events)time.sleep(0.08)@@ -61,6 +63,12 @@ def test_tool_timeout_returns_error_and_stops_heartbeats(monkeypatch) -> None:assert payload["tool"] == "slow_tool"assert elapsed_ms >= 40assert len(events) == event_count_at_return+ timeout_event = next(+ data+ for event_type, data in events+ if event_type == "tool_progress" and data.get("stage") == "timeout"+ )+ assert timeout_event["call_id"] == "slow-call"def test_write_tool_timeout_warns_but_does_not_return_before_completion(monkeypatch) -> None:@@ -76,12 +84,16 @@ def test_write_tool_timeout_warns_but_does_not_return_before_completion(monkeypamax_iterations=1,)- result, elapsed_ms = agent._invoke_tool("place_order", {})+ result, elapsed_ms = agent._invoke_tool(+ "place_order", {}, call_id="write-call"+ )assert json.loads(result) == {"status": "ok"}assert registry.completed is Trueassert elapsed_ms >= 70assert any(- event_type == "tool_progress" and data.get("stage") == "timeout_warning"+ event_type == "tool_progress"+ and data.get("stage") == "timeout_warning"+ and data.get("call_id") == "write-call"for event_type, data in events)diff --git a/frontend/src/components/chat/ConversationTimeline.tsx b/frontend/src/components/chat/ConversationTimeline.tsxindex 39fdc07ad..dd3cbca80 100644--- a/frontend/src/components/chat/ConversationTimeline.tsx+++ b/frontend/src/components/chat/ConversationTimeline.tsx@@ -57,19 +57,25 @@ export const ConversationTimeline = memo(function ConversationTimeline({ messagereturn (<div className="fixed right-3 top-1/2 -translate-y-1/2 h-2/3 flex flex-col justify-between items-center z-20 py-4">- {userIndices.map((idx) => (- <button- key={idx}- onClick={() => scrollTo(idx)}- className={cn(- "rounded-full transition-all shrink-0",- idx === activeIdx- ? "w-3 h-3 bg-primary shadow-sm shadow-primary/30"- : "w-2 h-2 bg-muted-foreground/25 hover:bg-muted-foreground/50"- )}- title={messages[idx].content.slice(0, 40)}- />- ))}+ {userIndices.map((idx) => {+ const prompt = messages[idx].content.slice(0, 40);+ const active = idx === activeIdx;+ return (+ <button+ key={idx}+ onClick={() => scrollTo(idx)}+ aria-current={active ? "true" : undefined}+ aria-label={prompt}+ className={cn(+ "rounded-full transition-all shrink-0",+ active+ ? "w-3 h-3 bg-primary shadow-sm shadow-primary/30"+ : "w-2 h-2 bg-muted-foreground/25 hover:bg-muted-foreground/50"+ )}+ title={prompt}+ />+ );+ })}</div>);});diff --git a/frontend/src/components/chat/MandateProposalCard.tsx b/frontend/src/components/chat/MandateProposalCard.tsxindex c83e69edd..716d3d93c 100644--- a/frontend/src/components/chat/MandateProposalCard.tsx+++ b/frontend/src/components/chat/MandateProposalCard.tsx@@ -27,12 +27,18 @@ function formatUsd(value: number): string {return `$${value.toLocaleString("en-US", { maximumFractionDigits: 0 })}`;}+function translateManifestKey(key: string, values: Record<string, string | number>): string {+ return String(i18n.t(key as never, values as never));+}+function formatLeverage(leverage: MandateProfile["leverage"]): string {if (typeof leverage === "number") {- return leverage <= 1 ? "no leverage" : `${leverage}× leverage`;+ return leverage <= 1+ ? i18n.t("mandate.noLeverage")+ : i18n.t("mandate.leverageValue", { value: leverage });}const lowered = leverage.toLowerCase();- return lowered === "none" || lowered === "" ? "no leverage" : leverage;+ return lowered === "none" || lowered === "" ? i18n.t("mandate.noLeverage") : leverage;}function formatUniverse(universe: MandateProfile["universe"]): string {@@ -109,7 +115,9 @@ function ProfileTile({</div><div><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>+ <dd className="font-mono font-medium text-foreground">+ {i18n.t("mandate.tradesPerDay", { count: profile.daily_trade_cap })}+ </dd></div><div><dt className="text-muted-foreground">{i18n.t("mandate.leverage")}</dt>@@ -235,15 +243,25 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,<span className="inline-flex max-w-full flex-wrap items-center gap-1.5 rounded-lg bg-emerald-500/10 px-2.5 py-1 text-xs font-medium text-emerald-600 dark:text-emerald-400"><ShieldCheck className="h-3 w-3 shrink-0" /><span className="shrink-0">- Mandate {committed.selected_ordinal != null ? `#${committed.selected_ordinal} ` : ""}active+ {i18n.t("mandate.mandateActive", {+ id: committed.selected_ordinal != null ? `#${committed.selected_ordinal}` : "",+ })}</span>{maxOrder != null && (- <span className="shrink-0 font-mono text-[11px]">· ≤{formatUsd(maxOrder)}/order</span>+ <span className="shrink-0 font-mono text-[11px]">+ · {translateManifestKey("mandate.maxPerOrder", { amount: formatUsd(maxOrder) })}+ </span>+ )}+ {dailyCap != null && (+ <span className="shrink-0 font-mono text-[11px]">+ · {i18n.t("mandate.tradesPerDay", { count: dailyCap })}+ </span>)}- {dailyCap != null && <span className="shrink-0 font-mono text-[11px]">· {dailyCap}/day</span>}{expires && (<span className="shrink-0 text-[10px] text-muted-foreground">- · expires {expires.toLocaleDateString()}+ · {translateManifestKey("mandate.expiresOn", {+ date: expires.toLocaleDateString(i18n.resolvedLanguage || i18n.language),+ })}</span>)}</span>@@ -273,7 +291,11 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,)}{proposal.account && (<p className="mt-0.5 text-[11px] text-muted-foreground">- {proposal.account.broker} · {proposal.account.type} account · funded by {proposal.account.funded_by}+ {translateManifestKey("mandate.accountSummary", {+ broker: proposal.account.broker,+ type: proposal.account.type,+ fundedBy: proposal.account.funded_by,+ })}</p>)}</div>@@ -295,7 +317,11 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,onAdjustCancel={() => setAdjustingOrdinal(null)}onAdjustSubmit={(text) => {setAdjustingOrdinal(null);- onAdjust(`For mandate proposal "${profile.label}" (option ${profile.ordinal}): ${text}`);+ onAdjust(translateManifestKey("mandate.adjustRequestMessage", {+ label: profile.label,+ ordinal: profile.ordinal,+ text,+ }));}}/>))}diff --git a/frontend/src/components/chat/MessageBubble.tsx b/frontend/src/components/chat/MessageBubble.tsxindex 94a8de20e..1bfb1ec48 100644--- a/frontend/src/components/chat/MessageBubble.tsx+++ b/frontend/src/components/chat/MessageBubble.tsx@@ -210,14 +210,17 @@ export const MessageBubble = memo(function MessageBubble({ msg, onRetry }: Props<p className="text-sm text-danger leading-relaxed">{msg.content}</p></div>{onRetry && (- <button- onClick={() => onRetry(msg)}- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs text-muted-foreground hover:text-foreground hover:bg-muted/80 border border-transparent hover:border-border transition-all"- title={hint}- >- <RefreshCw className="h-3 w-3" />- <span>{hint}</span>- </button>+ <div className="space-y-1.5">+ <p className="text-xs leading-relaxed text-muted-foreground">{hint}</p>+ <button+ onClick={() => onRetry(msg)}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs text-muted-foreground hover:text-foreground hover:bg-muted/80 border border-transparent hover:border-border transition-all"+ title={i18n.t("messageBubble.retry" as never)}+ >+ <RefreshCw className="h-3 w-3" />+ <span>{i18n.t("messageBubble.retry" as never)}</span>+ </button>+ </div>)}</div></div>diff --git a/frontend/src/components/chat/MetricsCard.tsx b/frontend/src/components/chat/MetricsCard.tsxindex e09de188e..e1884c2f5 100644--- a/frontend/src/components/chat/MetricsCard.tsx+++ b/frontend/src/components/chat/MetricsCard.tsx@@ -35,7 +35,11 @@ export const MetricsCard = memo(function MetricsCard({ metrics, compact = falsecompact ? "grid-cols-3" : "grid-cols-[repeat(auto-fit,minmax(120px,1fr))]")}>{shown.map(({ k, v }) => (- <div key={k} className="text-center py-1">+ <div+ key={k}+ className="text-center py-1"+ title={i18n.t(`metrics.gloss.${k}` as never)}+ ><p className="text-[10px] text-muted-foreground uppercase tracking-wide font-medium">{getMetricLabel(k)}</p>diff --git a/frontend/src/components/chat/RunnerStatus.tsx b/frontend/src/components/chat/RunnerStatus.tsxindex 60b4058a1..3fd6508bd 100644--- a/frontend/src/components/chat/RunnerStatus.tsx+++ b/frontend/src/components/chat/RunnerStatus.tsx@@ -283,8 +283,19 @@ export function isVisibleRuntimeConnector(broker: LiveBrokerStatus): boolean {export const RunnerStatus = memo(function RunnerStatus({ status, unavailable, halted, onRefresh }: Props) {const [open, setOpen] = useState(false);+ const [, setVisibilityRefresh] = useState(0);const visibleBrokers = status?.brokers.filter(isVisibleRuntimeConnector) ?? [];+ useEffect(() => {+ const refreshOnTabRestore = () => {+ if (document.visibilityState !== "visible") return;+ setVisibilityRefresh(Date.now());+ onRefresh();+ };+ document.addEventListener("visibilitychange", refreshOnTabRestore);+ return () => document.removeEventListener("visibilitychange", refreshOnTabRestore);+ }, [onRefresh]);+if (unavailable) return null;if (!status || visibleBrokers.length === 0) return null;diff --git a/frontend/src/components/chat/SwarmDashboard.tsx b/frontend/src/components/chat/SwarmDashboard.tsxindex 666150e25..9ab378ea9 100644--- a/frontend/src/components/chat/SwarmDashboard.tsx+++ b/frontend/src/components/chat/SwarmDashboard.tsx@@ -266,7 +266,7 @@ export const SwarmDashboard = memo(function SwarmDashboard({) : (<><div- className="hidden min-w-0 sm:block"+ className="hidden min-w-0 md:block"data-agent-layout="wide"role="table">@@ -305,7 +305,7 @@ export const SwarmDashboard = memo(function SwarmDashboard({</div></div>- <div className="space-y-2 sm:hidden" data-agent-layout="narrow">+ <div className="space-y-2 md:hidden" data-agent-layout="narrow">{agents.map((agent) => (<NarrowAgentCardagent={agent}diff --git a/frontend/src/components/chat/WelcomeScreen.tsx b/frontend/src/components/chat/WelcomeScreen.tsxindex 454591781..f6aa86dc4 100644--- a/frontend/src/components/chat/WelcomeScreen.tsx+++ b/frontend/src/components/chat/WelcomeScreen.tsx@@ -1,4 +1,4 @@-import { useState } from "react";+import { useRef, useState } from "react";import { useTranslation } from "react-i18next";import { ChevronDown, TrendingUp, Globe, Sparkles, Users, UserCircle2, NotebookPen, Landmark, Gem } from "lucide-react";import { BrandMark } from "@/components/common/BrandMark";@@ -239,6 +239,7 @@ export function WelcomeScreen({ onExample }: Props) {const { t } = useTranslation();const [greetingKey] = useState(() => pickGreetingKey());const [isExamplesOpen, setIsExamplesOpen] = useState(false);+ const examplesTriggerRef = useRef<HTMLButtonElement>(null);return (<div className="flex w-full flex-col items-center px-4 pb-14 text-center">@@ -278,6 +279,7 @@ export function WelcomeScreen({ onExample }: Props) {</div><button+ ref={examplesTriggerRef}type="button"aria-expanded={isExamplesOpen}aria-controls="welcome-example-library"@@ -294,6 +296,13 @@ export function WelcomeScreen({ onExample }: Props) {<divid="welcome-example-library"aria-hidden={!isExamplesOpen}+ onKeyDown={(event) => {+ if (event.key !== "Escape" || !isExamplesOpen) return;+ event.preventDefault();+ event.stopPropagation();+ setIsExamplesOpen(false);+ examplesTriggerRef.current?.focus();+ }}className={`grid text-left transition-[grid-template-rows,opacity] duration-300 ease-out ${isExamplesOpen? "grid-rows-[1fr] opacity-100"@@ -315,7 +324,7 @@ export function WelcomeScreen({ onExample }: Props) {type="button"tabIndex={isExamplesOpen ? 0 : -1}onClick={() => onExample(t(ex.promptKey as any))}- className="block w-full rounded-xl border border-border/60 px-3 py-2.5 text-left transition-colors hover:border-primary/40 hover:bg-muted/40"+ className="block w-full rounded-xl border border-border/60 px-3 py-2.5 text-left transition-colors hover:border-primary/40 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40"><span className="text-sm font-medium leading-snug text-foreground">{t(ex.titleKey as any)}diff --git a/frontend/src/components/chat/__tests__/ConversationTimeline.test.tsx b/frontend/src/components/chat/__tests__/ConversationTimeline.test.tsxindex dfaa095ec..1d93333bf 100644--- a/frontend/src/components/chat/__tests__/ConversationTimeline.test.tsx+++ b/frontend/src/components/chat/__tests__/ConversationTimeline.test.tsx@@ -1,10 +1,10 @@import { createRef } from "react";-import { render, screen } from "@testing-library/react";+import { render, screen, waitFor } from "@testing-library/react";import { ConversationTimeline } from "../ConversationTimeline";import type { AgentMessage } from "@/types/agent";describe("ConversationTimeline", () => {- it("caps the minimap at the 40 most recent user messages", () => {+ it("caps the minimap at the 40 most recent user messages", async () => {const messages: AgentMessage[] = Array.from({ length: 50 }, (_, index) => ({id: `message-${index}`,type: "user",@@ -24,5 +24,14 @@ describe("ConversationTimeline", () => {expect(screen.queryByTitle("Prompt 9")).not.toBeInTheDocument();expect(screen.getByTitle("Prompt 10")).toBeInTheDocument();expect(screen.getByTitle("Prompt 49")).toBeInTheDocument();+ await waitFor(() => {+ expect(screen.getByRole("button", { name: "Prompt 10" })).toHaveAttribute(+ "aria-current",+ "true",+ );+ });+ expect(screen.getByRole("button", { name: "Prompt 49" })).not.toHaveAttribute(+ "aria-current",+ );});});diff --git a/frontend/src/components/chat/__tests__/MessageBubble.test.tsx b/frontend/src/components/chat/__tests__/MessageBubble.test.tsxindex 947ea1542..e733dd85a 100644--- a/frontend/src/components/chat/__tests__/MessageBubble.test.tsx+++ b/frontend/src/components/chat/__tests__/MessageBubble.test.tsx@@ -30,6 +30,10 @@ function makeMsg(overrides: Partial<StoredAgentMessage> = {}): StoredAgentMessag}describe("MessageBubble", () => {+ beforeAll(() => {+ i18n.addResource("en", "translation", "messageBubble.retry", "Try again");+ });+describe("user messages", () => {it("renders user content in the bounded neutral bubble without an avatar or timestamp", () => {const { container } = render(@@ -132,14 +136,21 @@ describe("MessageBubble", () => {expect(onRetry).toHaveBeenCalledWith(msg);});- it("shows timeout hint for timeout errors", () => {+ it("shows the timeout hint as muted text above a short retry action", () => {render(<MessageBubblemsg={makeMsg({ type: "error", content: "Execution timed out after 600s" })}onRetry={vi.fn()}/>,);- expect(screen.getByText(/Try simplifying the strategy/)).toBeInTheDocument();+ const hint = screen.getByText(/Timed out/);+ const retry = screen.getByRole("button", { name: "Try again" });++ expect(hint.tagName).toBe("P");+ expect(hint).toHaveClass("text-muted-foreground");+ expect(retry).toHaveTextContent("Try again");+ expect(retry).not.toHaveTextContent(hint.textContent ?? "");+ expect(hint.compareDocumentPosition(retry) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();});});diff --git a/frontend/src/components/chat/__tests__/MetricsCard.test.tsx b/frontend/src/components/chat/__tests__/MetricsCard.test.tsxindex 1be54761d..9dc450317 100644--- a/frontend/src/components/chat/__tests__/MetricsCard.test.tsx+++ b/frontend/src/components/chat/__tests__/MetricsCard.test.tsx@@ -1,4 +1,5 @@import { render, screen } from "@testing-library/react";+import i18n from "../../../i18n";import { MetricsCard } from "../MetricsCard";describe("MetricsCard", () => {@@ -11,6 +12,22 @@ describe("MetricsCard", () => {trade_count: 42,};+ beforeAll(() => {+ i18n.addResourceBundle(+ "en",+ "translation",+ {+ metrics: {+ gloss: {+ sharpe: "Return earned per unit of total risk.",+ },+ },+ },+ true,+ true,+ );+ });+it("renders nothing when metrics is empty", () => {const { container } = render(<MetricsCard metrics={{}} />);expect(container.innerHTML).toBe("");@@ -24,6 +41,15 @@ describe("MetricsCard", () => {expect(screen.getByText("Trades")).toBeInTheDocument();});+ it("adds a localized plain-language tooltip to each metric cell", () => {+ render(<MetricsCard metrics={{ sharpe: 1.5 }} />);++ expect(screen.getByText("Sharpe").parentElement).toHaveAttribute(+ "title",+ "Return earned per unit of total risk.",+ );+ });+it("renders formatted metric values", () => {render(<MetricsCard metrics={sampleMetrics} />);expect(screen.getByText("+12.34%")).toBeInTheDocument();diff --git a/frontend/src/components/chat/__tests__/RunnerStatus.test.tsx b/frontend/src/components/chat/__tests__/RunnerStatus.test.tsxindex de8ae2c65..d152ca343 100644--- a/frontend/src/components/chat/__tests__/RunnerStatus.test.tsx+++ b/frontend/src/components/chat/__tests__/RunnerStatus.test.tsx@@ -124,4 +124,24 @@ describe("RunnerStatus compact connector panel", () => {expect(container).toBeEmptyDOMElement();});++ it("refreshes timestamps and status immediately when a hidden tab becomes visible", () => {+ const onRefresh = vi.fn();+ render(+ <RunnerStatus+ status={status([+ broker("longbridge", { configured: true, connection_state: "connected" }),+ ])}+ onRefresh={onRefresh}+ />,+ );+ Object.defineProperty(document, "visibilityState", {+ configurable: true,+ value: "visible",+ });++ document.dispatchEvent(new Event("visibilitychange"));++ expect(onRefresh).toHaveBeenCalledTimes(1);+ });});diff --git a/frontend/src/components/chat/__tests__/SwarmDashboard.test.tsx b/frontend/src/components/chat/__tests__/SwarmDashboard.test.tsxindex 965c101c9..6a779cb3b 100644--- a/frontend/src/components/chat/__tests__/SwarmDashboard.test.tsx+++ b/frontend/src/components/chat/__tests__/SwarmDashboard.test.tsx@@ -51,6 +51,10 @@ describe("SwarmDashboard", () => {expect(html).toContain('data-agent-layout="wide"');expect(html).toContain('data-agent-layout="narrow"');+ expect(html).toContain("hidden min-w-0 md:block");+ expect(html).toContain("space-y-2 md:hidden");+ expect(html).not.toContain("hidden min-w-0 sm:block");+ expect(html).not.toContain("space-y-2 sm:hidden");expect(html).toContain("grid-cols-[minmax(0,1.25fr)_minmax(0,0.85fr)_minmax(0,1fr)_minmax(0,0.55fr)_minmax(0,1.5fr)]",);diff --git a/frontend/src/components/chat/__tests__/SwarmStatusCard.test.tsx b/frontend/src/components/chat/__tests__/SwarmStatusCard.test.tsxindex b4e987fe7..2728c57f9 100644--- a/frontend/src/components/chat/__tests__/SwarmStatusCard.test.tsx+++ b/frontend/src/components/chat/__tests__/SwarmStatusCard.test.tsx@@ -85,7 +85,7 @@ describe("SwarmStatusCard", () => {);expect(html).not.toContain("0/1");- expect(html).not.toContain("Layer 1/1");+ expect(html).not.toContain("Round 1 of 1");expect(html).not.toContain('value="0" max="1"');expect(html).toContain('data-layer-state="indeterminate"');expect(html).toContain(@@ -101,11 +101,11 @@ describe("SwarmStatusCard", () => {const html = renderToStaticMarkup(<SwarmStatusCard status={makeStatus()} />);expect(html).toContain("3/6 agents");- expect(html).toContain("Layer 1/2");+ expect(html).toContain("Round 1 of 2");expect(html).toContain('data-layer-state="determinate"');expect(html).toContain('role="progressbar"');expect(html).toContain('aria-valuemin="0"');- expect(html).toContain('aria-valuetext="Layer 1/2"');+ expect(html).toContain('aria-valuetext="Round 1 of 2"');expect(html).toContain("grid h-1.5 min-w-0 gap-1");expect(html).not.toContain("grid h-2 min-w-0 gap-1");expect(html).not.toContain(diff --git a/frontend/src/components/chat/__tests__/ThinkingTimeline.test.tsx b/frontend/src/components/chat/__tests__/ThinkingTimeline.test.tsxindex ec8678a06..19845b2fe 100644--- a/frontend/src/components/chat/__tests__/ThinkingTimeline.test.tsx+++ b/frontend/src/components/chat/__tests__/ThinkingTimeline.test.tsx@@ -39,7 +39,7 @@ describe("ThinkingTimeline", () => {];render(<ThinkingTimeline messages={msgs} isLatest />);- expect(screen.getByText(/Running Run backtest/)).toBeInTheDocument();+ expect(screen.getByText(/Running Run the backtest/)).toBeInTheDocument();});it("expands and collapses on click", async () => {@@ -113,7 +113,7 @@ describe("ThinkingTimeline", () => {await user.click(screen.getByRole("button"));expect(screen.getByText("Run command")).toBeInTheDocument();expect(screen.getByText("Generate code")).toBeInTheDocument();- expect(screen.getByText("Run backtest")).toBeInTheDocument();+ expect(screen.getByText("Run the backtest")).toBeInTheDocument();});it("exposes disclosure semantics and preserves an explicit user expansion", async () => {@@ -145,6 +145,6 @@ describe("ThinkingTimeline", () => {makeMsg({ type: "tool_call", tool: "unusually_long_tool_name", status: "running" }),]} />);- expect(screen.getByText(/Running unusually_long_tool_name/)).toHaveClass("truncate");+ expect(screen.getByText(/Running Unusually long tool name/)).toHaveClass("truncate");});});diff --git a/frontend/src/components/chat/__tests__/ToolProgressIndicator.test.tsx b/frontend/src/components/chat/__tests__/ToolProgressIndicator.test.tsxindex 084bcd746..4ee9e5fe2 100644--- a/frontend/src/components/chat/__tests__/ToolProgressIndicator.test.tsx+++ b/frontend/src/components/chat/__tests__/ToolProgressIndicator.test.tsx@@ -32,7 +32,7 @@ describe("ToolProgressIndicator", () => {const tcs = [makeTc({ status: "ok" }), makeTc({ id: "tc-2", status: "error" })];render(<ToolProgressIndicator toolCalls={tcs} />);expect(screen.getAllByText("2 tools completed")).toHaveLength(2);- expect(screen.getAllByText(/Run backtest/)).toHaveLength(2);+ expect(screen.getAllByText(/Run the backtest/)).toHaveLength(2);});it("renders nothing for empty array", () => {@@ -44,7 +44,7 @@ describe("ToolProgressIndicator", () => {const tcs = [makeTc({ elapsed_s: 5 })];render(<ToolProgressIndicator toolCalls={tcs} />);expect(screen.getByRole("status")).toBeInTheDocument();- expect(screen.getByText(/Run backtest/)).toBeInTheDocument();+ expect(screen.getByText(/Run the backtest/)).toBeInTheDocument();expect(screen.getByText("5s")).toBeInTheDocument();});@@ -65,7 +65,7 @@ describe("ToolProgressIndicator", () => {makeTc({ id: "backtest#2", status: "running" }),];render(<ToolProgressIndicator toolCalls={tcs} />);- expect(screen.getAllByText(/Run backtest/)).toHaveLength(2);+ expect(screen.getAllByText(/Run the backtest/)).toHaveLength(2);});it("shows the most recent running tools behind a clickable earlier count", async () => {@@ -80,7 +80,7 @@ describe("ToolProgressIndicator", () => {expect(screen.queryByText(/Run command/)).not.toBeInTheDocument();expect(screen.queryByText(/Generate code/)).not.toBeInTheDocument();- expect(screen.getByText(/Run backtest/)).toBeInTheDocument();+ expect(screen.getByText(/Run the backtest/)).toBeInTheDocument();expect(screen.getByText(/Read file/)).toBeInTheDocument();await user.click(screen.getByRole("button", { name: "+2 earlier" }));@@ -101,7 +101,7 @@ describe("ToolProgressIndicator", () => {const visibleSteps = screen.getAllByText(/^Step /).map((node) => node.textContent);expect(visibleSteps).toEqual(["Step 4 · Read file",- "Step 3 · Run backtest",+ "Step 3 · Run the backtest",]);expect(screen.queryByText(/Generate code/)).not.toBeInTheDocument();diff --git a/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx b/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsxindex bb23e44dd..52e27102b 100644--- a/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx+++ b/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx@@ -117,6 +117,11 @@ describe("WelcomeScreen", () => {expect(trigger).toHaveAttribute("aria-expanded", "true");expect(library).toHaveAttribute("aria-hidden", "false");expect(within(library!).getAllByRole("button")).toHaveLength(21);+ expect(library!.querySelectorAll('svg[aria-hidden="true"]')).toHaveLength(8);+ expect(within(library!).getAllByRole("button")[0]).toHaveClass(+ "focus-visible:ring-2",+ "focus-visible:ring-primary/40",+ );for (const category of ["A-Share Backtest","Research & Analysis",@@ -131,6 +136,23 @@ describe("WelcomeScreen", () => {}});+ it("closes the example library with Escape and restores focus to its trigger", async () => {+ const user = userEvent.setup();+ render(<WelcomeScreen onExample={onExample} />);++ const trigger = screen.getByRole("button", { name: "Browse all examples" });+ await user.click(trigger);+ const library = document.getElementById("welcome-example-library")!;+ const firstExample = within(library).getAllByRole("button")[0];+ firstExample.focus();++ await user.keyboard("{Escape}");++ expect(trigger).toHaveAttribute("aria-expanded", "false");+ expect(library).toHaveAttribute("aria-hidden", "true");+ expect(trigger).toHaveFocus();+ });+it("does not render capability chips", () => {render(<WelcomeScreen onExample={onExample} />);diff --git a/frontend/src/components/common/ConfirmDialog.tsx b/frontend/src/components/common/ConfirmDialog.tsxindex 278baf735..32ea5c00c 100644--- a/frontend/src/components/common/ConfirmDialog.tsx+++ b/frontend/src/components/common/ConfirmDialog.tsx@@ -32,16 +32,51 @@ export function ConfirmDialog({children,}: ConfirmDialogProps) {const confirmRef = useRef<HTMLButtonElement>(null);+ const dialogRef = useRef<HTMLDivElement>(null);+ const onCancelRef = useRef(onCancel);+ onCancelRef.current = onCancel;useEffect(() => {if (!open) return;+ const previouslyFocused = document.activeElement instanceof HTMLElement+ ? document.activeElement+ : null;confirmRef.current?.focus();const onKeyDown = (e: KeyboardEvent) => {- if (e.key === "Escape") onCancel();+ if (e.key === "Escape") {+ e.preventDefault();+ onCancelRef.current();+ return;+ }+ if (e.key !== "Tab") return;++ const dialog = dialogRef.current;+ if (!dialog) return;+ const focusable = Array.from(dialog.querySelectorAll<HTMLElement>(+ 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',+ ));+ if (focusable.length === 0) {+ e.preventDefault();+ return;+ }++ const first = focusable[0];+ const last = focusable[focusable.length - 1];+ const active = document.activeElement;+ if (e.shiftKey && (active === first || !dialog.contains(active))) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && (active === last || !dialog.contains(active))) {+ e.preventDefault();+ first.focus();+ }};document.addEventListener("keydown", onKeyDown);- return () => document.removeEventListener("keydown", onKeyDown);- }, [open, onCancel]);+ return () => {+ document.removeEventListener("keydown", onKeyDown);+ if (previouslyFocused?.isConnected) previouslyFocused.focus();+ };+ }, [open]);if (!open) return null;@@ -51,6 +86,7 @@ export function ConfirmDialog({onClick={onCancel}><div+ ref={dialogRef}role="alertdialog"aria-modal="true"aria-labelledby="confirm-dialog-title"diff --git a/frontend/src/components/common/__tests__/ConfirmDialog.test.tsx b/frontend/src/components/common/__tests__/ConfirmDialog.test.tsxnew file mode 100644index 000000000..349308144--- /dev/null+++ b/frontend/src/components/common/__tests__/ConfirmDialog.test.tsx@@ -0,0 +1,47 @@+import { useState } from "react";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { ConfirmDialog } from "../ConfirmDialog";++function DialogHarness() {+ const [open, setOpen] = useState(false);+ return (+ <>+ <button type="button" onClick={() => setOpen(true)}>+ Open dialog+ </button>+ <ConfirmDialog+ open={open}+ title="Delete session?"+ confirmLabel="Delete"+ cancelLabel="Cancel"+ onConfirm={() => setOpen(false)}+ onCancel={() => setOpen(false)}+ />+ </>+ );+}++describe("ConfirmDialog keyboard focus", () => {+ it("traps Tab inside the dialog and restores focus after Escape", async () => {+ const user = userEvent.setup();+ render(<DialogHarness />);++ const trigger = screen.getByRole("button", { name: "Open dialog" });+ await user.click(trigger);++ const confirm = screen.getByRole("button", { name: "Delete" });+ const cancel = screen.getByRole("button", { name: "Cancel" });+ expect(confirm).toHaveFocus();++ await user.tab();+ expect(cancel).toHaveFocus();++ await user.tab({ shift: true });+ expect(confirm).toHaveFocus();++ await user.keyboard("{Escape}");+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();+ expect(trigger).toHaveFocus();+ });+});diff --git a/frontend/src/components/common/__tests__/ErrorBoundary.test.tsx b/frontend/src/components/common/__tests__/ErrorBoundary.test.tsxindex 5e48b989b..5cac73f00 100644--- a/frontend/src/components/common/__tests__/ErrorBoundary.test.tsx+++ b/frontend/src/components/common/__tests__/ErrorBoundary.test.tsx@@ -56,6 +56,6 @@ describe("ErrorBoundary", () => {<ThrowEmpty /></ErrorBoundary>,);- expect(screen.getByText("Something went wrong")).toBeInTheDocument();+ expect(screen.getByText(/Something went wrong/)).toBeInTheDocument();});});diff --git a/frontend/src/components/layout/ConnectionBanner.tsx b/frontend/src/components/layout/ConnectionBanner.tsxindex a4e983133..fdbfe100e 100644--- a/frontend/src/components/layout/ConnectionBanner.tsx+++ b/frontend/src/components/layout/ConnectionBanner.tsx@@ -9,19 +9,32 @@ interface Props {export function ConnectionBanner({ status, retryAttempt }: Props) {const { t } = useTranslation();- if (status === "connected" || status === "disconnected") return null;+ if (status === "connected") return null;+ const terminal = status === "disconnected" || (+ status === "reconnecting" && (retryAttempt ?? 0) >= 5+ );return (- <div className="flex items-center gap-2 px-4 py-2 text-xs bg-warning/15 text-warning border-b border-warning/30">- {status === "reconnecting" ? (+ <div+ className="absolute inset-x-0 top-0 z-30 flex min-h-8 items-center gap-2 border-b border-warning/30 bg-warning/15 px-4 py-2 text-xs text-warning"+ role="status"+ >+ {!terminal ? (<>- <RefreshCw className="h-3.5 w-3.5 animate-spin" />+ <RefreshCw className="h-3.5 w-3.5 animate-spin" aria-hidden="true" /><span>{t('connection.reconnecting', { attempt: retryAttempt || 1 })}</span></>) : (<>- <WifiOff className="h-3.5 w-3.5" />+ <WifiOff className="h-3.5 w-3.5" aria-hidden="true" /><span>{t('connection.disconnected')}</span>+ <button+ type="button"+ onClick={() => window.location.reload()}+ className="ms-auto rounded-md border border-warning/40 px-2 py-0.5 font-medium transition-colors hover:bg-warning/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-warning/40"+ >+ {t('connection.reload' as never)}+ </button></>)}</div>diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex 25bb58145..78cbcb70b 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -44,6 +44,15 @@ export function Layout() {safeSet("qa-sidebar", collapsed ? "collapsed" : "expanded");}, [collapsed]);+ useEffect(() => {+ const syncSidebarPreference = (event: StorageEvent) => {+ if (event.key !== null && event.key !== "qa-sidebar") return;+ setCollapsed(safeGet("qa-sidebar") === "collapsed");+ };+ window.addEventListener("storage", syncSidebarPreference);+ return () => window.removeEventListener("storage", syncSidebarPreference);+ }, []);+const loadSessions = () => {api.listSessions().then((list) => setSessions(Array.isArray(list) ? list : []))@@ -277,7 +286,7 @@ export function Layout() {</aside>{/* Main */}- <div className="flex-1 flex flex-col overflow-hidden">+ <div className="relative flex-1 flex flex-col overflow-hidden"><ConnectionBanner status={sseStatus} retryAttempt={sseRetryAttempt} /><main id="main" className="flex-1 overflow-auto"><Outlet />@@ -380,7 +389,6 @@ function LanguageSwitcher() {ref={triggerRef}type="button"onClick={() => setOpen((v) => !v)}- aria-haspopup="menu"aria-expanded={open}aria-label={t("layout.language")}className="flex items-center gap-1 p-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors max-md:justify-center"diff --git a/frontend/src/components/layout/__tests__/ConnectionBanner.test.tsx b/frontend/src/components/layout/__tests__/ConnectionBanner.test.tsxindex 374b40294..4e5f99d7b 100644--- a/frontend/src/components/layout/__tests__/ConnectionBanner.test.tsx+++ b/frontend/src/components/layout/__tests__/ConnectionBanner.test.tsx@@ -1,15 +1,27 @@import { render, screen } from "@testing-library/react";+import i18n from "../../../i18n";import { ConnectionBanner } from "../ConnectionBanner";describe("ConnectionBanner", () => {+ beforeAll(() => {+ i18n.addResourceBundle(+ "en",+ "translation",+ { connection: { reload: "Reload" } },+ true,+ true,+ );+ });+it("renders nothing when status is connected", () => {const { container } = render(<ConnectionBanner status="connected" />);expect(container.innerHTML).toBe("");});- it("renders nothing when status is disconnected", () => {- const { container } = render(<ConnectionBanner status="disconnected" />);- expect(container.innerHTML).toBe("");+ it("renders the disconnected terminal state with a reload affordance", () => {+ render(<ConnectionBanner status="disconnected" />);+ expect(screen.getByText(/Connection lost/)).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();});it("shows the calm reconnecting message regardless of attempt count", () => {@@ -27,5 +39,14 @@ describe("ConnectionBanner", () => {const { container } = render(<ConnectionBanner status="reconnecting" retryAttempt={1} />);const banner = container.firstChild as HTMLElement;expect(banner.className).toMatch(/warning/);+ expect(banner).toHaveClass("absolute");+ });++ it("switches to the terminal state after five reconnect attempts", () => {+ render(<ConnectionBanner status="reconnecting" retryAttempt={5} />);++ expect(screen.getByText(/Connection lost/)).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();+ expect(document.querySelector(".animate-spin")).not.toBeInTheDocument();});});diff --git a/frontend/src/components/layout/__tests__/Layout.test.tsx b/frontend/src/components/layout/__tests__/Layout.test.tsxindex b3c644d63..e48d6fbed 100644--- a/frontend/src/components/layout/__tests__/Layout.test.tsx+++ b/frontend/src/components/layout/__tests__/Layout.test.tsx@@ -95,6 +95,7 @@ describe("Layout accessibility", () => {expect(screen.getByRole("link", { name: "New Chat" })).toHaveAttribute("title", "New Chat");expect(screen.getByText("Skip to main content")).toHaveAttribute("href", "#main");expect(screen.getByRole("main")).toHaveAttribute("id", "main");+ expect(screen.getByRole("main").parentElement).toHaveClass("relative");});it("exposes session actions on keyboard focus and labels the rename input", async () => {@@ -123,4 +124,24 @@ describe("Layout accessibility", () => {expect(() => renderLayout()).not.toThrow();});++ it("uses button disclosure semantics for the language switcher", () => {+ renderLayout();++ const languageButton = screen.getByRole("button", { name: "Language" });+ expect(languageButton).toHaveAttribute("aria-expanded", "false");+ expect(languageButton).not.toHaveAttribute("aria-haspopup");+ });++ it("synchronizes the sidebar preference from another tab", () => {+ window.localStorage.setItem("qa-sidebar", "expanded");+ renderLayout();+ const sidebar = screen.getByRole("complementary", { name: "Vibe-Trading sidebar" });+ expect(sidebar).toHaveClass("w-64");++ window.localStorage.setItem("qa-sidebar", "collapsed");+ fireEvent(window, new StorageEvent("storage", { key: "qa-sidebar" }));++ expect(sidebar).toHaveClass("w-12");+ });});diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 2c4ea47ee..748c29732 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -151,7 +151,8 @@},"connection": {"reconnecting": "جارٍ إعادة الاتصال…",- "disconnected": "فُقد الاتصال"+ "disconnected": "فُقد الاتصال",+ "reload": "Reload"},"welcome": {"categories": {@@ -448,7 +449,8 @@"swarmModeChip": "وضع السرب","goalModeChip": "هدف البحث","continueGoalMessage": "متابعة هدف البحث: {{goal}}",- "loadEarlier": "تحميل الرسائل الأقدم"+ "loadEarlier": "تحميل الرسائل الأقدم",+ "authRequired": "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use."},"runDetail": {"title": "تفاصيل التشغيل",@@ -784,14 +786,19 @@"adjustInputLabel": "محتوى طلب التعديل","confirmTitle": "تأكيد الالتزام بالتفويض","confirmDescription": "سيؤدي الالتزام إلى منح الوكيل صلاحية تداول فورية ضمن الحدود الموضحة أدناه.",- "confirmButton": "تأكيد والالتزام"+ "confirmButton": "تأكيد والالتزام",+ "maxPerOrder": "≤{{amount}}/order",+ "expiresOn": "expires {{date}}",+ "accountSummary": "{{broker}} · {{type}} account · funded by {{fundedBy}}",+ "adjustRequestMessage": "For mandate proposal \"{{label}}\" (option {{ordinal}}): {{text}}"},"messageBubble": {"copied": "تم النسخ","copy": "نسخ",- "timeoutHint": "انتهت مهلة التنفيذ. حاول تبسيط الاستراتيجية أو تقليل عدد الأصول.",- "apiFailedHint": "فشل استدعاء API. يرجى المحاولة لاحقًا.",- "executionFailedHint": "فشل التنفيذ. انقر للمحاولة مرة أخرى."+ "timeoutHint": "Timed out. Simplify the strategy or use fewer assets.",+ "apiFailedHint": "API request failed. Try again shortly.",+ "executionFailedHint": "Execution failed. Try again.",+ "retry": "Try again"},"pineViewer": {"pineScript": "Pine Script v6",@@ -871,6 +878,109 @@},"metrics": {"good": "جيد",- "poor": "ضعيف"+ "poor": "ضعيف",+ "gloss": {+ "total_return": "How much the strategy gained or lost over the full test period.",+ "annual_return": "The strategy's return scaled to a typical one-year period.",+ "sharpe": "Return earned per unit of total risk, where higher is generally better.",+ "max_drawdown": "The largest peak-to-trough loss during the test period.",+ "win_rate": "The share of completed trades that made a profit.",+ "trade_count": "The number of trades completed during the test period.",+ "calmar": "Annual return divided by maximum drawdown, balancing growth against worst loss.",+ "sortino": "Return earned per unit of downside risk, where higher is generally better.",+ "profit_loss_ratio": "The average winning trade compared with the average losing trade.",+ "max_consecutive_loss": "The longest run of losing trades in a row.",+ "benchmark_return": "The return of the comparison benchmark over the same period.",+ "excess_return": "How much the strategy outperformed or underperformed its benchmark.",+ "information_ratio": "Excess return earned per unit of tracking error against the benchmark.",+ "final_value": "The portfolio value at the end of the test period.",+ "avg_holding_days": "The average number of days each position stayed open."+ }+ },+ "tools": {+ "add_goal_evidence": "Add goal evidence",+ "alpha_bench": "Benchmark alpha factors",+ "alpha_compare": "Compare alpha factors",+ "alpha_zoo": "Browse alpha library",+ "analyze_image": "Analyze the image",+ "analyze_trade_journal": "Analyze trade journal",+ "background_run": "Start background task",+ "backtest": "Run the backtest",+ "bash": "Run command",+ "cancel_background": "Cancel background task",+ "check_background": "Check background task",+ "compact": "Summarize conversation",+ "create_hypothesis": "Create research hypothesis",+ "delete_skill": "Delete custom skill",+ "edit_file": "Edit code",+ "extract_shadow_strategy": "Extract shadow strategy",+ "factor_analysis": "Analyze factors",+ "financial_rigor": "Verify financial analysis",+ "generate_backtest_config": "Generate backtest config",+ "get_block_trades": "Fetch block trades",+ "get_dragon_tiger": "Fetch dragon-tiger list",+ "get_financial_statements": "Fetch financial statements",+ "get_fund_flow": "Fetch fund flow",+ "get_fundamentals": "Fetch fundamentals",+ "get_lockup_expiry": "Fetch lockup expiries",+ "get_macro_series": "Fetch macro series",+ "get_margin_trading": "Fetch margin trading",+ "get_market_data": "Fetch market data",+ "get_northbound_flow": "Fetch northbound flow",+ "get_options_chain": "Fetch options chain",+ "get_research_goal": "View research goal",+ "get_research_reports": "Fetch research reports",+ "get_sec_filings": "Fetch SEC filings",+ "get_sector_info": "Fetch sector data",+ "get_shareholder_count": "Fetch shareholder count",+ "get_stock_news": "Fetch stock news",+ "get_stock_profile": "Fetch stock profile",+ "iwencai_search": "Search iWenCai",+ "link_autopilot_backtest": "Link autopilot backtest",+ "link_backtest": "Link hypothesis backtest",+ "load_skill": "Load strategy knowledge",+ "options_pricing": "Price options",+ "patch_skill": "Update custom skill",+ "pattern": "Detect chart patterns",+ "portfolio_risk_xray": "X-ray portfolio risk",+ "propose_mandate_profiles": "Propose trading mandates",+ "qveris_execute": "Execute QVeris action",+ "qveris_inspect": "Inspect QVeris action",+ "qveris_search": "Search QVeris",+ "read_document": "Read document",+ "read_file": "Read file",+ "read_url": "Read webpage",+ "remember": "Remember this",+ "render_shadow_report": "Create shadow report",+ "report_audit": "Audit research report",+ "run_research_autopilot": "Run research autopilot",+ "run_shadow_backtest": "Run shadow backtest",+ "run_swarm": "Convene the team",+ "save_skill": "Save custom skill",+ "scaffold_signal_engine": "Build signal engine",+ "scan_shadow_signals": "Scan shadow signals",+ "screen_market": "Screen market",+ "sdm_decay_scan": "Scan strategy decay",+ "sdm_register": "Register strategy",+ "sdm_status": "Check strategy status",+ "search_hypotheses": "Search hypotheses",+ "search_symbol": "Search symbols",+ "session_search": "Search past sessions",+ "skill_file": "Read skill file",+ "start_research_goal": "Start research goal",+ "trading_account": "View broker account",+ "trading_cancel_order": "Cancel broker order",+ "trading_check": "Check broker connection",+ "trading_connections": "List broker connections",+ "trading_history": "View trade history",+ "trading_orders": "View broker orders",+ "trading_place_order": "Place broker order",+ "trading_positions": "View broker positions",+ "trading_quote": "Fetch broker quote",+ "trading_select_connection": "Select broker connection",+ "update_hypothesis": "Update research hypothesis",+ "update_research_goal_status": "Update goal status",+ "web_search": "Search the web",+ "write_file": "Generate code"}}diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 952d140c9..88244632c 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -3,9 +3,9 @@"version": "v0.1.12"},"charts": {- "noPriceData": "No price data",- "noCorrelationData": "No correlation data",- "noEquityData": "No equity data"+ "noPriceData": "No price data for this symbol yet",+ "noCorrelationData": "Pick at least two symbols to compare",+ "noEquityData": "No account-value curve yet — run a backtest first"},"layout": {"home": "Home",@@ -156,7 +156,8 @@},"connection": {"reconnecting": "Reconnecting…",- "disconnected": "Connection lost. Reload the page to reconnect."+ "disconnected": "Connection lost. Reload the page to reconnect.",+ "reload": "Reload"},"welcome": {"categories": {@@ -453,7 +454,8 @@"swarmModeChip": "Team mode","goalModeChip": "Research goal","continueGoalMessage": "Continue research goal: {{goal}}",- "loadEarlier": "Load earlier messages"+ "loadEarlier": "Load earlier messages",+ "authRequired": "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use."},"runDetail": {"title": "Run Detail",@@ -753,12 +755,12 @@},"swarmStatus": {"agents": "{{done}}/{{total}} agents",- "layer": "Layer {{current}}/{{total}}",+ "layer": "Round {{current}} of {{total}}","agent": "Agent","status": "Status","tool": "Tool","time": "Time",- "iters": "Iters",+ "iters": "Passes","output": "Output","waitingForEvents": "Waiting for agent events...","teamStarting": "The team is spinning up — first updates in a few seconds…",@@ -789,14 +791,19 @@"adjustInputLabel": "Adjustment request","confirmTitle": "Confirm mandate commit","confirmDescription": "This grants the agent trading authorization under the limits shown below and takes effect immediately.",- "confirmButton": "Confirm & commit"+ "confirmButton": "Confirm & commit",+ "maxPerOrder": "≤{{amount}}/order",+ "expiresOn": "expires {{date}}",+ "accountSummary": "{{broker}} · {{type}} account · funded by {{fundedBy}}",+ "adjustRequestMessage": "For mandate proposal \"{{label}}\" (option {{ordinal}}): {{text}}"},"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."+ "timeoutHint": "Timed out. Simplify the strategy or use fewer assets.",+ "apiFailedHint": "API request failed. Try again shortly.",+ "executionFailedHint": "Execution failed. Try again.",+ "retry": "Try again"},"pineViewer": {"pineScript": "Pine Script v6",@@ -833,19 +840,19 @@"step4Desc": "Optionally approve a trading mandate with explicit limits — nothing trades without your confirmation."},"errorBoundary": {- "somethingWrong": "Something went wrong"+ "somethingWrong": "Something went wrong. Reload the page to continue."},"toolProgress": {"step": "Step {{step}} · {{tool}}",- "toolsRunning": "Tools running: {{count}}",- "toolsCompleted": "Tools completed: {{count}}",+ "toolsRunning": "Working on {{count}} things at once",+ "toolsCompleted": "Finished {{count}} steps","more": "… +{{count}} more","etaSeconds": "~{{seconds}}s left","earlier": "+{{count}} earlier"},"swarm": {"assemblingTeam": "Assembling team…",- "preparingLayers": "Preparing layers…",+ "preparingLayers": "Working out who goes first…","agentProgress": "Swarm agent progress","status": {"waiting": "Waiting",@@ -871,6 +878,109 @@},"metrics": {"good": "good",- "poor": "poor"+ "poor": "poor",+ "gloss": {+ "total_return": "How much the strategy gained or lost over the full test period.",+ "annual_return": "The strategy's return scaled to a typical one-year period.",+ "sharpe": "Return earned per unit of total risk, where higher is generally better.",+ "max_drawdown": "The largest peak-to-trough loss during the test period.",+ "win_rate": "The share of completed trades that made a profit.",+ "trade_count": "The number of trades completed during the test period.",+ "calmar": "Annual return divided by maximum drawdown, balancing growth against worst loss.",+ "sortino": "Return earned per unit of downside risk, where higher is generally better.",+ "profit_loss_ratio": "The average winning trade compared with the average losing trade.",+ "max_consecutive_loss": "The longest run of losing trades in a row.",+ "benchmark_return": "The return of the comparison benchmark over the same period.",+ "excess_return": "How much the strategy outperformed or underperformed its benchmark.",+ "information_ratio": "Excess return earned per unit of tracking error against the benchmark.",+ "final_value": "The portfolio value at the end of the test period.",+ "avg_holding_days": "The average number of days each position stayed open."+ }+ },+ "tools": {+ "add_goal_evidence": "Add goal evidence",+ "alpha_bench": "Benchmark alpha factors",+ "alpha_compare": "Compare alpha factors",+ "alpha_zoo": "Browse alpha library",+ "analyze_image": "Analyze the image",+ "analyze_trade_journal": "Analyze trade journal",+ "background_run": "Start background task",+ "backtest": "Run the backtest",+ "bash": "Run command",+ "cancel_background": "Cancel background task",+ "check_background": "Check background task",+ "compact": "Summarize conversation",+ "create_hypothesis": "Create research hypothesis",+ "delete_skill": "Delete custom skill",+ "edit_file": "Edit code",+ "extract_shadow_strategy": "Extract shadow strategy",+ "factor_analysis": "Analyze factors",+ "financial_rigor": "Verify financial analysis",+ "generate_backtest_config": "Generate backtest config",+ "get_block_trades": "Fetch block trades",+ "get_dragon_tiger": "Fetch dragon-tiger list",+ "get_financial_statements": "Fetch financial statements",+ "get_fund_flow": "Fetch fund flow",+ "get_fundamentals": "Fetch fundamentals",+ "get_lockup_expiry": "Fetch lockup expiries",+ "get_macro_series": "Fetch macro series",+ "get_margin_trading": "Fetch margin trading",+ "get_market_data": "Fetch market data",+ "get_northbound_flow": "Fetch northbound flow",+ "get_options_chain": "Fetch options chain",+ "get_research_goal": "View research goal",+ "get_research_reports": "Fetch research reports",+ "get_sec_filings": "Fetch SEC filings",+ "get_sector_info": "Fetch sector data",+ "get_shareholder_count": "Fetch shareholder count",+ "get_stock_news": "Fetch stock news",+ "get_stock_profile": "Fetch stock profile",+ "iwencai_search": "Search iWenCai",+ "link_autopilot_backtest": "Link autopilot backtest",+ "link_backtest": "Link hypothesis backtest",+ "load_skill": "Load strategy knowledge",+ "options_pricing": "Price options",+ "patch_skill": "Update custom skill",+ "pattern": "Detect chart patterns",+ "portfolio_risk_xray": "X-ray portfolio risk",+ "propose_mandate_profiles": "Propose trading mandates",+ "qveris_execute": "Execute QVeris action",+ "qveris_inspect": "Inspect QVeris action",+ "qveris_search": "Search QVeris",+ "read_document": "Read document",+ "read_file": "Read file",+ "read_url": "Read webpage",+ "remember": "Remember this",+ "render_shadow_report": "Create shadow report",+ "report_audit": "Audit research report",+ "run_research_autopilot": "Run research autopilot",+ "run_shadow_backtest": "Run shadow backtest",+ "run_swarm": "Convene the team",+ "save_skill": "Save custom skill",+ "scaffold_signal_engine": "Build signal engine",+ "scan_shadow_signals": "Scan shadow signals",+ "screen_market": "Screen market",+ "sdm_decay_scan": "Scan strategy decay",+ "sdm_register": "Register strategy",+ "sdm_status": "Check strategy status",+ "search_hypotheses": "Search hypotheses",+ "search_symbol": "Search symbols",+ "session_search": "Search past sessions",+ "skill_file": "Read skill file",+ "start_research_goal": "Start research goal",+ "trading_account": "View broker account",+ "trading_cancel_order": "Cancel broker order",+ "trading_check": "Check broker connection",+ "trading_connections": "List broker connections",+ "trading_history": "View trade history",+ "trading_orders": "View broker orders",+ "trading_place_order": "Place broker order",+ "trading_positions": "View broker positions",+ "trading_quote": "Fetch broker quote",+ "trading_select_connection": "Select broker connection",+ "update_hypothesis": "Update research hypothesis",+ "update_research_goal_status": "Update goal status",+ "web_search": "Search the web",+ "write_file": "Generate code"}}diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 8e0d34228..83572b66a 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -151,7 +151,8 @@},"connection": {"reconnecting": "再接続しています…",- "disconnected": "接続が切断されました"+ "disconnected": "接続が切断されました",+ "reload": "Reload"},"welcome": {"categories": {@@ -448,7 +449,8 @@"swarmModeChip": "スウォームモード","goalModeChip": "リサーチ目標","continueGoalMessage": "リサーチ目標を続行: {{goal}}",- "loadEarlier": "以前のメッセージを読み込む"+ "loadEarlier": "以前のメッセージを読み込む",+ "authRequired": "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use."},"runDetail": {"title": "実行詳細",@@ -784,14 +786,19 @@"adjustInputLabel": "調整リクエスト内容","confirmTitle": "マンデートのコミットを確認","confirmDescription": "コミットすると、以下の上限でエージェントに取引権限が即座に付与されます。",- "confirmButton": "確認してコミット"+ "confirmButton": "確認してコミット",+ "maxPerOrder": "≤{{amount}}/order",+ "expiresOn": "expires {{date}}",+ "accountSummary": "{{broker}} · {{type}} account · funded by {{fundedBy}}",+ "adjustRequestMessage": "For mandate proposal \"{{label}}\" (option {{ordinal}}): {{text}}"},"messageBubble": {"copied": "コピーしました","copy": "コピー",- "timeoutHint": "実行がタイムアウトしました。戦略を簡素化するか、銘柄数を減らしてください。",- "apiFailedHint": "API 呼び出しに失敗しました。しばらくしてから再試行してください。",- "executionFailedHint": "実行に失敗しました。クリックして再試行してください。"+ "timeoutHint": "Timed out. Simplify the strategy or use fewer assets.",+ "apiFailedHint": "API request failed. Try again shortly.",+ "executionFailedHint": "Execution failed. Try again.",+ "retry": "Try again"},"pineViewer": {"pineScript": "Pine Script v6",@@ -871,6 +878,109 @@},"metrics": {"good": "良好",- "poor": "要注意"+ "poor": "要注意",+ "gloss": {+ "total_return": "How much the strategy gained or lost over the full test period.",+ "annual_return": "The strategy's return scaled to a typical one-year period.",+ "sharpe": "Return earned per unit of total risk, where higher is generally better.",+ "max_drawdown": "The largest peak-to-trough loss during the test period.",+ "win_rate": "The share of completed trades that made a profit.",+ "trade_count": "The number of trades completed during the test period.",+ "calmar": "Annual return divided by maximum drawdown, balancing growth against worst loss.",+ "sortino": "Return earned per unit of downside risk, where higher is generally better.",+ "profit_loss_ratio": "The average winning trade compared with the average losing trade.",+ "max_consecutive_loss": "The longest run of losing trades in a row.",+ "benchmark_return": "The return of the comparison benchmark over the same period.",+ "excess_return": "How much the strategy outperformed or underperformed its benchmark.",+ "information_ratio": "Excess return earned per unit of tracking error against the benchmark.",+ "final_value": "The portfolio value at the end of the test period.",+ "avg_holding_days": "The average number of days each position stayed open."+ }+ },+ "tools": {+ "add_goal_evidence": "Add goal evidence",+ "alpha_bench": "Benchmark alpha factors",+ "alpha_compare": "Compare alpha factors",+ "alpha_zoo": "Browse alpha library",+ "analyze_image": "Analyze the image",+ "analyze_trade_journal": "Analyze trade journal",+ "background_run": "Start background task",+ "backtest": "Run the backtest",+ "bash": "Run command",+ "cancel_background": "Cancel background task",+ "check_background": "Check background task",+ "compact": "Summarize conversation",+ "create_hypothesis": "Create research hypothesis",+ "delete_skill": "Delete custom skill",+ "edit_file": "Edit code",+ "extract_shadow_strategy": "Extract shadow strategy",+ "factor_analysis": "Analyze factors",+ "financial_rigor": "Verify financial analysis",+ "generate_backtest_config": "Generate backtest config",+ "get_block_trades": "Fetch block trades",+ "get_dragon_tiger": "Fetch dragon-tiger list",+ "get_financial_statements": "Fetch financial statements",+ "get_fund_flow": "Fetch fund flow",+ "get_fundamentals": "Fetch fundamentals",+ "get_lockup_expiry": "Fetch lockup expiries",+ "get_macro_series": "Fetch macro series",+ "get_margin_trading": "Fetch margin trading",+ "get_market_data": "Fetch market data",+ "get_northbound_flow": "Fetch northbound flow",+ "get_options_chain": "Fetch options chain",+ "get_research_goal": "View research goal",+ "get_research_reports": "Fetch research reports",+ "get_sec_filings": "Fetch SEC filings",+ "get_sector_info": "Fetch sector data",+ "get_shareholder_count": "Fetch shareholder count",+ "get_stock_news": "Fetch stock news",+ "get_stock_profile": "Fetch stock profile",+ "iwencai_search": "Search iWenCai",+ "link_autopilot_backtest": "Link autopilot backtest",+ "link_backtest": "Link hypothesis backtest",+ "load_skill": "Load strategy knowledge",+ "options_pricing": "Price options",+ "patch_skill": "Update custom skill",+ "pattern": "Detect chart patterns",+ "portfolio_risk_xray": "X-ray portfolio risk",+ "propose_mandate_profiles": "Propose trading mandates",+ "qveris_execute": "Execute QVeris action",+ "qveris_inspect": "Inspect QVeris action",+ "qveris_search": "Search QVeris",+ "read_document": "Read document",+ "read_file": "Read file",+ "read_url": "Read webpage",+ "remember": "Remember this",+ "render_shadow_report": "Create shadow report",+ "report_audit": "Audit research report",+ "run_research_autopilot": "Run research autopilot",+ "run_shadow_backtest": "Run shadow backtest",+ "run_swarm": "Convene the team",+ "save_skill": "Save custom skill",+ "scaffold_signal_engine": "Build signal engine",+ "scan_shadow_signals": "Scan shadow signals",+ "screen_market": "Screen market",+ "sdm_decay_scan": "Scan strategy decay",+ "sdm_register": "Register strategy",+ "sdm_status": "Check strategy status",+ "search_hypotheses": "Search hypotheses",+ "search_symbol": "Search symbols",+ "session_search": "Search past sessions",+ "skill_file": "Read skill file",+ "start_research_goal": "Start research goal",+ "trading_account": "View broker account",+ "trading_cancel_order": "Cancel broker order",+ "trading_check": "Check broker connection",+ "trading_connections": "List broker connections",+ "trading_history": "View trade history",+ "trading_orders": "View broker orders",+ "trading_place_order": "Place broker order",+ "trading_positions": "View broker positions",+ "trading_quote": "Fetch broker quote",+ "trading_select_connection": "Select broker connection",+ "update_hypothesis": "Update research hypothesis",+ "update_research_goal_status": "Update goal status",+ "web_search": "Search the web",+ "write_file": "Generate code"}}diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex e2097e852..2a35e349f 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -151,7 +151,8 @@},"connection": {"reconnecting": "다시 연결하는 중…",- "disconnected": "연결이 끊겼습니다"+ "disconnected": "연결이 끊겼습니다",+ "reload": "Reload"},"welcome": {"categories": {@@ -448,7 +449,8 @@"swarmModeChip": "스웜 모드","goalModeChip": "리서치 목표","continueGoalMessage": "리서치 목표 계속: {{goal}}",- "loadEarlier": "이전 메시지 불러오기"+ "loadEarlier": "이전 메시지 불러오기",+ "authRequired": "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use."},"runDetail": {"title": "실행 상세",@@ -784,14 +786,19 @@"adjustInputLabel": "조정 요청 내용","confirmTitle": "mandate 커밋 확인","confirmDescription": "커밋하면 아래 한도로 에이전트에게 즉시 거래 권한이 부여됩니다.",- "confirmButton": "확인 후 커밋"+ "confirmButton": "확인 후 커밋",+ "maxPerOrder": "≤{{amount}}/order",+ "expiresOn": "expires {{date}}",+ "accountSummary": "{{broker}} · {{type}} account · funded by {{fundedBy}}",+ "adjustRequestMessage": "For mandate proposal \"{{label}}\" (option {{ordinal}}): {{text}}"},"messageBubble": {"copied": "복사됨","copy": "복사",- "timeoutHint": "실행 시간이 초과되었습니다. 전략을 단순화하거나 자산 수를 줄여 보세요.",- "apiFailedHint": "API 호출에 실패했습니다. 잠시 후 다시 시도해 주세요.",- "executionFailedHint": "실행에 실패했습니다. 클릭하여 다시 시도하세요."+ "timeoutHint": "Timed out. Simplify the strategy or use fewer assets.",+ "apiFailedHint": "API request failed. Try again shortly.",+ "executionFailedHint": "Execution failed. Try again.",+ "retry": "Try again"},"pineViewer": {"pineScript": "Pine Script v6",@@ -871,6 +878,109 @@},"metrics": {"good": "양호",- "poor": "미흡"+ "poor": "미흡",+ "gloss": {+ "total_return": "How much the strategy gained or lost over the full test period.",+ "annual_return": "The strategy's return scaled to a typical one-year period.",+ "sharpe": "Return earned per unit of total risk, where higher is generally better.",+ "max_drawdown": "The largest peak-to-trough loss during the test period.",+ "win_rate": "The share of completed trades that made a profit.",+ "trade_count": "The number of trades completed during the test period.",+ "calmar": "Annual return divided by maximum drawdown, balancing growth against worst loss.",+ "sortino": "Return earned per unit of downside risk, where higher is generally better.",+ "profit_loss_ratio": "The average winning trade compared with the average losing trade.",+ "max_consecutive_loss": "The longest run of losing trades in a row.",+ "benchmark_return": "The return of the comparison benchmark over the same period.",+ "excess_return": "How much the strategy outperformed or underperformed its benchmark.",+ "information_ratio": "Excess return earned per unit of tracking error against the benchmark.",+ "final_value": "The portfolio value at the end of the test period.",+ "avg_holding_days": "The average number of days each position stayed open."+ }+ },+ "tools": {+ "add_goal_evidence": "Add goal evidence",+ "alpha_bench": "Benchmark alpha factors",+ "alpha_compare": "Compare alpha factors",+ "alpha_zoo": "Browse alpha library",+ "analyze_image": "Analyze the image",+ "analyze_trade_journal": "Analyze trade journal",+ "background_run": "Start background task",+ "backtest": "Run the backtest",+ "bash": "Run command",+ "cancel_background": "Cancel background task",+ "check_background": "Check background task",+ "compact": "Summarize conversation",+ "create_hypothesis": "Create research hypothesis",+ "delete_skill": "Delete custom skill",+ "edit_file": "Edit code",+ "extract_shadow_strategy": "Extract shadow strategy",+ "factor_analysis": "Analyze factors",+ "financial_rigor": "Verify financial analysis",+ "generate_backtest_config": "Generate backtest config",+ "get_block_trades": "Fetch block trades",+ "get_dragon_tiger": "Fetch dragon-tiger list",+ "get_financial_statements": "Fetch financial statements",+ "get_fund_flow": "Fetch fund flow",+ "get_fundamentals": "Fetch fundamentals",+ "get_lockup_expiry": "Fetch lockup expiries",+ "get_macro_series": "Fetch macro series",+ "get_margin_trading": "Fetch margin trading",+ "get_market_data": "Fetch market data",+ "get_northbound_flow": "Fetch northbound flow",+ "get_options_chain": "Fetch options chain",+ "get_research_goal": "View research goal",+ "get_research_reports": "Fetch research reports",+ "get_sec_filings": "Fetch SEC filings",+ "get_sector_info": "Fetch sector data",+ "get_shareholder_count": "Fetch shareholder count",+ "get_stock_news": "Fetch stock news",+ "get_stock_profile": "Fetch stock profile",+ "iwencai_search": "Search iWenCai",+ "link_autopilot_backtest": "Link autopilot backtest",+ "link_backtest": "Link hypothesis backtest",+ "load_skill": "Load strategy knowledge",+ "options_pricing": "Price options",+ "patch_skill": "Update custom skill",+ "pattern": "Detect chart patterns",+ "portfolio_risk_xray": "X-ray portfolio risk",+ "propose_mandate_profiles": "Propose trading mandates",+ "qveris_execute": "Execute QVeris action",+ "qveris_inspect": "Inspect QVeris action",+ "qveris_search": "Search QVeris",+ "read_document": "Read document",+ "read_file": "Read file",+ "read_url": "Read webpage",+ "remember": "Remember this",+ "render_shadow_report": "Create shadow report",+ "report_audit": "Audit research report",+ "run_research_autopilot": "Run research autopilot",+ "run_shadow_backtest": "Run shadow backtest",+ "run_swarm": "Convene the team",+ "save_skill": "Save custom skill",+ "scaffold_signal_engine": "Build signal engine",+ "scan_shadow_signals": "Scan shadow signals",+ "screen_market": "Screen market",+ "sdm_decay_scan": "Scan strategy decay",+ "sdm_register": "Register strategy",+ "sdm_status": "Check strategy status",+ "search_hypotheses": "Search hypotheses",+ "search_symbol": "Search symbols",+ "session_search": "Search past sessions",+ "skill_file": "Read skill file",+ "start_research_goal": "Start research goal",+ "trading_account": "View broker account",+ "trading_cancel_order": "Cancel broker order",+ "trading_check": "Check broker connection",+ "trading_connections": "List broker connections",+ "trading_history": "View trade history",+ "trading_orders": "View broker orders",+ "trading_place_order": "Place broker order",+ "trading_positions": "View broker positions",+ "trading_quote": "Fetch broker quote",+ "trading_select_connection": "Select broker connection",+ "update_hypothesis": "Update research hypothesis",+ "update_research_goal_status": "Update goal status",+ "web_search": "Search the web",+ "write_file": "Generate code"}}diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 170156abe..087e1e0a7 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -31,7 +31,7 @@"monitorBadge": "运行时监控","title": "实盘 / 模拟运行时状态","subtitlePre": "只读状态,来自",- "subtitlePost": "。本页面不会授权连接器、启动或停止 runner、提交或撤销订单,也不会修改 mandate。",+ "subtitlePost": "。本页面不会授权连接器、启动或停止执行程序、提交或撤销订单,也不会修改交易授权(mandate)。","refresh": "刷新","unavailableTitle": "运行时状态不可用","unavailableHint": "在后端提供最新状态快照前,请将连接器运行时视为不可用。",@@ -41,14 +41,14 @@"clear": "正常","brokers": "券商","authorized": "已授权",- "runners": "Runner",+ "runners": "执行程序","running": "{{count}} 个运行中","noProfilesTitle": "未报告任何运行时档案","noProfilesBody": "后端未返回任何已识别的实盘或模拟券商档案。","authPresent": "已授权","authMissing": "未授权",- "runnerAlive": "runner 存活",- "runnerStopped": "runner 已停止",+ "runnerAlive": "执行程序存活",+ "runnerStopped": "执行程序已停止","haltedPill": "已熔断","recognizedProfile": "已识别的连接器档案","unknownProfile": "未知连接器档案",@@ -60,22 +60,22 @@"profileType": "档案类型","recognized": "已识别","unknown": "未知",- "mandate": "Mandate",+ "mandate": "交易授权(mandate)","account": "账户","unrecorded": "未记录","expiry": "到期","expired": "已过期","limits": "限额",- "noMandate": "未报告活跃 mandate。",+ "noMandate": "未报告活跃交易授权(mandate)。","riskStateTitle": "运行时风险状态","riskHalted": "风险熔断","riskHaltedDesc": "该档案的熔断开关已触发。在状态恢复前请将连接器运行时视为已停止。","riskActive": "运行时活跃",- "riskActiveDesc": "Runner 存活且存在未过期的 mandate。本页面仍仅为只读状态。",+ "riskActiveDesc": "执行程序存活且存在未过期的交易授权(mandate)。本页面仍仅为只读状态。","riskIdle": "就绪但空闲",- "riskIdleDesc": "授权与 mandate 均存在,但 runner 未存活。",+ "riskIdleDesc": "授权与交易授权(mandate)均存在,但执行程序未存活。","riskDormant": "休眠",- "riskDormantDesc": "由于缺少授权、mandate 或 runner 存活状态,连接器运行时尚未就绪以进行自主运行。",+ "riskDormantDesc": "由于缺少授权、交易授权(mandate)或执行程序存活状态,连接器运行时尚未就绪以进行自主运行。","limitsUnavailable": "限额不可用","perOrder": "/单","exposure": "敞口",@@ -151,7 +151,8 @@},"connection": {"reconnecting": "正在重新连接…",- "disconnected": "连接已断开,刷新页面即可重连。"+ "disconnected": "连接已断开,刷新页面即可重连。",+ "reload": "刷新"},"welcome": {"categories": {@@ -177,18 +178,18 @@"optionsGreeksDesc": "给期权定价,并算出它对股价、时间、波动率的敏感度(Greeks:Delta/Gamma/Theta/Vega)","valueCommittee": "四大师价值委员会","valueCommitteeDesc": "巴菲特/芒格/段永平/李录 四视角辩论一只股票",- "valueCommitteePrompt": "用 run_swarm 执行 value_investing_committee,分析腾讯(00700.HK):巴菲特看护城河和价格、芒格做逆向、段永平看生意和人、李录看十年确定性,主席综合共识和矛盾",+ "valueCommitteePrompt": "用 run_swarm 执行 value_investing_committee,分析腾讯(00700.HK):巴菲特看护城河和价格、芒格做逆向、段永平看生意和人、李录看十年确定性,主席综合共识和矛盾","bottleneckHunter": "供应链瓶颈猎手","bottleneckHunterDesc": "在大趋势里找出上游卡脖子的小供应商,再筛掉估值已经太贵的",- "bottleneckHunterPrompt": "用 bottleneck-hunter 技能找 AI 基础设施的 Layer 2/3 供应链瓶颈机会(光模块/激光器/InP 衬底),给瓶颈评级和过估值门的候选公司",+ "bottleneckHunterPrompt": "用 bottleneck-hunter 技能找 AI 基础设施的 Layer 2/3 供应链瓶颈机会(光模块/激光器/InP 衬底),给瓶颈评级和过估值门的候选公司","thesisTracker": "投资逻辑追踪","thesisTrackerDesc": "给持仓写下 5 句话投资逻辑、触发卖出的红线和估值锚点",- "thesisTrackerPrompt": "用 thesis-tracker 技能给贵州茅台(600519.SH)建立投资论文:5 句话核心论文、可验证假设、红线清单、估值锚点,用 financial_rigor 验算",+ "thesisTrackerPrompt": "用 thesis-tracker 技能给贵州茅台(600519.SH)建立投资论文:5 句话核心论文、可验证假设、红线清单、估值锚点,用 financial_rigor 验算","valuationCheck": "估值核算(PE/PB/ROE)","valuationCheckDesc": "逐位精确复核 PE / PB / ROE / 市值,再做乐观/中性/悲观三档估值",- "valuationCheckPrompt": "用 financial_rigor 工具验算贵州茅台估值:股价 1500、EPS 68.6、每股净资产 180,精确算 PE/PB/ROE,再做三情景估值(增速 12%/8%/0%,PE 22/18/14,3 年)",+ "valuationCheckPrompt": "用 financial_rigor 工具验算贵州茅台估值:股价 1500、EPS 68.6、每股净资产 180,精确算 PE/PB/ROE,再做三情景估值(增速 12%/8%/0%,PE 22/18/14,3 年)","investmentCommittee": "多空辩论:该买还是该卖",- "investmentCommitteeDesc": "多智能体辩论:多头 vs 空头,风险审查,投资经理决策",+ "investmentCommitteeDesc": "智能体团队辩论:多头 vs 空头,风险审查,投资经理决策","quantStrategyDesk": "量化策略工作台","quantStrategyDeskDesc": "筛选 → 因子研究 → 回测 → 风险审计流水线","earningsReport": "分析财报 PDF",@@ -216,8 +217,8 @@"usTechMaxDivPrompt": "回测600519.SH、000858.SZ、601318.SH、000001.SZ、600036.SH的最大分散化投资组合,2024全年","multiFactorAlphaPrompt": "在沪深 300 成分股上利用动量、反转、成交量和波动率构建多因子 Alpha 模型,进行 IC 加权因子合成,回测 2023-2024 年","optionsGreeksPrompt": "利用 Black-Scholes 计算期权希腊字母:现货=100,执行价=105,无风险利率=3%,波动率=25%,到期时间=90天,分析 Delta/Gamma/Theta/Vega",- "investmentCommitteePrompt": "[联队模式] 使用 investment_committee 预设评估在当前市场环境下对 600519.SH 进行做多还是做空",- "quantStrategyDeskPrompt": "[联队模式] 使用 quant_strategy_desk 预设在沪深 300 成分股中寻找并回测最佳动量策略",+ "investmentCommitteePrompt": "[智能体团队模式] 使用 investment_committee 预设评估在当前市场环境下对 600519.SH 进行做多还是做空",+ "quantStrategyDeskPrompt": "[智能体团队模式] 使用 quant_strategy_desk 预设在沪深 300 成分股中寻找并回测最佳动量策略","earningsReportPrompt": "总结上传财务报告中的核心财务指标、风险和展望","macroResearchPrompt": "阅读最新的央行货币政策报告,总结对 A 股市场的影响","analyzeBrokerExportPrompt": "分析我刚刚上传的交易日志 —— 包含持仓统计、胜率、核心标的以及小时分布的完整画像",@@ -288,7 +289,7 @@"reasoningEffortMedium": "中","reasoningEffortHigh": "高","reasoningEffortMax": "最大",- "reasoningEffortDesc": "模型在回答前的思考强度。更高的强度会进行更彻底的推理,但回答速度较慢;选择「关闭」以获得最快的响应速度。",+ "reasoningEffortDesc": "模型回答前先思考多久。调高更周全,但也更慢;想要最快回复就选「关闭」。","localApiAccess": "本地 API 访问","localApiAccessDesc": "对远程或专用 Web UI 部署,请在浏览器中输入一次服务器 API 密钥。本地主机(localhost)使用可保持为空。","serverApiKey": "服务器 API 密钥",@@ -347,7 +348,7 @@"keepCurrentToken": "留空以保留当前 Token","iwencaiApiKey": "iWenCai API 密钥","fredApiKey": "FRED API 密钥",- "iwencaiDesc": "用于通过 iWenCai (问财) 进行语义化选股。需要免费的访问密钥。",+ "iwencaiDesc": "用于通过 iWenCai(问财)进行语义化选股。需要免费的访问密钥。","clearSavedKey": "清除已保存的密钥","fredDesc": "用于 FRED 宏观经济数据(CPI、GDP、失业率等)。从 fred.stlouisfed.org 获取的免费密钥。","featureFlags": "功能开关 (Feature Flags)",@@ -357,10 +358,10 @@"sessionRuntime": "会话运行时","flagsReadFrom": "功能开关从 {{env_path}} 中的 {{env1}}、{{env2}} 和 {{env3}} 读取。","unknownError": "未知错误",- "providerChangeHint": "更改提供商会更新推荐的模型和端点。",+ "providerChangeHint": "切换服务商后,推荐的模型和接口地址会自动更新。","oauth": "OAuth","apiKey": "API 密钥",- "tushareTokenDesc": "用于中国 A 股、期货、基金和宏观数据。若未设置,项目会在可用时回退到 AKShare。"+ "tushareTokenDesc": "用于中国 A 股、期货、基金和宏观数据。没填的话会自动改用 AKShare 的免费数据。"},"qveris": {"title": "QVeris 工具市场",@@ -445,10 +446,11 @@"researchGoal": "研究目标","agentSwarm": "智能体团队","attachmentChip": "附件",- "swarmModeChip": "团队模式",+ "swarmModeChip": "智能体团队模式","goalModeChip": "研究目标","continueGoalMessage": "继续研究目标:{{goal}}",- "loadEarlier": "加载更早的消息"+ "loadEarlier": "加载更早的消息",+ "authRequired": "远程 API 访问需要 API 密钥。请在设置中添加密钥,或在 localhost 上运行后端以仅限本地使用。"},"runDetail": {"title": "运行详情",@@ -697,7 +699,7 @@"observedSharpe": "观测夏普比率","ci": "{{pct}} 置信区间","medianSharpe": "中位数夏普比率",- "probSharpePositive": "P(夏普比率 > 0)",+ "probSharpePositive": "P(夏普比率 > 0)","walkForward": "前推分析","profitable": "{{profitable}}/{{total}} 盈利","walkForwardDesc": "拆分为 {{n}} 个连续窗口以检验绩效一致性。",@@ -726,18 +728,18 @@"authorized": "已授权","notConnected": "未连接","connectProfile": "连接此配置以启用连接器运行时",- "authorizeNote": "在 OAuth 授权成功且提交 mandate 之前,连接器通道保持只读。",+ "authorizeNote": "在 OAuth 授权成功且提交交易授权(mandate)之前,连接器通道保持只读。","runner": "运行器","runnerRunning": "运行中","runnerStopped": "已停止","lastTick": "最后心跳",- "activeMandate": "活跃 mandate",+ "activeMandate": "活跃交易授权(mandate)","expiresIn": "{{time}} 后过期","expired": "已过期","limitsUnavailable": "限制信息不可用",- "noActiveMandate": "无活跃 mandate。请让智能体提议一个,然后在启动连接器运行时之前提交。",+ "noActiveMandate": "无活跃交易授权(mandate)。请让智能体提议一个,然后在启动连接器运行时之前提交。","haltedControlsDisabled": "已停止 — 运行器控制已禁用",- "runtimeActive": "运行时在 mandate 内活跃",+ "runtimeActive": "运行时在交易授权(mandate)内活跃","idle": "空闲","stopRunner": "停止运行器","startRunner": "启动运行器",@@ -748,20 +750,20 @@},"swarmStatus": {"agents": "{{done}}/{{total}} 个智能体",- "layer": "第 {{current}}/{{total}} 层",+ "layer": "第 {{current}}/{{total}} 轮","agent": "智能体","status": "状态","tool": "工具","time": "耗时",- "iters": "迭代",+ "iters": "轮次","output": "输出","waitingForEvents": "等待智能体事件...",- "teamStarting": "团队正在启动,稍等几秒就有第一批进展…",+ "teamStarting": "智能体团队正在启动,稍等几秒就有第一批进展…","detailsUnavailable": "暂无详细信息"},"mandate": {- "runtimeMandate": "连接器运行时 mandate",- "reauthMandate": "重新授权连接器 mandate",+ "runtimeMandate": "连接器运行时交易授权(mandate)",+ "reauthMandate": "重新授权连接器交易授权(mandate)","universe": "标的池","maxOrder": "单笔最大","dailyCap": "每日上限",@@ -772,26 +774,31 @@"commit": "提交「{{label}}」","cancel": "取消","sendAdjustment": "发送调整",- "mandateActive": "Mandate {{id}} 已生效",+ "mandateActive": "交易授权(mandate) {{id}} 已生效","fundedBy": "资金来源",- "noBroker": "无法提交 mandate:连接器 broker 信息缺失。请让智能体重新生成提案。",- "failedToCommit": "提交 mandate 失败。",+ "noBroker": "无法提交交易授权(mandate):连接器券商信息缺失。请让智能体重新生成提案。",+ "failedToCommit": "提交交易授权(mandate)失败。","noLeverage": "无杠杆","leverageValue": "{{value}}× 杠杆","tradesPerDay": "{{count}} 笔/天",- "adjustTitle": "调整此 mandate",+ "adjustTitle": "调整此交易授权(mandate)","adjustPlaceholder": "例如:保持不变但将每日上限提高到 10","adjustInputLabel": "调整请求内容",- "confirmTitle": "确认提交 mandate",+ "confirmTitle": "确认提交交易授权(mandate)","confirmDescription": "提交后将立即依据下方额度授权智能体进行真实交易。",- "confirmButton": "确认并提交"+ "confirmButton": "确认并提交",+ "maxPerOrder": "每笔 ≤{{amount}}",+ "expiresOn": "到期日:{{date}}",+ "accountSummary": "{{broker}} · {{type}} 账户 · 资金来源:{{fundedBy}}",+ "adjustRequestMessage": "针对授权提案「{{label}}」(选项 {{ordinal}})的调整:{{text}}"},"messageBubble": {"copied": "已复制","copy": "复制",- "timeoutHint": "执行超时。请尝试简化策略或减少资产数量。",- "apiFailedHint": "API 调用失败。请稍后重试。",- "executionFailedHint": "执行失败。点击重试。"+ "timeoutHint": "执行超时。可简化策略或减少资产。",+ "apiFailedHint": "API 请求失败。请稍后重试。",+ "executionFailedHint": "执行失败。请重试。",+ "retry": "再试一次"},"pineViewer": {"pineScript": "Pine Script v6",@@ -825,28 +832,28 @@"step3Title": "3. 查看结果","step3Desc": "查看绩效指标、净值曲线,以及可导出的 Pine Script 策略代码。","step4Title": "4. 准备好了再上线",- "step4Desc": "可选择授权明确额度的交易 mandate——未经你确认不会下任何真实订单。"+ "step4Desc": "可选择授权明确额度的交易授权(mandate)——未经你确认不会下任何真实订单。"},"errorBoundary": {- "somethingWrong": "出了点问题"+ "somethingWrong": "出了点问题,刷新页面就能继续。"},"charts": {- "noPriceData": "暂无价格数据",- "noCorrelationData": "暂无相关性数据",- "noEquityData": "暂无收益曲线数据"+ "noPriceData": "这个标的还没有价格数据",+ "noCorrelationData": "至少选两个标的才能比较",+ "noEquityData": "还没有净值曲线——先跑一次回测"},"toolProgress": {"step": "步骤 {{step}} · {{tool}}",- "toolsRunning": "运行中的工具:{{count}}",- "toolsCompleted": "已完成的工具:{{count}}",+ "toolsRunning": "同时在做 {{count}} 件事",+ "toolsCompleted": "已完成 {{count}} 步","more": "… 另有 {{count}} 个","etaSeconds": "预计剩余 {{seconds}} 秒","earlier": "+{{count}} 个较早步骤"},"swarm": {- "assemblingTeam": "正在组建团队…",- "preparingLayers": "正在准备执行层…",- "agentProgress": "团队进度",+ "assemblingTeam": "正在组建智能体团队…",+ "preparingLayers": "正在安排分工顺序…",+ "agentProgress": "智能体团队进度","status": {"waiting": "等待中","running": "运行中",@@ -871,6 +878,109 @@},"metrics": {"good": "良好",- "poor": "欠佳"+ "poor": "欠佳",+ "gloss": {+ "total_return": "策略在整个测试期间的总盈利或总亏损幅度。",+ "annual_return": "将策略收益折算为典型一年周期后的收益率。",+ "sharpe": "策略每承担一单位总体风险获得的收益,通常越高越好。",+ "max_drawdown": "测试期间从净值高点到随后低点的最大跌幅。",+ "win_rate": "已完成交易中实现盈利的交易占比。",+ "trade_count": "测试期间完成的交易总次数。",+ "calmar": "年化收益与最大回撤的比值,用于权衡增长和最严重亏损。",+ "sortino": "策略每承担一单位下行风险获得的收益,通常越高越好。",+ "profit_loss_ratio": "平均每笔盈利交易与平均每笔亏损交易的金额之比。",+ "max_consecutive_loss": "连续出现亏损交易的最长次数。",+ "benchmark_return": "同一期间内对比基准的收益率。",+ "excess_return": "策略相对基准多赚或少赚的收益幅度。",+ "information_ratio": "策略每承担一单位基准跟踪误差获得的超额收益。",+ "final_value": "测试期结束时投资组合的价值。",+ "avg_holding_days": "每个持仓从开仓到平仓的平均天数。"+ }+ },+ "tools": {+ "add_goal_evidence": "添加目标证据",+ "alpha_bench": "评测因子",+ "alpha_compare": "对比因子",+ "alpha_zoo": "浏览因子库",+ "analyze_image": "分析图片",+ "analyze_trade_journal": "分析交易日志",+ "background_run": "启动后台任务",+ "backtest": "运行回测",+ "bash": "运行命令",+ "cancel_background": "取消后台任务",+ "check_background": "查看后台任务",+ "compact": "总结对话",+ "create_hypothesis": "创建研究假设",+ "delete_skill": "删除自定义技能",+ "edit_file": "编辑代码",+ "extract_shadow_strategy": "提取影子策略",+ "factor_analysis": "分析因子",+ "financial_rigor": "核验财务分析",+ "generate_backtest_config": "生成回测配置",+ "get_block_trades": "获取大宗交易",+ "get_dragon_tiger": "获取龙虎榜",+ "get_financial_statements": "获取财务报表",+ "get_fund_flow": "获取资金流向",+ "get_fundamentals": "获取基本面",+ "get_lockup_expiry": "获取解禁安排",+ "get_macro_series": "获取宏观数据",+ "get_margin_trading": "获取两融数据",+ "get_market_data": "获取市场数据",+ "get_northbound_flow": "获取北向资金",+ "get_options_chain": "获取期权链",+ "get_research_goal": "查看研究目标",+ "get_research_reports": "获取研报",+ "get_sec_filings": "获取SEC文件",+ "get_sector_info": "获取板块信息",+ "get_shareholder_count": "获取股东户数",+ "get_stock_news": "获取股票新闻",+ "get_stock_profile": "获取股票概况",+ "iwencai_search": "搜索问财",+ "link_autopilot_backtest": "关联自动回测",+ "link_backtest": "关联假设回测",+ "load_skill": "加载策略知识",+ "options_pricing": "计算期权价格",+ "patch_skill": "更新自定义技能",+ "pattern": "识别图表形态",+ "portfolio_risk_xray": "透视组合风险",+ "propose_mandate_profiles": "推荐交易授权",+ "qveris_execute": "执行QVeris操作",+ "qveris_inspect": "检查QVeris操作",+ "qveris_search": "搜索QVeris",+ "read_document": "读取文档",+ "read_file": "读取文件",+ "read_url": "读取网页",+ "remember": "记住此信息",+ "render_shadow_report": "生成影子报告",+ "report_audit": "审计研究报告",+ "run_research_autopilot": "运行研究自动驾驶",+ "run_shadow_backtest": "运行影子回测",+ "run_swarm": "召集分析团队",+ "save_skill": "保存自定义技能",+ "scaffold_signal_engine": "构建信号引擎",+ "scan_shadow_signals": "扫描影子信号",+ "screen_market": "筛选市场",+ "sdm_decay_scan": "扫描策略衰减",+ "sdm_register": "登记策略",+ "sdm_status": "查看策略状态",+ "search_hypotheses": "搜索研究假设",+ "search_symbol": "搜索标的",+ "session_search": "搜索历史会话",+ "skill_file": "读取技能文件",+ "start_research_goal": "开始研究目标",+ "trading_account": "查看券商账户",+ "trading_cancel_order": "取消券商订单",+ "trading_check": "检查券商连接",+ "trading_connections": "列出券商连接",+ "trading_history": "查看交易历史",+ "trading_orders": "查看券商订单",+ "trading_place_order": "提交券商订单",+ "trading_positions": "查看券商持仓",+ "trading_quote": "获取券商报价",+ "trading_select_connection": "选择券商连接",+ "update_hypothesis": "更新研究假设",+ "update_research_goal_status": "更新目标状态",+ "web_search": "搜索网页",+ "write_file": "生成代码"}}diff --git a/frontend/src/lib/__tests__/api.test.ts b/frontend/src/lib/__tests__/api.test.tsindex f87315ecf..ba1cb5034 100644--- a/frontend/src/lib/__tests__/api.test.ts+++ b/frontend/src/lib/__tests__/api.test.ts@@ -127,4 +127,32 @@ describe("api request helper", () => {}),);});++ it("resolves authorization errors through the active i18n key", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ detail: "server fallback" }), {+ status: 401,+ headers: { "content-type": "application/json" },+ }),+ ),+ );++ const apiModule = await loadApiModule();+ const { default: i18n } = await import("@/i18n");+ i18n.addResource(+ "en",+ "translation",+ "agent.authRequired",+ "Add an API key in Settings.",+ );+ await i18n.changeLanguage("en");++ expect(apiModule.AUTH_REQUIRED_MESSAGE).toBe("Add an API key in Settings.");+ await expect(apiModule.api.getCorrelation("A,B", 90, "pearson")).rejects.toMatchObject({+ status: 401,+ message: "Add an API key in Settings.",+ } satisfies Partial<ApiError>);+ });});diff --git a/frontend/src/lib/__tests__/swarmStatus.test.ts b/frontend/src/lib/__tests__/swarmStatus.test.tsnew file mode 100644index 000000000..3c0c66efd--- /dev/null+++ b/frontend/src/lib/__tests__/swarmStatus.test.ts@@ -0,0 +1,76 @@+import {+ applySwarmEvent,+ buildSwarmStatusFromStarted,+ buildSwarmStatusFromToolResultPreview,+} from "../swarmStatus";++describe("swarmStatus server timestamps", () => {+ it("leaves the run start unset until a server timestamp arrives", () => {+ const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => {+ throw new Error("client clock must not seed swarm status");+ });++ const initial = buildSwarmStatusFromStarted({+ run_id: "run-1",+ status: "pending",+ tasks: [],+ })!;+ expect(initial.startedAt).toBe(0);++ const started = applySwarmEvent(initial, {+ type: "run_started",+ timestamp: "2026-07-29T12:00:00Z",+ });+ expect(started.startedAt).toBe(Date.parse("2026-07-29T12:00:00Z"));+ expect(nowSpy).not.toHaveBeenCalled();+ });++ it("derives agent elapsed time only from paired server event timestamps", () => {+ const initial = buildSwarmStatusFromStarted({+ run_id: "run-2",+ status: "running",+ agents: [{ id: "analyst" }],+ tasks: [{ id: "task-1", agent_id: "analyst", status: "pending" }],+ })!;+ const started = applySwarmEvent(initial, {+ type: "task_started",+ agent_id: "analyst",+ task_id: "task-1",+ timestamp: "2026-07-29T12:00:00Z",+ });+ const completed = applySwarmEvent(started, {+ type: "task_completed",+ agent_id: "analyst",+ task_id: "task-1",+ timestamp: "2026-07-29T12:00:05Z",+ });+ const missingCompletionTimestamp = applySwarmEvent(started, {+ type: "task_completed",+ agent_id: "analyst",+ task_id: "task-1",+ });++ expect(completed.agents[0].elapsed_s).toBe(5);+ expect(missingCompletionTimestamp.agents[0].elapsed_s).toBeUndefined();+ });++ it("seeds parsed and truncated previews only from serialized server times", () => {+ const parsed = buildSwarmStatusFromToolResultPreview(JSON.stringify({+ run_id: "run-3",+ preset: "demo",+ status: "completed",+ tasks: [{+ started_at: "2026-07-29T12:00:01Z",+ completed_at: "2026-07-29T12:00:08Z",+ }],+ }))!;+ const truncated = buildSwarmStatusFromToolResultPreview(+ '{"run_id":"run-4","preset":"demo","status":"completed","started_at":"2026-07-29T12:00:02Z","completed_at":"2026-07-29T12:00:09Z"',+ )!;++ expect(parsed.startedAt).toBe(Date.parse("2026-07-29T12:00:01Z"));+ expect(parsed.completedAt).toBe(Date.parse("2026-07-29T12:00:08Z"));+ expect(truncated.startedAt).toBe(Date.parse("2026-07-29T12:00:02Z"));+ expect(truncated.completedAt).toBe(Date.parse("2026-07-29T12:00:09Z"));+ });+});diff --git a/frontend/src/lib/__tests__/tools.test.ts b/frontend/src/lib/__tests__/tools.test.tsindex 3706ae46e..ff8ea373d 100644--- a/frontend/src/lib/__tests__/tools.test.ts+++ b/frontend/src/lib/__tests__/tools.test.ts@@ -1,3 +1,4 @@+import i18n from "@/i18n";import { localizeToolName, TOOL_LABELS } from "../tools";describe("TOOL_LABELS", () => {@@ -29,19 +30,21 @@ describe("TOOL_LABELS", () => {});describe("localizeToolName", () => {- it("returns label for known tools", () => {- expect(localizeToolName("backtest")).toBe("Run backtest");+ it("resolves the tools.<name> i18n key", () => {+ i18n.addResource("en", "translation", "tools.localized_test_tool", "Localized tool");++ expect(localizeToolName("localized_test_tool")).toBe("Localized tool");});it("returns fallback for unknown tools when fallback provided", () => {expect(localizeToolName("unknown_tool", "My Fallback")).toBe("My Fallback");});- it("returns raw tool name for unknown tools with no fallback", () => {- expect(localizeToolName("some_new_tool")).toBe("some_new_tool");+ it("humanizes unknown tools with no fallback", () => {+ expect(localizeToolName("some_new_tool")).toBe("Some new tool");});- it("prefers TOOL_LABELS over fallback", () => {+ it("uses TOOL_LABELS as the default before an explicit fallback", () => {expect(localizeToolName("bash", "ignored")).toBe("Run command");});});diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 1e4ba189a..0e84bda50 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1,3 +1,4 @@+import i18n from "@/i18n";import { authHeaders, withAuthTicket } from "@/lib/apiAuth";const BASE = "";@@ -12,8 +13,18 @@ export class ApiError extends Error {}}-export const AUTH_REQUIRED_MESSAGE =- "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use.";+const AUTH_REQUIRED_MESSAGE_KEY = "agent.authRequired";++function getAuthRequiredMessage(): string {+ return i18n.t(AUTH_REQUIRED_MESSAGE_KEY as never);+}++// Keep the existing string export compatible with consumers while updating its+// live ES-module binding whenever the active locale changes.+export let AUTH_REQUIRED_MESSAGE = getAuthRequiredMessage();+i18n.on("languageChanged", () => {+ AUTH_REQUIRED_MESSAGE = getAuthRequiredMessage();+});export function isAuthRequiredError(error: unknown): boolean {return error instanceof ApiError && (error.status === 401 || error.status === 403);@@ -53,7 +64,7 @@ async function errorFromResponse(res: Response): Promise<ApiError> {detail = body.detail || body.message || detail;} catch { /* ignore */ }if (res.status === 401 || res.status === 403) {- detail = AUTH_REQUIRED_MESSAGE;+ detail = getAuthRequiredMessage();}return new ApiError(detail, res.status);}@@ -1044,4 +1055,15 @@ export interface MessageItem {created_at: string;linked_attempt_id?: string;metadata?: Record<string, unknown>;+ tool_trail?: ToolTrailItem[];+}++export interface ToolTrailItem {+ tool: string;+ status: "running" | "ok" | "error";+ arguments?: Record<string, string>;+ elapsed_ms?: number;+ preview?: string;+ call_id?: string;+ timestamp?: number;}diff --git a/frontend/src/lib/swarmStatus.ts b/frontend/src/lib/swarmStatus.tsindex 071d10b7b..8eadafdd9 100644--- a/frontend/src/lib/swarmStatus.ts+++ b/frontend/src/lib/swarmStatus.ts@@ -18,10 +18,33 @@ function asNumber(value: unknown): number | undefined {return typeof value === "number" && Number.isFinite(value) ? value : undefined;}-function timestampMs(value: unknown, fallback = Date.now()): number {- if (typeof value !== "string") return fallback;+function timestampMs(value: unknown): number | undefined {+ if (typeof value !== "string") return undefined;const parsed = new Date(value).getTime();- return Number.isFinite(parsed) ? parsed : fallback;+ return Number.isFinite(parsed) ? parsed : undefined;+}++function serverRunTimes(record: AnyRecord): {+ startedAt?: number;+ completedAt?: number;+} {+ const tasks = Array.isArray(record.tasks) ? record.tasks.map(asRecord) : [];+ const taskStarts = tasks+ .map((task) => timestampMs(task.started_at))+ .filter((value): value is number => value != null);+ const taskCompletions = tasks+ .map((task) => timestampMs(task.completed_at))+ .filter((value): value is number => value != null);+ const explicitStart = timestampMs(record.started_at)+ ?? timestampMs(record.created_at)+ ?? timestampMs(record.timestamp);+ const explicitCompletion = timestampMs(record.completed_at);++ return {+ startedAt: explicitStart ?? (taskStarts.length > 0 ? Math.min(...taskStarts) : undefined),+ completedAt: explicitCompletion+ ?? (taskCompletions.length > 0 ? Math.max(...taskCompletions) : undefined),+ };}function normalizeRunStatus(value: unknown): SwarmRunStatus["status"] {@@ -83,7 +106,7 @@ function updateAgent(return { ...status, agents };}-export function buildSwarmStatusFromStarted(data: AnyRecord, now = Date.now()): SwarmRunStatus | null {+export function buildSwarmStatusFromStarted(data: AnyRecord): SwarmRunStatus | null {const runId = asString(data.run_id);if (!runId) return null;@@ -123,16 +146,16 @@ export function buildSwarmStatusFromStarted(data: AnyRecord, now = Date.now()):status: normalizeRunStatus(data.status),currentLayer: 0,totalLayers: 0,- startedAt: now,+ startedAt: serverRunTimes(data).startedAt ?? 0,agents,};}-export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown, now = Date.now()): SwarmRunStatus {+export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown): SwarmRunStatus {const event = asRecord(rawEvent);const data = asRecord(event.data);const type = asString(event.type);- const eventTime = timestampMs(event.timestamp, now);+ const eventTime = timestampMs(event.timestamp);const { agentId, taskId } = eventAgentKey(event);if (type === "layer_started") {@@ -146,19 +169,27 @@ export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown, now}if (type === "run_started") {- return { ...current, status: "running", startedAt: current.startedAt || eventTime };+ return {+ ...current,+ status: "running",+ startedAt: current.startedAt || eventTime || 0,+ };}if (type === "run_completed") {return {...current,status: normalizeRunStatus(data.status),- completedAt: eventTime,+ completedAt: eventTime ?? current.completedAt,};}if (type === "run_error") {- return { ...current, status: "failed", completedAt: eventTime };+ return {+ ...current,+ status: "failed",+ completedAt: eventTime ?? current.completedAt,+ };}if (type === "task_started" || type === "worker_started") {@@ -167,7 +198,7 @@ export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown, nowagentId: agent.agentId || agentId,taskId: agent.taskId || taskId,status: "running",- startedAt: eventTime,+ startedAt: eventTime ?? agent.startedAt,}));}@@ -215,7 +246,9 @@ export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown, nowreturn updateAgent(current, { agentId, taskId }, (agent) => ({...agent,status: "done",- elapsed_s: agent.startedAt ? Math.max(0, (eventTime - agent.startedAt) / 1000) : agent.elapsed_s,+ elapsed_s: agent.startedAt && eventTime+ ? Math.max(0, (eventTime - agent.startedAt) / 1000)+ : agent.elapsed_s,iterations: asNumber(data.iterations) ?? agent.iterations,lastText: asString(data.summary) || agent.lastText,}));@@ -225,7 +258,9 @@ export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown, nowreturn updateAgent(current, { agentId, taskId }, (agent) => ({...agent,status: "failed",- elapsed_s: agent.startedAt ? Math.max(0, (eventTime - agent.startedAt) / 1000) : agent.elapsed_s,+ elapsed_s: agent.startedAt && eventTime+ ? Math.max(0, (eventTime - agent.startedAt) / 1000)+ : agent.elapsed_s,error: asString(data.error) || asString(data.reason) || agent.error,}));}@@ -251,21 +286,25 @@ export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown, nowreturn current;}-export function buildSwarmStatusFromToolResultPreview(preview: string, now = Date.now()): SwarmRunStatus | null {+export function buildSwarmStatusFromToolResultPreview(preview: string): SwarmRunStatus | null {if (!preview.includes("run_id") && !preview.includes("preset")) return null;try {const parsed = JSON.parse(preview) as AnyRecord;const runId = asString(parsed.run_id);if (!runId) return null;+ const times = serverRunTimes(parsed);+ const status = normalizeRunStatus(parsed.status);return {runId,preset: asString(parsed.preset) || "swarm",- status: normalizeRunStatus(parsed.status),+ status,currentLayer: 0,totalLayers: 0,- startedAt: now,- completedAt: ["completed", "failed", "cancelled"].includes(asString(parsed.status)) ? now : undefined,+ startedAt: times.startedAt ?? 0,+ completedAt: ["completed", "failed", "cancelled"].includes(status)+ ? times.completedAt+ : undefined,agents: [],};} catch {@@ -274,14 +313,22 @@ export function buildSwarmStatusFromToolResultPreview(preview: string, now = Datconst preset = preview.match(/"preset"\s*:\s*"([^"]+)"/)?.[1] || "swarm";const rawStatus = preview.match(/"status"\s*:\s*"([^"]+)"/)?.[1] || "unknown";const status = normalizeRunStatus(rawStatus);+ const startedAt = timestampMs(+ preview.match(/"(?:started_at|created_at|timestamp)"\s*:\s*"([^"]+)"/)?.[1],+ );+ const completedAt = timestampMs(+ preview.match(/"completed_at"\s*:\s*"([^"]+)"/)?.[1],+ );return {runId,preset,status,currentLayer: 0,totalLayers: 0,- startedAt: now,- completedAt: ["completed", "failed", "cancelled"].includes(status) ? now : undefined,+ startedAt: startedAt ?? 0,+ completedAt: ["completed", "failed", "cancelled"].includes(status)+ ? completedAt+ : undefined,agents: [],};}diff --git a/frontend/src/lib/tools.ts b/frontend/src/lib/tools.tsindex 26bbecc67..741dbea91 100644--- a/frontend/src/lib/tools.ts+++ b/frontend/src/lib/tools.ts@@ -1,3 +1,5 @@+import i18n from "@/i18n";+/*** Single source of truth for tool name → user-facing label.*/@@ -32,12 +34,12 @@ export const TOOL_LABELS: Record<string, string> = {spawn_subagent: "Spawn sub-agent",};+function humanizeToolName(tool: string): string {+ const humanized = tool.replace(/_/g, " ");+ return humanized.charAt(0).toUpperCase() + humanized.slice(1);+}+export function localizeToolName(tool: string, fallback?: string): string {- if (tool in TOOL_LABELS) {- return TOOL_LABELS[tool];- }- if (fallback !== undefined) {- return fallback;- }- return tool;+ const defaultValue = TOOL_LABELS[tool] ?? fallback ?? humanizeToolName(tool);+ return i18n.t(`tools.${tool}` as never, { defaultValue });}diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex dfc7ecd4c..36feb5a3d 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -8,6 +8,23 @@ import { router } from "./router";import "highlight.js/styles/github-dark-dimmed.min.css";import "./index.css";+const prefetchMiniEquityChart = () => {+ void import("@/components/charts/MiniEquityChart");+};++const idleWindow = window as Window & {+ requestIdleCallback?: (+ callback: IdleRequestCallback,+ options?: IdleRequestOptions,+ ) => number;+};++if (typeof idleWindow.requestIdleCallback === "function") {+ idleWindow.requestIdleCallback(prefetchMiniEquityChart, { timeout: 2000 });+} else {+ window.setTimeout(prefetchMiniEquityChart, 0);+}+createRoot(document.getElementById("root")!).render(<StrictMode><ErrorBoundary>diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 19a51480d..36ad75c80 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -26,6 +26,7 @@ import {buildSwarmStatusFromStarted,buildSwarmStatusFromToolResultPreview,} from "@/lib/swarmStatus";+import { buildToolTimelineMessages } from "@/pages/agentToolTimeline";/* ---------- Message grouping ---------- */type MsgGroup =@@ -58,6 +59,22 @@ function groupMessages(msgs: StoredAgentMessage[]): MsgGroup[] {const act = () => useAgentStore.getState();+function eventCallId(data: Record<string, unknown>): string | undefined {+ return typeof data.call_id === "string" && data.call_id+ ? data.call_id+ : undefined;+}++interface PendingToolProgress {+ callId?: string;+ tool: string;+ progress: NonNullable<ToolCallEntry["progress"]>;+}++function toolProgressKey(callId: string | undefined, tool: string): string {+ return callId ? `call:${callId}` : `tool:${tool}`;+}+// 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)@@ -286,8 +303,8 @@ export function Agent() {const lastEventRef = useRef(0);const sseTimeoutMsRef = useRef(90_000);- /* tool_progress coalescing — keep latest payload per-tool, flush once per rAF. */- const pendingProgressRef = useRef<Map<string, NonNullable<ToolCallEntry["progress"]>>>(new Map());+ /* tool_progress coalescing — keep latest payload per invocation, flush once per rAF. */+ const pendingProgressRef = useRef<Map<string, PendingToolProgress>>(new Map());const progressRafRef = useRef(0);const pendingTextRef = useRef("");const pendingReasoningRef = useRef<boolean | null>(null);@@ -537,6 +554,17 @@ export function Agent() {const runId = meta?.run_id as string | undefined;const metrics = meta?.metrics as Record<string, number> | undefined;const ts = new Date(m.created_at).getTime();+ const toolTimeline = m.role === "assistant"+ ? buildToolTimelineMessages(m.tool_trail ?? [], {+ fallbackTimestamp: ts,+ idPrefix: `${m.message_id}_`,+ })+ : [];+ agentMsgs.push(...toolTimeline);+ const lastToolTimestamp = toolTimeline.length > 0+ ? toolTimeline[toolTimeline.length - 1].timestamp+ : ts - 1;+ const assistantTs = Math.max(ts, lastToolTimestamp + 1);if (m.role === "user") {const displayPrompt = toDisplayPrompt(m.content);agentMsgs.push({@@ -549,10 +577,10 @@ export function Agent() {} else if (runId) {// Show text answer first (if non-empty), then chart cardif (m.content && m.content !== "Strategy execution completed.") {- agentMsgs.push({ id: m.message_id + "_ans", type: "answer", content: m.content, timestamp: ts });+ agentMsgs.push({ id: m.message_id + "_ans", type: "answer", content: m.content, timestamp: assistantTs });}if (metrics && Object.keys(metrics).length > 0) {- agentMsgs.push({ id: m.message_id, type: "run_complete", content: "", runId, metrics, timestamp: ts + 1 });+ agentMsgs.push({ id: m.message_id, type: "run_complete", content: "", runId, metrics, timestamp: assistantTs + 1 });} else {// Fetch run data to check report-worthiness; show fallback card if fetch failslet fetchedMetrics: Record<string, number> | undefined;@@ -578,12 +606,12 @@ export function Agent() {runId,metrics: fetchedMetrics,equityCurve: fetchedCurve,- timestamp: ts + 1,+ timestamp: assistantTs + 1,});}}} else {- agentMsgs.push({ id: m.message_id, type: "answer", content: m.content, timestamp: ts });+ agentMsgs.push({ id: m.message_id, type: "answer", content: m.content, timestamp: assistantTs });}}if (genRef.current !== gen) return;@@ -662,10 +690,11 @@ export function Agent() {replayAttemptSeenRef.current = true;queueStreamUpdate("", false);const toolName = String(d.tool || "");+ const callId = eventCallId(d);toolCallSeqRef.current += 1;// Only update toolCalls tracker (no message creation during streaming)act().addToolCall({- id: `${toolName}#${toolCallSeqRef.current}`, tool: toolName,+ id: callId ?? `${toolName}#${toolCallSeqRef.current}`, tool: toolName,arguments: (d.arguments as Record<string, string>) ?? {},status: "running", timestamp: Date.now(),});@@ -675,10 +704,11 @@ export function Agent() {tool_result: (d) => {touch();const toolName = String(d.tool || "");- // Drop any in-flight coalesced progress for this tool.- pendingProgressRef.current.delete(toolName);+ const callId = eventCallId(d);+ // Drop any in-flight coalesced progress for this invocation.+ pendingProgressRef.current.delete(toolProgressKey(callId, toolName));// Only update tracker (no message creation during streaming)- act().updateOldestRunningToolCall(toolName, {+ act().updateRunningToolCall(callId, toolName, {status: d.status === "ok" ? "ok" : "error",preview: String(d.preview || ""),elapsed_ms: Number(d.elapsed_ms || 0),@@ -700,7 +730,7 @@ export function Agent() {if (act().status !== "streaming") act().setStatus("streaming");const toolName = String(d.tool || "");if (!toolName) return;- act().updateOldestRunningToolCall(toolName, {+ act().updateRunningToolCall(eventCallId(d), toolName, {elapsed_s: Number(d.elapsed_s || 0),});},@@ -710,21 +740,25 @@ export function Agent() {replayAttemptSeenRef.current = true;const toolName = String(d.tool || "");if (!toolName) return;+ const callId = eventCallId(d);const payload: NonNullable<ToolCallEntry["progress"]> = {};if (typeof d.stage === "string" && d.stage) payload.stage = d.stage;if (typeof d.message === "string" && d.message) payload.message = d.message;if (typeof d.current === "number") payload.current = d.current;if (typeof d.total === "number") payload.total = d.total;- // Coalesce: keep latest payload per tool, flush once per animation frame.- pendingProgressRef.current.set(toolName, payload);+ // Coalesce: keep latest payload per invocation, flush once per animation frame.+ pendingProgressRef.current.set(+ toolProgressKey(callId, toolName),+ { callId, tool: toolName, progress: payload },+ );if (progressRafRef.current) return;progressRafRef.current = requestAnimationFrame(() => {progressRafRef.current = 0;const pending = pendingProgressRef.current;if (pending.size === 0) return;const store = act();- for (const [tool, progress] of pending) {- store.updateOldestRunningToolCall(tool, { progress });+ for (const { callId: pendingCallId, tool, progress } of pending.values()) {+ store.updateRunningToolCall(pendingCallId, tool, { progress });}pending.clear();});@@ -781,11 +815,8 @@ export function Agent() {// Build ThinkingTimeline summary from accumulated toolCallsconst completedTools = s.toolCalls;if (completedTools.length > 0) {- for (const tc of completedTools) {- s.addMessage({ id: tc.id + "_call", type: "tool_call", content: "", tool: tc.tool, args: tc.arguments, status: tc.status || "ok", timestamp: tc.timestamp });- if (tc.elapsed_ms != null) {- s.addMessage({ id: "", type: "tool_result", content: tc.preview || "", tool: tc.tool, status: tc.status || "ok", elapsed_ms: tc.elapsed_ms, timestamp: tc.timestamp + 1 });- }+ for (const message of buildToolTimelineMessages(completedTools)) {+ s.addMessage(message);}}diff --git a/frontend/src/pages/__tests__/agentToolTimeline.test.ts b/frontend/src/pages/__tests__/agentToolTimeline.test.tsnew file mode 100644index 000000000..8ace850f8--- /dev/null+++ b/frontend/src/pages/__tests__/agentToolTimeline.test.ts@@ -0,0 +1,57 @@+import { buildToolTimelineMessages } from "../agentToolTimeline";++describe("buildToolTimelineMessages", () => {+ it("rebuilds persisted tool calls and results with the live completion mapping", () => {+ expect(buildToolTimelineMessages(+ [+ {+ tool: "get_market_data",+ call_id: "call-market-1",+ arguments: { symbol: "AAPL" },+ status: "ok",+ elapsed_ms: 125,+ preview: "AAPL 195.00",+ timestamp: 1_785_342_400_000,+ },+ {+ tool: "write_file",+ arguments: { path: "report.md" },+ status: "error",+ timestamp: 1_785_342_400_000,+ },+ ],+ {+ fallbackTimestamp: 1_785_342_500_000,+ idPrefix: "message-1_",+ },+ )).toEqual([+ {+ id: "message-1_call-market-1_call",+ type: "tool_call",+ content: "",+ tool: "get_market_data",+ args: { symbol: "AAPL" },+ status: "ok",+ timestamp: 1_785_342_400_000,+ },+ {+ id: "message-1_call-market-1_result",+ type: "tool_result",+ content: "AAPL 195.00",+ tool: "get_market_data",+ status: "ok",+ elapsed_ms: 125,+ timestamp: 1_785_342_400_001,+ },+ {+ id: "message-1_write_file#2_call",+ type: "tool_call",+ content: "",+ tool: "write_file",+ args: { path: "report.md" },+ status: "error",+ timestamp: 1_785_342_400_002,+ },+ ]);+ });+});diff --git a/frontend/src/pages/agentToolTimeline.ts b/frontend/src/pages/agentToolTimeline.tsnew file mode 100644index 000000000..66f77d872--- /dev/null+++ b/frontend/src/pages/agentToolTimeline.ts@@ -0,0 +1,61 @@+import type { StoredAgentMessage } from "@/stores/agent";++export interface ToolTimelineEntry {+ id?: string;+ call_id?: string;+ tool: string;+ arguments?: Record<string, string>;+ status?: "running" | "ok" | "error";+ preview?: string;+ elapsed_ms?: number;+ timestamp?: number;+}++interface ToolTimelineOptions {+ fallbackTimestamp?: number;+ idPrefix?: string;+}++/** Convert consolidated tool records into the transcript timeline shape. */+export function buildToolTimelineMessages(+ entries: readonly ToolTimelineEntry[],+ options: ToolTimelineOptions = {},+): StoredAgentMessage[] {+ const fallbackTimestamp = options.fallbackTimestamp ?? Date.now();+ const idPrefix = options.idPrefix ?? "";+ const messages: StoredAgentMessage[] = [];+ let previousTimestamp = Number.NEGATIVE_INFINITY;++ entries.forEach((entry, index) => {+ const candidateTimestamp = typeof entry.timestamp === "number" && Number.isFinite(entry.timestamp)+ ? entry.timestamp+ : fallbackTimestamp + index * 2;+ const timestamp = Math.max(candidateTimestamp, previousTimestamp + 1);+ const entryId = entry.id || entry.call_id || `${entry.tool}#${index + 1}`;+ const status = entry.status || "ok";++ messages.push({+ id: `${idPrefix}${entryId}_call`,+ type: "tool_call",+ content: "",+ tool: entry.tool,+ args: entry.arguments ?? {},+ status,+ timestamp,+ });+ if (entry.elapsed_ms != null) {+ messages.push({+ id: `${idPrefix}${entryId}_result`,+ type: "tool_result",+ content: entry.preview || "",+ tool: entry.tool,+ status,+ elapsed_ms: entry.elapsed_ms,+ timestamp: timestamp + 1,+ });+ }+ previousTimestamp = entry.elapsed_ms != null ? timestamp + 1 : timestamp;+ });++ return messages;+}diff --git a/frontend/src/stores/__tests__/agent.test.ts b/frontend/src/stores/__tests__/agent.test.tsindex 3ccfa9be5..4a845ce42 100644--- a/frontend/src/stores/__tests__/agent.test.ts+++ b/frontend/src/stores/__tests__/agent.test.ts@@ -135,18 +135,69 @@ describe("tool calls", () => {expect(useAgentStore.getState().toolCalls[0].status).toBe("running");});+ it("matches interleaved parallel same-name calls by call_id", () => {+ const store = useAgentStore.getState();+ store.addToolCall(makeToolCall({ id: "call-1", tool: "search" }));+ store.addToolCall(makeToolCall({ id: "call-2", tool: "search" }));++ store.updateRunningToolCall("call-2", "search", {+ elapsed_s: 2,+ progress: { stage: "second", current: 8, total: 10 },+ });+ store.updateRunningToolCall("call-1", "search", {+ elapsed_s: 4,+ progress: { stage: "first", current: 3, total: 10 },+ });+ store.updateRunningToolCall("call-2", "search", {+ status: "ok",+ preview: "second-result",+ });++ expect(useAgentStore.getState().toolCalls).toMatchObject([+ {+ id: "call-1",+ status: "running",+ elapsed_s: 4,+ progress: { stage: "first", current: 3, total: 10 },+ },+ {+ id: "call-2",+ status: "ok",+ elapsed_s: 2,+ preview: "second-result",+ progress: { stage: "second", current: 8, total: 10 },+ },+ ]);++ store.updateRunningToolCall("call-1", "search", {+ status: "error",+ preview: "first-result",+ });+ expect(useAgentStore.getState().toolCalls.map((tc) => tc.status)).toEqual([+ "error",+ "ok",+ ]);+ });++ it("does not fall back to tool name when a call_id is unknown", () => {+ const store = useAgentStore.getState();+ store.addToolCall(makeToolCall({ id: "call-1", tool: "search" }));+ store.updateRunningToolCall("missing-call", "search", { status: "ok" });+ expect(useAgentStore.getState().toolCalls[0].status).toBe("running");+ });+it("updates repeated running tool calls in FIFO order", () => {const store = useAgentStore.getState();store.addToolCall(makeToolCall({ id: "search#1", tool: "search" }));store.addToolCall(makeToolCall({ id: "search#2", tool: "search" }));- store.updateOldestRunningToolCall("search", { status: "ok" });+ store.updateRunningToolCall(undefined, "search", { status: "ok" });expect(useAgentStore.getState().toolCalls.map((tc) => tc.status)).toEqual(["ok","running",]);- store.updateOldestRunningToolCall("search", { status: "error" });+ store.updateRunningToolCall(undefined, "search", { status: "error" });expect(useAgentStore.getState().toolCalls.map((tc) => tc.status)).toEqual(["ok","error",diff --git a/frontend/src/stores/agent.ts b/frontend/src/stores/agent.tsindex d9d7402a6..d64440a3f 100644--- a/frontend/src/stores/agent.ts+++ b/frontend/src/stores/agent.ts@@ -39,6 +39,11 @@ interface AgentState {addToolCall: (entry: ToolCallEntry) => void;updateToolCall: (id: string, update: Partial<ToolCallEntry>) => void;+ updateRunningToolCall: (+ callId: string | undefined,+ tool: string,+ update: Partial<ToolCallEntry>,+ ) => void;updateOldestRunningToolCall: (tool: string, update: Partial<ToolCallEntry>) => void;upsertSwarmStatus: (status: SwarmRunStatus) => void;updateSwarmStatus: (runId: string, updater: (status: SwarmRunStatus) => SwarmRunStatus) => void;@@ -113,6 +118,20 @@ export const useAgentStore = create<AgentState>((set) => ({set((s) => ({toolCalls: s.toolCalls.map((tc) => tc.id === id ? { ...tc, ...update } : tc),})),+ updateRunningToolCall: (callId, tool, update) =>+ set((s) => {+ const idx = callId+ ? s.toolCalls.findIndex(+ (tc) => tc.id === callId && tc.status === "running",+ )+ : s.toolCalls.findIndex(+ (tc) => tc.tool === tool && tc.status === "running",+ );+ if (idx < 0) return {};+ const toolCalls = [...s.toolCalls];+ toolCalls[idx] = { ...toolCalls[idx], ...update };+ return { toolCalls };+ }),updateOldestRunningToolCall: (tool, update) =>set((s) => {let idx = -1;