"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Improve UI responsiveness and task navigation
Haozhe Wu3bb01ebed991
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 13a765fa9..569cea574 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -10,6 +10,15 @@ For general project setup (`pip install -e ".[dev]"`, dev servers,`pytest --ignore=agent/tests/e2e_backtest`), see the README. For bug reportsand feature requests, use the GitHub issue templates.+The Web UI bounds API requests (including reading the response body) to two+minutes by default. Set `VITE_API_TIMEOUT_MS` in `frontend/.env.local` before+starting Vite or building the frontend to change this limit. Conversation-list+requests use at most 15 seconds so an unavailable backend shows a connection+error and a retry action promptly. Timed-out writes are never retried+automatically: the server may still be processing them, so check the current+state before repeating an action. These limits do not interrupt an accepted+agent run or its SSE stream.+For AI-assisted or automation-assisted contributions, also see[`AGENT_CONTRIBUTOR_GUIDE.md`](AGENT_CONTRIBUTOR_GUIDE.md). It summarizes safelocal checks, higher-risk broker/MCP/credential surfaces, and the expected PRdiff --git a/agent/src/api/system_routes.py b/agent/src/api/system_routes.pyindex 5d7f23021..4324ba4c7 100644--- a/agent/src/api/system_routes.py+++ b/agent/src/api/system_routes.py@@ -5,6 +5,7 @@ Mounted by ``agent/api_server.py`` via ``register_system_routes(app, ...)``.from __future__ import annotations+import asyncioimport loggingimport osimport signal@@ -300,7 +301,9 @@ def register_system_routes(raise HTTPException(status_code=400, detail="method must be 'pearson' or 'spearman'")try:- result = compute_correlation_matrix(codes=code_list, days=days, method=method)+ result = await asyncio.to_thread(+ compute_correlation_matrix, codes=code_list, days=days, method=method+ )return resultexcept ValueError as exc:raise HTTPException(status_code=400, detail=str(exc))@@ -344,7 +347,8 @@ def register_system_routes(raise HTTPException(status_code=400, detail="exit_threshold must be below enter_threshold")try:- return compute_regime_timeline(+ return await asyncio.to_thread(+ compute_regime_timeline,codes=code_list,days=days,corr_window=corr_window,diff --git a/agent/src/tools/options_chain_tool.py b/agent/src/tools/options_chain_tool.pyindex db0e15d49..dfc582336 100644--- a/agent/src/tools/options_chain_tool.py+++ b/agent/src/tools/options_chain_tool.py@@ -10,6 +10,7 @@ reuses one session, so the agent never hits Yahoo un-spaced.from __future__ import annotationsimport json+import mathfrom typing import Any, Dict, List, Optionalfrom backtest.loaders import yahoo_client@@ -161,9 +162,27 @@ def _success(ticker: str, result: Dict[str, Any]) -> str:calls = _contracts(block.get("calls"))puts = _contracts(block.get("puts"))+ quote = result.get("quote")+ price = quote.get("regularMarketPrice") if isinstance(quote, dict) else None+ underlying_price = _positive_number(price)+ # Determine ATM from the complete ladder, before the output-row cap.+ strikes = {+ strike+ for rows in (block.get("calls"), block.get("puts"))+ if isinstance(rows, list)+ for row in rows+ if isinstance(row, dict)+ if (strike := _positive_number(row.get("strike"))) is not None+ }+ atm_strike = (+ min(strikes, key=lambda strike: (abs(strike - underlying_price), strike))+ if underlying_price is not None and strikes else None+ )data = {"ticker": ticker,+ "underlying_price": underlying_price,+ "atm_strike": atm_strike,"expiration": block.get("expirationDate"),"expirations": expirations,"calls_count": len(calls),@@ -177,6 +196,20 @@ def _success(ticker: str, result: Dict[str, Any]) -> str:)+def _positive_number(value: Any) -> float | None:+ """Validate a source number without guessing missing values.++ Args:+ value: The price or strike supplied by the data source.++ Returns:+ A finite positive number, or None for missing or malformed input.+ """+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ return None+ return float(value) if math.isfinite(value) and value > 0 else None++def _contracts(raw: Any) -> List[Dict[str, Any]]:"""Normalize a Yahoo calls/puts array into capped snake_case rows."""if not isinstance(raw, list):diff --git a/agent/tests/test_options_chain_tool.py b/agent/tests/test_options_chain_tool.pyindex 44fa6b69a..6915d6ca1 100644--- a/agent/tests/test_options_chain_tool.py+++ b/agent/tests/test_options_chain_tool.py@@ -9,6 +9,8 @@ from __future__ import annotationsimport jsonfrom unittest.mock import patch+import pytest+from src.tools import options_chain_tool as oc@@ -115,6 +117,28 @@ class TestOptionsChainSuccess:payload = json.loads(out)assert payload["data"]["calls_count"] == oc._MAX_CONTRACTS_PER_SIDE+ def test_atm_uses_quote_and_full_ladder_before_capping(self):+ result = _sample_result()+ result["quote"] = {"regularMarketPrice": 337.4}+ result["options"][0]["calls"] = [+ {"strike": float(i)} for i in range(100, 401)+ ]+ data = json.loads(oc._success("AAPL", result))["data"]+ assert data["underlying_price"] == 337.4+ assert data["atm_strike"] == 337.0+ assert len(data["calls"]) == oc._MAX_CONTRACTS_PER_SIDE+ assert all(row["strike"] != data["atm_strike"] for row in data["calls"])++ @pytest.mark.parametrize("quote", [None, {}, {"regularMarketPrice": None},+ {"regularMarketPrice": True}, {"regularMarketPrice": 0},+ {"regularMarketPrice": float("nan")}, {"regularMarketPrice": "337.4"}])+ def test_missing_or_invalid_quote_never_guesses_atm(self, quote):+ result = _sample_result()+ result["quote"] = quote+ data = json.loads(oc._success("AAPL", result))["data"]+ assert data["underlying_price"] is None+ assert data["atm_strike"] is None+class TestOptionsChainErrors:"""Error envelopes: missing ticker, bad expiration, upstream failure."""diff --git a/agent/tests/test_system_routes.py b/agent/tests/test_system_routes.pyindex be3516b80..75d1a628e 100644--- a/agent/tests/test_system_routes.py+++ b/agent/tests/test_system_routes.py@@ -12,6 +12,10 @@ client with a configured key is used to prove the auth gate rejects.from __future__ import annotations+import asyncio+import threading++import httpximport pytestfrom fastapi.testclient import TestClient@@ -204,3 +208,47 @@ def test_correlation_rate_limiter_is_per_client(monkeypatch: pytest.MonkeyPatch)assert limiter.allow("1.1.1.1") is Trueassert limiter.allow("1.1.1.1") is Falseassert limiter.allow("2.2.2.2") is True+++ ("path", "module_name", "function_name"),+ [+ ("/correlation", "backtest.correlation", "compute_correlation_matrix"),+ ("/correlation/regime", "backtest.regime", "compute_regime_timeline"),+ ],+)+def test_slow_analysis_does_not_block_other_api_requests(+ monkeypatch: pytest.MonkeyPatch, path: str, module_name: str, function_name: str+):+ """Health must respond while a price-data computation is still waiting."""+ import importlib++ started = threading.Event()+ release = threading.Event()+ finished = threading.Event()++ def compute(**kwargs):+ started.set()+ release.wait(timeout=1)+ finished.set()+ return {"labels": kwargs["codes"], "matrix": [[1.0, 0.5], [0.5, 1.0]]}++ monkeypatch.setattr(importlib.import_module(module_name), function_name, compute)+ monkeypatch.delenv("API_AUTH_KEY", raising=False)+ monkeypatch.setattr(api_server, "_API_KEY", "")+ transport = httpx.ASGITransport(app=api_server.app, client=("127.0.0.1", 50000))+ async def probe():+ async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:+ analysis = asyncio.create_task(client.get(path, params={"codes": "AAPL,SPY"}))+ try:+ assert await asyncio.to_thread(started.wait, 2)+ health = await client.get("/health")+ assert health.status_code == 200+ assert not finished.is_set(), "Analysis blocked the API event loop"+ finally:+ release.set()+ response = await analysis+ assert response.status_code == 200+ assert response.json()["labels"] == ["AAPL", "SPY"]++ asyncio.run(probe())diff --git a/frontend/src/components/chat/EnhancedMarkdown.tsx b/frontend/src/components/chat/EnhancedMarkdown.tsxnew file mode 100644index 000000000..3c43f6ba5--- /dev/null+++ b/frontend/src/components/chat/EnhancedMarkdown.tsx@@ -0,0 +1,18 @@+import ReactMarkdown, { type Options } from "react-markdown";+import rehypeHighlight from "rehype-highlight";+import rehypeKatex from "rehype-katex";+import "katex/dist/katex.min.css";++const rehypePlugins: Options["rehypePlugins"] = [rehypeHighlight, rehypeKatex];++export default function EnhancedMarkdown({ content, remarkPlugins, components }: {+ content: string;+ remarkPlugins: Options["remarkPlugins"];+ components: Options["components"];+}) {+ return (+ <ReactMarkdown remarkPlugins={remarkPlugins} rehypePlugins={rehypePlugins} components={components}>+ {content}+ </ReactMarkdown>+ );+}diff --git a/frontend/src/components/chat/MessageBubble.tsx b/frontend/src/components/chat/MessageBubble.tsxindex 039d4bfcf..a4a1777df 100644--- a/frontend/src/components/chat/MessageBubble.tsx+++ b/frontend/src/components/chat/MessageBubble.tsx@@ -1,12 +1,9 @@import i18n from '@/i18n';-import { Component, memo, useState, useCallback, type ReactNode } from "react";+import { Component, lazy, memo, Suspense, useState, useCallback, type ReactNode } from "react";import { XCircle, RefreshCw, Copy, Check, Paperclip, Users, Target, Clock3 } from "lucide-react";import ReactMarkdown, { type Options as ReactMarkdownOptions } from "react-markdown";import remarkGfm from "remark-gfm";import remarkMath from "remark-math";-import rehypeHighlight from "rehype-highlight";-import rehypeKatex from "rehype-katex";-import "katex/dist/katex.min.css";import { toast } from "sonner";import { normalizeMathDelimiters } from "@/lib/markdown";import { downloadGeneratedReport } from "@/lib/api";@@ -21,7 +18,8 @@ const remarkPlugins: ReactMarkdownOptions["remarkPlugins"] = [remarkGfm,[remarkMath, { singleDollarTextMath: false }],];-const rehypePlugins: ReactMarkdownOptions["rehypePlugins"] = [rehypeHighlight, rehypeKatex];+// Math fonts and syntax highlighters are only needed for completed answers.+const EnhancedMarkdown = lazy(() => import("./EnhancedMarkdown"));const markdownComponents: ReactMarkdownOptions["components"] = {table: ({ node, ...props }) => {void node;@@ -96,16 +94,24 @@ export const MarkdownContent = memo(function MarkdownContent({normalized = content;}+ const structuralMarkdown = (+ <ReactMarkdown remarkPlugins={remarkPlugins} components={markdownComponents}>+ {normalized}+ </ReactMarkdown>+ );+return (<div className={proseClassName}><MarkdownErrorBoundary content={content}>- <ReactMarkdown- remarkPlugins={remarkPlugins}- rehypePlugins={streaming ? [] : rehypePlugins}- components={markdownComponents}- >- {normalized}- </ReactMarkdown>+ {streaming ? structuralMarkdown : (+ <Suspense fallback={structuralMarkdown}>+ <EnhancedMarkdown+ content={normalized}+ remarkPlugins={remarkPlugins}+ components={markdownComponents}+ />+ </Suspense>+ )}</MarkdownErrorBoundary>{showCursor && (<span className="inline-block w-0.5 h-4 bg-primary ml-0.5 animate-pulse align-middle" />diff --git a/frontend/src/components/chat/WelcomeScreen.tsx b/frontend/src/components/chat/WelcomeScreen.tsxindex b4dc8f226..6db913ffc 100644--- a/frontend/src/components/chat/WelcomeScreen.tsx+++ b/frontend/src/components/chat/WelcomeScreen.tsx@@ -1,6 +1,6 @@import { useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { ChevronDown, TrendingUp, Globe, Sparkles, Users, UserCircle2, NotebookPen, Landmark, Gem } from "lucide-react";+import { ChevronDown, TrendingUp, Globe, Sparkles, Users, UserCircle2, NotebookPen, Landmark, Gem, Search, WalletCards } from "lucide-react";import { BrandMark } from "@/components/common/BrandMark";interface Example {@@ -196,24 +196,19 @@ const GREETING_KEYS = {const QUICK_ACTIONS = [{- titleKey: "welcome.examples.valuationCheck",- promptKey: "welcome.examples.valuationCheckPrompt",- icon: <Gem className="h-4 w-4" aria-hidden="true" />,+ titleKey: "welcome.tasks.research",+ promptKey: "welcome.tasks.researchPrompt",+ icon: <Search className="h-4 w-4" aria-hidden="true" />,},{- titleKey: "welcome.examples.optionsGreeks",- promptKey: "welcome.examples.optionsGreeksPrompt",- icon: <Sparkles className="h-4 w-4" aria-hidden="true" />,- },- {- titleKey: "welcome.examples.crossMarketPortfolio",- promptKey: "welcome.examples.crossMarketPortfolioPrompt",+ titleKey: "welcome.tasks.backtest",+ promptKey: "welcome.tasks.backtestPrompt",icon: <TrendingUp className="h-4 w-4" aria-hidden="true" />,},{- titleKey: "welcome.examples.investmentCommittee",- promptKey: "welcome.examples.investmentCommitteePrompt",- icon: <Users className="h-4 w-4" aria-hidden="true" />,+ titleKey: "welcome.tasks.portfolio",+ promptKey: "welcome.tasks.portfolioPrompt",+ icon: <WalletCards className="h-4 w-4" aria-hidden="true" />,},] as const;@@ -255,6 +250,7 @@ export function WelcomeScreen({ onExample }: Props) {</div><p className="mt-3 text-sm text-muted-foreground">{t("welcome.taskSubtitle" as any)}+ <span className="mt-2 block text-xs">{t("welcome.tasks.hint")}</span></p></div>diff --git a/frontend/src/components/chat/__tests__/MessageBubble.math.test.tsx b/frontend/src/components/chat/__tests__/MessageBubble.math.test.tsxindex dffd9e666..1b64e601f 100644--- a/frontend/src/components/chat/__tests__/MessageBubble.math.test.tsx+++ b/frontend/src/components/chat/__tests__/MessageBubble.math.test.tsx@@ -1,4 +1,4 @@-import { render } from "@testing-library/react";+import { render, waitFor } from "@testing-library/react";import { MarkdownContent, MessageBubble } from "../MessageBubble";import type { AgentMessage } from "@/types/agent";@@ -11,23 +11,27 @@ function answer(content: string): AgentMessage {}describe("MessageBubble LaTeX rendering", () => {- it("renders \\(...\\) as KaTeX inline math", () => {+ // These cases verify the real math pipeline; module preparation belongs+ // outside the per-assertion wait, especially when the full suite is busy.+ beforeAll(async () => { await import("../EnhancedMarkdown"); });++ it("renders \\(...\\) as KaTeX inline math", async () => {const { container } = render(<MessageBubble msg={answer("Sharpe: \\(\\frac{R_p - R_f}{\\sigma_p}\\)")} />,);- expect(container.querySelector(".katex")).not.toBeNull();+ await waitFor(() => expect(container.querySelector(".katex")).not.toBeNull());});- it("renders \\[...\\] as KaTeX display math", () => {+ it("renders \\[...\\] as KaTeX display math", async () => {const { container } = render(<MessageBubble msg={answer("\\[\\sum_{i=1}^n w_i r_i\\]")} />,);- expect(container.querySelector(".katex-display")).not.toBeNull();+ await waitFor(() => expect(container.querySelector(".katex-display")).not.toBeNull());});- it("renders $$...$$ as KaTeX math", () => {+ it("renders $$...$$ as KaTeX math", async () => {const { container } = render(<MessageBubble msg={answer("Vol: $$\\sigma^2$$")} />);- expect(container.querySelector(".katex")).not.toBeNull();+ await waitFor(() => expect(container.querySelector(".katex")).not.toBeNull());});it("does NOT treat dollar amounts as math", () => {diff --git a/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx b/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsxindex 2783fd8ff..8864b5da2 100644--- a/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx+++ b/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx@@ -62,34 +62,26 @@ describe("WelcomeScreen", () => {).toBeInTheDocument();});- it("hands off all four quick-action prompts unchanged", async () => {+ it("fills the three beginner task prompts without submitting a request", async () => {const actions = [{- label: "Check if a stock is expensive",- prompt:- "Use the financial_rigor tool to verify Kweichow Moutai's valuation: price 1500, EPS 68.6, book value per share 180 — compute PE, PB, ROE exactly, then a three-scenario valuation (growth 12%/8%/0%, PE 22/18/14, 3 years)",+ label: "Research a stock",+ prompt: "Research AAPL: summarize its business, recent financial performance, and key risks using current data. State the sources and dates, and flag missing information.",},{- label: "Options risk check (Greeks)",- prompt:- "Calculate option Greeks using Black-Scholes: spot=100, strike=105, risk-free rate=3%, vol=25%, expiry=90 days, analyze Delta/Gamma/Theta/Vega",+ label: "Test a strategy",+ prompt: "Backtest a 20/60-day moving-average strategy on AAPL over the past year. Compare returns and drawdowns with buy-and-hold, and include trading costs. Keep this research-only.",},{- label: "Balance a 3-stock portfolio",- prompt:- "Build a risk-parity portfolio with 000001.SZ, 600519.SH, 000858.SZ, backtest for the full year of 2024, and compare with equal-weighted benchmark",- },- {- label: "Buy or sell? Let a committee debate",- prompt:- "[Swarm Team Mode] Use the investment_committee preset to evaluate whether to go long or short on 600519.SH given current market conditions",+ label: "Review my holdings",+ prompt: "Summarize my connected accounts and holdings, including concentration and portfolio risks. If no account is connected, explain how to set one up first. Do not place or modify orders.",},];const user = userEvent.setup();render(<WelcomeScreen onExample={onExample} />);const quickActions = screen.getByRole("group", { name: "Quick actions" });- expect(within(quickActions).getAllByRole("button")).toHaveLength(4);+ expect(within(quickActions).getAllByRole("button")).toHaveLength(3);for (const [index, action] of actions.entries()) {await user.click(@@ -97,7 +89,7 @@ describe("WelcomeScreen", () => {);expect(onExample).toHaveBeenNthCalledWith(index + 1, action.prompt);}- expect(onExample).toHaveBeenCalledTimes(4);+ expect(onExample).toHaveBeenCalledTimes(3);});it("marks the clicked quick action as selected and moves the selection", async () => {@@ -111,22 +103,22 @@ describe("WelcomeScreen", () => {expect(button).not.toHaveClass("text-primary");}- const committee = within(quickActions).getByRole("button", {- name: "Buy or sell? Let a committee debate",+ const portfolio = within(quickActions).getByRole("button", {+ name: "Review my holdings",});- await user.click(committee);- expect(committee).toHaveAttribute("aria-pressed", "true");- expect(committee).toHaveClass("text-primary");+ await user.click(portfolio);+ expect(portfolio).toHaveAttribute("aria-pressed", "true");+ expect(portfolio).toHaveClass("text-primary");expect(onExample).toHaveBeenCalledTimes(1);- const valuation = within(quickActions).getByRole("button", {- name: "Check if a stock is expensive",+ const research = within(quickActions).getByRole("button", {+ name: "Research a stock",});- await user.click(valuation);- expect(committee).toHaveAttribute("aria-pressed", "false");- expect(committee).not.toHaveClass("text-primary");- expect(valuation).toHaveAttribute("aria-pressed", "true");- expect(valuation).toHaveClass("text-primary");+ await user.click(research);+ expect(portfolio).toHaveAttribute("aria-pressed", "false");+ expect(portfolio).not.toHaveClass("text-primary");+ expect(research).toHaveAttribute("aria-pressed", "true");+ expect(research).toHaveClass("text-primary");expect(onExample).toHaveBeenCalledTimes(2);});diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex e1b8aac3a..f7ffc4de2 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";-import { useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { Link, Outlet, useLocation, useSearchParams } from "react-router";-import { Activity, BarChart3, Bot, CalendarClock, CandlestickChart, Check, ChevronDown, FileText, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2, WalletCards } from "lucide-react";+import { Check, ChevronDown, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Loader2, X } from "lucide-react";import { cn } from "@/lib/utils";import { useDarkMode } from "@/hooks/useDarkMode";import { api, type SessionItem } from "@/lib/api";@@ -10,6 +10,10 @@ import { useAgentStore } from "@/stores/agent";import { BrandMark } from "@/components/common/BrandMark";import { ConnectionBanner } from "@/components/layout/ConnectionBanner";import { SUPPORTED_LANGUAGES } from "@/i18n";+import i18n from "@/i18n";+import { toast } from "sonner";+import { SidebarNavigation } from "./SidebarNavigation";+import { PageHelp } from "./PageHelp";// APP_VERSION is sourced from i18n locale files (app.version key) to keep a// single source of truth across the footer and every localised README.@@ -17,31 +21,44 @@ import { SUPPORTED_LANGUAGES } from "@/i18n";export function Layout() {const { t } = useTranslation();- // "/" is the product (chat); marketing moved to /about. The Agent entry- // matches both "/" and legacy "/agent" deep links.- const NAV = [- { to: "/", icon: Bot, label: t('layout.agent') },- { to: "/runtime", icon: Activity, label: t('layout.runtime') },- { to: "/scheduled", icon: CalendarClock, label: t('layout.scheduled') },- { to: "/reports", icon: FileText, label: t('layout.reports') },- { to: "/portfolio", icon: WalletCards, label: t('layout.portfolio') },- { to: "/alpha-zoo", icon: Layers, label: t('layout.alphaZoo') },- { to: "/options", icon: CandlestickChart, label: t('layout.optionsLab') },- { to: "/settings", icon: Settings, label: t('layout.settings') },- { to: "/correlation", icon: BarChart3, label: t('layout.correlation') },- ];const { pathname } = useLocation();const [searchParams] = useSearchParams();const { dark, toggle } = useDarkMode();const [sessions, setSessions] = useState<SessionItem[]>([]);const [sessionsLoading, setSessionsLoading] = useState(true);+ const [sessionsError, setSessionsError] = useState<string | null>(null);+ const sessionsLoadGeneration = useRef(0);+ const pendingSessionActions = useRef(new Set<string>());const sseStatus = useAgentStore(s => s.sseStatus);const sseRetryAttempt = useAgentStore(s => s.sseRetryAttempt);const [collapsed, setCollapsed] = useState(() => safeGet("qa-sidebar") === "collapsed");+ const [sessionsOpen, setSessionsOpen] = useState(false);+ const sessionsPanelRef = useRef<HTMLDivElement>(null);+ const sessionsTriggerRef = useRef<HTMLButtonElement>(null);const activeSessionId = searchParams.get("session");const streamingSessionId = useAgentStore(s => s.streamingSessionId);+ useEffect(() => {+ if (!sessionsOpen) return;+ const dismiss = (event: MouseEvent) => {+ if (!sessionsPanelRef.current?.contains(event.target as Node)+ && !sessionsTriggerRef.current?.contains(event.target as Node)) setSessionsOpen(false);+ };+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ setSessionsOpen(false);+ sessionsTriggerRef.current?.focus();+ }+ };+ document.addEventListener("mousedown", dismiss);+ document.addEventListener("keydown", onKey);+ return () => {+ document.removeEventListener("mousedown", dismiss);+ document.removeEventListener("keydown", onKey);+ };+ }, [sessionsOpen]);+useEffect(() => {safeSet("qa-sidebar", collapsed ? "collapsed" : "expanded");}, [collapsed]);@@ -55,17 +72,32 @@ export function Layout() {return () => window.removeEventListener("storage", syncSidebarPreference);}, []);- const loadSessions = () => {+ const loadSessions = useCallback(() => {+ const generation = ++sessionsLoadGeneration.current;+ setSessionsLoading(true);api.listSessions()- .then((list) => setSessions(Array.isArray(list) ? list : []))- .catch(() => {})- .finally(() => setSessionsLoading(false));- };+ .then((list) => {+ if (generation !== sessionsLoadGeneration.current) return;+ setSessions(Array.isArray(list) ? list : []);+ setSessionsError(null);+ })+ .catch((error: unknown) => {+ if (generation === sessionsLoadGeneration.current) {+ setSessionsError(error instanceof Error ? error.message : i18n.t("settings.unknownError"));+ }+ })+ .finally(() => {+ if (generation === sessionsLoadGeneration.current) setSessionsLoading(false);+ });+ }, []);// Load sessions on mount. Also refresh when navigating TO /agent or when// the active session changes (covers new session creation from Agent).- const isAgentPage = pathname.startsWith("/agent");- useEffect(() => { loadSessions(); }, [isAgentPage, activeSessionId]);+ const isAgentPage = pathname === "/" || pathname.startsWith("/agent");+ useEffect(() => {+ loadSessions();+ return () => { sessionsLoadGeneration.current += 1; };+ }, [isAgentPage, activeSessionId, loadSessions]);// Re-list after out-of-band title changes (e.g. LLM auto-titling on the// first completed exchange).@@ -73,27 +105,40 @@ export function Layout() {const refresh = () => loadSessions();window.addEventListener("vibe:sessions-refresh", refresh);return () => window.removeEventListener("vibe:sessions-refresh", refresh);- }, []);+ }, [loadSessions]);const [deleteTarget, setDeleteTarget] = useState<string | null>(null);const [renameTarget, setRenameTarget] = useState<string | null>(null);const [renameValue, setRenameValue] = useState("");const deleteSession = async (sid: string) => {+ if (pendingSessionActions.current.has(sid)) return;+ pendingSessionActions.current.add(sid);try {await api.deleteSession(sid);setSessions((prev) => prev.filter((s) => s.session_id !== sid));- } catch { /* ignore */ }- setDeleteTarget(null);+ setDeleteTarget(null);+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("settings.unknownError"));+ } finally {+ pendingSessionActions.current.delete(sid);+ }};const renameSession = async (sid: string) => {if (!renameValue.trim()) { setRenameTarget(null); return; }+ if (pendingSessionActions.current.has(sid)) return;+ pendingSessionActions.current.add(sid);+ const title = renameValue.trim();try {- await api.renameSession(sid, renameValue.trim());- setSessions((prev) => prev.map((s) => s.session_id === sid ? { ...s, title: renameValue.trim() } : s));- } catch { /* ignore */ }- setRenameTarget(null);+ await api.renameSession(sid, title);+ setSessions((prev) => prev.map((s) => s.session_id === sid ? { ...s, title } : s));+ setRenameTarget(null);+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("settings.unknownError"));+ } finally {+ pendingSessionActions.current.delete(sid);+ }};return (@@ -127,36 +172,31 @@ export function Layout() {</div>{/* Nav */}- <nav- aria-label={t('layout.mainNavigation', { defaultValue: 'Main navigation' })}- className={cn("space-y-0.5", collapsed ? "p-1" : "p-2 max-md:p-1")}+ <SidebarNavigation collapsed={collapsed} />++ <button+ ref={sessionsTriggerRef}+ type="button"+ aria-label={t("layout.sessions")}+ aria-expanded={sessionsOpen}+ aria-controls="sidebar-sessions"+ title={t("layout.sessions")}+ onClick={() => setSessionsOpen((open) => !open)}+ className={cn("mx-1 mt-2 flex items-center justify-center rounded-md border-t p-2 text-muted-foreground hover:bg-muted", !collapsed && "md:hidden")}>- {NAV.map(({ to, icon: Icon, label }) => {- const text = label;- return (- <Link- key={to}- to={to}- aria-label={text}- className={cn(- "flex items-center rounded-md text-[13px] transition-colors",- collapsed ? "justify-center px-2 py-1.5" : "gap-3 px-3 py-1.5 max-md:justify-center max-md:px-2",- (to === "/" ? pathname === "/" || pathname.startsWith("/agent") : pathname.startsWith(to))- ? "bg-primary/10 text-primary font-medium"- : "text-muted-foreground hover:bg-muted/60 hover:text-foreground"- )}- title={collapsed ? text : undefined}- >- <Icon className="h-4 w-4 shrink-0" aria-hidden="true" />- {!collapsed && <span className="max-md:hidden">{text}</span>}- </Link>- );- })}- </nav>+ <MessageSquare className="h-4 w-4" />+ </button>- {/* Sessions — hidden when collapsed */}- {!collapsed && (- <div className="flex-1 overflow-auto border-t border-border/60 mt-2 flex flex-col max-md:hidden">+ {/* Compact layouts keep history and new-chat actions in a disclosure. */}+ {(!collapsed || sessionsOpen) && (+ <div+ ref={sessionsPanelRef}+ id="sidebar-sessions"+ aria-label={t("layout.sessions")}+ className={cn("overflow-auto flex flex-col border-border/60", sessionsOpen+ ? "fixed inset-y-0 start-12 z-40 w-[min(18rem,calc(100vw-3rem))] border-e bg-card shadow-xl"+ : "flex-1 border-t mt-2 max-md:hidden")}+ ><div className="flex items-center justify-between px-4 py-2"><span className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground"><MessageSquare className="h-3.5 w-3.5" />@@ -164,14 +204,23 @@ export function Layout() {</span><Linkto="/agent"+ onClick={() => setSessionsOpen(false)}aria-label={t('layout.newChat')}className="flex items-center gap-1 p-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"title={t('layout.newChat')}><Plus className="h-3.5 w-3.5" aria-hidden="true" /></Link>+ {sessionsOpen && <button type="button" aria-label={t("layout.collapse")} onClick={() => { setSessionsOpen(false); sessionsTriggerRef.current?.focus(); }} className="rounded p-1.5 text-muted-foreground hover:bg-muted"><X className="h-4 w-4" /></button>}</div>+ {sessionsOpen && sessionsError && (+ <div className="mx-3 mb-3 rounded-md border border-warning/30 bg-warning/10 p-3 text-xs">+ <p>{t("layout.sessionsLoadFailed")} {sessionsError}</p>+ <button type="button" onClick={loadSessions} disabled={sessionsLoading} className="mt-2 rounded border px-2 py-1 disabled:opacity-50">{t("connection.retry")}</button>+ </div>+ )}+<div className="px-2 pb-2 space-y-0.5 overflow-auto flex-1">{sessionsLoading ? (<div className="space-y-1.5 px-2 py-1">@@ -179,7 +228,7 @@ export function Layout() {<div key={i} className="h-7 rounded-md bg-muted/50 animate-pulse" />))}</div>- ) : sessions.length === 0 ? (+ ) : !sessionsError && sessions.length === 0 ? (<p className="px-3 py-2 text-xs text-muted-foreground/60">{t('layout.noSessions')}</p>) : null}{sessions.map((s) => {@@ -201,6 +250,7 @@ export function Layout() {) : (<Linkto={`/agent?session=${s.session_id}`}+ onClick={() => setSessionsOpen(false)}className={cn("flex-1 min-w-0 ps-3 pe-14 py-1.5 rounded-md text-xs transition-colors truncate block border-s-2",isActive@@ -267,6 +317,7 @@ export function Layout() {<button onClick={() => setCollapsed(false)} className="p-1.5 text-muted-foreground hover:text-foreground rounded transition-colors" title={t('layout.expand')}><ChevronsRight className="h-3.5 w-3.5" /></button>+ <LanguageSwitcher compact /></>) : (<>@@ -307,8 +358,18 @@ export function Layout() {{/* Main */}<div className="relative flex-1 flex flex-col overflow-hidden">- <ConnectionBanner status={sseStatus} retryAttempt={sseRetryAttempt} />+ {sessionsError ? (+ <div role="alert" className="flex flex-wrap items-center gap-2 border-b border-warning/30 bg-warning/10 px-4 py-2 text-xs">+ <span className="font-medium">{t("layout.sessionsLoadFailed")}</span>+ <span className="text-muted-foreground">{sessionsError}</span>+ <button type="button" onClick={loadSessions} disabled={sessionsLoading} className="ms-auto rounded-md border px-2 py-1 disabled:opacity-50">+ {sessionsLoading ? t("settings.loading") : t("connection.retry")}+ </button>+ <Link to="/settings" className="text-primary underline">{t("layout.settings")}</Link>+ </div>+ ) : <ConnectionBanner status={sseStatus} retryAttempt={sseRetryAttempt} />}<main id="main" className="flex-1 min-h-0 overflow-auto">+ <PageHelp /><Outlet /></main></div>@@ -329,7 +390,7 @@ export function Layout() {// the trigger sits in the layout or which language is active. We measure// the trigger with getBoundingClientRect() and update on resize/scroll.// ----------------------------------------------------------------------------function LanguageSwitcher() {+function LanguageSwitcher({ compact = false }: { compact?: boolean }) {const { i18n, t } = useTranslation();const [open, setOpen] = useState(false);const triggerRef = useRef<HTMLButtonElement | null>(null);@@ -414,8 +475,8 @@ function LanguageSwitcher() {className="flex items-center gap-1 p-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors max-md:justify-center"><Languages className="h-3.5 w-3.5 shrink-0" />- <span className="whitespace-nowrap max-md:hidden">{current.label}</span>- <ChevronDown className={cn("h-3 w-3 shrink-0 transition-transform max-md:hidden", open && "rotate-180")} />+ {!compact && <span className="whitespace-nowrap max-md:hidden">{current.label}</span>}+ {!compact && <ChevronDown className={cn("h-3 w-3 shrink-0 transition-transform max-md:hidden", open && "rotate-180")} />}</button>{open && menuStyle && (<uldiff --git a/frontend/src/components/layout/PageHelp.tsx b/frontend/src/components/layout/PageHelp.tsxnew file mode 100644index 000000000..e383e8664--- /dev/null+++ b/frontend/src/components/layout/PageHelp.tsx@@ -0,0 +1,25 @@+import { ChevronDown, CircleHelp } from "lucide-react";+import { Link, useLocation } from "react-router";+import { useTranslation } from "react-i18next";+import { isNavigationActive, NAVIGATION_GROUPS, type NavigationItem } from "./navigation";++export function PageHelp() {+ const { t } = useTranslation();+ const { pathname } = useLocation();+ const item = NAVIGATION_GROUPS.flatMap<NavigationItem>((group) => [...group.items]).find((entry) => isNavigationActive(entry.to, pathname));+ if (!item || item.id === "agent") return null;+ return (+ <details key={item.id} className="group border-b border-border/60 bg-card/50 px-4 py-2">+ <summary className="flex cursor-pointer list-none items-center gap-2 text-xs text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 [&::-webkit-details-marker]:hidden">+ <CircleHelp className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />+ {t("navigation.howTo", { feature: t(`layout.${item.id}`) })}+ <ChevronDown className="ms-auto h-3 w-3 transition-transform group-open:rotate-180" aria-hidden="true" />+ </summary>+ <div className="max-w-3xl space-y-2 py-3 text-sm leading-relaxed">+ <p>{t(`navigation.descriptions.${item.id}`)}</p>+ <p className="text-muted-foreground">{t(`navigation.instructions.${item.id}`)}</p>+ {item.id === "reports" && <Link to="/" className="inline-flex text-primary underline underline-offset-2">{t("navigation.startResearch")}</Link>}+ </div>+ </details>+ );+}diff --git a/frontend/src/components/layout/SidebarNavigation.tsx b/frontend/src/components/layout/SidebarNavigation.tsxnew file mode 100644index 000000000..970ffb8be--- /dev/null+++ b/frontend/src/components/layout/SidebarNavigation.tsx@@ -0,0 +1,89 @@+import { useEffect, useRef, useState } from "react";+import { Menu, X } from "lucide-react";+import { Link, useLocation } from "react-router";+import { useTranslation } from "react-i18next";+import { cn } from "@/lib/utils";+import { isNavigationActive, NAVIGATION_GROUPS } from "./navigation";++export function SidebarNavigation({ collapsed }: { collapsed: boolean }) {+ const { t } = useTranslation();+ const { pathname } = useLocation();+ const [menuOpen, setMenuOpen] = useState(false);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const panelRef = useRef<HTMLElement>(null);++ useEffect(() => { setMenuOpen(false); }, [pathname, collapsed]);+ useEffect(() => {+ if (!menuOpen) return;+ panelRef.current?.querySelector<HTMLElement>("a")?.focus();+ const close = () => setMenuOpen(false);+ const dismiss = (event: MouseEvent) => {+ if (!panelRef.current?.contains(event.target as Node)+ && !triggerRef.current?.contains(event.target as Node)) close();+ };+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ close();+ triggerRef.current?.focus();+ }+ };+ document.addEventListener("mousedown", dismiss);+ document.addEventListener("keydown", onKey);+ window.addEventListener("resize", close);+ return () => {+ document.removeEventListener("mousedown", dismiss);+ document.removeEventListener("keydown", onKey);+ window.removeEventListener("resize", close);+ };+ }, [menuOpen]);++ const groups = (compact: boolean, drawer = false) => NAVIGATION_GROUPS.map(({ id, items }) => (+ <section key={id} aria-label={t(`navigation.groups.${id}`)} className={cn(id !== "research" && "border-t border-border/60 pt-2")}>+ {!compact && <p className={cn("mb-1 px-3 text-[10px] font-medium text-muted-foreground/70", !drawer && "max-md:hidden")}>{t(`navigation.groups.${id}`)}</p>}+ <div className="space-y-0.5">+ {items.map(({ id: itemId, to, icon: Icon }) => {+ const label = t(`layout.${itemId}`);+ const active = isNavigationActive(to, pathname);+ return (+ <Link key={to} to={to} aria-label={label} aria-current={active ? "page" : undefined}+ title={`${label} — ${t(`navigation.descriptions.${itemId}`)}`}+ onClick={() => setMenuOpen(false)}+ className={cn("flex items-center rounded-md text-[13px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40",+ compact ? "justify-center px-2 py-1.5" : "gap-3 px-3 py-1.5",+ !compact && !drawer && "max-md:justify-center max-md:px-2",+ active ? "bg-primary/10 text-primary font-medium" : "text-muted-foreground hover:bg-muted/60 hover:text-foreground")}+ >+ <Icon className="h-4 w-4 shrink-0" aria-hidden="true" />+ {!compact && <span className={cn(!drawer && "max-md:hidden")}>{label}</span>}+ </Link>+ );+ })}+ </div>+ </section>+ ));++ return (+ <>+ <nav aria-label={t("layout.mainNavigation")}+ className={cn("max-h-[60vh] shrink-0 overflow-y-auto space-y-3", collapsed ? "p-1" : "p-2 max-md:p-1")}+ >+ <button ref={triggerRef} type="button" aria-label={t("navigation.menu")} title={t("navigation.menu")}+ aria-expanded={menuOpen} aria-controls="sidebar-feature-menu" onClick={() => setMenuOpen((open) => !open)}+ className={cn("flex w-full justify-center rounded-md border border-border/60 p-2 text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40", !collapsed && "md:hidden")}+ ><Menu className="h-4 w-4" aria-hidden="true" /></button>+ {groups(collapsed)}+ </nav>+ {menuOpen && (+ <nav ref={panelRef} id="sidebar-feature-menu" aria-label={t("navigation.menu")}+ className="fixed inset-y-0 start-12 z-40 w-[min(18rem,calc(100vw-3rem))] space-y-3 overflow-y-auto border-e bg-card p-3 shadow-xl"+ >+ <div className="flex items-center justify-between px-3 py-1 text-sm font-medium">+ {t("navigation.menu")}+ <button type="button" aria-label={t("navigation.close")} onClick={() => { setMenuOpen(false); triggerRef.current?.focus(); }} className="rounded p-1.5 hover:bg-muted"><X className="h-4 w-4" aria-hidden="true" /></button>+ </div>+ {groups(false, true)}+ </nav>+ )}+ </>+ );+}diff --git a/frontend/src/components/layout/__tests__/Layout.test.tsx b/frontend/src/components/layout/__tests__/Layout.test.tsxindex 981011a14..193166565 100644--- a/frontend/src/components/layout/__tests__/Layout.test.tsx+++ b/frontend/src/components/layout/__tests__/Layout.test.tsx@@ -1,6 +1,10 @@-import { fireEvent, render, screen } from "@testing-library/react";+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";import { MemoryRouter, Route, Routes } from "react-router";import { Layout } from "../Layout";+import { api } from "@/lib/api";+import { toast } from "sonner";++vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));const sessions = [{@@ -86,6 +90,13 @@ function renderLayout() {}describe("Layout accessibility", () => {+ beforeEach(() => {+ window.localStorage.removeItem("qa-sidebar");+ vi.mocked(toast.error).mockClear();+ vi.mocked(api.listSessions).mockReset().mockResolvedValue(sessions as never);+ vi.mocked(api.renameSession).mockReset().mockResolvedValue({ status: "ok" });+ vi.mocked(api.deleteSession).mockReset().mockResolvedValue({ status: "ok" });+ });it("labels landmarks, brand, main content, and the new-chat affordance", () => {renderLayout();@@ -151,4 +162,70 @@ describe("Layout accessibility", () => {expect(sidebar).toHaveClass("w-12");});++ it("shows a connection failure instead of an empty history, and retries", async () => {+ vi.mocked(api.listSessions).mockRejectedValueOnce(new Error("Backend unavailable"));+ renderLayout();+ expect(await screen.findByRole("alert")).toHaveTextContent("Backend unavailable");+ expect(screen.queryByText("No sessions yet")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "connection.retry" }));+ expect(await screen.findByText(sessions[0].title)).toBeInTheDocument();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ it("retains the rename draft and surfaces a failed save", async () => {+ vi.mocked(api.renameSession).mockRejectedValueOnce(new Error("Rename failed"));+ renderLayout();+ await screen.findByText(sessions[0].title);+ fireEvent.click(screen.getByRole("button", { name: "Rename" }));+ const input = screen.getByRole("textbox");+ fireEvent.change(input, { target: { value: "My renamed chat" } });+ fireEvent.keyDown(input, { key: "Enter" });+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Rename failed"));+ expect(input).toHaveValue("My renamed chat");+ fireEvent.keyDown(input, { key: "Enter" });+ expect(await screen.findByText("My renamed chat")).toBeInTheDocument();+ });++ it("keeps a failed deletion visible so it can be retried", async () => {+ vi.mocked(api.deleteSession).mockRejectedValueOnce(new Error("Delete failed"));+ renderLayout();+ await screen.findByText(sessions[0].title);+ fireEvent.click(screen.getByRole("button", { name: "Delete" }));+ fireEvent.click(screen.getByRole("button", { name: "Confirm" }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Delete failed"));+ expect(screen.getByText(sessions[0].title)).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Confirm" }));+ await waitFor(() => expect(screen.queryByText(sessions[0].title)).not.toBeInTheDocument());+ });++ it("does not submit rename twice when Enter is followed by blur", async () => {+ let complete!: (value: { status: string }) => void;+ vi.mocked(api.renameSession).mockReturnValueOnce(new Promise((resolve) => { complete = resolve; }));+ renderLayout();+ await screen.findByText(sessions[0].title);+ fireEvent.click(screen.getByRole("button", { name: "Rename" }));+ const input = screen.getByRole("textbox");+ fireEvent.change(input, { target: { value: "Renamed once" } });+ fireEvent.keyDown(input, { key: "Enter" });+ fireEvent.blur(input);+ expect(api.renameSession).toHaveBeenCalledOnce();+ await act(async () => complete({ status: "ok" }));+ expect(screen.getByText("Renamed once")).toBeInTheDocument();+ });++ it("keeps history, new chat and language reachable with a collapsed sidebar", async () => {+ window.localStorage.setItem("qa-sidebar", "collapsed");+ renderLayout();+ const trigger = screen.getByRole("button", { name: "Sessions" });+ expect(screen.queryByRole("link", { name: "New Chat" })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Language" })).toBeInTheDocument();+ fireEvent.click(trigger);+ expect(trigger).toHaveAttribute("aria-expanded", "true");+ expect(await screen.findByText(sessions[0].title)).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "New Chat" })).toBeInTheDocument();+ fireEvent.keyDown(document, { key: "Escape" });+ expect(trigger).toHaveAttribute("aria-expanded", "false");+ expect(trigger).toHaveFocus();+ });});diff --git a/frontend/src/components/layout/__tests__/Navigation.test.tsx b/frontend/src/components/layout/__tests__/Navigation.test.tsxnew file mode 100644index 000000000..e63391d51--- /dev/null+++ b/frontend/src/components/layout/__tests__/Navigation.test.tsx@@ -0,0 +1,69 @@+import { fireEvent, render, screen, within } from "@testing-library/react";+import { MemoryRouter } from "react-router";+import i18n from "@/i18n";+import { SidebarNavigation } from "../SidebarNavigation";+import { PageHelp } from "../PageHelp";++beforeAll(async () => { await i18n.changeLanguage("en"); });++function renderNavigation(path = "/", collapsed = false) {+ return render(<MemoryRouter initialEntries={[path]}><SidebarNavigation collapsed={collapsed} /><PageHelp /></MemoryRouter>);+}++it("keeps every feature directly reachable and distinguishes tasks from tools and setup", () => {+ renderNavigation();+ expect(within(screen.getByRole("region", { name: "Everyday research" })).getAllByRole("link").map((link) => link.getAttribute("href")))+ .toEqual(["/", "/reports", "/portfolio"]);+ expect(within(screen.getByRole("region", { name: "Specialized analysis" })).getAllByRole("link").map((link) => link.getAttribute("href")))+ .toEqual(["/alpha-zoo", "/options", "/correlation"]);+ expect(within(screen.getByRole("region", { name: "Automation & setup" })).getAllByRole("link").map((link) => link.getAttribute("href")))+ .toEqual(["/scheduled", "/runtime", "/settings"]);+ expect(screen.getByRole("link", { name: "Research assistant" })).toHaveAttribute("aria-current", "page");+});++it("retains labels and help in a compact sidebar, including nested factor routes", () => {+ renderNavigation("/alpha-zoo/compare", true);+ const link = screen.getByRole("link", { name: "Factor research" });+ expect(link).toHaveAttribute("aria-current", "page");+ expect(link).toHaveAttribute("title", expect.stringContaining("stock-selection signals"));+ expect(screen.getByRole("navigation").querySelectorAll('[aria-current="page"]')).toHaveLength(1);+});++it("explains the backtest prerequisite and the separate location of chat-generated documents", () => {+ renderNavigation("/reports");+ fireEvent.click(screen.getByText("How to use Backtest reports"));+ expect(screen.getByText(/Download PDFs and other chat-generated documents/)).toBeVisible();+ expect(screen.getByRole("link", { name: "Start with the research assistant" })).toHaveAttribute("href", "/");+});++it("resets page help on navigation and states the scheduler prerequisite", () => {+ renderNavigation("/reports");+ fireEvent.click(screen.getByText("How to use Backtest reports"));+ fireEvent.click(screen.getByRole("link", { name: "Scheduled research" }));+ const summary = screen.getByText("How to use Scheduled research");+ expect(summary.closest("details")).not.toHaveAttribute("open");+ fireEvent.click(summary);+ expect(screen.getByText(/local scheduler must be enabled/)).toBeVisible();+});++it("opens a labeled feature menu in compact mode and returns focus on Escape", () => {+ renderNavigation("/", true);+ const trigger = screen.getByRole("button", { name: "Browse features" });+ fireEvent.click(trigger);+ const menu = screen.getByRole("navigation", { name: "Browse features" });+ expect(within(menu).getByText("Options analysis")).toBeVisible();+ expect(within(menu).getByText("Trading status")).toBeVisible();+ expect(within(menu).getAllByRole("link")).toHaveLength(9);+ fireEvent.keyDown(document, { key: "Escape" });+ expect(screen.queryByRole("navigation", { name: "Browse features" })).not.toBeInTheDocument();+ expect(trigger).toHaveFocus();+});++it("closes the feature menu after selecting a destination", () => {+ renderNavigation("/", true);+ fireEvent.click(screen.getByRole("button", { name: "Browse features" }));+ const menu = screen.getByRole("navigation", { name: "Browse features" });+ fireEvent.click(within(menu).getByRole("link", { name: "Backtest reports" }));+ expect(screen.queryByRole("navigation", { name: "Browse features" })).not.toBeInTheDocument();+ expect(screen.getByText("How to use Backtest reports")).toBeInTheDocument();+});diff --git a/frontend/src/components/layout/navigation.ts b/frontend/src/components/layout/navigation.tsnew file mode 100644index 000000000..7d9629240--- /dev/null+++ b/frontend/src/components/layout/navigation.ts@@ -0,0 +1,26 @@+import { Activity, BarChart3, Bot, CalendarClock, CandlestickChart, FileText, Layers, Settings, WalletCards } from "lucide-react";++export const NAVIGATION_GROUPS = [+ { id: "research", items: [+ { id: "agent", to: "/", icon: Bot },+ { id: "reports", to: "/reports", icon: FileText },+ { id: "portfolio", to: "/portfolio", icon: WalletCards },+ ] },+ { id: "analysis", items: [+ { id: "alphaZoo", to: "/alpha-zoo", icon: Layers },+ { id: "optionsLab", to: "/options", icon: CandlestickChart },+ { id: "correlation", to: "/correlation", icon: BarChart3 },+ ] },+ { id: "automation", items: [+ { id: "scheduled", to: "/scheduled", icon: CalendarClock },+ { id: "runtime", to: "/runtime", icon: Activity },+ { id: "settings", to: "/settings", icon: Settings },+ ] },+] as const;++export type NavigationItem = typeof NAVIGATION_GROUPS[number]["items"][number];++export function isNavigationActive(to: string, pathname: string): boolean {+ return to === "/" ? pathname === "/" || pathname === "/agent"+ : pathname === to || pathname.startsWith(`${to}/`);+}diff --git a/frontend/src/components/options/OptionsChainTable.tsx b/frontend/src/components/options/OptionsChainTable.tsxindex 51c26b104..5b903e43f 100644--- a/frontend/src/components/options/OptionsChainTable.tsx+++ b/frontend/src/components/options/OptionsChainTable.tsx@@ -6,7 +6,6 @@ import { api } from "@/lib/api";import {bidAskSpreadPct,expirationLabel,- nearestStrikeIndex,type OptionsChainData,type OptionsContractRow,} from "@/lib/options";@@ -130,12 +129,7 @@ function SkeletonRows() {);}-interface Props {- /** Entry spot from the builder — anchors the ATM highlight when available. */- referenceSpot?: number;-}--export function OptionsChainTable({ referenceSpot }: Props) {+export function OptionsChainTable() {const { t } = useTranslation();const [tickerInput, setTickerInput] = useState(DEFAULT_TICKER);const [data, setData] = useState<OptionsChainData | null>(null);@@ -176,16 +170,8 @@ export function OptionsChainTable({ referenceSpot }: Props) {void load(ticker);};- const atmStrike = useMemo(() => {- if (!data) return null;- const rows = data.calls.length > 0 ? data.calls : data.puts;- if (rows.length === 0) return null;- const anchor =- referenceSpot !== undefined && Number.isFinite(referenceSpot) && referenceSpot > 0- ? referenceSpot- : [...rows].sort((a, b) => a.strike - b.strike)[Math.floor(rows.length / 2)].strike;- return rows[nearestStrikeIndex(rows, anchor)].strike;- }, [data, referenceSpot]);+ const atmStrike = data?.atm_strike != null && Number.isFinite(data.atm_strike)+ && data.atm_strike > 0 ? data.atm_strike : null;return (<section className="rounded-xl border border-border/60 bg-card p-4 shadow-sm">diff --git a/frontend/src/components/options/__tests__/OptionsChainTable.test.tsx b/frontend/src/components/options/__tests__/OptionsChainTable.test.tsxnew file mode 100644index 000000000..3df1eca49--- /dev/null+++ b/frontend/src/components/options/__tests__/OptionsChainTable.test.tsx@@ -0,0 +1,40 @@+import { render, screen, waitFor } from "@testing-library/react";+import { api } from "@/lib/api";+import { OptionsChainTable } from "../OptionsChainTable";+import type { OptionsChainResponse, OptionsContractRow } from "@/lib/options";++vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock("@/lib/api", () => ({ api: { getOptionsChain: vi.fn() } }));++function chain(strikes: number[], atm: number | null): OptionsChainResponse {+ return {+ ok: true, market: "us", source: "yahoo", data: {+ ticker: "AAPL", expiration: 1750000000, expirations: [1750000000],+ underlying_price: atm === null ? null : 337.4, atm_strike: atm,+ calls_count: strikes.length, puts_count: 0, puts: [],+ calls: strikes.map((strike) => ({ contract_symbol: `call-${strike}`, strike,+ last_price: null, bid: null, ask: null, volume: null, open_interest: null,+ implied_volatility: null, in_the_money: false, expiration: 1750000000,+ } satisfies OptionsContractRow)),+ },+ };+}++afterEach(() => vi.clearAllMocks());++it("marks the source-derived ATM strike instead of the simulator's default 100", async () => {+ vi.mocked(api.getOptionsChain).mockResolvedValue(chain([100, 330, 337, 340], 337));+ render(<OptionsChainTable />);+ const badge = await screen.findByText("options.chain.atm");+ expect(badge.closest("td")).toHaveTextContent("337");+});++it.each([+ ["missing quote", chain([100, 330, 337, 340], null)],+ ["ATM outside the displayed row cap", chain([100, 110, 120], 337)],+])("does not invent an ATM badge when %s", async (_name, response) => {+ vi.mocked(api.getOptionsChain).mockResolvedValue(response);+ render(<OptionsChainTable />);+ await waitFor(() => expect(screen.getByText("100")).toBeInTheDocument());+ expect(screen.queryByText("options.chain.atm")).not.toBeInTheDocument();+});diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex efdfbb03d..a01292cf7 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -2,17 +2,49 @@"app": {"version": "v0.1.16"},+ "navigation": {+ "menu": "استعرض الميزات",+ "close": "إغلاق قائمة الميزات",+ "groups": {+ "research": "البحث اليومي",+ "analysis": "تحليل متخصص",+ "automation": "الأتمتة والإعداد"+ },+ "howTo": "كيفية استخدام {{feature}}",+ "startResearch": "ابدأ بمساعد البحث",+ "descriptions": {+ "agent": "اطرح سؤالاً بحثياً أو صف استراتيجية بكلماتك.",+ "reports": "راجع الاختبارات التاريخية المكتملة وقارنها.",+ "portfolio": "اطلع على الأرصدة والمراكز في الحسابات المتصلة.",+ "alphaZoo": "استكشف إشارات اختيار الأسهم وقيّم أداءها التاريخي أو قارنه.",+ "optionsLab": "ابنِ استراتيجيات خيارات واستكشف الأرباح والمخاطر وسلاسل الخيارات الأمريكية.",+ "correlation": "قارن العلاقة بين تحركات الأصول.",+ "scheduled": "كرر مهمة بحثية وفق جدول زمني.",+ "runtime": "تحقق من اتصالات الوسطاء وحالة تشغيل التداول.",+ "settings": "اضبط النماذج ومصادر البيانات واتصالات الوسطاء."+ },+ "instructions": {+ "reports": "اطلب أولاً من المساعد اختبار استراتيجية تاريخياً، ثم افتح نتائجها هنا. نزّل ملفات PDF والمستندات المنشأة في الدردشة من المحادثة الأصلية.",+ "portfolio": "أضف مصدر حساب وفعّله، ثم حدّث المراكز. تقدم هذه الصفحة ملخصاً للحسابات للقراءة فقط.",+ "alphaZoo": "اقرأ تعريف العامل، ثم اختر السوق والفترة لتقييم الإشارات أو مقارنتها. تحقّق من الإشارات المرشحة باختبار تاريخي.",+ "optionsLab": "اختر نموذجاً جاهزاً أو أضف أرجل خيارات، ثم عدّل السعر والأجل والتقلب؛ تتحدث النتائج تلقائياً. رمز سهم السلسلة الفعلية منفصل عن مدخلات المحاكاة.",+ "correlation": "أدخل رمزين على الأقل للأصول، واختر الفترة، ثم اضغط حساب.",+ "scheduled": "أدخل تعليمات البحث وتكراره واحفظها. يلزم تفعيل المجدول المحلي لتشغيل المهام، وإعداد قناة لإرسال النتائج.",+ "runtime": "اضبط اتصال الوسيط أولاً في الإعدادات أو صفحة المحفظة. تعتمد عمليات التداول المتاحة على قدرات الوسيط والتفويض الذي تمنحه.",+ "settings": "اضبط نموذجاً للبدء. أضف مصادر بيانات أو اتصالات وسطاء حسب المهمة؛ لا يحتاج بحث بيانات السوق العامة إلى حساب وسيط."+ }+ },"layout": {"home": "الرئيسية",- "agent": "الوكيل",- "runtime": "مراقبة التداول",- "scheduled": "المجدولة",- "reports": "التقارير",- "portfolio": "المحفظة",- "alphaZoo": "مكتبة ألفا",+ "agent": "مساعد البحث",+ "runtime": "حالة التداول",+ "scheduled": "البحث المجدول",+ "reports": "تقارير الاختبار التاريخي",+ "portfolio": "مراكز الحسابات",+ "alphaZoo": "بحث العوامل","settings": "الإعدادات",- "correlation": "مصفوفة الارتباط",- "optionsLab": "مختبر الخيارات",+ "correlation": "ارتباط الأصول",+ "optionsLab": "تحليل الخيارات","sessions": "الجلسات","newChat": "محادثة جديدة","noSessions": "لا توجد محادثات بعد — اضغط + لبدء محادثة",@@ -28,7 +60,8 @@"skipToMain": "تخطَّ إلى المحتوى الرئيسي","sidebar": "الشريط الجانبي لـ Vibe-Trading","mainNavigation": "التنقل الرئيسي",- "about": "حول"+ "about": "حول",+ "sessionsLoadFailed": "تعذر تحميل المحادثات."},"runtime": {"monitorBadge": "مراقبة التداول",@@ -255,7 +288,7 @@"unavailable": "مكتبة التقارير غير متاحة","loadError": "تعذّر تحميل التقارير.","emptyTitle": "لا توجد تقارير بعد",- "emptyBody": "أنشئ اختبارًا عكسيًا من الوكيل، ثم عُد هنا لمراجعته.",+ "emptyBody": "اطلب من مساعد البحث إجراء اختبار تاريخي، ثم عُد هنا لمراجعة النتائج.","noMatchesTitle": "لا توجد تقارير مطابقة","noMatchesBody": "عدّل استعلام البحث أو فلتر الحالة أو النطاق الزمني.","noPrompt": "لم يتم تسجيل أي مطالبة.",@@ -269,9 +302,22 @@"connection": {"reconnecting": "جارٍ إعادة الاتصال…","disconnected": "فُقد الاتصال. أعد تحميل الصفحة لاستعادة الاتصال.",- "reload": "إعادة التحميل"+ "reload": "إعادة التحميل",+ "retry": "إعادة محاولة الاتصال",+ "requestFailed": "تعذر الاتصال بخادم API. تأكد من تشغيله ومن توفر اتصال الشبكة.",+ "requestTimeout": "انتهت مهلة الطلب. تحقق من الاتصال بالخادم ثم حاول مجددًا.",+ "requestTimeoutMutation": "انتهت مهلة الطلب. قد يظل الخادم يعالجه؛ تحقق من الحالة الحالية قبل إعادة المحاولة."},"welcome": {+ "tasks": {+ "research": "ابحث عن سهم",+ "backtest": "اختبر استراتيجية",+ "portfolio": "راجع مراكزي",+ "hint": "تملأ الأمثلة مربع الرسالة. عدّل الرمز أو الاستراتيجية قبل الإرسال.",+ "researchPrompt": "ابحث عن AAPL باستخدام البيانات الحالية المتاحة: لخّص نشاطها وأداءها المالي الأخير والمخاطر الرئيسية. اذكر المصادر والتواريخ والمعلومات الناقصة.",+ "backtestPrompt": "اختبر تاريخياً استراتيجية المتوسط المتحرك لمدة 20 و60 يوماً لسهم AAPL خلال السنة الماضية. قارن العائد والتراجع مع الشراء والاحتفاظ، وأدرج تكاليف التداول. للبحث فقط.",+ "portfolioPrompt": "لخّص مراكز حساباتي المتصلة والتركيز ومخاطر المحفظة. إذا لم يوجد حساب متصل، اشرح كيفية إعداده أولاً. لا ترسل أو تعدّل أوامر."+ },"categories": {"multiMarketBacktest": "اختبار عكسي لأسهم A","researchAnalysis": "البحث والتحليل",diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex 28d7398cf..718fde384 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -7,16 +7,48 @@"noCorrelationData": "Wählen Sie mindestens zwei Symbole zum Vergleichen","noEquityData": "Noch keine Kontowert-Kurve — führen Sie zuerst einen Backtest durch"},+ "navigation": {+ "menu": "Funktionen entdecken",+ "close": "Funktionsmenü schließen",+ "groups": {+ "research": "Tägliche Recherche",+ "analysis": "Spezialisierte Analyse",+ "automation": "Automatisierung & Einrichtung"+ },+ "howTo": "So verwendest du {{feature}}",+ "startResearch": "Mit dem Rechercheassistenten starten",+ "descriptions": {+ "agent": "Stelle eine Recherchefrage oder beschreibe eine Strategie in eigenen Worten.",+ "reports": "Abgeschlossene Backtests ansehen und vergleichen.",+ "portfolio": "Guthaben und Positionen verbundener Konten zusammen ansehen.",+ "alphaZoo": "Aktienauswahlsignale erkunden und historische Ergebnisse bewerten oder vergleichen.",+ "optionsLab": "Optionsstrategien erstellen, Gewinn und Risiko untersuchen und US-Optionsketten ansehen.",+ "correlation": "Vergleichen, wie sich Vermögenswerte gemeinsam bewegen.",+ "scheduled": "Eine Recherche nach Zeitplan wiederholen.",+ "runtime": "Brokerverbindungen und den Betriebsstatus des Handels prüfen.",+ "settings": "Modelle, Datenquellen und Brokerverbindungen konfigurieren."+ },+ "instructions": {+ "reports": "Bitte den Assistenten zuerst um einen Strategie-Backtest und öffne hier die Ergebnisse. Im Chat erstellte PDFs und andere Dokumente lädst du in der ursprünglichen Unterhaltung herunter.",+ "portfolio": "Füge eine Kontoquelle hinzu, aktiviere sie und aktualisiere die Positionen. Diese Seite zeigt Kontodaten schreibgeschützt an.",+ "alphaZoo": "Lies die Faktordefinition und wähle Markt und Zeitraum, um Signale zu bewerten oder zu vergleichen. Prüfe Kandidaten mit einem Backtest.",+ "optionsLab": "Wähle eine Vorlage oder füge Optionslegs hinzu und passe Preis, Laufzeit und Volatilität an; Ergebnisse werden automatisch aktualisiert. Das Symbol der echten Optionskette ist von der Simulation getrennt.",+ "correlation": "Gib mindestens zwei Wertpapiercodes ein, wähle den Zeitraum und klicke auf Berechnen.",+ "scheduled": "Gib einen Rechercheauftrag ein, wähle die Häufigkeit und speichere. Für die Ausführung muss der lokale Planer aktiviert sein; zur Zustellung ist ein eingerichteter Kanal nötig.",+ "runtime": "Richte zuerst unter Einstellungen oder Portfolio eine Brokerverbindung ein. Verfügbare Handelsaktionen hängen von den Brokerfunktionen und deiner Autorisierung ab.",+ "settings": "Richte zunächst ein Modell ein. Ergänze Datenquellen oder Brokerverbindungen nach Bedarf; für öffentliche Marktrecherche ist kein Brokerkonto nötig."+ }+ },"layout": {"home": "Startseite",- "agent": "Agent",- "runtime": "Runtime",- "scheduled": "Geplant",- "reports": "Berichte",- "alphaZoo": "Alpha Zoo",+ "agent": "Rechercheassistent",+ "runtime": "Handelsstatus",+ "scheduled": "Geplante Recherche",+ "reports": "Backtest-Berichte",+ "alphaZoo": "Faktorrecherche","settings": "Einstellungen",- "correlation": "Korrelationsmatrix",- "optionsLab": "Options-Labor",+ "correlation": "Korrelation der Anlagen",+ "optionsLab": "Optionsanalyse","sessions": "Sitzungen","newChat": "Neuer Chat","noSessions": "Noch keine Chats — drücken Sie +, um einen zu starten",@@ -33,7 +65,8 @@"sidebar": "Vibe-Trading-Seitenleiste","mainNavigation": "Hauptnavigation","about": "Über",- "portfolio": "Portfolio"+ "portfolio": "Kontopositionen",+ "sessionsLoadFailed": "Gespräche können nicht geladen werden."},"runtime": {"monitorBadge": "Runtime-Monitor",@@ -260,7 +293,7 @@"unavailable": "Berichtsbibliothek nicht verfügbar","loadError": "Berichte konnten nicht geladen werden.","emptyTitle": "Noch keine Berichte",- "emptyBody": "Erstellen Sie einen Backtest im Agent-Bereich, dann kehren Sie hierher zurück, um ihn zu prüfen.",+ "emptyBody": "Bitte den Rechercheassistenten um einen Backtest und sieh dir hier die Ergebnisse an.","noMatchesTitle": "Keine passenden Berichte","noMatchesBody": "Passen Sie Ihre Suchanfrage, den Statusfilter oder den Datumsbereich an.","noPrompt": "Kein Prompt erfasst.",@@ -274,9 +307,22 @@"connection": {"reconnecting": "Verbindung wird wiederhergestellt …","disconnected": "Verbindung verloren. Laden Sie die Seite neu, um wieder zu verbinden.",- "reload": "Neu laden"+ "reload": "Neu laden",+ "retry": "Verbindung erneut versuchen",+ "requestFailed": "Der API-Server ist nicht erreichbar. Prüfe, ob er läuft und eine Netzwerkverbindung besteht.",+ "requestTimeout": "Die Anfrage hat das Zeitlimit überschritten. Prüfe die Serververbindung und versuche es erneut.",+ "requestTimeoutMutation": "Die Anfrage hat das Zeitlimit überschritten. Der Server verarbeitet sie möglicherweise noch; prüfe den aktuellen Status, bevor du es erneut versuchst."},"welcome": {+ "tasks": {+ "research": "Eine Aktie recherchieren",+ "backtest": "Eine Strategie prüfen",+ "portfolio": "Meine Positionen prüfen",+ "hint": "Beispiele füllen das Nachrichtenfeld. Passe Symbol oder Strategie vor dem Senden an.",+ "researchPrompt": "Recherchiere AAPL mit aktuell verfügbaren Daten: Fasse Geschäft, jüngste Finanzentwicklung und wesentliche Risiken zusammen. Nenne Quellen und Daten und kennzeichne fehlende Informationen.",+ "backtestPrompt": "Teste eine 20/60-Tage-Durchschnittsstrategie für AAPL im vergangenen Jahr historisch. Vergleiche Renditen und Drawdowns mit Kaufen und Halten und berücksichtige Handelskosten. Nur Recherche.",+ "portfolioPrompt": "Fasse Positionen, Konzentration und Portfoliorisiken meiner verbundenen Konten zusammen. Erkläre zuerst die Einrichtung, falls kein Konto verbunden ist. Keine Orders aufgeben oder ändern."+ },"categories": {"multiMarketBacktest": "A-Share Backtest","researchAnalysis": "Recherche & Analyse",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 26716b1b5..5a15bb7dc 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -7,17 +7,49 @@"noCorrelationData": "Pick at least two symbols to compare","noEquityData": "No account-value curve yet — run a backtest first"},+ "navigation": {+ "menu": "Browse features",+ "close": "Close feature menu",+ "groups": {+ "research": "Everyday research",+ "analysis": "Specialized analysis",+ "automation": "Automation & setup"+ },+ "howTo": "How to use {{feature}}",+ "startResearch": "Start with the research assistant",+ "descriptions": {+ "agent": "Ask a research question or describe a strategy in your own words.",+ "reports": "Review and compare completed backtests.",+ "portfolio": "See balances and holdings across connected accounts.",+ "alphaZoo": "Explore stock-selection signals and evaluate their historical performance.",+ "optionsLab": "Build option strategies, explore payoff and risk, and browse US option chains.",+ "correlation": "Compare how assets move together.",+ "scheduled": "Repeat a research task on a schedule.",+ "runtime": "Check broker connections and trading runtime status.",+ "settings": "Configure models, data sources, and broker connections."+ },+ "instructions": {+ "reports": "Ask the research assistant to backtest a strategy first, then open its results here. Download PDFs and other chat-generated documents from the original conversation.",+ "portfolio": "Add and enable an account source, then refresh its holdings. This page provides a read-only account overview.",+ "alphaZoo": "Read a factor definition, then choose a market and date range to evaluate or compare signals. Validate candidates with a backtest.",+ "optionsLab": "Choose a preset or add option legs, then adjust price, expiry, and volatility; results update automatically. The stock symbol for the live chain is separate from the simulation inputs.",+ "correlation": "Enter at least two asset symbols, choose a lookback window, then select Compute.",+ "scheduled": "Enter a research instruction, choose its cadence, and save. The local scheduler must be enabled for jobs to run; delivery also needs a configured channel.",+ "runtime": "Configure a broker connection in Settings or Portfolio first. Available trading actions depend on that broker's capabilities and your authorization.",+ "settings": "Configure a model to start. Add data sources or broker connections as your task needs them; public-market research does not require a broker account."+ }+ },"layout": {"home": "Home",- "agent": "Agent",- "runtime": "Runtime",- "scheduled": "Scheduled",- "reports": "Reports",- "portfolio": "Portfolio",- "alphaZoo": "Alpha Zoo",+ "agent": "Research assistant",+ "runtime": "Trading status",+ "scheduled": "Scheduled research",+ "reports": "Backtest reports",+ "portfolio": "Account holdings",+ "alphaZoo": "Factor research","settings": "Settings",- "correlation": "Correlation Matrix",- "optionsLab": "Options Lab",+ "correlation": "Asset correlation",+ "optionsLab": "Options analysis","sessions": "Sessions","newChat": "New Chat","noSessions": "No chats yet — press + to start one",@@ -33,7 +65,8 @@"skipToMain": "Skip to main content","sidebar": "Vibe-Trading sidebar","mainNavigation": "Main navigation",- "about": "About"+ "about": "About",+ "sessionsLoadFailed": "Cannot load conversations."},"runtime": {"monitorBadge": "Runtime Monitor",@@ -260,7 +293,7 @@"unavailable": "Report library unavailable","loadError": "Unable to load reports.","emptyTitle": "No reports yet",- "emptyBody": "Create a backtest from Agent, then return here to review it.",+ "emptyBody": "Ask the research assistant to run a backtest, then return here to review the results.","noMatchesTitle": "No matching reports","noMatchesBody": "Adjust your search query, status filter, or date range.","noPrompt": "No prompt recorded.",@@ -274,9 +307,22 @@"connection": {"reconnecting": "Reconnecting…","disconnected": "Connection lost. Reload the page to reconnect.",- "reload": "Reload"+ "reload": "Reload",+ "retry": "Retry connection",+ "requestFailed": "Cannot reach the API server. Check that it is running and that your network connection is available.",+ "requestTimeout": "The request timed out. Check the server connection, then try again.",+ "requestTimeoutMutation": "The request timed out. The server may still be processing it; check the current state before trying again."},"welcome": {+ "tasks": {+ "research": "Research a stock",+ "backtest": "Test a strategy",+ "portfolio": "Review my holdings",+ "hint": "Examples fill the message box. Edit the symbol or strategy before sending.",+ "researchPrompt": "Research AAPL: summarize its business, recent financial performance, and key risks using current data. State the sources and dates, and flag missing information.",+ "backtestPrompt": "Backtest a 20/60-day moving-average strategy on AAPL over the past year. Compare returns and drawdowns with buy-and-hold, and include trading costs. Keep this research-only.",+ "portfolioPrompt": "Summarize my connected accounts and holdings, including concentration and portfolio risks. If no account is connected, explain how to set one up first. Do not place or modify orders."+ },"categories": {"multiMarketBacktest": "A-Share Backtest","researchAnalysis": "Research & Analysis",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 91a2e39c1..140dcfda5 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -7,17 +7,49 @@"noCorrelationData": "Elige al menos dos símbolos para comparar","noEquityData": "Aún no hay curva de valor de cuenta — ejecuta primero un backtest"},+ "navigation": {+ "menu": "Explorar funciones",+ "close": "Cerrar menú de funciones",+ "groups": {+ "research": "Investigación habitual",+ "analysis": "Análisis especializado",+ "automation": "Automatización y ajustes"+ },+ "howTo": "Cómo usar {{feature}}",+ "startResearch": "Empieza con el asistente de investigación",+ "descriptions": {+ "agent": "Plantea una pregunta de investigación o describe una estrategia con tus palabras.",+ "reports": "Consulta y compara backtests terminados.",+ "portfolio": "Consulta los saldos y posiciones de las cuentas conectadas.",+ "alphaZoo": "Explora señales de selección de acciones y evalúa o compara su rendimiento histórico.",+ "optionsLab": "Construye estrategias de opciones, explora beneficios y riesgos y consulta cadenas de opciones de EE. UU.",+ "correlation": "Compara cómo se mueven los activos entre sí.",+ "scheduled": "Repite una investigación según un horario.",+ "runtime": "Comprueba conexiones de brókeres y el estado de ejecución de operaciones.",+ "settings": "Configura modelos, fuentes de datos y conexiones de brókeres."+ },+ "instructions": {+ "reports": "Primero pide al asistente un backtest de una estrategia y abre aquí sus resultados. Descarga los PDF y documentos generados en el chat desde la conversación original.",+ "portfolio": "Añade y activa una fuente de cuenta y actualiza las posiciones. Esta página resume los datos de las cuentas en modo de solo lectura.",+ "alphaZoo": "Lee la definición del factor y elige mercado y fechas para evaluar o comparar señales. Valida las candidatas con un backtest.",+ "optionsLab": "Elige un preajuste o añade patas de opciones y ajusta precio, vencimiento y volatilidad; los resultados se actualizan automáticamente. El símbolo de la cadena real es independiente de la simulación.",+ "correlation": "Introduce al menos dos símbolos de activos, elige el período y pulsa Calcular.",+ "scheduled": "Introduce la instrucción de investigación, elige la frecuencia y guarda. El programador local debe estar activado para ejecutar tareas; el envío requiere un canal configurado.",+ "runtime": "Primero configura una conexión de bróker en Ajustes o Cartera. Las operaciones disponibles dependen de sus capacidades y de tu autorización.",+ "settings": "Configura un modelo para empezar. Añade datos o conexiones de brókeres según lo necesites; investigar datos públicos de mercado no requiere una cuenta de bróker."+ }+ },"layout": {"home": "Inicio",- "agent": "Agente",- "runtime": "Runtime",- "scheduled": "Programado",- "reports": "Informes",- "portfolio": "Cartera",- "alphaZoo": "Alpha Zoo",+ "agent": "Asistente de investigación",+ "runtime": "Estado de operaciones",+ "scheduled": "Investigación programada",+ "reports": "Informes de backtest",+ "portfolio": "Posiciones de cuentas",+ "alphaZoo": "Investigación de factores","settings": "Configuración",- "correlation": "Matriz de correlación",- "optionsLab": "Laboratorio de opciones",+ "correlation": "Correlación de activos",+ "optionsLab": "Análisis de opciones","sessions": "Sesiones","newChat": "Nuevo chat","noSessions": "Aún no hay chats — pulsa + para empezar uno",@@ -33,7 +65,8 @@"skipToMain": "Saltar al contenido principal","sidebar": "Barra lateral de Vibe-Trading","mainNavigation": "Navegación principal",- "about": "Acerca de"+ "about": "Acerca de",+ "sessionsLoadFailed": "No se pueden cargar las conversaciones."},"runtime": {"monitorBadge": "Monitor de Runtime",@@ -260,7 +293,7 @@"unavailable": "Biblioteca de informes no disponible","loadError": "No se pudieron cargar los informes.","emptyTitle": "Aún no hay informes",- "emptyBody": "Crea un backtest desde Agente y vuelve aquí para revisarlo.",+ "emptyBody": "Pide al asistente de investigación un backtest y vuelve aquí para revisar los resultados.","noMatchesTitle": "No hay informes que coincidan","noMatchesBody": "Ajusta tu búsqueda, el filtro de estado o el rango de fechas.","noPrompt": "No se registró ningún prompt.",@@ -274,9 +307,22 @@"connection": {"reconnecting": "Reconectando…","disconnected": "Se perdió la conexión. Recarga la página para reconectar.",- "reload": "Recargar"+ "reload": "Recargar",+ "retry": "Reintentar conexión",+ "requestFailed": "No se puede conectar con el servidor API. Comprueba que esté en funcionamiento y que haya conexión de red.",+ "requestTimeout": "La solicitud agotó el tiempo de espera. Comprueba la conexión con el servidor y vuelve a intentarlo.",+ "requestTimeoutMutation": "La solicitud agotó el tiempo de espera. El servidor podría seguir procesándola; comprueba el estado actual antes de reintentar."},"welcome": {+ "tasks": {+ "research": "Investigar una acción",+ "backtest": "Probar una estrategia",+ "portfolio": "Revisar mis posiciones",+ "hint": "Los ejemplos rellenan el mensaje. Edita el símbolo o la estrategia antes de enviarlo.",+ "researchPrompt": "Investiga AAPL con los datos actuales disponibles: resume su negocio, resultados financieros recientes y riesgos principales. Indica fuentes, fechas e información que falta.",+ "backtestPrompt": "Haz un backtest de una estrategia de medias móviles de 20/60 días en AAPL durante el último año. Compara rentabilidad y caídas con comprar y mantener e incluye costes de negociación. Solo investigación.",+ "portfolioPrompt": "Resume mis cuentas conectadas y posiciones, su concentración y riesgos de cartera. Si no hay cuentas conectadas, explica primero cómo configurarlas. No envíes ni modifiques órdenes."+ },"categories": {"multiMarketBacktest": "Backtest de acciones A","researchAnalysis": "Investigación y análisis",diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.jsonindex 3f7f7b6c3..85677a7f7 100644--- a/frontend/src/i18n/locales/id.json+++ b/frontend/src/i18n/locales/id.json@@ -7,17 +7,49 @@"noCorrelationData": "Pilih setidaknya dua simbol untuk dibandingkan","noEquityData": "Belum ada kurva nilai akun — jalankan backtest terlebih dahulu"},+ "navigation": {+ "menu": "Jelajahi fitur",+ "close": "Tutup menu fitur",+ "groups": {+ "research": "Riset sehari-hari",+ "analysis": "Analisis khusus",+ "automation": "Otomatisasi & pengaturan"+ },+ "howTo": "Cara menggunakan {{feature}}",+ "startResearch": "Mulai dengan asisten riset",+ "descriptions": {+ "agent": "Ajukan pertanyaan riset atau jelaskan strategi dengan kata-kata sendiri.",+ "reports": "Lihat dan bandingkan backtest yang telah selesai.",+ "portfolio": "Lihat saldo dan posisi dari akun yang terhubung.",+ "alphaZoo": "Jelajahi sinyal pemilihan saham dan evaluasi atau bandingkan kinerja historisnya.",+ "optionsLab": "Susun strategi opsi, pelajari laba dan risiko, serta lihat rantai opsi AS.",+ "correlation": "Bandingkan hubungan pergerakan aset.",+ "scheduled": "Ulangi tugas riset sesuai jadwal.",+ "runtime": "Periksa koneksi broker dan status pelaksanaan perdagangan.",+ "settings": "Atur model, sumber data, dan koneksi broker."+ },+ "instructions": {+ "reports": "Minta asisten melakukan backtest strategi terlebih dahulu, lalu buka hasilnya di sini. Unduh PDF dan dokumen yang dibuat di chat dari percakapan asal.",+ "portfolio": "Tambahkan dan aktifkan sumber akun, lalu perbarui posisi. Halaman ini merangkum data akun dalam mode baca saja.",+ "alphaZoo": "Baca definisi faktor, lalu pilih pasar dan rentang tanggal untuk mengevaluasi atau membandingkan sinyal. Validasi kandidat dengan backtest.",+ "optionsLab": "Pilih preset atau tambahkan kaki opsi, lalu sesuaikan harga, jatuh tempo, dan volatilitas; hasil diperbarui otomatis. Simbol rantai opsi aktual terpisah dari masukan simulasi.",+ "correlation": "Masukkan setidaknya dua simbol aset, pilih periode, lalu klik Hitung.",+ "scheduled": "Isi instruksi riset, pilih frekuensi, dan simpan. Penjadwal lokal harus diaktifkan agar tugas berjalan; pengiriman juga memerlukan kanal yang telah diatur.",+ "runtime": "Atur koneksi broker di Pengaturan atau Portofolio terlebih dahulu. Tindakan perdagangan yang tersedia bergantung pada kemampuan broker dan otorisasi Anda.",+ "settings": "Atur model untuk memulai. Tambahkan data atau koneksi broker sesuai kebutuhan; riset data pasar publik tidak memerlukan akun broker."+ }+ },"layout": {"home": "Beranda",- "agent": "Agent",- "runtime": "Runtime",- "scheduled": "Terjadwal",- "reports": "Laporan",- "portfolio": "Portofolio",- "alphaZoo": "Alpha Zoo",+ "agent": "Asisten riset",+ "runtime": "Status perdagangan",+ "scheduled": "Riset terjadwal",+ "reports": "Laporan backtest",+ "portfolio": "Posisi akun",+ "alphaZoo": "Riset faktor","settings": "Pengaturan",- "correlation": "Matriks Korelasi",- "optionsLab": "Lab Opsi",+ "correlation": "Korelasi aset",+ "optionsLab": "Analisis opsi","sessions": "Sesi","newChat": "Chat Baru","noSessions": "Belum ada chat — tekan + untuk memulai",@@ -33,7 +65,8 @@"skipToMain": "Lewati ke konten utama","sidebar": "Sidebar Vibe-Trading","mainNavigation": "Navigasi utama",- "about": "Tentang"+ "about": "Tentang",+ "sessionsLoadFailed": "Percakapan tidak dapat dimuat."},"runtime": {"monitorBadge": "Monitor Runtime",@@ -260,7 +293,7 @@"unavailable": "Pustaka laporan tidak tersedia","loadError": "Tidak dapat memuat laporan.","emptyTitle": "Belum ada laporan",- "emptyBody": "Buat backtest dari Agent, lalu kembali ke sini untuk meninjaunya.",+ "emptyBody": "Minta asisten riset melakukan backtest, lalu kembali ke sini untuk melihat hasilnya.","noMatchesTitle": "Tidak ada laporan yang cocok","noMatchesBody": "Sesuaikan pencarian, filter status, atau rentang tanggal.","noPrompt": "Tidak ada prompt yang tercatat.",@@ -274,9 +307,22 @@"connection": {"reconnecting": "Menghubungkan kembali…","disconnected": "Koneksi terputus. Muat ulang halaman untuk menghubungkan kembali.",- "reload": "Muat Ulang"+ "reload": "Muat Ulang",+ "retry": "Coba sambungkan lagi",+ "requestFailed": "Tidak dapat menghubungi server API. Pastikan server berjalan dan koneksi jaringan tersedia.",+ "requestTimeout": "Waktu permintaan habis. Periksa koneksi server, lalu coba lagi.",+ "requestTimeoutMutation": "Waktu permintaan habis. Server mungkin masih memprosesnya; periksa status saat ini sebelum mencoba lagi."},"welcome": {+ "tasks": {+ "research": "Riset sebuah saham",+ "backtest": "Uji sebuah strategi",+ "portfolio": "Tinjau posisi saya",+ "hint": "Contoh mengisi kotak pesan. Ubah simbol atau strategi sebelum mengirim.",+ "researchPrompt": "Riset AAPL dengan data terkini yang tersedia: rangkum bisnis, kinerja keuangan terbaru, dan risiko utama. Cantumkan sumber, tanggal, serta informasi yang belum tersedia.",+ "backtestPrompt": "Backtest strategi rata-rata bergerak 20/60 hari pada AAPL selama setahun terakhir. Bandingkan imbal hasil dan penurunan dengan beli dan tahan, serta perhitungkan biaya transaksi. Hanya untuk riset.",+ "portfolioPrompt": "Rangkum akun dan posisi saya yang terhubung, konsentrasi, serta risiko portofolio. Jika belum ada akun terhubung, jelaskan cara menyiapkannya terlebih dahulu. Jangan mengirim atau mengubah order."+ },"categories": {"multiMarketBacktest": "Backtest A-Share","researchAnalysis": "Riset & Analisis",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex ee40854eb..12fb64633 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -2,17 +2,49 @@"app": {"version": "v0.1.16"},+ "navigation": {+ "menu": "機能を見る",+ "close": "機能メニューを閉じる",+ "groups": {+ "research": "日々のリサーチ",+ "analysis": "専門分析",+ "automation": "自動化と設定"+ },+ "howTo": "{{feature}}の使い方",+ "startResearch": "リサーチアシスタントから始める",+ "descriptions": {+ "agent": "調べたいことや検証したい戦略を自分の言葉で伝えます。",+ "reports": "完了したバックテストを確認・比較します。",+ "portfolio": "接続した口座の残高と保有資産をまとめて確認します。",+ "alphaZoo": "銘柄選択のシグナルを調べ、過去の成績を評価・比較します。",+ "optionsLab": "オプション戦略を組み立て、損益とリスクや米国のオプションチェーンを確認します。",+ "correlation": "複数の資産の値動きの関係を比較します。",+ "scheduled": "リサーチを指定した周期で繰り返します。",+ "runtime": "ブローカーの接続と取引の稼働状況を確認します。",+ "settings": "モデル、データソース、ブローカー接続を設定します。"+ },+ "instructions": {+ "reports": "まずアシスタントに戦略のバックテストを依頼し、ここで結果を開きます。会話で作成した PDF などは元の会話からダウンロードします。",+ "portfolio": "口座ソースを追加して有効にし、保有資産を更新します。このページは口座情報の読み取り専用の概要です。",+ "alphaZoo": "因子の定義を読み、市場と期間を選んで評価・比較します。候補のシグナルはバックテストで検証してください。",+ "optionsLab": "プリセットを選ぶかレッグを追加し、価格、満期、変動率を調整すると結果が自動更新されます。実際のチェーンの銘柄とシミュレーションの入力は別々に設定します。",+ "correlation": "資産コードを2つ以上入力し、対象期間を選んで計算します。",+ "scheduled": "リサーチ指示と周期を入力して保存します。実行にはローカルのスケジューラーを有効にする必要があり、配信にはチャネル設定も必要です。",+ "runtime": "先に設定または保有資産ページでブローカーを接続します。利用できる取引操作はブローカーの機能とあなたの許可に依存します。",+ "settings": "まずモデルを設定します。必要に応じてデータソースやブローカー接続を追加します。公開市場のリサーチにはブローカー口座は不要です。"+ }+ },"layout": {"home": "ホーム",- "agent": "エージェント",- "runtime": "取引モニター",- "scheduled": "スケジュール",- "reports": "レポート",- "portfolio": "ポートフォリオ",- "alphaZoo": "アルファ・ライブラリ",+ "agent": "リサーチアシスタント",+ "runtime": "取引の状態",+ "scheduled": "定期リサーチ",+ "reports": "バックテスト結果",+ "portfolio": "口座の保有資産",+ "alphaZoo": "因子リサーチ","settings": "設定",- "correlation": "相関行列",- "optionsLab": "オプションラボ",+ "correlation": "資産の相関",+ "optionsLab": "オプション分析","sessions": "セッション","newChat": "新規チャット","noSessions": "チャットはまだありません。+を押して始めましょう",@@ -28,7 +60,8 @@"skipToMain": "メインコンテンツへスキップ","sidebar": "Vibe-Trading サイドバー","mainNavigation": "メインナビゲーション",- "about": "概要"+ "about": "概要",+ "sessionsLoadFailed": "会話を読み込めません。"},"runtime": {"monitorBadge": "取引モニター",@@ -255,7 +288,7 @@"unavailable": "レポートライブラリが利用できません","loadError": "レポートを読み込めませんでした。","emptyTitle": "レポートがまだありません",- "emptyBody": "まずエージェントでバックテストを作成し、ここに戻って確認してください。",+ "emptyBody": "リサーチアシスタントにバックテストを依頼し、ここで結果を確認します。","noMatchesTitle": "一致するレポートがありません","noMatchesBody": "検索クエリ、状態フィルタ、日付範囲を見直してください。","noPrompt": "プロンプトが記録されていません。",@@ -269,9 +302,22 @@"connection": {"reconnecting": "再接続しています…","disconnected": "接続が切れました。再接続するにはページを再読み込みしてください。",- "reload": "再読み込み"+ "reload": "再読み込み",+ "retry": "接続を再試行",+ "requestFailed": "API サーバーに接続できません。サーバーの起動とネットワーク接続を確認してください。",+ "requestTimeout": "リクエストがタイムアウトしました。サーバーへの接続を確認して再試行してください。",+ "requestTimeoutMutation": "リクエストがタイムアウトしました。サーバーが処理を続けている可能性があります。現在の状態を確認してから再試行してください。"},"welcome": {+ "tasks": {+ "research": "株式を調べる",+ "backtest": "戦略を検証する",+ "portfolio": "保有資産を確認する",+ "hint": "例文が入力欄に入ります。銘柄や戦略を編集してから送信できます。",+ "researchPrompt": "AAPL の事業、最近の財務成績、主なリスクを現在利用できるデータで調べてください。出典と日付を示し、不足する情報を明記してください。",+ "backtestPrompt": "AAPL の過去1年で20日・60日移動平均戦略をバックテストし、売買コストを含めて買い持ちとリターンやドローダウンを比較してください。リサーチのみです。",+ "portfolioPrompt": "接続済み口座の保有資産、集中度、ポートフォリオのリスクをまとめてください。口座未接続なら設定方法を先に説明してください。注文の発注や変更はしないでください。"+ },"categories": {"multiMarketBacktest": "A株バックテスト","researchAnalysis": "リサーチ & 分析",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 3989fba0b..bcdc09d02 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -2,17 +2,49 @@"app": {"version": "v0.1.16"},+ "navigation": {+ "menu": "기능 둘러보기",+ "close": "기능 메뉴 닫기",+ "groups": {+ "research": "일상 리서치",+ "analysis": "전문 분석",+ "automation": "자동화 및 설정"+ },+ "howTo": "{{feature}} 사용 방법",+ "startResearch": "리서치 도우미로 시작하기",+ "descriptions": {+ "agent": "리서치 질문이나 검증할 전략을 자연어로 설명하세요.",+ "reports": "완료된 백테스트를 확인하고 비교합니다.",+ "portfolio": "연결된 계좌의 잔고와 보유 자산을 모아 봅니다.",+ "alphaZoo": "종목 선택 신호를 살펴보고 과거 성과를 평가하거나 비교합니다.",+ "optionsLab": "옵션 전략을 구성하고 손익과 위험, 미국 옵션 체인을 살펴봅니다.",+ "correlation": "여러 자산의 가격 움직임 관계를 비교합니다.",+ "scheduled": "지정한 주기로 리서치를 반복합니다.",+ "runtime": "브로커 연결과 거래 실행 상태를 확인합니다.",+ "settings": "모델, 데이터 소스, 브로커 연결을 설정합니다."+ },+ "instructions": {+ "reports": "먼저 도우미에게 전략 백테스트를 요청한 후 여기에서 결과를 엽니다. 대화에서 생성한 PDF 등은 원래 대화에서 다운로드하세요.",+ "portfolio": "계좌 소스를 추가하고 활성화한 후 보유 자산을 새로 고칩니다. 이 페이지는 계좌 정보를 읽기 전용으로 요약합니다.",+ "alphaZoo": "팩터 정의를 읽고 시장과 날짜 범위를 선택하여 평가하거나 비교하세요. 후보 신호는 백테스트로 검증하세요.",+ "optionsLab": "프리셋을 선택하거나 옵션 레그를 추가하고 가격, 만기, 변동성을 조정하면 결과가 자동 갱신됩니다. 실제 체인의 종목과 시뮬레이션 입력은 별도로 설정합니다.",+ "correlation": "자산 코드를 두 개 이상 입력하고 기간을 선택한 다음 계산을 누르세요.",+ "scheduled": "리서치 지시와 실행 주기를 입력하고 저장하세요. 실행하려면 로컬 스케줄러가 활성화되어 있어야 하며, 결과 전달에는 채널 설정이 필요합니다.",+ "runtime": "먼저 설정 또는 보유 자산 페이지에서 브로커를 연결하세요. 사용 가능한 거래 작업은 브로커 기능과 사용자의 승인에 따라 달라집니다.",+ "settings": "먼저 모델을 설정하세요. 필요에 따라 데이터 소스나 브로커 연결을 추가하면 됩니다. 공개 시장 리서치에는 브로커 계좌가 필요하지 않습니다."+ }+ },"layout": {"home": "홈",- "agent": "에이전트",- "runtime": "거래 모니터",- "scheduled": "예약",- "reports": "리포트",- "portfolio": "포트폴리오",- "alphaZoo": "알파 라이브러리",+ "agent": "리서치 도우미",+ "runtime": "거래 상태",+ "scheduled": "예약 리서치",+ "reports": "백테스트 보고서",+ "portfolio": "계좌 보유 자산",+ "alphaZoo": "팩터 리서치","settings": "설정",- "correlation": "상관 행렬",- "optionsLab": "옵션 랩",+ "correlation": "자산 상관관계",+ "optionsLab": "옵션 분석","sessions": "세션","newChat": "새 채팅","noSessions": "아직 채팅이 없습니다. +를 눌러 시작하세요",@@ -28,7 +60,8 @@"skipToMain": "본문으로 건너뛰기","sidebar": "Vibe-Trading 사이드바","mainNavigation": "주 내비게이션",- "about": "소개"+ "about": "소개",+ "sessionsLoadFailed": "대화를 불러올 수 없습니다."},"runtime": {"monitorBadge": "거래 모니터",@@ -255,7 +288,7 @@"unavailable": "리포트 라이브러리를 사용할 수 없음","loadError": "리포트를 불러올 수 없습니다.","emptyTitle": "아직 리포트가 없습니다",- "emptyBody": "먼저 에이전트에서 백테스트를 생성한 다음 여기로 돌아와 확인하세요.",+ "emptyBody": "리서치 도우미에게 백테스트를 요청한 다음 여기에서 결과를 확인하세요.","noMatchesTitle": "일치하는 리포트가 없습니다","noMatchesBody": "검색어, 상태 필터, 날짜 범위를 조정해 보세요.","noPrompt": "기록된 프롬프트가 없습니다.",@@ -269,9 +302,22 @@"connection": {"reconnecting": "다시 연결하는 중…","disconnected": "연결이 끊겼습니다. 다시 연결하려면 페이지를 새로고침하세요.",- "reload": "새로고침"+ "reload": "새로고침",+ "retry": "연결 다시 시도",+ "requestFailed": "API 서버에 연결할 수 없습니다. 서버 실행 여부와 네트워크 연결을 확인하세요.",+ "requestTimeout": "요청 시간이 초과되었습니다. 서버 연결을 확인한 후 다시 시도하세요.",+ "requestTimeoutMutation": "요청 시간이 초과되었습니다. 서버에서 아직 처리 중일 수 있으니 현재 상태를 확인한 후 다시 시도하세요."},"welcome": {+ "tasks": {+ "research": "주식 조사하기",+ "backtest": "전략 검증하기",+ "portfolio": "내 보유 자산 확인",+ "hint": "예시가 입력창에 채워집니다. 종목이나 전략을 수정한 뒤 보내세요.",+ "researchPrompt": "현재 이용 가능한 데이터로 AAPL의 사업, 최근 재무 성과, 주요 위험을 조사하세요. 출처와 날짜를 밝히고 누락된 정보를 명시하세요.",+ "backtestPrompt": "지난 1년간 AAPL의 20/60일 이동평균 전략을 백테스트하고 거래 비용을 포함하여 매수 후 보유 전략과 수익 및 낙폭을 비교하세요. 리서치만 수행하세요.",+ "portfolioPrompt": "연결된 계좌의 보유 자산, 집중도, 포트폴리오 위험을 요약하세요. 연결된 계좌가 없다면 먼저 설정 방법을 설명하세요. 주문을 제출하거나 변경하지 마세요."+ },"categories": {"multiMarketBacktest": "A주 백테스트","researchAnalysis": "리서치 & 분석",diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex 755dea4b2..84e90bd10 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -7,17 +7,49 @@"noCorrelationData": "Escolha pelo menos dois símbolos para comparar","noEquityData": "Ainda não há curva de valor da conta – execute primeiro um backtest"},+ "navigation": {+ "menu": "Explorar recursos",+ "close": "Fechar menu de recursos",+ "groups": {+ "research": "Pesquisa cotidiana",+ "analysis": "Análise especializada",+ "automation": "Automação e configuração"+ },+ "howTo": "Como usar {{feature}}",+ "startResearch": "Comece com o assistente de pesquisa",+ "descriptions": {+ "agent": "Faça uma pergunta de pesquisa ou descreva uma estratégia com suas palavras.",+ "reports": "Veja e compare backtests concluídos.",+ "portfolio": "Veja saldos e posições das contas conectadas.",+ "alphaZoo": "Explore sinais de seleção de ações e avalie ou compare o desempenho histórico.",+ "optionsLab": "Monte estratégias de opções, explore ganhos e riscos e consulte cadeias de opções dos EUA.",+ "correlation": "Compare como os ativos se movimentam juntos.",+ "scheduled": "Repita uma pesquisa em horários definidos.",+ "runtime": "Confira conexões de corretoras e o estado de execução das operações.",+ "settings": "Configure modelos, fontes de dados e conexões de corretoras."+ },+ "instructions": {+ "reports": "Primeiro peça ao assistente um backtest de uma estratégia e abra os resultados aqui. Baixe PDFs e documentos gerados no chat na conversa original.",+ "portfolio": "Adicione e habilite uma fonte de conta e atualize as posições. Esta página resume os dados das contas em modo somente leitura.",+ "alphaZoo": "Leia a definição do fator e escolha mercado e período para avaliar ou comparar sinais. Valide os candidatos com um backtest.",+ "optionsLab": "Escolha uma predefinição ou adicione pernas de opções e ajuste preço, vencimento e volatilidade; os resultados se atualizam automaticamente. O código da cadeia real é separado das entradas da simulação.",+ "correlation": "Informe pelo menos dois códigos de ativos, escolha o período e clique em Calcular.",+ "scheduled": "Informe a instrução de pesquisa, escolha a frequência e salve. O agendador local deve estar habilitado para executar tarefas; a entrega também requer um canal configurado.",+ "runtime": "Primeiro configure uma conexão de corretora em Configurações ou Carteira. As operações disponíveis dependem dos recursos da corretora e da sua autorização.",+ "settings": "Configure um modelo para começar. Adicione dados ou conexões de corretoras conforme necessário; pesquisas com dados públicos de mercado não exigem conta em corretora."+ }+ },"layout": {"home": "Início",- "agent": "Agente",- "runtime": "Runtime",- "scheduled": "Agendado",- "reports": "Relatórios",- "portfolio": "Portfólio",- "alphaZoo": "Alpha Zoo",+ "agent": "Assistente de pesquisa",+ "runtime": "Estado das operações",+ "scheduled": "Pesquisa agendada",+ "reports": "Relatórios de backtest",+ "portfolio": "Posições das contas",+ "alphaZoo": "Pesquisa de fatores","settings": "Configurações",- "correlation": "Matriz de Correlação",- "optionsLab": "Laboratório de opções",+ "correlation": "Correlação de ativos",+ "optionsLab": "Análise de opções","sessions": "Sessões","newChat": "Novo chat","noSessions": "Ainda não há chats — pressione + para iniciar um.",@@ -33,7 +65,8 @@"skipToMain": "Pular para o conteúdo principal","sidebar": "Barra lateral Vibe-Trading","mainNavigation": "Navegação principal",- "about": "Sobre"+ "about": "Sobre",+ "sessionsLoadFailed": "Não foi possível carregar as conversas."},"runtime": {"monitorBadge": "Monitor de Runtime",@@ -260,7 +293,7 @@"unavailable": "Biblioteca de relatórios indisponível","loadError": "Não foi possível carregar relatórios.","emptyTitle": "Ainda não há relatórios",- "emptyBody": "Crie um backtest do Agente e retorne aqui para revisá-lo.",+ "emptyBody": "Peça ao assistente de pesquisa um backtest e volte aqui para ver os resultados.","noMatchesTitle": "Nenhum relatório correspondente","noMatchesBody": "Ajuste sua consulta de pesquisa, filtro de status ou intervalo de datas.","noPrompt": "Nenhum prompt registrado.",@@ -274,9 +307,22 @@"connection": {"reconnecting": "Reconectando…","disconnected": "Conexão perdida. Recarregue a página para reconectar.",- "reload": "Recarregar"+ "reload": "Recarregar",+ "retry": "Tentar conexão novamente",+ "requestFailed": "Não foi possível conectar ao servidor API. Verifique se ele está em execução e se há conexão de rede.",+ "requestTimeout": "A solicitação excedeu o tempo limite. Verifique a conexão com o servidor e tente novamente.",+ "requestTimeoutMutation": "A solicitação excedeu o tempo limite. O servidor ainda pode estar processando; verifique o estado atual antes de tentar novamente."},"welcome": {+ "tasks": {+ "research": "Pesquisar uma ação",+ "backtest": "Testar uma estratégia",+ "portfolio": "Revisar minhas posições",+ "hint": "Os exemplos preenchem a mensagem. Edite o código ou a estratégia antes de enviar.",+ "researchPrompt": "Pesquise AAPL com os dados atuais disponíveis: resuma o negócio, os resultados financeiros recentes e os principais riscos. Informe fontes, datas e informações ausentes.",+ "backtestPrompt": "Faça um backtest da estratégia de médias móveis de 20/60 dias de AAPL no último ano. Compare retorno e quedas com comprar e manter, incluindo custos de negociação. Apenas pesquisa.",+ "portfolioPrompt": "Resuma minhas contas conectadas e posições, concentração e riscos da carteira. Se não houver conta conectada, explique primeiro como configurar uma. Não envie nem altere ordens."+ },"categories": {"multiMarketBacktest": "Backtest em múltiplos mercados","researchAnalysis": "Pesquisa e Análise",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 6450a4d86..6e6d68763 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -2,17 +2,49 @@"app": {"version": "v0.1.16"},+ "navigation": {+ "menu": "浏览功能",+ "close": "关闭功能菜单",+ "groups": {+ "research": "日常研究",+ "analysis": "专项分析",+ "automation": "自动化与设置"+ },+ "howTo": "{{feature}}怎么用",+ "startResearch": "从研究助手开始",+ "descriptions": {+ "agent": "用自己的话提出研究问题,或描述要回测的策略。",+ "reports": "查看并比较已完成的回测结果。",+ "portfolio": "汇总已连接账户的资金和持仓。",+ "alphaZoo": "浏览选股信号,评测或比较其历史表现。",+ "optionsLab": "构建期权组合,观察损益与风险,并查看美股期权链。",+ "correlation": "比较多只资产是否同涨同跌。",+ "scheduled": "按指定时间重复执行研究任务。",+ "runtime": "查看券商连接和交易运行状态。",+ "settings": "配置模型、数据源和券商连接。"+ },+ "instructions": {+ "reports": "先在研究助手中描述策略并完成回测,再到这里打开结果。聊天生成的 PDF 等文档在原对话中下载。",+ "portfolio": "先添加并启用账户来源,再刷新获取持仓。此页为账户数据的只读汇总。",+ "alphaZoo": "先看因子定义,再选择市场和日期范围进行评测或比较。候选信号还需经过回测验证。",+ "optionsLab": "选择预设或添加期权腿,修改价格、期限和波动率,结果会自动更新。真实期权链的股票代码与模拟参数分开设置。",+ "correlation": "输入至少两个资产代码,选择时间窗口,再点击计算。",+ "scheduled": "填写研究指令、选择执行频率并保存。任务执行需要启用本地调度服务;推送结果还需配置投递渠道。",+ "runtime": "先在设置或持仓页配置券商连接。可用的交易操作取决于该券商的能力和你的授权。",+ "settings": "初次使用先配置模型。按任务需要添加数据源或券商连接;研究公开行情无需连接券商账户。"+ }+ },"layout": {"home": "首页",- "agent": "智能体",- "runtime": "交易监控",- "scheduled": "定时任务",- "reports": "报告",- "portfolio": "持仓",- "alphaZoo": "Alpha 因子库",+ "agent": "研究助手",+ "runtime": "交易状态",+ "scheduled": "定时研究",+ "reports": "回测报告",+ "portfolio": "账户持仓",+ "alphaZoo": "因子研究","settings": "设置",- "correlation": "相关性矩阵",- "optionsLab": "期权实验室",+ "correlation": "资产相关性",+ "optionsLab": "期权分析","sessions": "会话","newChat": "新建对话","noSessions": "还没有对话——点 + 开始第一个",@@ -28,7 +60,8 @@"skipToMain": "跳转到主要内容","sidebar": "Vibe-Trading 侧边栏","mainNavigation": "主导航",- "about": "关于"+ "about": "关于",+ "sessionsLoadFailed": "无法加载会话。"},"runtime": {"monitorBadge": "交易监控",@@ -255,7 +288,7 @@"unavailable": "报告库不可用","loadError": "无法加载报告。","emptyTitle": "暂无报告",- "emptyBody": "先在智能体中创建一次回测,然后回到这里查看。",+ "emptyBody": "先让研究助手运行一次回测,再到这里查看结果。","noMatchesTitle": "没有匹配的报告","noMatchesBody": "请调整搜索词、状态筛选或日期范围。","noPrompt": "未记录提示词。",@@ -269,9 +302,22 @@"connection": {"reconnecting": "正在重新连接…","disconnected": "连接已断开,刷新页面即可重连。",- "reload": "刷新"+ "reload": "刷新",+ "retry": "重试连接",+ "requestFailed": "无法连接 API 服务。请检查后端是否已启动,以及网络连接是否正常。",+ "requestTimeout": "请求超时。请检查服务连接后重试。",+ "requestTimeoutMutation": "请求超时。服务端可能仍在处理;请先检查当前状态,再决定是否重试。"},"welcome": {+ "tasks": {+ "research": "研究一只股票",+ "backtest": "验证一个策略",+ "portfolio": "检查我的持仓",+ "hint": "示例会填入输入框;可以修改股票或策略后再发送。",+ "researchPrompt": "帮我研究 AAPL:用当前可用数据总结业务、近期财务表现和主要风险,注明来源和日期,明确指出缺失的信息。",+ "backtestPrompt": "回测 AAPL 过去一年 20/60 日均线策略,与买入持有比较收益和回撤,并计入交易成本。仅做研究。",+ "portfolioPrompt": "总结我已连接账户的持仓、集中度和组合风险。如果还没有连接账户,先说明如何配置。不要提交或修改订单。"+ },"categories": {"multiMarketBacktest": "A股回测","researchAnalysis": "研究与分析",diff --git a/frontend/src/lib/__tests__/api.test.ts b/frontend/src/lib/__tests__/api.test.tsindex aebdcdd78..4dee67727 100644--- a/frontend/src/lib/__tests__/api.test.ts+++ b/frontend/src/lib/__tests__/api.test.ts@@ -19,7 +19,7 @@ describe("generated report download", () => {});const { downloadGeneratedReport } = await loadApiModule();await downloadGeneratedReport("a".repeat(32), "研究报告.pdf");- expect(fetch).toHaveBeenCalledWith(`/api/reports/${"a".repeat(32)}`, { headers: { Authorization: "Bearer report-test-key" } });+ expect(fetch).toHaveBeenCalledWith(`/api/reports/${"a".repeat(32)}`, expect.objectContaining({ headers: { Authorization: "Bearer report-test-key" } }));expect(click).toHaveBeenCalledOnce();});});@@ -183,3 +183,64 @@ describe("api request helper", () => {} satisfies Partial<ApiError>);});});++describe("API failure recovery", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.stubEnv("VITE_API_TIMEOUT_MS", "1000");+ vi.stubGlobal("localStorage", { getItem: () => "", setItem: vi.fn(), removeItem: vi.fn() });+ });+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ });++ function hangUntilAbort(signal: AbortSignal) {+ return new Promise<never>((_, reject) => {+ signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });+ });+ }++ it("bounds a stalled conversation-list request and clears its timer", async () => {+ vi.stubGlobal("fetch", vi.fn((_url, init) => hangUntilAbort(init.signal)));+ const { api } = await loadApiModule();+ const pending = expect(api.listSessions()).rejects.toMatchObject({+ code: "request_timeout", message: expect.stringContaining("timed out"),+ });+ await vi.advanceTimersByTimeAsync(1000);+ await pending;+ expect(vi.getTimerCount()).toBe(0);+ });++ it("keeps the timeout active while reading a stalled response body", async () => {+ vi.stubGlobal("fetch", vi.fn(async (_url, init) => ({+ ok: true,+ text: () => hangUntilAbort(init.signal),+ })));+ const { api } = await loadApiModule();+ const pending = expect(api.listSessions()).rejects.toMatchObject({ code: "request_timeout" });+ await vi.advanceTimersByTimeAsync(1000);+ await pending;+ });++ it("explains a failed server connection in the active locale", async () => {+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch")));+ const { api } = await loadApiModule();+ await expect(api.listSessions()).rejects.toMatchObject({+ code: "network_error", message: expect.stringContaining("Check that it is running"),+ });+ });++ it("does not replay a timed-out write and reports its uncertain outcome", async () => {+ const fetch = vi.fn((_url, init) => hangUntilAbort(init.signal));+ vi.stubGlobal("fetch", fetch);+ const { api } = await loadApiModule();+ const pending = expect(api.renameSession("session", "new title")).rejects.toMatchObject({+ code: "request_timeout", message: expect.stringContaining("check the current state"),+ });+ await vi.advanceTimersByTimeAsync(1000);+ await pending;+ expect(fetch).toHaveBeenCalledOnce();+ });+});diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 48ffcf9fe..84f39b5e9 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -7,11 +7,50 @@ import type {} from "@/lib/options";const BASE = "";+const configuredTimeout = Number(import.meta.env.VITE_API_TIMEOUT_MS);+const REQUEST_TIMEOUT_MS = Number.isFinite(configuredTimeout) && configuredTimeout > 0+ ? configuredTimeout : 120_000;+const METADATA_TIMEOUT_MS = Math.min(REQUEST_TIMEOUT_MS, 15_000);++/** Bound both the connection and body read; never automatically replay writes. */+async function performRequest<T>(+ path: string,+ options: RequestInit,+ read: (response: Response) => Promise<T>,+ timeoutMs = REQUEST_TIMEOUT_MS,+): Promise<T> {+ const controller = new AbortController();+ let timedOut = false;+ const timer = setTimeout(() => {+ timedOut = true;+ controller.abort();+ }, timeoutMs);+ const abort = () => controller.abort(options.signal?.reason);+ if (options.signal?.aborted) abort();+ else options.signal?.addEventListener("abort", abort, { once: true });+ try {+ const response = await fetch(`${BASE}${path}`, { ...options, signal: controller.signal });+ if (!response.ok) throw await errorFromResponse(response);+ return await read(response);+ } catch (error) {+ if (timedOut) {+ const mutation = options.method && !["GET", "HEAD"].includes(options.method.toUpperCase());+ throw new ApiError(i18n.t(mutation ? "connection.requestTimeoutMutation" : "connection.requestTimeout"), 0, "request_timeout");+ }+ if (options.signal?.aborted || error instanceof ApiError) throw error;+ if (error instanceof TypeError) {+ throw new ApiError(i18n.t("connection.requestFailed"), 0, "network_error");+ }+ throw error;+ } finally {+ clearTimeout(timer);+ options.signal?.removeEventListener("abort", abort);+ }+}export async function downloadGeneratedReport(reportId: string, filename: string): Promise<void> {- const response = await fetch(`${BASE}/api/reports/${encodeURIComponent(reportId)}`, { headers: authHeaders() });- if (!response.ok) throw new ApiError(response.statusText, response.status);- const url = URL.createObjectURL(await response.blob());+ const blob = await performRequest(`/api/reports/${encodeURIComponent(reportId)}`, { headers: authHeaders() }, (response) => response.blob());+ const url = URL.createObjectURL(blob);const link = document.createElement("a");link.href = url;link.download = filename;@@ -325,14 +364,16 @@ async function errorFromResponse(res: Response): Promise<ApiError> {detail = i18n.t("agent.messageTooLong", { limit: structured.max_length.toLocaleString() });}}- } catch { /* ignore */ }+ } catch {+ if (res.status >= 500) detail = i18n.t("connection.requestFailed");+ }if (res.status === 401 || res.status === 403) {detail = getAuthRequiredMessage();}return new ApiError(detail, res.status, code);}-async function request<T>(path: string, options?: RequestInit): Promise<T> {+async function request<T>(path: string, options?: RequestInit, timeoutMs?: number): Promise<T> {const { headers, ...rest } = options ?? {};const mergedHeaders: Record<string, string> = { "Content-Type": "application/json", ...authHeaders() };if (headers) {@@ -340,26 +381,24 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {mergedHeaders[key] = value;});}- const res = await fetch(`${BASE}${path}`, {+ return performRequest(path, {...rest,headers: mergedHeaders,- });- if (!res.ok) {- throw await errorFromResponse(res);- }- const text = await res.text();- if (!text) return {} as T;-- const contentType = res.headers.get("content-type") || "";- if (!contentType.includes("application/json")) {- const preview = text.slice(0, 80).replace(/\s+/g, " ");- throw new ApiError(- `Expected JSON from ${path}, got ${contentType || "unknown content type"}: ${preview}`,- res.status,- );- }+ }, async (res) => {+ const text = await res.text();+ if (!text) return {} as T;++ const contentType = res.headers.get("content-type") || "";+ if (!contentType.includes("application/json")) {+ const preview = text.slice(0, 80).replace(/\s+/g, " ");+ throw new ApiError(+ `Expected JSON from ${path}, got ${contentType || "unknown content type"}: ${preview}`,+ res.status,+ );+ }- return JSON.parse(text) as T;+ return JSON.parse(text) as T;+ }, timeoutMs);}export interface UploadResult {@@ -371,11 +410,7 @@ export interface UploadResult {async function uploadFile(file: File): Promise<UploadResult> {const form = new FormData();form.append("file", file);- const res = await fetch(`${BASE}/upload`, { method: "POST", headers: authHeaders(), body: form });- if (!res.ok) {- throw await errorFromResponse(res);- }- return res.json();+ return performRequest("/upload", { method: "POST", headers: authHeaders(), body: form }, (res) => res.json());}function appendQueryParam(url: string, key: string, value: string): string {@@ -439,9 +474,7 @@ export const api = {getPortfolioHistory: (limit = 180) =>request<{ status: string; history: PortfolioHistoryPoint[] }>(`/api/portfolio/history?limit=${encodeURIComponent(String(limit))}`),downloadPortfolioCsv: async () => {- const response = await fetch(`${BASE}/api/portfolio/export.csv`, { headers: authHeaders() });- if (!response.ok) throw await errorFromResponse(response);- return response.blob();+ return performRequest("/api/portfolio/export.csv", { headers: authHeaders() }, (response) => response.blob());},listRuns: (limit?: number) => request<RunListItem[]>(`/runs${limit ? `?limit=${encodeURIComponent(String(limit))}` : ""}`),getRun: (id: string, params: RunDetailParams = {}) => {@@ -455,7 +488,7 @@ export const api = {getRunFactor: (id: string) => request<FactorReportPayload>(`/runs/${id}/factor`),getRunAttribution: (id: string) => request<AttributionResponse>(`/runs/${encodeURIComponent(id)}/attribution`),getRunPine: (id: string) => request<PineScriptResult>(`/runs/${id}/pine`),- listSessions: () => request<SessionItem[]>("/sessions"),+ listSessions: () => request<SessionItem[]>("/sessions", undefined, METADATA_TIMEOUT_MS),createSession: (title?: string) => request<SessionItem>("/sessions", { method: "POST", body: JSON.stringify({ title: title || "" }) }),deleteSession: (sid: string) => request<{ status: string }>(`/sessions/${sid}`, { method: "DELETE" }),renameSession: (sid: string, title: string) => request<{ status: string }>(`/sessions/${sid}`, { method: "PATCH", body: JSON.stringify({ title }) }),diff --git a/frontend/src/lib/options.ts b/frontend/src/lib/options.tsindex 044e9fd95..65c258c67 100644--- a/frontend/src/lib/options.ts+++ b/frontend/src/lib/options.ts@@ -112,6 +112,9 @@ export interface OptionsContractRow {export interface OptionsChainData {ticker: string;+ /** Source quote and nearest strike in the complete ladder, before row capping. */+ underlying_price?: number | null;+ atm_strike?: number | null;expiration: number;/** Epoch seconds. */expirations: number[];diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex f87a15de7..5de535b31 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -258,6 +258,7 @@ export function Agent() {const [visibleRowCount, setVisibleRowCount] = useState(TIMELINE_WINDOW_SIZE);const visibleRowsSessionRef = useRef<string | null>(null);const [llmSettings, setLlmSettings] = useState<LLMSettings | null>(null);+ const [historyError, setHistoryError] = useState<string | null>(null);const [runtimeIdentity, setRuntimeIdentity] = useState<RuntimeIdentity>({});const messages = useAgentStore(s => s.messages);@@ -521,6 +522,7 @@ export function Agent() {}, []);const loadSessionMessages = useCallback(async (sid: string, gen: number) => {+ setHistoryError(null);try {const msgs = await api.getSessionMessages(sid);if (genRef.current !== gen) return;@@ -665,12 +667,13 @@ export function Agent() {act().cacheSession(sid, agentMsgs);setRuntimeIdentity(latestRuntimeIdentity ?? {});scheduleHistoryScroll();- } catch {+ } catch (error) {if (genRef.current !== gen) return;setRuntimeIdentity({});act().setSessionLoading(false);+ setHistoryError(error instanceof Error ? error.message : t("settings.unknownError"));}- }, [scheduleHistoryScroll]);+ }, [scheduleHistoryScroll, t]);const refreshSessionMessages = useCallback(async (sid: string) => {const gen = genRef.current + 1;@@ -1339,6 +1342,7 @@ export function Agent() {doDisconnect();setRuntimeIdentity({});setGroundingRevision(null);+ setHistoryError(null);setLiveItems([]);liveRuntimeRef.current?.resetSession();if (curSid && curMsgs.length > 0) cacheSession(curSid, curMsgs);@@ -1507,7 +1511,7 @@ export function Agent() {archiveActivity("failed");act().setStatus("error");const message = isAuthRequiredError(error) ? AUTH_REQUIRED_MESSAGE- : error instanceof ApiError && error.code === 'message_too_long' ? error.message : t('agent.failedToSend');+ : error instanceof ApiError && ['message_too_long', 'network_error', 'request_timeout'].includes(error.code || '') ? error.message : t('agent.failedToSend');toast.error(message);act().addMessage({ id: "", type: "error", content: message, timestamp: Date.now() });}@@ -1783,6 +1787,16 @@ export function Agent() {runtimeModel={visibleRuntimeIdentity.model}runtimeReasoningEffort={visibleRuntimeIdentity.reasoningEffort}/>+ {historyError && (+ <div role="alert" className="flex flex-wrap items-center gap-2 border-b border-warning/30 bg-warning/10 px-4 py-2 text-xs">+ <span>{t("layout.sessionsLoadFailed")} {historyError}</span>+ <button type="button" onClick={() => {+ if (!sessionId) return;+ act().setSessionLoading(true);+ void refreshSessionMessages(sessionId);+ }} className="ms-auto rounded-md border px-2 py-1">{t("connection.retry")}</button>+ </div>+ )}<divref={listRef}data-streaming={status === "streaming" ? "true" : undefined}@@ -1807,7 +1821,7 @@ export function Agent() {))}</div>)}- {!sessionLoading && messages.length === 0 && (+ {!sessionLoading && !historyError && messages.length === 0 && (// my-auto (not justify-*) centers the hero vertically while staying// scroll-reachable once the example library expands past the viewport.<div className="msg-enter my-auto">diff --git a/frontend/src/pages/OptionsLab.tsx b/frontend/src/pages/OptionsLab.tsxindex c2572233f..6ac9fc53f 100644--- a/frontend/src/pages/OptionsLab.tsx+++ b/frontend/src/pages/OptionsLab.tsx@@ -226,7 +226,7 @@ export function OptionsLab() {</section>{/* Live US options chain */}- <OptionsChainTable referenceSpot={params.entry_spot} />+ <OptionsChainTable /><p className="pb-2 text-xs text-muted-foreground">{t("options.disclaimer")}</p></div>diff --git a/frontend/src/pages/Reports.tsx b/frontend/src/pages/Reports.tsxindex 9678aa532..70c83e195 100644--- a/frontend/src/pages/Reports.tsx+++ b/frontend/src/pages/Reports.tsx@@ -185,6 +185,7 @@ export function Reports() {<p className="mt-1 text-sm text-muted-foreground">{runs.length === 0 ? t("reports.emptyBody") : t("reports.noMatchesBody")}</p>+ {runs.length === 0 && <Link to="/" className="mt-5 inline-flex rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground">{t("navigation.startResearch")}</Link>}</section>) : null}diff --git a/frontend/src/pages/__tests__/AgentBackgroundStreamCompletion.test.tsx b/frontend/src/pages/__tests__/AgentBackgroundStreamCompletion.test.tsxindex e29980187..6d2eaa084 100644--- a/frontend/src/pages/__tests__/AgentBackgroundStreamCompletion.test.tsx+++ b/frontend/src/pages/__tests__/AgentBackgroundStreamCompletion.test.tsx@@ -1,4 +1,4 @@-import { act, render, waitFor } from "@testing-library/react";+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";import { createMemoryRouter, RouterProvider } from "react-router";import { Agent } from "../Agent";import { useAgentStore } from "@/stores/agent";@@ -136,4 +136,23 @@ describe("Agent background stream completion reconciliation", () => {});expect(useAgentStore.getState().streamingSessionId).toBe("session-bg");});++ it("recovers an unavailable conversation without discarding the composer draft", async () => {+ apiMock.getSessionMessages.mockReset()+ .mockRejectedValueOnce(new Error("History unavailable"))+ .mockResolvedValueOnce([storedReply("session-one")]);+ const router = createMemoryRouter(+ [{ path: "/", element: <Agent /> }],+ { initialEntries: ["/?session=session-one"] },+ );+ render(<RouterProvider router={router} />);+ expect(await screen.findByRole("alert")).toHaveTextContent("History unavailable");+ const composer = screen.getByRole("textbox");+ fireEvent.change(composer, { target: { value: "Keep my draft" } });+ fireEvent.click(screen.getByRole("button", { name: "Retry connection" }));+ await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());+ await waitFor(() => expect(useAgentStore.getState().messages.some((message) => message.content === "done")).toBe(true));+ expect(composer).toHaveValue("Keep my draft");+ expect(apiMock.getSessionMessages).toHaveBeenCalledTimes(2);+ });});diff --git a/frontend/src/pages/__tests__/Reports.test.tsx b/frontend/src/pages/__tests__/Reports.test.tsxindex e35031470..ec11b50e6 100644--- a/frontend/src/pages/__tests__/Reports.test.tsx+++ b/frontend/src/pages/__tests__/Reports.test.tsx@@ -15,6 +15,13 @@ describe("Reports page", () => {apiMock.listRuns.mockReset();});+ it("gives a first-time user an actionable path to create a backtest", async () => {+ apiMock.listRuns.mockResolvedValue([]);+ render(<Reports />, { wrapper: MemoryRouter });+ expect(await screen.findByText("No reports yet")).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "Start with the research assistant" })).toHaveAttribute("href", "/");+ });+it("lists backtest reports newest first with Full Report links and skips non-report runs", async () => {apiMock.listRuns.mockResolvedValue([{diff --git a/frontend/src/vite-env.d.ts b/frontend/src/vite-env.d.tsnew file mode 100644index 000000000..11f02fe2a--- /dev/null+++ b/frontend/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />